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