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                         default:
914                                 break;
915                 }
916
917                 if (member_id) {
918                         prop_str = RNA_path_struct_property_py(ptr, prop, index);
919                         if (prop_str) {
920                                 ret = BLI_sprintfN("bpy.context.%s.%s", member_id, prop_str);
921                                 MEM_freeN(prop_str);
922                         }
923                 }
924 #undef CTX_TEST_PTR_ID
925 #undef CTX_TEST_PTR_ID_CAST
926 #undef CTX_TEST_SPACE_TYPE
927         }
928
929         return ret;
930 }
931 #endif
932
933 char *WM_prop_pystring_assign(bContext *C, PointerRNA *ptr, PropertyRNA *prop, int index)
934 {
935         char *lhs, *rhs, *ret;
936
937         lhs = C ? wm_prop_pystring_from_context(C, ptr, prop, index) : NULL;
938
939         if (lhs == NULL) {
940                 /* fallback to bpy.data.foo[id] if we dont find in the context */
941                 lhs = RNA_path_full_property_py(ptr, prop, index);
942         }
943
944         if (!lhs) {
945                 return NULL;
946         }
947
948         rhs = RNA_property_as_string(C, ptr, prop, index, INT_MAX);
949         if (!rhs) {
950                 MEM_freeN(lhs);
951                 return NULL;
952         }
953
954         ret = BLI_sprintfN("%s = %s", lhs, rhs);
955         MEM_freeN(lhs);
956         MEM_freeN(rhs);
957         return ret;
958 }
959
960 void WM_operator_properties_create_ptr(PointerRNA *ptr, wmOperatorType *ot)
961 {
962         RNA_pointer_create(NULL, ot->srna, NULL, ptr);
963 }
964
965 void WM_operator_properties_create(PointerRNA *ptr, const char *opstring)
966 {
967         wmOperatorType *ot = WM_operatortype_find(opstring, false);
968
969         if (ot)
970                 WM_operator_properties_create_ptr(ptr, ot);
971         else
972                 RNA_pointer_create(NULL, &RNA_OperatorProperties, NULL, ptr);
973 }
974
975 /* similar to the function above except its uses ID properties
976  * used for keymaps and macros */
977 void WM_operator_properties_alloc(PointerRNA **ptr, IDProperty **properties, const char *opstring)
978 {
979         if (*properties == NULL) {
980                 IDPropertyTemplate val = {0};
981                 *properties = IDP_New(IDP_GROUP, &val, "wmOpItemProp");
982         }
983
984         if (*ptr == NULL) {
985                 *ptr = MEM_callocN(sizeof(PointerRNA), "wmOpItemPtr");
986                 WM_operator_properties_create(*ptr, opstring);
987         }
988
989         (*ptr)->data = *properties;
990
991 }
992
993 void WM_operator_properties_sanitize(PointerRNA *ptr, const bool no_context)
994 {
995         RNA_STRUCT_BEGIN (ptr, prop)
996         {
997                 switch (RNA_property_type(prop)) {
998                         case PROP_ENUM:
999                                 if (no_context)
1000                                         RNA_def_property_flag(prop, PROP_ENUM_NO_CONTEXT);
1001                                 else
1002                                         RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1003                                 break;
1004                         case PROP_POINTER:
1005                         {
1006                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
1007
1008                                 /* recurse into operator properties */
1009                                 if (RNA_struct_is_a(ptype, &RNA_OperatorProperties)) {
1010                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1011                                         WM_operator_properties_sanitize(&opptr, no_context);
1012                                 }
1013                                 break;
1014                         }
1015                         default:
1016                                 break;
1017                 }
1018         }
1019         RNA_STRUCT_END;
1020 }
1021
1022
1023 /** set all props to their default,
1024  * \param do_update Only update un-initialized props.
1025  *
1026  * \note, theres nothing specific to operators here.
1027  * this could be made a general function.
1028  */
1029 bool WM_operator_properties_default(PointerRNA *ptr, const bool do_update)
1030 {
1031         bool changed = false;
1032         RNA_STRUCT_BEGIN (ptr, prop)
1033         {
1034                 switch (RNA_property_type(prop)) {
1035                         case PROP_POINTER:
1036                         {
1037                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
1038                                 if (ptype != &RNA_Struct) {
1039                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1040                                         changed |= WM_operator_properties_default(&opptr, do_update);
1041                                 }
1042                                 break;
1043                         }
1044                         default:
1045                                 if ((do_update == false) || (RNA_property_is_set(ptr, prop) == false)) {
1046                                         if (RNA_property_reset(ptr, prop, -1)) {
1047                                                 changed = true;
1048                                         }
1049                                 }
1050                                 break;
1051                 }
1052         }
1053         RNA_STRUCT_END;
1054
1055         return changed;
1056 }
1057
1058 /* remove all props without PROP_SKIP_SAVE */
1059 void WM_operator_properties_reset(wmOperator *op)
1060 {
1061         if (op->ptr->data) {
1062                 PropertyRNA *iterprop;
1063                 iterprop = RNA_struct_iterator_property(op->type->srna);
1064
1065                 RNA_PROP_BEGIN (op->ptr, itemptr, iterprop)
1066                 {
1067                         PropertyRNA *prop = itemptr.data;
1068
1069                         if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
1070                                 const char *identifier = RNA_property_identifier(prop);
1071                                 RNA_struct_idprops_unset(op->ptr, identifier);
1072                         }
1073                 }
1074                 RNA_PROP_END;
1075         }
1076 }
1077
1078 void WM_operator_properties_clear(PointerRNA *ptr)
1079 {
1080         IDProperty *properties = ptr->data;
1081
1082         if (properties) {
1083                 IDP_ClearProperty(properties);
1084         }
1085 }
1086
1087 void WM_operator_properties_free(PointerRNA *ptr)
1088 {
1089         IDProperty *properties = ptr->data;
1090
1091         if (properties) {
1092                 IDP_FreeProperty(properties);
1093                 MEM_freeN(properties);
1094                 ptr->data = NULL; /* just in case */
1095         }
1096 }
1097
1098 /* ************ default op callbacks, exported *********** */
1099
1100 void WM_operator_view3d_unit_defaults(struct bContext *C, struct wmOperator *op)
1101 {
1102         if (op->flag & OP_IS_INVOKE) {
1103                 Scene *scene = CTX_data_scene(C);
1104                 View3D *v3d = CTX_wm_view3d(C);
1105
1106                 const float dia = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
1107
1108                 /* always run, so the values are initialized,
1109                  * otherwise we may get differ behavior when (dia != 1.0) */
1110                 RNA_STRUCT_BEGIN (op->ptr, prop)
1111                 {
1112                         if (RNA_property_type(prop) == PROP_FLOAT) {
1113                                 PropertySubType pstype = RNA_property_subtype(prop);
1114                                 if (pstype == PROP_DISTANCE) {
1115                                         /* we don't support arrays yet */
1116                                         BLI_assert(RNA_property_array_check(prop) == false);
1117                                         /* initialize */
1118                                         if (!RNA_property_is_set_ex(op->ptr, prop, false)) {
1119                                                 const float value = RNA_property_float_get_default(op->ptr, prop) * dia;
1120                                                 RNA_property_float_set(op->ptr, prop, value);
1121                                         }
1122                                 }
1123                         }
1124                 }
1125                 RNA_STRUCT_END;
1126         }
1127 }
1128
1129 int WM_operator_smooth_viewtx_get(const wmOperator *op)
1130 {
1131         return (op->flag & OP_IS_INVOKE) ? U.smooth_viewtx : 0;
1132 }
1133
1134 /* invoke callback, uses enum property named "type" */
1135 int WM_menu_invoke_ex(bContext *C, wmOperator *op, int opcontext)
1136 {
1137         PropertyRNA *prop = op->type->prop;
1138         uiPopupMenu *pup;
1139         uiLayout *layout;
1140
1141         if (prop == NULL) {
1142                 printf("%s: %s has no enum property set\n", __func__, op->type->idname);
1143         }
1144         else if (RNA_property_type(prop) != PROP_ENUM) {
1145                 printf("%s: %s \"%s\" is not an enum property\n",
1146                        __func__, op->type->idname, RNA_property_identifier(prop));
1147         }
1148         else if (RNA_property_is_set(op->ptr, prop)) {
1149                 const int retval = op->type->exec(C, op);
1150                 OPERATOR_RETVAL_CHECK(retval);
1151                 return retval;
1152         }
1153         else {
1154                 pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
1155                 layout = UI_popup_menu_layout(pup);
1156                 /* set this so the default execution context is the same as submenus */
1157                 uiLayoutSetOperatorContext(layout, opcontext);
1158                 uiItemsFullEnumO(layout, op->type->idname, RNA_property_identifier(prop), op->ptr->data, opcontext, 0);
1159                 UI_popup_menu_end(C, pup);
1160                 return OPERATOR_INTERFACE;
1161         }
1162
1163         return OPERATOR_CANCELLED;
1164 }
1165
1166 int WM_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1167 {
1168         return WM_menu_invoke_ex(C, op, WM_OP_INVOKE_REGION_WIN);
1169 }
1170
1171 struct EnumSearchMenu {
1172         wmOperator *op; /* the operator that will be executed when selecting an item */
1173
1174         bool use_previews;
1175         short prv_cols, prv_rows;
1176 };
1177
1178 /* generic enum search invoke popup */
1179 static uiBlock *wm_enum_search_menu(bContext *C, ARegion *ar, void *arg)
1180 {
1181         struct EnumSearchMenu *search_menu = arg;
1182         wmWindow *win = CTX_wm_window(C);
1183         wmOperator *op = search_menu->op;
1184         /* template_ID uses 4 * widget_unit for width, we use a bit more, some items may have a suffix to show */
1185         const int width = search_menu->use_previews ? 5 * U.widget_unit * search_menu->prv_cols : UI_searchbox_size_x();
1186         const int height = search_menu->use_previews ? 5 * U.widget_unit * search_menu->prv_rows : UI_searchbox_size_y();
1187         static char search[256] = "";
1188         uiBlock *block;
1189         uiBut *but;
1190
1191         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1192         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
1193
1194         search[0] = '\0';
1195         BLI_assert(search_menu->use_previews || (search_menu->prv_cols == 0 && search_menu->prv_rows == 0));
1196 #if 0 /* ok, this isn't so easy... */
1197         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, "");
1198 #endif
1199         but = uiDefSearchButO_ptr(block, op->type, op->ptr->data, search, 0, ICON_VIEWZOOM, sizeof(search),
1200                                   10, 10, width, UI_UNIT_Y, search_menu->prv_rows, search_menu->prv_cols, "");
1201
1202         /* fake button, it holds space for search items */
1203         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - UI_searchbox_size_y(), width, height, NULL, 0, 0, 0, 0, NULL);
1204
1205         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1206         UI_but_focus_on_enter_event(win, but);
1207
1208         return block;
1209 }
1210
1211 /**
1212  * Similar to #WM_enum_search_invoke, but draws previews. Also, this can't
1213  * be used as invoke callback directly since it needs additional info.
1214  */
1215 int WM_enum_search_invoke_previews(
1216         bContext *C, wmOperator *op, short prv_cols, short prv_rows)
1217 {
1218         static struct EnumSearchMenu search_menu;
1219
1220         search_menu.op = op;
1221         search_menu.use_previews = true;
1222         search_menu.prv_cols = prv_cols;
1223         search_menu.prv_rows = prv_rows;
1224
1225         UI_popup_block_invoke(C, wm_enum_search_menu, &search_menu);
1226
1227         return OPERATOR_INTERFACE;
1228 }
1229
1230 int WM_enum_search_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1231 {
1232         static struct EnumSearchMenu search_menu;
1233         search_menu.op = op;
1234         UI_popup_block_invoke(C, wm_enum_search_menu, &search_menu);
1235         return OPERATOR_INTERFACE;
1236 }
1237
1238 /* Can't be used as an invoke directly, needs message arg (can be NULL) */
1239 int WM_operator_confirm_message_ex(bContext *C, wmOperator *op,
1240                                    const char *title, const int icon,
1241                                    const char *message)
1242 {
1243         uiPopupMenu *pup;
1244         uiLayout *layout;
1245         IDProperty *properties = op->ptr->data;
1246
1247         if (properties && properties->len)
1248                 properties = IDP_CopyProperty(op->ptr->data);
1249         else
1250                 properties = NULL;
1251
1252         pup = UI_popup_menu_begin(C, title, icon);
1253         layout = UI_popup_menu_layout(pup);
1254         uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0);
1255         UI_popup_menu_end(C, pup);
1256         
1257         return OPERATOR_INTERFACE;
1258 }
1259
1260 int WM_operator_confirm_message(bContext *C, wmOperator *op, const char *message)
1261 {
1262         return WM_operator_confirm_message_ex(C, op, IFACE_("OK?"), ICON_QUESTION, message);
1263 }
1264
1265 int WM_operator_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1266 {
1267         return WM_operator_confirm_message(C, op, NULL);
1268 }
1269
1270 /* op->invoke, opens fileselect if path property not set, otherwise executes */
1271 int WM_operator_filesel(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1272 {
1273         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1274                 return WM_operator_call_notest(C, op); /* call exec direct */
1275         }
1276         else {
1277                 WM_event_add_fileselect(C, op);
1278                 return OPERATOR_RUNNING_MODAL;
1279         }
1280 }
1281
1282 bool WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const struct ImageFormatData *im_format)
1283 {
1284         PropertyRNA *prop;
1285         char filepath[FILE_MAX];
1286         /* dont NULL check prop, this can only run on ops with a 'filepath' */
1287         prop = RNA_struct_find_property(op->ptr, "filepath");
1288         RNA_property_string_get(op->ptr, prop, filepath);
1289         if (BKE_image_path_ensure_ext_from_imformat(filepath, im_format)) {
1290                 RNA_property_string_set(op->ptr, prop, filepath);
1291                 /* note, we could check for and update 'filename' here,
1292                  * but so far nothing needs this. */
1293                 return true;
1294         }
1295         return false;
1296 }
1297
1298 /* op->poll */
1299 int WM_operator_winactive(bContext *C)
1300 {
1301         if (CTX_wm_window(C) == NULL) return 0;
1302         return 1;
1303 }
1304
1305 /* return false, if the UI should be disabled */
1306 bool WM_operator_check_ui_enabled(const bContext *C, const char *idname)
1307 {
1308         wmWindowManager *wm = CTX_wm_manager(C);
1309         Scene *scene = CTX_data_scene(C);
1310
1311         return !((ED_undo_is_valid(C, idname) == false) || WM_jobs_test(wm, scene, WM_JOB_TYPE_ANY));
1312 }
1313
1314 wmOperator *WM_operator_last_redo(const bContext *C)
1315 {
1316         wmWindowManager *wm = CTX_wm_manager(C);
1317         wmOperator *op;
1318
1319         /* only for operators that are registered and did an undo push */
1320         for (op = wm->operators.last; op; op = op->prev)
1321                 if ((op->type->flag & OPTYPE_REGISTER) && (op->type->flag & OPTYPE_UNDO))
1322                         break;
1323
1324         return op;
1325 }
1326
1327 /**
1328  * Use for drag & drop a path or name with operators invoke() function.
1329  */
1330 ID *WM_operator_drop_load_path(struct bContext *C, wmOperator *op, const short idcode)
1331 {
1332         ID *id = NULL;
1333         /* check input variables */
1334         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1335                 const bool is_relative_path = RNA_boolean_get(op->ptr, "relative_path");
1336                 char path[FILE_MAX];
1337                 bool exists = false;
1338
1339                 RNA_string_get(op->ptr, "filepath", path);
1340
1341                 errno = 0;
1342
1343                 if (idcode == ID_IM) {
1344                         id = (ID *)BKE_image_load_exists_ex(path, &exists);
1345                 }
1346                 else {
1347                         BLI_assert(0);
1348                 }
1349
1350                 if (!id) {
1351                         BKE_reportf(op->reports, RPT_ERROR, "Cannot read %s '%s': %s",
1352                                     BKE_idcode_to_name(idcode), path,
1353                                     errno ? strerror(errno) : TIP_("unsupported format"));
1354                         return NULL;
1355                 }
1356
1357                 if (is_relative_path ) {
1358                         if (exists == false) {
1359                                 Main *bmain = CTX_data_main(C);
1360
1361                                 if (idcode == ID_IM) {
1362                                         BLI_path_rel(((Image *)id)->name, bmain->name);
1363                                 }
1364                                 else {
1365                                         BLI_assert(0);
1366                                 }
1367                         }
1368                 }
1369         }
1370         else if (RNA_struct_property_is_set(op->ptr, "name")) {
1371                 char name[MAX_ID_NAME - 2];
1372                 RNA_string_get(op->ptr, "name", name);
1373                 id = BKE_libblock_find_name(idcode, name);
1374                 if (!id) {
1375                         BKE_reportf(op->reports, RPT_ERROR, "%s '%s' not found",
1376                                     BKE_idcode_to_name(idcode), name);
1377                         return NULL;
1378                 }
1379                 id_us_plus(id);
1380         }
1381
1382         return id;
1383 }
1384
1385 static void wm_block_redo_cb(bContext *C, void *arg_op, int UNUSED(arg_event))
1386 {
1387         wmOperator *op = arg_op;
1388
1389         if (op == WM_operator_last_redo(C)) {
1390                 /* operator was already executed once? undo & repeat */
1391                 ED_undo_operator_repeat(C, op);
1392         }
1393         else {
1394                 /* operator not executed yet, call it */
1395                 ED_undo_push_op(C, op);
1396                 wm_operator_register(C, op);
1397
1398                 WM_operator_repeat(C, op);
1399         }
1400 }
1401
1402 static void wm_block_redo_cancel_cb(bContext *C, void *arg_op)
1403 {
1404         wmOperator *op = arg_op;
1405
1406         /* if operator never got executed, free it */
1407         if (op != WM_operator_last_redo(C))
1408                 WM_operator_free(op);
1409 }
1410
1411 static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
1412 {
1413         wmOperator *op = arg_op;
1414         uiBlock *block;
1415         uiLayout *layout;
1416         uiStyle *style = UI_style_get();
1417         int width = 15 * UI_UNIT_X;
1418
1419         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1420         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1421         /* UI_BLOCK_NUMSELECT for layer buttons */
1422         UI_block_flag_enable(block, UI_BLOCK_NUMSELECT | UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1423
1424         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
1425          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
1426         assert(op->type->flag & OPTYPE_REGISTER);
1427
1428         UI_block_func_handle_set(block, wm_block_redo_cb, arg_op);
1429         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, 0, style);
1430
1431         if (op == WM_operator_last_redo(C))
1432                 if (!WM_operator_check_ui_enabled(C, op->type->name))
1433                         uiLayoutSetEnabled(layout, false);
1434
1435         if (op->type->flag & OPTYPE_MACRO) {
1436                 for (op = op->macro.first; op; op = op->next) {
1437                         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1438                         if (op->next)
1439                                 uiItemS(layout);
1440                 }
1441         }
1442         else {
1443                 uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1444         }
1445         
1446         UI_block_bounds_set_popup(block, 4, 0, 0);
1447
1448         return block;
1449 }
1450
1451 typedef struct wmOpPopUp {
1452         wmOperator *op;
1453         int width;
1454         int height;
1455         int free_op;
1456 } wmOpPopUp;
1457
1458 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1459 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1460 {
1461         wmOpPopUp *data = arg1;
1462         uiBlock *block = arg2;
1463
1464         /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be cancelled
1465          * in case WM_operator_call_ex exits/reloads the current file (T49199). */
1466         UI_popup_menu_retval_set(block, UI_RETURN_OK, true);
1467
1468         WM_operator_call_ex(C, data->op, true);
1469
1470         /* let execute handle freeing it */
1471         //data->free_op = false;
1472         //data->op = NULL;
1473
1474         /* in this case, wm_operator_ui_popup_cancel wont run */
1475         MEM_freeN(data);
1476
1477         /* get context data *after* WM_operator_call_ex which might have closed the current file and changed context */
1478         wmWindowManager *wm = CTX_wm_manager(C);
1479         wmWindow *win = CTX_wm_window(C);
1480
1481         /* check window before 'block->handle' incase the
1482          * popup execution closed the window and freed the block. see T44688.
1483          */
1484         /* Post 2.78 TODO: Check if this fix and others related to T44688 are still
1485          * needed or can be improved now that requesting context data has been corrected
1486          * (see above). We're close to release so not a good time for experiments.
1487          * -- Julian
1488          */
1489         if (BLI_findindex(&wm->windows, win) != -1) {
1490                 UI_popup_block_close(C, win, block);
1491         }
1492 }
1493
1494 /* Dialogs are popups that require user verification (click OK) before exec */
1495 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1496 {
1497         wmOpPopUp *data = userData;
1498         wmOperator *op = data->op;
1499         uiBlock *block;
1500         uiLayout *layout;
1501         uiStyle *style = UI_style_get();
1502
1503         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1504         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1505
1506         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogues have many items
1507          * where quitting by accident is very annoying */
1508         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NUMSELECT);
1509
1510         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1511         
1512         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1513         
1514         /* clear so the OK button is left alone */
1515         UI_block_func_set(block, NULL, NULL, NULL);
1516
1517         /* new column so as not to interfere with custom layouts [#26436] */
1518         {
1519                 uiBlock *col_block;
1520                 uiLayout *col;
1521                 uiBut *btn;
1522
1523                 col = uiLayoutColumn(layout, false);
1524                 col_block = uiLayoutGetBlock(col);
1525                 /* Create OK button, the callback of which will execute op */
1526                 btn = uiDefBut(col_block, UI_BTYPE_BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1527                 UI_but_func_set(btn, dialog_exec_cb, data, col_block);
1528         }
1529
1530         /* center around the mouse */
1531         UI_block_bounds_set_popup(block, 4, data->width / -2, data->height / 2);
1532
1533         return block;
1534 }
1535
1536 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1537 {
1538         wmOpPopUp *data = userData;
1539         wmOperator *op = data->op;
1540         uiBlock *block;
1541         uiLayout *layout;
1542         uiStyle *style = UI_style_get();
1543
1544         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1545         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1546         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1547
1548         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1549
1550         /* since ui is defined the auto-layout args are not used */
1551         uiLayoutOperatorButs(C, layout, op, NULL, 'V', 0);
1552
1553         UI_block_func_set(block, NULL, NULL, NULL);
1554
1555         UI_block_bounds_set_popup(block, 4, 0, 0);
1556
1557         return block;
1558 }
1559
1560 static void wm_operator_ui_popup_cancel(struct bContext *C, void *userData)
1561 {
1562         wmOpPopUp *data = userData;
1563         wmOperator *op = data->op;
1564
1565         if (op) {
1566                 if (op->type->cancel) {
1567                         op->type->cancel(C, op);
1568                 }
1569
1570                 if (data->free_op) {
1571                         WM_operator_free(op);
1572                 }
1573         }
1574
1575         MEM_freeN(data);
1576 }
1577
1578 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1579 {
1580         wmOpPopUp *data = arg;
1581         wmOperator *op = data->op;
1582
1583         if (op && retval > 0)
1584                 WM_operator_call_ex(C, op, true);
1585         
1586         MEM_freeN(data);
1587 }
1588
1589 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1590 {
1591         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1592         data->op = op;
1593         data->width = width;
1594         data->height = height;
1595         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1596         UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data, op);
1597         return OPERATOR_RUNNING_MODAL;
1598 }
1599
1600 /**
1601  * For use by #WM_operator_props_popup_call, #WM_operator_props_popup only.
1602  *
1603  * \note operator menu needs undo flag enabled, for redo callback */
1604 static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
1605                                       const bool do_call, const bool do_redo)
1606 {
1607         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1608                 BKE_reportf(op->reports, RPT_ERROR,
1609                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1610                 return OPERATOR_CANCELLED;
1611         }
1612
1613         if (do_redo) {
1614                 if ((op->type->flag & OPTYPE_UNDO) == 0) {
1615                         BKE_reportf(op->reports, RPT_ERROR,
1616                                     "Operator '%s' does not have undo enabled, incorrect invoke function", op->type->idname);
1617                         return OPERATOR_CANCELLED;
1618                 }
1619         }
1620
1621         /* if we don't have global undo, we can't do undo push for automatic redo,
1622          * so we require manual OK clicking in this popup */
1623         if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
1624                 return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
1625
1626         UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op, op);
1627
1628         if (do_call)
1629                 wm_block_redo_cb(C, op, 0);
1630
1631         return OPERATOR_RUNNING_MODAL;
1632 }
1633
1634 /**
1635  * Same as #WM_operator_props_popup but don't use operator redo.
1636  * just wraps #WM_operator_props_dialog_popup.
1637  */
1638 int WM_operator_props_popup_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1639 {
1640         return wm_operator_props_popup_ex(C, op, false, false);
1641 }
1642
1643 /**
1644  * Same as #WM_operator_props_popup but call the operator first,
1645  * This way - the button values correspond to the result of the operator.
1646  * Without this, first access to a button will make the result jump, see T32452.
1647  */
1648 int WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1649 {
1650         return wm_operator_props_popup_ex(C, op, true, true);
1651 }
1652
1653 int WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1654 {
1655         return wm_operator_props_popup_ex(C, op, false, true);
1656 }
1657
1658 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1659 {
1660         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1661         
1662         data->op = op;
1663         data->width = width;
1664         data->height = height;
1665         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1666
1667         /* op is not executed until popup OK but is clicked */
1668         UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data, op);
1669
1670         return OPERATOR_RUNNING_MODAL;
1671 }
1672
1673 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1674 {
1675         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1676         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1677                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1678                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1679                 return OPERATOR_CANCELLED;
1680         }
1681         if (op->type->poll && op->type->poll(C) == 0) {
1682                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1683                 return OPERATOR_CANCELLED;
1684         }
1685         
1686         UI_popup_block_invoke(C, wm_block_create_redo, op);
1687
1688         return OPERATOR_CANCELLED;
1689 }
1690
1691 /* ***************** Debug menu ************************* */
1692
1693 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1694 {
1695         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1696         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1697         WM_event_add_notifier(C, NC_WINDOW, NULL);
1698
1699         return OPERATOR_FINISHED;
1700 }
1701
1702 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1703 {
1704         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1705         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1706 }
1707
1708 static void WM_OT_debug_menu(wmOperatorType *ot)
1709 {
1710         ot->name = "Debug Menu";
1711         ot->idname = "WM_OT_debug_menu";
1712         ot->description = "Open a popup to set the debug level";
1713         
1714         ot->invoke = wm_debug_menu_invoke;
1715         ot->exec = wm_debug_menu_exec;
1716         ot->poll = WM_operator_winactive;
1717         
1718         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1719 }
1720
1721 /* ***************** Operator defaults ************************* */
1722 static int wm_operator_defaults_exec(bContext *C, wmOperator *op)
1723 {
1724         PointerRNA ptr = CTX_data_pointer_get_type(C, "active_operator", &RNA_Operator);
1725
1726         if (!ptr.data) {
1727                 BKE_report(op->reports, RPT_ERROR, "No operator in context");
1728                 return OPERATOR_CANCELLED;
1729         }
1730
1731         WM_operator_properties_reset((wmOperator *)ptr.data);
1732         return OPERATOR_FINISHED;
1733 }
1734
1735 /* used by operator preset menu. pre-2.65 this was a 'Reset' button */
1736 static void WM_OT_operator_defaults(wmOperatorType *ot)
1737 {
1738         ot->name = "Restore Defaults";
1739         ot->idname = "WM_OT_operator_defaults";
1740         ot->description = "Set the active operator to its default values";
1741
1742         ot->exec = wm_operator_defaults_exec;
1743
1744         ot->flag = OPTYPE_INTERNAL;
1745 }
1746
1747 /* ***************** Splash Screen ************************* */
1748
1749 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1750 {
1751         wmWindow *win = CTX_wm_window(C);
1752         UI_popup_block_close(C, win, arg_block);
1753 }
1754
1755 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1756
1757 static void wm_block_splash_refreshmenu(bContext *C, void *UNUSED(arg_block), void *UNUSED(arg))
1758 {
1759         ARegion *ar_menu = CTX_wm_menu(C);
1760         ED_region_tag_refresh_ui(ar_menu);
1761 }
1762
1763 static int wm_resource_check_prev(void)
1764 {
1765
1766         const char *res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, true);
1767
1768         // if (res) printf("USER: %s\n", res);
1769
1770 #if 0 /* ignore the local folder */
1771         if (res == NULL) {
1772                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1773                 res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, true);
1774         }
1775 #endif
1776
1777         // if (res) printf("LOCAL: %s\n", res);
1778         if (res) {
1779                 return false;
1780         }
1781         else {
1782                 return (BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, true) != NULL);
1783         }
1784 }
1785
1786 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1787 {
1788         uiBlock *block;
1789         uiBut *but;
1790         uiLayout *layout, *split, *col;
1791         uiStyle *style = UI_style_get();
1792         const struct RecentFile *recent;
1793         int i;
1794         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", true);
1795         char url[96];
1796         const char *version_suffix = NULL;
1797
1798 #ifndef WITH_HEADLESS
1799         extern char datatoc_splash_png[];
1800         extern int datatoc_splash_png_size;
1801
1802         extern char datatoc_splash_2x_png[];
1803         extern int datatoc_splash_2x_png_size;
1804         ImBuf *ibuf;
1805 #else
1806         ImBuf *ibuf = NULL;
1807 #endif
1808
1809 #ifdef WITH_BUILDINFO
1810         int label_delta = 0;
1811         int hash_width, date_width;
1812         char date_buf[128] = "\0";
1813         char hash_buf[128] = "\0";
1814         extern unsigned long build_commit_timestamp;
1815         extern char build_hash[], build_commit_date[], build_commit_time[], build_branch[];
1816
1817         /* Builds made from tag only shows tag sha */
1818         BLI_snprintf(hash_buf, sizeof(hash_buf), "Hash: %s", build_hash);
1819         BLI_snprintf(date_buf, sizeof(date_buf), "Date: %s %s", build_commit_date, build_commit_time);
1820         
1821         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.pixelsize * U.dpi);
1822         hash_width = (int)BLF_width(style->widgetlabel.uifont_id, hash_buf, sizeof(hash_buf)) + U.widget_unit;
1823         date_width = (int)BLF_width(style->widgetlabel.uifont_id, date_buf, sizeof(date_buf)) + U.widget_unit;
1824 #endif  /* WITH_BUILDINFO */
1825
1826 #ifndef WITH_HEADLESS
1827         if (U.pixelsize == 2) {
1828                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_2x_png,
1829                                              datatoc_splash_2x_png_size, IB_rect, NULL, "<splash screen>");
1830         }
1831         else {
1832                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1833                                              datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1834         }
1835
1836         /* overwrite splash with template image */
1837         if (U.app_template[0] != '\0') {
1838                 ImBuf *ibuf_template = NULL;
1839                 char splash_filepath[FILE_MAX];
1840                 char template_directory[FILE_MAX];
1841
1842                 if (BKE_appdir_app_template_id_search(
1843                         U.app_template,
1844                         template_directory, sizeof(template_directory)))
1845                 {
1846                         BLI_join_dirfile(
1847                                 splash_filepath, sizeof(splash_filepath), template_directory,
1848                                 (U.pixelsize == 2) ? "splash_2x.png" : "splash.png");
1849                         ibuf_template = IMB_loadiffname(splash_filepath, IB_rect, NULL);
1850                         if (ibuf_template) {
1851                                 const int x_expect = ibuf->x;
1852                                 const int y_expect = 230 * (int)U.pixelsize;
1853                                 /* don't cover the header text */
1854                                 if (ibuf_template->x == x_expect && ibuf_template->y == y_expect) {
1855                                         memcpy(ibuf->rect, ibuf_template->rect, ibuf_template->x * ibuf_template->y * sizeof(char[4]));
1856                                 }
1857                                 else {
1858                                         printf("Splash expected %dx%d found %dx%d, ignoring: %s\n",
1859                                                x_expect, y_expect, ibuf_template->x, ibuf_template->y, splash_filepath);
1860                                 }
1861                                 IMB_freeImBuf(ibuf_template);
1862                         }
1863                 }
1864         }
1865 #endif
1866
1867         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1868
1869         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1870          * with the OS when the splash shows, window clipping in this case gives
1871          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1872         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1873
1874         /* XXX splash scales with pixelsize, should become widget-units */
1875         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 */
1876         UI_but_func_set(but, wm_block_splash_close, block, NULL);
1877         UI_block_func_set(block, wm_block_splash_refreshmenu, block, NULL);
1878
1879         /* label for 'a' bugfix releases, or 'Release Candidate 1'...
1880          *  avoids recreating splash for version updates */
1881         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "rc")) {
1882                 version_suffix = "Release Candidate";
1883         }
1884         else if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1885                 version_suffix = STRINGIFY(BLENDER_VERSION_CHAR);
1886         }
1887         if (version_suffix != NULL && version_suffix[0]) {
1888                 /* placed after the version number in the image,
1889                  * placing y is tricky to match baseline */
1890                 int x = 260 * U.pixelsize - (2 * UI_DPI_FAC);
1891                 int y = 242 * U.pixelsize + (4 * UI_DPI_FAC);
1892                 int w = 240 * U.pixelsize;
1893
1894                 /* hack to have text draw 'text_sel' */
1895                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1896                 but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x, y, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1897                 /* XXX, set internal flag - UI_SELECT */
1898                 UI_but_flag_enable(but, 1);
1899                 UI_block_emboss_set(block, UI_EMBOSS);
1900         }
1901
1902 #ifdef WITH_BUILDINFO
1903         if (build_commit_timestamp != 0) {
1904                 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);
1905                 label_delta = 12;
1906         }
1907         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);
1908
1909         if (!STREQ(build_branch, "master")) {
1910                 char branch_buf[128] = "\0";
1911                 int branch_width;
1912                 BLI_snprintf(branch_buf, sizeof(branch_buf), "Branch: %s", build_branch);
1913                 branch_width = (int)BLF_width(style->widgetlabel.uifont_id, branch_buf, sizeof(branch_buf)) + U.widget_unit;
1914                 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);
1915         }
1916 #endif  /* WITH_BUILDINFO */
1917         
1918         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.pixelsize * 480, U.pixelsize * 110, 0, style);
1919         
1920         UI_block_emboss_set(block, UI_EMBOSS);
1921         /* show the splash menu (containing interaction presets), using python */
1922         if (mt) {
1923                 Menu menu = {NULL};
1924                 menu.layout = layout;
1925                 menu.type = mt;
1926                 mt->draw(C, &menu);
1927
1928 //              wmWindowManager *wm = CTX_wm_manager(C);
1929 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
1930         }
1931         
1932         UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN);
1933         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
1934         
1935         split = uiLayoutSplit(layout, 0.0f, false);
1936         col = uiLayoutColumn(split, false);
1937         uiItemL(col, IFACE_("Links"), ICON_NONE);
1938 #if 0
1939         uiItemStringO(col, IFACE_("Support an Open Animation Movie"), ICON_URL, "WM_OT_url_open", "url",
1940                       "https://cloud.blender.org/join");
1941 #endif
1942         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url",
1943                       "http://www.blender.org/foundation/donation-payment/");
1944         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url",
1945                       "http://www.blender.org/about/credits/");
1946         BLI_snprintf(url, sizeof(url), "http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/%d.%d",
1947                      BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1948         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", url);
1949         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url",
1950                       "https://docs.blender.org/manual/en/dev/");
1951         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
1952         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1953                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d"
1954                                                STRINGIFY(BLENDER_VERSION_CHAR) "_release",
1955                              BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1956         }
1957         else {
1958                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d_%d",
1959                              BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
1960         }
1961         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
1962         uiItemL(col, "", ICON_NONE);
1963
1964         col = uiLayoutColumn(split, false);
1965
1966         if (wm_resource_check_prev()) {
1967                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
1968                 uiItemS(col);
1969         }
1970
1971         uiItemL(col, IFACE_("Recent"), ICON_NONE);
1972         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
1973                 const char *filename = BLI_path_basename(recent->filepath);
1974                 uiItemStringO(col, filename,
1975                               BLO_has_bfile_extension(filename) ? ICON_FILE_BLEND : ICON_FILE_BACKUP,
1976                               "WM_OT_open_mainfile", "filepath", recent->filepath);
1977         }
1978
1979         uiItemS(col);
1980         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
1981         uiItemL(col, "", ICON_NONE);
1982         
1983         mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
1984         if (mt) {
1985                 Menu menu = {NULL};
1986                 menu.layout = uiLayoutColumn(layout, false);
1987                 menu.type = mt;
1988                 mt->draw(C, &menu);
1989         }
1990
1991         UI_block_bounds_set_centered(block, 0);
1992         
1993         return block;
1994 }
1995
1996 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
1997 {
1998         UI_popup_block_invoke(C, wm_block_create_splash, NULL);
1999         
2000         return OPERATOR_FINISHED;
2001 }
2002
2003 static void WM_OT_splash(wmOperatorType *ot)
2004 {
2005         ot->name = "Splash Screen";
2006         ot->idname = "WM_OT_splash";
2007         ot->description = "Open the splash screen with release info";
2008         
2009         ot->invoke = wm_splash_invoke;
2010         ot->poll = WM_operator_winactive;
2011 }
2012
2013
2014 /* ***************** Search menu ************************* */
2015
2016 struct SearchPopupInit_Data {
2017         int size[2];
2018 };
2019
2020 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *userdata)
2021 {
2022         const struct SearchPopupInit_Data *init_data = userdata;
2023         static char search[256] = "";
2024         wmEvent event;
2025         wmWindow *win = CTX_wm_window(C);
2026         uiBlock *block;
2027         uiBut *but;
2028         
2029         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
2030         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
2031         
2032         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, init_data->size[0], UI_UNIT_Y, 0, 0, "");
2033         UI_but_func_operator_search(but);
2034         
2035         /* fake button, it holds space for search items */
2036         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - init_data->size[1],
2037                  init_data->size[0], init_data->size[1], NULL, 0, 0, 0, 0, NULL);
2038         
2039         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
2040         
2041         wm_event_init_from_window(win, &event);
2042         event.type = EVT_BUT_OPEN;
2043         event.val = KM_PRESS;
2044         event.customdata = but;
2045         event.customdatafree = false;
2046         wm_event_add(win, &event);
2047         
2048         return block;
2049 }
2050
2051 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2052 {
2053         return OPERATOR_FINISHED;
2054 }
2055
2056 static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2057 {
2058         struct SearchPopupInit_Data data = {
2059                 .size = {
2060                     UI_searchbox_size_x() * 2,
2061                     UI_searchbox_size_y(),
2062                 },
2063         };
2064
2065         UI_popup_block_invoke(C, wm_block_search_menu, &data);
2066         
2067         return OPERATOR_INTERFACE;
2068 }
2069
2070 /* op->poll */
2071 static int wm_search_menu_poll(bContext *C)
2072 {
2073         if (CTX_wm_window(C) == NULL) {
2074                 return 0;
2075         }
2076         else {
2077                 ScrArea *sa = CTX_wm_area(C);
2078                 if (sa) {
2079                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
2080                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
2081                 }
2082                 else {
2083                         Object *editob = CTX_data_edit_object(C);
2084                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
2085                 }
2086         }
2087         return 1;
2088 }
2089
2090 static void WM_OT_search_menu(wmOperatorType *ot)
2091 {
2092         ot->name = "Search Menu";
2093         ot->idname = "WM_OT_search_menu";
2094         ot->description = "Pop-up a search menu over all available operators in current context";
2095         
2096         ot->invoke = wm_search_menu_invoke;
2097         ot->exec = wm_search_menu_exec;
2098         ot->poll = wm_search_menu_poll;
2099 }
2100
2101 static int wm_call_menu_exec(bContext *C, wmOperator *op)
2102 {
2103         char idname[BKE_ST_MAXNAME];
2104         RNA_string_get(op->ptr, "name", idname);
2105
2106         return UI_popup_menu_invoke(C, idname, op->reports);
2107 }
2108
2109 static void WM_OT_call_menu(wmOperatorType *ot)
2110 {
2111         ot->name = "Call Menu";
2112         ot->idname = "WM_OT_call_menu";
2113         ot->description = "Call (draw) a pre-defined menu";
2114
2115         ot->exec = wm_call_menu_exec;
2116         ot->poll = WM_operator_winactive;
2117
2118         ot->flag = OPTYPE_INTERNAL;
2119
2120         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
2121 }
2122
2123 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2124 {
2125         char idname[BKE_ST_MAXNAME];
2126         RNA_string_get(op->ptr, "name", idname);
2127
2128         return UI_pie_menu_invoke(C, idname, event);
2129 }
2130
2131 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
2132 {
2133         char idname[BKE_ST_MAXNAME];
2134         RNA_string_get(op->ptr, "name", idname);
2135
2136         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
2137 }
2138
2139 static void WM_OT_call_menu_pie(wmOperatorType *ot)
2140 {
2141         ot->name = "Call Pie Menu";
2142         ot->idname = "WM_OT_call_menu_pie";
2143         ot->description = "Call (draw) a pre-defined pie menu";
2144
2145         ot->invoke = wm_call_pie_menu_invoke;
2146         ot->exec = wm_call_pie_menu_exec;
2147         ot->poll = WM_operator_winactive;
2148
2149         ot->flag = OPTYPE_INTERNAL;
2150
2151         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
2152 }
2153
2154 /* ************ window / screen operator definitions ************** */
2155
2156 /* this poll functions is needed in place of WM_operator_winactive
2157  * while it crashes on full screen */
2158 static int wm_operator_winactive_normal(bContext *C)
2159 {
2160         wmWindow *win = CTX_wm_window(C);
2161         bScreen *screen;
2162
2163         if (win == NULL)
2164                 return 0;
2165         if (!((screen = WM_window_get_active_screen(win)) && (screen->state == SCREENNORMAL)))
2166                 return 0;
2167
2168         return 1;
2169 }
2170
2171 /* included for script-access */
2172 static void WM_OT_window_close(wmOperatorType *ot)
2173 {
2174         ot->name = "Close Window";
2175         ot->idname = "WM_OT_window_close";
2176         ot->description = "Close the current Blender window";
2177
2178         ot->exec = wm_window_close_exec;
2179         ot->poll = WM_operator_winactive;
2180 }
2181
2182 static void WM_OT_window_new(wmOperatorType *ot)
2183 {
2184         PropertyRNA *prop;
2185
2186         ot->name = "New Window";
2187         ot->idname = "WM_OT_window_new";
2188         ot->description = "Create a new Blender window";
2189
2190         ot->exec = wm_window_new_exec;
2191         ot->invoke = wm_window_new_invoke;
2192         ot->poll = wm_operator_winactive_normal;
2193
2194         prop = RNA_def_enum(ot->srna, "screen", DummyRNA_NULL_items, 0, "Screen", "");
2195         RNA_def_enum_funcs(prop, wm_window_new_screen_itemf);
2196         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
2197         ot->prop = prop;
2198 }
2199
2200 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2201 {
2202         ot->name = "Toggle Window Fullscreen";
2203         ot->idname = "WM_OT_window_fullscreen_toggle";
2204         ot->description = "Toggle the current window fullscreen";
2205
2206         ot->exec = wm_window_fullscreen_toggle_exec;
2207         ot->poll = WM_operator_winactive;
2208 }
2209
2210 static int wm_exit_blender_exec(bContext *C, wmOperator *op)
2211 {
2212         WM_operator_free(op);
2213         
2214         WM_exit(C);
2215         
2216         return OPERATOR_FINISHED;
2217 }
2218
2219 static void WM_OT_quit_blender(wmOperatorType *ot)
2220 {
2221         ot->name = "Quit Blender";
2222         ot->idname = "WM_OT_quit_blender";
2223         ot->description = "Quit Blender";
2224
2225         ot->invoke = WM_operator_confirm;
2226         ot->exec = wm_exit_blender_exec;
2227 }
2228
2229 /* *********************** */
2230
2231 #if defined(WIN32)
2232
2233 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2234 {
2235         GHOST_toggleConsole(2);
2236         return OPERATOR_FINISHED;
2237 }
2238
2239 static void WM_OT_console_toggle(wmOperatorType *ot)
2240 {
2241         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
2242         ot->name = CTX_N_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
2243         ot->idname = "WM_OT_console_toggle";
2244         ot->description = N_("Toggle System Console");
2245         
2246         ot->exec = wm_console_toggle_exec;
2247         ot->poll = WM_operator_winactive;
2248 }
2249
2250 #endif
2251
2252 /* ************ default paint cursors, draw always around cursor *********** */
2253 /*
2254  * - returns handler to free
2255  * - poll(bContext): returns 1 if draw should happen
2256  * - draw(bContext): drawing callback for paint cursor
2257  */
2258
2259 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2260                                wmPaintCursorDraw draw, void *customdata)
2261 {
2262         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2263         
2264         BLI_addtail(&wm->paintcursors, pc);
2265         
2266         pc->customdata = customdata;
2267         pc->poll = poll;
2268         pc->draw = draw;
2269         
2270         return pc;
2271 }
2272
2273 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2274 {
2275         wmPaintCursor *pc;
2276         
2277         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
2278                 if (pc == (wmPaintCursor *)handle) {
2279                         BLI_remlink(&wm->paintcursors, pc);
2280                         MEM_freeN(pc);
2281                         return;
2282                 }
2283         }
2284 }
2285
2286 /* ************ window gesture operator-callback definitions ************** */
2287 /*
2288  * These are default callbacks for use in operators requiring gesture input
2289  */
2290
2291 /* **************** Border gesture *************** */
2292
2293 /**
2294  * Border gesture has two types:
2295  * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
2296  * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
2297  *
2298  * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
2299  */
2300
2301 static int border_apply_rect(wmOperator *op)
2302 {
2303         wmGesture *gesture = op->customdata;
2304         rcti *rect = gesture->customdata;
2305         
2306         if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
2307                 return 0;
2308
2309         
2310         /* operator arguments and storage. */
2311         RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
2312         RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
2313         RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
2314         RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
2315
2316         return 1;
2317 }
2318
2319 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
2320 {
2321         PropertyRNA *prop;
2322
2323         int retval;
2324
2325         if (!border_apply_rect(op))
2326                 return 0;
2327         
2328         /* XXX weak; border should be configured for this without reading event types */
2329         if ((prop = RNA_struct_find_property(op->ptr, "gesture_mode"))) {
2330                 RNA_property_int_set(op->ptr, prop, gesture_mode);
2331         }
2332
2333         retval = op->type->exec(C, op);
2334         OPERATOR_RETVAL_CHECK(retval);
2335
2336         return 1;
2337 }
2338
2339 static void wm_gesture_end(bContext *C, wmOperator *op)
2340 {
2341         wmGesture *gesture = op->customdata;
2342         
2343         WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2344         op->customdata = NULL;
2345
2346         ED_area_tag_redraw(CTX_wm_area(C));
2347         
2348         if (RNA_struct_find_property(op->ptr, "cursor")) {
2349                 WM_cursor_modal_restore(CTX_wm_window(C));
2350         }
2351 }
2352
2353 int WM_border_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2354 {
2355         if (ISTWEAK(event->type))
2356                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
2357         else
2358                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
2359
2360         /* add modal handler */
2361         WM_event_add_modal_handler(C, op);
2362         
2363         wm_gesture_tag_redraw(C);
2364
2365         return OPERATOR_RUNNING_MODAL;
2366 }
2367
2368 int WM_border_select_modal(bContext *C, wmOperator *op, const wmEvent *event)
2369 {
2370         wmGesture *gesture = op->customdata;
2371         rcti *rect = gesture->customdata;
2372         int sx, sy;
2373         
2374         if (event->type == MOUSEMOVE) {
2375                 wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2376
2377                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2378                         rect->xmin = rect->xmax = event->x - sx;
2379                         rect->ymin = rect->ymax = event->y - sy;
2380                 }
2381                 else {
2382                         rect->xmax = event->x - sx;
2383                         rect->ymax = event->y - sy;
2384                 }
2385                 border_apply_rect(op);
2386
2387                 wm_gesture_tag_redraw(C);
2388         }
2389         else if (event->type == EVT_MODAL_MAP) {
2390                 switch (event->val) {
2391                         case GESTURE_MODAL_BEGIN:
2392                                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2393                                         gesture->mode = 1;
2394                                         wm_gesture_tag_redraw(C);
2395                                 }
2396                                 break;
2397                         case GESTURE_MODAL_SELECT:
2398                         case GESTURE_MODAL_DESELECT:
2399                         case GESTURE_MODAL_IN:
2400                         case GESTURE_MODAL_OUT:
2401                                 if (border_apply(C, op, event->val)) {
2402                                         wm_gesture_end(C, op);
2403                                         return OPERATOR_FINISHED;
2404                                 }
2405                                 wm_gesture_end(C, op);
2406                                 return OPERATOR_CANCELLED;
2407
2408                         case GESTURE_MODAL_CANCEL:
2409                                 wm_gesture_end(C, op);
2410                                 return OPERATOR_CANCELLED;
2411                 }
2412
2413         }
2414 #ifdef WITH_INPUT_NDOF
2415         else if (event->type == NDOF_MOTION) {
2416                 return OPERATOR_PASS_THROUGH;
2417         }
2418 #endif
2419 //      /* Allow view navigation??? */
2420 //      else {
2421 //              return OPERATOR_PASS_THROUGH;
2422 //      }
2423
2424         return OPERATOR_RUNNING_MODAL;
2425 }
2426
2427 void WM_border_select_cancel(bContext *C, wmOperator *op)
2428 {
2429         wm_gesture_end(C, op);
2430 }
2431
2432 /* **************** circle gesture *************** */
2433 /* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
2434
2435 #ifdef GESTURE_MEMORY
2436 int circle_select_size = 25; /* XXX - need some operator memory thing! */
2437 #endif
2438
2439 int WM_gesture_circle_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2440 {
2441         op->customdata = WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
2442         
2443         /* add modal handler */
2444         WM_event_add_modal_handler(C, op);
2445         
2446         wm_gesture_tag_redraw(C);
2447         
2448         return OPERATOR_RUNNING_MODAL;
2449 }
2450
2451 static void gesture_circle_apply(bContext *C, wmOperator *op)
2452 {
2453         wmGesture *gesture = op->customdata;
2454         rcti *rect = gesture->customdata;
2455         
2456         if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_NOP)
2457                 return;
2458
2459         /* operator arguments and storage. */
2460         RNA_int_set(op->ptr, "x", rect->xmin);
2461         RNA_int_set(op->ptr, "y", rect->ymin);
2462         RNA_int_set(op->ptr, "radius", rect->xmax);
2463         
2464         if (op->type->exec) {
2465                 int retval;
2466                 retval = op->type->exec(C, op);
2467                 OPERATOR_RETVAL_CHECK(retval);
2468         }
2469 #ifdef GESTURE_MEMORY
2470         circle_select_size = rect->xmax;
2471 #endif
2472 }
2473
2474 int WM_gesture_circle_modal(bContext *C, wmOperator *op, const wmEvent *event)
2475 {
2476         wmGesture *gesture = op->customdata;
2477         rcti *rect = gesture->customdata;
2478         int sx, sy;
2479
2480         if (event->type == MOUSEMOVE) {
2481                 wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2482
2483                 rect->xmin = event->x - sx;
2484                 rect->ymin = event->y - sy;
2485
2486                 wm_gesture_tag_redraw(C);
2487
2488                 if (gesture->mode)
2489                         gesture_circle_apply(C, op);
2490         }
2491         else if (event->type == EVT_MODAL_MAP) {
2492                 float fac;
2493                 
2494                 switch (event->val) {
2495                         case GESTURE_MODAL_CIRCLE_SIZE:
2496                                 fac = 0.3f * (event->y - event->prevy);
2497                                 if (fac > 0)
2498                                         rect->xmax += ceil(fac);
2499                                 else
2500                                         rect->xmax += floor(fac);
2501                                 if (rect->xmax < 1) rect->xmax = 1;
2502                                 wm_gesture_tag_redraw(C);
2503                                 break;
2504                         case GESTURE_MODAL_CIRCLE_ADD:
2505                                 rect->xmax += 2 + rect->xmax / 10;
2506                                 wm_gesture_tag_redraw(C);
2507                                 break;
2508                         case GESTURE_MODAL_CIRCLE_SUB:
2509                                 rect->xmax -= 2 + rect->xmax / 10;
2510                                 if (rect->xmax < 1) rect->xmax = 1;
2511                                 wm_gesture_tag_redraw(C);
2512                                 break;
2513                         case GESTURE_MODAL_SELECT:
2514                         case GESTURE_MODAL_DESELECT:
2515                         case GESTURE_MODAL_NOP:
2516                                 if (RNA_struct_find_property(op->ptr, "gesture_mode"))
2517                                         RNA_int_set(op->ptr, "gesture_mode", event->val);
2518
2519                                 if (event->val != GESTURE_MODAL_NOP) {
2520                                         /* apply first click */
2521                                         gesture_circle_apply(C, op);
2522                                         gesture->mode = 1;
2523                                         wm_gesture_tag_redraw(C);
2524                                 }
2525                                 break;
2526
2527                         case GESTURE_MODAL_CANCEL:
2528                         case GESTURE_MODAL_CONFIRM:
2529                                 wm_gesture_end(C, op);
2530                                 return OPERATOR_FINISHED; /* use finish or we don't get an undo */
2531                 }
2532         }
2533 #ifdef WITH_INPUT_NDOF
2534         else if (event->type == NDOF_MOTION) {
2535                 return OPERATOR_PASS_THROUGH;
2536         }
2537 #endif
2538         /* Allow view navigation??? */
2539         /* note, this gives issues: 1) other modal ops run on top (border select), 2) middlemouse is used now 3) tablet/trackpad? */
2540 //      else {
2541 //              return OPERATOR_PASS_THROUGH;
2542 //      }
2543
2544         return OPERATOR_RUNNING_MODAL;
2545 }
2546
2547 void WM_gesture_circle_cancel(bContext *C, wmOperator *op)
2548 {
2549         wm_gesture_end(C, op);
2550 }
2551
2552 #if 0
2553 /* template to copy from */
2554 void WM_OT_circle_gesture(wmOperatorType *ot)
2555 {
2556         ot->name = "Circle Gesture";
2557         ot->idname = "WM_OT_circle_gesture";
2558         ot->description = "Enter rotate mode with a circular gesture";
2559         
2560         ot->invoke = WM_gesture_circle_invoke;
2561         ot->modal = WM_gesture_circle_modal;
2562         
2563         ot->poll = WM_operator_winactive;
2564         
2565         RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
2566         RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
2567         RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
2568
2569 }
2570 #endif
2571
2572 /* **************** Tweak gesture *************** */
2573
2574 static void tweak_gesture_modal(bContext *C, const wmEvent *event)
2575 {
2576         wmWindow *window = CTX_wm_window(C);
2577         wmGesture *gesture = window->tweak;
2578         rcti *rect = gesture->customdata;
2579         int sx, sy, val;
2580         
2581         switch (event->type) {
2582                 case MOUSEMOVE:
2583                 case INBETWEEN_MOUSEMOVE:
2584                         
2585                         wm_subwindow_origin_get(window, gesture->swinid, &sx, &sy);
2586                         
2587                         rect->xmax = event->x - sx;
2588                         rect->ymax = event->y - sy;
2589                         
2590                         if ((val = wm_gesture_evaluate(gesture))) {
2591                                 wmEvent tevent;
2592
2593                                 wm_event_init_from_window(window, &tevent);
2594                                 /* We want to get coord from start of drag, not from point where it becomes a tweak event, see T40549 */
2595                                 tevent.x = rect->xmin + sx;
2596                                 tevent.y = rect->ymin + sy;
2597                                 if (gesture->event_type == LEFTMOUSE)
2598                                         tevent.type = EVT_TWEAK_L;
2599                                 else if (gesture->event_type == RIGHTMOUSE)
2600                                         tevent.type = EVT_TWEAK_R;
2601                                 else
2602                                         tevent.type = EVT_TWEAK_M;
2603                                 tevent.val = val;
2604                                 /* mouse coords! */
2605
2606                                 /* important we add immediately after this event, so future mouse releases
2607                                  * (which may be in the queue already), are handled in order, see T44740 */
2608                                 wm_event_add_ex(window, &tevent, event);
2609                                 
2610                                 WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2611                         }
2612                         
2613                         break;
2614                         
2615                 case LEFTMOUSE:
2616                 case RIGHTMOUSE:
2617                 case MIDDLEMOUSE:
2618                         if (gesture->event_type == event->type) {
2619                                 WM_gesture_end(C, gesture);
2620
2621                                 /* when tweak fails we should give the other keymap entries a chance */
2622
2623                                 /* XXX, assigning to readonly, BAD JUJU! */
2624                                 ((wmEvent *)event)->val = KM_RELEASE;
2625                         }
2626                         break;
2627                 default:
2628                         if (!ISTIMER(event->type) && event->type != EVENT_NONE) {
2629                                 WM_gesture_end(C, gesture);
2630                         }
2631                         break;
2632         }
2633 }
2634
2635 /* standard tweak, called after window handlers passed on event */
2636 void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
2637 {
2638         wmWindow *win = CTX_wm_window(C);
2639         
2640         if (win->tweak == NULL) {
2641                 if (CTX_wm_region(C)) {
2642                         if (event->val == KM_PRESS) {
2643                                 if (ELEM(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE)) {
2644                                         win->tweak = WM_gesture_new(C, event, WM_GESTURE_TWEAK);
2645                                 }
2646                         }
2647                 }
2648         }
2649         else {
2650                 /* no tweaks if event was handled */
2651                 if ((action & WM_HANDLER_BREAK)) {
2652                         WM_gesture_end(C, win->tweak);
2653                 }
2654                 else
2655                         tweak_gesture_modal(C, event);
2656         }
2657 }
2658
2659 /* *********************** lasso gesture ****************** */
2660
2661 int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2662 {
2663         PropertyRNA *prop;
2664
2665         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LASSO);
2666         
2667         /* add modal handler */
2668         WM_event_add_modal_handler(C, op);
2669         
2670         wm_gesture_tag_redraw(C);
2671         
2672         if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
2673                 WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
2674         }
2675         
2676         return OPERATOR_RUNNING_MODAL;
2677 }
2678
2679 int WM_gesture_lines_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2680 {
2681         PropertyRNA *prop;
2682
2683         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LINES);
2684         
2685         /* add modal handler */
2686         WM_event_add_modal_handler(C, op);
2687         
2688         wm_gesture_tag_redraw(C);
2689         
2690         if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
2691                 WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
2692         }
2693         
2694         return OPERATOR_RUNNING_MODAL;
2695 }
2696
2697
2698 static void gesture_lasso_apply(bContext *C, wmOperator *op)
2699 {
2700         wmGesture *gesture = op->customdata;
2701         PointerRNA itemptr;
2702         float loc[2];
2703         int i;
2704         const short *lasso = gesture->customdata;
2705         
2706         /* operator storage as path. */
2707
2708         RNA_collection_clear(op->ptr, "path");
2709         for (i = 0; i < gesture->points; i++, lasso += 2) {
2710                 loc[0] = lasso[0];
2711                 loc[1] = lasso[1];
2712                 RNA_collection_add(op->ptr, "path", &itemptr);
2713                 RNA_float_set_array(&itemptr, "loc", loc);
2714         }
2715         
2716         wm_gesture_end(C, op);
2717                 
2718         if (op->type->exec) {
2719                 int retval = op->type->exec(C, op);
2720                 OPERATOR_RETVAL_CHECK(retval);
2721         }
2722 }
2723
2724 int WM_gesture_lasso_modal(bContext *C, wmOperator *op, const wmEvent *event)
2725 {
2726         wmGesture *gesture = op->customdata;
2727         int sx, sy;
2728         
2729         switch (event->type) {
2730                 case MOUSEMOVE:
2731                 case INBETWEEN_MOUSEMOVE:
2732                         
2733                         wm_gesture_tag_redraw(C);
2734                         
2735                         wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2736
2737                         if (gesture->points == gesture->size) {
2738                                 short *old_lasso = gesture->customdata;
2739                                 gesture->customdata = MEM_callocN(2 * sizeof(short) * (gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
2740                                 memcpy(gesture->customdata, old_lasso, 2 * sizeof(short) * gesture->size);
2741                                 gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
2742                                 MEM_freeN(old_lasso);
2743                                 // printf("realloc\n");
2744                         }
2745
2746                         {
2747                                 int x, y;
2748                                 short *lasso = gesture->customdata;
2749                                 
2750                                 lasso += (2 * gesture->points - 2);
2751                                 x = (event->x - sx - lasso[0]);
2752                                 y = (event->y - sy - lasso[1]);
2753                                 
2754                                 /* make a simple distance check to get a smoother lasso
2755                                  * add only when at least 2 pixels between this and previous location */
2756                                 if ((x * x + y * y) > 4) {
2757                                         lasso += 2;
2758                                         lasso[0] = event->x - sx;
2759                                         lasso[1] = event->y - sy;
2760                                         gesture->points++;
2761                                 }
2762                         }
2763                         break;
2764                         
2765                 case LEFTMOUSE:
2766                 case MIDDLEMOUSE:
2767                 case RIGHTMOUSE:
2768                         if (event->val == KM_RELEASE) {   /* key release */
2769                                 gesture_lasso_apply(C, op);
2770                                 return OPERATOR_FINISHED;
2771                         }
2772                         break;
2773                 case ESCKEY:
2774                         wm_gesture_end(C, op);
2775                         return OPERATOR_CANCELLED;
2776         }
2777         return OPERATOR_RUNNING_MODAL;
2778 }
2779
2780 int WM_gesture_lines_modal(bContext *C, wmOperator *op, const wmEvent *event)
2781 {
2782         return WM_gesture_lasso_modal(C, op, event);
2783 }
2784
2785 void WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
2786 {
2787         wm_gesture_end(C, op);
2788 }
2789
2790 void WM_gesture_lines_cancel(bContext *C, wmOperator *op)
2791 {
2792         wm_gesture_end(C, op);
2793 }
2794
2795 /**
2796  * helper function, we may want to add options for conversion to view space
2797  *
2798  * caller must free.
2799  */
2800 const int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
2801 {
2802         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
2803         int (*mcords)[2] = NULL;
2804         BLI_assert(prop != NULL);
2805
2806         if (prop) {
2807                 const int len = RNA_property_collection_length(op->ptr, prop);
2808
2809                 if (len) {
2810                         int i = 0;
2811                         mcords = MEM_mallocN(sizeof(int) * 2 * len, __func__);
2812
2813                         RNA_PROP_BEGIN (op->ptr, itemptr, prop)
2814                         {
2815                                 float loc[2];
2816
2817                                 RNA_float_get_array(&itemptr, "loc", loc);
2818                                 mcords[i][0] = (int)loc[0];
2819                                 mcords[i][1] = (int)loc[1];
2820                                 i++;
2821                         }
2822                         RNA_PROP_END;
2823                 }
2824                 *mcords_tot = len;
2825         }
2826         else {
2827                 *mcords_tot = 0;
2828         }
2829
2830         /* cast for 'const' */
2831         return (const int (*)[2])mcords;
2832 }
2833
2834 #if 0
2835 /* template to copy from */
2836
2837 static int gesture_lasso_exec(bContext *C, wmOperator *op)
2838 {
2839         RNA_BEGIN (op->ptr, itemptr, "path")
2840         {
2841                 float loc[2];
2842                 
2843                 RNA_float_get_array(&itemptr, "loc", loc);
2844                 printf("Location: %f %f\n", loc[0], loc[1]);
2845         }
2846         RNA_END;
2847         
2848         return OPERATOR_FINISHED;
2849 }
2850
2851 void WM_OT_lasso_gesture(wmOperatorType *ot)
2852 {
2853         PropertyRNA *prop;
2854         
2855         ot->name = "Lasso Gesture";
2856         ot->idname = "WM_OT_lasso_gesture";
2857         ot->description = "Select objects within the lasso as you move the pointer";
2858         
2859         ot->invoke = WM_gesture_lasso_invoke;
2860         ot->modal = WM_gesture_lasso_modal;
2861         ot->exec = gesture_lasso_exec;
2862         
2863         ot->poll = WM_operator_winactive;
2864         
2865         prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2866         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2867 }
2868 #endif
2869
2870 /* *********************** straight line gesture ****************** */
2871
2872 static int straightline_apply(bContext *C, wmOperator *op)
2873 {
2874         wmGesture *gesture = op->customdata;
2875         rcti *rect = gesture->customdata;
2876         
2877         if (rect->xmin == rect->xmax && rect->ymin == rect->ymax)
2878                 return 0;
2879         
2880         /* operator arguments and storage. */
2881         RNA_int_set(op->ptr, "xstart", rect->xmin);
2882         RNA_int_set(op->ptr, "ystart", rect->ymin);
2883         RNA_int_set(op->ptr, "xend", rect->xmax);
2884         RNA_int_set(op->ptr, "yend", rect->ymax);
2885
2886         if (op->type->exec) {
2887                 int retval = op->type->exec(C, op);
2888                 OPERATOR_RETVAL_CHECK(retval);
2889         }
2890         
2891         return 1;
2892 }
2893
2894
2895 int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2896 {
2897         PropertyRNA *prop;
2898
2899         op->customdata = WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
2900         
2901         /* add modal handler */
2902         WM_event_add_modal_handler(C, op);
2903         
2904         wm_gesture_tag_redraw(C);
2905         
2906         if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
2907                 WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
2908         }
2909                 
2910         return OPERATOR_RUNNING_MODAL;
2911 }
2912
2913 int WM_gesture_straightline_modal(bContext *C, wmOperator *op, const wmEvent *event)
2914 {
2915         wmGesture *gesture = op->customdata;
2916         rcti *rect = gesture->customdata;
2917         int sx, sy;
2918         
2919         if (event->type == MOUSEMOVE) {
2920                 wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2921                 
2922                 if (gesture->mode == 0) {
2923                         rect->xmin = rect->xmax = event->x - sx;
2924                         rect->ymin = rect->ymax = event->y - sy;
2925                 }
2926                 else {
2927                         rect->xmax = event->x - sx;
2928                         rect->ymax = event->y - sy;
2929                         straightline_apply(C, op);
2930                 }
2931                 
2932                 wm_gesture_tag_redraw(C);
2933         }
2934         else if (event->type == EVT_MODAL_MAP) {
2935                 switch (event->val) {
2936                         case GESTURE_MODAL_BEGIN:
2937                                 if (gesture->mode == 0) {
2938                                         gesture->mode = 1;
2939                                         wm_gesture_tag_redraw(C);
2940                                 }
2941                                 break;
2942                         case GESTURE_MODAL_SELECT:
2943                                 if (straightline_apply(C, op)) {
2944                                         wm_gesture_end(C, op);
2945                                         return OPERATOR_FINISHED;
2946                                 }
2947                                 wm_gesture_end(C, op);
2948                                 return OPERATOR_CANCELLED;
2949                                 
2950                         case GESTURE_MODAL_CANCEL:
2951                                 wm_gesture_end(C, op);
2952                                 return OPERATOR_CANCELLED;
2953                 }
2954                 
2955         }
2956
2957         return OPERATOR_RUNNING_MODAL;
2958 }
2959
2960 void WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
2961 {
2962         wm_gesture_end(C, op);
2963 }
2964
2965 #if 0
2966 /* template to copy from */
2967 void WM_OT_straightline_gesture(wmOperatorType *ot)
2968 {
2969         PropertyRNA *prop;
2970         
2971         ot->name = "Straight Line Gesture";
2972         ot->idname = "WM_OT_straightline_gesture";
2973         ot->description = "Draw a straight line as you move the pointer";
2974         
2975         ot->invoke = WM_gesture_straightline_invoke;
2976         ot->modal = WM_gesture_straightline_modal;
2977         ot->exec = gesture_straightline_exec;
2978         
2979         ot->poll = WM_operator_winactive;
2980         
2981         WM_operator_properties_gesture_straightline(ot, 0);
2982 }
2983 #endif
2984
2985 /* *********************** radial control ****************** */
2986
2987 #define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
2988 #define WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE (35 * UI_DPI_FAC)
2989 #define WM_RADIAL_CONTROL_DISPLAY_WIDTH (WM_RADIAL_CONTROL_DISPLAY_SIZE - WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE)
2990 #define WM_RADIAL_MAX_STR 10
2991
2992 typedef struct {
2993         PropertyType type;
2994         PropertySubType subtype;
2995         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2996         PointerRNA fill_col_override_ptr, fill_col_override_test_ptr;
2997         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2998         PropertyRNA *fill_col_override_prop, *fill_col_override_test_prop;
2999         StructRNA *image_id_srna;
3000         float initial_value, current_value, min_value, max_value;
3001         int initial_mouse[2];
3002         int slow_mouse[2];
3003         bool slow_mode;
3004         Dial *dial;
3005         unsigned int gltex;
3006         ListBase orig_paintcursors;
3007         bool use_secondary_tex;
3008         void *cursor;
3009         NumInput num_input;
3010 } RadialControl;
3011
3012 static void radial_control_update_header(wmOperator *op, bContext *C)
3013 {
3014         RadialControl *rc = op->customdata;
3015         char msg[UI_MAX_DRAW_STR];
3016         ScrArea *sa = CTX_wm_area(C);
3017         Scene *scene = CTX_data_scene(C);
3018         
3019         if (sa) {
3020                 if (hasNumInput(&rc->num_input)) {
3021                         char num_str[NUM_STR_REP_LEN];
3022                         outputNumInput(&rc->num_input, num_str, &scene->unit);
3023                         BLI_snprintf(msg, sizeof(msg), "%s: %s", RNA_property_ui_name(rc->prop), num_str);
3024                 }
3025                 else {
3026                         const char *ui_name = RNA_property_ui_name(rc->prop);
3027                         switch (rc->subtype) {
3028                                 case PROP_NONE:
3029                                 case PROP_DISTANCE:
3030                                         BLI_snprintf(msg, sizeof(msg), "%s: %0.4f", ui_name, rc->current_value);
3031                                         break;
3032                                 case PROP_PIXEL:
3033                                         BLI_snprintf(msg, sizeof(msg), "%s: %d", ui_name, (int)rc->current_value); /* XXX: round to nearest? */
3034                                         break;
3035                                 case PROP_PERCENTAGE:
3036                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.1f%%", ui_name, rc->current_value);
3037                                         break;
3038                                 case PROP_FACTOR:
3039                                         BLI_snprintf(msg, sizeof(msg), "%s: %1.3f", ui_name, rc->current_value);
3040                                         break;
3041                                 case PROP_ANGLE:
3042                                         BLI_snprintf(msg, sizeof(msg), "%s: %3.2f", ui_name, RAD2DEGF(rc->current_value));
3043                                         break;
3044                                 default:
3045                                         BLI_snprintf(msg, sizeof(msg), "%s", ui_name); /* XXX: No value? */
3046                                         break;
3047                         }
3048                 }
3049                 ED_area_headerprint(sa, msg);
3050         }
3051 }
3052
3053 static void radial_control_set_initial_mouse(RadialControl *rc, const wmEvent *event)
3054 {
3055         float d[2] = {0, 0};
3056         float zoom[2] = {1, 1};
3057
3058         rc->initial_mouse[0] = event->x;
3059         rc->initial_mouse[1] = event->y;
3060
3061         switch (rc->subtype) {
3062                 case PROP_NONE:
3063                 case PROP_DISTANCE:
3064                 case PROP_PIXEL:
3065                         d[0] = rc->initial_value;
3066                         break;
3067                 case PROP_PERCENTAGE:
3068                         d[0] = (rc->initial_value) / 100.0f * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
3069                         break;
3070                 case PROP_FACTOR:
3071                         d[0] = (1 - rc->initial_value) * WM_RADIAL_CONTROL_DISPLAY_WIDTH + WM_RADIAL_CONTROL_DISPLAY_MIN_SIZE;
3072                         break;
3073                 case PROP_ANGLE:
3074                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cosf(rc->initial_value);
3075                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sinf(rc->initial_value);
3076                         break;
3077                 default:
3078                         return;
3079         }
3080
3081         if (rc->zoom_prop) {
3082                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3083                 d[0] *= zoom[0];
3084                 d[1] *= zoom[1];
3085         }
3086
3087         rc->initial_mouse[0] -= d[0];
3088         rc->initial_mouse[1] -= d[1];
3089 }
3090
3091 static void radial_control_set_tex(RadialControl *rc)
3092 {
3093         ImBuf *ibuf;
3094
3095         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
3096                 case ID_BR:
3097                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data, rc->use_secondary_tex))) {
3098                                 glGenTextures(1, &rc->gltex);
3099                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
3100                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, ibuf->x, ibuf->y, 0,
3101                                              GL_RED, GL_FLOAT, ibuf->rect_float);
3102                                 MEM_freeN(ibuf->rect_float);
3103                                 MEM_freeN(ibuf);
3104                         }
3105                         break;
3106                 default:
3107                         break;
3108         }
3109 }
3110
3111 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
3112 {
3113         float col[3] = {0, 0, 0};
3114         float rot;
3115
3116         /* set fill color */
3117         if (rc->fill_col_prop) {
3118                 PointerRNA *fill_ptr;
3119                 PropertyRNA *fill_prop;
3120
3121                 if (rc->fill_col_override_prop &&
3122                     RNA_property_boolean_get(&rc->fill_col_override_test_ptr, rc->fill_col_override_test_prop))
3123                 {
3124                         fill_ptr = &rc->fill_col_override_ptr;
3125                         fill_prop = rc->fill_col_override_prop;
3126                 }
3127                 else {
3128                         fill_ptr = &rc->fill_col_ptr;
3129                         fill_prop = rc->fill_col_prop;
3130                 }
3131
3132                 RNA_property_float_get_array(fill_ptr, fill_prop, col);
3133         }
3134                 
3135         Gwn_VertFormat *format = immVertexFormat();
3136         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
3137
3138         if (rc->gltex) {
3139
3140                 unsigned int texCoord = GWN_vertformat_attr_add(format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
3141
3142                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
3143
3144                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3145                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3146
3147                 GLint swizzleMask[] = {GL_ZERO, GL_ZERO, GL_ZERO, GL_RED};
3148                 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);
3149
3150                 immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_MASK_UNIFORM_COLOR);
3151
3152                 immUniformColor3fvAlpha(col, alpha);
3153                 immUniform1i("image", GL_TEXTURE0);
3154
3155                 /* set up rotation if available */
3156                 if (rc->rot_prop) {
3157                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
3158                         gpuPushMatrix();
3159                         gpuRotate2D(RAD2DEGF(rot));
3160                 }
3161
3162                 /* draw textured quad */
3163                 immBegin(GWN_PRIM_TRI_FAN, 4);
3164
3165                 immAttrib2f(texCoord, 0, 0);
3166                 immVertex2f(pos, -radius, -radius);
3167
3168                 immAttrib2f(texCoord, 1, 0);
3169                 immVertex2f(pos, radius, -radius);
3170                 
3171                 immAttrib2f(texCoord, 1, 1);
3172                 immVertex2f(pos, radius, radius);
3173                 
3174                 immAttrib2f(texCoord, 0, 1);
3175                 immVertex2f(pos, -radius, radius);
3176
3177                 immEnd();
3178
3179                 /* undo rotation */
3180                 if (rc->rot_prop)
3181                         gpuPopMatrix();
3182         }
3183         else {
3184                 /* flat color if no texture available */
3185                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3186                 immUniformColor3fvAlpha(col, alpha);
3187                 imm_draw_circle_fill(pos, 0.0f, 0.0f, radius, 40);
3188         }
3189         
3190         immUnbindProgram();
3191 }
3192
3193 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
3194 {
3195         RadialControl *rc = customdata;
3196         ARegion *ar = CTX_wm_region(C);
3197         uiStyle *style = UI_style_get();
3198         const uiFontStyle *fstyle = &style->widget;
3199         const int fontid = fstyle->uifont_id;
3200         short fstyle_points = fstyle->points;
3201         char str[WM_RADIAL_MAX_STR];
3202         short strdrawlen = 0;
3203         float strwidth, strheight;