45084980727d3e3aef99f7a90045fdd36ba17de0
[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 original 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, there's 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         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_POPUP);
772
773         search[0] = '\0';
774 #if 0 /* ok, this isn't so easy... */
775         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, "");
776 #endif
777         but = uiDefSearchButO_ptr(block, op->type, op->ptr->data, search, 0, ICON_VIEWZOOM, sizeof(search),
778                                   10, 10, UI_searchbox_size_x(), UI_UNIT_Y, 0, 0, "");
779
780         /* fake button, it holds space for search items */
781         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);
782
783         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
784
785         wm_event_init_from_window(win, &event);
786         event.type = EVT_BUT_OPEN;
787         event.val = KM_PRESS;
788         event.customdata = but;
789         event.customdatafree = false;
790         wm_event_add(win, &event);
791
792         return block;
793 }
794
795
796 int WM_enum_search_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
797 {
798         UI_popup_block_invoke(C, wm_enum_search_menu, op);
799         return OPERATOR_INTERFACE;
800 }
801
802 /* Can't be used as an invoke directly, needs message arg (can be NULL) */
803 int WM_operator_confirm_message_ex(bContext *C, wmOperator *op,
804                                    const char *title, const int icon,
805                                    const char *message)
806 {
807         uiPopupMenu *pup;
808         uiLayout *layout;
809         IDProperty *properties = op->ptr->data;
810
811         if (properties && properties->len)
812                 properties = IDP_CopyProperty(op->ptr->data);
813         else
814                 properties = NULL;
815
816         pup = UI_popup_menu_begin(C, title, icon);
817         layout = UI_popup_menu_layout(pup);
818         uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0, NULL);
819         UI_popup_menu_end(C, pup);
820
821         return OPERATOR_INTERFACE;
822 }
823
824 int WM_operator_confirm_message(bContext *C, wmOperator *op, const char *message)
825 {
826         return WM_operator_confirm_message_ex(C, op, IFACE_("OK?"), ICON_QUESTION, message);
827 }
828
829 int WM_operator_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
830 {
831         return WM_operator_confirm_message(C, op, NULL);
832 }
833
834 /* op->invoke, opens fileselect if path property not set, otherwise executes */
835 int WM_operator_filesel(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
836 {
837         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
838                 return WM_operator_call_notest(C, op); /* call exec direct */
839         }
840         else {
841                 WM_event_add_fileselect(C, op);
842                 return OPERATOR_RUNNING_MODAL;
843         }
844 }
845
846 bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const struct ImageFormatData *im_format)
847 {
848         PropertyRNA *prop;
849         char filepath[FILE_MAX];
850         /* dont NULL check prop, this can only run on ops with a 'filepath' */
851         prop = RNA_struct_find_property(op->ptr, "filepath");
852         RNA_property_string_get(op->ptr, prop, filepath);
853         if (BKE_image_path_ensure_ext_from_imformat(filepath, im_format)) {
854                 RNA_property_string_set(op->ptr, prop, filepath);
855                 /* note, we could check for and update 'filename' here,
856                  * but so far nothing needs this. */
857                 return true;
858         }
859         return false;
860 }
861
862 /* op->poll */
863 bool WM_operator_winactive(bContext *C)
864 {
865         if (CTX_wm_window(C) == NULL) return 0;
866         return 1;
867 }
868
869 /* return false, if the UI should be disabled */
870 bool WM_operator_check_ui_enabled(const bContext *C, const char *idname)
871 {
872         wmWindowManager *wm = CTX_wm_manager(C);
873         Scene *scene = CTX_data_scene(C);
874
875         return !((ED_undo_is_valid(C, idname) == false) || WM_jobs_test(wm, scene, WM_JOB_TYPE_ANY));
876 }
877
878 wmOperator *WM_operator_last_redo(const bContext *C)
879 {
880         wmWindowManager *wm = CTX_wm_manager(C);
881         wmOperator *op;
882
883         /* only for operators that are registered and did an undo push */
884         for (op = wm->operators.last; op; op = op->prev)
885                 if ((op->type->flag & OPTYPE_REGISTER) && (op->type->flag & OPTYPE_UNDO))
886                         break;
887
888         return op;
889 }
890
891 /**
892  * Use for drag & drop a path or name with operators invoke() function.
893  */
894 ID *WM_operator_drop_load_path(struct bContext *C, wmOperator *op, const short idcode)
895 {
896         Main *bmain = CTX_data_main(C);
897         ID *id = NULL;
898         /* check input variables */
899         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
900                 const bool is_relative_path = RNA_boolean_get(op->ptr, "relative_path");
901                 char path[FILE_MAX];
902                 bool exists = false;
903
904                 RNA_string_get(op->ptr, "filepath", path);
905
906                 errno = 0;
907
908                 if (idcode == ID_IM) {
909                         id = (ID *)BKE_image_load_exists_ex(bmain, path, &exists);
910                 }
911                 else {
912                         BLI_assert(0);
913                 }
914
915                 if (!id) {
916                         BKE_reportf(op->reports, RPT_ERROR, "Cannot read %s '%s': %s",
917                                     BKE_idcode_to_name(idcode), path,
918                                     errno ? strerror(errno) : TIP_("unsupported format"));
919                         return NULL;
920                 }
921
922                 if (is_relative_path ) {
923                         if (exists == false) {
924                                 if (idcode == ID_IM) {
925                                         BLI_path_rel(((Image *)id)->name, BKE_main_blendfile_path(bmain));
926                                 }
927                                 else {
928                                         BLI_assert(0);
929                                 }
930                         }
931                 }
932         }
933         else if (RNA_struct_property_is_set(op->ptr, "name")) {
934                 char name[MAX_ID_NAME - 2];
935                 RNA_string_get(op->ptr, "name", name);
936                 id = BKE_libblock_find_name(bmain, idcode, name);
937                 if (!id) {
938                         BKE_reportf(op->reports, RPT_ERROR, "%s '%s' not found",
939                                     BKE_idcode_to_name(idcode), name);
940                         return NULL;
941                 }
942                 id_us_plus(id);
943         }
944
945         return id;
946 }
947
948 static void wm_block_redo_cb(bContext *C, void *arg_op, int UNUSED(arg_event))
949 {
950         wmOperator *op = arg_op;
951
952         if (op == WM_operator_last_redo(C)) {
953                 /* operator was already executed once? undo & repeat */
954                 ED_undo_operator_repeat(C, op);
955         }
956         else {
957                 /* operator not executed yet, call it */
958                 ED_undo_push_op(C, op);
959                 wm_operator_register(C, op);
960
961                 WM_operator_repeat(C, op);
962         }
963 }
964
965 static void wm_block_redo_cancel_cb(bContext *C, void *arg_op)
966 {
967         wmOperator *op = arg_op;
968
969         /* if operator never got executed, free it */
970         if (op != WM_operator_last_redo(C))
971                 WM_operator_free(op);
972 }
973
974 static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
975 {
976         wmOperator *op = arg_op;
977         uiBlock *block;
978         uiLayout *layout;
979         uiStyle *style = UI_style_get();
980         int width = 15 * UI_UNIT_X;
981
982         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
983         UI_block_flag_disable(block, UI_BLOCK_LOOP);
984         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_REGULAR);
985
986         /* UI_BLOCK_NUMSELECT for layer buttons */
987         UI_block_flag_enable(block, UI_BLOCK_NUMSELECT | UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
988
989         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
990          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
991         assert(op->type->flag & OPTYPE_REGISTER);
992
993         UI_block_func_handle_set(block, wm_block_redo_cb, arg_op);
994         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, 0, style);
995
996         if (op == WM_operator_last_redo(C))
997                 if (!WM_operator_check_ui_enabled(C, op->type->name))
998                         uiLayoutSetEnabled(layout, false);
999
1000         if (op->type->flag & OPTYPE_MACRO) {
1001                 for (op = op->macro.first; op; op = op->next) {
1002                         uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1003                         if (op->next)
1004                                 uiItemS(layout);
1005                 }
1006         }
1007         else {
1008                 uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1009         }
1010
1011         UI_block_bounds_set_popup(block, 4, 0, 0);
1012
1013         return block;
1014 }
1015
1016 typedef struct wmOpPopUp {
1017         wmOperator *op;
1018         int width;
1019         int height;
1020         int free_op;
1021 } wmOpPopUp;
1022
1023 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1024 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1025 {
1026         wmOpPopUp *data = arg1;
1027         uiBlock *block = arg2;
1028
1029         /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be canceled
1030          * in case WM_operator_call_ex exits/reloads the current file (T49199). */
1031         UI_popup_menu_retval_set(block, UI_RETURN_OK, true);
1032
1033         WM_operator_call_ex(C, data->op, true);
1034
1035         /* let execute handle freeing it */
1036         //data->free_op = false;
1037         //data->op = NULL;
1038
1039         /* in this case, wm_operator_ui_popup_cancel wont run */
1040         MEM_freeN(data);
1041
1042         /* get context data *after* WM_operator_call_ex which might have closed the current file and changed context */
1043         wmWindowManager *wm = CTX_wm_manager(C);
1044         wmWindow *win = CTX_wm_window(C);
1045
1046         /* check window before 'block->handle' incase the
1047          * popup execution closed the window and freed the block. see T44688.
1048          */
1049         /* Post 2.78 TODO: Check if this fix and others related to T44688 are still
1050          * needed or can be improved now that requesting context data has been corrected
1051          * (see above). We're close to release so not a good time for experiments.
1052          * -- Julian
1053          */
1054         if (BLI_findindex(&wm->windows, win) != -1) {
1055                 UI_popup_block_close(C, win, block);
1056         }
1057 }
1058
1059 /* Dialogs are popups that require user verification (click OK) before exec */
1060 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1061 {
1062         wmOpPopUp *data = userData;
1063         wmOperator *op = data->op;
1064         uiBlock *block;
1065         uiLayout *layout;
1066         uiStyle *style = UI_style_get();
1067
1068         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1069         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1070         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_REGULAR);
1071
1072         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogues have many items
1073          * where quitting by accident is very annoying */
1074         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NUMSELECT);
1075
1076         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1077
1078         uiTemplateOperatorPropertyButs(C, layout, op, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
1079
1080         /* clear so the OK button is left alone */
1081         UI_block_func_set(block, NULL, NULL, NULL);
1082
1083         /* new column so as not to interfere with custom layouts [#26436] */
1084         {
1085                 uiBlock *col_block;
1086                 uiLayout *col;
1087                 uiBut *btn;
1088
1089                 col = uiLayoutColumn(layout, false);
1090                 col_block = uiLayoutGetBlock(col);
1091                 /* Create OK button, the callback of which will execute op */
1092                 btn = uiDefBut(col_block, UI_BTYPE_BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1093                 UI_but_func_set(btn, dialog_exec_cb, data, col_block);
1094         }
1095
1096         /* center around the mouse */
1097         UI_block_bounds_set_popup(block, 4, data->width / -2, data->height / 2);
1098
1099         return block;
1100 }
1101
1102 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1103 {
1104         wmOpPopUp *data = userData;
1105         wmOperator *op = data->op;
1106         uiBlock *block;
1107         uiLayout *layout;
1108         uiStyle *style = UI_style_get();
1109
1110         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1111         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1112         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1113         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_REGULAR);
1114
1115         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1116
1117         /* since ui is defined the auto-layout args are not used */
1118         uiTemplateOperatorPropertyButs(C, layout, op, 'V', 0);
1119
1120         UI_block_func_set(block, NULL, NULL, NULL);
1121
1122         UI_block_bounds_set_popup(block, 4, 0, 0);
1123
1124         return block;
1125 }
1126
1127 static void wm_operator_ui_popup_cancel(struct bContext *C, void *userData)
1128 {
1129         wmOpPopUp *data = userData;
1130         wmOperator *op = data->op;
1131
1132         if (op) {
1133                 if (op->type->cancel) {
1134                         op->type->cancel(C, op);
1135                 }
1136
1137                 if (data->free_op) {
1138                         WM_operator_free(op);
1139                 }
1140         }
1141
1142         MEM_freeN(data);
1143 }
1144
1145 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1146 {
1147         wmOpPopUp *data = arg;
1148         wmOperator *op = data->op;
1149
1150         if (op && retval > 0)
1151                 WM_operator_call_ex(C, op, true);
1152
1153         MEM_freeN(data);
1154 }
1155
1156 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1157 {
1158         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1159         data->op = op;
1160         data->width = width;
1161         data->height = height;
1162         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1163         UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data, op);
1164         return OPERATOR_RUNNING_MODAL;
1165 }
1166
1167 /**
1168  * For use by #WM_operator_props_popup_call, #WM_operator_props_popup only.
1169  *
1170  * \note operator menu needs undo flag enabled, for redo callback */
1171 static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
1172                                       const bool do_call, const bool do_redo)
1173 {
1174         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1175                 BKE_reportf(op->reports, RPT_ERROR,
1176                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1177                 return OPERATOR_CANCELLED;
1178         }
1179
1180         if (do_redo) {
1181                 if ((op->type->flag & OPTYPE_UNDO) == 0) {
1182                         BKE_reportf(op->reports, RPT_ERROR,
1183                                     "Operator '%s' does not have undo enabled, incorrect invoke function", op->type->idname);
1184                         return OPERATOR_CANCELLED;
1185                 }
1186         }
1187
1188         /* if we don't have global undo, we can't do undo push for automatic redo,
1189          * so we require manual OK clicking in this popup */
1190         if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
1191                 return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
1192
1193         UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op, op);
1194
1195         if (do_call)
1196                 wm_block_redo_cb(C, op, 0);
1197
1198         return OPERATOR_RUNNING_MODAL;
1199 }
1200
1201 /**
1202  * Same as #WM_operator_props_popup but don't use operator redo.
1203  * just wraps #WM_operator_props_dialog_popup.
1204  */
1205 int WM_operator_props_popup_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1206 {
1207         return wm_operator_props_popup_ex(C, op, false, false);
1208 }
1209
1210 /**
1211  * Same as #WM_operator_props_popup but call the operator first,
1212  * This way - the button values correspond to the result of the operator.
1213  * Without this, first access to a button will make the result jump, see T32452.
1214  */
1215 int WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1216 {
1217         return wm_operator_props_popup_ex(C, op, true, true);
1218 }
1219
1220 int WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1221 {
1222         return wm_operator_props_popup_ex(C, op, false, true);
1223 }
1224
1225 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1226 {
1227         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1228
1229         data->op = op;
1230         data->width = width;
1231         data->height = height;
1232         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1233
1234         /* op is not executed until popup OK but is clicked */
1235         UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data, op);
1236
1237         return OPERATOR_RUNNING_MODAL;
1238 }
1239
1240 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1241 {
1242         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1243         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1244                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1245                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1246                 return OPERATOR_CANCELLED;
1247         }
1248         if (op->type->poll && op->type->poll(C) == 0) {
1249                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1250                 return OPERATOR_CANCELLED;
1251         }
1252
1253         UI_popup_block_invoke(C, wm_block_create_redo, op);
1254
1255         return OPERATOR_CANCELLED;
1256 }
1257
1258 /* ***************** Debug menu ************************* */
1259
1260 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1261 {
1262         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1263         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1264         WM_event_add_notifier(C, NC_WINDOW, NULL);
1265
1266         return OPERATOR_FINISHED;
1267 }
1268
1269 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1270 {
1271         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1272         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1273 }
1274
1275 static void WM_OT_debug_menu(wmOperatorType *ot)
1276 {
1277         ot->name = "Debug Menu";
1278         ot->idname = "WM_OT_debug_menu";
1279         ot->description = "Open a popup to set the debug level";
1280
1281         ot->invoke = wm_debug_menu_invoke;
1282         ot->exec = wm_debug_menu_exec;
1283         ot->poll = WM_operator_winactive;
1284
1285         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1286 }
1287
1288 /* ***************** Operator defaults ************************* */
1289 static int wm_operator_defaults_exec(bContext *C, wmOperator *op)
1290 {
1291         PointerRNA ptr = CTX_data_pointer_get_type(C, "active_operator", &RNA_Operator);
1292
1293         if (!ptr.data) {
1294                 BKE_report(op->reports, RPT_ERROR, "No operator in context");
1295                 return OPERATOR_CANCELLED;
1296         }
1297
1298         WM_operator_properties_reset((wmOperator *)ptr.data);
1299         return OPERATOR_FINISHED;
1300 }
1301
1302 /* used by operator preset menu. pre-2.65 this was a 'Reset' button */
1303 static void WM_OT_operator_defaults(wmOperatorType *ot)
1304 {
1305         ot->name = "Restore Defaults";
1306         ot->idname = "WM_OT_operator_defaults";
1307         ot->description = "Set the active operator to its default values";
1308
1309         ot->exec = wm_operator_defaults_exec;
1310
1311         ot->flag = OPTYPE_INTERNAL;
1312 }
1313
1314 /* ***************** Splash Screen ************************* */
1315
1316 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1317 {
1318         wmWindow *win = CTX_wm_window(C);
1319         UI_popup_block_close(C, win, arg_block);
1320 }
1321
1322 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1323
1324 static void wm_block_splash_refreshmenu(bContext *C, void *UNUSED(arg_block), void *UNUSED(arg))
1325 {
1326         ARegion *ar_menu = CTX_wm_menu(C);
1327         ED_region_tag_refresh_ui(ar_menu);
1328 }
1329
1330 static int wm_resource_check_prev(void)
1331 {
1332
1333         const char *res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, true);
1334
1335         // if (res) printf("USER: %s\n", res);
1336
1337 #if 0 /* ignore the local folder */
1338         if (res == NULL) {
1339                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1340                 res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, true);
1341         }
1342 #endif
1343
1344         // if (res) printf("LOCAL: %s\n", res);
1345         if (res) {
1346                 return false;
1347         }
1348         else {
1349                 return (BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, true) != NULL);
1350         }
1351 }
1352
1353 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1354 {
1355         uiBlock *block;
1356         uiBut *but;
1357         uiLayout *layout, *split, *col;
1358         uiStyle *style = UI_style_get();
1359         const struct RecentFile *recent;
1360         int i;
1361         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", true);
1362         char url[96];
1363         const char *version_suffix = NULL;
1364
1365 #ifndef WITH_HEADLESS
1366         extern char datatoc_splash_png[];
1367         extern int datatoc_splash_png_size;
1368
1369         extern char datatoc_splash_2x_png[];
1370         extern int datatoc_splash_2x_png_size;
1371         ImBuf *ibuf;
1372 #else
1373         ImBuf *ibuf = NULL;
1374 #endif
1375
1376 #ifdef WITH_BUILDINFO
1377         int label_delta = 0;
1378         int hash_width, date_width;
1379         char date_buf[128] = "\0";
1380         char hash_buf[128] = "\0";
1381         extern unsigned long build_commit_timestamp;
1382         extern char build_hash[], build_commit_date[], build_commit_time[], build_branch[];
1383
1384         /* Builds made from tag only shows tag sha */
1385         BLI_snprintf(hash_buf, sizeof(hash_buf), "Hash: %s", build_hash);
1386         BLI_snprintf(date_buf, sizeof(date_buf), "Date: %s %s", build_commit_date, build_commit_time);
1387
1388         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.pixelsize * U.dpi);
1389         hash_width = (int)BLF_width(style->widgetlabel.uifont_id, hash_buf, sizeof(hash_buf)) + U.widget_unit;
1390         date_width = (int)BLF_width(style->widgetlabel.uifont_id, date_buf, sizeof(date_buf)) + U.widget_unit;
1391 #endif  /* WITH_BUILDINFO */
1392
1393 #ifndef WITH_HEADLESS
1394         if (U.pixelsize == 2) {
1395                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_2x_png,
1396                                              datatoc_splash_2x_png_size, IB_rect, NULL, "<splash screen>");
1397         }
1398         else {
1399                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1400                                              datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1401         }
1402
1403         /* overwrite splash with template image */
1404         if (U.app_template[0] != '\0') {
1405                 ImBuf *ibuf_template = NULL;
1406                 char splash_filepath[FILE_MAX];
1407                 char template_directory[FILE_MAX];
1408
1409                 if (BKE_appdir_app_template_id_search(
1410                         U.app_template,
1411                         template_directory, sizeof(template_directory)))
1412                 {
1413                         BLI_join_dirfile(
1414                                 splash_filepath, sizeof(splash_filepath), template_directory,
1415                                 (U.pixelsize == 2) ? "splash_2x.png" : "splash.png");
1416                         ibuf_template = IMB_loadiffname(splash_filepath, IB_rect, NULL);
1417                         if (ibuf_template) {
1418                                 const int x_expect = ibuf->x;
1419                                 const int y_expect = 230 * (int)U.pixelsize;
1420                                 /* don't cover the header text */
1421                                 if (ibuf_template->x == x_expect && ibuf_template->y == y_expect) {
1422                                         memcpy(ibuf->rect, ibuf_template->rect, ibuf_template->x * ibuf_template->y * sizeof(char[4]));
1423                                 }
1424                                 else {
1425                                         CLOG_ERROR(WM_LOG_OPERATORS,
1426                                                    "Splash expected %dx%d found %dx%d, ignoring: %s\n",
1427                                                    x_expect, y_expect, ibuf_template->x, ibuf_template->y, splash_filepath);
1428                                 }
1429                                 IMB_freeImBuf(ibuf_template);
1430                         }
1431                 }
1432         }
1433 #endif
1434
1435         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1436
1437         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1438          * with the OS when the splash shows, window clipping in this case gives
1439          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1440         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1441         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_POPUP);
1442
1443         /* XXX splash scales with pixelsize, should become widget-units */
1444         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 */
1445         UI_but_func_set(but, wm_block_splash_close, block, NULL);
1446         UI_block_func_set(block, wm_block_splash_refreshmenu, block, NULL);
1447
1448         /* label for 'a' bugfix releases, or 'Release Candidate 1'...
1449          *  avoids recreating splash for version updates */
1450         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "rc")) {
1451                 version_suffix = "Release Candidate";
1452         }
1453         else if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1454                 version_suffix = STRINGIFY(BLENDER_VERSION_CHAR);
1455         }
1456         if (version_suffix != NULL && version_suffix[0]) {
1457                 /* placed after the version number in the image,
1458                  * placing y is tricky to match baseline */
1459                 int x = 260 * U.pixelsize - (2 * UI_DPI_FAC);
1460                 int y = 242 * U.pixelsize + (4 * UI_DPI_FAC);
1461                 int w = 240 * U.pixelsize;
1462
1463                 /* hack to have text draw 'text_sel' */
1464                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1465                 but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x, y, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1466                 /* XXX, set internal flag - UI_SELECT */
1467                 UI_but_flag_enable(but, 1);
1468                 UI_block_emboss_set(block, UI_EMBOSS);
1469         }
1470
1471 #ifdef WITH_BUILDINFO
1472         if (build_commit_timestamp != 0) {
1473                 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);
1474                 label_delta = 12;
1475         }
1476         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);
1477
1478         if (!STREQ(build_branch, "master")) {
1479                 char branch_buf[128] = "\0";
1480                 int branch_width;
1481                 BLI_snprintf(branch_buf, sizeof(branch_buf), "Branch: %s", build_branch);
1482                 branch_width = (int)BLF_width(style->widgetlabel.uifont_id, branch_buf, sizeof(branch_buf)) + U.widget_unit;
1483                 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);
1484         }
1485 #endif  /* WITH_BUILDINFO */
1486
1487         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.pixelsize * 480, U.pixelsize * 110, 0, style);
1488
1489         UI_block_emboss_set(block, UI_EMBOSS);
1490         /* show the splash menu (containing interaction presets), using python */
1491         if (mt) {
1492                 UI_menutype_draw(C, mt, layout);
1493
1494 //              uiItemM(layout, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
1495         }
1496
1497         UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN);
1498         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
1499
1500         split = uiLayoutSplit(layout, 0.0f, false);
1501         col = uiLayoutColumn(split, false);
1502         uiItemL(col, IFACE_("Links"), ICON_NONE);
1503 #if 0
1504         uiItemStringO(col, IFACE_("Support an Open Animation Movie"), ICON_URL, "WM_OT_url_open", "url",
1505                       "https://cloud.blender.org/join");
1506 #endif
1507         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url",
1508                       "http://www.blender.org/foundation/donation-payment/");
1509         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url",
1510                       "http://www.blender.org/about/credits/");
1511         BLI_snprintf(url, sizeof(url), "http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/%d.%d",
1512                      BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1513         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", url);
1514         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url",
1515                       "https://docs.blender.org/manual/en/dev/");
1516         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
1517         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1518                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/%d.%d"STRINGIFY(BLENDER_VERSION_CHAR),
1519                              BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1520         }
1521         else {
1522                 BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/master");
1523         }
1524         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
1525         uiItemL(col, "", ICON_NONE);
1526
1527         col = uiLayoutColumn(split, false);
1528
1529         if (wm_resource_check_prev()) {
1530                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
1531                 uiItemS(col);
1532         }
1533
1534         uiItemL(col, IFACE_("Recent"), ICON_NONE);
1535         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
1536                 const char *filename = BLI_path_basename(recent->filepath);
1537                 uiItemStringO(col, filename,
1538                               BLO_has_bfile_extension(filename) ? ICON_FILE_BLEND : ICON_FILE_BACKUP,
1539                               "WM_OT_open_mainfile", "filepath", recent->filepath);
1540         }
1541
1542         uiItemS(col);
1543         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
1544         uiItemL(col, "", ICON_NONE);
1545
1546         mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
1547         if (mt) {
1548                 UI_menutype_draw(C, mt, uiLayoutColumn(layout, false));
1549         }
1550
1551         UI_block_bounds_set_centered(block, 0);
1552
1553         return block;
1554 }
1555
1556 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
1557 {
1558         UI_popup_block_invoke(C, wm_block_create_splash, NULL);
1559
1560         return OPERATOR_FINISHED;
1561 }
1562
1563 static void WM_OT_splash(wmOperatorType *ot)
1564 {
1565         ot->name = "Splash Screen";
1566         ot->idname = "WM_OT_splash";
1567         ot->description = "Open the splash screen with release info";
1568
1569         ot->invoke = wm_splash_invoke;
1570         ot->poll = WM_operator_winactive;
1571 }
1572
1573
1574 /* ***************** Search menu ************************* */
1575
1576 struct SearchPopupInit_Data {
1577         int size[2];
1578 };
1579
1580 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *userdata)
1581 {
1582         const struct SearchPopupInit_Data *init_data = userdata;
1583         static char search[256] = "";
1584         wmEvent event;
1585         wmWindow *win = CTX_wm_window(C);
1586         uiBlock *block;
1587         uiBut *but;
1588
1589         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1590         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
1591         UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_POPUP);
1592
1593         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, init_data->size[0], UI_UNIT_Y, 0, 0, "");
1594         UI_but_func_operator_search(but);
1595
1596         /* fake button, it holds space for search items */
1597         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - init_data->size[1],
1598                  init_data->size[0], init_data->size[1], NULL, 0, 0, 0, 0, NULL);
1599
1600         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1601
1602         wm_event_init_from_window(win, &event);
1603         event.type = EVT_BUT_OPEN;
1604         event.val = KM_PRESS;
1605         event.customdata = but;
1606         event.customdatafree = false;
1607         wm_event_add(win, &event);
1608
1609         return block;
1610 }
1611
1612 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1613 {
1614         return OPERATOR_FINISHED;
1615 }
1616
1617 static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
1618 {
1619         struct SearchPopupInit_Data data = {
1620                 .size = {
1621                     UI_searchbox_size_x() * 2,
1622                     UI_searchbox_size_y(),
1623                 },
1624         };
1625
1626         UI_popup_block_invoke(C, wm_block_search_menu, &data);
1627
1628         return OPERATOR_INTERFACE;
1629 }
1630
1631 /* op->poll */
1632 static bool wm_search_menu_poll(bContext *C)
1633 {
1634         if (CTX_wm_window(C) == NULL) {
1635                 return 0;
1636         }
1637         else {
1638                 ScrArea *sa = CTX_wm_area(C);
1639                 if (sa) {
1640                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
1641                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
1642                 }
1643                 else {
1644                         Object *editob = CTX_data_edit_object(C);
1645                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
1646                 }
1647         }
1648         return 1;
1649 }
1650
1651 static void WM_OT_search_menu(wmOperatorType *ot)
1652 {
1653         ot->name = "Search Menu";
1654         ot->idname = "WM_OT_search_menu";
1655         ot->description = "Pop-up a search menu over all available operators in current context";
1656
1657         ot->invoke = wm_search_menu_invoke;
1658         ot->exec = wm_search_menu_exec;
1659         ot->poll = wm_search_menu_poll;
1660 }
1661
1662 static int wm_call_menu_exec(bContext *C, wmOperator *op)
1663 {
1664         char idname[BKE_ST_MAXNAME];
1665         RNA_string_get(op->ptr, "name", idname);
1666
1667         return UI_popup_menu_invoke(C, idname, op->reports);
1668 }
1669
1670 static void WM_OT_call_menu(wmOperatorType *ot)
1671 {
1672         ot->name = "Call Menu";
1673         ot->idname = "WM_OT_call_menu";
1674         ot->description = "Call (draw) a pre-defined menu";
1675
1676         ot->exec = wm_call_menu_exec;
1677         ot->poll = WM_operator_winactive;
1678
1679         ot->flag = OPTYPE_INTERNAL;
1680
1681         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
1682 }
1683
1684 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1685 {
1686         char idname[BKE_ST_MAXNAME];
1687         RNA_string_get(op->ptr, "name", idname);
1688
1689         return UI_pie_menu_invoke(C, idname, event);
1690 }
1691
1692 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
1693 {
1694         char idname[BKE_ST_MAXNAME];
1695         RNA_string_get(op->ptr, "name", idname);
1696
1697         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
1698 }
1699
1700 static void WM_OT_call_menu_pie(wmOperatorType *ot)
1701 {
1702         ot->name = "Call Pie Menu";
1703         ot->idname = "WM_OT_call_menu_pie";
1704         ot->description = "Call (draw) a pre-defined pie menu";
1705
1706         ot->invoke = wm_call_pie_menu_invoke;
1707         ot->exec = wm_call_pie_menu_exec;
1708         ot->poll = WM_operator_winactive;
1709
1710         ot->flag = OPTYPE_INTERNAL;
1711
1712         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
1713 }
1714
1715 /* ************ window / screen operator definitions ************** */
1716
1717 /* this poll functions is needed in place of WM_operator_winactive
1718  * while it crashes on full screen */
1719 static bool wm_operator_winactive_normal(bContext *C)
1720 {
1721         wmWindow *win = CTX_wm_window(C);
1722
1723         if (win == NULL || win->screen == NULL || win->screen->state != SCREENNORMAL)
1724                 return 0;
1725
1726         return 1;
1727 }
1728
1729 /* included for script-access */
1730 static void WM_OT_window_close(wmOperatorType *ot)
1731 {
1732         ot->name = "Close Window";
1733         ot->idname = "WM_OT_window_close";
1734         ot->description = "Close the current Blender window";
1735
1736         ot->exec = wm_window_close_exec;
1737         ot->poll = WM_operator_winactive;
1738 }
1739
1740 static void WM_OT_window_duplicate(wmOperatorType *ot)
1741 {
1742         ot->name = "Duplicate Window";
1743         ot->idname = "WM_OT_window_duplicate";
1744         ot->description = "Duplicate the current Blender window";
1745
1746         ot->exec = wm_window_duplicate_exec;
1747         ot->poll = wm_operator_winactive_normal;
1748 }
1749
1750 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
1751 {
1752         ot->name = "Toggle Window Fullscreen";
1753         ot->idname = "WM_OT_window_fullscreen_toggle";
1754         ot->description = "Toggle the current window fullscreen";
1755
1756         ot->exec = wm_window_fullscreen_toggle_exec;
1757         ot->poll = WM_operator_winactive;
1758 }
1759
1760 static int wm_exit_blender_exec(bContext *C, wmOperator *UNUSED(op))
1761 {
1762         wm_quit_with_optional_confirmation_prompt(C, CTX_wm_window(C));
1763         return OPERATOR_FINISHED;
1764 }
1765
1766 static int wm_exit_blender_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1767 {
1768         if (U.uiflag & USER_QUIT_PROMPT) {
1769                 return wm_exit_blender_exec(C, op);
1770         }
1771         else {
1772                 return WM_operator_confirm(C, op, event);
1773         }
1774 }
1775
1776 static void WM_OT_quit_blender(wmOperatorType *ot)
1777 {
1778         ot->name = "Quit Blender";
1779         ot->idname = "WM_OT_quit_blender";
1780         ot->description = "Quit Blender";
1781
1782         ot->invoke = wm_exit_blender_invoke;
1783         ot->exec = wm_exit_blender_exec;
1784 }
1785
1786 /* *********************** */
1787
1788 #if defined(WIN32)
1789
1790 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1791 {
1792         GHOST_toggleConsole(2);
1793         return OPERATOR_FINISHED;
1794 }
1795
1796 static void WM_OT_console_toggle(wmOperatorType *ot)
1797 {
1798         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
1799         ot->name = CTX_N_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
1800         ot->idname = "WM_OT_console_toggle";
1801         ot->description = N_("Toggle System Console");
1802
1803         ot->exec = wm_console_toggle_exec;
1804         ot->poll = WM_operator_winactive;
1805 }
1806
1807 #endif
1808
1809 /* ************ default paint cursors, draw always around cursor *********** */
1810 /*
1811  * - returns handler to free
1812  * - poll(bContext): returns 1 if draw should happen
1813  * - draw(bContext): drawing callback for paint cursor
1814  */
1815
1816 void *WM_paint_cursor_activate(
1817         wmWindowManager *wm, bool (*poll)(bContext *C),
1818         wmPaintCursorDraw draw, void *customdata)
1819 {
1820         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
1821
1822         BLI_addtail(&wm->paintcursors, pc);
1823
1824         pc->customdata = customdata;
1825         pc->poll = poll;
1826         pc->draw = draw;
1827
1828         return pc;
1829 }
1830
1831 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
1832 {
1833         wmPaintCursor *pc;
1834
1835         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
1836                 if (pc == (wmPaintCursor *)handle) {
1837                         BLI_remlink(&wm->paintcursors, pc);
1838                         MEM_freeN(pc);
1839                         return;
1840                 }
1841         }
1842 }
1843
1844 /* *********************** radial control ****************** */
1845
1846 #define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
1847 #define WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE (35 * UI_DPI_FAC)
1848 #define WM_RADIAL_CONTROL_DISPLAY_WIDTH (WM_RADIAL_CONTROL_DISPLAY_SIZE - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE)
1849 #define WM_RADIAL_MAX_STR 10
1850
1851 typedef struct {
1852         PropertyType type;
1853         PropertySubType subtype;
1854         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
1855         PointerRNA fill_col_override_ptr, fill_col_override_test_ptr;
1856         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
1857         PropertyRNA *fill_col_override_prop, *fill_col_override_test_prop;
1858         StructRNA *image_id_srna;
1859         float initial_value, current_value, min_value, max_value;
1860         int initial_mouse[2];
1861         int slow_mouse[2];
1862         bool slow_mode;
1863         Dial *dial;
1864         unsigned int gltex;
1865         ListBase orig_paintcursors;
1866         bool use_secondary_tex;
1867         void *cursor;
1868         NumInput num_input;
1869 } RadialControl;
1870
1871 static void radial_control_update_header(wmOperator *op, bContext *C)
1872 {
1873         RadialControl *rc = op->customdata;
1874         char msg[UI_MAX_DRAW_STR];
1875         ScrArea *sa = CTX_wm_area(C);
1876         Scene *scene = CTX_data_scene(C);
1877
1878         if (sa) {
1879                 if (hasNumInput(&rc->num_input)) {
1880                         char num_str[NUM_STR_REP_LEN];
1881                         outputNumInput(&rc->num_input, num_str, &scene->unit);
1882                         BLI_snprintf(msg, sizeof(msg), "%s: %s", RNA_property_ui_name(rc->prop), num_str);
1883                 }
1884                 else {
1885                         const char *ui_name = RNA_property_ui_name(rc->prop);
1886                         switch (rc->subtype) {
1887                                 case PROP_NONE:
1888                                 case PROP_DISTANCE:
1889                                         BLI_snprintf(msg, sizeof(msg), "%s: %0.4f", ui_name, rc->current_value);
1890                                         break;
1891                                 case PROP_PIXEL:
1892                                         BLI_snprintf(msg, sizeof(msg), "%s: %d", ui_name, (int)rc->current_value); /* XXX: round to nearest? */
1893                                         break;
1894                                 case PROP_PERCENTAGE:
1895                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.1f%%", ui_name, rc->current_value);
1896                                         break;
1897                                 case PROP_FACTOR:
1898                                         BLI_snprintf(msg, sizeof(msg), "%s: %1.3f", ui_name, rc->current_value);
1899                                         break;
1900                                 case PROP_ANGLE:
1901                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.2f", ui_name, RAD2DEGF(rc->current_value));
1902                                         break;
1903                                 default:
1904                                         BLI_snprintf(msg, sizeof(msg), "%s", ui_name); /* XXX: No value? */
1905                                         break;
1906                         }
1907                 }
1908                 ED_area_headerprint(sa, msg);
1909         }
1910 }
1911
1912 static void radial_control_set_initial_mouse(RadialControl *rc, const wmEvent *event)
1913 {
1914         float d[2] = {0, 0};
1915         float zoom[2] = {1, 1};
1916
1917         rc->initial_mouse[0] = event->x;
1918         rc->initial_mouse[1] = event->y;
1919
1920         switch (rc->subtype) {
1921                 case PROP_NONE:
1922                 case PROP_DISTANCE:
1923                 case PROP_PIXEL:
1924                         d[0] = rc->initial_value;
1925                         break;
1926                 case PROP_PERCENTAGE:
1927                         d[0] = (rc->initial_value) / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
1928                         break;
1929                 case PROP_FACTOR:
1930                         d[0] = (1 - rc->initial_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
1931                         break;
1932                 case PROP_ANGLE:
1933                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cosf(rc->initial_value);
1934                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sinf(rc->initial_value);
1935                         break;
1936                 default:
1937                         return;
1938         }
1939
1940         if (rc->zoom_prop) {
1941                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
1942                 d[0] *= zoom[0];
1943                 d[1] *= zoom[1];
1944         }
1945
1946         rc->initial_mouse[0] -= d[0];
1947         rc->initial_mouse[1] -= d[1];
1948 }
1949
1950 static void radial_control_set_tex(RadialControl *rc)
1951 {
1952         ImBuf *ibuf;
1953
1954         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
1955                 case ID_BR:
1956                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data, rc->use_secondary_tex))) {
1957                                 glGenTextures(1, &rc->gltex);
1958                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
1959                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, ibuf->x, ibuf->y, 0,
1960                                              GL_ALPHA, GL_FLOAT, ibuf->rect_float);
1961                                 MEM_freeN(ibuf->rect_float);
1962                                 MEM_freeN(ibuf);
1963                         }
1964                         break;
1965                 default:
1966                         break;
1967         }
1968 }
1969
1970 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
1971 {
1972         float col[3] = {0, 0, 0};
1973         float rot;
1974
1975         /* set fill color */
1976         if (rc->fill_col_prop) {
1977                 PointerRNA *fill_ptr;
1978                 PropertyRNA *fill_prop;
1979
1980                 if (rc->fill_col_override_prop &&
1981                     RNA_property_boolean_get(&rc->fill_col_override_test_ptr, rc->fill_col_override_test_prop))
1982                 {
1983                         fill_ptr = &rc->fill_col_override_ptr;
1984                         fill_prop = rc->fill_col_override_prop;
1985                 }
1986                 else {
1987                         fill_ptr = &rc->fill_col_ptr;
1988                         fill_prop = rc->fill_col_prop;
1989                 }
1990
1991                 RNA_property_float_get_array(fill_ptr, fill_prop, col);
1992         }
1993         glColor4f(col[0], col[1], col[2], alpha);
1994
1995         if (rc->gltex) {
1996                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
1997
1998                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1999                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2000
2001                 /* set up rotation if available */
2002                 if (rc->rot_prop) {
2003                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2004                         glPushMatrix();
2005                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
2006                 }
2007
2008                 /* draw textured quad */
2009                 GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
2010                 glBegin(GL_QUADS);
2011                 glTexCoord2f(0, 0);
2012                 glVertex2f(-radius, -radius);
2013                 glTexCoord2f(1, 0);
2014                 glVertex2f(radius, -radius);
2015                 glTexCoord2f(1, 1);
2016                 glVertex2f(radius, radius);
2017                 glTexCoord2f(0, 1);
2018                 glVertex2f(-radius, radius);
2019                 glEnd();
2020                 GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
2021
2022                 /* undo rotation */
2023                 if (rc->rot_prop)
2024                         glPopMatrix();
2025         }
2026         else {
2027                 /* flat color if no texture available */
2028                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
2029         }
2030 }
2031
2032 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
2033 {
2034         RadialControl *rc = customdata;
2035         ARegion *ar = CTX_wm_region(C);
2036         uiStyle *style = UI_style_get();
2037         const uiFontStyle *fstyle = &style->widget;
2038         const int fontid = fstyle->uifont_id;
2039         short fstyle_points = fstyle->points;
2040         char str[WM_RADIAL_MAX_STR];
2041         short strdrawlen = 0;
2042         float strwidth, strheight;
2043         float r1 = 0.0f, r2 = 0.0f, rmin = 0.0, tex_radius, alpha;
2044         float zoom[2], col[3] = {1, 1, 1};
2045
2046         switch (rc->subtype) {
2047                 case PROP_NONE:
2048                 case PROP_DISTANCE:
2049                 case PROP_PIXEL:
2050                         r1 = rc->current_value;
2051                         r2 = rc->initial_value;
2052                         tex_radius = r1;
2053                         alpha = 0.75;
2054                         break;
2055                 case PROP_PERCENTAGE:
2056                         r1 = rc->current_value / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2057                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2058                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2059                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.1f%%", rc->current_value);
2060                         strdrawlen = BLI_strlen_utf8(str);
2061                         tex_radius = r1;
2062                         alpha = 0.75;
2063                         break;
2064                 case PROP_FACTOR:
2065                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2066                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2067                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2068                         alpha = rc->current_value / 2.0f + 0.5f;
2069                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%1.3f", rc->current_value);
2070                         strdrawlen = BLI_strlen_utf8(str);
2071                         break;
2072                 case PROP_ANGLE:
2073                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2074                         alpha = 0.75;
2075                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2076                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.2f", RAD2DEGF(rc->current_value));
2077                         strdrawlen = BLI_strlen_utf8(str);
2078                         break;
2079                 default:
2080                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
2081                         alpha = 0.75;
2082                         break;
2083         }
2084
2085         /* Keep cursor in the original place */
2086         x = rc->initial_mouse[0] - ar->winrct.xmin;
2087         y = rc->initial_mouse[1] - ar->winrct.ymin;
2088         glTranslatef((float)x, (float)y, 0.0f);
2089
2090         glEnable(GL_BLEND);
2091         glEnable(GL_LINE_SMOOTH);
2092
2093         /* apply zoom if available */
2094         if (rc->zoom_prop) {
2095                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2096                 glScalef(zoom[0], zoom[1], 1);
2097         }
2098
2099         /* draw rotated texture */
2100         radial_control_paint_tex(rc, tex_radius, alpha);
2101
2102         /* set line color */
2103         if (rc->col_prop)
2104                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
2105         glColor4f(col[0], col[1], col[2], 0.5);
2106
2107         if (rc->subtype == PROP_ANGLE) {
2108                 glPushMatrix();
2109                 /* draw original angle line */
2110                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
2111                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2112                 /* draw new angle line */
2113                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
2114                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2115                 glPopMatrix();
2116         }
2117
2118         /* draw circles on top */
2119         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r1, 40);
2120         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r2, 40);
2121         if (rmin > 0.0f)
2122                 glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), rmin, 40);
2123
2124         BLF_size(fontid, 1.5 * fstyle_points * U.pixelsize, U.dpi);
2125         BLF_enable(fontid, BLF_SHADOW);
2126         BLF_shadow(fontid, 3, (const float[4]){0.0f, 0.0f, 0.0f, 0.5f});
2127         BLF_shadow_offset(fontid, 1, -1);
2128
2129         /* draw value */
2130         BLF_width_and_height(fontid, str, strdrawlen, &strwidth, &strheight);
2131         BLF_position(fontid, -0.5f * strwidth, -0.5f * strheight, 0.0f);
2132         BLF_draw(fontid, str, strdrawlen);
2133
2134         BLF_disable(fontid, BLF_SHADOW);
2135
2136         glDisable(GL_BLEND);
2137         glDisable(GL_LINE_SMOOTH);
2138 }
2139
2140 typedef enum {
2141         RC_PROP_ALLOW_MISSING = 1,
2142         RC_PROP_REQUIRE_FLOAT = 2,
2143         RC_PROP_REQUIRE_BOOL = 4,
2144 } RCPropFlags;
2145
2146 /**
2147  * Attempt to retrieve the rna pointer/property from an rna path.
2148  *
2149  * \return 0 for failure, 1 for success, and also 1 if property is not set.
2150  */
2151 static int radial_control_get_path(
2152         PointerRNA *ctx_ptr, wmOperator *op,
2153         const char *name, PointerRNA *r_ptr,
2154         PropertyRNA **r_prop, int req_length, RCPropFlags flags)
2155 {
2156         PropertyRNA *unused_prop;
2157         int len;
2158         char *str;
2159
2160         /* check flags */
2161         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
2162                 BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
2163                 return 0;
2164         }
2165
2166         /* get an rna string path from the operator's properties */
2167         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
2168                 return 1;
2169
2170         if (str[0] == '\0') {
2171                 if (r_prop) *r_prop = NULL;
2172                 MEM_freeN(str);
2173                 return 1;
2174         }
2175
2176         if (!r_prop)
2177                 r_prop = &unused_prop;
2178
2179         /* get rna from path */
2180         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
2181                 MEM_freeN(str);
2182                 if (flags & RC_PROP_ALLOW_MISSING)
2183                         return 1;
2184                 else {
2185                         BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
2186                         return 0;
2187                 }
2188         }
2189
2190         /* check property type */
2191         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
2192                 PropertyType prop_type = RNA_property_type(*r_prop);
2193
2194                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
2195                     ((flags & RC_PROP_REQUIRE_FLOAT) && (prop_type != PROP_FLOAT)))
2196                 {
2197                         MEM_freeN(str);
2198                         BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
2199                         return 0;
2200                 }
2201         }
2202
2203         /* check property's array length */
2204         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
2205                 MEM_freeN(str);
2206                 BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
2207                             name, len, req_length);
2208                 return 0;
2209         }
2210
2211         /* success */
2212         MEM_freeN(str);
2213         return 1;
2214 }
2215
2216 /* initialize the rna pointers and properties using rna paths */
2217 static int radial_control_get_properties(bContext *C, wmOperator *op)
2218 {
2219         RadialControl *rc = op->customdata;
2220         PointerRNA ctx_ptr, use_secondary_ptr;
2221         PropertyRNA *use_secondary_prop = NULL;
2222         const char *data_path;
2223
2224         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
2225
2226         /* check if we use primary or secondary path */
2227         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
2228                                      &use_secondary_ptr, &use_secondary_prop,
2229                                      0, (RC_PROP_ALLOW_MISSING |
2230                                          RC_PROP_REQUIRE_BOOL)))
2231         {
2232                 return 0;
2233         }
2234         else {
2235                 if (use_secondary_prop &&
2236                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
2237                 {
2238                         data_path = "data_path_secondary";
2239                 }
2240                 else {
2241                         data_path = "data_path_primary";
2242                 }
2243         }
2244
2245         if (!radial_control_get_path(&ctx_ptr, op, data_path, &rc->ptr, &rc->prop, 0, 0))
2246                 return 0;
2247
2248         /* data path is required */
2249         if (!rc->prop)
2250                 return 0;
2251
2252         if (!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 0, RC_PROP_REQUIRE_FLOAT))
2253                 return 0;
2254         if (!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2255                 return 0;
2256
2257
2258         if (!radial_control_get_path(
2259                 &ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2260         {
2261                 return 0;
2262         }
2263
2264         if (!radial_control_get_path(
2265                 &ctx_ptr, op, "fill_color_override_path",
2266                 &rc->fill_col_override_ptr, &rc->fill_col_override_prop, 3, RC_PROP_REQUIRE_FLOAT))
2267         {
2268                 return 0;
2269         }
2270         if (!radial_control_get_path(
2271                 &ctx_ptr, op, "fill_color_override_test_path",
2272                 &rc->fill_col_override_test_ptr, &rc->fill_col_override_test_prop, 0, RC_PROP_REQUIRE_BOOL))
2273         {
2274                 return 0;
2275         }
2276
2277         /* slightly ugly; allow this property to not resolve
2278          * correctly. needed because 3d texture paint shares the same
2279          * keymap as 2d image paint */
2280         if (!radial_control_get_path(&ctx_ptr, op, "zoom_path",
2281                                      &rc->zoom_ptr, &rc->zoom_prop, 2,
2282                                      RC_PROP_REQUIRE_FLOAT | RC_PROP_ALLOW_MISSING))
2283         {
2284                 return 0;
2285         }
2286
2287         if (!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0))
2288                 return 0;
2289         else if (rc->image_id_ptr.data) {
2290                 /* extra check, pointer must be to an ID */
2291                 if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
2292                         BKE_report(op->reports, RPT_ERROR, "Pointer from path image_id is not an ID");
2293                         return 0;
2294                 }
2295         }
2296
2297         rc->use_secondary_tex = RNA_boolean_get(op->ptr, "secondary_tex");
2298
2299         return 1;
2300 }
2301
2302 static int radial_control_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2303 {
2304         wmWindowManager *wm;
2305         RadialControl *rc;
2306
2307
2308         if (!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
2309                 return OPERATOR_CANCELLED;
2310
2311         if (!radial_control_get_properties(C, op)) {
2312                 MEM_freeN(rc);
2313                 return OPERATOR_CANCELLED;
2314         }
2315
2316         /* get type, initial, min, and max values of the property */
2317         switch ((rc->type = RNA_property_type(rc->prop))) {
2318                 case PROP_INT:
2319                 {
2320                         int value, min, max, step;
2321
2322                         value = RNA_property_int_get(&rc->ptr, rc->prop);
2323                         RNA_property_int_ui_range(&rc->ptr, rc->prop, &min, &max, &step);
2324
2325                         rc->initial_value = value;
2326                         rc->min_value = min_ii(value, min);
2327                         rc->max_value = max_ii(value, max);
2328                         break;
2329                 }
2330                 case PROP_FLOAT:
2331                 {
2332                         float value, min, max, step, precision;
2333
2334                         value = RNA_property_float_get(&rc->ptr, rc->prop);
2335                         RNA_property_float_ui_range(&rc->ptr, rc->prop, &min, &max, &step, &precision);
2336
2337                         rc->initial_value = value;
2338                         rc->min_value = min_ff(value, min);
2339                         rc->max_value = max_ff(value, max);
2340                         break;
2341                 }
2342                 default:
2343                         BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
2344                         MEM_freeN(rc);
2345                         return OPERATOR_CANCELLED;
2346         }
2347
2348         /* initialize numerical input */
2349         initNumInput(&rc->num_input);
2350         rc->num_input.idx_max = 0;
2351         rc->num_input.val_flag[0] |= NUM_NO_NEGATIVE;
2352         rc->num_input.unit_sys = USER_UNIT_NONE;
2353         rc->num_input.unit_type[0] = B_UNIT_LENGTH;
2354
2355         /* get subtype of property */
2356         rc->subtype = RNA_property_subtype(rc->prop);
2357         if (!ELEM(rc->subtype, PROP_NONE, PROP_DISTANCE, PROP_FACTOR, PROP_PERCENTAGE, PROP_ANGLE, PROP_PIXEL)) {
2358                 BKE_report(op->reports, RPT_ERROR, "Property must be a none, distance, factor, percentage, angle, or pixel");
2359                 MEM_freeN(rc);
2360                 return OPERATOR_CANCELLED;
2361         }
2362
2363         rc->current_value = rc->initial_value;
2364         radial_control_set_initial_mouse(rc, event);
2365         radial_control_set_tex(rc);
2366
2367         /* temporarily disable other paint cursors */
2368         wm = CTX_wm_manager(C);
2369         rc->orig_paintcursors = wm->paintcursors;
2370         BLI_listbase_clear(&wm->paintcursors);
2371
2372         /* add radial control paint cursor */
2373         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
2374                                               radial_control_paint_cursor, rc);
2375
2376         WM_event_add_modal_handler(C, op);
2377
2378         return OPERATOR_RUNNING_MODAL;
2379 }
2380
2381 static void radial_control_set_value(RadialControl *rc, float val)
2382 {
2383         switch (rc->type) {
2384                 case PROP_INT:
2385                         RNA_property_int_set(&rc->ptr, rc->prop, val);
2386                         break;
2387                 case PROP_FLOAT:
2388                         RNA_property_float_set(&rc->ptr, rc->prop, val);
2389                         break;
2390                 default:
2391                         break;
2392         }
2393 }
2394
2395 static void radial_control_cancel(bContext *C, wmOperator *op)
2396 {
2397         RadialControl *rc = op->customdata;
2398         wmWindowManager *wm = CTX_wm_manager(C);
2399         ScrArea *sa = CTX_wm_area(C);
2400
2401         if (rc->dial) {
2402                 MEM_freeN(rc->dial);
2403                 rc->dial = NULL;
2404         }
2405
2406         if (sa) {
2407                 ED_area_headerprint(sa, NULL);
2408         }
2409
2410         WM_paint_cursor_end(wm, rc->cursor);
2411
2412         /* restore original paint cursors */
2413         wm->paintcursors = rc->orig_paintcursors;
2414
2415         /* not sure if this is a good notifier to use;
2416          * intended purpose is to update the UI so that the
2417          * new value is displayed in sliders/numfields */
2418         WM_event_add_notifier(C, NC_WINDOW, NULL);
2419
2420         glDeleteTextures(1, &rc->gltex);
2421
2422         MEM_freeN(rc);
2423 }
2424
2425 static int radial_control_modal(bContext *C, wmOperator *op, const wmEvent *event)
2426 {
2427         RadialControl *rc = op->customdata;
2428         float new_value, dist = 0.0f, zoom[2];
2429         float delta[2], ret = OPERATOR_RUNNING_MODAL;
2430         bool snap;
2431         float angle_precision = 0.0f;
2432         const bool has_numInput = hasNumInput(&rc->num_input);
2433         bool handled = false;
2434         float numValue;
2435         /* TODO: fix hardcoded events */
2436
2437         snap = event->ctrl != 0;
2438
2439         /* Modal numinput active, try to handle numeric inputs first... */
2440         if (event->val == KM_PRESS && has_numInput && handleNumInput(C, &rc->num_input, event)) {
2441                 handled = true;
2442                 applyNumInput(&rc->num_input, &numValue);
2443
2444                 if (rc->subtype == PROP_ANGLE) {
2445                         numValue = DEG2RADF(numValue);
2446                         numValue = fmod(numValue, 2.0f * (float)M_PI);
2447                         if (numValue < 0.0f)
2448                                 numValue += 2.0f * (float)M_PI;
2449                 }
2450
2451                 CLAMP(numValue, rc->min_value, rc->max_value);
2452                 new_value = numValue;
2453
2454                 radial_control_set_value(rc, new_value);
2455                 rc->current_value = new_value;
2456                 radial_control_update_header(op, C);
2457                 return OPERATOR_RUNNING_MODAL;
2458         }
2459         else {
2460                 handled = false;
2461                 switch (event->type) {
2462                         case ESCKEY:
2463                         case RIGHTMOUSE:
2464                                 /* canceled; restore original value */
2465                                 radial_control_set_value(rc, rc->initial_value);
2466                                 ret = OPERATOR_CANCELLED;
2467                                 break;
2468
2469                         case LEFTMOUSE:
2470                         case PADENTER:
2471                         case RETKEY:
2472                                 /* done; value already set */
2473                                 RNA_property_update(C, &rc->ptr, rc->prop);
2474                                 ret = OPERATOR_FINISHED;
2475                                 break;
2476
2477                         case MOUSEMOVE:
2478                                 if (!has_numInput) {
2479                                         if (rc->slow_mode) {
2480                                                 if (rc->subtype == PROP_ANGLE) {
2481                                                         float position[2] = {event->x, event->y};
2482
2483                                                         /* calculate the initial angle here first */
2484                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2485                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2486
2487                                                         /* precision angle gets calculated from dial and gets added later */
2488                                                         angle_precision = -0.1f * BLI_dial_angle(rc->dial, position);
2489                                                 }
2490                                                 else {
2491                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2492                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2493
2494                                                         if (rc->zoom_prop) {
2495                                                                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2496                                                                 delta[0] /= zoom[0];
2497                                                                 delta[1] /= zoom[1];
2498                                                         }
2499
2500                                                         dist = len_v2(delta);
2501
2502                                                         delta[0] = event->x - rc->slow_mouse[0];
2503                                                         delta[1] = event->y - rc->slow_mouse[1];
2504
2505                                                         if (rc->zoom_prop) {
2506                                                                 delta[0] /= zoom[0];
2507                                                                 delta[1] /= zoom[1];
2508                                                         }
2509
2510                                                         dist = dist + 0.1f * (delta[0] + delta[1]);
2511                                                 }
2512                                         }
2513                                         else {
2514                                                 delta[0] = rc->initial_mouse[0] - event->x;
2515                                                 delta[1] = rc->initial_mouse[1] - event->y;
2516
2517                                                 if (rc->zoom_prop) {
2518                                                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2519                                                         delta[0] /= zoom[0];
2520                                                         delta[1] /= zoom[1];
2521                                                 }
2522
2523                                                 dist = len_v2(delta);
2524                                         }
2525
2526                                         /* calculate new value and apply snapping  */
2527                                         switch (rc->subtype) {
2528                                                 case PROP_NONE:
2529                                                 case PROP_DISTANCE:
2530                                                 case PROP_PIXEL:
2531                                                         new_value = dist;
2532                                                         if (snap) new_value = ((int)new_value + 5) / 10 * 10;
2533                                                         break;
2534                                                 case PROP_PERCENTAGE:
2535                                                         new_value = ((dist - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE) / WM_RADIAL_CONTROL_DISPLAY_WIDTH) * 100.0f;
2536                                                         if (snap) new_value = ((int)(new_value + 2.5f)) / 5 * 5;
2537                                                         break;
2538                                                 case PROP_FACTOR:
2539                                                         new_value = (WM_RADIAL_CONTROL_DISPLAY_SIZE - dist) / WM_RADIAL_CONTROL_DISPLAY_WIDTH;
2540                                                         if (snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
2541                                                         break;
2542                                                 case PROP_ANGLE:
2543                                                         new_value = atan2f(delta[1], delta[0]) + (float)M_PI + angle_precision;
2544                                                         new_value = fmod(new_value, 2.0f * (float)M_PI);
2545                                                         if (new_value < 0.0f)
2546                                                                 new_value += 2.0f * (float)M_PI;
2547                                                         if (snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10 * 10);
2548                                                         break;
2549                                                 default:
2550                                                         new_value = dist; /* dummy value, should this ever happen? - campbell */
2551                                                         break;
2552                                         }
2553
2554                                         /* clamp and update */
2555                                         CLAMP(new_value, rc->min_value, rc->max_value);
2556                                         radial_control_set_value(rc, new_value);
2557                                         rc->current_value = new_value;
2558                                         handled = true;
2559                                         break;
2560                                 }
2561                                 break;
2562
2563                         case LEFTSHIFTKEY:
2564                         case RIGHTSHIFTKEY:
2565                         {
2566                                 if (event->val == KM_PRESS) {
2567                                         rc->slow_mouse[0] = event->x;
2568                                         rc->slow_mouse[1] = event->y;
2569                                         rc->slow_mode = true;
2570                                         if (rc->subtype == PROP_ANGLE) {
2571                                                 float initial_position[2] = {UNPACK2(rc->initial_mouse)};
2572                                                 float current_position[2] = {UNPACK2(rc->slow_mouse)};
2573                                                 rc->dial = BLI_dial_initialize(initial_position, 0.0f);
2574                                                 /* immediately set the position to get a an initial direction */
2575                                                 BLI_dial_angle(rc->dial, current_position);
2576                                         }
2577                                         handled = true;
2578                                 }
2579                                 if (event->val == KM_RELEASE) {
2580                                         rc->slow_mode = false;
2581                                         handled = true;
2582                                         if (rc->dial) {
2583                                                 MEM_freeN(rc->dial);
2584                                                 rc->dial = NULL;
2585                                         }
2586                                 }
2587                                 break;
2588                         }
2589                 }
2590
2591                 /* Modal numinput inactive, try to handle numeric inputs last... */
2592                 if (!handled && event->val == KM_PRESS && handleNumInput(C, &rc->num_input, event)) {
2593                         applyNumInput(&rc->num_input, &numValue);
2594
2595                         if (rc->subtype == PROP_ANGLE) {
2596                                 numValue = DEG2RADF(numValue);
2597                                 numValue = fmod(numValue, 2.0f * (float)M_PI);
2598                                 if (numValue < 0.0f)
2599                                         numValue += 2.0f * (float)M_PI;
2600                         }
2601
2602                         CLAMP(numValue, rc->min_value, rc->max_value);
2603                         new_value = numValue;
2604
2605                         radial_control_set_value(rc, new_value);
2606
2607                         rc->current_value = new_value;
2608                         radial_control_update_header(op, C);
2609                         return OPERATOR_RUNNING_MODAL;
2610                 }
2611         }
2612
2613         ED_region_tag_redraw(CTX_wm_region(C));
2614         radial_control_update_header(op, C);
2615
2616         if (ret != OPERATOR_RUNNING_MODAL)
2617                 radial_control_cancel(C, op);
2618
2619         return ret;
2620 }
2621
2622 static void WM_OT_radial_control(wmOperatorType *ot)
2623 {
2624         ot->name = "Radial Control";
2625         ot->idname = "WM_OT_radial_control";
2626         ot->description = "Set some size property (like e.g. brush size) with mouse wheel";
2627
2628         ot->invoke = radial_control_invoke;
2629         ot->modal = radial_control_modal;
2630         ot->cancel = radial_control_cancel;
2631
2632         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2633
2634         /* all paths relative to the context */
2635         PropertyRNA *prop;
2636         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");
2637         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2638
2639         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");
2640         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2641
2642         prop = RNA_def_string(ot->srna, "use_secondary", NULL, 0, "Use Secondary", "Path of property to select between the primary and secondary data paths");
2643         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2644
2645         prop = RNA_def_string(ot->srna, "rotation_path", NULL, 0, "Rotation Path", "Path of property used to rotate the texture display");
2646         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2647
2648         prop = RNA_def_string(ot->srna, "color_path", NULL, 0, "Color Path", "Path of property used to set the color of the control");
2649         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2650
2651         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");
2652         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2653
2654         prop = RNA_def_string(ot->srna, "fill_color_override_path", NULL, 0, "Fill Color Override Path", "");
2655         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2656         prop = RNA_def_string(ot->srna, "fill_color_override_test_path", NULL, 0, "Fill Color Override Test", "");
2657         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2658
2659         prop = RNA_def_string(ot->srna, "zoom_path", NULL, 0, "Zoom Path", "Path of property used to set the zoom level for the control");
2660         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2661
2662         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");
2663         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2664
2665         prop = RNA_def_boolean(ot->srna, "secondary_tex", false, "Secondary Texture", "Tweak brush secondary/mask texture");
2666         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2667 }
2668
2669 /* ************************** timer for testing ***************** */
2670
2671 /* uses no type defines, fully local testing function anyway... ;) */
2672
2673 static void redraw_timer_window_swap(bContext *C)
2674 {
2675         wmWindow *win = CTX_wm_window(C);
2676         ScrArea *sa;
2677         CTX_wm_menu_set(C, NULL);
2678
2679         for (sa = CTX_wm_screen(C)->areabase.first; sa; sa = sa->next)
2680                 ED_area_tag_redraw(sa);
2681         wm_draw_update(C);
2682
2683         CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2684 }
2685
2686 enum {
2687         eRTDrawRegion = 0,
2688         eRTDrawRegionSwap = 1,
2689         eRTDrawWindow = 2,
2690         eRTDrawWindowSwap = 3,
2691         eRTAnimationStep = 4,
2692         eRTAnimationPlay = 5,
2693         eRTUndo = 6,
2694 };
2695
2696 static const EnumPropertyItem redraw_timer_type_items[] = {
2697         {eRTDrawRegion, "DRAW", 0, "Draw Region", "Draw Region"},
2698         {eRTDrawRegionSwap, "DRAW_SWAP", 0, "Draw Region + Swap", "Draw Region and Swap"},
2699         {eRTDrawWindow, "DRAW_WIN", 0, "Draw Window", "Draw Window"},
2700         {eRTDrawWindowSwap, "DRAW_WIN_SWAP", 0, "Draw Window + Swap", "Draw Window and Swap"},
2701         {eRTAnimationStep, "ANIM_STEP", 0, "Anim Step", "Animation Steps"},
2702         {eRTAnimationPlay, "ANIM_PLAY", 0, "Anim Play", "Animation Playback"},
2703         {eRTUndo, "UNDO", 0, "Undo/Redo", "Undo/Redo"},
2704         {0, NULL, 0, NULL, NULL}
2705 };
2706
2707
2708 static void redraw_timer_step(
2709         bContext *C, Main *bmain, Scene *scene,
2710         wmWindow *win, ScrArea *sa, ARegion *ar,
2711         const int type, const int cfra)
2712 {
2713         if (type == eRTDrawRegion) {
2714                 if (ar) {
2715                         ED_region_do_draw(C, ar);
2716                         ar->do_draw = false;
2717                 }
2718         }
2719         else if (type == eRTDrawRegionSwap) {
2720                 CTX_wm_menu_set(C, NULL);
2721
2722                 ED_region_tag_redraw(ar);
2723                 wm_draw_update(C);
2724
2725                 CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2726         }
2727         else if (type == eRTDrawWindow) {
2728                 ScrArea *sa_iter;
2729
2730                 CTX_wm_menu_set(C, NULL);
2731
2732                 for (sa_iter = win->screen->areabase.first; sa_iter; sa_iter = sa_iter->next) {
2733                         ARegion *ar_iter;
2734                         CTX_wm_area_set(C, sa_iter);
2735
2736                         for (ar_iter = sa_iter->regionbase.first; ar_iter; ar_iter = ar_iter->next) {
2737                                 if (ar_iter->swinid) {
2738                                         CTX_wm_region_set(C, ar_iter);
2739                                         ED_region_do_draw(C, ar_iter);
2740                                         ar_iter->do_draw = false;
2741                                 }
2742                         }
2743                 }
2744
2745                 CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2746
2747                 CTX_wm_area_set(C, sa);
2748                 CTX_wm_region_set(C, ar);
2749         }
2750         else if (type == eRTDrawWindowSwap) {
2751                 redraw_timer_window_swap(C);
2752         }
2753         else if (type == eRTAnimationStep) {
2754                 scene->r.cfra += (cfra == scene->r.cfra) ? 1 : -1;
2755                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
2756         }
2757         else if (type == eRTAnimationPlay) {
2758                 /* play anim, return on same frame as started with */
2759                 int tot = (scene->r.efra - scene->r.sfra) + 1;
2760
2761                 while (tot--) {
2762                         /* todo, ability to escape! */
2763                         scene->r.cfra++;
2764                         if (scene->r.cfra > scene->r.efra)
2765                                 scene->r.cfra = scene->r.sfra;
2766
2767                         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
2768                         redraw_timer_window_swap(C);
2769                 }
2770         }
2771         else { /* eRTUndo */
2772                 ED_undo_pop(C);
2773                 ED_undo_redo(C);
2774         }
2775 }
2776
2777 static int redraw_timer_exec(bContext *C, wmOperator *op)
2778 {
2779         Main *bmain = CTX_data_main(C);
2780         Scene *scene = CTX_data_scene(C);
2781         wmWindow *win = CTX_wm_window(C);
2782         ScrArea *sa = CTX_wm_area(C);
2783         ARegion *ar = CTX_wm_region(C);
2784         double time_start, time_delta;
2785         const int type = RNA_enum_get(op->ptr, "type");
2786         const int iter = RNA_int_get(op->ptr, "iterations");
2787         const double time_limit = (double)RNA_float_get(op->ptr, "time_limit");
2788         const int cfra = scene->r.cfra;
2789         int a, iter_steps = 0;
2790         const char *infostr = "";
2791
2792         WM_cursor_wait(1);
2793
2794         time_start = PIL_check_seconds_timer();
2795
2796         for (a = 0; a < iter; a++) {
2797                 redraw_timer_step(C, bmain, scene, win, sa, ar, type, cfra);
2798                 iter_steps += 1;
2799
2800                 if (time_limit != 0.0) {
2801                         if ((PIL_check_seconds_timer() - time_start) > time_limit) {
2802                                 break;
2803                         }
2804                         a = 0;
2805                 }
2806         }
2807
2808         time_delta = (PIL_check_seconds_timer() - time_start) * 1000;
2809
2810         RNA_enum_description(redraw_timer_type_items, type, &infostr);
2811
2812         WM_cursor_wait(0);
2813
2814         BKE_reportf(op->reports, RPT_WARNING,
2815                     "%d x %s: %.4f ms, average: %.8f ms",
2816                     iter_steps, infostr, time_delta, time_delta / iter_steps);
2817
2818         return OPERATOR_FINISHED;
2819 }
2820
2821 static void WM_OT_redraw_timer(wmOperatorType *ot)
2822 {
2823         ot->name = "Redraw Timer";
2824         ot->idname = "WM_OT_redraw_timer";
2825         ot->description = "Simple redraw timer to test the speed of updating the interface";
2826
2827         ot->invoke = WM_menu_invoke;
2828         ot->exec = redraw_timer_exec;
2829         ot->poll = WM_operator_winactive;
2830
2831         ot->prop = RNA_def_enum(ot->srna, "type", redraw_timer_type_items, eRTDrawRegion, "Type", "");
2832         RNA_def_int(ot->srna, "iterations", 10, 1, INT_MAX, "Iterations", "Number of times to redraw", 1, 1000);
2833         RNA_def_float(ot->srna, "time_limit", 0.0, 0.0, FLT_MAX,
2834                       "Time Limit", "Seconds to run the test for (override iterations)", 0.0, 60.0);
2835
2836 }
2837
2838 /* ************************** memory statistics for testing ***************** */
2839
2840 static int memory_statistics_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2841 {
2842         MEM_printmemlist_stats();
2843         return OPERATOR_FINISHED;
2844 }
2845
2846 static void WM_OT_memory_statistics(wmOperatorType *ot)
2847 {
2848         ot->name = "Memory Statistics";
2849         ot->idname = "WM_OT_memory_statistics";
2850         ot->description = "Print memory statistics to the console";
2851
2852         ot->exec = memory_statistics_exec;
2853 }
2854
2855 /* ************************** memory statistics for testing ***************** */
2856
2857 static int dependency_relations_exec(bContext *C, wmOperator *UNUSED(op))
2858 {
2859         Main *bmain = CTX_data_main(C);
2860         Scene *scene = CTX_data_scene(C);
2861         Object *ob = CTX_data_active_object(C);
2862
2863         DAG_print_dependencies(bmain, scene, ob);
2864
2865         return OPERATOR_FINISHED;
2866 }
2867
2868 static void WM_OT_dependency_relations(wmOperatorType *ot)
2869 {
2870         ot->name = "Dependency Relations";
2871         ot->idname = "WM_OT_dependency_relations";
2872         ot->description = "Print dependency graph relations to the console";
2873
2874         ot->exec = dependency_relations_exec;
2875 }
2876
2877 /* *************************** Mat/tex/etc. previews generation ************* */
2878
2879 typedef struct PreviewsIDEnsureData {
2880         bContext *C;
2881         Scene *scene;
2882 } PreviewsIDEnsureData;
2883
2884 static void previews_id_ensure(bContext *C, Scene *scene, ID *id)
2885 {
2886         BLI_assert(ELEM(GS(id->name), ID_MA, ID_TE, ID_IM, ID_WO, ID_LA));
2887
2888         /* Only preview non-library datablocks, lib ones do not pertain to this .blend file!
2889          * Same goes for ID with no user. */
2890         if (!ID_IS_LINKED(id) && (id->us != 0)) {
2891                 UI_id_icon_render(C, scene, id, false, false);
2892                 UI_id_icon_render(C, scene, id, true, false);
2893         }
2894 }
2895
2896 static int previews_id_ensure_callback(void *userdata, ID *UNUSED(self_id), ID **idptr, int cb_flag)
2897 {
2898         if (cb_flag & IDWALK_CB_PRIVATE) {
2899                 return IDWALK_RET_NOP;
2900         }
2901
2902         PreviewsIDEnsureData *data = userdata;
2903         ID *id = *idptr;
2904
2905         if (id && (id->tag & LIB_TAG_DOIT)) {
2906                 BLI_assert(ELEM(GS(id->name), ID_MA, ID_TE, ID_IM, ID_WO, ID_LA));
2907                 previews_id_ensure(data->C, data->scene, id);
2908                 id->tag &= ~LIB_TAG_DOIT;
2909         }
2910
2911         return IDWALK_RET_NOP;
2912 }
2913
2914 static int previews_ensure_exec(bContext *C, wmOperator *UNUSED(op))
2915 {
2916         Main *bmain = CTX_data_main(C);
2917         ListBase *lb[] = {&bmain->mat, &bmain->tex, &bmain->image, &bmain->world, &bmain->lamp, NULL};
2918         PreviewsIDEnsureData preview_id_data;
2919         Scene *scene;
2920         ID *id;
2921         int i;
2922
2923         /* We use LIB_TAG_DOIT to check whether we have already handled a given ID or not. */
2924         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
2925         for (i = 0; lb[i]; i++) {
2926                 BKE_main_id_tag_listbase(lb[i], LIB_TAG_DOIT, true);
2927         }
2928
2929         preview_id_data.C = C;
2930         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
2931                 preview_id_data.scene = scene;
2932                 id = (ID *)scene;
2933
2934                 BKE_library_foreach_ID_link(NULL, id, previews_id_ensure_callback, &preview_id_data, IDWALK_RECURSE);
2935         }
2936
2937         /* Check a last time for ID not used (fake users only, in theory), and
2938          * do our best for those, using current scene... */
2939         for (i = 0; lb[i]; i++) {
2940                 for (id = lb[i]->first; id; id = id->next) {
2941                         if (id->tag & LIB_TAG_DOIT) {
2942                                 previews_id_ensure(C, NULL, id);
2943                                 id->tag &= ~LIB_TAG_DOIT;
2944                         }
2945                 }
2946         }
2947
2948         return OPERATOR_FINISHED;
2949 }
2950
2951 static void WM_OT_previews_ensure(wmOperatorType *ot)
2952 {
2953         ot->name = "Refresh Data-Block Previews";
2954         ot->idname = "WM_OT_previews_ensure";
2955         ot->description = "Ensure data-block previews are available and up-to-date "
2956                           "(to be saved in .blend file, only for some types like materials, textures, etc.)";
2957
2958         ot->exec = previews_ensure_exec;
2959 }
2960
2961 /* *************************** Datablocks previews clear ************* */
2962
2963 /* Only types supporting previews currently. */
2964 static const EnumPropertyItem preview_id_type_items[] = {
2965     {FILTER_ID_SCE, "SCENE", 0, "Scenes", ""},
2966     {FILTER_ID_GR, "GROUP", 0, "Groups", ""},
2967     {FILTER_ID_OB, "OBJECT", 0, "Objects", ""},
2968     {FILTER_ID_MA, "MATERIAL", 0, "Materials", ""},
2969     {FILTER_ID_LA, "LAMP", 0, "Lamps", ""},
2970     {FILTER_ID_WO, "WORLD", 0, "Worlds", ""},
2971     {FILTER_ID_TE, "TEXTURE", 0, "Textures", ""},
2972     {FILTER_ID_IM, "IMAGE", 0, "Images", ""},
2973 #if 0  /* XXX TODO */
2974     {FILTER_ID_BR, "BRUSH", 0, "Brushes", ""},
2975 #endif
2976     {0, NULL, 0, NULL, NULL}
2977 };
2978
2979 static int previews_clear_exec(bContext *C, wmOperator *op)
2980 {
2981         Main *bmain = CTX_data_main(C);
2982         ListBase *lb[] = {&bmain->object, &bmain->group,
2983                           &bmain->mat, &bmain->world, &bmain->lamp, &bmain->tex, &bmain->image, NULL};
2984         int i;
2985
2986         const int id_filters = RNA_enum_get(op->ptr, "id_type");
2987
2988         for (i = 0; lb[i]; i++) {
2989                 ID *id = lb[i]->first;
2990
2991                 if (!id) continue;
2992
2993 //              printf("%s: %d, %d, %d -> %d\n", id->name, GS(id->name), BKE_idcode_to_idfilter(GS(id->name)),
2994 //                                               id_filters, BKE_idcode_to_idfilter(GS(id->name)) & id_filters);
2995
2996                 if (!id || !(BKE_idcode_to_idfilter(GS(id->name)) & id_filters)) {
2997                         continue;
2998                 }
2999
3000                 for (; id; id = id->next) {
3001                         PreviewImage *prv_img = BKE_previewimg_id_ensure(id);
3002
3003                         BKE_previewimg_clear(prv_img);
3004                 }
3005         }
3006
3007         return OPERATOR_FINISHED;
3008 }
3009
3010 static void WM_OT_previews_clear(wmOperatorType *ot)
3011 {
3012         ot->name = "Clear Data-Block Previews";
3013         ot->idname = "WM_OT_previews_clear";
3014         ot->description = "Clear data-block previews (only for some types like objects, materials, textures, etc.)";
3015
3016         ot->exec = previews_clear_exec;
3017         ot->invoke = WM_menu_invoke;
3018
3019         ot->prop = RNA_def_enum_flag(ot->srna, "id_type", preview_id_type_items,
3020                                      FILTER_ID_SCE | FILTER_ID_OB | FILTER_ID_GR |
3021                                      FILTER_ID_MA | FILTER_ID_LA | FILTER_ID_WO | FILTER_ID_TE | FILTER_ID_IM,
3022                                      "Data-Block Type", "Which data-block previews to clear");
3023 }
3024
3025 /* *************************** Doc from UI ************* */
3026
3027 static int doc_view_manual_ui_context_exec(bContext *C, wmOperator *UNUSED(op))
3028 {
3029         PointerRNA ptr_props;
3030         char buf[512];
3031         short retval = OPERATOR_CANCELLED;
3032
3033         if (UI_but_online_manual_id_from_active(C, buf, sizeof(buf))) {
3034                 WM_operator_properties_create(&ptr_props, "WM_OT_doc_view_manual");
3035                 RNA_string_set(&ptr_props, "doc_id", buf);
3036
3037                 retval = WM_operator_name_call_ptr(
3038                         C, WM_operatortype_find("WM_OT_doc_view_manual", false),
3039                         WM_OP_EXEC_DEFAULT, &ptr_props);
3040
3041                 WM_operator_properties_free(&ptr_props);
3042         }
3043
3044         return retval;
3045 }
3046
3047 static void WM_OT_doc_view_manual_ui_context(wmOperatorType *ot)
3048 {
3049         /* identifiers */
3050         ot->name = "View Online Manual";
3051         ot->idname = "WM_OT_doc_view_manual_ui_context";
3052         ot->description = "View a context based online manual in a web browser";
3053
3054         /* callbacks */
3055         ot->poll = ED_operator_regionactive;
3056         ot->exec = doc_view_manual_ui_context_exec;
3057 }
3058
3059 /* ******************************************************* */
3060
3061 /* ******************************************************* */
3062 /* toggle 3D for current window, turning it fullscreen if needed */
3063 static void WM_OT_stereo3d_set(wmOperatorType *ot)
3064 {
3065         PropertyRNA *prop;
3066
3067         ot->name = "Set Stereo 3D";
3068         ot->idname = "WM_OT_set_stereo_3d";
3069         ot->description = "Toggle 3D stereo support for current window (or change the display mode)";
3070
3071         ot->exec = wm_stereo3d_set_exec;
3072         ot->invoke = wm_stereo3d_set_invoke;
3073         ot->poll = WM_operator_winactive;
3074         ot->ui = wm_stereo3d_set_draw;
3075         ot->check = wm_stereo3d_set_check;
3076         ot->cancel = wm_stereo3d_set_cancel;
3077
3078         prop = RNA_def_enum(ot->srna, "display_mode", rna_enum_stereo3d_display_items, S3D_DISPLAY_ANAGLYPH, "Display Mode", "");
3079         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3080         prop = RNA_def_enum(ot->srna, "anaglyph_type", rna_enum_stereo3d_anaglyph_type_items, S3D_ANAGLYPH_REDCYAN, "Anaglyph Type", "");
3081         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3082         prop = RNA_def_enum(ot->srna, "interlace_type", rna_enum_stereo3d_interlace_type_items, S3D_INTERLACE_ROW, "Interlace Type", "");
3083         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3084         prop = RNA_def_boolean(ot->srna, "use_interlace_swap", false, "Swap Left/Right",
3085                                "Swap left and right stereo channels");
3086         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3087         prop = RNA_def_boolean(ot->srna, "use_sidebyside_crosseyed", false, "Cross-Eyed",
3088                                "Right eye should see left image and vice-versa");
3089         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3090 }
3091
3092 void wm_operatortypes_register(void)
3093 {
3094         WM_operatortype_append(WM_OT_window_close);
3095         WM_operatortype_append(WM_OT_window_duplicate);
3096         WM_operatortype_append(WM_OT_read_history);
3097         WM_operatortype_append(WM_OT_read_homefile);
3098         WM_operatortype_append(WM_OT_read_factory_settings);
3099         WM_operatortype_append(WM_OT_save_homefile);
3100         WM_operatortype_append(WM_OT_save_userpref);
3101         WM_operatortype_append(WM_OT_userpref_autoexec_path_add);
3102         WM_operatortype_append(WM_OT_userpref_autoexec_path_remove);
3103         WM_operatortype_append(WM_OT_window_fullscreen_toggle);
3104         WM_operatortype_append(WM_OT_quit_blender);
3105         WM_operatortype_append(WM_OT_open_mainfile);
3106         WM_operatortype_append(WM_OT_revert_mainfile);
3107         WM_operatortype_append(WM_OT_link);
3108         WM_operatortype_append(WM_OT_append);
3109         WM_operatortype_append(WM_OT_lib_relocate);
3110         WM_operatortype_append(WM_OT_lib_reload);
3111         WM_operatortype_append(WM_OT_recover_last_session);
3112         WM_operatortype_append(WM_OT_recover_auto_save);
3113         WM_operatortype_append(WM_OT_save_as_mainfile);
3114         WM_operatortype_append(WM_OT_save_mainfile);
3115         WM_operatortype_append(WM_OT_redraw_timer);
3116         WM_operatortype_append(WM_OT_memory_statistics);
3117         WM_operatortype_append(WM_OT_dependency_relations);
3118         WM_operatortype_append(WM_OT_debug_menu);
3119         WM_operatortype_append(WM_OT_operator_defaults);
3120         WM_operatortype_append(WM_OT_splash);
3121         WM_operatortype_append(WM_OT_search_menu);
3122         WM_operatortype_append(WM_OT_call_menu);
3123         WM_operatortype_append(WM_OT_call_menu_pie);
3124         WM_operatortype_append(WM_OT_radial_control);
3125         WM_operatortype_append(WM_OT_stereo3d_set);
3126 #if defined(WIN32)
3127         WM_operatortype_append(WM_OT_console_toggle);
3128 #endif
3129         WM_operatortype_append(WM_OT_previews_ensure);
3130         WM_operatortype_append(WM_OT_previews_clear);
3131         WM_operatortype_append(WM_OT_doc_view_manual_ui_context);
3132 }
3133
3134 /* circleselect-like modal operators */
3135 static void gesture_circle_modal_keymap(wmKeyConfig *keyconf)
3136 {
3137         static const EnumPropertyItem modal_items[] = {
3138                 {GESTURE_MODAL_CANCEL,  "CANCEL", 0, "Cancel", ""},
3139                 {GESTURE_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
3140                 {GESTURE_MODAL_CIRCLE_ADD, "ADD", 0, "Add", ""},
3141                 {GESTURE_MODAL_CIRCLE_SUB, "SUBTRACT", 0, "Subtract", ""},
3142                 {GESTURE_MODAL_CIRCLE_SIZE, "SIZE", 0, "Size", ""},
3143
3144                 {GESTURE_MODAL_SELECT,  "SELECT", 0, "Select", ""},
3145                 {GESTURE_MODAL_DESELECT, "DESELECT", 0, "DeSelect", ""},
3146                 {GESTURE_MODAL_NOP,&nb