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