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