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