Cleanup: trailing whitespace (comment blocks)
[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         Main *bmain = CTX_data_main(C);
1310         ID *id = NULL;
1311         /* check input variables */
1312         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1313                 const bool is_relative_path = RNA_boolean_get(op->ptr, "relative_path");
1314                 char path[FILE_MAX];
1315                 bool exists = false;
1316
1317                 RNA_string_get(op->ptr, "filepath", path);
1318
1319                 errno = 0;
1320
1321                 if (idcode == ID_IM) {
1322                         id = (ID *)BKE_image_load_exists_ex(path, &exists);
1323                 }
1324                 else {
1325                         BLI_assert(0);
1326                 }
1327
1328                 if (!id) {
1329                         BKE_reportf(op->reports, RPT_ERROR, "Cannot read %s '%s': %s",
1330                                     BKE_idcode_to_name(idcode), path,
1331                                     errno ? strerror(errno) : TIP_("unsupported format"));
1332                         return NULL;
1333                 }
1334
1335                 if (is_relative_path ) {
1336                         if (exists == false) {
1337                                 if (idcode == ID_IM) {
1338                                         BLI_path_rel(((Image *)id)->name, bmain->name);
1339                                 }
1340                                 else {
1341                                         BLI_assert(0);
1342                                 }
1343                         }
1344                 }
1345         }
1346         else if (RNA_struct_property_is_set(op->ptr, "name")) {
1347                 char name[MAX_ID_NAME - 2];
1348                 RNA_string_get(op->ptr, "name", name);
1349                 id = BKE_libblock_find_name(bmain, idcode, name);
1350                 if (!id) {
1351                         BKE_reportf(op->reports, RPT_ERROR, "%s '%s' not found",
1352                                     BKE_idcode_to_name(idcode), name);
1353                         return NULL;
1354                 }
1355                 id_us_plus(id);
1356         }
1357
1358         return id;
1359 }
1360
1361 static void wm_block_redo_cb(bContext *C, void *arg_op, int UNUSED(arg_event))
1362 {
1363         wmOperator *op = arg_op;
1364
1365         if (op == WM_operator_last_redo(C)) {
1366                 /* operator was already executed once? undo & repeat */
1367                 ED_undo_operator_repeat(C, op);
1368         }
1369         else {
1370                 /* operator not executed yet, call it */
1371                 ED_undo_push_op(C, op);
1372                 wm_operator_register(C, op);
1373
1374                 WM_operator_repeat(C, op);
1375         }
1376 }
1377
1378 static void wm_block_redo_cancel_cb(bContext *C, void *arg_op)
1379 {
1380         wmOperator *op = arg_op;
1381
1382         /* if operator never got executed, free it */
1383         if (op != WM_operator_last_redo(C))
1384                 WM_operator_free(op);
1385 }
1386
1387 static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
1388 {
1389         wmOperator *op = arg_op;
1390         uiBlock *block;
1391         uiLayout *layout;
1392         uiStyle *style = UI_style_get();
1393         int width = 15 * UI_UNIT_X;
1394
1395         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1396         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1397         /* UI_BLOCK_NUMSELECT for layer buttons */
1398         UI_block_flag_enable(block, UI_BLOCK_NUMSELECT | UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1399
1400         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
1401          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
1402         assert(op->type->flag & OPTYPE_REGISTER);
1403
1404         UI_block_func_handle_set(block, wm_block_redo_cb, arg_op);
1405         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, 0, style);
1406
1407         if (op == WM_operator_last_redo(C))
1408                 if (!WM_operator_check_ui_enabled(C, op->type->name))
1409                         uiLayoutSetEnabled(layout, false);
1410
1411         if (op->type->flag & OPTYPE_MACRO) {
1412                 for (op = op->macro.first; op; op = op->next) {
1413                         uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1414                         if (op->next)
1415                                 uiItemS(layout);
1416                 }
1417         }
1418         else {
1419                 uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1420         }
1421         
1422         UI_block_bounds_set_popup(block, 4, 0, 0);
1423
1424         return block;
1425 }
1426
1427 typedef struct wmOpPopUp {
1428         wmOperator *op;
1429         int width;
1430         int height;
1431         int free_op;
1432 } wmOpPopUp;
1433
1434 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1435 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1436 {
1437         wmOpPopUp *data = arg1;
1438         uiBlock *block = arg2;
1439
1440         /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be canceled
1441          * in case WM_operator_call_ex exits/reloads the current file (T49199). */
1442         UI_popup_menu_retval_set(block, UI_RETURN_OK, true);
1443
1444         WM_operator_call_ex(C, data->op, true);
1445
1446         /* let execute handle freeing it */
1447         //data->free_op = false;
1448         //data->op = NULL;
1449
1450         /* in this case, wm_operator_ui_popup_cancel wont run */
1451         MEM_freeN(data);
1452
1453         /* get context data *after* WM_operator_call_ex which might have closed the current file and changed context */
1454         wmWindowManager *wm = CTX_wm_manager(C);
1455         wmWindow *win = CTX_wm_window(C);
1456
1457         /* check window before 'block->handle' incase the
1458          * popup execution closed the window and freed the block. see T44688.
1459          */
1460         /* Post 2.78 TODO: Check if this fix and others related to T44688 are still
1461          * needed or can be improved now that requesting context data has been corrected
1462          * (see above). We're close to release so not a good time for experiments.
1463          * -- Julian
1464          */
1465         if (BLI_findindex(&wm->windows, win) != -1) {
1466                 UI_popup_block_close(C, win, block);
1467         }
1468 }
1469
1470 /* Dialogs are popups that require user verification (click OK) before exec */
1471 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1472 {
1473         wmOpPopUp *data = userData;
1474         wmOperator *op = data->op;
1475         uiBlock *block;
1476         uiLayout *layout;
1477         uiStyle *style = UI_style_get();
1478
1479         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1480         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1481
1482         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogues have many items
1483          * where quitting by accident is very annoying */
1484         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NUMSELECT);
1485
1486         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1487         
1488         uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1489         
1490         /* clear so the OK button is left alone */
1491         UI_block_func_set(block, NULL, NULL, NULL);
1492
1493         /* new column so as not to interfere with custom layouts [#26436] */
1494         {
1495                 uiBlock *col_block;
1496                 uiLayout *col;
1497                 uiBut *btn;
1498
1499                 col = uiLayoutColumn(layout, false);
1500                 col_block = uiLayoutGetBlock(col);
1501                 /* Create OK button, the callback of which will execute op */
1502                 btn = uiDefBut(col_block, UI_BTYPE_BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1503                 UI_but_func_set(btn, dialog_exec_cb, data, col_block);
1504         }
1505
1506         /* center around the mouse */
1507         UI_block_bounds_set_popup(block, 4, data->width / -2, data->height / 2);
1508
1509         return block;
1510 }
1511
1512 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1513 {
1514         wmOpPopUp *data = userData;
1515         wmOperator *op = data->op;
1516         uiBlock *block;
1517         uiLayout *layout;
1518         uiStyle *style = UI_style_get();
1519
1520         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1521         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1522         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1523
1524         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1525
1526         /* since ui is defined the auto-layout args are not used */
1527         uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'V', 0);
1528
1529         UI_block_func_set(block, NULL, NULL, NULL);
1530
1531         UI_block_bounds_set_popup(block, 4, 0, 0);
1532
1533         return block;
1534 }
1535
1536 static void wm_operator_ui_popup_cancel(struct bContext *C, void *userData)
1537 {
1538         wmOpPopUp *data = userData;
1539         wmOperator *op = data->op;
1540
1541         if (op) {
1542                 if (op->type->cancel) {
1543                         op->type->cancel(C, op);
1544                 }
1545
1546                 if (data->free_op) {
1547                         WM_operator_free(op);
1548                 }
1549         }
1550
1551         MEM_freeN(data);
1552 }
1553
1554 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1555 {
1556         wmOpPopUp *data = arg;
1557         wmOperator *op = data->op;
1558
1559         if (op && retval > 0)
1560                 WM_operator_call_ex(C, op, true);
1561         
1562         MEM_freeN(data);
1563 }
1564
1565 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1566 {
1567         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1568         data->op = op;
1569         data->width = width;
1570         data->height = height;
1571         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1572         UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data, op);
1573         return OPERATOR_RUNNING_MODAL;
1574 }
1575
1576 /**
1577  * For use by #WM_operator_props_popup_call, #WM_operator_props_popup only.
1578  *
1579  * \note operator menu needs undo flag enabled, for redo callback */
1580 static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
1581                                       const bool do_call, const bool do_redo)
1582 {
1583         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1584                 BKE_reportf(op->reports, RPT_ERROR,
1585                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1586                 return OPERATOR_CANCELLED;
1587         }
1588
1589         if (do_redo) {
1590                 if ((op->type->flag & OPTYPE_UNDO) == 0) {
1591                         BKE_reportf(op->reports, RPT_ERROR,
1592                                     "Operator '%s' does not have undo enabled, incorrect invoke function", op->type->idname);
1593                         return OPERATOR_CANCELLED;
1594                 }
1595         }
1596
1597         /* if we don't have global undo, we can't do undo push for automatic redo,
1598          * so we require manual OK clicking in this popup */
1599         if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
1600                 return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
1601
1602         UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op, op);
1603
1604         if (do_call)
1605                 wm_block_redo_cb(C, op, 0);
1606
1607         return OPERATOR_RUNNING_MODAL;
1608 }
1609
1610 /**
1611  * Same as #WM_operator_props_popup but don't use operator redo.
1612  * just wraps #WM_operator_props_dialog_popup.
1613  */
1614 int WM_operator_props_popup_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1615 {
1616         return wm_operator_props_popup_ex(C, op, false, false);
1617 }
1618
1619 /**
1620  * Same as #WM_operator_props_popup but call the operator first,
1621  * This way - the button values correspond to the result of the operator.
1622  * Without this, first access to a button will make the result jump, see T32452.
1623  */
1624 int WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1625 {
1626         return wm_operator_props_popup_ex(C, op, true, true);
1627 }
1628
1629 int WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1630 {
1631         return wm_operator_props_popup_ex(C, op, false, true);
1632 }
1633
1634 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1635 {
1636         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1637         
1638         data->op = op;
1639         data->width = width;
1640         data->height = height;
1641         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1642
1643         /* op is not executed until popup OK but is clicked */
1644         UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data, op);
1645
1646         return OPERATOR_RUNNING_MODAL;
1647 }
1648
1649 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1650 {
1651         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1652         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1653                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1654                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1655                 return OPERATOR_CANCELLED;
1656         }
1657         if (op->type->poll && op->type->poll(C) == 0) {
1658                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1659                 return OPERATOR_CANCELLED;
1660         }
1661         
1662         UI_popup_block_invoke(C, wm_block_create_redo, op);
1663
1664         return OPERATOR_CANCELLED;
1665 }
1666
1667 /* ***************** Debug menu ************************* */
1668
1669 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1670 {
1671         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1672         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1673         WM_event_add_notifier(C, NC_WINDOW, NULL);
1674
1675         return OPERATOR_FINISHED;
1676 }
1677
1678 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1679 {
1680         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1681         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1682 }
1683
1684 static void WM_OT_debug_menu(wmOperatorType *ot)
1685 {
1686         ot->name = "Debug Menu";
1687         ot->idname = "WM_OT_debug_menu";
1688         ot->description = "Open a popup to set the debug level";
1689         
1690         ot->invoke = wm_debug_menu_invoke;
1691         ot->exec = wm_debug_menu_exec;
1692         ot->poll = WM_operator_winactive;
1693         
1694         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1695 }
1696
1697 /* ***************** Operator defaults ************************* */
1698 static int wm_operator_defaults_exec(bContext *C, wmOperator *op)
1699 {
1700         PointerRNA ptr = CTX_data_pointer_get_type(C, "active_operator", &RNA_Operator);
1701
1702         if (!ptr.data) {
1703                 BKE_report(op->reports, RPT_ERROR, "No operator in context");
1704                 return OPERATOR_CANCELLED;
1705         }
1706
1707         WM_operator_properties_reset((wmOperator *)ptr.data);
1708         return OPERATOR_FINISHED;
1709 }
1710
1711 /* used by operator preset menu. pre-2.65 this was a 'Reset' button */
1712 static void WM_OT_operator_defaults(wmOperatorType *ot)
1713 {
1714         ot->name = "Restore Defaults";
1715         ot->idname = "WM_OT_operator_defaults";
1716         ot->description = "Set the active operator to its default values";
1717
1718         ot->exec = wm_operator_defaults_exec;
1719
1720         ot->flag = OPTYPE_INTERNAL;
1721 }
1722
1723 /* ***************** Splash Screen ************************* */
1724
1725 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1726 {
1727         wmWindow *win = CTX_wm_window(C);
1728         UI_popup_block_close(C, win, arg_block);
1729 }
1730
1731 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1732
1733 static void wm_block_splash_refreshmenu(bContext *C, void *UNUSED(arg_block), void *UNUSED(arg))
1734 {
1735         ARegion *ar_menu = CTX_wm_menu(C);
1736         ED_region_tag_refresh_ui(ar_menu);
1737 }
1738
1739 static int wm_resource_check_prev(void)
1740 {
1741
1742         const char *res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, true);
1743
1744         // if (res) printf("USER: %s\n", res);
1745
1746 #if 0 /* ignore the local folder */
1747         if (res == NULL) {
1748                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1749                 res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, true);
1750         }
1751 #endif
1752
1753         // if (res) printf("LOCAL: %s\n", res);
1754         if (res) {
1755                 return false;
1756         }
1757         else {
1758                 return (BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, true) != NULL);
1759         }
1760 }
1761
1762 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1763 {
1764         uiBlock *block;
1765         uiBut *but;
1766         uiLayout *layout, *split, *col;
1767         uiStyle *style = UI_style_get();
1768         const struct RecentFile *recent;
1769         int i;
1770         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", true);
1771         char url[96];
1772         const char *version_suffix = NULL;
1773
1774 #ifndef WITH_HEADLESS
1775         extern char datatoc_splash_png[];
1776         extern int datatoc_splash_png_size;
1777
1778         extern char datatoc_splash_2x_png[];
1779         extern int datatoc_splash_2x_png_size;
1780         ImBuf *ibuf;
1781 #else
1782         ImBuf *ibuf = NULL;
1783 #endif
1784
1785 #ifdef WITH_BUILDINFO
1786         int label_delta = 0;
1787         int hash_width, date_width;
1788         char date_buf[128] = "\0";
1789         char hash_buf[128] = "\0";
1790         extern unsigned long build_commit_timestamp;
1791         extern char build_hash[], build_commit_date[], build_commit_time[], build_branch[];
1792
1793         /* Builds made from tag only shows tag sha */
1794         BLI_snprintf(hash_buf, sizeof(hash_buf), "Hash: %s", build_hash);
1795         BLI_snprintf(date_buf, sizeof(date_buf), "Date: %s %s", build_commit_date, build_commit_time);
1796         
1797         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.pixelsize * U.dpi);
1798         hash_width = (int)BLF_width(style->widgetlabel.uifont_id, hash_buf, sizeof(hash_buf)) + U.widget_unit;
1799         date_width = (int)BLF_width(style->widgetlabel.uifont_id, date_buf, sizeof(date_buf)) + U.widget_unit;
1800 #endif  /* WITH_BUILDINFO */
1801
1802 #ifndef WITH_HEADLESS
1803         if (U.pixelsize == 2) {
1804                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_2x_png,
1805                                              datatoc_splash_2x_png_size, IB_rect, NULL, "<splash screen>");
1806         }
1807         else {
1808                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1809                                              datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1810         }
1811
1812         /* overwrite splash with template image */
1813         if (U.app_template[0] != '\0') {
1814                 ImBuf *ibuf_template = NULL;
1815                 char splash_filepath[FILE_MAX];
1816                 char template_directory[FILE_MAX];
1817
1818                 if (BKE_appdir_app_template_id_search(
1819                         U.app_template,
1820                         template_directory, sizeof(template_directory)))
1821                 {
1822                         BLI_join_dirfile(
1823                                 splash_filepath, sizeof(splash_filepath), template_directory,
1824                                 (U.pixelsize == 2) ? "splash_2x.png" : "splash.png");
1825                         ibuf_template = IMB_loadiffname(splash_filepath, IB_rect, NULL);
1826                         if (ibuf_template) {
1827                                 const int x_expect = ibuf->x;
1828                                 const int y_expect = 230 * (int)U.pixelsize;
1829                                 /* don't cover the header text */
1830                                 if (ibuf_template->x == x_expect && ibuf_template->y == y_expect) {
1831                                         memcpy(ibuf->rect, ibuf_template->rect, ibuf_template->x * ibuf_template->y * sizeof(char[4]));
1832                                 }
1833                                 else {
1834                                         CLOG_ERROR(WM_LOG_OPERATORS,
1835                                                    "Splash expected %dx%d found %dx%d, ignoring: %s\n",
1836                                                    x_expect, y_expect, ibuf_template->x, ibuf_template->y, splash_filepath);
1837                                 }
1838                                 IMB_freeImBuf(ibuf_template);
1839                         }
1840                 }
1841         }
1842 #endif
1843
1844         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1845
1846         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1847          * with the OS when the splash shows, window clipping in this case gives
1848          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1849         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1850
1851         /* XXX splash scales with pixelsize, should become widget-units */
1852         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 */
1853         UI_but_func_set(but, wm_block_splash_close, block, NULL);
1854         UI_block_func_set(block, wm_block_splash_refreshmenu, block, NULL);
1855
1856         /* label for 'a' bugfix releases, or 'Release Candidate 1'...
1857          *  avoids recreating splash for version updates */
1858         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "rc")) {
1859                 version_suffix = "Release Candidate";
1860         }
1861         else if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1862                 version_suffix = STRINGIFY(BLENDER_VERSION_CHAR);
1863         }
1864         if (version_suffix != NULL && version_suffix[0]) {
1865                 /* placed after the version number in the image,
1866                  * placing y is tricky to match baseline */
1867                 int x = 260 * U.pixelsize - (2 * UI_DPI_FAC);
1868                 int y = 242 * U.pixelsize + (4 * UI_DPI_FAC);
1869                 int w = 240 * U.pixelsize;
1870
1871                 /* hack to have text draw 'text_sel' */
1872                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1873                 but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x, y, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1874                 /* XXX, set internal flag - UI_SELECT */
1875                 UI_but_flag_enable(but, 1);
1876                 UI_block_emboss_set(block, UI_EMBOSS);
1877         }
1878
1879 #ifdef WITH_BUILDINFO
1880         if (build_commit_timestamp != 0) {
1881                 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);
1882                 label_delta = 12;
1883         }
1884         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);
1885
1886         if (!STREQ(build_branch, "master")) {
1887                 char branch_buf[128] = "\0";
1888                 int branch_width;
1889                 BLI_snprintf(branch_buf, sizeof(branch_buf), "Branch: %s", build_branch);
1890                 branch_width = (int)BLF_width(style->widgetlabel.uifont_id, branch_buf, sizeof(branch_buf)) + U.widget_unit;
1891                 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);
1892         }
1893 #endif  /* WITH_BUILDINFO */
1894         
1895         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.pixelsize * 480, U.pixelsize * 110, 0, style);
1896         
1897         UI_block_emboss_set(block, UI_EMBOSS);
1898         /* show the splash menu (containing interaction presets), using python */
1899         if (mt) {
1900                 UI_menutype_draw(C, mt, layout);
1901
1902 //              wmWindowManager *wm = CTX_wm_manager(C);
1903 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
1904         }
1905         
1906         UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN);
1907         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
1908         
1909         split = uiLayoutSplit(layout, 0.0f, false);
1910         col = uiLayoutColumn(split, false);
1911         uiItemL(col, IFACE_("Links"), ICON_NONE);
1912 #if 0
1913         uiItemStringO(col, IFACE_("Support an Open Animation Movie"), ICON_URL, "WM_OT_url_open", "url",
1914                       "https://cloud.blender.org/join");
1915 #endif
1916         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url",
1917                       "http://www.blender.org/foundation/donation-payment/");
1918         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url",
1919                       "http://www.blender.org/about/credits/");
1920         BLI_snprintf(url, sizeof(url), "http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/%d.%d",
1921                      BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1922         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", url);
1923         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url",
1924                       "https://docs.blender.org/manual/en/dev/");
1925         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
1926         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1927                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/%d.%d"STRINGIFY(BLENDER_VERSION_CHAR),
1928                              BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1929         }
1930         else {
1931                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/master");
1932         }
1933         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
1934         uiItemL(col, "", ICON_NONE);
1935
1936         col = uiLayoutColumn(split, false);
1937
1938         if (wm_resource_check_prev()) {
1939                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
1940                 uiItemS(col);
1941         }
1942
1943         uiItemL(col, IFACE_("Recent"), ICON_NONE);
1944         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
1945                 const char *filename = BLI_path_basename(recent->filepath);
1946                 uiItemStringO(col, filename,
1947                               BLO_has_bfile_extension(filename) ? ICON_FILE_BLEND : ICON_FILE_BACKUP,
1948                               "WM_OT_open_mainfile", "filepath", recent->filepath);
1949         }
1950
1951         uiItemS(col);
1952         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
1953         uiItemL(col, "", ICON_NONE);
1954         
1955         mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
1956         if (mt) {
1957                 UI_menutype_draw(C, mt, uiLayoutColumn(layout, false));
1958         }
1959
1960         UI_block_bounds_set_centered(block, 0);
1961         
1962         return block;
1963 }
1964
1965 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
1966 {
1967         UI_popup_block_invoke(C, wm_block_create_splash, NULL);
1968         
1969         return OPERATOR_FINISHED;
1970 }
1971
1972 static void WM_OT_splash(wmOperatorType *ot)
1973 {
1974         ot->name = "Splash Screen";
1975         ot->idname = "WM_OT_splash";
1976         ot->description = "Open the splash screen with release info";
1977         
1978         ot->invoke = wm_splash_invoke;
1979         ot->poll = WM_operator_winactive;
1980 }
1981
1982
1983 /* ***************** Search menu ************************* */
1984
1985 struct SearchPopupInit_Data {
1986         int size[2];
1987 };
1988
1989 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *userdata)
1990 {
1991         const struct SearchPopupInit_Data *init_data = userdata;
1992         static char search[256] = "";
1993         wmEvent event;
1994         wmWindow *win = CTX_wm_window(C);
1995         uiBlock *block;
1996         uiBut *but;
1997         
1998         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1999         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
2000         
2001         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, init_data->size[0], UI_UNIT_Y, 0, 0, "");
2002         UI_but_func_operator_search(but);
2003         
2004         /* fake button, it holds space for search items */
2005         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - init_data->size[1],
2006                  init_data->size[0], init_data->size[1], NULL, 0, 0, 0, 0, NULL);
2007         
2008         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
2009         
2010         wm_event_init_from_window(win, &event);
2011         event.type = EVT_BUT_OPEN;
2012         event.val = KM_PRESS;
2013         event.customdata = but;
2014         event.customdatafree = false;
2015         wm_event_add(win, &event);
2016         
2017         return block;
2018 }
2019
2020 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2021 {
2022         return OPERATOR_FINISHED;
2023 }
2024
2025 static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2026 {
2027         struct SearchPopupInit_Data data = {
2028                 .size = {
2029                     UI_searchbox_size_x() * 2,
2030                     UI_searchbox_size_y(),
2031                 },
2032         };
2033
2034         UI_popup_block_invoke(C, wm_block_search_menu, &data);
2035         
2036         return OPERATOR_INTERFACE;
2037 }
2038
2039 /* op->poll */
2040 static int wm_search_menu_poll(bContext *C)
2041 {
2042         if (CTX_wm_window(C) == NULL) {
2043                 return 0;
2044         }
2045         else {
2046                 ScrArea *sa = CTX_wm_area(C);
2047                 if (sa) {
2048                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
2049                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
2050                 }
2051                 else {
2052                         Object *editob = CTX_data_edit_object(C);
2053                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
2054                 }
2055         }
2056         return 1;
2057 }
2058
2059 static void WM_OT_search_menu(wmOperatorType *ot)
2060 {
2061         ot->name = "Search Menu";
2062         ot->idname = "WM_OT_search_menu";
2063         ot->description = "Pop-up a search menu over all available operators in current context";
2064         
2065         ot->invoke = wm_search_menu_invoke;
2066         ot->exec = wm_search_menu_exec;
2067         ot->poll = wm_search_menu_poll;
2068 }
2069
2070 static int wm_call_menu_exec(bContext *C, wmOperator *op)
2071 {
2072         char idname[BKE_ST_MAXNAME];
2073         RNA_string_get(op->ptr, "name", idname);
2074
2075         return UI_popup_menu_invoke(C, idname, op->reports);
2076 }
2077
2078 static void WM_OT_call_menu(wmOperatorType *ot)
2079 {
2080         ot->name = "Call Menu";
2081         ot->idname = "WM_OT_call_menu";
2082         ot->description = "Call (draw) a pre-defined menu";
2083
2084         ot->exec = wm_call_menu_exec;
2085         ot->poll = WM_operator_winactive;
2086
2087         ot->flag = OPTYPE_INTERNAL;
2088
2089         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
2090 }
2091
2092 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2093 {
2094         char idname[BKE_ST_MAXNAME];
2095         RNA_string_get(op->ptr, "name", idname);
2096
2097         return UI_pie_menu_invoke(C, idname, event);
2098 }
2099
2100 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
2101 {
2102         char idname[BKE_ST_MAXNAME];
2103         RNA_string_get(op->ptr, "name", idname);
2104
2105         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
2106 }
2107
2108 static void WM_OT_call_menu_pie(wmOperatorType *ot)
2109 {
2110         ot->name = "Call Pie Menu";
2111         ot->idname = "WM_OT_call_menu_pie";
2112         ot->description = "Call (draw) a pre-defined pie menu";
2113
2114         ot->invoke = wm_call_pie_menu_invoke;
2115         ot->exec = wm_call_pie_menu_exec;
2116         ot->poll = WM_operator_winactive;
2117
2118         ot->flag = OPTYPE_INTERNAL;
2119
2120         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
2121 }
2122
2123 /* ************ window / screen operator definitions ************** */
2124
2125 /* this poll functions is needed in place of WM_operator_winactive
2126  * while it crashes on full screen */
2127 static int wm_operator_winactive_normal(bContext *C)
2128 {
2129         wmWindow *win = CTX_wm_window(C);
2130
2131         if (win == NULL || win->screen == NULL || win->screen->state != SCREENNORMAL)
2132                 return 0;
2133
2134         return 1;
2135 }
2136
2137 /* included for script-access */
2138 static void WM_OT_window_close(wmOperatorType *ot)
2139 {
2140         ot->name = "Close Window";
2141         ot->idname = "WM_OT_window_close";
2142         ot->description = "Close the current Blender window";
2143
2144         ot->exec = wm_window_close_exec;
2145         ot->poll = WM_operator_winactive;
2146 }
2147
2148 static void WM_OT_window_duplicate(wmOperatorType *ot)
2149 {
2150         ot->name = "Duplicate Window";
2151         ot->idname = "WM_OT_window_duplicate";
2152         ot->description = "Duplicate the current Blender window";
2153                 
2154         ot->exec = wm_window_duplicate_exec;
2155         ot->poll = wm_operator_winactive_normal;
2156 }
2157
2158 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2159 {
2160         ot->name = "Toggle Window Fullscreen";
2161         ot->idname = "WM_OT_window_fullscreen_toggle";
2162         ot->description = "Toggle the current window fullscreen";
2163
2164         ot->exec = wm_window_fullscreen_toggle_exec;
2165         ot->poll = WM_operator_winactive;
2166 }
2167
2168 static int wm_exit_blender_exec(bContext *C, wmOperator *UNUSED(op))
2169 {
2170         wm_quit_with_optional_confirmation_prompt(C, CTX_wm_window(C));
2171         return OPERATOR_FINISHED;
2172 }
2173
2174 static int wm_exit_blender_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2175 {
2176         if (U.uiflag & USER_QUIT_PROMPT) {
2177                 return wm_exit_blender_exec(C, op);
2178         }
2179         else {
2180                 return WM_operator_confirm(C, op, event);
2181         }
2182 }
2183
2184 static void WM_OT_quit_blender(wmOperatorType *ot)
2185 {
2186         ot->name = "Quit Blender";
2187         ot->idname = "WM_OT_quit_blender";
2188         ot->description = "Quit Blender";
2189
2190         ot->invoke = wm_exit_blender_invoke;
2191         ot->exec = wm_exit_blender_exec;
2192 }
2193
2194 /* *********************** */
2195
2196 #if defined(WIN32)
2197
2198 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2199 {
2200         GHOST_toggleConsole(2);
2201         return OPERATOR_FINISHED;
2202 }
2203
2204 static void WM_OT_console_toggle(wmOperatorType *ot)
2205 {
2206         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
2207         ot->name = CTX_N_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
2208         ot->idname = "WM_OT_console_toggle";
2209         ot->description = N_("Toggle System Console");
2210         
2211         ot->exec = wm_console_toggle_exec;
2212         ot->poll = WM_operator_winactive;
2213 }
2214
2215 #endif
2216
2217 /* ************ default paint cursors, draw always around cursor *********** */
2218 /*
2219  * - returns handler to free
2220  * - poll(bContext): returns 1 if draw should happen
2221  * - draw(bContext): drawing callback for paint cursor
2222  */
2223
2224 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2225                                wmPaintCursorDraw draw, void *customdata)
2226 {
2227         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2228         
2229         BLI_addtail(&wm->paintcursors, pc);
2230         
2231         pc->customdata = customdata;
2232         pc->poll = poll;
2233         pc->draw = draw;
2234         
2235         return pc;
2236 }
2237
2238 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2239 {
2240         wmPaintCursor *pc;
2241         
2242         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
2243                 if (pc == (wmPaintCursor *)handle) {
2244                         BLI_remlink(&wm->paintcursors, pc);
2245                         MEM_freeN(pc);
2246                         return;
2247                 }
2248         }
2249 }
2250
2251 /* *********************** radial control ****************** */
2252
2253 #define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
2254 #define WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE (35 * UI_DPI_FAC)
2255 #define WM_RADIAL_CONTROL_DISPLAY_WIDTH (WM_RADIAL_CONTROL_DISPLAY_SIZE - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE)
2256 #define WM_RADIAL_MAX_STR 10
2257
2258 typedef struct {
2259         PropertyType type;
2260         PropertySubType subtype;
2261         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2262         PointerRNA fill_col_override_ptr, fill_col_override_test_ptr;
2263         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2264         PropertyRNA *fill_col_override_prop, *fill_col_override_test_prop;
2265         StructRNA *image_id_srna;
2266         float initial_value, current_value, min_value, max_value;
2267         int initial_mouse[2];
2268         int slow_mouse[2];
2269         bool slow_mode;
2270         Dial *dial;
2271         unsigned int gltex;
2272         ListBase orig_paintcursors;
2273         bool use_secondary_tex;
2274         void *cursor;
2275         NumInput num_input;
2276 } RadialControl;
2277
2278 static void radial_control_update_header(wmOperator *op, bContext *C)
2279 {
2280         RadialControl *rc = op->customdata;
2281         char msg[UI_MAX_DRAW_STR];
2282         ScrArea *sa = CTX_wm_area(C);
2283         Scene *scene = CTX_data_scene(C);
2284         
2285         if (sa) {
2286                 if (hasNumInput(&rc->num_input)) {
2287                         char num_str[NUM_STR_REP_LEN];
2288                         outputNumInput(&rc->num_input, num_str, &scene->unit);
2289                         BLI_snprintf(msg, sizeof(msg), "%s: %s", RNA_property_ui_name(rc->prop), num_str);
2290                 }
2291                 else {
2292                         const char *ui_name = RNA_property_ui_name(rc->prop);
2293                         switch (rc->subtype) {
2294                                 case PROP_NONE:
2295                                 case PROP_DISTANCE:
2296                                         BLI_snprintf(msg, sizeof(msg), "%s: %0.4f", ui_name, rc->current_value);
2297                                         break;
2298                                 case PROP_PIXEL:
2299                                         BLI_snprintf(msg, sizeof(msg), "%s: %d", ui_name, (int)rc->current_value); /* XXX: round to nearest? */
2300                                         break;
2301                                 case PROP_PERCENTAGE:
2302                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.1f%%", ui_name, rc->current_value);
2303                                         break;
2304                                 case PROP_FACTOR:
2305                                         BLI_snprintf(msg, sizeof(msg), "%s: %1.3f", ui_name, rc->current_value);
2306                                         break;
2307                                 case PROP_ANGLE:
2308                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.2f", ui_name, RAD2DEGF(rc->current_value));
2309                                         break;
2310                                 default:
2311                                         BLI_snprintf(msg, sizeof(msg), "%s", ui_name); /* XXX: No value? */
2312                                         break;
2313                         }
2314                 }
2315                 ED_area_headerprint(sa, msg);
2316         }
2317 }
2318
2319 static void radial_control_set_initial_mouse(RadialControl *rc, const wmEvent *event)
2320 {
2321         float d[2] = {0, 0};
2322         float zoom[2] = {1, 1};
2323
2324         rc->initial_mouse[0] = event->x;
2325         rc->initial_mouse[1] = event->y;
2326
2327         switch (rc->subtype) {
2328                 case PROP_NONE:
2329                 case PROP_DISTANCE:
2330                 case PROP_PIXEL:
2331                         d[0] = rc->initial_value;
2332                         break;
2333                 case PROP_PERCENTAGE:
2334                         d[0] = (rc->initial_value) / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2335                         break;
2336                 case PROP_FACTOR:
2337                         d[0] = (1 - rc->initial_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2338                         break;
2339                 case PROP_ANGLE:
2340                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cosf(rc->initial_value);
2341                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sinf(rc->initial_value);
2342                         break;
2343                 default:
2344                         return;
2345         }
2346
2347         if (rc->zoom_prop) {
2348                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2349                 d[0] *= zoom[0];
2350                 d[1] *= zoom[1];
2351         }
2352
2353         rc->initial_mouse[0] -= d[0];
2354         rc->initial_mouse[1] -= d[1];
2355 }
2356
2357 static void radial_control_set_tex(RadialControl *rc)
2358 {
2359         ImBuf *ibuf;
2360
2361         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
2362                 case ID_BR:
2363                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data, rc->use_secondary_tex))) {
2364                                 glGenTextures(1, &rc->gltex);
2365                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2366                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, ibuf->x, ibuf->y, 0,
2367                                              GL_ALPHA, GL_FLOAT, ibuf->rect_float);
2368                                 MEM_freeN(ibuf->rect_float);
2369                                 MEM_freeN(ibuf);
2370                         }
2371                         break;
2372                 default:
2373                         break;
2374         }
2375 }
2376
2377 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
2378 {
2379         float col[3] = {0, 0, 0};
2380         float rot;
2381
2382         /* set fill color */
2383         if (rc->fill_col_prop) {
2384                 PointerRNA *fill_ptr;
2385                 PropertyRNA *fill_prop;
2386
2387                 if (rc->fill_col_override_prop &&
2388                     RNA_property_boolean_get(&rc->fill_col_override_test_ptr, rc->fill_col_override_test_prop))
2389                 {
2390                         fill_ptr = &rc->fill_col_override_ptr;
2391                         fill_prop = rc->fill_col_override_prop;
2392                 }
2393                 else {
2394                         fill_ptr = &rc->fill_col_ptr;
2395                         fill_prop = rc->fill_col_prop;
2396                 }
2397
2398                 RNA_property_float_get_array(fill_ptr, fill_prop, col);
2399         }
2400         glColor4f(col[0], col[1], col[2], alpha);
2401
2402         if (rc->gltex) {
2403                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2404
2405                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2406                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2407
2408                 /* set up rotation if available */
2409                 if (rc->rot_prop) {
2410                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2411                         glPushMatrix();
2412                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
2413                 }
2414
2415                 /* draw textured quad */
2416                 GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
2417                 glBegin(GL_QUADS);
2418                 glTexCoord2f(0, 0);
2419                 glVertex2f(-radius, -radius);
2420                 glTexCoord2f(1, 0);
2421                 glVertex2f(radius, -radius);
2422                 glTexCoord2f(1, 1);
2423                 glVertex2f(radius, radius);
2424                 glTexCoord2f(0, 1);
2425                 glVertex2f(-radius, radius);
2426                 glEnd();
2427                 GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
2428
2429                 /* undo rotation */
2430                 if (rc->rot_prop)
2431                         glPopMatrix();
2432         }
2433         else {
2434                 /* flat color if no texture available */
2435                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
2436         }
2437 }
2438
2439 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
2440 {
2441         RadialControl *rc = customdata;
2442         ARegion *ar = CTX_wm_region(C);
2443         uiStyle *style = UI_style_get();
2444         const uiFontStyle *fstyle = &style->widget;
2445         const int fontid = fstyle->uifont_id;
2446         short fstyle_points = fstyle->points;
2447         char str[WM_RADIAL_MAX_STR];
2448         short strdrawlen = 0;
2449         float strwidth, strheight;
2450         float r1 = 0.0f, r2 = 0.0f, rmin = 0.0, tex_radius, alpha;
2451         float zoom[2], col[3] = {1, 1, 1};      
2452
2453         switch (rc->subtype) {
2454                 case PROP_NONE:
2455                 case PROP_DISTANCE:
2456                 case PROP_PIXEL:
2457                         r1 = rc->current_value;
2458                         r2 = rc->initial_value;
2459                         tex_radius = r1;
2460                         alpha = 0.75;
2461                         break;
2462                 case PROP_PERCENTAGE:
2463                         r1 = rc->current_value / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2464                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2465                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2466                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.1f%%", rc->current_value);
2467                         strdrawlen = BLI_strlen_utf8(str);
2468                         tex_radius = r1;
2469                         alpha = 0.75;
2470                         break;
2471                 case PROP_FACTOR:
2472                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2473                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2474                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2475                         alpha = rc->current_value / 2.0f + 0.5f;
2476                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%1.3f", rc->current_value);
2477                         strdrawlen = BLI_strlen_utf8(str);
2478                         break;
2479                 case PROP_ANGLE:
2480                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2481                         alpha = 0.75;
2482                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2483                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.2f", RAD2DEGF(rc->current_value));
2484                         strdrawlen = BLI_strlen_utf8(str);
2485                         break;
2486                 default:
2487                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
2488                         alpha = 0.75;
2489                         break;
2490         }
2491
2492         /* Keep cursor in the original place */
2493         x = rc->initial_mouse[0] - ar->winrct.xmin;
2494         y = rc->initial_mouse[1] - ar->winrct.ymin;
2495         glTranslatef((float)x, (float)y, 0.0f);
2496
2497         glEnable(GL_BLEND);
2498         glEnable(GL_LINE_SMOOTH);
2499
2500         /* apply zoom if available */
2501         if (rc->zoom_prop) {
2502                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2503                 glScalef(zoom[0], zoom[1], 1);
2504         }
2505
2506         /* draw rotated texture */
2507         radial_control_paint_tex(rc, tex_radius, alpha);
2508
2509         /* set line color */
2510         if (rc->col_prop)
2511                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
2512         glColor4f(col[0], col[1], col[2], 0.5);
2513
2514         if (rc->subtype == PROP_ANGLE) {
2515                 glPushMatrix();
2516                 /* draw original angle line */
2517                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
2518                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2519                 /* draw new angle line */
2520                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
2521                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2522                 glPopMatrix();
2523         }
2524
2525         /* draw circles on top */
2526         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r1, 40);
2527         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r2, 40);
2528         if (rmin > 0.0f)
2529                 glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), rmin, 40);
2530
2531         BLF_size(fontid, 1.5 * fstyle_points * U.pixelsize, U.dpi);
2532         BLF_enable(fontid, BLF_SHADOW);
2533         BLF_shadow(fontid, 3, (const float[4]){0.0f, 0.0f, 0.0f, 0.5f});
2534         BLF_shadow_offset(fontid, 1, -1);
2535
2536         /* draw value */
2537         BLF_width_and_height(fontid, str, strdrawlen, &strwidth, &strheight);
2538         BLF_position(fontid, -0.5f * strwidth, -0.5f * strheight, 0.0f);
2539         BLF_draw(fontid, str, strdrawlen);
2540
2541         BLF_disable(fontid, BLF_SHADOW);
2542
2543         glDisable(GL_BLEND);
2544         glDisable(GL_LINE_SMOOTH);
2545 }
2546
2547 typedef enum {
2548         RC_PROP_ALLOW_MISSING = 1,
2549         RC_PROP_REQUIRE_FLOAT = 2,
2550         RC_PROP_REQUIRE_BOOL = 4,
2551 } RCPropFlags;
2552
2553 /**
2554  * Attempt to retrieve the rna pointer/property from an rna path.
2555  *
2556  * \return 0 for failure, 1 for success, and also 1 if property is not set.
2557  */
2558 static int radial_control_get_path(
2559         PointerRNA *ctx_ptr, wmOperator *op,
2560         const char *name, PointerRNA *r_ptr,
2561         PropertyRNA **r_prop, int req_length, RCPropFlags flags)
2562 {
2563         PropertyRNA *unused_prop;
2564         int len;
2565         char *str;
2566
2567         /* check flags */
2568         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
2569                 BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
2570                 return 0;
2571         }
2572
2573         /* get an rna string path from the operator's properties */
2574         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
2575                 return 1;
2576
2577         if (str[0] == '\0') {
2578                 if (r_prop) *r_prop = NULL;
2579                 MEM_freeN(str);
2580                 return 1;
2581         }
2582
2583         if (!r_prop)
2584                 r_prop = &unused_prop;
2585
2586         /* get rna from path */
2587         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
2588                 MEM_freeN(str);
2589                 if (flags & RC_PROP_ALLOW_MISSING)
2590                         return 1;
2591                 else {
2592                         BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
2593                         return 0;
2594                 }
2595         }
2596
2597         /* check property type */
2598         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
2599                 PropertyType prop_type = RNA_property_type(*r_prop);
2600
2601                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
2602                     ((flags & RC_PROP_REQUIRE_FLOAT) && (prop_type != PROP_FLOAT)))
2603                 {
2604                         MEM_freeN(str);
2605                         BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
2606                         return 0;
2607                 }
2608         }
2609         
2610         /* check property's array length */
2611         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
2612                 MEM_freeN(str);
2613                 BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
2614                             name, len, req_length);
2615                 return 0;
2616         }
2617
2618         /* success */
2619         MEM_freeN(str);
2620         return 1;
2621 }
2622
2623 /* initialize the rna pointers and properties using rna paths */
2624 static int radial_control_get_properties(bContext *C, wmOperator *op)
2625 {
2626         RadialControl *rc = op->customdata;
2627         PointerRNA ctx_ptr, use_secondary_ptr;
2628         PropertyRNA *use_secondary_prop = NULL;
2629         const char *data_path;
2630
2631         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
2632
2633         /* check if we use primary or secondary path */
2634         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
2635                                      &use_secondary_ptr, &use_secondary_prop,
2636                                      0, (RC_PROP_ALLOW_MISSING |
2637                                          RC_PROP_REQUIRE_BOOL)))
2638         {
2639                 return 0;
2640         }
2641         else {
2642                 if (use_secondary_prop &&
2643                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
2644                 {
2645                         data_path = "data_path_secondary";
2646                 }
2647                 else {
2648                         data_path = "data_path_primary";
2649                 }
2650         }
2651
2652         if (!radial_control_get_path(&ctx_ptr, op, data_path, &rc->ptr, &rc->prop, 0, 0))
2653                 return 0;
2654
2655         /* data path is required */
2656         if (!rc->prop)
2657                 return 0;
2658         
2659         if (!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 0, RC_PROP_REQUIRE_FLOAT))
2660                 return 0;
2661         if (!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2662                 return 0;
2663
2664
2665         if (!radial_control_get_path(
2666                 &ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2667         {
2668                 return 0;
2669         }
2670
2671         if (!radial_control_get_path(
2672                 &ctx_ptr, op, "fill_color_override_path",
2673                 &rc->fill_col_override_ptr, &rc->fill_col_override_prop, 3, RC_PROP_REQUIRE_FLOAT))
2674         {
2675                 return 0;
2676         }
2677         if (!radial_control_get_path(
2678                 &ctx_ptr, op, "fill_color_override_test_path",
2679                 &rc->fill_col_override_test_ptr, &rc->fill_col_override_test_prop, 0, RC_PROP_REQUIRE_BOOL))
2680         {
2681                 return 0;
2682         }
2683
2684         /* slightly ugly; allow this property to not resolve
2685          * correctly. needed because 3d texture paint shares the same
2686          * keymap as 2d image paint */
2687         if (!radial_control_get_path(&ctx_ptr, op, "zoom_path",
2688                                      &rc->zoom_ptr, &rc->zoom_prop, 2,
2689                                      RC_PROP_REQUIRE_FLOAT | RC_PROP_ALLOW_MISSING))
2690         {
2691                 return 0;
2692         }
2693         
2694         if (!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0))
2695                 return 0;
2696         else if (rc->image_id_ptr.data) {
2697                 /* extra check, pointer must be to an ID */
2698                 if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
2699                         BKE_report(op->reports, RPT_ERROR, "Pointer from path image_id is not an ID");
2700                         return 0;
2701                 }
2702         }
2703
2704         rc->use_secondary_tex = RNA_boolean_get(op->ptr, "secondary_tex");
2705
2706         return 1;
2707 }
2708
2709 static int radial_control_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2710 {
2711         wmWindowManager *wm;
2712         RadialControl *rc;
2713
2714
2715         if (!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
2716                 return OPERATOR_CANCELLED;
2717
2718         if (!radial_control_get_properties(C, op)) {
2719                 MEM_freeN(rc);
2720                 return OPERATOR_CANCELLED;
2721         }
2722
2723         /* get type, initial, min, and max values of the property */
2724         switch ((rc->type = RNA_property_type(rc->prop))) {
2725                 case PROP_INT:
2726                 {
2727                         int value, min, max, step;
2728
2729                         value = RNA_property_int_get(&rc->ptr, rc->prop);
2730                         RNA_property_int_ui_range(&rc->ptr, rc->prop, &min, &max, &step);
2731
2732                         rc->initial_value = value;
2733                         rc->min_value = min_ii(value, min);
2734                         rc->max_value = max_ii(value, max);
2735                         break;
2736                 }
2737                 case PROP_FLOAT:
2738                 {
2739                         float value, min, max, step, precision;
2740
2741                         value = RNA_property_float_get(&rc->ptr, rc->prop);
2742                         RNA_property_float_ui_range(&rc->ptr, rc->prop, &min, &max, &step, &precision);
2743
2744                         rc->initial_value = value;
2745                         rc->min_value = min_ff(value, min);
2746                         rc->max_value = max_ff(value, max);
2747                         break;
2748                 }
2749                 default:
2750                         BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
2751                         MEM_freeN(rc);
2752                         return OPERATOR_CANCELLED;
2753         }
2754
2755         /* initialize numerical input */
2756         initNumInput(&rc->num_input);
2757         rc->num_input.idx_max = 0;
2758         rc->num_input.val_flag[0] |= NUM_NO_NEGATIVE;
2759         rc->num_input.unit_sys = USER_UNIT_NONE;
2760         rc->num_input.unit_type[0] = B_UNIT_LENGTH;
2761
2762         /* get subtype of property */
2763         rc->subtype = RNA_property_subtype(rc->prop);
2764         if (!ELEM(rc->subtype, PROP_NONE, PROP_DISTANCE, PROP_FACTOR, PROP_PERCENTAGE, PROP_ANGLE, PROP_PIXEL)) {
2765                 BKE_report(op->reports, RPT_ERROR, "Property must be a none, distance, factor, percentage, angle, or pixel");
2766                 MEM_freeN(rc);
2767                 return OPERATOR_CANCELLED;
2768         }
2769
2770         rc->current_value = rc->initial_value;
2771         radial_control_set_initial_mouse(rc, event);
2772         radial_control_set_tex(rc);
2773
2774         /* temporarily disable other paint cursors */
2775         wm = CTX_wm_manager(C);
2776         rc->orig_paintcursors = wm->paintcursors;
2777         BLI_listbase_clear(&wm->paintcursors);
2778
2779         /* add radial control paint cursor */
2780         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
2781                                               radial_control_paint_cursor, rc);
2782
2783         WM_event_add_modal_handler(C, op);
2784
2785         return OPERATOR_RUNNING_MODAL;
2786 }
2787
2788 static void radial_control_set_value(RadialControl *rc, float val)
2789 {
2790         switch (rc->type) {
2791                 case PROP_INT:
2792                         RNA_property_int_set(&rc->ptr, rc->prop, val);
2793                         break;
2794                 case PROP_FLOAT:
2795                         RNA_property_float_set(&rc->ptr, rc->prop, val);
2796                         break;
2797                 default:
2798                         break;
2799         }
2800 }
2801
2802 static void radial_control_cancel(bContext *C, wmOperator *op)
2803 {
2804         RadialControl *rc = op->customdata;
2805         wmWindowManager *wm = CTX_wm_manager(C);
2806         ScrArea *sa = CTX_wm_area(C);
2807
2808         if (rc->dial) {
2809                 MEM_freeN(rc->dial);
2810                 rc->dial = NULL;
2811         }
2812
2813         if (sa) {
2814                 ED_area_headerprint(sa, NULL);
2815         }
2816         
2817         WM_paint_cursor_end(wm, rc->cursor);
2818
2819         /* restore original paint cursors */
2820         wm->paintcursors = rc->orig_paintcursors;
2821
2822         /* not sure if this is a good notifier to use;
2823          * intended purpose is to update the UI so that the
2824          * new value is displayed in sliders/numfields */
2825         WM_event_add_notifier(C, NC_WINDOW, NULL);
2826
2827         glDeleteTextures(1, &rc->gltex);
2828
2829         MEM_freeN(rc);
2830 }
2831
2832 static int radial_control_modal(bContext *C, wmOperator *op, const wmEvent *event)
2833 {
2834         RadialControl *rc = op->customdata;
2835         float new_value, dist = 0.0f, zoom[2];
2836         float delta[2], ret = OPERATOR_RUNNING_MODAL;
2837         bool snap;
2838         float angle_precision = 0.0f;
2839         const bool has_numInput = hasNumInput(&rc->num_input);
2840         bool handled = false;
2841         float numValue;
2842         /* TODO: fix hardcoded events */
2843
2844         snap = event->ctrl != 0;
2845
2846         /* Modal numinput active, try to handle numeric inputs first... */
2847         if (event->val == KM_PRESS && has_numInput && handleNumInput(C, &rc->num_input, event)) {
2848                 handled = true;
2849                 applyNumInput(&rc->num_input, &numValue);
2850
2851                 if (rc->subtype == PROP_ANGLE) {
2852                         numValue = DEG2RADF(numValue);
2853                         numValue = fmod(numValue, 2.0f * (float)M_PI);
2854                         if (numValue < 0.0f)
2855                                 numValue += 2.0f * (float)M_PI;
2856                 }
2857                 
2858                 CLAMP(numValue, rc->min_value, rc->max_value);
2859                 new_value = numValue;
2860                 
2861                 radial_control_set_value(rc, new_value);
2862                 rc->current_value = new_value;
2863                 radial_control_update_header(op, C);
2864                 return OPERATOR_RUNNING_MODAL;
2865         }
2866         else {
2867                 handled = false;
2868                 switch (event->type) {
2869                         case ESCKEY:
2870                         case RIGHTMOUSE:
2871                                 /* canceled; restore original value */
2872                                 radial_control_set_value(rc, rc->initial_value);
2873                                 ret = OPERATOR_CANCELLED;
2874                                 break;
2875
2876                         case LEFTMOUSE:
2877                         case PADENTER:
2878                         case RETKEY:
2879                                 /* done; value already set */
2880                                 RNA_property_update(C, &rc->ptr, rc->prop);
2881                                 ret = OPERATOR_FINISHED;
2882                                 break;
2883
2884                         case MOUSEMOVE:
2885                                 if (!has_numInput) {
2886                                         if (rc->slow_mode) {
2887                                                 if (rc->subtype == PROP_ANGLE) {
2888                                                         float position[2] = {event->x, event->y};
2889
2890                                                         /* calculate the initial angle here first */
2891                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2892                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2893
2894                                                         /* precision angle gets calculated from dial and gets added later */
2895                                                         angle_precision = -0.1f * BLI_dial_angle(rc->dial, position);
2896                                                 }
2897                                                 else {
2898                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2899                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2900
2901                                                         if (rc->zoom_prop) {
2902                                                                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2903                                                                 delta[0] /= zoom[0];
2904                                                                 delta[1] /= zoom[1];
2905                                                         }
2906
2907                                                         dist = len_v2(delta);
2908
2909                                                         delta[0] = event->x - rc->slow_mouse[0];
2910                                                         delta[1] = event->y - rc->slow_mouse[1];
2911
2912                                                         if (rc->zoom_prop) {
2913                                                                 delta[0] /= zoom[0];
2914                                                                 delta[1] /= zoom[1];
2915                                                         }
2916
2917                                                         dist = dist + 0.1f * (delta[0] + delta[1]);
2918                                                 }
2919                                         }
2920                                         else {
2921                                                 delta[0] = rc->initial_mouse[0] - event->x;
2922                                                 delta[1] = rc->initial_mouse[1] - event->y;
2923
2924                                                 if (rc->zoom_prop) {
2925                                                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2926                                                         delta[0] /= zoom[0];
2927                                                         delta[1] /= zoom[1];
2928                                                 }
2929
2930                                                 dist = len_v2(delta);
2931                                         }
2932
2933                                         /* calculate new value and apply snapping  */
2934                                         switch (rc->subtype) {
2935                                                 case PROP_NONE:
2936                                                 case PROP_DISTANCE:
2937                                                 case PROP_PIXEL:
2938                                                         new_value = dist;
2939                                                         if (snap) new_value = ((int)new_value + 5) / 10 * 10;
2940                                                         break;
2941                                                 case PROP_PERCENTAGE:
2942                                                         new_value = ((dist - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE) / WM_RADIAL_CONTROL_DISPLAY_WIDTH) * 100.0f;
2943                                                         if (snap) new_value = ((int)(new_value + 2.5f)) / 5 * 5;
2944                                                         break;
2945                                                 case PROP_FACTOR:
2946                                                         new_value = (WM_RADIAL_CONTROL_DISPLAY_SIZE - dist) / WM_RADIAL_CONTROL_DISPLAY_WIDTH;
2947                                                         if (snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
2948                                                         break;
2949                                                 case PROP_ANGLE:
2950                                                         new_value = atan2f(delta[1], delta[0]) + (float)M_PI + angle_precision;
2951                                                         new_value = fmod(new_value, 2.0f * (float)M_PI);
2952                                                         if (new_value < 0.0f)
2953                                                                 new_value += 2.0f * (float)M_PI;
2954                                                         if (snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10 * 10);
2955                                                         break;
2956                                                 default:
2957                                                         new_value = dist; /* dummy value, should this ever happen? - campbell */
2958                                                         break;
2959                                         }
2960
2961                                         /* clamp and update */
2962                                         CLAMP(new_value, rc->min_value, rc->max_value);
2963                                         radial_control_set_value(rc, new_value);
2964                                         rc->current_value = new_value;
2965                                         handled = true;
2966                                         break;
2967                                 }
2968                                 break;
2969
2970                         case LEFTSHIFTKEY:
2971                         case RIGHTSHIFTKEY:
2972                         {
2973                                 if (event->val == KM_PRESS) {
2974                                         rc->slow_mouse[0] = event->x;
2975                                         rc->slow_mouse[1] = event->y;
2976                                         rc->slow_mode = true;
2977                                         if (rc->subtype == PROP_ANGLE) {
2978                                                 float initial_position[2] = {UNPACK2(rc->initial_mouse)};
2979                                                 float current_position[2] = {UNPACK2(rc->slow_mouse)};
2980                                                 rc->dial = BLI_dial_initialize(initial_position, 0.0f);
2981                                                 /* immediately set the position to get a an initial direction */
2982                                                 BLI_dial_angle(rc->dial, current_position);
2983                                         }
2984                                         handled = true;
2985                                 }
2986                                 if (event->val == KM_RELEASE) {
2987                                         rc->slow_mode = false;
2988                                         handled = true;
2989                                         if (rc->dial) {
2990                                                 MEM_freeN(rc->dial);
2991                                                 rc->dial = NULL;
2992                                         }
2993                                 }
2994                                 break;
2995                         }
2996                 }
2997
2998                 /* Modal numinput inactive, try to handle numeric inputs last... */
2999                 if (!handled && event->val == KM_PRESS && handleNumInput(C, &rc->num_input, event)) {
3000                         applyNumInput(&rc->num_input, &numValue);
3001
3002                         if (rc->subtype == PROP_ANGLE) {
3003                                 numValue = DEG2RADF(numValue);
3004                                 numValue = fmod(numValue, 2.0f * (float)M_PI);
3005                                 if (numValue < 0.0f)
3006                                         numValue += 2.0f * (float)M_PI;
3007                         }
3008
3009                         CLAMP(numValue, rc->min_value, rc->max_value);
3010                         new_value = numValue;
3011                         
3012                         radial_control_set_value(rc, new_value);
3013                         
3014                         rc->current_value = new_value;
3015                         radial_control_update_header(op, C);
3016                         return OPERATOR_RUNNING_MODAL;
3017                 }
3018         }
3019
3020         ED_region_tag_redraw(CTX_wm_region(C));
3021         radial_control_update_header(op, C);
3022
3023         if (ret != OPERATOR_RUNNING_MODAL)
3024                 radial_control_cancel(C, op);
3025
3026         return ret;
3027 }
3028
3029 static void WM_OT_radial_control(wmOperatorType *ot)
3030 {
3031         ot->name = "Radial Control";
3032         ot->idname = "WM_OT_radial_control";
3033         ot->description = "Set some size property (like e.g. brush size) with mouse wheel";
3034
3035         ot->invoke = radial_control_invoke;
3036         ot->modal = radial_control_modal;
3037         ot->cancel = radial_control_cancel;
3038
3039         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
3040
3041         /* all paths relative to the context */
3042         PropertyRNA *prop;
3043         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");
3044         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3045
3046         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");
3047         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3048
3049         prop = RNA_def_string(ot->srna, "use_secondary", NULL, 0, "Use Secondary", "Path of property to select between the primary and secondary data paths");
3050         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3051
3052         prop = RNA_def_string(ot->srna, "rotation_path", NULL, 0, "Rotation Path", "Path of property used to rotate the texture display");
3053         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3054
3055         prop = RNA_def_string(ot->srna, "color_path", NULL, 0, "Color Path", "Path of property used to set the color of the control");
3056         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3057
3058         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");
3059         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3060
3061         prop = RNA_def_string(ot->srna, "fill_color_override_path", NULL, 0, "Fill Color Override Path", "");
3062         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3063         prop = RNA_def_string(ot->srna, "fill_color_override_test_path", NULL, 0, "Fill Color Override Test", "");
3064         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3065
3066         prop = RNA_def_string(ot->srna, "zoom_path", NULL, 0, "Zoom Path", "Path of property used to set the zoom level for the control");
3067         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3068
3069         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");
3070         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3071
3072         prop = RNA_def_boolean(ot->srna, "secondary_tex", false, "Secondary Texture", "Tweak brush secondary/mask texture");
3073         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3074 }
3075
3076 /* ************************** timer for testing ***************** */
3077
3078 /* uses no type defines, fully local testing function anyway... ;) */
3079
3080 static void redraw_timer_window_swap(bContext *C)
3081 {
3082         wmWindow *win = CTX_wm_window(C);
3083         ScrArea *sa;
3084         CTX_wm_menu_set(C, NULL);
3085
3086         for (sa = CTX_wm_screen(C)->areabase.first; sa; sa = sa->next)
3087                 ED_area_tag_redraw(sa);
3088         wm_draw_update(C);
3089
3090         CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
3091 }
3092
3093 enum {
3094         eRTDrawRegion = 0,
3095         eRTDrawRegionSwap = 1,
3096         eRTDrawWindow = 2,
3097         eRTDrawWindowSwap = 3,
3098         eRTAnimationStep = 4,
3099         eRTAnimationPlay = 5,
3100         eRTUndo = 6,
3101 };
3102
3103 static const EnumPropertyItem redraw_timer_type_items[] = {
3104         {eRTDrawRegion, "DRAW", 0, "Draw Region", "Draw Region"},
3105         {eRTDrawRegionSwap, "DRAW_SWAP", 0, "Draw Region + Swap", "Draw Region and Swap"},
3106         {eRTDrawWindow, "DRAW_WIN", 0, "Draw Window", "Draw Window"},
3107         {eRTDrawWindowSwap, "DRAW_WIN_SWAP", 0, "Draw Window + Swap", "Draw Window and Swap"},
3108         {eRTAnimationStep, "ANIM_STEP", 0, "Anim Step", "Animation Steps"},
3109         {eRTAnimationPlay, "ANIM_PLAY", 0, "Anim Play", "Animation Playback"},
3110         {eRTUndo, "UNDO", 0, "Undo/Redo", "Undo/Redo"},
3111         {0, NULL, 0, NULL, NULL}
3112 };
3113
3114
3115 static void redraw_timer_step(
3116         bContext *C, Main *bmain, Scene *scene,
3117         wmWindow *win, ScrArea *sa, ARegion *ar,
3118         const int type, const int cfra)
3119 {
3120         if (type == eRTDrawRegion) {
3121                 if (ar) {
3122                         ED_region_do_draw(C, ar);
3123                         ar->do_draw = false;
3124                 }
3125         }
3126         else if (type == eRTDrawRegionSwap) {
3127                 CTX_wm_menu_set(C, NULL);
3128
3129                 ED_region_tag_redraw(ar);
3130                 wm_draw_update(C);
3131
3132                 CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
313