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