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