Tool System: per space/mode tool support
[blender.git] / source / blender / windowmanager / intern / wm_operators.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_operators.c
28  *  \ingroup wm
29  *
30  * Functions for dealing with wmOperator, adding, removing, calling
31  * as well as some generic operators and shared operator properties.
32  */
33
34
35 #include <float.h>
36 #include <string.h>
37 #include <ctype.h>
38 #include <stdio.h>
39 #include <stddef.h>
40 #include <assert.h>
41 #include <errno.h>
42
43 #ifdef WIN32
44 #  include "GHOST_C-api.h"
45 #endif
46
47 #include "MEM_guardedalloc.h"
48
49 #include "CLG_log.h"
50
51 #include "DNA_ID.h"
52 #include "DNA_object_types.h"
53 #include "DNA_screen_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_userdef_types.h"
56 #include "DNA_windowmanager_types.h"
57 #include "DNA_workspace_types.h"
58
59 #include "BLT_translation.h"
60
61 #include "PIL_time.h"
62
63 #include "BLI_blenlib.h"
64 #include "BLI_dial_2d.h"
65 #include "BLI_dynstr.h" /*for WM_operator_pystring */
66 #include "BLI_math.h"
67 #include "BLI_utildefines.h"
68 #include "BLI_ghash.h"
69
70 #include "BLO_readfile.h"
71
72 #include "BKE_appdir.h"
73 #include "BKE_blender_version.h"
74 #include "BKE_brush.h"
75 #include "BKE_context.h"
76 #include "BKE_icons.h"
77 #include "BKE_idprop.h"
78 #include "BKE_image.h"
79 #include "BKE_library.h"
80 #include "BKE_library_query.h"
81 #include "BKE_global.h"
82 #include "BKE_main.h"
83 #include "BKE_material.h"
84 #include "BKE_report.h"
85 #include "BKE_scene.h"
86 #include "BKE_screen.h" /* BKE_ST_MAXNAME */
87 #include "BKE_unit.h"
88
89 #include "BKE_idcode.h"
90
91 #include "BLF_api.h"
92
93 #include "GPU_immediate.h"
94 #include "GPU_immediate_util.h"
95 #include "GPU_matrix.h"
96
97 #include "IMB_imbuf_types.h"
98 #include "IMB_imbuf.h"
99
100 #include "ED_numinput.h"
101 #include "ED_screen.h"
102 #include "ED_undo.h"
103 #include "ED_view3d.h"
104
105 #include "RNA_access.h"
106 #include "RNA_define.h"
107 #include "RNA_enum_types.h"
108
109 #include "UI_interface.h"
110 #include "UI_interface_icons.h"
111 #include "UI_resources.h"
112
113 #include "WM_api.h"
114 #include "WM_types.h"
115
116 #include "wm.h"
117 #include "wm_draw.h"
118 #include "wm_event_system.h"
119 #include "wm_event_types.h"
120 #include "wm_files.h"
121 #include "wm_window.h"
122
123 static GHash *global_ops_hash = NULL;
124 /** Counter for operator-properties that should not be tagged with #OP_PROP_TAG_ADVANCED. */
125 static int ot_prop_basic_count = -1;
126
127 #define UNDOCUMENTED_OPERATOR_TIP N_("(undocumented operator)")
128
129 /* ************ operator API, exported ********** */
130
131
132 wmOperatorType *WM_operatortype_find(const char *idname, bool quiet)
133 {
134         if (idname[0]) {
135                 wmOperatorType *ot;
136
137                 /* needed to support python style names without the _OT_ syntax */
138                 char idname_bl[OP_MAX_TYPENAME];
139                 WM_operator_bl_idname(idname_bl, idname);
140
141                 ot = BLI_ghash_lookup(global_ops_hash, idname_bl);
142                 if (ot) {
143                         return ot;
144                 }
145
146                 if (!quiet) {
147                         CLOG_INFO(WM_LOG_OPERATORS, 0, "search for unknown operator '%s', '%s'\n", idname_bl, idname);
148                 }
149         }
150         else {
151                 if (!quiet) {
152                         CLOG_INFO(WM_LOG_OPERATORS, 0, "search for empty operator");
153                 }
154         }
155
156         return NULL;
157 }
158
159 /* caller must free */
160 void WM_operatortype_iter(GHashIterator *ghi)
161 {
162         BLI_ghashIterator_init(ghi, global_ops_hash);
163 }
164
165 /** \name Operator Type Append
166  * \{ */
167
168 static wmOperatorType *wm_operatortype_append__begin(void)
169 {
170         wmOperatorType *ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
171
172         BLI_assert(ot_prop_basic_count == -1);
173
174         ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties);
175         RNA_def_struct_property_tags(ot->srna, rna_enum_operator_property_tags);
176         /* Set the default i18n context now, so that opfunc can redefine it if needed! */
177         RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
178         ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT;
179
180         return ot;
181 }
182 static void wm_operatortype_append__end(wmOperatorType *ot)
183 {
184         if (ot->name == NULL) {
185                 CLOG_ERROR(WM_LOG_OPERATORS, "Operator '%s' has no name property", ot->idname);
186         }
187
188         /* Allow calling _begin without _end in operatortype creation. */
189         WM_operatortype_props_advanced_end(ot);
190
191         /* XXX All ops should have a description but for now allow them not to. */
192         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP);
193         RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
194
195         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
196 }
197
198 /* all ops in 1 list (for time being... needs evaluation later) */
199 void WM_operatortype_append(void (*opfunc)(wmOperatorType *))
200 {
201         wmOperatorType *ot = wm_operatortype_append__begin();
202         opfunc(ot);
203         wm_operatortype_append__end(ot);
204 }
205
206 void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata)
207 {
208         wmOperatorType *ot = wm_operatortype_append__begin();
209         opfunc(ot, userdata);
210         wm_operatortype_append__end(ot);
211 }
212
213 /** \} */
214
215 /* ********************* macro operator ******************** */
216
217 typedef struct {
218         int retval;
219 } MacroData;
220
221 static void wm_macro_start(wmOperator *op)
222 {
223         if (op->customdata == NULL) {
224                 op->customdata = MEM_callocN(sizeof(MacroData), "MacroData");
225         }
226 }
227
228 static int wm_macro_end(wmOperator *op, int retval)
229 {
230         if (retval & OPERATOR_CANCELLED) {
231                 MacroData *md = op->customdata;
232
233                 if (md->retval & OPERATOR_FINISHED) {
234                         retval |= OPERATOR_FINISHED;
235                         retval &= ~OPERATOR_CANCELLED;
236                 }
237         }
238
239         /* if modal is ending, free custom data */
240         if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) {
241                 if (op->customdata) {
242                         MEM_freeN(op->customdata);
243                         op->customdata = NULL;
244                 }
245         }
246
247         return retval;
248 }
249
250 /* macro exec only runs exec calls */
251 static int wm_macro_exec(bContext *C, wmOperator *op)
252 {
253         wmOperator *opm;
254         int retval = OPERATOR_FINISHED;
255         
256         wm_macro_start(op);
257
258         for (opm = op->macro.first; opm; opm = opm->next) {
259                 
260                 if (opm->type->exec) {
261                         retval = opm->type->exec(C, opm);
262                         OPERATOR_RETVAL_CHECK(retval);
263                 
264                         if (retval & OPERATOR_FINISHED) {
265                                 MacroData *md = op->customdata;
266                                 md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
267                         }
268                         else {
269                                 break; /* operator didn't finish, end macro */
270                         }
271                 }
272                 else {
273                         CLOG_WARN(WM_LOG_OPERATORS, "'%s' cant exec macro", opm->type->idname);
274                 }
275         }
276         
277         return wm_macro_end(op, retval);
278 }
279
280 static int wm_macro_invoke_internal(bContext *C, wmOperator *op, const wmEvent *event, wmOperator *opm)
281 {
282         int retval = OPERATOR_FINISHED;
283
284         /* start from operator received as argument */
285         for (; opm; opm = opm->next) {
286                 if (opm->type->invoke)
287                         retval = opm->type->invoke(C, opm, event);
288                 else if (opm->type->exec)
289                         retval = opm->type->exec(C, opm);
290
291                 OPERATOR_RETVAL_CHECK(retval);
292
293                 BLI_movelisttolist(&op->reports->list, &opm->reports->list);
294                 
295                 if (retval & OPERATOR_FINISHED) {
296                         MacroData *md = op->customdata;
297                         md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
298                 }
299                 else {
300                         break; /* operator didn't finish, end macro */
301                 }
302         }
303
304         return wm_macro_end(op, retval);
305 }
306
307 static int wm_macro_invoke(bContext *C, wmOperator *op, const wmEvent *event)
308 {
309         wm_macro_start(op);
310         return wm_macro_invoke_internal(C, op, event, op->macro.first);
311 }
312
313 static int wm_macro_modal(bContext *C, wmOperator *op, const wmEvent *event)
314 {
315         wmOperator *opm = op->opm;
316         int retval = OPERATOR_FINISHED;
317         
318         if (opm == NULL) {
319                 CLOG_ERROR(WM_LOG_OPERATORS, "macro error, calling NULL modal()");
320         }
321         else {
322                 retval = opm->type->modal(C, opm, event);
323                 OPERATOR_RETVAL_CHECK(retval);
324
325                 /* if we're halfway through using a tool and cancel it, clear the options [#37149] */
326                 if (retval & OPERATOR_CANCELLED) {
327                         WM_operator_properties_clear(opm->ptr);
328                 }
329
330                 /* if this one is done but it's not the last operator in the macro */
331                 if ((retval & OPERATOR_FINISHED) && opm->next) {
332                         MacroData *md = op->customdata;
333
334                         md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
335
336                         retval = wm_macro_invoke_internal(C, op, event, opm->next);
337
338                         /* if new operator is modal and also added its own handler */
339                         if (retval & OPERATOR_RUNNING_MODAL && op->opm != opm) {
340                                 wmWindow *win = CTX_wm_window(C);
341                                 wmEventHandler *handler;
342
343                                 handler = BLI_findptr(&win->modalhandlers, op, offsetof(wmEventHandler, op));
344                                 if (handler) {
345                                         BLI_remlink(&win->modalhandlers, handler);
346                                         wm_event_free_handler(handler);
347                                 }
348
349                                 /* if operator is blocking, grab cursor
350                                  * This may end up grabbing twice, but we don't care.
351                                  * */
352                                 if (op->opm->type->flag & OPTYPE_BLOCKING) {
353                                         int bounds[4] = {-1, -1, -1, -1};
354                                         const bool wrap = (
355                                                 (U.uiflag & USER_CONTINUOUS_MOUSE) &&
356                                                 ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR)));
357
358                                         if (wrap) {
359                                                 ARegion *ar = CTX_wm_region(C);
360                                                 if (ar) {
361                                                         bounds[0] = ar->winrct.xmin;
362                                                         bounds[1] = ar->winrct.ymax;
363                                                         bounds[2] = ar->winrct.xmax;
364                                                         bounds[3] = ar->winrct.ymin;
365                                                 }
366                                         }
367
368                                         WM_cursor_grab_enable(win, wrap, false, bounds);
369                                 }
370                         }
371                 }
372         }
373
374         return wm_macro_end(op, retval);
375 }
376
377 static void wm_macro_cancel(bContext *C, wmOperator *op)
378 {
379         /* call cancel on the current modal operator, if any */
380         if (op->opm && op->opm->type->cancel) {
381                 op->opm->type->cancel(C, op->opm);
382         }
383
384         wm_macro_end(op, OPERATOR_CANCELLED);
385 }
386
387 /* Names have to be static for now */
388 wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag)
389 {
390         wmOperatorType *ot;
391         const char *i18n_context;
392         
393         if (WM_operatortype_find(idname, true)) {
394                 CLOG_ERROR(WM_LOG_OPERATORS, "operator %s exists, cannot create macro", idname);
395                 return NULL;
396         }
397         
398         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
399         ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties);
400         
401         ot->idname = idname;
402         ot->name = name;
403         ot->description = description;
404         ot->flag = OPTYPE_MACRO | flag;
405         
406         ot->exec = wm_macro_exec;
407         ot->invoke = wm_macro_invoke;
408         ot->modal = wm_macro_modal;
409         ot->cancel = wm_macro_cancel;
410         ot->poll = NULL;
411
412         if (!ot->description) /* XXX All ops should have a description but for now allow them not to. */
413                 ot->description = UNDOCUMENTED_OPERATOR_TIP;
414         
415         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
416         RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
417         /* Use i18n context from ext.srna if possible (py operators). */
418         i18n_context = ot->ext.srna ? RNA_struct_translation_context(ot->ext.srna) : BLT_I18NCONTEXT_OPERATOR_DEFAULT;
419         RNA_def_struct_translation_context(ot->srna, i18n_context);
420         ot->translation_context = i18n_context;
421
422         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
423
424         return ot;
425 }
426
427 void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata)
428 {
429         wmOperatorType *ot;
430
431         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
432         ot->srna = RNA_def_struct_ptr(&BLENDER_RNA, "", &RNA_OperatorProperties);
433
434         ot->flag = OPTYPE_MACRO;
435         ot->exec = wm_macro_exec;
436         ot->invoke = wm_macro_invoke;
437         ot->modal = wm_macro_modal;
438         ot->cancel = wm_macro_cancel;
439         ot->poll = NULL;
440
441         if (!ot->description)
442                 ot->description = UNDOCUMENTED_OPERATOR_TIP;
443
444         /* Set the default i18n context now, so that opfunc can redefine it if needed! */
445         RNA_def_struct_translation_context(ot->srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
446         ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT;
447         opfunc(ot, userdata);
448
449         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
450         RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
451
452         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
453 }
454
455 wmOperatorTypeMacro *WM_operatortype_macro_define(wmOperatorType *ot, const char *idname)
456 {
457         wmOperatorTypeMacro *otmacro = MEM_callocN(sizeof(wmOperatorTypeMacro), "wmOperatorTypeMacro");
458
459         BLI_strncpy(otmacro->idname, idname, OP_MAX_TYPENAME);
460
461         /* do this on first use, since operatordefinitions might have been not done yet */
462         WM_operator_properties_alloc(&(otmacro->ptr), &(otmacro->properties), idname);
463         WM_operator_properties_sanitize(otmacro->ptr, 1);
464
465         BLI_addtail(&ot->macro, otmacro);
466
467         {
468                 /* operator should always be found but in the event its not. don't segfault */
469                 wmOperatorType *otsub = WM_operatortype_find(idname, 0);
470                 if (otsub) {
471                         RNA_def_pointer_runtime(ot->srna, otsub->idname, otsub->srna,
472                                                 otsub->name, otsub->description);
473                 }
474         }
475
476         return otmacro;
477 }
478
479 static void wm_operatortype_free_macro(wmOperatorType *ot)
480 {
481         wmOperatorTypeMacro *otmacro;
482         
483         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
484                 if (otmacro->ptr) {
485                         WM_operator_properties_free(otmacro->ptr);
486                         MEM_freeN(otmacro->ptr);
487                 }
488         }
489         BLI_freelistN(&ot->macro);
490 }
491
492 void WM_operatortype_remove_ptr(wmOperatorType *ot)
493 {
494         BLI_assert(ot == WM_operatortype_find(ot->idname, false));
495
496         RNA_struct_free(&BLENDER_RNA, ot->srna);
497
498         if (ot->last_properties) {
499                 IDP_FreeProperty(ot->last_properties);
500                 MEM_freeN(ot->last_properties);
501         }
502
503         if (ot->macro.first)
504                 wm_operatortype_free_macro(ot);
505
506         BLI_ghash_remove(global_ops_hash, ot->idname, NULL, NULL);
507
508         WM_keyconfig_update_operatortype();
509
510         MEM_freeN(ot);
511 }
512
513 bool WM_operatortype_remove(const char *idname)
514 {
515         wmOperatorType *ot = WM_operatortype_find(idname, 0);
516
517         if (ot == NULL)
518                 return false;
519
520         WM_operatortype_remove_ptr(ot);
521
522         return true;
523 }
524
525 /**
526  * Remove memory of all previously executed tools.
527  */
528 void WM_operatortype_last_properties_clear_all(void)
529 {
530         GHashIterator iter;
531
532         for (WM_operatortype_iter(&iter);
533              (!BLI_ghashIterator_done(&iter));
534              (BLI_ghashIterator_step(&iter)))
535         {
536                 wmOperatorType *ot = BLI_ghashIterator_getValue(&iter);
537
538                 if (ot->last_properties) {
539                         IDP_FreeProperty(ot->last_properties);
540                         MEM_freeN(ot->last_properties);
541                         ot->last_properties = NULL;
542                 }
543         }
544 }
545
546 /**
547  * Tag all operator-properties of \a ot defined after calling this, until
548  * the next #WM_operatortype_props_advanced_end call (if available), with
549  * #OP_PROP_TAG_ADVANCED. Previously defined ones properties not touched.
550  *
551  * Calling this multiple times without a call to #WM_operatortype_props_advanced_end,
552  * all calls after the first one are ignored. Meaning all propereties defined after the
553  * first call are tagged as advanced.
554  *
555  * This doesn't do the actual tagging, #WM_operatortype_props_advanced_end does which is
556  * called for all operators during registration (see #wm_operatortype_append__end).
557  */
558 void WM_operatortype_props_advanced_begin(wmOperatorType *ot)
559 {
560         if (ot_prop_basic_count == -1) { /* Don't do anything if _begin was called before, but not _end  */
561                 ot_prop_basic_count = RNA_struct_count_properties(ot->srna);
562         }
563 }
564
565 /**
566  * Tags all operator-properties of \ot defined since the first #WM_operatortype_props_advanced_begin
567  * call, or the last #WM_operatortype_props_advanced_end call, with #OP_PROP_TAG_ADVANCED.
568  * Note that this is called for all operators during registration (see #wm_operatortype_append__end).
569  * So it does not need to be explicitly called in operator-type definition.
570  */
571 void WM_operatortype_props_advanced_end(wmOperatorType *ot)
572 {
573         PointerRNA struct_ptr;
574         int counter = 0;
575
576         if (ot_prop_basic_count == -1) {
577                 /* WM_operatortype_props_advanced_begin was not called. Don't do anything. */
578                 return;
579         }
580
581         RNA_pointer_create(NULL, ot->srna, NULL, &struct_ptr);
582
583         RNA_STRUCT_BEGIN (&struct_ptr, prop)
584         {
585                 counter++;
586                 if (counter > ot_prop_basic_count) {
587                         WM_operatortype_prop_tag(prop, OP_PROP_TAG_ADVANCED);
588                 }
589         }
590         RNA_STRUCT_END;
591
592         ot_prop_basic_count = -1;
593 }
594
595 /* SOME_OT_op -> some.op */
596 void WM_operator_py_idname(char *to, const char *from)
597 {
598         const char *sep = strstr(from, "_OT_");
599         if (sep) {
600                 int ofs = (sep - from);
601                 
602                 /* note, we use ascii tolower instead of system tolower, because the
603                  * latter depends on the locale, and can lead to idname mismatch */
604                 memcpy(to, from, sizeof(char) * ofs);
605                 BLI_str_tolower_ascii(to, ofs);
606
607                 to[ofs] = '.';
608                 BLI_strncpy(to + (ofs + 1), sep + 4, OP_MAX_TYPENAME - (ofs + 1));
609         }
610         else {
611                 /* should not happen but support just in case */
612                 BLI_strncpy(to, from, OP_MAX_TYPENAME);
613         }
614 }
615
616 /* some.op -> SOME_OT_op */
617 void WM_operator_bl_idname(char *to, const char *from)
618 {
619         if (from) {
620                 const char *sep = strchr(from, '.');
621
622                 if (sep) {
623                         int ofs = (sep - from);
624
625                         memcpy(to, from, sizeof(char) * ofs);
626                         BLI_str_toupper_ascii(to, ofs);
627                         strcpy(to + ofs, "_OT_");
628                         strcpy(to + (ofs + 4), sep + 1);
629                 }
630                 else {
631                         /* should not happen but support just in case */
632                         BLI_strncpy(to, from, OP_MAX_TYPENAME);
633                 }
634         }
635         else
636                 to[0] = 0;
637 }
638
639 /**
640  * Sanity check to ensure #WM_operator_bl_idname won't fail.
641  * \returns true when there are no problems with \a idname, otherwise report an error.
642  */
643 bool WM_operator_py_idname_ok_or_report(ReportList *reports, const char *classname, const char *idname)
644 {
645         const char *ch = idname;
646         int dot = 0;
647         int i;
648         for (i = 0; *ch; i++, ch++) {
649                 if ((*ch >= 'a' && *ch <= 'z') || (*ch >= '0' && *ch <= '9') || *ch == '_') {
650                         /* pass */
651                 }
652                 else if (*ch == '.') {
653                         dot++;
654                 }
655                 else {
656                         BKE_reportf(reports, RPT_ERROR,
657                                     "Registering operator class: '%s', invalid bl_idname '%s', at position %d",
658                                     classname, idname, i);
659                         return false;
660                 }
661         }
662
663         if (i > (MAX_NAME - 3)) {
664                 BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s', invalid bl_idname '%s', "
665                             "is too long, maximum length is %d", classname, idname,
666                             MAX_NAME - 3);
667                 return false;
668         }
669
670         if (dot != 1) {
671                 BKE_reportf(reports, RPT_ERROR,
672                             "Registering operator class: '%s', invalid bl_idname '%s', must contain 1 '.' character",
673                             classname, idname);
674                 return false;
675         }
676         return true;
677 }
678
679 /**
680  * Print a string representation of the operator, with the args that it runs so python can run it again.
681  *
682  * When calling from an existing wmOperator, better to use simple version:
683  * `WM_operator_pystring(C, op);`
684  *
685  * \note Both \a op and \a opptr may be `NULL` (\a op is only used for macro operators).
686  */
687 char *WM_operator_pystring_ex(bContext *C, wmOperator *op, const bool all_args, const bool macro_args,
688                               wmOperatorType *ot, PointerRNA *opptr)
689 {
690         char idname_py[OP_MAX_TYPENAME];
691
692         /* for building the string */
693         DynStr *dynstr = BLI_dynstr_new();
694         char *cstring;
695         char *cstring_args;
696
697         /* arbitrary, but can get huge string with stroke painting otherwise */
698         int max_prop_length = 10;
699
700         WM_operator_py_idname(idname_py, ot->idname);
701         BLI_dynstr_appendf(dynstr, "bpy.ops.%s(", idname_py);
702
703         if (op && op->macro.first) {
704                 /* Special handling for macros, else we only get default values in this case... */
705                 wmOperator *opm;
706                 bool first_op = true;
707
708                 opm = macro_args ? op->macro.first : NULL;
709
710                 for (; opm; opm = opm->next) {
711                         PointerRNA *opmptr = opm->ptr;
712                         PointerRNA opmptr_default;
713                         if (opmptr == NULL) {
714                                 WM_operator_properties_create_ptr(&opmptr_default, opm->type);
715                                 opmptr = &opmptr_default;
716                         }
717
718                         cstring_args = RNA_pointer_as_string_id(C, opmptr);
719                         if (first_op) {
720                                 BLI_dynstr_appendf(dynstr, "%s=%s", opm->type->idname, cstring_args);
721                                 first_op = false;
722                         }
723                         else {
724                                 BLI_dynstr_appendf(dynstr, ", %s=%s", opm->type->idname, cstring_args);
725                         }
726                         MEM_freeN(cstring_args);
727
728                         if (opmptr == &opmptr_default) {
729                                 WM_operator_properties_free(&opmptr_default);
730                         }
731                 }
732         }
733         else {
734                 /* only to get the orginal props for comparisons */
735                 PointerRNA opptr_default;
736                 const bool macro_args_test = ot->macro.first ? macro_args : true;
737
738                 if (opptr == NULL) {
739                         WM_operator_properties_create_ptr(&opptr_default, ot);
740                         opptr = &opptr_default;
741                 }
742
743                 cstring_args = RNA_pointer_as_string_keywords(C, opptr, false, all_args, macro_args_test, max_prop_length);
744                 BLI_dynstr_append(dynstr, cstring_args);
745                 MEM_freeN(cstring_args);
746
747                 if (opptr == &opptr_default) {
748                         WM_operator_properties_free(&opptr_default);
749                 }
750         }
751
752         BLI_dynstr_append(dynstr, ")");
753
754         cstring = BLI_dynstr_get_cstring(dynstr);
755         BLI_dynstr_free(dynstr);
756         return cstring;
757 }
758
759 char *WM_operator_pystring(bContext *C, wmOperator *op,
760                            const bool all_args, const bool macro_args)
761 {
762         return WM_operator_pystring_ex(C, op, all_args, macro_args, op->type, op->ptr);
763 }
764
765
766 /**
767  * \return true if the string was shortened
768  */
769 bool WM_operator_pystring_abbreviate(char *str, int str_len_max)
770 {
771         const int str_len = strlen(str);
772         const char *parens_start = strchr(str, '(');
773
774         if (parens_start) {
775                 const int parens_start_pos = parens_start - str;
776                 const char *parens_end = strrchr(parens_start + 1, ')');
777
778                 if (parens_end) {
779                         const int parens_len = parens_end - parens_start;
780
781                         if (parens_len > str_len_max) {
782                                 const char *comma_first = strchr(parens_start, ',');
783
784                                 /* truncate after the first comma */
785                                 if (comma_first) {
786                                         const char end_str[] = " ... )";
787                                         const int end_str_len = sizeof(end_str) - 1;
788
789                                         /* leave a place for the first argument*/
790                                         const int new_str_len = (comma_first - parens_start) + 1;
791
792                                         if (str_len >= new_str_len + parens_start_pos + end_str_len + 1) {
793                                                 /* append " ... )" to the string after the comma */
794                                                 memcpy(str + new_str_len + parens_start_pos, end_str, end_str_len + 1);
795
796                                                 return true;
797                                         }
798                                 }
799                         }
800                 }
801         }
802
803         return false;
804 }
805
806 /* return NULL if no match is found */
807 #if 0
808 static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index)
809 {
810
811         /* loop over all context items and do 2 checks
812          *
813          * - see if the pointer is in the context.
814          * - see if the pointers ID is in the context.
815          */
816
817         /* don't get from the context store since this is normally set only for the UI and not usable elsewhere */
818         ListBase lb = CTX_data_dir_get_ex(C, false, true, true);
819         LinkData *link;
820
821         const char *member_found = NULL;
822         const char *member_id = NULL;
823
824         char *prop_str = NULL;
825         char *ret = NULL;
826
827
828         for (link = lb.first; link; link = link->next) {
829                 const char *identifier = link->data;
830                 PointerRNA ctx_item_ptr = {{0}} // CTX_data_pointer_get(C, identifier); // XXX, this isnt working
831
832                 if (ctx_item_ptr.type == NULL) {
833                         continue;
834                 }
835
836                 if (ptr->id.data == ctx_item_ptr.id.data) {
837                         if ((ptr->data == ctx_item_ptr.data) &&
838                             (ptr->type == ctx_item_ptr.type))
839                         {
840                                 /* found! */
841                                 member_found = identifier;
842                                 break;
843                         }
844                         else if (RNA_struct_is_ID(ctx_item_ptr.type)) {
845                                 /* we found a reference to this ID,
846                                  * so fallback to it if there is no direct reference */
847                                 member_id = identifier;
848                         }
849                 }
850         }
851
852         if (member_found) {
853                 prop_str = RNA_path_property_py(ptr, prop, index);
854                 if (prop_str) {
855                         ret = BLI_sprintfN("bpy.context.%s.%s", member_found, prop_str);
856                         MEM_freeN(prop_str);
857                 }
858         }
859         else if (member_id) {
860                 prop_str = RNA_path_struct_property_py(ptr, prop, index);
861                 if (prop_str) {
862                         ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str);
863                         MEM_freeN(prop_str);
864                 }
865         }
866
867         BLI_freelistN(&lb);
868
869         return ret;
870 }
871 #else
872
873 /* use hard coded checks for now */
874 static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index)
875 {
876         const char *member_id = NULL;
877
878         char *prop_str = NULL;
879         char *ret = NULL;
880
881         if (ptr->id.data) {
882
883 #define CTX_TEST_PTR_ID(C, member, idptr) \
884                 { \
885                         const char *ctx_member = member; \
886                         PointerRNA ctx_item_ptr = CTX_data_pointer_get(C, ctx_member); \
887                         if (ctx_item_ptr.id.data == idptr) { \
888                                 member_id = ctx_member; \
889                                 break; \
890                         } \
891                 } (void)0
892
893 #define CTX_TEST_PTR_ID_CAST(C, member, member_full, cast, idptr) \
894                 { \
895                         const char *ctx_member = member; \
896                         const char *ctx_member_full = member_full; \
897                         PointerRNA ctx_item_ptr = CTX_data_pointer_get(C, ctx_member); \
898                         if (ctx_item_ptr.id.data && cast(ctx_item_ptr.id.data) == idptr) { \
899                                 member_id = ctx_member_full; \
900                                 break; \
901                         } \
902                 } (void)0
903
904 #define CTX_TEST_PTR_DATA_TYPE(C, member, rna_type, rna_ptr, dataptr_cmp) \
905                 { \
906                         const char *ctx_member = member; \
907                         if (RNA_struct_is_a((ptr)->type, &(rna_type)) && (ptr)->data == (dataptr_cmp)) { \
908                                 member_id = ctx_member; \
909                                 break; \
910                         } \
911                 } (void)0
912
913 #define CTX_TEST_SPACE_TYPE(space_data_type, member_full, dataptr_cmp) \
914                 { \
915                         const char *ctx_member_full = member_full; \
916                         if (space_data->spacetype == space_data_type && ptr->data == dataptr_cmp) { \
917                                 member_id = ctx_member_full; \
918                                 break; \
919                         } \
920                 } (void)0
921
922                 switch (GS(((ID *)ptr->id.data)->name)) {
923                         case ID_SCE:
924                         {
925                                 CTX_TEST_PTR_DATA_TYPE(C, "active_gpencil_brush", RNA_GPencilBrush, ptr, CTX_data_active_gpencil_brush(C));
926                                 CTX_TEST_PTR_ID(C, "scene", ptr->id.data);
927                                 break;
928                         }
929                         case ID_OB:
930                         {
931                                 CTX_TEST_PTR_ID(C, "object", ptr->id.data);
932                                 break;
933                         }
934                         /* from rna_Main_objects_new */
935                         case OB_DATA_SUPPORT_ID_CASE:
936                         {
937 #define ID_CAST_OBDATA(id_pt) (((Object *)(id_pt))->data)
938                                 CTX_TEST_PTR_ID_CAST(C, "object", "object.data", ID_CAST_OBDATA, ptr->id.data);
939                                 break;
940 #undef ID_CAST_OBDATA
941                         }
942                         case ID_MA:
943                         {
944 #define ID_CAST_OBMATACT(id_pt) (give_current_material(((Object *)id_pt), ((Object *)id_pt)->actcol))
945                                 CTX_TEST_PTR_ID_CAST(C, "object", "object.active_material", ID_CAST_OBMATACT, ptr->id.data);
946                                 break;
947 #undef ID_CAST_OBMATACT
948                         }
949                         case ID_WO:
950                         {
951 #define ID_CAST_SCENEWORLD(id_pt) (((Scene *)(id_pt))->world)
952                                 CTX_TEST_PTR_ID_CAST(C, "scene", "scene.world", ID_CAST_SCENEWORLD, ptr->id.data);
953                                 break;
954 #undef ID_CAST_SCENEWORLD
955                         }
956                         case ID_SCR:
957                         {
958                                 CTX_TEST_PTR_ID(C, "screen", ptr->id.data);
959
960                                 SpaceLink *space_data = CTX_wm_space_data(C);
961
962                                 CTX_TEST_PTR_DATA_TYPE(C, "space_data", RNA_Space, ptr, space_data);
963                                 CTX_TEST_PTR_DATA_TYPE(C, "area", RNA_Area, ptr, CTX_wm_area(C));
964                                 CTX_TEST_PTR_DATA_TYPE(C, "region", RNA_Region, ptr, CTX_wm_region(C));
965
966                                 CTX_TEST_SPACE_TYPE(SPACE_IMAGE, "space_data.uv_editor", space_data);
967                                 CTX_TEST_SPACE_TYPE(SPACE_VIEW3D, "space_data.fx_settings", &(CTX_wm_view3d(C)->fx_settings));
968                                 CTX_TEST_SPACE_TYPE(SPACE_NLA, "space_data.dopesheet", CTX_wm_space_nla(C)->ads);
969                                 CTX_TEST_SPACE_TYPE(SPACE_IPO, "space_data.dopesheet", CTX_wm_space_graph(C)->ads);
970                                 CTX_TEST_SPACE_TYPE(SPACE_ACTION, "space_data.dopesheet", &(CTX_wm_space_action(C)->ads));
971                                 CTX_TEST_SPACE_TYPE(SPACE_FILE, "space_data.params", CTX_wm_space_file(C)->params);
972                                 break;
973                         }
974                         default:
975                                 break;
976                 }
977
978                 if (member_id) {
979                         prop_str = RNA_path_struct_property_py(ptr, prop, index);
980                         if (prop_str) {
981                                 ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str);
982                                 MEM_freeN(prop_str);
983                         }
984                 }
985 #undef CTX_TEST_PTR_ID
986 #undef CTX_TEST_PTR_ID_CAST
987 #undef CTX_TEST_SPACE_TYPE
988         }
989
990         return ret;
991 }
992 #endif
993
994 char *WM_prop_pystring_assign(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index)
995 {
996         char *lhs, *rhs, *ret;
997
998         lhs = C ? wm_prop_pystring_from_context(C, ptr, prop, index) : NULL;
999
1000         if (lhs == NULL) {
1001                 /* fallback to bpy.data.foo[id] if we dont find in the context */
1002                 lhs = RNA_path_full_property_py(ptr, prop, index);
1003         }
1004
1005         if (!lhs) {
1006                 return NULL;
1007         }
1008
1009         rhs = RNA_property_as_string(C, ptr, prop, index, INT_MAX);
1010         if (!rhs) {
1011                 MEM_freeN(lhs);
1012                 return NULL;
1013         }
1014
1015         ret = BLI_sprintfN("%s = %s", lhs, rhs);
1016         MEM_freeN(lhs);
1017         MEM_freeN(rhs);
1018         return ret;
1019 }
1020
1021 void WM_operator_properties_create_ptr(PointerRNA *ptr, wmOperatorType *ot)
1022 {
1023         RNA_pointer_create(NULL, ot->srna, NULL, ptr);
1024 }
1025
1026 void WM_operator_properties_create(PointerRNA *ptr, const char *opstring)
1027 {
1028         wmOperatorType *ot = WM_operatortype_find(opstring, false);
1029
1030         if (ot)
1031                 WM_operator_properties_create_ptr(ptr, ot);
1032         else
1033                 RNA_pointer_create(NULL, &RNA_OperatorProperties, NULL, ptr);
1034 }
1035
1036 /* similar to the function above except its uses ID properties
1037  * used for keymaps and macros */
1038 void WM_operator_properties_alloc(PointerRNA **ptr, IDProperty **properties, const char *opstring)
1039 {
1040         if (*properties == NULL) {
1041                 IDPropertyTemplate val = {0};
1042                 *properties = IDP_New(IDP_GROUP, &val, "wmOpItemProp");
1043         }
1044
1045         if (*ptr == NULL) {
1046                 *ptr = MEM_callocN(sizeof(PointerRNA), "wmOpItemPtr");
1047                 WM_operator_properties_create(*ptr, opstring);
1048         }
1049
1050         (*ptr)->data = *properties;
1051
1052 }
1053
1054 void WM_operator_properties_sanitize(PointerRNA *ptr, const bool no_context)
1055 {
1056         RNA_STRUCT_BEGIN (ptr, prop)
1057         {
1058                 switch (RNA_property_type(prop)) {
1059                         case PROP_ENUM:
1060                                 if (no_context)
1061                                         RNA_def_property_flag(prop, PROP_ENUM_NO_CONTEXT);
1062                                 else
1063                                         RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1064                                 break;
1065                         case PROP_POINTER:
1066                         {
1067                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
1068
1069                                 /* recurse into operator properties */
1070                                 if (RNA_struct_is_a(ptype, &RNA_OperatorProperties)) {
1071                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1072                                         WM_operator_properties_sanitize(&opptr, no_context);
1073                                 }
1074                                 break;
1075                         }
1076                         default:
1077                                 break;
1078                 }
1079         }
1080         RNA_STRUCT_END;
1081 }
1082
1083
1084 /** set all props to their default,
1085  * \param do_update Only update un-initialized props.
1086  *
1087  * \note, theres nothing specific to operators here.
1088  * this could be made a general function.
1089  */
1090 bool WM_operator_properties_default(PointerRNA *ptr, const bool do_update)
1091 {
1092         bool changed = false;
1093         RNA_STRUCT_BEGIN (ptr, prop)
1094         {
1095                 switch (RNA_property_type(prop)) {
1096                         case PROP_POINTER:
1097                         {
1098                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
1099                                 if (ptype != &RNA_Struct) {
1100                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1101                                         changed |= WM_operator_properties_default(&opptr, do_update);
1102                                 }
1103                                 break;
1104                         }
1105                         default:
1106                                 if ((do_update == false) || (RNA_property_is_set(ptr, prop) == false)) {
1107                                         if (RNA_property_reset(ptr, prop, -1)) {
1108                                                 changed = true;
1109                                         }
1110                                 }
1111                                 break;
1112                 }
1113         }
1114         RNA_STRUCT_END;
1115
1116         return changed;
1117 }
1118
1119 /* remove all props without PROP_SKIP_SAVE */
1120 void WM_operator_properties_reset(wmOperator *op)
1121 {
1122         if (op->ptr->data) {
1123                 PropertyRNA *iterprop;
1124                 iterprop = RNA_struct_iterator_property(op->type->srna);
1125
1126                 RNA_PROP_BEGIN (op->ptr, itemptr, iterprop)
1127                 {
1128                         PropertyRNA *prop = itemptr.data;
1129
1130                         if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
1131                                 const char *identifier = RNA_property_identifier(prop);
1132                                 RNA_struct_idprops_unset(op->ptr, identifier);
1133                         }
1134                 }
1135                 RNA_PROP_END;
1136         }
1137 }
1138
1139 void WM_operator_properties_clear(PointerRNA *ptr)
1140 {
1141         IDProperty *properties = ptr->data;
1142
1143         if (properties) {
1144                 IDP_ClearProperty(properties);
1145         }
1146 }
1147
1148 void WM_operator_properties_free(PointerRNA *ptr)
1149 {
1150         IDProperty *properties = ptr->data;
1151
1152         if (properties) {
1153                 IDP_FreeProperty(properties);
1154                 MEM_freeN(properties);
1155                 ptr->data = NULL; /* just in case */
1156         }
1157 }
1158
1159 /* ************ default op callbacks, exported *********** */
1160
1161 void WM_operator_view3d_unit_defaults(struct bContext *C, struct wmOperator *op)
1162 {
1163         if (op->flag & OP_IS_INVOKE) {
1164                 Scene *scene = CTX_data_scene(C);
1165                 View3D *v3d = CTX_wm_view3d(C);
1166
1167                 const float dia = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
1168
1169                 /* always run, so the values are initialized,
1170                  * otherwise we may get differ behavior when (dia != 1.0) */
1171                 RNA_STRUCT_BEGIN (op->ptr, prop)
1172                 {
1173                         if (RNA_property_type(prop) == PROP_FLOAT) {
1174                                 PropertySubType pstype = RNA_property_subtype(prop);
1175                                 if (pstype == PROP_DISTANCE) {
1176                                         /* we don't support arrays yet */
1177                                         BLI_assert(RNA_property_array_check(prop) == false);
1178                                         /* initialize */
1179                                         if (!RNA_property_is_set_ex(op->ptr, prop, false)) {
1180                                                 const float value = RNA_property_float_get_default(op->ptr, prop) * dia;
1181                                                 RNA_property_float_set(op->ptr, prop, value);
1182                                         }
1183                                 }
1184                         }
1185                 }
1186                 RNA_STRUCT_END;
1187         }
1188 }
1189
1190 int WM_operator_smooth_viewtx_get(const wmOperator *op)
1191 {
1192         return (op->flag & OP_IS_INVOKE) ? U.smooth_viewtx : 0;
1193 }
1194
1195 /* invoke callback, uses enum property named "type" */
1196 int WM_menu_invoke_ex(bContext *C, wmOperator *op, int opcontext)
1197 {
1198         PropertyRNA *prop = op->type->prop;
1199         uiPopupMenu *pup;
1200         uiLayout *layout;
1201
1202         if (prop == NULL) {
1203                 CLOG_ERROR(WM_LOG_OPERATORS,
1204                            "'%s' has no enum property set",
1205                            op->type->idname);
1206         }
1207         else if (RNA_property_type(prop) != PROP_ENUM) {
1208                 CLOG_ERROR(WM_LOG_OPERATORS,
1209                            "'%s', '%s' is not an enum property",
1210                            op->type->idname, RNA_property_identifier(prop));
1211         }
1212         else if (RNA_property_is_set(op->ptr, prop)) {
1213                 const int retval = op->type->exec(C, op);
1214                 OPERATOR_RETVAL_CHECK(retval);
1215                 return retval;
1216         }
1217         else {
1218                 pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
1219                 layout = UI_popup_menu_layout(pup);
1220                 /* set this so the default execution context is the same as submenus */
1221                 uiLayoutSetOperatorContext(layout, opcontext);
1222                 uiItemsFullEnumO(layout, op->type->idname, RNA_property_identifier(prop), op->ptr->data, opcontext, 0);
1223                 UI_popup_menu_end(C, pup);
1224                 return OPERATOR_INTERFACE;
1225         }
1226
1227         return OPERATOR_CANCELLED;
1228 }
1229
1230 int WM_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1231 {
1232         return WM_menu_invoke_ex(C, op, WM_OP_INVOKE_REGION_WIN);
1233 }
1234
1235 struct EnumSearchMenu {
1236         wmOperator *op; /* the operator that will be executed when selecting an item */
1237
1238         bool use_previews;
1239         short prv_cols, prv_rows;
1240 };
1241
1242 /* generic enum search invoke popup */
1243 static uiBlock *wm_enum_search_menu(bContext *C, ARegion *ar, void *arg)
1244 {
1245         struct EnumSearchMenu *search_menu = arg;
1246         wmWindow *win = CTX_wm_window(C);
1247         wmOperator *op = search_menu->op;
1248         /* template_ID uses 4 * widget_unit for width, we use a bit more, some items may have a suffix to show */
1249         const int width = search_menu->use_previews ? 5 * U.widget_unit * search_menu->prv_cols : UI_searchbox_size_x();
1250         const int height = search_menu->use_previews ? 5 * U.widget_unit * search_menu->prv_rows : UI_searchbox_size_y();
1251         static char search[256] = "";
1252         uiBlock *block;
1253         uiBut *but;
1254
1255         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1256         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
1257
1258         search[0] = '\0';
1259         BLI_assert(search_menu->use_previews || (search_menu->prv_cols == 0 && search_menu->prv_rows == 0));
1260 #if 0 /* ok, this isn't so easy... */
1261         uiDefBut(block, UI_BTYPE_LABEL, 0, RNA_struct_ui_name(op->type->srna), 10, 10, UI_searchbox_size_x(), UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
1262 #endif
1263         but = uiDefSearchButO_ptr(block, op->type, op->ptr->data, search, 0, ICON_VIEWZOOM, sizeof(search),
1264                                   10, 10, width, UI_UNIT_Y, search_menu->prv_rows, search_menu->prv_cols, "");
1265
1266         /* fake button, it holds space for search items */
1267         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - UI_searchbox_size_y(), width, height, NULL, 0, 0, 0, 0, NULL);
1268
1269         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1270         UI_but_focus_on_enter_event(win, but);
1271
1272         return block;
1273 }
1274
1275 /**
1276  * Similar to #WM_enum_search_invoke, but draws previews. Also, this can't
1277  * be used as invoke callback directly since it needs additional info.
1278  */
1279 int WM_enum_search_invoke_previews(
1280         bContext *C, wmOperator *op, short prv_cols, short prv_rows)
1281 {
1282         static struct EnumSearchMenu search_menu;
1283
1284         search_menu.op = op;
1285         search_menu.use_previews = true;
1286         search_menu.prv_cols = prv_cols;
1287         search_menu.prv_rows = prv_rows;
1288
1289         UI_popup_block_invoke(C, wm_enum_search_menu, &search_menu);
1290
1291         return OPERATOR_INTERFACE;
1292 }
1293
1294 int WM_enum_search_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1295 {
1296         static struct EnumSearchMenu search_menu;
1297         search_menu.op = op;
1298         UI_popup_block_invoke(C, wm_enum_search_menu, &search_menu);
1299         return OPERATOR_INTERFACE;
1300 }
1301
1302 /* Can't be used as an invoke directly, needs message arg (can be NULL) */
1303 int WM_operator_confirm_message_ex(bContext *C, wmOperator *op,
1304                                    const char *title, const int icon,
1305                                    const char *message)
1306 {
1307         uiPopupMenu *pup;
1308         uiLayout *layout;
1309         IDProperty *properties = op->ptr->data;
1310
1311         if (properties && properties->len)
1312                 properties = IDP_CopyProperty(op->ptr->data);
1313         else
1314                 properties = NULL;
1315
1316         pup = UI_popup_menu_begin(C, title, icon);
1317         layout = UI_popup_menu_layout(pup);
1318         uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0, NULL);
1319         UI_popup_menu_end(C, pup);
1320         
1321         return OPERATOR_INTERFACE;
1322 }
1323
1324 int WM_operator_confirm_message(bContext *C, wmOperator *op, const char *message)
1325 {
1326         return WM_operator_confirm_message_ex(C, op, IFACE_("OK?"), ICON_QUESTION, message);
1327 }
1328
1329 int WM_operator_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1330 {
1331         return WM_operator_confirm_message(C, op, NULL);
1332 }
1333
1334 /* op->invoke, opens fileselect if path property not set, otherwise executes */
1335 int WM_operator_filesel(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1336 {
1337         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1338                 return WM_operator_call_notest(C, op); /* call exec direct */
1339         }
1340         else {
1341                 WM_event_add_fileselect(C, op);
1342                 return OPERATOR_RUNNING_MODAL;
1343         }
1344 }
1345
1346 bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const struct ImageFormatData *im_format)
1347 {
1348         PropertyRNA *prop;
1349         char filepath[FILE_MAX];
1350         /* dont NULL check prop, this can only run on ops with a 'filepath' */
1351         prop = RNA_struct_find_property(op->ptr, "filepath");
1352         RNA_property_string_get(op->ptr, prop, filepath);
1353         if (BKE_image_path_ensure_ext_from_imformat(filepath, im_format)) {
1354                 RNA_property_string_set(op->ptr, prop, filepath);
1355                 /* note, we could check for and update 'filename' here,
1356                  * but so far nothing needs this. */
1357                 return true;
1358         }
1359         return false;
1360 }
1361
1362 /* op->poll */
1363 int WM_operator_winactive(bContext *C)
1364 {
1365         if (CTX_wm_window(C) == NULL) return 0;
1366         return 1;
1367 }
1368
1369 /* return false, if the UI should be disabled */
1370 bool WM_operator_check_ui_enabled(const bContext *C, const char *idname)
1371 {
1372         wmWindowManager *wm = CTX_wm_manager(C);
1373         Scene *scene = CTX_data_scene(C);
1374
1375         return !((ED_undo_is_valid(C, idname) == false) || WM_jobs_test(wm, scene, WM_JOB_TYPE_ANY));
1376 }
1377
1378 wmOperator *WM_operator_last_redo(const bContext *C)
1379 {
1380         wmWindowManager *wm = CTX_wm_manager(C);
1381         wmOperator *op;
1382
1383         /* only for operators that are registered and did an undo push */
1384         for (op = wm->operators.last; op; op = op->prev)
1385                 if ((op->type->flag & OPTYPE_REGISTER) && (op->type->flag & OPTYPE_UNDO))
1386                         break;
1387
1388         return op;
1389 }
1390
1391 IDProperty *WM_operator_last_properties_ensure_idprops(wmOperatorType *ot)
1392 {
1393         if (ot->last_properties == NULL) {
1394                 IDPropertyTemplate val = {0};
1395                 ot->last_properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
1396         }
1397         return ot->last_properties;
1398 }
1399
1400 void WM_operator_last_properties_ensure(wmOperatorType *ot, PointerRNA *ptr)
1401 {
1402         IDProperty *props = WM_operator_last_properties_ensure_idprops(ot);
1403         RNA_pointer_create(NULL, ot->srna, props, ptr);
1404 }
1405
1406 /**
1407  * Use for drag & drop a path or name with operators invoke() function.
1408  */
1409 ID *WM_operator_drop_load_path(struct bContext *C, wmOperator *op, const short idcode)
1410 {
1411         ID *id = NULL;
1412         /* check input variables */
1413         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1414                 const bool is_relative_path = RNA_boolean_get(op->ptr, "relative_path");
1415                 char path[FILE_MAX];
1416                 bool exists = false;
1417
1418                 RNA_string_get(op->ptr, "filepath", path);
1419
1420                 errno = 0;
1421
1422                 if (idcode == ID_IM) {
1423                         id = (ID *)BKE_image_load_exists_ex(path, &exists);
1424                 }
1425                 else {
1426                         BLI_assert(0);
1427                 }
1428
1429                 if (!id) {
1430                         BKE_reportf(op->reports, RPT_ERROR, "Cannot read %s '%s': %s",
1431                                     BKE_idcode_to_name(idcode), path,
1432                                     errno ? strerror(errno) : TIP_("unsupported format"));
1433                         return NULL;
1434                 }
1435
1436                 if (is_relative_path ) {
1437                         if (exists == false) {
1438                                 Main *bmain = CTX_data_main(C);
1439
1440                                 if (idcode == ID_IM) {
1441                                         BLI_path_rel(((Image *)id)->name, bmain->name);
1442                                 }
1443                                 else {
1444                                         BLI_assert(0);
1445                                 }
1446                         }
1447                 }
1448         }
1449         else if (RNA_struct_property_is_set(op->ptr, "name")) {
1450                 char name[MAX_ID_NAME - 2];
1451                 RNA_string_get(op->ptr, "name", name);
1452                 id = BKE_libblock_find_name(idcode, name);
1453                 if (!id) {
1454                         BKE_reportf(op->reports, RPT_ERROR, "%s '%s' not found",
1455                                     BKE_idcode_to_name(idcode), name);
1456                         return NULL;
1457                 }
1458                 id_us_plus(id);
1459         }
1460
1461         return id;
1462 }
1463
1464 static void wm_block_redo_cb(bContext *C, void *arg_op, int UNUSED(arg_event))
1465 {
1466         wmOperator *op = arg_op;
1467
1468         if (op == WM_operator_last_redo(C)) {
1469                 /* operator was already executed once? undo & repeat */
1470                 ED_undo_operator_repeat(C, op);
1471         }
1472         else {
1473                 /* operator not executed yet, call it */
1474                 ED_undo_push_op(C, op);
1475                 wm_operator_register(C, op);
1476
1477                 WM_operator_repeat(C, op);
1478         }
1479 }
1480
1481 static void wm_block_redo_cancel_cb(bContext *C, void *arg_op)
1482 {
1483         wmOperator *op = arg_op;
1484
1485         /* if operator never got executed, free it */
1486         if (op != WM_operator_last_redo(C))
1487                 WM_operator_free(op);
1488 }
1489
1490 static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
1491 {
1492         wmOperator *op = arg_op;
1493         uiBlock *block;
1494         uiLayout *layout;
1495         uiStyle *style = UI_style_get();
1496         int width = 15 * UI_UNIT_X;
1497
1498         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1499         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1500         /* UI_BLOCK_NUMSELECT for layer buttons */
1501         UI_block_flag_enable(block, UI_BLOCK_NUMSELECT | UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1502
1503         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
1504          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
1505         assert(op->type->flag & OPTYPE_REGISTER);
1506
1507         UI_block_func_handle_set(block, wm_block_redo_cb, arg_op);
1508         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, 0, style);
1509
1510         if (op == WM_operator_last_redo(C))
1511                 if (!WM_operator_check_ui_enabled(C, op->type->name))
1512                         uiLayoutSetEnabled(layout, false);
1513
1514         if (op->type->flag & OPTYPE_MACRO) {
1515                 for (op = op->macro.first; op; op = op->next) {
1516                         uiTemplateOperatorPropertyButs(C, layout, op, NULL, UI_BUT_LABEL_ALIGN_SPLIT_COLUMN,
1517                                                        UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1518                         if (op->next)
1519                                 uiItemS(layout);
1520                 }
1521         }
1522         else {
1523                 uiTemplateOperatorPropertyButs(C, layout, op, NULL, UI_BUT_LABEL_ALIGN_SPLIT_COLUMN,
1524                                                UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1525         }
1526         
1527         UI_block_bounds_set_popup(block, 4, 0, 0);
1528
1529         return block;
1530 }
1531
1532 typedef struct wmOpPopUp {
1533         wmOperator *op;
1534         int width;
1535         int height;
1536         int free_op;
1537 } wmOpPopUp;
1538
1539 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1540 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1541 {
1542         wmOpPopUp *data = arg1;
1543         uiBlock *block = arg2;
1544
1545         /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be canceled
1546          * in case WM_operator_call_ex exits/reloads the current file (T49199). */
1547         UI_popup_menu_retval_set(block, UI_RETURN_OK, true);
1548
1549         WM_operator_call_ex(C, data->op, true);
1550
1551         /* let execute handle freeing it */
1552         //data->free_op = false;
1553         //data->op = NULL;
1554
1555         /* in this case, wm_operator_ui_popup_cancel wont run */
1556         MEM_freeN(data);
1557
1558         /* get context data *after* WM_operator_call_ex which might have closed the current file and changed context */
1559         wmWindowManager *wm = CTX_wm_manager(C);
1560         wmWindow *win = CTX_wm_window(C);
1561
1562         /* check window before 'block->handle' incase the
1563          * popup execution closed the window and freed the block. see T44688.
1564          */
1565         /* Post 2.78 TODO: Check if this fix and others related to T44688 are still
1566          * needed or can be improved now that requesting context data has been corrected
1567          * (see above). We're close to release so not a good time for experiments.
1568          * -- Julian
1569          */
1570         if (BLI_findindex(&wm->windows, win) != -1) {
1571                 UI_popup_block_close(C, win, block);
1572         }
1573 }
1574
1575 /* Dialogs are popups that require user verification (click OK) before exec */
1576 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1577 {
1578         wmOpPopUp *data = userData;
1579         wmOperator *op = data->op;
1580         uiBlock *block;
1581         uiLayout *layout;
1582         uiStyle *style = UI_style_get();
1583
1584         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1585         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1586
1587         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogues have many items
1588          * where quitting by accident is very annoying */
1589         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NUMSELECT);
1590
1591         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1592         
1593         uiTemplateOperatorPropertyButs(C, layout, op, NULL, UI_BUT_LABEL_ALIGN_SPLIT_COLUMN,
1594                                        UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1595         
1596         /* clear so the OK button is left alone */
1597         UI_block_func_set(block, NULL, NULL, NULL);
1598
1599         /* new column so as not to interfere with custom layouts [#26436] */
1600         {
1601                 uiBlock *col_block;
1602                 uiLayout *col;
1603                 uiBut *btn;
1604
1605                 col = uiLayoutColumn(layout, false);
1606                 col_block = uiLayoutGetBlock(col);
1607                 /* Create OK button, the callback of which will execute op */
1608                 btn = uiDefBut(col_block, UI_BTYPE_BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1609                 UI_but_func_set(btn, dialog_exec_cb, data, col_block);
1610         }
1611
1612         /* center around the mouse */
1613         UI_block_bounds_set_popup(block, 4, data->width / -2, data->height / 2);
1614
1615         return block;
1616 }
1617
1618 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1619 {
1620         wmOpPopUp *data = userData;
1621         wmOperator *op = data->op;
1622         uiBlock *block;
1623         uiLayout *layout;
1624         uiStyle *style = UI_style_get();
1625
1626         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1627         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1628         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1629
1630         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1631
1632         /* since ui is defined the auto-layout args are not used */
1633         uiTemplateOperatorPropertyButs(C, layout, op, NULL, UI_BUT_LABEL_ALIGN_COLUMN, 0);
1634
1635         UI_block_func_set(block, NULL, NULL, NULL);
1636
1637         UI_block_bounds_set_popup(block, 4, 0, 0);
1638
1639         return block;
1640 }
1641
1642 static void wm_operator_ui_popup_cancel(struct bContext *C, void *userData)
1643 {
1644         wmOpPopUp *data = userData;
1645         wmOperator *op = data->op;
1646
1647         if (op) {
1648                 if (op->type->cancel) {
1649                         op->type->cancel(C, op);
1650                 }
1651
1652                 if (data->free_op) {
1653                         WM_operator_free(op);
1654                 }
1655         }
1656
1657         MEM_freeN(data);
1658 }
1659
1660 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1661 {
1662         wmOpPopUp *data = arg;
1663         wmOperator *op = data->op;
1664
1665         if (op && retval > 0)
1666                 WM_operator_call_ex(C, op, true);
1667         
1668         MEM_freeN(data);
1669 }
1670
1671 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1672 {
1673         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1674         data->op = op;
1675         data->width = width;
1676         data->height = height;
1677         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1678         UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data, op);
1679         return OPERATOR_RUNNING_MODAL;
1680 }
1681
1682 /**
1683  * For use by #WM_operator_props_popup_call, #WM_operator_props_popup only.
1684  *
1685  * \note operator menu needs undo flag enabled, for redo callback */
1686 static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
1687                                       const bool do_call, const bool do_redo)
1688 {
1689         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1690                 BKE_reportf(op->reports, RPT_ERROR,
1691                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1692                 return OPERATOR_CANCELLED;
1693         }
1694
1695         if (do_redo) {
1696                 if ((op->type->flag & OPTYPE_UNDO) == 0) {
1697                         BKE_reportf(op->reports, RPT_ERROR,
1698                                     "Operator '%s' does not have undo enabled, incorrect invoke function", op->type->idname);
1699                         return OPERATOR_CANCELLED;
1700                 }
1701         }
1702
1703         /* if we don't have global undo, we can't do undo push for automatic redo,
1704          * so we require manual OK clicking in this popup */
1705         if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
1706                 return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
1707
1708         UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op, op);
1709
1710         if (do_call)
1711                 wm_block_redo_cb(C, op, 0);
1712
1713         return OPERATOR_RUNNING_MODAL;
1714 }
1715
1716 /**
1717  * Same as #WM_operator_props_popup but don't use operator redo.
1718  * just wraps #WM_operator_props_dialog_popup.
1719  */
1720 int WM_operator_props_popup_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1721 {
1722         return wm_operator_props_popup_ex(C, op, false, false);
1723 }
1724
1725 /**
1726  * Same as #WM_operator_props_popup but call the operator first,
1727  * This way - the button values correspond to the result of the operator.
1728  * Without this, first access to a button will make the result jump, see T32452.
1729  */
1730 int WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1731 {
1732         return wm_operator_props_popup_ex(C, op, true, true);
1733 }
1734
1735 int WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1736 {
1737         return wm_operator_props_popup_ex(C, op, false, true);
1738 }
1739
1740 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1741 {
1742         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1743         
1744         data->op = op;
1745         data->width = width;
1746         data->height = height;
1747         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1748
1749         /* op is not executed until popup OK but is clicked */
1750         UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data, op);
1751
1752         return OPERATOR_RUNNING_MODAL;
1753 }
1754
1755 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1756 {
1757         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1758         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1759                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1760                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1761                 return OPERATOR_CANCELLED;
1762         }
1763         if (op->type->poll && op->type->poll(C) == 0) {
1764                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1765                 return OPERATOR_CANCELLED;
1766         }
1767         
1768         UI_popup_block_invoke(C, wm_block_create_redo, op);
1769
1770         return OPERATOR_CANCELLED;
1771 }
1772
1773 /* ***************** Debug menu ************************* */
1774
1775 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1776 {
1777         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1778         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1779         WM_event_add_notifier(C, NC_WINDOW, NULL);
1780
1781         return OPERATOR_FINISHED;
1782 }
1783
1784 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1785 {
1786         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1787         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1788 }
1789
1790 static void WM_OT_debug_menu(wmOperatorType *ot)
1791 {
1792         ot->name = "Debug Menu";
1793         ot->idname = "WM_OT_debug_menu";
1794         ot->description = "Open a popup to set the debug level";
1795         
1796         ot->invoke = wm_debug_menu_invoke;
1797         ot->exec = wm_debug_menu_exec;
1798         ot->poll = WM_operator_winactive;
1799         
1800         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1801 }
1802
1803 /* ***************** Operator defaults ************************* */
1804 static int wm_operator_defaults_exec(bContext *C, wmOperator *op)
1805 {
1806         PointerRNA ptr = CTX_data_pointer_get_type(C, "active_operator", &RNA_Operator);
1807
1808         if (!ptr.data) {
1809                 BKE_report(op->reports, RPT_ERROR, "No operator in context");
1810                 return OPERATOR_CANCELLED;
1811         }
1812
1813         WM_operator_properties_reset((wmOperator *)ptr.data);
1814         return OPERATOR_FINISHED;
1815 }
1816
1817 /* used by operator preset menu. pre-2.65 this was a 'Reset' button */
1818 static void WM_OT_operator_defaults(wmOperatorType *ot)
1819 {
1820         ot->name = "Restore Defaults";
1821         ot->idname = "WM_OT_operator_defaults";
1822         ot->description = "Set the active operator to its default values";
1823
1824         ot->exec = wm_operator_defaults_exec;
1825
1826         ot->flag = OPTYPE_INTERNAL;
1827 }
1828
1829 /* ***************** Splash Screen ************************* */
1830
1831 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1832 {
1833         wmWindow *win = CTX_wm_window(C);
1834         UI_popup_block_close(C, win, arg_block);
1835 }
1836
1837 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1838
1839 static void wm_block_splash_refreshmenu(bContext *C, void *UNUSED(arg_block), void *UNUSED(arg))
1840 {
1841         ARegion *ar_menu = CTX_wm_menu(C);
1842         ED_region_tag_refresh_ui(ar_menu);
1843 }
1844
1845 static int wm_resource_check_prev(void)
1846 {
1847
1848         const char *res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, true);
1849
1850         // if (res) printf("USER: %s\n", res);
1851
1852 #if 0 /* ignore the local folder */
1853         if (res == NULL) {
1854                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1855                 res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, true);
1856         }
1857 #endif
1858
1859         // if (res) printf("LOCAL: %s\n", res);
1860         if (res) {
1861                 return false;
1862         }
1863         else {
1864                 return (BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, true) != NULL);
1865         }
1866 }
1867
1868 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1869 {
1870         uiBlock *block;
1871         uiBut *but;
1872         uiLayout *layout, *split, *col;
1873         uiStyle *style = UI_style_get();
1874         const struct RecentFile *recent;
1875         int i;
1876         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", true);
1877         char url[96];
1878         const char *version_suffix = NULL;
1879
1880 #ifndef WITH_HEADLESS
1881         extern char datatoc_splash_png[];
1882         extern int datatoc_splash_png_size;
1883
1884         extern char datatoc_splash_2x_png[];
1885         extern int datatoc_splash_2x_png_size;
1886         ImBuf *ibuf;
1887 #else
1888         ImBuf *ibuf = NULL;
1889 #endif
1890
1891 #ifdef WITH_BUILDINFO
1892         int label_delta = 0;
1893         int hash_width, date_width;
1894         char date_buf[128] = "\0";
1895         char hash_buf[128] = "\0";
1896         extern unsigned long build_commit_timestamp;
1897         extern char build_hash[], build_commit_date[], build_commit_time[], build_branch[];
1898
1899         /* Builds made from tag only shows tag sha */
1900         BLI_snprintf(hash_buf, sizeof(hash_buf), "Hash: %s", build_hash);
1901         BLI_snprintf(date_buf, sizeof(date_buf), "Date: %s %s", build_commit_date, build_commit_time);
1902         
1903         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.pixelsize * U.dpi);
1904         hash_width = (int)BLF_width(style->widgetlabel.uifont_id, hash_buf, sizeof(hash_buf)) + U.widget_unit;
1905         date_width = (int)BLF_width(style->widgetlabel.uifont_id, date_buf, sizeof(date_buf)) + U.widget_unit;
1906 #endif  /* WITH_BUILDINFO */
1907
1908 #ifndef WITH_HEADLESS
1909         if (U.pixelsize == 2) {
1910                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_2x_png,
1911                                              datatoc_splash_2x_png_size, IB_rect, NULL, "<splash screen>");
1912         }
1913         else {
1914                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1915                                              datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1916         }
1917
1918         /* overwrite splash with template image */
1919         if (U.app_template[0] != '\0') {
1920                 ImBuf *ibuf_template = NULL;
1921                 char splash_filepath[FILE_MAX];
1922                 char template_directory[FILE_MAX];
1923
1924                 if (BKE_appdir_app_template_id_search(
1925                         U.app_template,
1926                         template_directory, sizeof(template_directory)))
1927                 {
1928                         BLI_join_dirfile(
1929                                 splash_filepath, sizeof(splash_filepath), template_directory,
1930                                 (U.pixelsize == 2) ? "splash_2x.png" : "splash.png");
1931                         ibuf_template = IMB_loadiffname(splash_filepath, IB_rect, NULL);
1932                         if (ibuf_template) {
1933                                 const int x_expect = ibuf->x;
1934                                 const int y_expect = 282 * (int)U.pixelsize;
1935                                 /* don't cover the header text */
1936                                 if (ibuf_template->x == x_expect && ibuf_template->y == y_expect) {
1937                                         memcpy(ibuf->rect, ibuf_template->rect, ibuf_template->x * ibuf_template->y * sizeof(char[4]));
1938                                 }
1939                                 else {
1940                                         CLOG_ERROR(WM_LOG_OPERATORS,
1941                                                    "Splash expected %dx%d found %dx%d, ignoring: %s\n",
1942                                                    x_expect, y_expect, ibuf_template->x, ibuf_template->y, splash_filepath);
1943                                 }
1944                                 IMB_freeImBuf(ibuf_template);
1945                         }
1946                 }
1947         }
1948 #endif
1949
1950         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1951
1952         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1953          * with the OS when the splash shows, window clipping in this case gives
1954          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1955         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1956
1957         /* XXX splash scales with pixelsize, should become widget-units */
1958         but = uiDefBut(block, UI_BTYPE_IMAGE, 0, "", 0, 0.5f * U.widget_unit, U.pixelsize * 501, U.pixelsize * 282, ibuf, 0.0, 0.0, 0, 0, ""); /* button owns the imbuf now */
1959         UI_but_func_set(but, wm_block_splash_close, block, NULL);
1960         UI_block_func_set(block, wm_block_splash_refreshmenu, block, NULL);
1961
1962         /* label for 'a' bugfix releases, or 'Release Candidate 1'...
1963          *  avoids recreating splash for version updates */
1964         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "rc")) {
1965                 version_suffix = "Release Candidate";
1966         }
1967         else if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1968                 version_suffix = STRINGIFY(BLENDER_VERSION_CHAR);
1969         }
1970         if (version_suffix != NULL && version_suffix[0]) {
1971                 /* placed after the version number in the image,
1972                  * placing y is tricky to match baseline */
1973                 int x = 236 * U.pixelsize - (2 * UI_DPI_FAC);
1974                 int y = 231 * U.pixelsize + (4 * UI_DPI_FAC);
1975                 int w = 240 * U.pixelsize;
1976
1977                 /* hack to have text draw 'text_sel' */
1978                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1979                 but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x, y, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1980                 /* XXX, set internal flag - UI_SELECT */
1981                 UI_but_flag_enable(but, 1);
1982                 UI_block_emboss_set(block, UI_EMBOSS);
1983         }
1984
1985 #ifdef WITH_BUILDINFO
1986         if (build_commit_timestamp != 0) {
1987                 but = uiDefBut(
1988                           block, UI_BTYPE_LABEL, 0, date_buf,
1989                           U.pixelsize * 502 - date_width, U.pixelsize * 267,
1990                           date_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1991                 /* XXX, set internal flag - UI_SELECT */
1992                 UI_but_flag_enable(but, 1);
1993                 label_delta = 12;
1994         }
1995         but = uiDefBut(
1996                   block, UI_BTYPE_LABEL, 0, hash_buf,
1997                   U.pixelsize * 502 - hash_width, U.pixelsize * (267 - label_delta),
1998                   hash_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1999         /* XXX, set internal flag - UI_SELECT */
2000         UI_but_flag_enable(but, 1);
2001
2002         if (!STREQ(build_branch, "master")) {
2003                 char branch_buf[128] = "\0";
2004                 int branch_width;
2005                 BLI_snprintf(branch_buf, sizeof(branch_buf), "Branch: %s", build_branch);
2006                 branch_width = (int)BLF_width(style->widgetlabel.uifont_id, branch_buf, sizeof(branch_buf)) + U.widget_unit;
2007                 but = uiDefBut(
2008                           block, UI_BTYPE_LABEL, 0, branch_buf,
2009                           U.pixelsize * 502 - branch_width, U.pixelsize * (255 - label_delta),
2010                           branch_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
2011                 /* XXX, set internal flag - UI_SELECT */
2012                 UI_but_flag_enable(but, 1);
2013         }
2014 #endif  /* WITH_BUILDINFO */
2015         
2016         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.pixelsize * 480, U.pixelsize * 110, 0, style);
2017         
2018         UI_block_emboss_set(block, UI_EMBOSS);
2019         /* show the splash menu (containing interaction presets), using python */
2020         if (mt) {
2021                 UI_menutype_draw(C, mt, layout);
2022
2023 //              wmWindowManager *wm = CTX_wm_manager(C);
2024 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
2025         }
2026         
2027         UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN);
2028         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
2029         
2030         split = uiLayoutSplit(layout, 0.0f, false);
2031         col = uiLayoutColumn(split, false);
2032         uiItemL(col, IFACE_("Links"), ICON_NONE);
2033 #if 0
2034         uiItemStringO(col, IFACE_("Support an Open Animation Movie"), ICON_URL, "WM_OT_url_open", "url",
2035                       "https://cloud.blender.org/join");
2036 #endif
2037         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url",
2038                       "http://www.blender.org/foundation/donation-payment/");
2039         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url",
2040                       "http://www.blender.org/about/credits/");
2041         BLI_snprintf(url, sizeof(url), "http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/%d.%d",
2042                      BLENDER_VERSION / 100, BLENDER_VERSION % 100);
2043         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", url);
2044         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url",
2045                       "https://docs.blender.org/manual/en/dev/");
2046         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
2047         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
2048                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/%d.%d"STRINGIFY(BLENDER_VERSION_CHAR),
2049                              BLENDER_VERSION / 100, BLENDER_VERSION % 100);
2050         }
2051         else {
2052                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/master");
2053         }
2054         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
2055         uiItemL(col, "", ICON_NONE);
2056
2057         col = uiLayoutColumn(split, false);
2058
2059         if (wm_resource_check_prev()) {
2060                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
2061                 uiItemS(col);
2062         }
2063
2064         uiItemL(col, IFACE_("Recent"), ICON_NONE);
2065         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
2066                 const char *filename = BLI_path_basename(recent->filepath);
2067                 uiItemStringO(col, filename,
2068                               BLO_has_bfile_extension(filename) ? ICON_FILE_BLEND : ICON_FILE_BACKUP,
2069                               "WM_OT_open_mainfile", "filepath", recent->filepath);
2070         }
2071
2072         uiItemS(col);
2073         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
2074         uiItemL(col, "", ICON_NONE);
2075         
2076         mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
2077         if (mt) {
2078                 UI_menutype_draw(C, mt, uiLayoutColumn(layout, false));
2079         }
2080
2081         UI_block_bounds_set_centered(block, 0);
2082         
2083         return block;
2084 }
2085
2086 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2087 {
2088         UI_popup_block_invoke(C, wm_block_create_splash, NULL);
2089         
2090         return OPERATOR_FINISHED;
2091 }
2092
2093 static void WM_OT_splash(wmOperatorType *ot)
2094 {
2095         ot->name = "Splash Screen";
2096         ot->idname = "WM_OT_splash";
2097         ot->description = "Open the splash screen with release info";
2098         
2099         ot->invoke = wm_splash_invoke;
2100         ot->poll = WM_operator_winactive;
2101 }
2102
2103
2104 /* ***************** Search menu ************************* */
2105
2106 struct SearchPopupInit_Data {
2107         int size[2];
2108 };
2109
2110 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *userdata)
2111 {
2112         const struct SearchPopupInit_Data *init_data = userdata;
2113         static char search[256] = "";
2114         wmEvent event;
2115         wmWindow *win = CTX_wm_window(C);
2116         uiBlock *block;
2117         uiBut *but;
2118         
2119         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
2120         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
2121         
2122         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, init_data->size[0], UI_UNIT_Y, 0, 0, "");
2123         UI_but_func_operator_search(but);
2124         
2125         /* fake button, it holds space for search items */
2126         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - init_data->size[1],
2127                  init_data->size[0], init_data->size[1], NULL, 0, 0, 0, 0, NULL);
2128         
2129         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
2130         
2131         wm_event_init_from_window(win, &event);
2132         event.type = EVT_BUT_OPEN;
2133         event.val = KM_PRESS;
2134         event.customdata = but;
2135         event.customdatafree = false;
2136         wm_event_add(win, &event);
2137         
2138         return block;
2139 }
2140
2141 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2142 {
2143         return OPERATOR_FINISHED;
2144 }
2145
2146 static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2147 {
2148         struct SearchPopupInit_Data data = {
2149                 .size = {
2150                     UI_searchbox_size_x() * 2,
2151                     UI_searchbox_size_y(),
2152                 },
2153         };
2154
2155         UI_popup_block_invoke(C, wm_block_search_menu, &data);
2156         
2157         return OPERATOR_INTERFACE;
2158 }
2159
2160 /* op->poll */
2161 static int wm_search_menu_poll(bContext *C)
2162 {
2163         if (CTX_wm_window(C) == NULL) {
2164                 return 0;
2165         }
2166         else {
2167                 ScrArea *sa = CTX_wm_area(C);
2168                 if (sa) {
2169                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
2170                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
2171                 }
2172                 else {
2173                         Object *editob = CTX_data_edit_object(C);
2174                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
2175                 }
2176         }
2177         return 1;
2178 }
2179
2180 static void WM_OT_search_menu(wmOperatorType *ot)
2181 {
2182         ot->name = "Search Menu";
2183         ot->idname = "WM_OT_search_menu";
2184         ot->description = "Pop-up a search menu over all available operators in current context";
2185         
2186         ot->invoke = wm_search_menu_invoke;
2187         ot->exec = wm_search_menu_exec;
2188         ot->poll = wm_search_menu_poll;
2189 }
2190
2191 static int wm_call_menu_exec(bContext *C, wmOperator *op)
2192 {
2193         char idname[BKE_ST_MAXNAME];
2194         RNA_string_get(op->ptr, "name", idname);
2195
2196         return UI_popup_menu_invoke(C, idname, op->reports);
2197 }
2198
2199 static void WM_OT_call_menu(wmOperatorType *ot)
2200 {
2201         ot->name = "Call Menu";
2202         ot->idname = "WM_OT_call_menu";
2203         ot->description = "Call (draw) a pre-defined menu";
2204
2205         ot->exec = wm_call_menu_exec;
2206         ot->poll = WM_operator_winactive;
2207
2208         ot->flag = OPTYPE_INTERNAL;
2209
2210         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
2211 }
2212
2213 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2214 {
2215         char idname[BKE_ST_MAXNAME];
2216         RNA_string_get(op->ptr, "name", idname);
2217
2218         return UI_pie_menu_invoke(C, idname, event);
2219 }
2220
2221 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
2222 {
2223         char idname[BKE_ST_MAXNAME];
2224         RNA_string_get(op->ptr, "name", idname);
2225
2226         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
2227 }
2228
2229 static void WM_OT_call_menu_pie(wmOperatorType *ot)
2230 {
2231         ot->name = "Call Pie Menu";
2232         ot->idname = "WM_OT_call_menu_pie";
2233         ot->description = "Call (draw) a pre-defined pie menu";
2234
2235         ot->invoke = wm_call_pie_menu_invoke;
2236         ot->exec = wm_call_pie_menu_exec;
2237         ot->poll = WM_operator_winactive;
2238
2239         ot->flag = OPTYPE_INTERNAL;
2240
2241         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
2242 }
2243
2244 /* ************ window / screen operator definitions ************** */
2245
2246 /* this poll functions is needed in place of WM_operator_winactive
2247  * while it crashes on full screen */
2248 static int wm_operator_winactive_normal(bContext *C)
2249 {
2250         wmWindow *win = CTX_wm_window(C);
2251         bScreen *screen;
2252
2253         if (win == NULL)
2254                 return 0;
2255         if (!((screen = WM_window_get_active_screen(win)) && (screen->state == SCREENNORMAL)))
2256                 return 0;
2257
2258         return 1;
2259 }
2260
2261 /* included for script-access */
2262 static void WM_OT_window_close(wmOperatorType *ot)
2263 {
2264         ot->name = "Close Window";
2265         ot->idname = "WM_OT_window_close";
2266         ot->description = "Close the current Blender window";
2267
2268         ot->exec = wm_window_close_exec;
2269         ot->poll = WM_operator_winactive;
2270 }
2271
2272 static void WM_OT_window_new(wmOperatorType *ot)
2273 {
2274         PropertyRNA *prop;
2275
2276         ot->name = "New Window";
2277         ot->idname = "WM_OT_window_new";
2278         ot->description = "Create a new Blender window";
2279
2280         ot->exec = wm_window_new_exec;
2281         ot->invoke = wm_window_new_invoke;
2282         ot->poll = wm_operator_winactive_normal;
2283
2284         prop = RNA_def_enum(ot->srna, "screen", DummyRNA_NULL_items, 0, "Screen", "");
2285         RNA_def_enum_funcs(prop, wm_window_new_screen_itemf);
2286         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
2287         ot->prop = prop;
2288 }
2289
2290 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2291 {
2292         ot->name = "Toggle Window Fullscreen";
2293         ot->idname = "WM_OT_window_fullscreen_toggle";
2294         ot->description = "Toggle the current window fullscreen";
2295
2296         ot->exec = wm_window_fullscreen_toggle_exec;
2297         ot->poll = WM_operator_winactive;
2298 }
2299
2300 static int wm_exit_blender_exec(bContext *C, wmOperator *UNUSED(op))
2301 {
2302         wm_quit_with_optional_confirmation_prompt(C, CTX_wm_window(C));
2303         return OPERATOR_FINISHED;
2304 }
2305
2306 static int wm_exit_blender_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2307 {
2308         if (U.uiflag & USER_QUIT_PROMPT) {
2309                 return wm_exit_blender_exec(C, op);
2310         }
2311         else {
2312                 return WM_operator_confirm(C, op, event);
2313         }
2314 }
2315
2316 static void WM_OT_quit_blender(wmOperatorType *ot)
2317 {
2318         ot->name = "Quit Blender";
2319         ot->idname = "WM_OT_quit_blender";
2320         ot->description = "Quit Blender";
2321
2322         ot->invoke = wm_exit_blender_invoke;
2323         ot->exec = wm_exit_blender_exec;
2324 }
2325
2326 /* *********************** */
2327
2328 #if defined(WIN32)
2329
2330 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2331 {
2332         GHOST_toggleConsole(2);
2333         return OPERATOR_FINISHED;
2334 }
2335
2336 static void WM_OT_console_toggle(wmOperatorType *ot)
2337 {
2338         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
2339         ot->name = CTX_N_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
2340         ot->idname = "WM_OT_console_toggle";
2341         ot->description = N_("Toggle System Console");
2342         
2343         ot->exec = wm_console_toggle_exec;
2344         ot->poll = WM_operator_winactive;
2345 }
2346
2347 #endif
2348
2349 /* ************ default paint cursors, draw always around cursor *********** */
2350 /*
2351  * - returns handler to free
2352  * - poll(bContext): returns 1 if draw should happen
2353  * - draw(bContext): drawing callback for paint cursor
2354  */
2355
2356 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2357                                wmPaintCursorDraw draw, void *customdata)
2358 {
2359         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2360         
2361         BLI_addtail(&wm->paintcursors, pc);
2362         
2363         pc->customdata = customdata;
2364         pc->poll = poll;
2365         pc->draw = draw;
2366         
2367         return pc;
2368 }
2369
2370 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2371 {
2372         wmPaintCursor *pc;
2373         
2374         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
2375                 if (pc == (wmPaintCursor *)handle) {
2376                         BLI_remlink(&wm->paintcursors, pc);
2377                         MEM_freeN(pc);
2378                         return;
2379                 }
2380         }
2381 }
2382
2383 /* *********************** radial control ****************** */
2384
2385 #define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
2386 #define WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE (35 * UI_DPI_FAC)
2387 #define WM_RADIAL_CONTROL_DISPLAY_WIDTH (WM_RADIAL_CONTROL_DISPLAY_SIZE - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE)
2388 #define WM_RADIAL_MAX_STR 10
2389
2390 typedef struct {
2391         PropertyType type;
2392         PropertySubType subtype;
2393         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2394         PointerRNA fill_col_override_ptr, fill_col_override_test_ptr;
2395         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2396         PropertyRNA *fill_col_override_prop, *fill_col_override_test_prop;
2397         StructRNA *image_id_srna;
2398         float initial_value, current_value, min_value, max_value;
2399         int initial_mouse[2];
2400         int slow_mouse[2];
2401         bool slow_mode;
2402         Dial *dial;
2403         unsigned int gltex;
2404         ListBase orig_paintcursors;
2405         bool use_secondary_tex;
2406         void *cursor;
2407         NumInput num_input;
2408 } RadialControl;
2409
2410 static void radial_control_update_header(wmOperator *op, bContext *C)
2411 {
2412         RadialControl *rc = op->customdata;
2413         char msg[UI_MAX_DRAW_STR];
2414         ScrArea *sa = CTX_wm_area(C);
2415         Scene *scene = CTX_data_scene(C);
2416         
2417         if (sa) {
2418                 if (hasNumInput(&rc->num_input)) {
2419                         char num_str[NUM_STR_REP_LEN];
2420                         outputNumInput(&rc->num_input, num_str, &scene->unit);
2421                         BLI_snprintf(msg, sizeof(msg), "%s: %s", RNA_property_ui_name(rc->prop), num_str);
2422                 }
2423                 else {
2424                         const char *ui_name = RNA_property_ui_name(rc->prop);
2425                         switch (rc->subtype) {
2426                                 case PROP_NONE:
2427                                 case PROP_DISTANCE:
2428                                         BLI_snprintf(msg, sizeof(msg), "%s: %0.4f", ui_name, rc->current_value);
2429                                         break;
2430                                 case PROP_PIXEL:
2431                                         BLI_snprintf(msg, sizeof(msg), "%s: %d", ui_name, (int)rc->current_value); /* XXX: round to nearest? */
2432                                         break;
2433                                 case PROP_PERCENTAGE:
2434                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.1f%%", ui_name, rc->current_value);
2435                                         break;
2436                                 case PROP_FACTOR:
2437                                         BLI_snprintf(msg, sizeof(msg), "%s: %1.3f", ui_name, rc->current_value);
2438                                         break;
2439                                 case PROP_ANGLE:
2440                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.2f", ui_name, RAD2DEGF(rc->current_value));
2441                                         break;
2442                                 default:
2443                                         BLI_snprintf(msg, sizeof(msg), "%s", ui_name); /* XXX: No value? */
2444                                         break;
2445                         }
2446                 }
2447                 ED_area_headerprint(sa, msg);
2448         }
2449 }
2450
2451 static void radial_control_set_initial_mouse(RadialControl *rc, const wmEvent *event)
2452 {
2453         float d[2] = {0, 0};
2454         float zoom[2] = {1, 1};
2455
2456         rc->initial_mouse[0] = event->x;
2457         rc->initial_mouse[1] = event->y;
2458
2459         switch (rc->subtype) {
2460                 case PROP_NONE:
2461                 case PROP_DISTANCE:
2462                 case PROP_PIXEL:
2463                         d[0] = rc->initial_value;
2464                         break;
2465                 case PROP_PERCENTAGE:
2466                         d[0] = (rc->initial_value) / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2467                         break;
2468                 case PROP_FACTOR:
2469                         d[0] = (1 - rc->initial_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2470                         break;
2471                 case PROP_ANGLE:
2472                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cosf(rc->initial_value);
2473                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sinf(rc->initial_value);
2474                         break;
2475                 default:
2476                         return;
2477         }
2478
2479         if (rc->zoom_prop) {
2480                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2481                 d[0] *= zoom[0];
2482                 d[1] *= zoom[1];
2483         }
2484
2485         rc->initial_mouse[0] -= d[0];
2486         rc->initial_mouse[1] -= d[1];
2487 }
2488
2489 static void radial_control_set_tex(RadialControl *rc)
2490 {
2491         ImBuf *ibuf;
2492
2493         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
2494                 case ID_BR:
2495                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data, rc->use_secondary_tex))) {
2496                                 glGenTextures(1, &rc->gltex);
2497                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2498                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, ibuf->x, ibuf->y, 0,
2499                                              GL_RED, GL_FLOAT, ibuf->rect_float);
2500                                 glBindTexture(GL_TEXTURE_2D, 0);
2501                                 MEM_freeN(ibuf->rect_float);
2502                                 MEM_freeN(ibuf);
2503                         }
2504                         break;
2505                 default:
2506                         break;
2507         }
2508 }
2509
2510 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
2511 {
2512         float col[3] = {0, 0, 0};
2513         float rot;
2514
2515         /* set fill color */
2516         if (rc->fill_col_prop) {
2517                 PointerRNA *fill_ptr;
2518                 PropertyRNA *fill_prop;
2519
2520                 if (rc->fill_col_override_prop &&
2521                     RNA_property_boolean_get(&rc->fill_col_override_test_ptr, rc->fill_col_override_test_prop))
2522                 {
2523                         fill_ptr = &rc->fill_col_override_ptr;
2524                         fill_prop = rc->fill_col_override_prop;
2525                 }
2526                 else {
2527                         fill_ptr = &rc->fill_col_ptr;
2528                         fill_prop = rc->fill_col_prop;
2529                 }
2530
2531                 RNA_property_float_get_array(fill_ptr, fill_prop, col);
2532         }
2533                 
2534         Gwn_VertFormat *format = immVertexFormat();
2535         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2536
2537         if (rc->gltex) {
2538
2539                 unsigned int texCoord = GWN_vertformat_attr_add(format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2540
2541                 glActiveTexture(GL_TEXTURE0);
2542                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2543
2544                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2545                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2546
2547                 GLint swizzleMask[] = {GL_ZERO, GL_ZERO, GL_ZERO, GL_RED};
2548                 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);
2549
2550                 immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_MASK_UNIFORM_COLOR);
2551
2552                 immUniformColor3fvAlpha(col, alpha);
2553                 immUniform1i("image", 0);
2554
2555                 /* set up rotation if available */
2556                 if (rc->rot_prop) {
2557                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2558                         gpuPushMatrix();
2559                         gpuRotate2D(RAD2DEGF(rot));
2560                 }
2561
2562                 /* draw textured quad */
2563                 immBegin(GWN_PRIM_TRI_FAN, 4);
2564
2565                 immAttrib2f(texCoord, 0, 0);
2566                 immVertex2f(pos, -radius, -radius);
2567
2568                 immAttrib2f(texCoord, 1, 0);
2569                 immVertex2f(pos, radius, -radius);
2570                 
2571                 immAttrib2f(texCoord, 1, 1);
2572                 immVertex2f(pos, radius, radius);
2573                 
2574                 immAttrib2f(texCoord, 0, 1);
2575                 immVertex2f(pos, -radius, radius);
2576
2577                 immEnd();
2578
2579                 /* undo rotation */
2580                 if (rc->rot_prop)
2581                         gpuPopMatrix();
2582         }
2583         else {
2584                 /* flat color if no texture available */
2585                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2586                 immUniformColor3fvAlpha(col, alpha);
2587                 imm_draw_circle_fill_2d(pos, 0.0f, 0.0f, radius, 40);
2588         }
2589         
2590         immUnbindProgram();
2591 }
2592
2593 static void radial_control_paint_cursor(bContext *UNUSED(C), int x, int y, void *customdata)
2594 {
2595         RadialControl *rc = customdata;
2596         uiStyle *style = UI_style_get();
2597         const uiFontStyle *fstyle = &style->widget;
2598         const int fontid = fstyle->uifont_id;
2599         short fstyle_points = fstyle->points;
2600         char str[WM_RADIAL_MAX_STR];
2601         short strdrawlen = 0;
2602         float strwidth, strheight;
2603         float r1 = 0.0f, r2 = 0.0f, rmin = 0.0, tex_radius, alpha;
2604         float zoom[2], col[3] = {1, 1, 1};      
2605
2606         switch (rc->subtype) {
2607                 case PROP_NONE:
2608                 case PROP_DISTANCE:
2609                 case PROP_PIXEL:
2610                         r1 = rc->current_value;
2611                         r2 = rc->initial_value;
2612                         tex_radius = r1;
2613                         alpha = 0.75;
2614                         break;
2615                 case PROP_PERCENTAGE:
2616                         r1 = rc->current_value / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2617                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2618                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2619                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.1f%%", rc->current_value);
2620                         strdrawlen = BLI_strlen_utf8(str);
2621                         tex_radius = r1;
2622                         alpha = 0.75;
2623                         break;
2624                 case PROP_FACTOR:
2625                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2626                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2627                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2628                         alpha = rc->current_value / 2.0f + 0.5f;
2629                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%1.3f", rc->current_value);
2630                         strdrawlen = BLI_strlen_utf8(str);
2631                         break;
2632                 case PROP_ANGLE:
2633                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2634                         alpha = 0.75;
2635                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2636                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.2f", RAD2DEGF(rc->current_value));
2637                         strdrawlen = BLI_strlen_utf8(str);
2638                         break;
2639                 default:
2640                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
2641                         alpha = 0.75;
2642                         break;
2643         }
2644
2645         /* Keep cursor in the original place */
2646         x = rc->initial_mouse[0];
2647         y = rc->initial_mouse[1];
2648         gpuTranslate2f((float)x, (float)y);
2649
2650         glEnable(GL_BLEND);
2651         glEnable(GL_LINE_SMOOTH);
2652
2653         /* apply zoom if available */
2654         if (rc->zoom_prop) {
2655                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2656                 gpuScale2fv(zoom);
2657         }
2658
2659         /* draw rotated texture */
2660         radial_control_paint_tex(rc, tex_radius, alpha);
2661
2662         /* set line color */
2663         if (rc->col_prop)
2664                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
2665
2666         Gwn_VertFormat *format = immVertexFormat();
2667         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2668
2669         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2670         immUniformColor3fvAlpha(col, 0.5f);
2671
2672         if (rc->subtype == PROP_ANGLE) {
2673                 gpuPushMatrix();
2674
2675                 /* draw original angle line */
2676                 gpuRotate2D(RAD2DEGF(rc->initial_value));
2677                 immBegin(GWN_PRIM_LINES, 2);
2678                 immVertex2f(pos, (float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f);
2679                 immVertex2f(pos, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2680                 immEnd();
2681
2682                 /* draw new angle line */
2683                 gpuRotate2D(RAD2DEGF(rc->current_value - rc->initial_value));
2684                 immBegin(GWN_PRIM_LINES, 2);
2685                 immVertex2f(pos, (float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f);
2686                 immVertex2f(pos, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2687                 immEnd();
2688
2689                 gpuPopMatrix();
2690         }
2691
2692         /* draw circles on top */
2693         imm_draw_circle_wire_2d(pos, 0.0f, 0.0f, r1, 40);
2694         imm_draw_circle_wire_2d(pos, 0.0f, 0.0f, r2, 40);
2695         if (rmin > 0.0f)
2696                 imm_draw_circle_wire_2d(pos, 0.0, 0.0f, rmin, 40);
2697         immUnbindProgram();
2698
2699         BLF_size(fontid, 1.5 * fstyle_points * U.pixelsize, U.dpi);
2700         BLF_enable(fontid, BLF_SHADOW);
2701         BLF_shadow(fontid, 3, (const float[4]){0.0f, 0.0f, 0.0f, 0.5f});
2702         BLF_shadow_offset(fontid, 1, -1);
2703
2704         /* draw value */
2705         BLF_width_and_height(fontid, str, strdrawlen, &strwidth, &strheight);
2706         BLF_position(fontid, -0.5f * strwidth, -0.5f * strheight, 0.0f);
2707         BLF_draw(fontid, str, strdrawlen);
2708
2709         BLF_disable(fontid, BLF_SHADOW);
2710
2711         glDisable(GL_BLEND);
2712         glDisable(GL_LINE_SMOOTH);
2713
2714 }
2715
2716 typedef enum {
2717         RC_PROP_ALLOW_MISSING = 1,
2718         RC_PROP_REQUIRE_FLOAT = 2,
2719         RC_PROP_REQUIRE_BOOL = 4,
2720 } RCPropFlags;
2721
2722 /**
2723  * Attempt to retrieve the rna pointer/property from an rna path.
2724  *
2725  * \return 0 for failure, 1 for success, and also 1 if property is not set.
2726  */
2727 static int radial_control_get_path(
2728         PointerRNA *ctx_ptr, wmOperator *op,
2729         const char *name, PointerRNA *r_ptr,
2730         PropertyRNA **r_prop, int req_length, RCPropFlags flags)
2731 {
2732         PropertyRNA *unused_prop;
2733         int len;
2734         char *str;
2735
2736         /* check flags */
2737         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
2738                 BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
2739                 return 0;
2740         }
2741
2742         /* get an rna string path from the operator's properties */
2743         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
2744                 return 1;
2745
2746         if (str[0] == '\0') {
2747                 if (r_prop) *r_prop = NULL;
2748                 MEM_freeN(str);
2749                 return 1;
2750         }
2751
2752         if (!r_prop)
2753                 r_prop = &unused_prop;
2754
2755         /* get rna from path */
2756         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
2757                 MEM_freeN(str);
2758                 if (flags & RC_PROP_ALLOW_MISSING)
2759                         return 1;
2760                 else {
2761                         BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
2762                         return 0;
2763                 }
2764         }
2765
2766         /* check property type */
2767         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
2768                 PropertyType prop_type = RNA_property_type(*r_prop);
2769
2770                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
2771                     ((flags & RC_PROP_REQUIRE_FLOAT) && (prop_type != PROP_FLOAT)))
2772                 {
2773                         MEM_freeN(str);
2774                         BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
2775                         return 0;
2776                 }
2777         }
2778         
2779         /* check property's array length */
2780         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
2781                 MEM_freeN(str);
2782                 BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
2783                             name, len, req_length);
2784                 return 0;
2785         }
2786
2787         /* success */
2788         MEM_freeN(str);
2789         return 1;
2790 }
2791
2792 /* initialize the rna pointers and properties using rna paths */
2793 static int radial_control_get_properties(bContext *C, wmOperator *op)
2794 {
2795         RadialControl *rc = op->customdata;
2796         PointerRNA ctx_ptr, use_secondary_ptr;
2797         PropertyRNA *use_secondary_prop = NULL;
2798         const char *data_path;
2799
2800         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
2801
2802         /* check if we use primary or secondary path */
2803         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
2804                                      &use_secondary_ptr, &use_secondary_prop,
2805                                      0, (RC_PROP_ALLOW_MISSING |
2806                                          RC_PROP_REQUIRE_BOOL)))
2807         {
2808                 return 0;
2809         }
2810         else {
2811                 if (use_secondary_prop &&
2812                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
2813                 {
2814                         data_path = "data_path_secondary";
2815                 }
2816                 else {
2817                         data_path = "data_path_primary";
2818                 }
2819         }
2820
2821         if (!radial_control_get_path(&ctx_ptr, op, data_path, &rc->ptr, &rc->prop, 0, 0))
2822                 return 0;
2823
2824         /* data path is required */
2825         if (!rc->prop)
2826                 return 0;
2827         
2828         if (!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 0, RC_PROP_REQUIRE_FLOAT))
2829                 return 0;
2830         if (!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2831                 return 0;
2832
2833
2834         if (!radial_control_get_path(
2835                 &ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2836         {
2837                 return 0;
2838         }
2839
2840         if (!radial_control_get_path(
2841                 &ctx_ptr, op, "fill_color_override_path",
2842                 &rc->fill_col_override_ptr, &rc->fill_col_override_prop, 3, RC_PROP_REQUIRE_FLOAT))
2843         {
2844                 return 0;
2845         }
2846         if (!radial_control_get_path(
2847                 &ctx_ptr, op, "fill_color_override_test_path",
2848                 &rc->fill_col_override_test_ptr, &rc->fill_col_override_test_prop, 0, RC_PROP_REQUIRE_BOOL))
2849         {
2850                 return 0;
2851         }
2852
2853         /* slightly ugly; allow this property to not resolve
2854          * correctly. needed because 3d texture paint shares the same
2855          * keymap as 2d image paint */
2856         if (!radial_control_get_path(&ctx_ptr, op, "zoom_path",
2857                                      &rc->zoom_ptr, &rc->zoom_prop, 2,
2858                                      RC_PROP_REQUIRE_FLOAT | RC_PROP_ALLOW_MISSING))
2859         {
2860                 return 0;
2861         }
2862         
2863         if (!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0))
2864                 return 0;
2865         else if (rc->image_id_ptr.data) {
2866                 /* extra check, pointer must be to an ID */
2867                 if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
2868                         BKE_report(op->reports, RPT_ERROR, "Pointer from path image_id is not an ID");
2869                         return 0;
2870                 }
2871         }
2872
2873         rc->use_secondary_tex = RNA_boolean_get(op->ptr, "secondary_tex");
2874
2875         return 1;
2876 }
2877
2878 static int radial_control_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2879 {
2880         wmWindowManager *wm;
2881         RadialControl *rc;
2882
2883
2884         if (!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
2885                 return OPERATOR_CANCELLED;
2886
2887         if (!radial_control_get_properties(C, op)) {
2888                 MEM_freeN(rc);
2889                 return OPERATOR_CANCELLED;
2890         }
2891
2892         /* get type, initial, min, and max values of the property */
2893         switch ((rc->type = RNA_property_type(rc->prop))) {
2894                 case PROP_INT:
2895                 {
2896                         int value, min, max, step;
2897
2898                         value = RNA_property_int_get(&rc->ptr, rc->prop);
2899                         RNA_property_int_ui_range(&rc->ptr, rc->prop, &min, &max, &step);
2900
2901                         rc->initial_value = value;
2902                         rc->min_value = min_ii(value, min);
2903                         rc->max_value = max_ii(value, max);
2904                         break;
2905                 }
2906                 case PROP_FLOAT:
2907                 {
2908                         float value, min, max, step, precision;
2909
2910                         value = RNA_property_float_get(&rc->ptr, rc->prop);
2911                         RNA_property_float_ui_range(&rc->ptr, rc->prop, &min, &max, &step, &precision);
2912
2913                         rc->initial_value = value;
2914                         rc->min_value = min_ff(value, min);
2915                         rc->max_value = max_ff(value, max);
2916                         break;
2917                 }
2918                 default:
2919                         BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
2920                         MEM_freeN(rc);
2921                         return OPERATOR_CANCELLED;
2922         }
2923
2924         /* initialize numerical input */
2925         initNumInput(&rc->num_input);
2926         rc->num_input.idx_max = 0;
2927         rc->num_input.val_flag[0] |= NUM_NO_NEGATIVE;
2928         rc->num_input.unit_sys = USER_UNIT_NONE;
2929         rc->num_input.unit_type[0] = B_UNIT_LENGTH;
2930
2931         /* get subtype of property */
2932         rc->subtype = RNA_property_subtype(rc->prop);
2933         if (!ELEM(rc->subtype, PROP_NONE, PROP_DISTANCE, PROP_FACTOR, PROP_PERCENTAGE, PROP_ANGLE, PROP_PIXEL)) {
2934                 BKE_report(op->reports, RPT_ERROR, "Property must be a none, distance, factor, percentage, angle, or pixel");
2935                 MEM_freeN(rc);
2936                 return OPERATOR_CANCELLED;
2937         }
2938
2939         rc->current_value = rc->initial_value;
2940         radial_control_set_initial_mouse(rc, event);
2941         radial_control_set_tex(rc);
2942
2943         /* temporarily disable other paint cursors */
2944         wm = CTX_wm_manager(C);
2945         rc->orig_paintcursors = wm->paintcursors;
2946         BLI_listbase_clear(&wm->paintcursors);
2947
2948         /* add radial control paint cursor */
2949         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
2950                                               radial_control_paint_cursor, rc);
2951
2952         WM_event_add_modal_handler(C, op);
2953
2954         return OPERATOR_RUNNING_MODAL;
2955 }
2956
2957 static void radial_control_set_value(RadialControl *rc, float val)
2958 {
2959         switch (rc->type) {
2960                 case PROP_INT:
2961                         RNA_property_int_set(&rc->ptr, rc->prop, val);
2962                         break;
2963                 case PROP_FLOAT:
2964                         RNA_property_float_set(&rc->ptr, rc->prop, val);
2965                         break;
2966                 default:
2967                         break;
2968         }
2969 }
2970
2971 static void radial_control_cancel(bContext *C, wmOperator *op)
2972 {
2973         RadialControl *rc = op->customdata;
2974         wmWindowManager *wm = CTX_wm_manager(C);
2975         ScrArea *sa = CTX_wm_area(C);
2976
2977         if (rc->dial) {
2978                 MEM_freeN(rc->dial);
2979                 rc->dial = NULL;
2980         }
2981
2982         if (sa) {
2983                 ED_area_headerprint(sa, NULL);
2984         }
2985         
2986         WM_paint_cursor_end(wm, rc->cursor);
2987
2988         /* restore original paint cursors */
2989         wm->paintcursors = rc->orig_paintcursors;
2990
2991         /* not sure if this is a good notifier to use;
2992          * intended purpose is to update the UI so that the
2993          * new value is displayed in sliders/numfields */
2994         WM_event_add_notifier(C, NC_WINDOW, NULL);
2995
2996         glDeleteTextures(1, &rc->gltex);
2997
2998         MEM_freeN(rc);
2999 }
3000
3001 static int radial_control_modal(bContext *C, wmOperator *op, const wmEvent *event)
3002 {
3003         RadialControl *rc = op->customdata;
3004         float new_value, dist = 0.0f, zoom[2];
3005         float delta[2], ret = OPERATOR_RUNNING_MODAL;
3006         bool snap;
3007         float angle_precision = 0.0f;
3008         const bool has_numInput = hasNumInput(&rc->num_input);
3009         bool handled = false;
3010         float numValue;
3011         /* TODO: fix hardcoded events */
3012
3013         snap = event->ctrl != 0;
3014
3015         /* Modal numinput active, try to handle numeric inputs first... */
3016         if (event->val == KM_PRESS && has_numInput && handleNumInput(C, &rc->num_input, event)) {
3017                 handled = true;
3018                 applyNumInput(&rc->num_input, &numValue);
3019
3020                 if (rc->subtype == PROP_ANGLE) {
3021                         numValue = DEG2RADF(numValue);
3022                         numValue = fmod(numValue, 2.0f * (float)M_PI);
3023                         if (numValue < 0.0f)
3024                                 numValue += 2.0f * (float)M_PI;
3025                 }
3026                 
3027                 CLAMP(numValue, rc->min_value, rc->max_value);
3028                 new_value = numValue;
3029                 
3030                 radial_control_set_value(rc, new_value);
3031                 rc->current_value = new_value;
3032                 radial_control_update_header(op, C);
3033                 return OPERATOR_RUNNING_MODAL;
3034         }
3035         else {
3036                 handled = false;
3037                 switch (event->type) {
3038                         case ESCKEY:
3039                         case RIGHTMOUSE:
3040                                 /* canceled; restore original value */
3041                                 radial_control_set_value(rc, rc->initial_value);
3042                                 ret = OPERATOR_CANCELLED;
3043                                 break;
3044
3045                         case LEFTMOUSE:
3046                         case PADENTER:
3047                         case RETKEY:
3048                                 /* done; value already set */
3049                                 RNA_property_update(C, &rc->ptr, rc->prop);
3050                                 ret = OPERATOR_FINISHED;
3051                                 break;
3052
3053                         case MOUSEMOVE:
3054                                 if (!has_numInput) {
3055                                         if (rc->slow_mode) {
3056                                                 if (rc->subtype == PROP_ANGLE) {
3057                                                         float position[2] = {event->x, event->y};
3058
3059                                                         /* calculate the initial angle here first */
3060                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
3061                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
3062
3063                                                         /* precision angle gets calculated from dial and gets added later */
3064                                                         angle_precision = -0.1f * BLI_dial_angle(rc->dial, position);
3065                                                 }
3066                                                 else {
3067                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
3068                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
3069
3070                                                         if (rc->zoom_prop) {
3071                                                                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3072                                                                 delta[0] /= zoom[0];
3073                                                                 delta[1] /= zoom[1];
3074                                                         }
3075
3076                                                         dist = len_v2(delta);
3077
3078                                                         delta[0] = event->x - rc->slow_mouse[0];
3079                                                         delta[1] = event->y - rc->slow_mouse[1];
3080
3081                                                         if (rc->zoom_prop) {
3082                                                                 delta[0] /= zoom[0];
3083                                                                 delta[1] /= zoom[1];
3084                                                         }
3085
3086                                                         dist = dist + 0.1f * (delta[0] + delta[1]);
3087                                                 }
3088                                         }
3089                                         else {
3090                                                 delta[0] = rc->initial_mouse[0] - event->x;
3091                                                 delta[1] = rc->initial_mouse[1] - event->y;
3092
3093                                                 if (rc->zoom_prop) {
3094                                                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3095                                                         delta[0] /= zoom[0];
3096                                                         delta[1] /= zoom[1];
3097                                                 }
3098
3099                                                 dist = len_v2(delta);
3100                                         }
3101
3102                                         /* calculate new value and apply snapping  */
3103                                         switch (rc->subtype) {
3104                                                 case PROP_NONE:
3105                                                 case PROP_DISTANCE:
3106                                                 case PROP_PIXEL:
3107                                                         new_value = dist;
3108                                                         if (snap) new_value = ((int)new_value + 5) / 10 * 10;
3109                                                         break;
3110                                                 case PROP_PERCENTAGE:
3111                                                         new_value = ((dist - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE) / WM_RADIAL_CONTROL_DISPLAY_WIDTH) * 100.0f;
3112                                                         if (snap) new_value = ((int)(new_value + 2.5f)) / 5 * 5;
3113                                                         break;
3114                                                 case PROP_FACTOR:
3115                                                         new_value = (WM_RADIAL_CONTROL_DISPLAY_SIZE - dist) / WM_RADIAL_CONTROL_DISPLAY_WIDTH;
3116                                                         if (snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
3117                                                         break;
3118                                                 case PROP_ANGLE:
3119                                                         new_value = atan2f(delta[1], delta[0]) + (float)M_PI + angle_precision;
3120                                                         new_value = fmod(new_value, 2.0f * (float)M_PI);
3121                                                         if (new_value < 0.0f)
3122                                                                 new_value += 2.0f * (float)M_PI;
3123                                                         if (snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10 * 10);
3124                                                         break;
3125                                                 default:
3126                                                         new_value = dist; /* dummy value, should this ever happen? - campbell */
3127                                                         break;
3128                                         }
3129
3130                                         /* clamp and update */
3131                                         CLAMP(new_value, rc->min_value, rc->max_value);
3132                                         radial_control_set_value(rc, new_value);
3133                                         rc->current_value = new_value;
3134                                         handled = true;
3135                                         break;
3136                                 }
3137                                 break;
3138
3139                         case LEFTSHIFTKEY:
3140                         case RIGHTSHIFTKEY:
3141                         {
3142                                 if (event->val == KM_PRESS) {
3143                                         rc->slow_mouse[0] = event->x;
3144                                         rc->slow_mouse[1] = event->y;
3145                                         rc->slow_mode = true;
3146                                         if (rc->subtype == PROP_ANGLE) {
3147                                                 float initial_position[2] = {UNPACK2(rc->initial_mouse)};
3148                                                 float current_position[2] = {UNPACK2(rc->slow_mouse)};
3149                                                 rc->dial = BLI_dial_initialize(initial_position, 0.0f);
3150                                                 /* immediately set the position to get a an initial&nbs