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