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