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