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