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