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