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