WM: minor changes to cursor API
[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 wmPaintCursor *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 bool WM_paint_cursor_end(wmWindowManager *wm, wmPaintCursor *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 true;
1840                 }
1841         }
1842         return false;
1843 }
1844
1845 void *WM_paint_cursor_customdata_get(wmPaintCursor *pc)
1846 {
1847         return pc->customdata;
1848 }
1849
1850 /* *********************** radial control ****************** */
1851
1852 #define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
1853 #define WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE (35 * UI_DPI_FAC)
1854 #define WM_RADIAL_CONTROL_DISPLAY_WIDTH (WM_RADIAL_CONTROL_DISPLAY_SIZE - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE)
1855 #define WM_RADIAL_MAX_STR 10
1856
1857 typedef struct {
1858         PropertyType type;
1859         PropertySubType subtype;
1860         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
1861         PointerRNA fill_col_override_ptr, fill_col_override_test_ptr;
1862         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
1863         PropertyRNA *fill_col_override_prop, *fill_col_override_test_prop;
1864         StructRNA *image_id_srna;
1865         float initial_value, current_value, min_value, max_value;
1866         int initial_mouse[2];
1867         int slow_mouse[2];
1868         bool slow_mode;
1869         Dial *dial;
1870         unsigned int gltex;
1871         ListBase orig_paintcursors;
1872         bool use_secondary_tex;
1873         void *cursor;
1874         NumInput num_input;
1875 } RadialControl;
1876
1877 static void radial_control_update_header(wmOperator *op, bContext *C)
1878 {
1879         RadialControl *rc = op->customdata;
1880         char msg[UI_MAX_DRAW_STR];
1881         ScrArea *sa = CTX_wm_area(C);
1882         Scene *scene = CTX_data_scene(C);
1883
1884         if (sa) {
1885                 if (hasNumInput(&rc->num_input)) {
1886                         char num_str[NUM_STR_REP_LEN];
1887                         outputNumInput(&rc->num_input, num_str, &scene->unit);
1888                         BLI_snprintf(msg, sizeof(msg), "%s: %s", RNA_property_ui_name(rc->prop), num_str);
1889                 }
1890                 else {
1891                         const char *ui_name = RNA_property_ui_name(rc->prop);
1892                         switch (rc->subtype) {
1893                                 case PROP_NONE:
1894                                 case PROP_DISTANCE:
1895                                         BLI_snprintf(msg, sizeof(msg), "%s: %0.4f", ui_name, rc->current_value);
1896                                         break;
1897                                 case PROP_PIXEL:
1898                                         BLI_snprintf(msg, sizeof(msg), "%s: %d", ui_name, (int)rc->current_value); /* XXX: round to nearest? */
1899                                         break;
1900                                 case PROP_PERCENTAGE:
1901                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.1f%%", ui_name, rc->current_value);
1902                                         break;
1903                                 case PROP_FACTOR:
1904                                         BLI_snprintf(msg, sizeof(msg), "%s: %1.3f", ui_name, rc->current_value);
1905                                         break;
1906                                 case PROP_ANGLE:
1907                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.2f", ui_name, RAD2DEGF(rc->current_value));
1908                                         break;
1909                                 default:
1910                                         BLI_snprintf(msg, sizeof(msg), "%s", ui_name); /* XXX: No value? */
1911                                         break;
1912                         }
1913                 }
1914                 ED_area_headerprint(sa, msg);
1915         }
1916 }
1917
1918 static void radial_control_set_initial_mouse(RadialControl *rc, const wmEvent *event)
1919 {
1920         float d[2] = {0, 0};
1921         float zoom[2] = {1, 1};
1922
1923         rc->initial_mouse[0] = event->x;
1924         rc->initial_mouse[1] = event->y;
1925
1926         switch (rc->subtype) {
1927                 case PROP_NONE:
1928                 case PROP_DISTANCE:
1929                 case PROP_PIXEL:
1930                         d[0] = rc->initial_value;
1931                         break;
1932                 case PROP_PERCENTAGE:
1933                         d[0] = (rc->initial_value) / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
1934                         break;
1935                 case PROP_FACTOR:
1936                         d[0] = (1 - rc->initial_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
1937                         break;
1938                 case PROP_ANGLE:
1939                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cosf(rc->initial_value);
1940                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sinf(rc->initial_value);
1941                         break;
1942                 default:
1943                         return;
1944         }
1945
1946         if (rc->zoom_prop) {
1947                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
1948                 d[0] *= zoom[0];
1949                 d[1] *= zoom[1];
1950         }
1951
1952         rc->initial_mouse[0] -= d[0];
1953         rc->initial_mouse[1] -= d[1];
1954 }
1955
1956 static void radial_control_set_tex(RadialControl *rc)
1957 {
1958         ImBuf *ibuf;
1959
1960         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
1961                 case ID_BR:
1962                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data, rc->use_secondary_tex))) {
1963                                 glGenTextures(1, &rc->gltex);
1964                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
1965                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, ibuf->x, ibuf->y, 0,
1966                                              GL_ALPHA, GL_FLOAT, ibuf->rect_float);
1967                                 MEM_freeN(ibuf->rect_float);
1968                                 MEM_freeN(ibuf);
1969                         }
1970                         break;
1971                 default:
1972                         break;
1973         }
1974 }
1975
1976 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
1977 {
1978         float col[3] = {0, 0, 0};
1979         float rot;
1980
1981         /* set fill color */
1982         if (rc->fill_col_prop) {
1983                 PointerRNA *fill_ptr;
1984                 PropertyRNA *fill_prop;
1985
1986                 if (rc->fill_col_override_prop &&
1987                     RNA_property_boolean_get(&rc->fill_col_override_test_ptr, rc->fill_col_override_test_prop))
1988                 {
1989                         fill_ptr = &rc->fill_col_override_ptr;
1990                         fill_prop = rc->fill_col_override_prop;
1991                 }
1992                 else {
1993                         fill_ptr = &rc->fill_col_ptr;
1994                         fill_prop = rc->fill_col_prop;
1995                 }
1996
1997                 RNA_property_float_get_array(fill_ptr, fill_prop, col);
1998         }
1999         glColor4f(col[0], col[1], col[2], alpha);
2000
2001         if (rc->gltex) {
2002                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2003
2004                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2005                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2006
2007                 /* set up rotation if available */
2008                 if (rc->rot_prop) {
2009                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2010                         glPushMatrix();
2011                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
2012                 }
2013
2014                 /* draw textured quad */
2015                 GPU_basic_shader_bind(GPU_SHADER_TEXTURE_2D | GPU_SHADER_USE_COLOR);
2016                 glBegin(GL_QUADS);
2017                 glTexCoord2f(0, 0);
2018                 glVertex2f(-radius, -radius);
2019                 glTexCoord2f(1, 0);
2020                 glVertex2f(radius, -radius);
2021                 glTexCoord2f(1, 1);
2022                 glVertex2f(radius, radius);
2023                 glTexCoord2f(0, 1);
2024                 glVertex2f(-radius, radius);
2025                 glEnd();
2026                 GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
2027
2028                 /* undo rotation */
2029                 if (rc->rot_prop)
2030                         glPopMatrix();
2031         }
2032         else {
2033                 /* flat color if no texture available */
2034                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
2035         }
2036 }
2037
2038 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
2039 {
2040         RadialControl *rc = customdata;
2041         ARegion *ar = CTX_wm_region(C);
2042         uiStyle *style = UI_style_get();
2043         const uiFontStyle *fstyle = &style->widget;
2044         const int fontid = fstyle->uifont_id;
2045         short fstyle_points = fstyle->points;
2046         char str[WM_RADIAL_MAX_STR];
2047         short strdrawlen = 0;
2048         float strwidth, strheight;
2049         float r1 = 0.0f, r2 = 0.0f, rmin = 0.0, tex_radius, alpha;
2050         float zoom[2], col[3] = {1, 1, 1};
2051
2052         switch (rc->subtype) {
2053                 case PROP_NONE:
2054                 case PROP_DISTANCE:
2055                 case PROP_PIXEL:
2056                         r1 = rc->current_value;
2057                         r2 = rc->initial_value;
2058                         tex_radius = r1;
2059                         alpha = 0.75;
2060                         break;
2061                 case PROP_PERCENTAGE:
2062                         r1 = rc->current_value / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2063                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2064                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2065                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.1f%%", rc->current_value);
2066                         strdrawlen = BLI_strlen_utf8(str);
2067                         tex_radius = r1;
2068                         alpha = 0.75;
2069                         break;
2070                 case PROP_FACTOR:
2071                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2072                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2073                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2074                         alpha = rc->current_value / 2.0f + 0.5f;
2075                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%1.3f", rc->current_value);
2076                         strdrawlen = BLI_strlen_utf8(str);
2077                         break;
2078                 case PROP_ANGLE:
2079                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
2080                         alpha = 0.75;
2081                         rmin = WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
2082                         BLI_snprintf(str, WM_RADIAL_MAX_STR, "%3.2f", RAD2DEGF(rc->current_value));
2083                         strdrawlen = BLI_strlen_utf8(str);
2084                         break;
2085                 default:
2086                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
2087                         alpha = 0.75;
2088                         break;
2089         }
2090
2091         /* Keep cursor in the original place */
2092         x = rc->initial_mouse[0] - ar->winrct.xmin;
2093         y = rc->initial_mouse[1] - ar->winrct.ymin;
2094         glTranslatef((float)x, (float)y, 0.0f);
2095
2096         glEnable(GL_BLEND);
2097         glEnable(GL_LINE_SMOOTH);
2098
2099         /* apply zoom if available */
2100         if (rc->zoom_prop) {
2101                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2102                 glScalef(zoom[0], zoom[1], 1);
2103         }
2104
2105         /* draw rotated texture */
2106         radial_control_paint_tex(rc, tex_radius, alpha);
2107
2108         /* set line color */
2109         if (rc->col_prop)
2110                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
2111         glColor4f(col[0], col[1], col[2], 0.5);
2112
2113         if (rc->subtype == PROP_ANGLE) {
2114                 glPushMatrix();
2115                 /* draw original angle line */
2116                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
2117                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2118                 /* draw new angle line */
2119                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
2120                 fdrawline((float)WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2121                 glPopMatrix();
2122         }
2123
2124         /* draw circles on top */
2125         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r1, 40);
2126         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r2, 40);
2127         if (rmin > 0.0f)
2128                 glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), rmin, 40);
2129
2130         BLF_size(fontid, 1.5 * fstyle_points * U.pixelsize, U.dpi);
2131         BLF_enable(fontid, BLF_SHADOW);
2132         BLF_shadow(fontid, 3, (const float[4]){0.0f, 0.0f, 0.0f, 0.5f});
2133         BLF_shadow_offset(fontid, 1, -1);
2134
2135         /* draw value */
2136         BLF_width_and_height(fontid, str, strdrawlen, &strwidth, &strheight);
2137         BLF_position(fontid, -0.5f * strwidth, -0.5f * strheight, 0.0f);
2138         BLF_draw(fontid, str, strdrawlen);
2139
2140         BLF_disable(fontid, BLF_SHADOW);
2141
2142         glDisable(GL_BLEND);
2143         glDisable(GL_LINE_SMOOTH);
2144 }
2145
2146 typedef enum {
2147         RC_PROP_ALLOW_MISSING = 1,
2148         RC_PROP_REQUIRE_FLOAT = 2,
2149         RC_PROP_REQUIRE_BOOL = 4,
2150 } RCPropFlags;
2151
2152 /**
2153  * Attempt to retrieve the rna pointer/property from an rna path.
2154  *
2155  * \return 0 for failure, 1 for success, and also 1 if property is not set.
2156  */
2157 static int radial_control_get_path(
2158         PointerRNA *ctx_ptr, wmOperator *op,
2159         const char *name, PointerRNA *r_ptr,
2160         PropertyRNA **r_prop, int req_length, RCPropFlags flags)
2161 {
2162         PropertyRNA *unused_prop;
2163         int len;
2164         char *str;
2165
2166         /* check flags */
2167         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
2168                 BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
2169                 return 0;
2170         }
2171
2172         /* get an rna string path from the operator's properties */
2173         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
2174                 return 1;
2175
2176         if (str[0] == '\0') {
2177                 if (r_prop) *r_prop = NULL;
2178                 MEM_freeN(str);
2179                 return 1;
2180         }
2181
2182         if (!r_prop)
2183                 r_prop = &unused_prop;
2184
2185         /* get rna from path */
2186         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
2187                 MEM_freeN(str);
2188                 if (flags & RC_PROP_ALLOW_MISSING)
2189                         return 1;
2190                 else {
2191                         BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
2192                         return 0;
2193                 }
2194         }
2195
2196         /* check property type */
2197         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
2198                 PropertyType prop_type = RNA_property_type(*r_prop);
2199
2200                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
2201                     ((flags & RC_PROP_REQUIRE_FLOAT) && (prop_type != PROP_FLOAT)))
2202                 {
2203                         MEM_freeN(str);
2204                         BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
2205                         return 0;
2206                 }
2207         }
2208
2209         /* check property's array length */
2210         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
2211                 MEM_freeN(str);
2212                 BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
2213                             name, len, req_length);
2214                 return 0;
2215         }
2216
2217         /* success */
2218         MEM_freeN(str);
2219         return 1;
2220 }
2221
2222 /* initialize the rna pointers and properties using rna paths */
2223 static int radial_control_get_properties(bContext *C, wmOperator *op)
2224 {
2225         RadialControl *rc = op->customdata;
2226         PointerRNA ctx_ptr, use_secondary_ptr;
2227         PropertyRNA *use_secondary_prop = NULL;
2228         const char *data_path;
2229
2230         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
2231
2232         /* check if we use primary or secondary path */
2233         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
2234                                      &use_secondary_ptr, &use_secondary_prop,
2235                                      0, (RC_PROP_ALLOW_MISSING |
2236                                          RC_PROP_REQUIRE_BOOL)))
2237         {
2238                 return 0;
2239         }
2240         else {
2241                 if (use_secondary_prop &&
2242                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
2243                 {
2244                         data_path = "data_path_secondary";
2245                 }
2246                 else {
2247                         data_path = "data_path_primary";
2248                 }
2249         }
2250
2251         if (!radial_control_get_path(&ctx_ptr, op, data_path, &rc->ptr, &rc->prop, 0, 0))
2252                 return 0;
2253
2254         /* data path is required */
2255         if (!rc->prop)
2256                 return 0;
2257
2258         if (!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 0, RC_PROP_REQUIRE_FLOAT))
2259                 return 0;
2260         if (!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2261                 return 0;
2262
2263
2264         if (!radial_control_get_path(
2265                 &ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 3, RC_PROP_REQUIRE_FLOAT))
2266         {
2267                 return 0;
2268         }
2269
2270         if (!radial_control_get_path(
2271                 &ctx_ptr, op, "fill_color_override_path",
2272                 &rc->fill_col_override_ptr, &rc->fill_col_override_prop, 3, RC_PROP_REQUIRE_FLOAT))
2273         {
2274                 return 0;
2275         }
2276         if (!radial_control_get_path(
2277                 &ctx_ptr, op, "fill_color_override_test_path",
2278                 &rc->fill_col_override_test_ptr, &rc->fill_col_override_test_prop, 0, RC_PROP_REQUIRE_BOOL))
2279         {
2280                 return 0;
2281         }
2282
2283         /* slightly ugly; allow this property to not resolve
2284          * correctly. needed because 3d texture paint shares the same
2285          * keymap as 2d image paint */
2286         if (!radial_control_get_path(&ctx_ptr, op, "zoom_path",
2287                                      &rc->zoom_ptr, &rc->zoom_prop, 2,
2288                                      RC_PROP_REQUIRE_FLOAT | RC_PROP_ALLOW_MISSING))
2289         {
2290                 return 0;
2291         }
2292
2293         if (!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0))
2294                 return 0;
2295         else if (rc->image_id_ptr.data) {
2296                 /* extra check, pointer must be to an ID */
2297                 if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
2298                         BKE_report(op->reports, RPT_ERROR, "Pointer from path image_id is not an ID");
2299                         return 0;
2300                 }
2301         }
2302
2303         rc->use_secondary_tex = RNA_boolean_get(op->ptr, "secondary_tex");
2304
2305         return 1;
2306 }
2307
2308 static int radial_control_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2309 {
2310         wmWindowManager *wm;
2311         RadialControl *rc;
2312
2313
2314         if (!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
2315                 return OPERATOR_CANCELLED;
2316
2317         if (!radial_control_get_properties(C, op)) {
2318                 MEM_freeN(rc);
2319                 return OPERATOR_CANCELLED;
2320         }
2321
2322         /* get type, initial, min, and max values of the property */
2323         switch ((rc->type = RNA_property_type(rc->prop))) {
2324                 case PROP_INT:
2325                 {
2326                         int value, min, max, step;
2327
2328                         value = RNA_property_int_get(&rc->ptr, rc->prop);
2329                         RNA_property_int_ui_range(&rc->ptr, rc->prop, &min, &max, &step);
2330
2331                         rc->initial_value = value;
2332                         rc->min_value = min_ii(value, min);
2333                         rc->max_value = max_ii(value, max);
2334                         break;
2335                 }
2336                 case PROP_FLOAT:
2337                 {
2338                         float value, min, max, step, precision;
2339
2340                         value = RNA_property_float_get(&rc->ptr, rc->prop);
2341                         RNA_property_float_ui_range(&rc->ptr, rc->prop, &min, &max, &step, &precision);
2342
2343                         rc->initial_value = value;
2344                         rc->min_value = min_ff(value, min);
2345                         rc->max_value = max_ff(value, max);
2346                         break;
2347                 }
2348                 default:
2349                         BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
2350                         MEM_freeN(rc);
2351                         return OPERATOR_CANCELLED;
2352         }
2353
2354         /* initialize numerical input */
2355         initNumInput(&rc->num_input);
2356         rc->num_input.idx_max = 0;
2357         rc->num_input.val_flag[0] |= NUM_NO_NEGATIVE;
2358         rc->num_input.unit_sys = USER_UNIT_NONE;
2359         rc->num_input.unit_type[0] = B_UNIT_LENGTH;
2360
2361         /* get subtype of property */
2362         rc->subtype = RNA_property_subtype(rc->prop);
2363         if (!ELEM(rc->subtype, PROP_NONE, PROP_DISTANCE, PROP_FACTOR, PROP_PERCENTAGE, PROP_ANGLE, PROP_PIXEL)) {
2364                 BKE_report(op->reports, RPT_ERROR, "Property must be a none, distance, factor, percentage, angle, or pixel");
2365                 MEM_freeN(rc);
2366                 return OPERATOR_CANCELLED;
2367         }
2368
2369         rc->current_value = rc->initial_value;
2370         radial_control_set_initial_mouse(rc, event);
2371         radial_control_set_tex(rc);
2372
2373         /* temporarily disable other paint cursors */
2374         wm = CTX_wm_manager(C);
2375         rc->orig_paintcursors = wm->paintcursors;
2376         BLI_listbase_clear(&wm->paintcursors);
2377
2378         /* add radial control paint cursor */
2379         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
2380                                               radial_control_paint_cursor, rc);
2381
2382         WM_event_add_modal_handler(C, op);
2383
2384         return OPERATOR_RUNNING_MODAL;
2385 }
2386
2387 static void radial_control_set_value(RadialControl *rc, float val)
2388 {
2389         switch (rc->type) {
2390                 case PROP_INT:
2391                         RNA_property_int_set(&rc->ptr, rc->prop, val);
2392                         break;
2393                 case PROP_FLOAT:
2394                         RNA_property_float_set(&rc->ptr, rc->prop, val);
2395                         break;
2396                 default:
2397                         break;
2398         }
2399 }
2400
2401 static void radial_control_cancel(bContext *C, wmOperator *op)
2402 {
2403         RadialControl *rc = op->customdata;
2404         wmWindowManager *wm = CTX_wm_manager(C);
2405         ScrArea *sa = CTX_wm_area(C);
2406
2407         if (rc->dial) {
2408                 MEM_freeN(rc->dial);
2409                 rc->dial = NULL;
2410         }
2411
2412         if (sa) {
2413                 ED_area_headerprint(sa, NULL);
2414         }
2415
2416         WM_paint_cursor_end(wm, rc->cursor);
2417
2418         /* restore original paint cursors */
2419         wm->paintcursors = rc->orig_paintcursors;
2420
2421         /* not sure if this is a good notifier to use;
2422          * intended purpose is to update the UI so that the
2423          * new value is displayed in sliders/numfields */
2424         WM_event_add_notifier(C, NC_WINDOW, NULL);
2425
2426         glDeleteTextures(1, &rc->gltex);
2427
2428         MEM_freeN(rc);
2429 }
2430
2431 static int radial_control_modal(bContext *C, wmOperator *op, const wmEvent *event)
2432 {
2433         RadialControl *rc = op->customdata;
2434         float new_value, dist = 0.0f, zoom[2];
2435         float delta[2], ret = OPERATOR_RUNNING_MODAL;
2436         bool snap;
2437         float angle_precision = 0.0f;
2438         const bool has_numInput = hasNumInput(&rc->num_input);
2439         bool handled = false;
2440         float numValue;
2441         /* TODO: fix hardcoded events */
2442
2443         snap = event->ctrl != 0;
2444
2445         /* Modal numinput active, try to handle numeric inputs first... */
2446         if (event->val == KM_PRESS && has_numInput && handleNumInput(C, &rc->num_input, event)) {
2447                 handled = true;
2448                 applyNumInput(&rc->num_input, &numValue);
2449
2450                 if (rc->subtype == PROP_ANGLE) {
2451                         numValue = DEG2RADF(numValue);
2452                         numValue = fmod(numValue, 2.0f * (float)M_PI);
2453                         if (numValue < 0.0f)
2454                                 numValue += 2.0f * (float)M_PI;
2455                 }
2456
2457                 CLAMP(numValue, rc->min_value, rc->max_value);
2458                 new_value = numValue;
2459
2460                 radial_control_set_value(rc, new_value);
2461                 rc->current_value = new_value;
2462                 radial_control_update_header(op, C);
2463                 return OPERATOR_RUNNING_MODAL;
2464         }
2465         else {
2466                 handled = false;
2467                 switch (event->type) {
2468                         case ESCKEY:
2469                         case RIGHTMOUSE:
2470                                 /* canceled; restore original value */
2471                                 radial_control_set_value(rc, rc->initial_value);
2472                                 ret = OPERATOR_CANCELLED;
2473                                 break;
2474
2475                         case LEFTMOUSE:
2476                         case PADENTER:
2477                         case RETKEY:
2478                                 /* done; value already set */
2479                                 RNA_property_update(C, &rc->ptr, rc->prop);
2480                                 ret = OPERATOR_FINISHED;
2481                                 break;
2482
2483                         case MOUSEMOVE:
2484                                 if (!has_numInput) {
2485                                         if (rc->slow_mode) {
2486                                                 if (rc->subtype == PROP_ANGLE) {
2487                                                         float position[2] = {event->x, event->y};
2488
2489                                                         /* calculate the initial angle here first */
2490                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2491                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2492
2493                                                         /* precision angle gets calculated from dial and gets added later */
2494                                                         angle_precision = -0.1f * BLI_dial_angle(rc->dial, position);
2495                                                 }
2496                                                 else {
2497                                                         delta[0] = rc->initial_mouse[0] - rc->slow_mouse[0];
2498                                                         delta[1] = rc->initial_mouse[1] - rc->slow_mouse[1];
2499
2500                                                         if (rc->zoom_prop) {
2501                                                                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2502                                                                 delta[0] /= zoom[0];
2503                                                                 delta[1] /= zoom[1];
2504                                                         }
2505
2506                                                         dist = len_v2(delta);
2507
2508                                                         delta[0] = event->x - rc->slow_mouse[0];
2509                                                         delta[1] = event->y - rc->slow_mouse[1];
2510
2511                                                         if (rc->zoom_prop) {
2512                                                                 delta[0] /= zoom[0];
2513                                                                 delta[1] /= zoom[1];
2514                                                         }
2515
2516                                                         dist = dist + 0.1f * (delta[0] + delta[1]);
2517                                                 }
2518                                         }
2519                                         else {
2520                                                 delta[0] = rc->initial_mouse[0] - event->x;
2521                                                 delta[1] = rc->initial_mouse[1] - event->y;
2522
2523                                                 if (rc->zoom_prop) {
2524                                                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2525                                                         delta[0] /= zoom[0];
2526                                                         delta[1] /= zoom[1];
2527                                                 }
2528
2529                                                 dist = len_v2(delta);
2530                                         }
2531
2532                                         /* calculate new value and apply snapping  */
2533                                         switch (rc->subtype) {
2534                                                 case PROP_NONE:
2535                                                 case PROP_DISTANCE:
2536                                                 case PROP_PIXEL:
2537                                                         new_value = dist;
2538                                                         if (snap) new_value = ((int)new_value + 5) / 10 * 10;
2539                                                         break;
2540                                                 case PROP_PERCENTAGE:
2541                                                         new_value = ((dist - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE) / WM_RADIAL_CONTROL_DISPLAY_WIDTH) * 100.0f;
2542                                                         if (snap) new_value = ((int)(new_value + 2.5f)) / 5 * 5;
2543                                                         break;
2544                                                 case PROP_FACTOR:
2545                                                         new_value = (WM_RADIAL_CONTROL_DISPLAY_SIZE - dist) / WM_RADIAL_CONTROL_DISPLAY_WIDTH;
2546                                                         if (snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
2547                                                         break;
2548                                                 case PROP_ANGLE:
2549                                                         new_value = atan2f(delta[1], delta[0]) + (float)M_PI + angle_precision;
2550                                                         new_value = fmod(new_value, 2.0f * (float)M_PI);
2551                                                         if (new_value < 0.0f)
2552                                                                 new_value += 2.0f * (float)M_PI;
2553                                                         if (snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10 * 10);
2554                                                         break;
2555                                                 default:
2556                                                         new_value = dist; /* dummy value, should this ever happen? - campbell */
2557                                                         break;
2558                                         }
2559
2560                                         /* clamp and update */
2561                                         CLAMP(new_value, rc->min_value, rc->max_value);
2562                                         radial_control_set_value(rc, new_value);
2563                                         rc->current_value = new_value;
2564                                         handled = true;
2565                                         break;
2566                                 }
2567                                 break;
2568
2569                         case LEFTSHIFTKEY:
2570                         case RIGHTSHIFTKEY:
2571                         {
2572                                 if (event->val == KM_PRESS) {
2573                                         rc->slow_mouse[0] = event->x;
2574                                         rc->slow_mouse[1] = event->y;
2575                                         rc->slow_mode = true;
2576                                         if (rc->subtype == PROP_ANGLE) {
2577                                                 float initial_position[2] = {UNPACK2(rc->initial_mouse)};
2578                                                 float current_position[2] = {UNPACK2(rc->slow_mouse)};
2579                                                 rc->dial = BLI_dial_initialize(initial_position, 0.0f);
2580                                                 /* immediately set the position to get a an initial direction */
2581                                                 BLI_dial_angle(rc->dial, current_position);
2582                                         }
2583                                         handled = true;
2584                                 }
2585                                 if (event->val == KM_RELEASE) {
2586                                         rc->slow_mode = false;
2587                                         handled = true;
2588                                         if (rc->dial) {
2589                                                 MEM_freeN(rc->dial);
2590                                                 rc->dial = NULL;
2591                                         }
2592                                 }
2593                                 break;
2594                         }
2595                 }
2596
2597                 /* Modal numinput inactive, try to handle numeric inputs last... */
2598                 if (!handled && event->val == KM_PRESS && handleNumInput(C, &rc->num_input, event)) {
2599                         applyNumInput(&rc->num_input, &numValue);
2600
2601                         if (rc->subtype == PROP_ANGLE) {
2602                                 numValue = DEG2RADF(numValue);
2603                                 numValue = fmod(numValue, 2.0f * (float)M_PI);
2604                                 if (numValue < 0.0f)
2605                                         numValue += 2.0f * (float)M_PI;
2606                         }
2607
2608                         CLAMP(numValue, rc->min_value, rc->max_value);
2609                         new_value = numValue;
2610
2611                         radial_control_set_value(rc, new_value);
2612
2613                         rc->current_value = new_value;
2614                         radial_control_update_header(op, C);
2615                         return OPERATOR_RUNNING_MODAL;
2616                 }
2617         }
2618
2619         ED_region_tag_redraw(CTX_wm_region(C));
2620         radial_control_update_header(op, C);
2621
2622         if (ret != OPERATOR_RUNNING_MODAL)
2623                 radial_control_cancel(C, op);
2624
2625         return ret;
2626 }
2627
2628 static void WM_OT_radial_control(wmOperatorType *ot)
2629 {
2630         ot->name = "Radial Control";
2631         ot->idname = "WM_OT_radial_control";
2632         ot->description = "Set some size property (like e.g. brush size) with mouse wheel";
2633
2634         ot->invoke = radial_control_invoke;
2635         ot->modal = radial_control_modal;
2636         ot->cancel = radial_control_cancel;
2637
2638         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2639
2640         /* all paths relative to the context */
2641         PropertyRNA *prop;
2642         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");
2643         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2644
2645         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");
2646         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2647
2648         prop = RNA_def_string(ot->srna, "use_secondary", NULL, 0, "Use Secondary", "Path of property to select between the primary and secondary data paths");
2649         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2650
2651         prop = RNA_def_string(ot->srna, "rotation_path", NULL, 0, "Rotation Path", "Path of property used to rotate the texture display");
2652         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2653
2654         prop = RNA_def_string(ot->srna, "color_path", NULL, 0, "Color Path", "Path of property used to set the color of the control");
2655         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2656
2657         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");
2658         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2659
2660         prop = RNA_def_string(ot->srna, "fill_color_override_path", NULL, 0, "Fill Color Override Path", "");
2661         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2662         prop = RNA_def_string(ot->srna, "fill_color_override_test_path", NULL, 0, "Fill Color Override Test", "");
2663         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2664
2665         prop = RNA_def_string(ot->srna, "zoom_path", NULL, 0, "Zoom Path", "Path of property used to set the zoom level for the control");
2666         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2667
2668         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");
2669         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2670
2671         prop = RNA_def_boolean(ot->srna, "secondary_tex", false, "Secondary Texture", "Tweak brush secondary/mask texture");
2672         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2673 }
2674
2675 /* ************************** timer for testing ***************** */
2676
2677 /* uses no type defines, fully local testing function anyway... ;) */
2678
2679 static void redraw_timer_window_swap(bContext *C)
2680 {
2681         wmWindow *win = CTX_wm_window(C);
2682         ScrArea *sa;
2683         CTX_wm_menu_set(C, NULL);
2684
2685         for (sa = CTX_wm_screen(C)->areabase.first; sa; sa = sa->next)
2686                 ED_area_tag_redraw(sa);
2687         wm_draw_update(C);
2688
2689         CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2690 }
2691
2692 enum {
2693         eRTDrawRegion = 0,
2694         eRTDrawRegionSwap = 1,
2695         eRTDrawWindow = 2,
2696         eRTDrawWindowSwap = 3,
2697         eRTAnimationStep = 4,
2698         eRTAnimationPlay = 5,
2699         eRTUndo = 6,
2700 };
2701
2702 static const EnumPropertyItem redraw_timer_type_items[] = {
2703         {eRTDrawRegion, "DRAW", 0, "Draw Region", "Draw Region"},
2704         {eRTDrawRegionSwap, "DRAW_SWAP", 0, "Draw Region + Swap", "Draw Region and Swap"},
2705         {eRTDrawWindow, "DRAW_WIN", 0, "Draw Window", "Draw Window"},
2706         {eRTDrawWindowSwap, "DRAW_WIN_SWAP", 0, "Draw Window + Swap", "Draw Window and Swap"},
2707         {eRTAnimationStep, "ANIM_STEP", 0, "Anim Step", "Animation Steps"},
2708         {eRTAnimationPlay, "ANIM_PLAY", 0, "Anim Play", "Animation Playback"},
2709         {eRTUndo, "UNDO", 0, "Undo/Redo", "Undo/Redo"},
2710         {0, NULL, 0, NULL, NULL}
2711 };
2712
2713
2714 static void redraw_timer_step(
2715         bContext *C, Main *bmain, Scene *scene,
2716         wmWindow *win, ScrArea *sa, ARegion *ar,
2717         const int type, const int cfra)
2718 {
2719         if (type == eRTDrawRegion) {
2720                 if (ar) {
2721                         ED_region_do_draw(C, ar);
2722                         ar->do_draw = false;
2723                 }
2724         }
2725         else if (type == eRTDrawRegionSwap) {
2726                 CTX_wm_menu_set(C, NULL);
2727
2728                 ED_region_tag_redraw(ar);
2729                 wm_draw_update(C);
2730
2731                 CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2732         }
2733         else if (type == eRTDrawWindow) {
2734                 ScrArea *sa_iter;
2735
2736                 CTX_wm_menu_set(C, NULL);
2737
2738                 for (sa_iter = win->screen->areabase.first; sa_iter; sa_iter = sa_iter->next) {
2739                         ARegion *ar_iter;
2740                         CTX_wm_area_set(C, sa_iter);
2741
2742                         for (ar_iter = sa_iter->regionbase.first; ar_iter; ar_iter = ar_iter->next) {
2743                                 if (ar_iter->swinid) {
2744                                         CTX_wm_region_set(C, ar_iter);
2745                                         ED_region_do_draw(C, ar_iter);
2746                                         ar_iter->do_draw = false;
2747                                 }
2748                         }
2749                 }
2750
2751                 CTX_wm_window_set(C, win);  /* XXX context manipulation warning! */
2752
2753                 CTX_wm_area_set(C, sa);
2754                 CTX_wm_region_set(C, ar);
2755         }
2756         else if (type == eRTDrawWindowSwap) {
2757                 redraw_timer_window_swap(C);
2758         }
2759         else if (type == eRTAnimationStep) {
2760                 scene->r.cfra += (cfra == scene->r.cfra) ? 1 : -1;
2761                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
2762         }
2763         else if (type == eRTAnimationPlay) {
2764                 /* play anim, return on same frame as started with */
2765                 int tot = (scene->r.efra - scene->r.sfra) + 1;
2766
2767                 while (tot--) {
2768                         /* todo, ability to escape! */
2769                         scene->r.cfra++;
2770                         if (scene->r.cfra > scene->r.efra)
2771                                 scene->r.cfra = scene->r.sfra;
2772
2773                         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
2774                         redraw_timer_window_swap(C);
2775                 }
2776         }
2777         else { /* eRTUndo */
2778                 ED_undo_pop(C);
2779                 ED_undo_redo(C);
2780         }
2781 }
2782
2783 static int redraw_timer_exec(bContext *C, wmOperator *op)
2784 {
2785         Main *bmain = CTX_data_main(C);
2786         Scene *scene = CTX_data_scene(C);
2787         wmWindow *win = CTX_wm_window(C);
2788         ScrArea *sa = CTX_wm_area(C);
2789         ARegion *ar = CTX_wm_region(C);
2790         double time_start, time_delta;
2791         const int type = RNA_enum_get(op->ptr, "type");
2792         const int iter = RNA_int_get(op->ptr, "iterations");
2793         const double time_limit = (double)RNA_float_get(op->ptr, "time_limit");
2794         const int cfra = scene->r.cfra;
2795         int a, iter_steps = 0;
2796         const char *infostr = "";
2797
2798         WM_cursor_wait(1);
2799
2800         time_start = PIL_check_seconds_timer();
2801
2802         for (a = 0; a < iter; a++) {
2803                 redraw_timer_step(C, bmain, scene, win, sa, ar, type, cfra);
2804                 iter_steps += 1;
2805
2806                 if (time_limit != 0.0) {
2807                         if ((PIL_check_seconds_timer() - time_start) > time_limit) {
2808                                 break;
2809                         }
2810                         a = 0;
2811                 }
2812         }
2813
2814         time_delta = (PIL_check_seconds_timer() - time_start) * 1000;
2815
2816         RNA_enum_description(redraw_timer_type_items, type, &infostr);
2817
2818         WM_cursor_wait(0);
2819
2820         BKE_reportf(op->reports, RPT_WARNING,
2821                     "%d x %s: %.4f ms, average: %.8f ms",
2822                     iter_steps, infostr, time_delta, time_delta / iter_steps);
2823
2824         return OPERATOR_FINISHED;
2825 }
2826
2827 static void WM_OT_redraw_timer(wmOperatorType *ot)
2828 {
2829         ot->name = "Redraw Timer";
2830         ot->idname = "WM_OT_redraw_timer";
2831         ot->description = "Simple redraw timer to test the speed of updating the interface";
2832
2833         ot->invoke = WM_menu_invoke;
2834         ot->exec = redraw_timer_exec;
2835         ot->poll = WM_operator_winactive;
2836
2837         ot->prop = RNA_def_enum(ot->srna, "type", redraw_timer_type_items, eRTDrawRegion, "Type", "");
2838         RNA_def_int(ot->srna, "iterations", 10, 1, INT_MAX, "Iterations", "Number of times to redraw", 1, 1000);
2839         RNA_def_float(ot->srna, "time_limit", 0.0, 0.0, FLT_MAX,
2840                       "Time Limit", "Seconds to run the test for (override iterations)", 0.0, 60.0);
2841
2842 }
2843
2844 /* ************************** memory statistics for testing ***************** */
2845
2846 static int memory_statistics_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2847 {
2848         MEM_printmemlist_stats();
2849         return OPERATOR_FINISHED;
2850 }
2851
2852 static void WM_OT_memory_statistics(wmOperatorType *ot)
2853 {
2854         ot->name = "Memory Statistics";
2855         ot->idname = "WM_OT_memory_statistics";
2856         ot->description = "Print memory statistics to the console";
2857
2858         ot->exec = memory_statistics_exec;
2859 }
2860
2861 /* ************************** memory statistics for testing ***************** */
2862
2863 static int dependency_relations_exec(bContext *C, wmOperator *UNUSED(op))
2864 {
2865         Main *bmain = CTX_data_main(C);
2866         Scene *scene = CTX_data_scene(C);
2867         Object *ob = CTX_data_active_object(C);
2868
2869         DAG_print_dependencies(bmain, scene, ob);
2870
2871         return OPERATOR_FINISHED;
2872 }
2873
2874 static void WM_OT_dependency_relations(wmOperatorType *ot)
2875 {
2876         ot->name = "Dependency Relations";
2877         ot->idname = "WM_OT_dependency_relations";
2878         ot->description = "Print dependency graph relations to the console";
2879
2880         ot->exec = dependency_relations_exec;
2881 }
2882
2883 /* *************************** Mat/tex/etc. previews generation ************* */
2884
2885 typedef struct PreviewsIDEnsureData {
2886         bContext *C;
2887         Scene *scene;
2888 } PreviewsIDEnsureData;
2889
2890 static void previews_id_ensure(bContext *C, Scene *scene, ID *id)
2891 {
2892         BLI_assert(ELEM(GS(id->name), ID_MA, ID_TE, ID_IM, ID_WO, ID_LA));
2893
2894         /* Only preview non-library datablocks, lib ones do not pertain to this .blend file!
2895          * Same goes for ID with no user. */
2896         if (!ID_IS_LINKED(id) && (id->us != 0)) {
2897                 UI_id_icon_render(C, scene, id, false, false);
2898                 UI_id_icon_render(C, scene, id, true, false);
2899         }
2900 }
2901
2902 static int previews_id_ensure_callback(void *userdata, ID *UNUSED(self_id), ID **idptr, int cb_flag)
2903 {
2904         if (cb_flag & IDWALK_CB_PRIVATE) {
2905                 return IDWALK_RET_NOP;
2906         }
2907
2908         PreviewsIDEnsureData *data = userdata;
2909         ID *id = *idptr;
2910
2911         if (id && (id->tag & LIB_TAG_DOIT)) {
2912                 BLI_assert(ELEM(GS(id->name), ID_MA, ID_TE, ID_IM, ID_WO, ID_LA));
2913                 previews_id_ensure(data->C, data->scene, id);
2914                 id->tag &= ~LIB_TAG_DOIT;
2915         }
2916
2917         return IDWALK_RET_NOP;
2918 }
2919
2920 static int previews_ensure_exec(bContext *C, wmOperator *UNUSED(op))
2921 {
2922         Main *bmain = CTX_data_main(C);
2923         ListBase *lb[] = {&bmain->mat, &bmain->tex, &bmain->image, &bmain->world, &bmain->lamp, NULL};
2924         PreviewsIDEnsureData preview_id_data;
2925         Scene *scene;
2926         ID *id;
2927         int i;
2928
2929         /* We use LIB_TAG_DOIT to check whether we have already handled a given ID or not. */
2930         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
2931         for (i = 0; lb[i]; i++) {
2932                 BKE_main_id_tag_listbase(lb[i], LIB_TAG_DOIT, true);
2933         }
2934
2935         preview_id_data.C = C;
2936         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
2937                 preview_id_data.scene = scene;
2938                 id = (ID *)scene;
2939
2940                 BKE_library_foreach_ID_link(NULL, id, previews_id_ensure_callback, &preview_id_data, IDWALK_RECURSE);
2941         }
2942
2943         /* Check a last time for ID not used (fake users only, in theory), and
2944          * do our best for those, using current scene... */
2945         for (i = 0; lb[i]; i++) {
2946                 for (id = lb[i]->first; id; id = id->next) {
2947                         if (id->tag & LIB_TAG_DOIT) {
2948                                 previews_id_ensure(C, NULL, id);
2949                                 id->tag &= ~LIB_TAG_DOIT;
2950                         }
2951                 }
2952         }
2953
2954         return OPERATOR_FINISHED;
2955 }
2956
2957 static void WM_OT_previews_ensure(wmOperatorType *ot)
2958 {
2959         ot->name = "Refresh Data-Block Previews";
2960         ot->idname = "WM_OT_previews_ensure";
2961         ot->description = "Ensure data-block previews are available and up-to-date "
2962                           "(to be saved in .blend file, only for some types like materials, textures, etc.)";
2963
2964         ot->exec = previews_ensure_exec;
2965 }
2966
2967 /* *************************** Datablocks previews clear ************* */
2968
2969 /* Only types supporting previews currently. */
2970 static const EnumPropertyItem preview_id_type_items[] = {
2971     {FILTER_ID_SCE, "SCENE", 0, "Scenes", ""},
2972     {FILTER_ID_GR, "GROUP", 0, "Groups", ""},
2973     {FILTER_ID_OB, "OBJECT", 0, "Objects", ""},
2974     {FILTER_ID_MA, "MATERIAL", 0, "Materials", ""},
2975     {FILTER_ID_LA, "LAMP", 0, "Lamps", ""},
2976     {FILTER_ID_WO, "WORLD", 0, "Worlds", ""},
2977     {FILTER_ID_TE, "TEXTURE", 0, "Textures", ""},
2978     {FILTER_ID_IM, "IMAGE", 0, "Images", ""},
2979 #if 0  /* XXX TODO */
2980     {FILTER_ID_BR, "BRUSH", 0, "Brushes", ""},
2981 #endif
2982     {0, NULL, 0, NULL, NULL}
2983 };
2984
2985 static int previews_clear_exec(bContext *C, wmOperator *op)
2986 {
2987         Main *bmain = CTX_data_main(C);
2988         ListBase *lb[] = {&bmain->object, &bmain->group,
2989                           &bmain->mat, &bmain->world, &bmain->lamp, &bmain->tex, &bmain->image, NULL};
2990         int i;
2991
2992         const int id_filters = RNA_enum_get(op->ptr, "id_type");
2993
2994         for (i = 0; lb[i]; i++) {
2995                 ID *id = lb[i]->first;
2996
2997                 if (!id) continue;
2998
2999 //              printf("%s: %d, %d, %d -> %d\n", id->name, GS(id->name), BKE_idcode_to_idfilter(GS(id->name)),
3000 //                                               id_filters, BKE_idcode_to_idfilter(GS(id->name)) & id_filters);
3001
3002                 if (!id || !(BKE_idcode_to_idfilter(GS(id->name)) & id_filters)) {
3003                         continue;
3004                 }
3005
3006                 for (; id; id = id->next) {
3007                         PreviewImage *prv_img = BKE_previewimg_id_ensure(id);
3008
3009                         BKE_previewimg_clear(prv_img);
3010                 }
3011         }
3012
3013         return OPERATOR_FINISHED;
3014 }
3015
3016 static void WM_OT_previews_clear(wmOperatorType *ot)
3017 {
3018         ot->name = "Clear Data-Block Previews";
3019         ot->idname = "WM_OT_previews_clear";
3020         ot->description = "Clear data-block previews (only for some types like objects, materials, textures, etc.)";
3021
3022         ot->exec = previews_clear_exec;
3023         ot->invoke = WM_menu_invoke;
3024
3025         ot->prop = RNA_def_enum_flag(ot->srna, "id_type", preview_id_type_items,
3026                                      FILTER_ID_SCE | FILTER_ID_OB | FILTER_ID_GR |
3027                                      FILTER_ID_MA | FILTER_ID_LA | FILTER_ID_WO | FILTER_ID_TE | FILTER_ID_IM,
3028                                      "Data-Block Type", "Which data-block previews to clear");
3029 }
3030
3031 /* *************************** Doc from UI ************* */
3032
3033 static int doc_view_manual_ui_context_exec(bContext *C, wmOperator *UNUSED(op))
3034 {
3035         PointerRNA ptr_props;
3036         char buf[512];
3037         short retval = OPERATOR_CANCELLED;
3038
3039         if (UI_but_online_manual_id_from_active(C, buf, sizeof(buf))) {
3040                 WM_operator_properties_create(&ptr_props, "WM_OT_doc_view_manual");
3041                 RNA_string_set(&ptr_props, "doc_id", buf);
3042
3043                 retval = WM_operator_name_call_ptr(
3044                         C, WM_operatortype_find("WM_OT_doc_view_manual", false),
3045                         WM_OP_EXEC_DEFAULT, &ptr_props);
3046
3047                 WM_operator_properties_free(&ptr_props);
3048         }
3049
3050         return retval;
3051 }
3052
3053 static void WM_OT_doc_view_manual_ui_context(wmOperatorType *ot)
3054 {
3055         /* identifiers */
3056         ot->name = "View Online Manual";
3057         ot->idname = "WM_OT_doc_view_manual_ui_context";
3058         ot->description = "View a context based online manual in a web browser";
3059
3060         /* callbacks */
3061         ot->poll = ED_operator_regionactive;
3062         ot->exec = doc_view_manual_ui_context_exec;
3063 }
3064
3065 /* ******************************************************* */
3066
3067 /* ******************************************************* */
3068 /* toggle 3D for current window, turning it fullscreen if needed */
3069 static void WM_OT_stereo3d_set(wmOperatorType *ot)
3070 {
3071         PropertyRNA *prop;
3072
3073         ot->name = "Set Stereo 3D";
3074         ot->idname = "WM_OT_set_stereo_3d";
3075         ot->description = "Toggle 3D stereo support for current window (or change the display mode)";
3076
3077         ot->exec = wm_stereo3d_set_exec;
3078         ot->invoke = wm_stereo3d_set_invoke;
3079         ot->poll = WM_operator_winactive;
3080         ot->ui = wm_stereo3d_set_draw;
3081         ot->check = wm_stereo3d_set_check;
3082         ot->cancel = wm_stereo3d_set_cancel;
3083
3084         prop = RNA_def_enum(ot->srna, "display_mode", rna_enum_stereo3d_display_items, S3D_DISPLAY_ANAGLYPH, "Display Mode", "");
3085         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3086         prop = RNA_def_enum(ot->srna, "anaglyph_type", rna_enum_stereo3d_anaglyph_type_items, S3D_ANAGLYPH_REDCYAN, "Anaglyph Type", "");
3087         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3088         prop = RNA_def_enum(ot->srna, "interlace_type", rna_enum_stereo3d_interlace_type_items, S3D_INTERLACE_ROW, "Interlace Type", "");
3089         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3090         prop = RNA_def_boolean(ot->srna, "use_interlace_swap", false, "Swap Left/Right",
3091                                "Swap left and right stereo channels");
3092         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3093         prop = RNA_def_boolean(ot->srna, "use_sidebyside_crosseyed", false, "Cross-Eyed",
3094                                "Right eye should see left image and vice-versa");
3095         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3096 }
3097
3098 void wm_operatortypes_register(void)
3099 {
3100         WM_operatortype_append(WM_OT_window_close);
3101         WM_operatortype_append(WM_OT_window_duplicate);
3102         WM_operatortype_append(WM_OT_read_history);
3103         WM_operatortype_append(WM_OT_read_homefile);
3104         WM_operatortype_append(WM_OT_read_factory_settings);
3105         WM_operatortype_append(WM_OT_save_homefile);
3106         WM_operatortype_append(WM_OT_save_userpref);
3107         WM_operatortype_append(WM_OT_userpref_autoexec_path_add);
3108         WM_operatortype_append(WM_OT_userpref_autoexec_path_remove);
3109         WM_operatortype_append(WM_OT_window_fullscreen_toggle);
3110         WM_operatortype_append(WM_OT_quit_blender);
3111         WM_operatortype_append(WM_OT_open_mainfile);
3112         WM_operatortype_append(WM_OT_revert_mainfile);
3113         WM_operatortype_append(WM_OT_link);
3114         WM_operatortype_append(WM_OT_append);
3115         WM_operatortype_append(WM_OT_lib_relocate);
3116         WM_operatortype_append(WM_OT_lib_reload);
3117         WM_operatortype_append(WM_OT_recover_last_session);
3118         WM_operatortype_append(WM_OT_recover_auto_save);
3119         WM_operatortype_append(WM_OT_save_as_mainfile);
3120         WM_operatortype_append(WM_OT_save_mainfile);
3121         WM_operatortype_append(WM_OT_redraw_timer);
3122         WM_operatortype_append(WM_OT_memory_statistics);
3123         WM_operatortype_append(WM_OT_dependency_relations);
3124         WM_operatortype_append(WM_OT_debug_menu);
3125         WM_operatortype_append(WM_OT_operator_defaults);
3126         WM_operatortype_append(WM_OT_splash);
3127         WM_operatortype_append(WM_OT_search_menu);
3128         WM_operatortype_append(WM_OT_call_menu);
3129         WM_operatortype_append(WM_OT_call_menu_pie);
3130         WM_operatortype_append(WM_OT_radial_control);
3131         WM_operatortype_append(WM_OT_stereo3d_set);
3132 #if defined(WIN32)
3133         WM_operatortype_append(WM_OT_console_toggle);
3134 #endif
3135         WM_operatortype_append(WM_OT_previews_ensure);
3136         WM_operatortype_append(WM_OT_previews_clear);
3137         WM_operatortype_append(WM_OT_doc_view_manual_ui_context);
3138 }
3139
3140 /* circleselect-like modal operators */
3141 static void gesture_circle_modal_keymap(wmKeyConfig *keyconf)
3142 {
3143         static const EnumPropertyItem modal_items[] = {
3144                 {GESTURE_MODAL_CANCEL,  "CANCEL", 0, "Cancel", ""},
3145                 {GESTURE_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
3146                 {GESTURE_MODAL_CIRCLE_ADD, "ADD", 0, "Add", ""},
3147                 {GESTURE_MODAL_CIRCLE_SUB, "SUBTRACT", 0, "Subtract", ""},
3148                 {GESTURE_MODAL_CIRCLE_SIZE, "SIZE", 0, "Size", ""},
3149
3150                 {GESTURE_MODAL_SELECT,  "SELECT", 0, "Select", ""},
3151                 {GESTURE_MODAL_DESELECT, "DESELECT", 0, "DeSelect", ""},
3152                 {GESTURE_MODAL_NOP, "NOP", 0, "No Operation",&nbs