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