code cleanup: spelling,
[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
31
32 #include <float.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <stdio.h>
36 #include <stddef.h>
37 #include <assert.h>
38
39 #include "GHOST_C-api.h"
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_ID.h"
44 #include "DNA_object_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_userdef_types.h"
48 #include "DNA_windowmanager_types.h"
49 #include "DNA_mesh_types.h" /* only for USE_BMESH_SAVE_AS_COMPAT */
50
51 #include "BLF_translation.h"
52
53 #include "PIL_time.h"
54
55 #include "BLI_blenlib.h"
56 #include "BLI_dynstr.h" /*for WM_operator_pystring */
57 #include "BLI_math.h"
58 #include "BLI_utildefines.h"
59 #include "BLI_ghash.h"
60
61 #include "BLO_readfile.h"
62
63 #include "BKE_blender.h"
64 #include "BKE_brush.h"
65 #include "BKE_context.h"
66 #include "BKE_depsgraph.h"
67 #include "BKE_idprop.h"
68 #include "BKE_image.h"
69 #include "BKE_library.h"
70 #include "BKE_global.h"
71 #include "BKE_main.h"
72 #include "BKE_report.h"
73 #include "BKE_scene.h"
74 #include "BKE_screen.h" /* BKE_ST_MAXNAME */
75 #include "BKE_utildefines.h"
76
77 #include "BKE_idcode.h"
78
79 #include "BIF_gl.h"
80 #include "BIF_glutil.h" /* for paint cursor */
81 #include "BLF_api.h"
82
83 #include "IMB_colormanagement.h"
84 #include "IMB_imbuf_types.h"
85 #include "IMB_imbuf.h"
86
87 #include "ED_screen.h"
88 #include "ED_util.h"
89 #include "ED_object.h"
90
91 #include "RNA_access.h"
92 #include "RNA_define.h"
93 #include "RNA_enum_types.h"
94
95 #include "UI_interface.h"
96 #include "UI_resources.h"
97
98 #include "WM_api.h"
99 #include "WM_types.h"
100
101 #include "wm.h"
102 #include "wm_draw.h"
103 #include "wm_event_system.h"
104 #include "wm_event_types.h"
105 #include "wm_subwindow.h"
106 #include "wm_window.h"
107
108 static GHash *global_ops_hash = NULL;
109
110 /* ************ operator API, exported ********** */
111
112
113 wmOperatorType *WM_operatortype_find(const char *idname, int quiet)
114 {
115         if (idname[0]) {
116                 wmOperatorType *ot;
117
118                 /* needed to support python style names without the _OT_ syntax */
119                 char idname_bl[OP_MAX_TYPENAME];
120                 WM_operator_bl_idname(idname_bl, idname);
121
122                 ot = BLI_ghash_lookup(global_ops_hash, idname_bl);
123                 if (ot) {
124                         return ot;
125                 }
126
127                 if (!quiet) {
128                         printf("search for unknown operator '%s', '%s'\n", idname_bl, idname);
129                 }
130         }
131         else {
132                 if (!quiet) {
133                         printf("search for empty operator\n");
134                 }
135         }
136
137         return NULL;
138 }
139
140 /* caller must free */
141 GHashIterator *WM_operatortype_iter(void)
142 {
143         return BLI_ghashIterator_new(global_ops_hash);
144 }
145
146 /* all ops in 1 list (for time being... needs evaluation later) */
147 void WM_operatortype_append(void (*opfunc)(wmOperatorType *))
148 {
149         wmOperatorType *ot;
150         
151         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
152         ot->srna = RNA_def_struct(&BLENDER_RNA, "", "OperatorProperties");
153         /* Set the default i18n context now, so that opfunc can redefine it if needed! */
154         RNA_def_struct_translation_context(ot->srna, BLF_I18NCONTEXT_OPERATOR_DEFAULT);
155         opfunc(ot);
156
157         if (ot->name == NULL) {
158                 fprintf(stderr, "ERROR: Operator %s has no name property!\n", ot->idname);
159                 ot->name = N_("Dummy Name");
160         }
161
162         /* XXX All ops should have a description but for now allow them not to. */
163         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : N_("(undocumented operator)"));
164         RNA_def_struct_identifier(ot->srna, ot->idname);
165
166         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
167 }
168
169 void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata)
170 {
171         wmOperatorType *ot;
172
173         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
174         ot->srna = RNA_def_struct(&BLENDER_RNA, "", "OperatorProperties");
175         /* Set the default i18n context now, so that opfunc can redefine it if needed! */
176         RNA_def_struct_translation_context(ot->srna, BLF_I18NCONTEXT_OPERATOR_DEFAULT);
177         opfunc(ot, userdata);
178         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : N_("(undocumented operator)"));
179         RNA_def_struct_identifier(ot->srna, ot->idname);
180
181         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
182 }
183
184 /* ********************* macro operator ******************** */
185
186 typedef struct {
187         int retval;
188 } MacroData;
189
190 static void wm_macro_start(wmOperator *op)
191 {
192         if (op->customdata == NULL) {
193                 op->customdata = MEM_callocN(sizeof(MacroData), "MacroData");
194         }
195 }
196
197 static int wm_macro_end(wmOperator *op, int retval)
198 {
199         if (retval & OPERATOR_CANCELLED) {
200                 MacroData *md = op->customdata;
201
202                 if (md->retval & OPERATOR_FINISHED) {
203                         retval |= OPERATOR_FINISHED;
204                         retval &= ~OPERATOR_CANCELLED;
205                 }
206         }
207
208         /* if modal is ending, free custom data */
209         if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) {
210                 if (op->customdata) {
211                         MEM_freeN(op->customdata);
212                         op->customdata = NULL;
213                 }
214         }
215
216         return retval;
217 }
218
219 /* macro exec only runs exec calls */
220 static int wm_macro_exec(bContext *C, wmOperator *op)
221 {
222         wmOperator *opm;
223         int retval = OPERATOR_FINISHED;
224         
225         wm_macro_start(op);
226
227         for (opm = op->macro.first; opm; opm = opm->next) {
228                 
229                 if (opm->type->exec) {
230                         retval = opm->type->exec(C, opm);
231                         OPERATOR_RETVAL_CHECK(retval);
232                 
233                         if (retval & OPERATOR_FINISHED) {
234                                 MacroData *md = op->customdata;
235                                 md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
236                         }
237                         else {
238                                 break; /* operator didn't finish, end macro */
239                         }
240                 }
241         }
242         
243         return wm_macro_end(op, retval);
244 }
245
246 static int wm_macro_invoke_internal(bContext *C, wmOperator *op, wmEvent *event, wmOperator *opm)
247 {
248         int retval = OPERATOR_FINISHED;
249
250         /* start from operator received as argument */
251         for (; opm; opm = opm->next) {
252                 if (opm->type->invoke)
253                         retval = opm->type->invoke(C, opm, event);
254                 else if (opm->type->exec)
255                         retval = opm->type->exec(C, opm);
256
257                 OPERATOR_RETVAL_CHECK(retval);
258
259                 BLI_movelisttolist(&op->reports->list, &opm->reports->list);
260                 
261                 if (retval & OPERATOR_FINISHED) {
262                         MacroData *md = op->customdata;
263                         md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
264                 }
265                 else {
266                         break; /* operator didn't finish, end macro */
267                 }
268         }
269
270         return wm_macro_end(op, retval);
271 }
272
273 static int wm_macro_invoke(bContext *C, wmOperator *op, wmEvent *event)
274 {
275         wm_macro_start(op);
276         return wm_macro_invoke_internal(C, op, event, op->macro.first);
277 }
278
279 static int wm_macro_modal(bContext *C, wmOperator *op, wmEvent *event)
280 {
281         wmOperator *opm = op->opm;
282         int retval = OPERATOR_FINISHED;
283         
284         if (opm == NULL)
285                 printf("%s: macro error, calling NULL modal()\n", __func__);
286         else {
287                 retval = opm->type->modal(C, opm, event);
288                 OPERATOR_RETVAL_CHECK(retval);
289
290                 /* if this one is done but it's not the last operator in the macro */
291                 if ((retval & OPERATOR_FINISHED) && opm->next) {
292                         MacroData *md = op->customdata;
293
294                         md->retval = OPERATOR_FINISHED; /* keep in mind that at least one operator finished */
295
296                         retval = wm_macro_invoke_internal(C, op, event, opm->next);
297
298                         /* if new operator is modal and also added its own handler */
299                         if (retval & OPERATOR_RUNNING_MODAL && op->opm != opm) {
300                                 wmWindow *win = CTX_wm_window(C);
301                                 wmEventHandler *handler = NULL;
302
303                                 for (handler = win->modalhandlers.first; handler; handler = handler->next) {
304                                         /* first handler in list is the new one */
305                                         if (handler->op == op)
306                                                 break;
307                                 }
308
309                                 if (handler) {
310                                         BLI_remlink(&win->modalhandlers, handler);
311                                         wm_event_free_handler(handler);
312                                 }
313
314                                 /* if operator is blocking, grab cursor
315                                  * This may end up grabbing twice, but we don't care.
316                                  * */
317                                 if (op->opm->type->flag & OPTYPE_BLOCKING) {
318                                         int bounds[4] = {-1, -1, -1, -1};
319                                         int wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) && ((op->opm->flag & OP_GRAB_POINTER) || (op->opm->type->flag & OPTYPE_GRAB_POINTER));
320
321                                         if (wrap) {
322                                                 ARegion *ar = CTX_wm_region(C);
323                                                 if (ar) {
324                                                         bounds[0] = ar->winrct.xmin;
325                                                         bounds[1] = ar->winrct.ymax;
326                                                         bounds[2] = ar->winrct.xmax;
327                                                         bounds[3] = ar->winrct.ymin;
328                                                 }
329                                         }
330
331                                         WM_cursor_grab_enable(CTX_wm_window(C), wrap, FALSE, bounds);
332                                 }
333                         }
334                 }
335         }
336
337         return wm_macro_end(op, retval);
338 }
339
340 static int wm_macro_cancel(bContext *C, wmOperator *op)
341 {
342         /* call cancel on the current modal operator, if any */
343         if (op->opm && op->opm->type->cancel) {
344                 op->opm->type->cancel(C, op->opm);
345         }
346
347         return wm_macro_end(op, OPERATOR_CANCELLED);
348 }
349
350 /* Names have to be static for now */
351 wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *name, const char *description, int flag)
352 {
353         wmOperatorType *ot;
354         
355         if (WM_operatortype_find(idname, TRUE)) {
356                 printf("%s: macro error: operator %s exists\n", __func__, idname);
357                 return NULL;
358         }
359         
360         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
361         ot->srna = RNA_def_struct(&BLENDER_RNA, "", "OperatorProperties");
362         
363         ot->idname = idname;
364         ot->name = name;
365         ot->description = description;
366         ot->flag = OPTYPE_MACRO | flag;
367         
368         ot->exec = wm_macro_exec;
369         ot->invoke = wm_macro_invoke;
370         ot->modal = wm_macro_modal;
371         ot->cancel = wm_macro_cancel;
372         ot->poll = NULL;
373
374         if (!ot->description) /* XXX All ops should have a description but for now allow them not to. */
375                 ot->description = N_("(undocumented operator)");
376         
377         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
378         RNA_def_struct_identifier(ot->srna, ot->idname);
379         RNA_def_struct_translation_context(ot->srna, BLF_I18NCONTEXT_OPERATOR_DEFAULT);
380
381         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
382
383         return ot;
384 }
385
386 void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *, void *), void *userdata)
387 {
388         wmOperatorType *ot;
389
390         ot = MEM_callocN(sizeof(wmOperatorType), "operatortype");
391         ot->srna = RNA_def_struct(&BLENDER_RNA, "", "OperatorProperties");
392
393         ot->flag = OPTYPE_MACRO;
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)
401                 ot->description = N_("(undocumented operator)");
402
403         /* Set the default i18n context now, so that opfunc can redefine it if needed! */
404         RNA_def_struct_translation_context(ot->srna, BLF_I18NCONTEXT_OPERATOR_DEFAULT);
405         opfunc(ot, userdata);
406
407         RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
408         RNA_def_struct_identifier(ot->srna, ot->idname);
409
410         BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
411 }
412
413 wmOperatorTypeMacro *WM_operatortype_macro_define(wmOperatorType *ot, const char *idname)
414 {
415         wmOperatorTypeMacro *otmacro = MEM_callocN(sizeof(wmOperatorTypeMacro), "wmOperatorTypeMacro");
416
417         BLI_strncpy(otmacro->idname, idname, OP_MAX_TYPENAME);
418
419         /* do this on first use, since operatordefinitions might have been not done yet */
420         WM_operator_properties_alloc(&(otmacro->ptr), &(otmacro->properties), idname);
421         WM_operator_properties_sanitize(otmacro->ptr, 1);
422
423         BLI_addtail(&ot->macro, otmacro);
424
425         {
426                 /* operator should always be found but in the event its not. don't segfault */
427                 wmOperatorType *otsub = WM_operatortype_find(idname, 0);
428                 if (otsub) {
429                         RNA_def_pointer_runtime(ot->srna, otsub->idname, otsub->srna,
430                                                 otsub->name, otsub->description);
431                 }
432         }
433
434         return otmacro;
435 }
436
437 static void wm_operatortype_free_macro(wmOperatorType *ot)
438 {
439         wmOperatorTypeMacro *otmacro;
440         
441         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
442                 if (otmacro->ptr) {
443                         WM_operator_properties_free(otmacro->ptr);
444                         MEM_freeN(otmacro->ptr);
445                 }
446         }
447         BLI_freelistN(&ot->macro);
448 }
449
450
451 int WM_operatortype_remove(const char *idname)
452 {
453         wmOperatorType *ot = WM_operatortype_find(idname, 0);
454
455         if (ot == NULL)
456                 return 0;
457         
458         RNA_struct_free(&BLENDER_RNA, ot->srna);
459
460         if (ot->last_properties) {
461                 IDP_FreeProperty(ot->last_properties);
462                 MEM_freeN(ot->last_properties);
463         }
464
465         if (ot->macro.first)
466                 wm_operatortype_free_macro(ot);
467
468         BLI_ghash_remove(global_ops_hash, (void *)ot->idname, NULL, NULL);
469
470         MEM_freeN(ot);
471         return 1;
472 }
473
474 /* SOME_OT_op -> some.op */
475 void WM_operator_py_idname(char *to, const char *from)
476 {
477         char *sep = strstr(from, "_OT_");
478         if (sep) {
479                 int ofs = (sep - from);
480                 
481                 /* note, we use ascii tolower instead of system tolower, because the
482                  * latter depends on the locale, and can lead to idname mistmatch */
483                 memcpy(to, from, sizeof(char) * ofs);
484                 BLI_ascii_strtolower(to, ofs);
485
486                 to[ofs] = '.';
487                 BLI_strncpy(to + (ofs + 1), sep + 4, OP_MAX_TYPENAME);
488         }
489         else {
490                 /* should not happen but support just in case */
491                 BLI_strncpy(to, from, OP_MAX_TYPENAME);
492         }
493 }
494
495 /* some.op -> SOME_OT_op */
496 void WM_operator_bl_idname(char *to, const char *from)
497 {
498         if (from) {
499                 char *sep = strchr(from, '.');
500
501                 if (sep) {
502                         int ofs = (sep - from);
503
504                         memcpy(to, from, sizeof(char) * ofs);
505                         BLI_ascii_strtoupper(to, ofs);
506
507                         BLI_strncpy(to + ofs, "_OT_", OP_MAX_TYPENAME);
508                         BLI_strncpy(to + (ofs + 4), sep + 1, OP_MAX_TYPENAME);
509                 }
510                 else {
511                         /* should not happen but support just in case */
512                         BLI_strncpy(to, from, OP_MAX_TYPENAME);
513                 }
514         }
515         else
516                 to[0] = 0;
517 }
518
519 /* print a string representation of the operator, with the args that it runs 
520  * so python can run it again,
521  *
522  * When calling from an existing wmOperator do.
523  * WM_operator_pystring(op->type, op->ptr);
524  */
525 char *WM_operator_pystring(bContext *C, wmOperatorType *ot, PointerRNA *opptr, int all_args)
526 {
527         char idname_py[OP_MAX_TYPENAME];
528
529         /* for building the string */
530         DynStr *dynstr = BLI_dynstr_new();
531         char *cstring;
532         char *cstring_args;
533
534         /* only to get the orginal props for comparisons */
535         PointerRNA opptr_default;
536
537         if (all_args == 0 || opptr == NULL) {
538                 WM_operator_properties_create_ptr(&opptr_default, ot);
539
540                 if (opptr == NULL)
541                         opptr = &opptr_default;
542         }
543
544         WM_operator_py_idname(idname_py, ot->idname);
545         BLI_dynstr_appendf(dynstr, "bpy.ops.%s(", idname_py);
546
547         cstring_args = RNA_pointer_as_string_keywords(C, opptr, &opptr_default, FALSE, all_args);
548         BLI_dynstr_append(dynstr, cstring_args);
549         MEM_freeN(cstring_args);
550
551         if (all_args == 0 || opptr == &opptr_default)
552                 WM_operator_properties_free(&opptr_default);
553
554         BLI_dynstr_append(dynstr, ")");
555
556         cstring = BLI_dynstr_get_cstring(dynstr);
557         BLI_dynstr_free(dynstr);
558         return cstring;
559 }
560
561 void WM_operator_properties_create_ptr(PointerRNA *ptr, wmOperatorType *ot)
562 {
563         RNA_pointer_create(NULL, ot->srna, NULL, ptr);
564 }
565
566 void WM_operator_properties_create(PointerRNA *ptr, const char *opstring)
567 {
568         wmOperatorType *ot = WM_operatortype_find(opstring, 0);
569
570         if (ot)
571                 WM_operator_properties_create_ptr(ptr, ot);
572         else
573                 RNA_pointer_create(NULL, &RNA_OperatorProperties, NULL, ptr);
574 }
575
576 /* similar to the function above except its uses ID properties
577  * used for keymaps and macros */
578 void WM_operator_properties_alloc(PointerRNA **ptr, IDProperty **properties, const char *opstring)
579 {
580         if (*properties == NULL) {
581                 IDPropertyTemplate val = {0};
582                 *properties = IDP_New(IDP_GROUP, &val, "wmOpItemProp");
583         }
584
585         if (*ptr == NULL) {
586                 *ptr = MEM_callocN(sizeof(PointerRNA), "wmOpItemPtr");
587                 WM_operator_properties_create(*ptr, opstring);
588         }
589
590         (*ptr)->data = *properties;
591
592 }
593
594 void WM_operator_properties_sanitize(PointerRNA *ptr, const short no_context)
595 {
596         RNA_STRUCT_BEGIN(ptr, prop)
597         {
598                 switch (RNA_property_type(prop)) {
599                         case PROP_ENUM:
600                                 if (no_context)
601                                         RNA_def_property_flag(prop, PROP_ENUM_NO_CONTEXT);
602                                 else
603                                         RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
604                                 break;
605                         case PROP_POINTER:
606                         {
607                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
608
609                                 /* recurse into operator properties */
610                                 if (RNA_struct_is_a(ptype, &RNA_OperatorProperties)) {
611                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
612                                         WM_operator_properties_sanitize(&opptr, no_context);
613                                 }
614                                 break;
615                         }
616                         default:
617                                 break;
618                 }
619         }
620         RNA_STRUCT_END;
621 }
622
623
624 /** set all props to their default,
625  * \param do_update Only update un-initialized props.
626  *
627  * \note, theres nothing specific to operators here.
628  * this could be made a general function.
629  */
630 int WM_operator_properties_default(PointerRNA *ptr, const int do_update)
631 {
632         int is_change = FALSE;
633         RNA_STRUCT_BEGIN(ptr, prop)
634         {
635                 switch (RNA_property_type(prop)) {
636                         case PROP_POINTER:
637                         {
638                                 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
639                                 if (ptype != &RNA_Struct) {
640                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
641                                         is_change |= WM_operator_properties_default(&opptr, do_update);
642                                 }
643                                 break;
644                         }
645                         default:
646                                 if ((do_update == FALSE) || (RNA_property_is_set(ptr, prop) == FALSE)) {
647                                         if (RNA_property_reset(ptr, prop, -1)) {
648                                                 is_change = 1;
649                                         }
650                                 }
651                                 break;
652                 }
653         }
654         RNA_STRUCT_END;
655
656         return is_change;
657 }
658
659 /* remove all props without PROP_SKIP_SAVE */
660 void WM_operator_properties_reset(wmOperator *op)
661 {
662         if (op->ptr->data) {
663                 PropertyRNA *iterprop;
664                 iterprop = RNA_struct_iterator_property(op->type->srna);
665
666                 RNA_PROP_BEGIN(op->ptr, itemptr, iterprop)
667                 {
668                         PropertyRNA *prop = itemptr.data;
669
670                         if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
671                                 const char *identifier = RNA_property_identifier(prop);
672                                 RNA_struct_idprops_unset(op->ptr, identifier);
673                         }
674                 }
675                 RNA_PROP_END;
676         }
677 }
678
679 void WM_operator_properties_free(PointerRNA *ptr)
680 {
681         IDProperty *properties = ptr->data;
682
683         if (properties) {
684                 IDP_FreeProperty(properties);
685                 MEM_freeN(properties);
686                 ptr->data = NULL; /* just in case */
687         }
688 }
689
690 /* ************ default op callbacks, exported *********** */
691
692 /* invoke callback, uses enum property named "type" */
693 int WM_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
694 {
695         PropertyRNA *prop = op->type->prop;
696         uiPopupMenu *pup;
697         uiLayout *layout;
698
699         if (prop == NULL) {
700                 printf("%s: %s has no enum property set\n", __func__, op->type->idname);
701         }
702         else if (RNA_property_type(prop) != PROP_ENUM) {
703                 printf("%s: %s \"%s\" is not an enum property\n",
704                        __func__, op->type->idname, RNA_property_identifier(prop));
705         }
706         else if (RNA_property_is_set(op->ptr, prop)) {
707                 const int retval = op->type->exec(C, op);
708                 OPERATOR_RETVAL_CHECK(retval);
709                 return retval;
710         }
711         else {
712                 pup = uiPupMenuBegin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
713                 layout = uiPupMenuLayout(pup);
714                 /* set this so the default execution context is the same as submenus */
715                 uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_REGION_WIN);
716                 uiItemsFullEnumO(layout, op->type->idname, RNA_property_identifier(prop), op->ptr->data, WM_OP_EXEC_REGION_WIN, 0);
717                 uiPupMenuEnd(C, pup);
718         }
719
720         return OPERATOR_CANCELLED;
721 }
722
723
724 /* generic enum search invoke popup */
725 static void operator_enum_search_cb(const struct bContext *C, void *arg_ot, const char *str, uiSearchItems *items)
726 {
727         wmOperatorType *ot = (wmOperatorType *)arg_ot;
728         PropertyRNA *prop = ot->prop;
729
730         if (prop == NULL) {
731                 printf("%s: %s has no enum property set\n",
732                        __func__, ot->idname);
733         }
734         else if (RNA_property_type(prop) != PROP_ENUM) {
735                 printf("%s: %s \"%s\" is not an enum property\n",
736                        __func__, ot->idname, RNA_property_identifier(prop));
737         }
738         else {
739                 PointerRNA ptr;
740
741                 EnumPropertyItem *item, *item_array;
742                 int do_free;
743
744                 RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
745                 RNA_property_enum_items((bContext *)C, &ptr, prop, &item_array, NULL, &do_free);
746
747                 for (item = item_array; item->identifier; item++) {
748                         /* note: need to give the index rather than the identifier because the enum can be freed */
749                         if (BLI_strcasestr(item->name, str))
750                                 if (0 == uiSearchItemAdd(items, item->name, SET_INT_IN_POINTER(item->value), 0))
751                                         break;
752                 }
753
754                 if (do_free)
755                         MEM_freeN(item_array);
756         }
757 }
758
759 static void operator_enum_call_cb(struct bContext *C, void *arg1, void *arg2)
760 {
761         wmOperatorType *ot = arg1;
762
763         if (ot) {
764                 if (ot->prop) {
765                         PointerRNA props_ptr;
766                         WM_operator_properties_create_ptr(&props_ptr, ot);
767                         RNA_property_enum_set(&props_ptr, ot->prop, GET_INT_FROM_POINTER(arg2));
768                         WM_operator_name_call(C, ot->idname, WM_OP_EXEC_DEFAULT, &props_ptr);
769                         WM_operator_properties_free(&props_ptr);
770                 }
771                 else {
772                         printf("%s: op->prop for '%s' is NULL\n", __func__, ot->idname);
773                 }
774         }
775 }
776
777 static uiBlock *wm_enum_search_menu(bContext *C, ARegion *ar, void *arg_op)
778 {
779         static char search[256] = "";
780         wmEvent event;
781         wmWindow *win = CTX_wm_window(C);
782         uiBlock *block;
783         uiBut *but;
784         wmOperator *op = (wmOperator *)arg_op;
785
786         block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
787         uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
788
789 #if 0 /* ok, this isn't so easy... */
790         uiDefBut(block, LABEL, 0, RNA_struct_ui_name(op->type->srna), 10, 10, 180, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
791 #endif
792         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, 9 * UI_UNIT_X, UI_UNIT_Y, 0, 0, "");
793         uiButSetSearchFunc(but, operator_enum_search_cb, op->type, operator_enum_call_cb, NULL);
794
795         /* fake button, it holds space for search items */
796         uiDefBut(block, LABEL, 0, "", 10, 10 - uiSearchBoxhHeight(), 9 * UI_UNIT_X, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
797
798         uiPopupBoundsBlock(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
799         uiEndBlock(C, block);
800
801         event = *(win->eventstate);  /* XXX huh huh? make api call */
802         event.type = EVT_BUT_OPEN;
803         event.val = KM_PRESS;
804         event.customdata = but;
805         event.customdatafree = FALSE;
806         wm_event_add(win, &event);
807
808         return block;
809 }
810
811
812 int WM_enum_search_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
813 {
814         uiPupBlock(C, wm_enum_search_menu, op);
815         return OPERATOR_CANCELLED;
816 }
817
818 /* Can't be used as an invoke directly, needs message arg (can be NULL) */
819 int WM_operator_confirm_message(bContext *C, wmOperator *op, const char *message)
820 {
821         uiPopupMenu *pup;
822         uiLayout *layout;
823         IDProperty *properties = op->ptr->data;
824
825         if (properties && properties->len)
826                 properties = IDP_CopyProperty(op->ptr->data);
827         else
828                 properties = NULL;
829
830         pup = uiPupMenuBegin(C, IFACE_("OK?"), ICON_QUESTION);
831         layout = uiPupMenuLayout(pup);
832         uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0);
833         uiPupMenuEnd(C, pup);
834         
835         return OPERATOR_CANCELLED;
836 }
837
838
839 int WM_operator_confirm(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
840 {
841         return WM_operator_confirm_message(C, op, NULL);
842 }
843
844 /* op->invoke, opens fileselect if path property not set, otherwise executes */
845 int WM_operator_filesel(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
846 {
847         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
848                 return WM_operator_call_notest(C, op); /* call exec direct */
849         }
850         else {
851                 WM_event_add_fileselect(C, op);
852                 return OPERATOR_RUNNING_MODAL;
853         }
854 }
855
856 int WM_operator_filesel_ensure_ext_imtype(wmOperator *op, const char imtype)
857 {
858         PropertyRNA *prop;
859         char filepath[FILE_MAX];
860         /* dont NULL check prop, this can only run on ops with a 'filepath' */
861         prop = RNA_struct_find_property(op->ptr, "filepath");
862         RNA_property_string_get(op->ptr, prop, filepath);
863         if (BKE_add_image_extension(filepath, imtype)) {
864                 RNA_property_string_set(op->ptr, prop, filepath);
865                 /* note, we could check for and update 'filename' here,
866                  * but so far nothing needs this. */
867                 return TRUE;
868         }
869         return FALSE;
870 }
871
872 /* default properties for fileselect */
873 void WM_operator_properties_filesel(wmOperatorType *ot, int filter, short type, short action, short flag, short display)
874 {
875         PropertyRNA *prop;
876
877         static EnumPropertyItem file_display_items[] = {
878                 {FILE_DEFAULTDISPLAY, "FILE_DEFAULTDISPLAY", 0, "Default", "Automatically determine display type for files"},
879                 {FILE_SHORTDISPLAY, "FILE_SHORTDISPLAY", ICON_SHORTDISPLAY, "Short List", "Display files as short list"},
880                 {FILE_LONGDISPLAY, "FILE_LONGDISPLAY", ICON_LONGDISPLAY, "Long List", "Display files as a detailed list"},
881                 {FILE_IMGDISPLAY, "FILE_IMGDISPLAY", ICON_IMGDISPLAY, "Thumbnails", "Display files as thumbnails"},
882                 {0, NULL, 0, NULL, NULL}
883         };
884
885
886         if (flag & WM_FILESEL_FILEPATH)
887                 RNA_def_string_file_path(ot->srna, "filepath", "", FILE_MAX, "File Path", "Path to file");
888
889         if (flag & WM_FILESEL_DIRECTORY)
890                 RNA_def_string_dir_path(ot->srna, "directory", "", FILE_MAX, "Directory", "Directory of the file");
891
892         if (flag & WM_FILESEL_FILENAME)
893                 RNA_def_string_file_name(ot->srna, "filename", "", FILE_MAX, "File Name", "Name of the file");
894
895         if (flag & WM_FILESEL_FILES)
896                 RNA_def_collection_runtime(ot->srna, "files", &RNA_OperatorFileListElement, "Files", "");
897
898         if (action == FILE_SAVE) {
899                 /* note, this is only used to check if we should highlight the filename area red when the
900                  * filepath is an existing file. */
901                 prop = RNA_def_boolean(ot->srna, "check_existing", 1, "Check Existing", "Check and warn on overwriting existing files");
902                 RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
903         }
904         
905         prop = RNA_def_boolean(ot->srna, "filter_blender", (filter & BLENDERFILE), "Filter .blend files", "");
906         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
907         prop = RNA_def_boolean(ot->srna, "filter_backup", (filter & BLENDERFILE_BACKUP), "Filter .blend files", "");
908         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
909         prop = RNA_def_boolean(ot->srna, "filter_image", (filter & IMAGEFILE), "Filter image files", "");
910         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
911         prop = RNA_def_boolean(ot->srna, "filter_movie", (filter & MOVIEFILE), "Filter movie files", "");
912         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
913         prop = RNA_def_boolean(ot->srna, "filter_python", (filter & PYSCRIPTFILE), "Filter python files", "");
914         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
915         prop = RNA_def_boolean(ot->srna, "filter_font", (filter & FTFONTFILE), "Filter font files", "");
916         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
917         prop = RNA_def_boolean(ot->srna, "filter_sound", (filter & SOUNDFILE), "Filter sound files", "");
918         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
919         prop = RNA_def_boolean(ot->srna, "filter_text", (filter & TEXTFILE), "Filter text files", "");
920         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
921         prop = RNA_def_boolean(ot->srna, "filter_btx", (filter & BTXFILE), "Filter btx files", "");
922         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
923         prop = RNA_def_boolean(ot->srna, "filter_collada", (filter & COLLADAFILE), "Filter COLLADA files", "");
924         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
925         prop = RNA_def_boolean(ot->srna, "filter_folder", (filter & FOLDERFILE), "Filter folders", "");
926         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
927
928         prop = RNA_def_int(ot->srna, "filemode", type, FILE_LOADLIB, FILE_SPECIAL,
929                            "File Browser Mode", "The setting for the file browser mode to load a .blend file, a library or a special file",
930                            FILE_LOADLIB, FILE_SPECIAL);
931         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
932
933         if (flag & WM_FILESEL_RELPATH)
934                 RNA_def_boolean(ot->srna, "relative_path", TRUE, "Relative Path", "Select the file relative to the blend file");
935
936         prop = RNA_def_enum(ot->srna, "display_type", file_display_items, display, "Display Type", "");
937         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
938 }
939
940 void WM_operator_properties_select_all(wmOperatorType *ot)
941 {
942         static EnumPropertyItem select_all_actions[] = {
943                 {SEL_TOGGLE, "TOGGLE", 0, "Toggle", "Toggle selection for all elements"},
944                 {SEL_SELECT, "SELECT", 0, "Select", "Select all elements"},
945                 {SEL_DESELECT, "DESELECT", 0, "Deselect", "Deselect all elements"},
946                 {SEL_INVERT, "INVERT", 0, "Invert", "Invert selection of all elements"},
947                 {0, NULL, 0, NULL, NULL}
948         };
949
950         RNA_def_enum(ot->srna, "action", select_all_actions, SEL_TOGGLE, "Action", "Selection action to execute");
951 }
952
953 void WM_operator_properties_border(wmOperatorType *ot)
954 {
955         RNA_def_int(ot->srna, "xmin", 0, INT_MIN, INT_MAX, "X Min", "", INT_MIN, INT_MAX);
956         RNA_def_int(ot->srna, "xmax", 0, INT_MIN, INT_MAX, "X Max", "", INT_MIN, INT_MAX);
957         RNA_def_int(ot->srna, "ymin", 0, INT_MIN, INT_MAX, "Y Min", "", INT_MIN, INT_MAX);
958         RNA_def_int(ot->srna, "ymax", 0, INT_MIN, INT_MAX, "Y Max", "", INT_MIN, INT_MAX);
959 }
960
961 void WM_operator_properties_border_to_rcti(struct wmOperator *op, rcti *rect)
962 {
963         rect->xmin = RNA_int_get(op->ptr, "xmin");
964         rect->ymin = RNA_int_get(op->ptr, "ymin");
965         rect->xmax = RNA_int_get(op->ptr, "xmax");
966         rect->ymax = RNA_int_get(op->ptr, "ymax");
967 }
968
969 void WM_operator_properties_gesture_border(wmOperatorType *ot, int extend)
970 {
971         RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
972
973         WM_operator_properties_border(ot);
974
975         if (extend) {
976                 RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
977         }
978 }
979
980 void WM_operator_properties_mouse_select(wmOperatorType *ot)
981 {
982         RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection instead of deselecting everything first");
983         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from selection");
984         RNA_def_boolean(ot->srna, "toggle", 0, "Toggle Selection", "Toggle the selection");
985 }
986
987 void WM_operator_properties_gesture_straightline(wmOperatorType *ot, int cursor)
988 {
989         RNA_def_int(ot->srna, "xstart", 0, INT_MIN, INT_MAX, "X Start", "", INT_MIN, INT_MAX);
990         RNA_def_int(ot->srna, "xend", 0, INT_MIN, INT_MAX, "X End", "", INT_MIN, INT_MAX);
991         RNA_def_int(ot->srna, "ystart", 0, INT_MIN, INT_MAX, "Y Start", "", INT_MIN, INT_MAX);
992         RNA_def_int(ot->srna, "yend", 0, INT_MIN, INT_MAX, "Y End", "", INT_MIN, INT_MAX);
993         
994         if (cursor)
995                 RNA_def_int(ot->srna, "cursor", cursor, 0, INT_MAX, "Cursor", "Mouse cursor style to use during the modal operator", 0, INT_MAX);
996 }
997
998
999 /* op->poll */
1000 int WM_operator_winactive(bContext *C)
1001 {
1002         if (CTX_wm_window(C) == NULL) return 0;
1003         return 1;
1004 }
1005
1006 /* return FALSE, if the UI should be disabled */
1007 int WM_operator_check_ui_enabled(const bContext *C, const char *idname)
1008 {
1009         wmWindowManager *wm = CTX_wm_manager(C);
1010         Scene *scene = CTX_data_scene(C);
1011
1012         return !(ED_undo_valid(C, idname) == 0 || WM_jobs_test(wm, scene, WM_JOB_TYPE_ANY));
1013 }
1014
1015 wmOperator *WM_operator_last_redo(const bContext *C)
1016 {
1017         wmWindowManager *wm = CTX_wm_manager(C);
1018         wmOperator *op;
1019
1020         /* only for operators that are registered and did an undo push */
1021         for (op = wm->operators.last; op; op = op->prev)
1022                 if ((op->type->flag & OPTYPE_REGISTER) && (op->type->flag & OPTYPE_UNDO))
1023                         break;
1024
1025         return op;
1026 }
1027
1028 static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
1029 {
1030         wmOperator *op = arg_op;
1031         uiBlock *block;
1032         uiLayout *layout;
1033         uiStyle *style = UI_GetStyle();
1034         int width = 300;
1035         
1036
1037         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1038         uiBlockClearFlag(block, UI_BLOCK_LOOP);
1039         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1040
1041         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
1042          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
1043         assert(op->type->flag & OPTYPE_REGISTER);
1044
1045         uiBlockSetHandleFunc(block, ED_undo_operator_repeat_cb_evt, arg_op);
1046         layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, style);
1047
1048         if (!WM_operator_check_ui_enabled(C, op->type->name))
1049                 uiLayoutSetEnabled(layout, FALSE);
1050
1051         if (op->type->flag & OPTYPE_MACRO) {
1052                 for (op = op->macro.first; op; op = op->next) {
1053                         uiItemL(layout, RNA_struct_ui_name(op->type->srna), ICON_NONE);
1054                         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1055                 }
1056         }
1057         else {
1058                 uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1059         }
1060         
1061
1062         uiPopupBoundsBlock(block, 4, 0, 0);
1063         uiEndBlock(C, block);
1064
1065         return block;
1066 }
1067
1068 typedef struct wmOpPopUp {
1069         wmOperator *op;
1070         int width;
1071         int height;
1072         int free_op;
1073 } wmOpPopUp;
1074
1075 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1076 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1077 {
1078         wmOpPopUp *data = arg1;
1079         uiBlock *block = arg2;
1080
1081         WM_operator_call(C, data->op);
1082
1083         /* let execute handle freeing it */
1084         //data->free_op = FALSE;
1085         //data->op = NULL;
1086
1087         /* in this case, wm_operator_ui_popup_cancel wont run */
1088         MEM_freeN(data);
1089
1090         uiPupBlockClose(C, block);
1091 }
1092
1093 static void dialog_check_cb(bContext *C, void *op_ptr, void *UNUSED(arg))
1094 {
1095         wmOperator *op = op_ptr;
1096         if (op->type->check) {
1097                 if (op->type->check(C, op)) {
1098                         /* refresh */
1099                 }
1100         }
1101 }
1102
1103 /* Dialogs are popups that require user verification (click OK) before exec */
1104 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1105 {
1106         wmOpPopUp *data = userData;
1107         wmOperator *op = data->op;
1108         uiBlock *block;
1109         uiLayout *layout;
1110         uiStyle *style = UI_GetStyle();
1111
1112         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1113         uiBlockClearFlag(block, UI_BLOCK_LOOP);
1114
1115         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogs have many items
1116          * where quitting by accident is very annoying */
1117         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN);
1118
1119         layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
1120         
1121         uiBlockSetFunc(block, dialog_check_cb, op, NULL);
1122
1123         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1124         
1125         /* clear so the OK button is left alone */
1126         uiBlockSetFunc(block, NULL, NULL, NULL);
1127
1128         /* new column so as not to interfere with custom layouts [#26436] */
1129         {
1130                 uiBlock *col_block;
1131                 uiLayout *col;
1132                 uiBut *btn;
1133
1134                 col = uiLayoutColumn(layout, FALSE);
1135                 col_block = uiLayoutGetBlock(col);
1136                 /* Create OK button, the callback of which will execute op */
1137                 btn = uiDefBut(col_block, BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1138                 uiButSetFunc(btn, dialog_exec_cb, data, col_block);
1139         }
1140
1141         /* center around the mouse */
1142         uiPopupBoundsBlock(block, 4, data->width / -2, data->height / 2);
1143         uiEndBlock(C, block);
1144
1145         return block;
1146 }
1147
1148 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1149 {
1150         wmOpPopUp *data = userData;
1151         wmOperator *op = data->op;
1152         uiBlock *block;
1153         uiLayout *layout;
1154         uiStyle *style = UI_GetStyle();
1155
1156         block = uiBeginBlock(C, ar, __func__, UI_EMBOSS);
1157         uiBlockClearFlag(block, UI_BLOCK_LOOP);
1158         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1159
1160         layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
1161
1162         /* since ui is defined the auto-layout args are not used */
1163         uiLayoutOperatorButs(C, layout, op, NULL, 'V', 0);
1164
1165         uiPopupBoundsBlock(block, 4, 0, 0);
1166         uiEndBlock(C, block);
1167
1168         return block;
1169 }
1170
1171 static void wm_operator_ui_popup_cancel(void *userData)
1172 {
1173         wmOpPopUp *data = userData;
1174         if (data->free_op && data->op) {
1175                 wmOperator *op = data->op;
1176                 WM_operator_free(op);
1177         }
1178
1179         MEM_freeN(data);
1180 }
1181
1182 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1183 {
1184         wmOpPopUp *data = arg;
1185         wmOperator *op = data->op;
1186
1187         if (op && retval > 0)
1188                 WM_operator_call(C, op);
1189 }
1190
1191 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1192 {
1193         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1194         data->op = op;
1195         data->width = width;
1196         data->height = height;
1197         data->free_op = TRUE; /* if this runs and gets registered we may want not to free it */
1198         uiPupBlockEx(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data);
1199         return OPERATOR_RUNNING_MODAL;
1200 }
1201
1202 /* operator menu needs undo, for redo callback */
1203 int WM_operator_props_popup(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1204 {
1205         
1206         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1207                 BKE_reportf(op->reports, RPT_ERROR,
1208                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1209                 return OPERATOR_CANCELLED;
1210         }
1211         
1212         ED_undo_push_op(C, op);
1213         wm_operator_register(C, op);
1214
1215         uiPupBlock(C, wm_block_create_redo, op);
1216
1217         return OPERATOR_RUNNING_MODAL;
1218 }
1219
1220 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1221 {
1222         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1223         
1224         data->op = op;
1225         data->width = width;
1226         data->height = height;
1227         data->free_op = TRUE; /* if this runs and gets registered we may want not to free it */
1228
1229         /* op is not executed until popup OK but is clicked */
1230         uiPupBlockEx(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data);
1231
1232         return OPERATOR_RUNNING_MODAL;
1233 }
1234
1235 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1236 {
1237         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1238         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1239                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1240                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1241                 return OPERATOR_CANCELLED;
1242         }
1243         if (op->type->poll && op->type->poll(C) == 0) {
1244                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1245                 return OPERATOR_CANCELLED;
1246         }
1247         
1248         uiPupBlock(C, wm_block_create_redo, op);
1249
1250         return OPERATOR_CANCELLED;
1251 }
1252
1253 /* ***************** Debug menu ************************* */
1254
1255 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1256 {
1257         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1258         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1259         WM_event_add_notifier(C, NC_WINDOW, NULL);
1260
1261         return OPERATOR_FINISHED;
1262 }
1263
1264 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1265 {
1266         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1267         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1268 }
1269
1270 static void WM_OT_debug_menu(wmOperatorType *ot)
1271 {
1272         ot->name = "Debug Menu";
1273         ot->idname = "WM_OT_debug_menu";
1274         ot->description = "Open a popup to set the debug level";
1275         
1276         ot->invoke = wm_debug_menu_invoke;
1277         ot->exec = wm_debug_menu_exec;
1278         ot->poll = WM_operator_winactive;
1279         
1280         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1281 }
1282
1283
1284 /* ***************** Splash Screen ************************* */
1285
1286 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1287 {
1288         uiPupBlockClose(C, arg_block);
1289 }
1290
1291 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1292
1293 /* XXX: hack to refresh splash screen with updated prest menu name,
1294  * since popup blocks don't get regenerated like panels do */
1295 static void wm_block_splash_refreshmenu(bContext *UNUSED(C), void *UNUSED(arg_block), void *UNUSED(arg))
1296 {
1297         /* ugh, causes crashes in other buttons, disabling for now until 
1298          * a better fix */
1299 #if 0
1300         uiPupBlockClose(C, arg_block);
1301         uiPupBlock(C, wm_block_create_splash, NULL);
1302 #endif
1303 }
1304
1305 static int wm_resource_check_prev(void)
1306 {
1307
1308         char *res = BLI_get_folder_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, TRUE);
1309
1310         // if (res) printf("USER: %s\n", res);
1311
1312 #if 0 /* ignore the local folder */
1313         if (res == NULL) {
1314                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1315                 res = BLI_get_folder_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, TRUE);
1316         }
1317 #endif
1318
1319         // if (res) printf("LOCAL: %s\n", res);
1320         if (res) {
1321                 return FALSE;
1322         }
1323         else {
1324                 return (BLI_get_folder_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, TRUE) != NULL);
1325         }
1326 }
1327
1328 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1329 {
1330         uiBlock *block;
1331         uiBut *but;
1332         uiLayout *layout, *split, *col;
1333         uiStyle *style = UI_GetStyle();
1334         struct RecentFile *recent;
1335         int i;
1336         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", TRUE);
1337         char url[96];
1338         char file [FILE_MAX];
1339
1340 #ifndef WITH_HEADLESS
1341         extern char datatoc_splash_png[];
1342         extern int datatoc_splash_png_size;
1343
1344         ImBuf *ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1345                                             datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1346 #else
1347         ImBuf *ibuf = NULL;
1348 #endif
1349
1350
1351 #ifdef WITH_BUILDINFO
1352         int ver_width, rev_width;
1353         char version_buf[128];
1354         char revision_buf[128];
1355         extern char build_rev[];
1356         
1357         BLI_snprintf(version_buf, sizeof(version_buf),
1358                      "%d.%02d.%d", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
1359         BLI_snprintf(revision_buf, sizeof(revision_buf), "r%s", build_rev);
1360         
1361         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.dpi);
1362         ver_width = (int)BLF_width(style->widgetlabel.uifont_id, version_buf) + 5;
1363         rev_width = (int)BLF_width(style->widgetlabel.uifont_id, revision_buf) + 5;
1364 #endif  /* WITH_BUILDINFO */
1365
1366         block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
1367
1368         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1369          * with the OS when the splash shows, window clipping in this case gives
1370          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1371         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1372         
1373         but = uiDefBut(block, BUT_IMAGE, 0, "", 0, 10, 501, 282, ibuf, 0.0, 0.0, 0, 0, ""); /* button owns the imbuf now */
1374         uiButSetFunc(but, wm_block_splash_close, block, NULL);
1375         uiBlockSetFunc(block, wm_block_splash_refreshmenu, block, NULL);
1376         
1377 #ifdef WITH_BUILDINFO   
1378         uiDefBut(block, LABEL, 0, version_buf, 494 - ver_width, 282 - 24, ver_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1379         uiDefBut(block, LABEL, 0, revision_buf, 494 - rev_width, 282 - 36, rev_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1380 #endif  /* WITH_BUILDINFO */
1381         
1382         layout = uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, 480, 110, style);
1383         
1384         uiBlockSetEmboss(block, UI_EMBOSS);
1385         /* show the splash menu (containing interaction presets), using python */
1386         if (mt) {
1387                 Menu menu = {NULL};
1388                 menu.layout = layout;
1389                 menu.type = mt;
1390                 mt->draw(C, &menu);
1391
1392 //              wmWindowManager *wm = CTX_wm_manager(C);
1393 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
1394         }
1395         
1396         uiBlockSetEmboss(block, UI_EMBOSSP);
1397         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
1398         
1399         split = uiLayoutSplit(layout, 0.0f, FALSE);
1400         col = uiLayoutColumn(split, FALSE);
1401         uiItemL(col, "Links", ICON_NONE);
1402         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/blenderorg/blender-foundation/donation-payment");
1403         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/development/credits");
1404         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/development/release-logs/blender-264");
1405         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url", "http://wiki.blender.org/index.php/Doc:2.6/Manual");
1406         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
1407         uiItemStringO(col, IFACE_("User Community"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/community/user-community");
1408         if (strcmp(STRINGIFY(BLENDER_VERSION_CYCLE), "release") == 0) {
1409                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d" STRINGIFY(BLENDER_VERSION_CHAR) "_release", BLENDER_VERSION / 100, BLENDER_VERSION % 100);
1410         }
1411         else {
1412                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d_%d", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
1413         }
1414         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
1415         uiItemL(col, "", ICON_NONE);
1416
1417         col = uiLayoutColumn(split, FALSE);
1418
1419         if (wm_resource_check_prev()) {
1420                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
1421                 uiItemS(col);
1422         }
1423
1424         uiItemL(col, IFACE_("Recent"), ICON_NONE);
1425         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
1426                 BLI_split_file_part(recent->filepath, file, sizeof(file));
1427                 if (BLO_has_bfile_extension(file))
1428                         uiItemStringO(col, BLI_path_basename(recent->filepath), ICON_FILE_BLEND, "WM_OT_open_mainfile", "filepath", recent->filepath);
1429                 else
1430                         uiItemStringO(col, BLI_path_basename(recent->filepath), ICON_FILE_BACKUP, "WM_OT_open_mainfile", "filepath", recent->filepath);
1431         }
1432
1433         uiItemS(col);
1434         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
1435         uiItemL(col, "", ICON_NONE);
1436         
1437         uiCenteredBoundsBlock(block, 0);
1438         uiEndBlock(C, block);
1439         
1440         return block;
1441 }
1442
1443 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
1444 {
1445         uiPupBlock(C, wm_block_create_splash, NULL);
1446         
1447         return OPERATOR_FINISHED;
1448 }
1449
1450 static void WM_OT_splash(wmOperatorType *ot)
1451 {
1452         ot->name = "Splash Screen";
1453         ot->idname = "WM_OT_splash";
1454         ot->description = "Opens a blocking popup region with release info";
1455         
1456         ot->invoke = wm_splash_invoke;
1457         ot->poll = WM_operator_winactive;
1458 }
1459
1460
1461 /* ***************** Search menu ************************* */
1462 static void operator_call_cb(struct bContext *C, void *UNUSED(arg1), void *arg2)
1463 {
1464         wmOperatorType *ot = arg2;
1465         
1466         if (ot)
1467                 WM_operator_name_call(C, ot->idname, WM_OP_INVOKE_DEFAULT, NULL);
1468 }
1469
1470 static void operator_search_cb(const struct bContext *C, void *UNUSED(arg), const char *str, uiSearchItems *items)
1471 {
1472         GHashIterator *iter = WM_operatortype_iter();
1473
1474         for (; !BLI_ghashIterator_isDone(iter); BLI_ghashIterator_step(iter)) {
1475                 wmOperatorType *ot = BLI_ghashIterator_getValue(iter);
1476
1477                 if ((ot->flag & OPTYPE_INTERNAL) && (G.debug & G_DEBUG_WM) == 0)
1478                         continue;
1479
1480                 if (BLI_strcasestr(ot->name, str)) {
1481                         if (WM_operator_poll((bContext *)C, ot)) {
1482                                 char name[256];
1483                                 int len = strlen(ot->name);
1484                                 
1485                                 /* display name for menu, can hold hotkey */
1486                                 BLI_strncpy(name, ot->name, sizeof(name));
1487                                 
1488                                 /* check for hotkey */
1489                                 if (len < sizeof(name) - 6) {
1490                                         if (WM_key_event_operator_string(C, ot->idname, WM_OP_EXEC_DEFAULT, NULL, TRUE,
1491                                                                          &name[len + 1], sizeof(name) - len - 1))
1492                                         {
1493                                                 name[len] = '|';
1494                                         }
1495                                 }
1496                                 
1497                                 if (0 == uiSearchItemAdd(items, name, ot, 0))
1498                                         break;
1499                         }
1500                 }
1501         }
1502         BLI_ghashIterator_free(iter);
1503 }
1504
1505 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *UNUSED(arg_op))
1506 {
1507         static char search[256] = "";
1508         wmEvent event;
1509         wmWindow *win = CTX_wm_window(C);
1510         uiBlock *block;
1511         uiBut *but;
1512         
1513         block = uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
1514         uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
1515         
1516         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, 9 * UI_UNIT_X, UI_UNIT_Y, 0, 0, "");
1517         uiButSetSearchFunc(but, operator_search_cb, NULL, operator_call_cb, NULL);
1518         
1519         /* fake button, it holds space for search items */
1520         uiDefBut(block, LABEL, 0, "", 10, 10 - uiSearchBoxhHeight(), 9 * UI_UNIT_X, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
1521         
1522         uiPopupBoundsBlock(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1523         uiEndBlock(C, block);
1524         
1525         event = *(win->eventstate);  /* XXX huh huh? make api call */
1526         event.type = EVT_BUT_OPEN;
1527         event.val = KM_PRESS;
1528         event.customdata = but;
1529         event.customdatafree = FALSE;
1530         wm_event_add(win, &event);
1531         
1532         return block;
1533 }
1534
1535 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1536 {
1537         return OPERATOR_FINISHED;
1538 }
1539
1540 static int wm_search_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1541 {
1542         uiPupBlock(C, wm_block_search_menu, op);
1543         
1544         return OPERATOR_CANCELLED;
1545 }
1546
1547 /* op->poll */
1548 static int wm_search_menu_poll(bContext *C)
1549 {
1550         if (CTX_wm_window(C) == NULL) {
1551                 return 0;
1552         }
1553         else {
1554                 ScrArea *sa = CTX_wm_area(C);
1555                 if (sa) {
1556                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
1557                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
1558                 }
1559                 else {
1560                         Object *editob = CTX_data_edit_object(C);
1561                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
1562                 }
1563         }
1564         return 1;
1565 }
1566
1567 static void WM_OT_search_menu(wmOperatorType *ot)
1568 {
1569         ot->name = "Search Menu";
1570         ot->idname = "WM_OT_search_menu";
1571         ot->description = "Pop-up a search menu over all available operators in current context";
1572         
1573         ot->invoke = wm_search_menu_invoke;
1574         ot->exec = wm_search_menu_exec;
1575         ot->poll = wm_search_menu_poll;
1576 }
1577
1578 static int wm_call_menu_exec(bContext *C, wmOperator *op)
1579 {
1580         char idname[BKE_ST_MAXNAME];
1581         RNA_string_get(op->ptr, "name", idname);
1582
1583         uiPupMenuInvoke(C, idname);
1584
1585         return OPERATOR_CANCELLED;
1586 }
1587
1588 static void WM_OT_call_menu(wmOperatorType *ot)
1589 {
1590         ot->name = "Call Menu";
1591         ot->idname = "WM_OT_call_menu";
1592
1593         ot->exec = wm_call_menu_exec;
1594         ot->poll = WM_operator_winactive;
1595
1596         ot->flag = OPTYPE_INTERNAL;
1597
1598         RNA_def_string(ot->srna, "name", "", BKE_ST_MAXNAME, "Name", "Name of the menu");
1599 }
1600
1601 /* ************ window / screen operator definitions ************** */
1602
1603 /* this poll functions is needed in place of WM_operator_winactive
1604  * while it crashes on full screen */
1605 static int wm_operator_winactive_normal(bContext *C)
1606 {
1607         wmWindow *win = CTX_wm_window(C);
1608
1609         if (win == NULL || win->screen == NULL || win->screen->full != SCREENNORMAL)
1610                 return 0;
1611
1612         return 1;
1613 }
1614
1615 static void WM_OT_window_duplicate(wmOperatorType *ot)
1616 {
1617         ot->name = "Duplicate Window";
1618         ot->idname = "WM_OT_window_duplicate";
1619         ot->description = "Duplicate the current Blender window";
1620                 
1621         ot->exec = wm_window_duplicate_exec;
1622         ot->poll = wm_operator_winactive_normal;
1623 }
1624
1625 static void WM_OT_save_homefile(wmOperatorType *ot)
1626 {
1627         ot->name = "Save User Settings";
1628         ot->idname = "WM_OT_save_homefile";
1629         ot->description = "Make the current file the default .blend file";
1630                 
1631         ot->invoke = WM_operator_confirm;
1632         ot->exec = WM_homefile_write_exec;
1633         ot->poll = WM_operator_winactive;
1634 }
1635
1636 static void WM_OT_read_homefile(wmOperatorType *ot)
1637 {
1638         ot->name = "Reload Start-Up File";
1639         ot->idname = "WM_OT_read_homefile";
1640         ot->description = "Open the default file (doesn't save the current file)";
1641         
1642         ot->invoke = WM_operator_confirm;
1643         ot->exec = WM_homefile_read_exec;
1644         /* ommit poll to run in background mode */
1645 }
1646
1647 static void WM_OT_read_factory_settings(wmOperatorType *ot)
1648 {
1649         ot->name = "Load Factory Settings";
1650         ot->idname = "WM_OT_read_factory_settings";
1651         ot->description = "Load default file and user preferences";
1652         
1653         ot->invoke = WM_operator_confirm;
1654         ot->exec = WM_homefile_read_exec;
1655         /* ommit poll to run in background mode */
1656 }
1657
1658 /* *************** open file **************** */
1659
1660 static void open_set_load_ui(wmOperator *op)
1661 {
1662         if (!RNA_struct_property_is_set(op->ptr, "load_ui"))
1663                 RNA_boolean_set(op->ptr, "load_ui", !(U.flag & USER_FILENOUI));
1664 }
1665
1666 static void open_set_use_scripts(wmOperator *op)
1667 {
1668         if (!RNA_struct_property_is_set(op->ptr, "use_scripts")) {
1669                 /* use G_SCRIPT_AUTOEXEC rather than the userpref because this means if
1670                  * the flag has been disabled from the command line, then opening
1671                  * from the menu wont enable this setting. */
1672                 RNA_boolean_set(op->ptr, "use_scripts", (G.f & G_SCRIPT_AUTOEXEC));
1673         }
1674 }
1675
1676 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1677 {
1678         const char *openname = G.main->name;
1679
1680         if (CTX_wm_window(C) == NULL) {
1681                 /* in rare cases this could happen, when trying to invoke in background
1682                  * mode on load for example. Don't use poll for this because exec()
1683                  * can still run without a window */
1684                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
1685                 return OPERATOR_CANCELLED;
1686         }
1687
1688         /* if possible, get the name of the most recently used .blend file */
1689         if (G.recent_files.first) {
1690                 struct RecentFile *recent = G.recent_files.first;
1691                 openname = recent->filepath;
1692         }
1693
1694         RNA_string_set(op->ptr, "filepath", openname);
1695         open_set_load_ui(op);
1696         open_set_use_scripts(op);
1697
1698         WM_event_add_fileselect(C, op);
1699
1700         return OPERATOR_RUNNING_MODAL;
1701 }
1702
1703 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
1704 {
1705         char path[FILE_MAX];
1706
1707         RNA_string_get(op->ptr, "filepath", path);
1708         open_set_load_ui(op);
1709         open_set_use_scripts(op);
1710
1711         if (RNA_boolean_get(op->ptr, "load_ui"))
1712                 G.fileflags &= ~G_FILE_NO_UI;
1713         else
1714                 G.fileflags |= G_FILE_NO_UI;
1715                 
1716         if (RNA_boolean_get(op->ptr, "use_scripts"))
1717                 G.f |= G_SCRIPT_AUTOEXEC;
1718         else
1719                 G.f &= ~G_SCRIPT_AUTOEXEC;
1720         
1721         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1722         /* do it before for now, but is this correct with multiple windows? */
1723         WM_event_add_notifier(C, NC_WINDOW, NULL);
1724
1725         WM_file_read(C, path, op->reports);
1726         
1727         return OPERATOR_FINISHED;
1728 }
1729
1730 static void WM_OT_open_mainfile(wmOperatorType *ot)
1731 {
1732         ot->name = "Open Blender File";
1733         ot->idname = "WM_OT_open_mainfile";
1734         ot->description = "Open a Blender file";
1735
1736         ot->invoke = wm_open_mainfile_invoke;
1737         ot->exec = wm_open_mainfile_exec;
1738         /* ommit window poll so this can work in background mode */
1739
1740         WM_operator_properties_filesel(ot, FOLDERFILE | BLENDERFILE, FILE_BLENDER, FILE_OPENFILE,
1741                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
1742
1743         RNA_def_boolean(ot->srna, "load_ui", 1, "Load UI", "Load user interface setup in the .blend file");
1744         RNA_def_boolean(ot->srna, "use_scripts", 1, "Trusted Source",
1745                         "Allow .blend file to execute scripts automatically, default available from system preferences");
1746 }
1747
1748 /* **************** link/append *************** */
1749
1750 static int wm_link_append_poll(bContext *C)
1751 {
1752         if (WM_operator_winactive(C)) {
1753                 /* linking changes active object which is pretty useful in general,
1754                  * but which totally confuses edit mode (i.e. it becoming not so obvious
1755                  * to leave from edit mode and inwalid tools in toolbar might be displayed)
1756                  * so disable link/append when in edit mode (sergey) */
1757                 if (CTX_data_edit_object(C))
1758                         return 0;
1759
1760                 return 1;
1761         }
1762
1763         return 0;
1764 }
1765
1766 static int wm_link_append_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1767 {
1768         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
1769                 return WM_operator_call_notest(C, op);
1770         }
1771         else {
1772                 /* XXX TODO solve where to get last linked library from */
1773                 if (G.lib[0] != '\0') {
1774                         RNA_string_set(op->ptr, "filepath", G.lib);
1775                 }
1776                 else if (G.relbase_valid) {
1777                         char path[FILE_MAX];
1778                         BLI_strncpy(path, G.main->name, sizeof(G.main->name));
1779                         BLI_parent_dir(path);
1780                         RNA_string_set(op->ptr, "filepath", path);
1781                 }
1782                 WM_event_add_fileselect(C, op);
1783                 return OPERATOR_RUNNING_MODAL;
1784         }
1785 }
1786
1787 static short wm_link_append_flag(wmOperator *op)
1788 {
1789         short flag = 0;
1790
1791         if (RNA_boolean_get(op->ptr, "autoselect")) flag |= FILE_AUTOSELECT;
1792         if (RNA_boolean_get(op->ptr, "active_layer")) flag |= FILE_ACTIVELAY;
1793         if (RNA_boolean_get(op->ptr, "relative_path")) flag |= FILE_RELPATH;
1794         if (RNA_boolean_get(op->ptr, "link")) flag |= FILE_LINK;
1795         if (RNA_boolean_get(op->ptr, "instance_groups")) flag |= FILE_GROUP_INSTANCE;
1796
1797         return flag;
1798 }
1799
1800 static int wm_link_append_exec(bContext *C, wmOperator *op)
1801 {
1802         Main *bmain = CTX_data_main(C);
1803         Scene *scene = CTX_data_scene(C);
1804         Main *mainl = NULL;
1805         BlendHandle *bh;
1806         PropertyRNA *prop;
1807         char name[FILE_MAX], dir[FILE_MAX], libname[FILE_MAX], group[GROUP_MAX];
1808         int idcode, totfiles = 0;
1809         short flag;
1810
1811         RNA_string_get(op->ptr, "filename", name);
1812         RNA_string_get(op->ptr, "directory", dir);
1813
1814         /* test if we have a valid data */
1815         if (BLO_is_a_library(dir, libname, group) == 0) {
1816                 BKE_report(op->reports, RPT_ERROR, "Not a library");
1817                 return OPERATOR_CANCELLED;
1818         }
1819         else if (group[0] == 0) {
1820                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1821                 return OPERATOR_CANCELLED;
1822         }
1823         else if (BLI_path_cmp(bmain->name, libname) == 0) {
1824                 BKE_report(op->reports, RPT_ERROR, "Cannot use current file as library");
1825                 return OPERATOR_CANCELLED;
1826         }
1827
1828         /* check if something is indicated for append/link */
1829         prop = RNA_struct_find_property(op->ptr, "files");
1830         if (prop) {
1831                 totfiles = RNA_property_collection_length(op->ptr, prop);
1832                 if (totfiles == 0) {
1833                         if (name[0] == '\0') {
1834                                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1835                                 return OPERATOR_CANCELLED;
1836                         }
1837                 }
1838         }
1839         else if (name[0] == '\0') {
1840                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1841                 return OPERATOR_CANCELLED;
1842         }
1843
1844         bh = BLO_blendhandle_from_file(libname, op->reports);
1845
1846         if (bh == NULL) {
1847                 /* unlikely since we just browsed it, but possible
1848                  * error reports will have been made by BLO_blendhandle_from_file() */
1849                 return OPERATOR_CANCELLED;
1850         }
1851
1852
1853         /* from here down, no error returns */
1854
1855         idcode = BKE_idcode_from_name(group);
1856
1857         /* now we have or selected, or an indicated file */
1858         if (RNA_boolean_get(op->ptr, "autoselect"))
1859                 BKE_scene_base_deselect_all(scene);
1860
1861         
1862         flag = wm_link_append_flag(op);
1863
1864         /* sanity checks for flag */
1865         if (scene->id.lib && (flag & FILE_GROUP_INSTANCE)) {
1866                 /* TODO, user never gets this message */
1867                 BKE_reportf(op->reports, RPT_WARNING, "Scene '%s' is linked, group instance disabled", scene->id.name + 2);
1868                 flag &= ~FILE_GROUP_INSTANCE;
1869         }
1870
1871
1872         /* tag everything, all untagged data can be made local
1873          * its also generally useful to know what is new
1874          *
1875          * take extra care flag_all_listbases_ids(LIB_LINK_TAG, 0) is called after! */
1876         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
1877
1878         /* here appending/linking starts */
1879         mainl = BLO_library_append_begin(bmain, &bh, libname);
1880         if (totfiles == 0) {
1881                 BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1882         }
1883         else {
1884                 RNA_BEGIN(op->ptr, itemptr, "files")
1885                 {
1886                         RNA_string_get(&itemptr, "name", name);
1887                         BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1888                 }
1889                 RNA_END;
1890         }
1891         BLO_library_append_end(C, mainl, &bh, idcode, flag);
1892         
1893         /* mark all library linked objects to be updated */
1894         recalc_all_library_objects(bmain);
1895         IMB_colormanagement_check_file_config(bmain);
1896
1897         /* append, rather than linking */
1898         if ((flag & FILE_LINK) == 0) {
1899                 Library *lib = BLI_findstring(&bmain->library, libname, offsetof(Library, filepath));
1900                 if (lib) BKE_library_make_local(bmain, lib, 1);
1901                 else BLI_assert(!"cant find name of just added library!");
1902         }
1903
1904         /* important we unset, otherwise these object wont
1905          * link into other scenes from this blend file */
1906         flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
1907
1908         /* recreate dependency graph to include new objects */
1909         DAG_scene_sort(bmain, scene);
1910         DAG_ids_flush_update(bmain, 0);
1911
1912         BLO_blendhandle_close(bh);
1913
1914         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
1915         BLI_strncpy(G.lib, dir, FILE_MAX);
1916
1917         WM_event_add_notifier(C, NC_WINDOW, NULL);
1918
1919         return OPERATOR_FINISHED;
1920 }
1921
1922 static void WM_OT_link_append(wmOperatorType *ot)
1923 {
1924         PropertyRNA *prop;
1925
1926         ot->name = "Link/Append from Library";
1927         ot->idname = "WM_OT_link_append";
1928         ot->description = "Link or Append from a Library .blend file";
1929         
1930         ot->invoke = wm_link_append_invoke;
1931         ot->exec = wm_link_append_exec;
1932         ot->poll = wm_link_append_poll;
1933         
1934         ot->flag |= OPTYPE_UNDO;
1935
1936         WM_operator_properties_filesel(
1937                 ot, FOLDERFILE | BLENDERFILE, FILE_LOADLIB, FILE_OPENFILE,
1938                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH | WM_FILESEL_FILES,
1939                 FILE_DEFAULTDISPLAY);
1940         
1941         /* better not save _any_ settings for this operator */
1942         /* properties */
1943         prop = RNA_def_boolean(ot->srna, "link", 1, "Link", "Link the objects or datablocks rather than appending");
1944         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1945         prop = RNA_def_boolean(ot->srna, "autoselect", 1, "Select", "Select the linked objects");
1946         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1947         prop = RNA_def_boolean(ot->srna, "active_layer", 1, "Active Layer", "Put the linked objects on the active layer");
1948         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1949         prop = RNA_def_boolean(ot->srna, "instance_groups", 1, "Instance Groups", "Create instances for each group as a DupliGroup");
1950         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1951 }
1952
1953 /* *************** recover last session **************** */
1954
1955 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1956 {
1957         char filename[FILE_MAX];
1958
1959         G.fileflags |= G_FILE_RECOVER;
1960
1961         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1962         /* do it before for now, but is this correct with multiple windows? */
1963         WM_event_add_notifier(C, NC_WINDOW, NULL);
1964
1965         /* load file */
1966         BLI_make_file_string("/", filename, BLI_temporary_dir(), "quit.blend");
1967         WM_file_read(C, filename, op->reports);
1968
1969         G.fileflags &= ~G_FILE_RECOVER;
1970         return OPERATOR_FINISHED;
1971 }
1972
1973 static void WM_OT_recover_last_session(wmOperatorType *ot)
1974 {
1975         ot->name = "Recover Last Session";
1976         ot->idname = "WM_OT_recover_last_session";
1977         ot->description = "Open the last closed file (\"quit.blend\")";
1978         
1979         ot->exec = wm_recover_last_session_exec;
1980         ot->poll = WM_operator_winactive;
1981 }
1982
1983 /* *************** recover auto save **************** */
1984
1985 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1986 {
1987         char path[FILE_MAX];
1988
1989         RNA_string_get(op->ptr, "filepath", path);
1990
1991         G.fileflags |= G_FILE_RECOVER;
1992
1993         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1994         /* do it before for now, but is this correct with multiple windows? */
1995         WM_event_add_notifier(C, NC_WINDOW, NULL);
1996
1997         /* load file */
1998         WM_file_read(C, path, op->reports);
1999
2000         G.fileflags &= ~G_FILE_RECOVER;
2001
2002         return OPERATOR_FINISHED;
2003 }
2004
2005 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2006 {
2007         char filename[FILE_MAX];
2008
2009         wm_autosave_location(filename);
2010         RNA_string_set(op->ptr, "filepath", filename);
2011         WM_event_add_fileselect(C, op);
2012
2013         return OPERATOR_RUNNING_MODAL;
2014 }
2015
2016 static void WM_OT_recover_auto_save(wmOperatorType *ot)
2017 {
2018         ot->name = "Recover Auto Save";
2019         ot->idname = "WM_OT_recover_auto_save";
2020         ot->description = "Open an automatically saved file to recover it";
2021         
2022         ot->exec = wm_recover_auto_save_exec;
2023         ot->invoke = wm_recover_auto_save_invoke;
2024         ot->poll = WM_operator_winactive;
2025
2026         WM_operator_properties_filesel(ot, BLENDERFILE, FILE_BLENDER, FILE_OPENFILE,
2027                                        WM_FILESEL_FILEPATH, FILE_LONGDISPLAY);
2028 }
2029
2030 /* *************** save file as **************** */
2031
2032 static void untitled(char *filepath)
2033 {
2034         if (G.save_over == 0 && strlen(filepath) < FILE_MAX - 16) {
2035                 char *c = BLI_last_slash(filepath);
2036                 
2037                 if (c)
2038                         strcpy(&c[1], "untitled.blend");
2039                 else
2040                         strcpy(filepath, "untitled.blend");
2041         }
2042 }
2043
2044 static void save_set_compress(wmOperator *op)
2045 {
2046         if (!RNA_struct_property_is_set(op->ptr, "compress")) {
2047                 if (G.save_over) /* keep flag for existing file */
2048                         RNA_boolean_set(op->ptr, "compress", G.fileflags & G_FILE_COMPRESS);
2049                 else /* use userdef for new file */
2050                         RNA_boolean_set(op->ptr, "compress", U.flag & USER_FILECOMPRESS);
2051         }
2052 }
2053
2054 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2055 {
2056         char name[FILE_MAX];
2057
2058         save_set_compress(op);
2059         
2060         /* if not saved before, get the name of the most recently used .blend file */
2061         if (G.main->name[0] == 0 && G.recent_files.first) {
2062                 struct RecentFile *recent = G.recent_files.first;
2063                 BLI_strncpy(name, recent->filepath, FILE_MAX);
2064         }
2065         else
2066                 BLI_strncpy(name, G.main->name, FILE_MAX);
2067         
2068         untitled(name);
2069         RNA_string_set(op->ptr, "filepath", name);
2070         
2071         WM_event_add_fileselect(C, op);
2072
2073         return OPERATOR_RUNNING_MODAL;
2074 }
2075
2076 /* function used for WM_OT_save_mainfile too */
2077 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2078 {
2079         char path[FILE_MAX];
2080         int fileflags;
2081
2082         save_set_compress(op);
2083         
2084         if (RNA_struct_property_is_set(op->ptr, "filepath"))
2085                 RNA_string_get(op->ptr, "filepath", path);
2086         else {
2087                 BLI_strncpy(path, G.main->name, FILE_MAX);
2088                 untitled(path);
2089         }
2090         
2091         fileflags = G.fileflags;
2092
2093         /* set compression flag */
2094         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "compress"),
2095                          G_FILE_COMPRESS);
2096         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
2097                          G_FILE_RELATIVE_REMAP);
2098         BKE_BIT_TEST_SET(fileflags,
2099                          (RNA_struct_property_is_set(op->ptr, "copy") &&
2100                           RNA_boolean_get(op->ptr, "copy")),
2101                          G_FILE_SAVE_COPY);
2102
2103 #ifdef USE_BMESH_SAVE_AS_COMPAT
2104         BKE_BIT_TEST_SET(fileflags,
2105                          (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
2106                           RNA_boolean_get(op->ptr, "use_mesh_compat")),
2107                          G_FILE_MESH_COMPAT);
2108 #endif
2109
2110         if (WM_file_write(C, path, fileflags, op->reports) != 0)
2111                 return OPERATOR_CANCELLED;
2112
2113         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2114
2115         return OPERATOR_FINISHED;
2116 }
2117
2118 /* function used for WM_OT_save_mainfile too */
2119 static int blend_save_check(bContext *UNUSED(C), wmOperator *op)
2120 {
2121         char filepath[FILE_MAX];
2122         RNA_string_get(op->ptr, "filepath", filepath);
2123         if (!BLO_has_bfile_extension(filepath)) {
2124                 /* some users would prefer BLI_replace_extension(),
2125                  * we keep getting knit-picking bug reports about this - campbell */
2126                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
2127                 RNA_string_set(op->ptr, "filepath", filepath);
2128                 return TRUE;
2129         }
2130         return FALSE;
2131 }
2132
2133 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
2134 {
2135         ot->name = "Save As Blender File";
2136         ot->idname = "WM_OT_save_as_mainfile";
2137         ot->description = "Save the current file in the desired location";
2138         
2139         ot->invoke = wm_save_as_mainfile_invoke;
2140         ot->exec = wm_save_as_mainfile_exec;
2141         ot->check = blend_save_check;
2142         /* ommit window poll so this can work in background mode */
2143
2144         WM_operator_properties_filesel(ot, FOLDERFILE | BLENDERFILE, FILE_BLENDER, FILE_SAVE,
2145                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
2146         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2147         RNA_def_boolean(ot->srna, "relative_remap", 1, "Remap Relative",
2148                         "Remap relative paths when saving in a different directory");
2149         RNA_def_boolean(ot->srna, "copy", 0, "Save Copy",
2150                         "Save a copy of the actual working state but does not make saved file active");
2151 #ifdef USE_BMESH_SAVE_AS_COMPAT
2152         RNA_def_boolean(ot->srna, "use_mesh_compat", 0, "Legacy Mesh Format",
2153                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
2154                         "be lost (no implicit triangulation)");
2155 #endif
2156 }
2157
2158 /* *************** save file directly ******** */
2159
2160 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2161 {
2162         char name[FILE_MAX];
2163         int ret;
2164         
2165         /* cancel if no active window */
2166         if (CTX_wm_window(C) == NULL)
2167                 return OPERATOR_CANCELLED;
2168
2169         save_set_compress(op);
2170
2171         /* if not saved before, get the name of the most recently used .blend file */
2172         if (G.main->name[0] == 0 && G.recent_files.first) {
2173                 struct RecentFile *recent = G.recent_files.first;
2174                 BLI_strncpy(name, recent->filepath, FILE_MAX);
2175         }
2176         else
2177                 BLI_strncpy(name, G.main->name, FILE_MAX);
2178
2179         untitled(name);
2180         
2181         RNA_string_set(op->ptr, "filepath", name);
2182
2183         if (G.save_over) {
2184                 if (BLI_exists(name)) {
2185                         uiPupMenuSaveOver(C, op, name);
2186                         ret = OPERATOR_RUNNING_MODAL;
2187                 }
2188                 else {
2189                         ret = wm_save_as_mainfile_exec(C, op);
2190                 }
2191         }
2192         else {
2193                 WM_event_add_fileselect(C, op);
2194                 ret = OPERATOR_RUNNING_MODAL;
2195         }
2196         
2197         return ret;
2198 }
2199
2200 static void WM_OT_save_mainfile(wmOperatorType *ot)
2201 {
2202         ot->name = "Save Blender File";
2203         ot->idname = "WM_OT_save_mainfile";
2204         ot->description = "Save the current Blender file";
2205         
2206         ot->invoke = wm_save_mainfile_invoke;
2207         ot->exec = wm_save_as_mainfile_exec;
2208         ot->check = blend_save_check;
2209         /* ommit window poll so this can work in background mode */
2210         
2211         WM_operator_properties_filesel(ot, FOLDERFILE | BLENDERFILE, FILE_BLENDER, FILE_SAVE,
2212                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
2213         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2214         RNA_def_boolean(ot->srna, "relative_remap", 0, "Remap Relative", "Remap relative paths when saving in a different directory");
2215 }
2216
2217 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2218 {
2219         ot->name = "Toggle Fullscreen";
2220         ot->idname = "WM_OT_window_fullscreen_toggle";
2221         ot->description = "Toggle the current window fullscreen";
2222
2223         ot->exec = wm_window_fullscreen_toggle_exec;
2224         ot->poll = WM_operator_winactive;
2225 }
2226
2227 static int wm_exit_blender_op(bContext *C, wmOperator *op)
2228 {
2229         WM_operator_free(op);
2230         
2231         WM_exit(C);
2232         
2233         return OPERATOR_FINISHED;
2234 }
2235
2236 static void WM_OT_quit_blender(wmOperatorType *ot)
2237 {
2238         ot->name = "Quit Blender";
2239         ot->idname = "WM_OT_quit_blender";
2240         ot->description = "Quit Blender";
2241
2242         ot->invoke = WM_operator_confirm;
2243         ot->exec = wm_exit_blender_op;
2244         ot->poll = WM_operator_winactive;
2245 }
2246
2247 /* *********************** */
2248
2249 #if defined(WIN32)
2250
2251 static int wm_console_toggle_op(bContext *UNUSED(C), wmOperator *UNUSED(op))
2252 {
2253         GHOST_toggleConsole(2);
2254         return OPERATOR_FINISHED;
2255 }
2256
2257 static void WM_OT_console_toggle(wmOperatorType *ot)
2258 {
2259         /* XXX Have to mark these for xgettext, as under linux they do not exists...
2260          *     And even worth, have to give the context as text, as xgettext doesn't expand macros. :( */
2261         ot->name = CTX_N_("Operator" /* BLF_I18NCONTEXT_OPERATOR_DEFAULT */, "Toggle System Console");
2262         ot->idname = "WM_OT_console_toggle";
2263         ot->description = N_("Toggle System Console");
2264         
2265         ot->exec = wm_console_toggle_op;
2266         ot->poll = WM_operator_winactive;
2267 }
2268
2269 #endif
2270
2271 /* ************ default paint cursors, draw always around cursor *********** */
2272 /*
2273  * - returns handler to free
2274  * - poll(bContext): returns 1 if draw should happen
2275  * - draw(bContext): drawing callback for paint cursor
2276  */
2277
2278 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2279                                wmPaintCursorDraw draw, void *customdata)
2280 {
2281         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2282         
2283         BLI_addtail(&wm->paintcursors, pc);
2284         
2285         pc->customdata = customdata;
2286         pc->poll = poll;
2287         pc->draw = draw;
2288         
2289         return pc;
2290 }
2291
2292 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2293 {
2294         wmPaintCursor *pc;
2295         
2296         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
2297                 if (pc == (wmPaintCursor *)handle) {
2298                         BLI_remlink(&wm->paintcursors, pc);
2299                         MEM_freeN(pc);
2300                         return;
2301                 }
2302         }
2303 }
2304
2305 /* ************ window gesture operator-callback definitions ************** */
2306 /*
2307  * These are default callbacks for use in operators requiring gesture input
2308  */
2309
2310 /* **************** Border gesture *************** */
2311
2312 /* Border gesture has two types:
2313  * 1) WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border
2314  * 2) WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends
2315  *
2316  * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
2317  */
2318
2319 static int border_apply_rect(wmOperator *op)
2320 {
2321         wmGesture *gesture = op->customdata;
2322         rcti *rect = gesture->customdata;
2323         
2324         if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
2325                 return 0;
2326
2327         
2328         /* operator arguments and storage. */
2329         RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
2330         RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
2331         RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
2332         RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
2333
2334         return 1;
2335 }
2336
2337 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
2338 {
2339         int retval;
2340
2341         if (!border_apply_rect(op))
2342                 return 0;
2343         
2344         /* XXX weak; border should be configured for this without reading event types */
2345         if (RNA_struct_find_property(op->ptr, "gesture_mode") )
2346                 RNA_int_set(op->ptr, "gesture_mode", gesture_mode);
2347
2348         retval = op->type->exec(C, op);
2349         OPERATOR_RETVAL_CHECK(retval);
2350
2351         return 1;
2352 }
2353
2354 static void wm_gesture_end(bContext *C, wmOperator *op)
2355 {
2356         wmGesture *gesture = op->customdata;
2357         
2358         WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2359         op->customdata = NULL;
2360
2361         ED_area_tag_redraw(CTX_wm_area(C));
2362         
2363         if (RNA_struct_find_property(op->ptr, "cursor") )
2364                 WM_cursor_restore(CTX_wm_window(C));
2365 }
2366
2367 int WM_border_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
2368 {
2369         if (ISTWEAK(event->type))
2370                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
2371         else
2372                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
2373
2374         /* add modal handler */
2375         WM_event_add_modal_handler(C, op);
2376         
2377         wm_gesture_tag_redraw(C);
2378
2379         return OPERATOR_RUNNING_MODAL;
2380 }
2381
2382 int WM_border_select_modal(bContext *C, wmOperator *op, wmEvent *event)
2383 {
2384         wmGesture *gesture = op->customdata;
2385         rcti *rect = gesture->customdata;
2386         int sx, sy;
2387         
2388         if (event->type == MOUSEMOVE) {
2389                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2390
2391                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2392                         rect->xmin = rect->xmax = event->x - sx;
2393                         rect->ymin = rect->ymax = event->y - sy;
2394                 }
2395                 else {
2396                         rect->xmax = event->x - sx;
2397                         rect->ymax = event->y - sy;
2398                 }
2399                 border_apply_rect(op);
2400
2401                 wm_gesture_tag_redraw(C);
2402         }
2403         else if (event->type == EVT_MODAL_MAP) {
2404                 switch (event->val) {
2405                         case GESTURE_MODAL_BEGIN:
2406                                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2407                                         gesture->mode = 1;
2408                                         wm_gesture_tag_redraw(C);
2409                                 }
2410                                 break;
2411                         case GESTURE_MODAL_SELECT:
2412                         case GESTURE_MODAL_DESELECT:
2413                         case GESTURE_MODAL_IN:
2414                         case GESTURE_MODAL_OUT:
2415                                 if (border_apply(C, op, event->val)) {
2416                                         wm_gesture_end(C, op);
2417                                         return OPERATOR_FINISHED;
2418                                 }
2419                                 wm_gesture_end(C, op);
2420                                 return OPERATOR_CANCELLED;
2421                                 break;
2422
2423                         case GESTURE_MODAL_CANCEL:
2424                                 wm_gesture_end(C, op);
2425                                 return OPERATOR_CANCELLED;
2426                 }
2427
2428         }
2429 //      /* Allow view navigation??? */
2430 //      else {
2431 //              return OPERATOR_PASS_THROUGH;
2432 //      }
2433
2434         return OPERATOR_RUNNING_MODAL;
2435 }
2436
2437 int WM_border_select_cancel(bContext *C, wmOperator *op)
2438 {
2439         wm_gesture_end(C, op);
2440
2441         return OPERATOR_CANCELLED;
2442 }
2443
2444 /* **************** circle gesture *************** */
2445 /* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
2446
2447 #ifdef GESTURE_MEMORY
2448 int circle_select_size = 25; /* XXX - need some operator memory thing! */
2449 #endif
2450
2451 int WM_gesture_circle_invoke(bContext *C, wmOperator *op, wmEvent *event)
2452 {
2453         op->customdata = WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
2454         
2455         /* add modal handler */
2456         WM_event_add_modal_handler(C, op);
2457         
2458         wm_gesture_tag_redraw(C);
2459         
2460         return OPERATOR_RUNNING_MODAL;
2461 }
2462
2463 static void gesture_circle_apply(bContext *C, wmOperator *op)
2464 {
2465         wmGesture *gesture = op->customdata;
2466         rcti *rect = gesture->customdata;
2467         
2468         if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_NOP)
2469                 return;
2470
2471         /* operator arguments and storage. */
2472         RNA_int_set(op->ptr, "x", rect->xmin);
2473         RNA_int_set(op->ptr, "y", rect->ymin);
2474         RNA_int_set(op->ptr, "radius", rect->xmax);
2475         
2476         if (op->type->exec) {
2477                 int retval;
2478                 retval = op->type->exec(C, op);
2479                 OPERATOR_RETVAL_CHECK(retval);
2480         }
2481 #ifdef GESTURE_MEMORY
2482         circle_select_size = rect->xmax;
2483 #endif
2484 }
2485
2486 int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
2487 {
2488         wmGesture *gesture = op->customdata;
2489         rcti *rect = gesture->customdata;
2490         int sx, sy;
2491
2492         if (event->type == MOUSEMOVE) {
2493                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2494
2495                 rect->xmin = event->x - sx;
2496                 rect->ymin = event->y - sy;
2497
2498                 wm_gesture_tag_redraw(C);
2499
2500                 if (gesture->mode)
2501                         gesture_circle_apply(C, op);
2502         }
2503         else if (event->type == EVT_MODAL_MAP) {
2504                 switch (event->val) {
2505                         case GESTURE_MODAL_CIRCLE_ADD:
2506                                 rect->xmax += 2 + rect->xmax / 10;
2507                                 wm_gesture_tag_redraw(C);
2508                                 break;
2509                         case GESTURE_MODAL_CIRCLE_SUB:
2510                                 rect->xmax -= 2 + rect->xmax / 10;
2511                                 if (rect->xmax < 1) rect->xmax = 1;
2512                                 wm_gesture_tag_redraw(C);
2513                                 break;
2514                         case GESTURE_MODAL_SELECT:
2515                         case GESTURE_MODAL_DESELECT:
2516                         case GESTURE_MODAL_NOP:
2517                                 if (RNA_struct_find_property(op->ptr, "gesture_mode"))
2518                                         RNA_int_set(op->ptr, "gesture_mode", event->val);
2519
2520                                 if (event->val != GESTURE_MODAL_NOP) {
2521                                         /* apply first click */
2522                                         gesture_circle_apply(C, op);
2523                                         gesture->mode = 1;
2524                                         wm_gesture_tag_redraw(C);
2525                                 }
2526                                 break;
2527
2528                         case GESTURE_MODAL_CANCEL:
2529                         case GESTURE_MODAL_CONFIRM:
2530                                 wm_gesture_end(C, op);
2531                                 return OPERATOR_FINISHED; /* use finish or we don't get an undo */
2532                 }
2533         }
2534 //      /* Allow view navigation??? */
2535 //      else {
2536 //              return OPERATOR_PASS_THROUGH;
2537 //      }
2538
2539         return OPERATOR_RUNNING_MODAL;
2540 }
2541
2542 int WM_gesture_circle_cancel(bContext *C, wmOperator *op)
2543 {
2544         wm_gesture_end(C, op);
2545
2546         return OPERATOR_CANCELLED;
2547 }
2548
2549 #if 0
2550 /* template to copy from */
2551 void WM_OT_circle_gesture(wmOperatorType *ot)
2552 {
2553         ot->name = "Circle Gesture";
2554         ot->idname = "WM_OT_circle_gesture";
2555         ot->description = "Enter rotate mode with a circular gesture";
2556         
2557         ot->invoke = WM_gesture_circle_invoke;
2558         ot->modal = WM_gesture_circle_modal;
2559         
2560         ot->poll = WM_operator_winactive;
2561         
2562         RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
2563         RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
2564         RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
2565
2566 }
2567 #endif
2568
2569 /* **************** Tweak gesture *************** */
2570
2571 static void tweak_gesture_modal(bContext *C, wmEvent *event)
2572 {
2573         wmWindow *window = CTX_wm_window(C);
2574         wmGesture *gesture = window->tweak;
2575         rcti *rect = gesture->customdata;
2576         int sx, sy, val;
2577         
2578         switch (event->type) {
2579                 case MOUSEMOVE:
2580                 case INBETWEEN_MOUSEMOVE:
2581                         
2582                         wm_subwindow_getorigin(window, gesture->swinid, &sx, &sy);
2583                         
2584                         rect->xmax = event->x - sx;
2585                         rect->ymax = event->y - sy;
2586                         
2587                         if ((val = wm_gesture_evaluate(gesture))) {
2588                                 wmEvent tevent;
2589
2590                                 tevent = *(window->eventstate);
2591                                 if (gesture->event_type == LEFTMOUSE)
2592                                         tevent.type = EVT_TWEAK_L;
2593                                 else if (gesture->event_type == RIGHTMOUSE)
2594                                         tevent.type = EVT_TWEAK_R;
2595                                 else
2596                                         tevent.type = EVT_TWEAK_M;
2597                                 tevent.val = val;
2598                                 /* mouse coords! */
2599                                 wm_event_add(window, &tevent);
2600                                 
2601                                 WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2602                         }
2603                         
2604                         break;
2605                         
2606                 case LEFTMOUSE:
2607                 case RIGHTMOUSE:
2608                 case MIDDLEMOUSE:
2609                         if (gesture->event_type == event->type) {
2610                                 WM_gesture_end(C, gesture);
2611
2612                                 /* when tweak fails we should give the other keymap entries a chance */
2613                                 event->val = KM_RELEASE;
2614                         }
2615                         break;
2616                 default:
2617                         if (!ISTIMER(event->type)) {
2618                                 WM_gesture_end(C, gesture);
2619                         }
2620                         break;
2621         }
2622 }
2623
2624 /* standard tweak, called after window handlers passed on event */
2625 void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
2626 {
2627         wmWindow *win = CTX_wm_window(C);
2628         
2629         if (win->tweak == NULL) {
2630                 if (CTX_wm_region(C)) {
2631                         if (event->val == KM_PRESS) {
2632                                 if (ELEM3(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE) )
2633                                         win->tweak = WM_gesture_new(C, event, WM_GESTURE_TWEAK);
2634                         }
2635                 }
2636         }
2637         else {
2638                 /* no tweaks if event was handled */
2639                 if ((action & WM_HANDLER_BREAK)) {
2640                         WM_gesture_end(C, win->tweak);
2641                 }
2642                 else
2643                         tweak_gesture_modal(C, event);
2644         }
2645 }
2646
2647 /* *********************** lasso gesture ****************** */
2648
2649 int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, wmEvent *event)
2650 {
2651         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LASSO);
2652         
2653         /* add modal handler */
2654         WM_event_add_modal_handler(C, op);
2655         
2656         wm_gesture_tag_redraw(C);
2657         
2658         if (RNA_struct_find_property(op->ptr, "cursor") )
2659                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2660         
2661         return OPERATOR_RUNNING_MODAL;
2662 }
2663
2664 int WM_gesture_lines_invoke(bContext *C, wmOperator *op, wmEvent *event)
2665 {
2666         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LINES);
2667         
2668         /* add modal handler */
2669         WM_event_add_modal_handler(C, op);
2670         
2671         wm_gesture_tag_redraw(C);
2672         
2673         if (RNA_struct_find_property(op->ptr, "cursor") )
2674                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2675         
2676         return OPERATOR_RUNNING_MODAL;
2677 }
2678
2679
2680 static void gesture_lasso_apply(bContext *C, wmOperator *op)
2681 {
2682         wmGesture *gesture = op->customdata;
2683         PointerRNA itemptr;
2684         float loc[2];
2685         int i;
2686         short *lasso = gesture->customdata;
2687         
2688         /* operator storage as path. */
2689
2690         RNA_collection_clear(op->ptr, "path");
2691         for (i = 0; i < gesture->points; i++, lasso += 2) {
2692                 loc[0] = lasso[0];
2693                 loc[1] = lasso[1];
2694                 RNA_collection_add(op->ptr, "path", &itemptr);
2695                 RNA_float_set_array(&itemptr, "loc", loc);
2696         }
2697         
2698         wm_gesture_end(C, op);
2699                 
2700         if (op->type->exec) {
2701                 int retval = op->type->exec(C, op);
2702                 OPERATOR_RETVAL_CHECK(retval);
2703         }
2704 }
2705
2706 int WM_gesture_lasso_modal(bContext *C, wmOperator *op, wmEvent *event)
2707 {
2708         wmGesture *gesture = op->customdata;
2709         int sx, sy;
2710         
2711         switch (event->type) {
2712                 case MOUSEMOVE:
2713                 case INBETWEEN_MOUSEMOVE:
2714                         
2715                         wm_gesture_tag_redraw(C);
2716                         
2717                         wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2718
2719                         if (gesture->points == gesture->size) {
2720                                 short *old_lasso = gesture->customdata;
2721                                 gesture->customdata = MEM_callocN(2 * sizeof(short) * (gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
2722                                 memcpy(gesture->customdata, old_lasso, 2 * sizeof(short) * gesture->size);
2723                                 gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
2724                                 MEM_freeN(old_lasso);
2725                                 // printf("realloc\n");
2726                         }
2727
2728                         {
2729                                 int x, y;
2730                                 short *lasso = gesture->customdata;
2731                                 
2732                                 lasso += (2 * gesture->points - 2);
2733                                 x = (event->x - sx - lasso[0]);
2734                                 y = (event->y - sy - lasso[1]);
2735                                 
2736                                 /* make a simple distance check to get a smoother lasso
2737                                  * add only when at least 2 pixels between this and previous location */
2738                                 if ((x * x + y * y) > 4) {
2739                                         lasso += 2;
2740                                         lasso[0] = event->x - sx;
2741                                         lasso[1] = event->y - sy;
2742                                         gesture->points++;
2743                                 }
2744                         }
2745                         break;
2746                         
2747                 case LEFTMOUSE:
2748                 case MIDDLEMOUSE:
2749                 case RIGHTMOUSE:
2750                         if (event->val == KM_RELEASE) {   /* key release */
2751                                 gesture_lasso_apply(C, op);
2752                                 return OPERATOR_FINISHED;
2753                         }
2754                         break;
2755                 case ESCKEY:
2756                         wm_gesture_end(C, op);
2757                         return OPERATOR_CANCELLED;
2758         }
2759         return OPERATOR_RUNNING_MODAL;
2760 }
2761
2762 int WM_gesture_lines_modal(bContext *C, wmOperator *op, wmEvent *event)
2763 {
2764         return WM_gesture_lasso_modal(C, op, event);
2765 }
2766
2767 int WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
2768 {
2769         wm_gesture_end(C, op);
2770
2771         return OPERATOR_CANCELLED;
2772 }
2773
2774 int WM_gesture_lines_cancel(bContext *C, wmOperator *op)
2775 {
2776         wm_gesture_end(C, op);
2777
2778         return OPERATOR_CANCELLED;
2779 }
2780
2781 /**
2782  * helper function, we may want to add options for conversion to view space
2783  *
2784  * caller must free.
2785  */
2786 const int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
2787 {
2788         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
2789         int (*mcords)[2] = NULL;
2790         BLI_assert(prop != NULL);
2791
2792         if (prop) {
2793                 const int len = RNA_property_collection_length(op->ptr, prop);
2794
2795                 if (len) {
2796                         int i = 0;
2797                         mcords = MEM_mallocN(sizeof(int) * 2 * len, __func__);
2798
2799                         RNA_PROP_BEGIN(op->ptr, itemptr, prop)
2800                         {
2801                                 float loc[2];
2802
2803                                 RNA_float_get_array(&itemptr, "loc", loc);
2804                                 mcords[i][0] = (int)loc[0];
2805                                 mcords[i][1] = (int)loc[1];
2806                                 i++;
2807                         }
2808                         RNA_PROP_END;
2809                 }
2810                 *mcords_tot = len;
2811         }
2812         else {
2813                 *mcords_tot = 0;
2814         }
2815
2816         /* cast for 'const' */
2817         return (const int (*)[2])mcords;
2818 }
2819
2820 #if 0
2821 /* template to copy from */
2822
2823 static int gesture_lasso_exec(bContext *C, wmOperator *op)
2824 {
2825         RNA_BEGIN(op->ptr, itemptr, "path")
2826         {
2827                 float loc[2];
2828                 
2829                 RNA_float_get_array(&itemptr, "loc", loc);
2830                 printf("Location: %f %f\n", loc[0], loc[1]);
2831         }
2832         RNA_END;
2833         
2834         return OPERATOR_FINISHED;
2835 }
2836
2837 void WM_OT_lasso_gesture(wmOperatorType *ot)
2838 {
2839         PropertyRNA *prop;
2840         
2841         ot->name = "Lasso Gesture";
2842         ot->idname = "WM_OT_lasso_gesture";
2843         ot->description = "Select objects within the lasso as you move the pointer";
2844         
2845         ot->invoke = WM_gesture_lasso_invoke;
2846         ot->modal = WM_gesture_lasso_modal;
2847         ot->exec = gesture_lasso_exec;
2848         
2849         ot->poll = WM_operator_winactive;
2850         
2851         prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2852         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2853 }
2854 #endif
2855
2856 /* *********************** straight line gesture ****************** */
2857
2858 static int straightline_apply(bContext *C, wmOperator *op)
2859 {
2860         wmGesture *gesture = op->customdata;
2861         rcti *rect = gesture->customdata;
2862         
2863         if (rect->xmin == rect->xmax && rect->ymin == rect->ymax)
2864                 return 0;
2865         
2866         /* operator arguments and storage. */
2867         RNA_int_set(op->ptr, "xstart", rect->xmin);
2868         RNA_int_set(op->ptr, "ystart", rect->ymin);
2869         RNA_int_set(op->ptr, "xend", rect->xmax);
2870         RNA_int_set(op->ptr, "yend", rect->ymax);
2871
2872         if (op->type->exec) {
2873                 int retval = op->type->exec(C, op);
2874                 OPERATOR_RETVAL_CHECK(retval);
2875         }
2876         
2877         return 1;
2878 }
2879
2880
2881 int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, wmEvent *event)
2882 {
2883         op->customdata = WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
2884         
2885         /* add modal handler */
2886         WM_event_add_modal_handler(C, op);
2887         
2888         wm_gesture_tag_redraw(C);
2889         
2890         if (RNA_struct_find_property(op->ptr, "cursor") )
2891                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2892                 
2893         return OPERATOR_RUNNING_MODAL;
2894 }
2895
2896 int WM_gesture_straightline_modal(bContext *C, wmOperator *op, wmEvent *event)
2897 {
2898         wmGesture *gesture = op->customdata;
2899         rcti *rect = gesture->customdata;
2900         int sx, sy;
2901         
2902         if (event->type == MOUSEMOVE) {
2903                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2904                 
2905                 if (gesture->mode == 0) {
2906                         rect->xmin = rect->xmax = event->x - sx;
2907                         rect->ymin = rect->ymax = event->y - sy;
2908                 }
2909                 else {
2910                         rect->xmax = event->x - sx;
2911                         rect->ymax = event->y - sy;
2912                         straightline_apply(C, op);
2913                 }
2914                 
2915                 wm_gesture_tag_redraw(C);
2916         }
2917         else if (event->type == EVT_MODAL_MAP) {
2918                 switch (event->val) {
2919                         case GESTURE_MODAL_BEGIN:
2920                                 if (gesture->mode == 0) {
2921                                         gesture->mode = 1;
2922                                         wm_gesture_tag_redraw(C);
2923                                 }
2924                                 break;
2925                         case GESTURE_MODAL_SELECT:
2926                                 if (straightline_apply(C, op)) {
2927                                         wm_gesture_end(C, op);
2928                                         return OPERATOR_FINISHED;
2929                                 }
2930                                 wm_gesture_end(C, op);
2931                                 return OPERATOR_CANCELLED;
2932                                 break;
2933                                 
2934                         case GESTURE_MODAL_CANCEL:
2935                                 wm_gesture_end(C, op);
2936                                 return OPERATOR_CANCELLED;
2937                 }
2938                 
2939         }
2940
2941         return OPERATOR_RUNNING_MODAL;
2942 }
2943
2944 int WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
2945 {
2946         wm_gesture_end(C, op);
2947
2948         return OPERATOR_CANCELLED;
2949 }
2950
2951 #if 0
2952 /* template to copy from */
2953 void WM_OT_straightline_gesture(wmOperatorType *ot)
2954 {
2955         PropertyRNA *prop;
2956         
2957         ot->name = "Straight Line Gesture";
2958         ot->idname = "WM_OT_straightline_gesture";
2959         ot->description = "Draw a straight line as you move the pointer";
2960         
2961         ot->invoke = WM_gesture_straightline_invoke;
2962         ot->modal = WM_gesture_straightline_modal;
2963         ot->exec = gesture_straightline_exec;
2964         
2965         ot->poll = WM_operator_winactive;
2966         
2967         WM_operator_properties_gesture_straightline(ot, 0);
2968 }
2969 #endif
2970
2971 /* *********************** radial control ****************** */
2972
2973 static const int WM_RADIAL_CONTROL_DISPLAY_SIZE = 200;
2974
2975 typedef struct {
2976         PropertyType type;
2977         PropertySubType subtype;
2978         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2979         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2980         StructRNA *image_id_srna;
2981         float initial_value, current_value, min_value, max_value;
2982         int initial_mouse[2];
2983         unsigned int gltex;
2984         ListBase orig_paintcursors;
2985         void *cursor;
2986 } RadialControl;
2987
2988 static void radial_control_set_initial_mouse(RadialControl *rc, wmEvent *event)
2989 {
2990         float d[2] = {0, 0};
2991         float zoom[2] = {1, 1};
2992
2993         rc->initial_mouse[0] = event->x;
2994         rc->initial_mouse[1] = event->y;
2995
2996         switch (rc->subtype) {
2997                 case PROP_DISTANCE:
2998                         d[0] = rc->initial_value;
2999                         break;
3000                 case PROP_FACTOR:
3001                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * (1 - rc->initial_value);
3002                         break;
3003                 case PROP_ANGLE:
3004                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cos(rc->initial_value);
3005                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sin(rc->initial_value);
3006                         break;
3007                 default:
3008                         return;
3009         }
3010
3011         if (rc->zoom_prop) {
3012                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3013                 d[0] *= zoom[0];
3014                 d[1] *= zoom[1];
3015         }
3016
3017         rc->initial_mouse[0] -= d[0];
3018         rc->initial_mouse[1] -= d[1];
3019 }
3020
3021 static void radial_control_set_tex(RadialControl *rc)
3022 {
3023         ImBuf *ibuf;
3024
3025         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
3026                 case ID_BR:
3027                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data))) {
3028                                 glGenTextures(1, &rc->gltex);
3029                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
3030                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ibuf->x, ibuf->y, 0,
3031                                              GL_ALPHA, GL_FLOAT, ibuf->rect_float);
3032                                 MEM_freeN(ibuf->rect_float);
3033                                 MEM_freeN(ibuf);
3034                         }
3035                         break;
3036                 default:
3037                         break;
3038         }
3039 }
3040
3041 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
3042 {
3043         float col[3] = {0, 0, 0};
3044         float rot;
3045
3046         /* set fill color */
3047         if (rc->fill_col_prop)
3048                 RNA_property_float_get_array(&rc->fill_col_ptr, rc->fill_col_prop, col);
3049         glColor4f(col[0], col[1], col[2], alpha);
3050
3051         if (rc->gltex) {
3052                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
3053
3054                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
3055                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
3056
3057                 /* set up rotation if available */
3058                 if (rc->rot_prop) {
3059                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
3060                         glPushMatrix();
3061                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
3062                 }
3063
3064                 /* draw textured quad */
3065                 glEnable(GL_TEXTURE_2D);
3066                 glBegin(GL_QUADS);
3067                 glTexCoord2f(0, 0);
3068                 glVertex2f(-radius, -radius);
3069                 glTexCoord2f(1, 0);
3070                 glVertex2f(radius, -radius);
3071                 glTexCoord2f(1, 1);
3072                 glVertex2f(radius, radius);
3073                 glTexCoord2f(0, 1);
3074                 glVertex2f(-radius, radius);
3075                 glEnd();
3076                 glDisable(GL_TEXTURE_2D);
3077
3078                 /* undo rotation */
3079                 if (rc->rot_prop)
3080                         glPopMatrix();
3081         }
3082         else {
3083                 /* flat color if no texture available */
3084                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
3085         }
3086 }
3087
3088 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
3089 {
3090         RadialControl *rc = customdata;
3091         ARegion *ar = CTX_wm_region(C);
3092         float r1 = 0.0f, r2 = 0.0f, tex_radius, alpha;
3093         float zoom[2], col[3] = {1, 1, 1};
3094
3095         switch (rc->subtype) {
3096                 case PROP_DISTANCE:
3097                         r1 = rc->current_value;
3098                         r2 = rc->initial_value;
3099                         tex_radius = r1;
3100                         alpha = 0.75;
3101                         break;
3102                 case PROP_FACTOR:
3103                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_SIZE;
3104                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
3105                         alpha = rc->current_value / 2.0f + 0.5f;
3106                         break;
3107                 case PROP_ANGLE:
3108                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
3109                         alpha = 0.75;
3110                         break;
3111                 default:
3112                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
3113                         alpha = 0.75;
3114                         break;
3115         }
3116
3117         /* Keep cursor in the original place */
3118         x = rc->initial_mouse[0] - ar->winrct.xmin;
3119         y = rc->initial_mouse[1] - ar->winrct.ymin;
3120         glTranslatef((float)x, (float)y, 0.0f);
3121
3122         glEnable(GL_BLEND);
3123         glEnable(GL_LINE_SMOOTH);
3124
3125         /* apply zoom if available */
3126         if (rc->zoom_prop) {
3127                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3128                 glScalef(zoom[0], zoom[1], 1);
3129         }
3130
3131         /* draw rotated texture */
3132         radial_control_paint_tex(rc, tex_radius, alpha);
3133
3134         /* set line color */
3135         if (rc->col_prop)
3136                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
3137         glColor4f(col[0], col[1], col[2], 0.5);
3138
3139         if (rc->subtype == PROP_ANGLE) {
3140                 glPushMatrix();
3141                 /* draw original angle line */
3142                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
3143                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3144                 /* draw new angle line */
3145                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
3146                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3147                 glPopMatrix();
3148         }
3149
3150         /* draw circles on top */
3151         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r1, 40);
3152         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r2, 40);
3153
3154         glDisable(GL_BLEND);
3155         glDisable(GL_LINE_SMOOTH);
3156 }
3157
3158 typedef enum {
3159         RC_PROP_ALLOW_MISSING = 1,
3160         RC_PROP_REQUIRE_FLOAT = 2,
3161         RC_PROP_REQUIRE_BOOL = 4,
3162 } RCPropFlags;
3163
3164 /* attempt to retrieve the rna pointer/property from an rna path;
3165  * returns 0 for failure, 1 for success, and also 1 if property is not
3166  * set */
3167 static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
3168                                    const char *name, PointerRNA *r_ptr,
3169                                    PropertyRNA **r_prop, int req_length, RCPropFlags flags)
3170 {
3171         PropertyRNA *unused_prop;
3172         int len;
3173         char *str;
3174
3175         /* check flags */
3176         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
3177                 BKE_report(op->reports, RPT_ERROR, "Property cannot be both boolean and float");
3178                 return 0;
3179         }
3180
3181         /* get an rna string path from the operator's properties */
3182         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
3183                 return 1;
3184
3185         if (str[0] == '\0') {
3186                 if (r_prop) *r_prop = NULL;
3187                 MEM_freeN(str);
3188                 return 1;
3189         }
3190
3191         if (!r_prop)
3192                 r_prop = &unused_prop;
3193
3194         /* get rna from path */
3195         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
3196                 MEM_freeN(str);
3197                 if (flags & RC_PROP_ALLOW_MISSING)
3198                         return 1;
3199                 else {
3200                         BKE_reportf(op->reports, RPT_ERROR, "Could not resolve path '%s'", name);
3201                         return 0;
3202                 }
3203         }
3204
3205         /* check property type */
3206         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
3207                 PropertyType prop_type = RNA_property_type(*r_prop);
3208
3209                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
3210                     ((flags & RC_PROP_REQUIRE_FLOAT) && prop_type != PROP_FLOAT))
3211                 {
3212                         MEM_freeN(str);
3213                         BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' is not a float", name);
3214                         return 0;
3215                 }
3216         }
3217         
3218         /* check property's array length */
3219         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
3220                 MEM_freeN(str);
3221                 BKE_reportf(op->reports, RPT_ERROR, "Property from path '%s' has length %d instead of %d",
3222                             name, len, req_length);
3223                 return 0;
3224         }
3225
3226         /* success */
3227         MEM_freeN(str);
3228         return 1;
3229 }
3230
3231 /* initialize the rna pointers and properties using rna paths */
3232 static int radial_control_get_properties(bContext *C, wmOperator *op)
3233 {
3234         RadialControl *rc = op->customdata;
3235         PointerRNA ctx_ptr, use_secondary_ptr;
3236         PropertyRNA *use_secondary_prop;
3237         const char *data_path;
3238
3239         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
3240
3241         /* check if we use primary or secondary path */
3242         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
3243                                      &use_secondary_ptr, &use_secondary_prop,
3244                                      0, (RC_PROP_ALLOW_MISSING |
3245                                          RC_PROP_REQUIRE_BOOL)))
3246         {
3247                 return 0;
3248         }
3249         else {
3250                 if (use_secondary_prop &&
3251                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
3252                 {
3253        &nb