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