dont re-use previous values for link/append operator, would get mixed up with when...
[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         PropertyRNA *prop;
1870
1871         ot->name = "Link/Append from Library";
1872         ot->idname = "WM_OT_link_append";
1873         ot->description = "Link or Append from a Library .blend file";
1874         
1875         ot->invoke = wm_link_append_invoke;
1876         ot->exec = wm_link_append_exec;
1877         ot->poll = wm_link_append_poll;
1878         
1879         ot->flag |= OPTYPE_UNDO;
1880
1881         WM_operator_properties_filesel(
1882                 ot, FOLDERFILE | BLENDERFILE, FILE_LOADLIB, FILE_OPENFILE,
1883                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH | WM_FILESEL_FILES,
1884                 FILE_DEFAULTDISPLAY);
1885         
1886         /* better not save _any_ settings for this operator */
1887         /* properties */
1888         prop = RNA_def_boolean(ot->srna, "link", 1, "Link", "Link the objects or datablocks rather than appending");
1889         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1890         prop = RNA_def_boolean(ot->srna, "autoselect", 1, "Select", "Select the linked objects");
1891         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1892         prop = RNA_def_boolean(ot->srna, "active_layer", 1, "Active Layer", "Put the linked objects on the active layer");
1893         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1894         prop = RNA_def_boolean(ot->srna, "instance_groups", 1, "Instance Groups", "Create instances for each group as a DupliGroup");
1895         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1896 }
1897
1898 /* *************** recover last session **************** */
1899
1900 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1901 {
1902         char filename[FILE_MAX];
1903
1904         G.fileflags |= G_FILE_RECOVER;
1905
1906         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1907         /* do it before for now, but is this correct with multiple windows? */
1908         WM_event_add_notifier(C, NC_WINDOW, NULL);
1909
1910         /* load file */
1911         BLI_make_file_string("/", filename, BLI_temporary_dir(), "quit.blend");
1912         WM_file_read(C, filename, op->reports);
1913
1914         G.fileflags &= ~G_FILE_RECOVER;
1915         return OPERATOR_FINISHED;
1916 }
1917
1918 static void WM_OT_recover_last_session(wmOperatorType *ot)
1919 {
1920         ot->name = "Recover Last Session";
1921         ot->idname = "WM_OT_recover_last_session";
1922         ot->description = "Open the last closed file (\"quit.blend\")";
1923         
1924         ot->exec = wm_recover_last_session_exec;
1925         ot->poll = WM_operator_winactive;
1926 }
1927
1928 /* *************** recover auto save **************** */
1929
1930 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1931 {
1932         char path[FILE_MAX];
1933
1934         RNA_string_get(op->ptr, "filepath", path);
1935
1936         G.fileflags |= G_FILE_RECOVER;
1937
1938         /* XXX wm in context is not set correctly after WM_file_read -> crash */
1939         /* do it before for now, but is this correct with multiple windows? */
1940         WM_event_add_notifier(C, NC_WINDOW, NULL);
1941
1942         /* load file */
1943         WM_file_read(C, path, op->reports);
1944
1945         G.fileflags &= ~G_FILE_RECOVER;
1946
1947         return OPERATOR_FINISHED;
1948 }
1949
1950 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1951 {
1952         char filename[FILE_MAX];
1953
1954         wm_autosave_location(filename);
1955         RNA_string_set(op->ptr, "filepath", filename);
1956         WM_event_add_fileselect(C, op);
1957
1958         return OPERATOR_RUNNING_MODAL;
1959 }
1960
1961 static void WM_OT_recover_auto_save(wmOperatorType *ot)
1962 {
1963         ot->name = "Recover Auto Save";
1964         ot->idname = "WM_OT_recover_auto_save";
1965         ot->description = "Open an automatically saved file to recover it";
1966         
1967         ot->exec = wm_recover_auto_save_exec;
1968         ot->invoke = wm_recover_auto_save_invoke;
1969         ot->poll = WM_operator_winactive;
1970
1971         WM_operator_properties_filesel(ot, BLENDERFILE, FILE_BLENDER, FILE_OPENFILE,
1972                                        WM_FILESEL_FILEPATH, FILE_LONGDISPLAY);
1973 }
1974
1975 /* *************** save file as **************** */
1976
1977 static void untitled(char *filepath)
1978 {
1979         if (G.save_over == 0 && strlen(filepath) < FILE_MAX - 16) {
1980                 char *c = BLI_last_slash(filepath);
1981                 
1982                 if (c)
1983                         strcpy(&c[1], "untitled.blend");
1984                 else
1985                         strcpy(filepath, "untitled.blend");
1986         }
1987 }
1988
1989 static void save_set_compress(wmOperator *op)
1990 {
1991         if (!RNA_struct_property_is_set(op->ptr, "compress")) {
1992                 if (G.save_over) /* keep flag for existing file */
1993                         RNA_boolean_set(op->ptr, "compress", G.fileflags & G_FILE_COMPRESS);
1994                 else /* use userdef for new file */
1995                         RNA_boolean_set(op->ptr, "compress", U.flag & USER_FILECOMPRESS);
1996         }
1997 }
1998
1999 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2000 {
2001         char name[FILE_MAX];
2002
2003         save_set_compress(op);
2004         
2005         /* if not saved before, get the name of the most recently used .blend file */
2006         if (G.main->name[0] == 0 && G.recent_files.first) {
2007                 struct RecentFile *recent = G.recent_files.first;
2008                 BLI_strncpy(name, recent->filepath, FILE_MAX);
2009         }
2010         else
2011                 BLI_strncpy(name, G.main->name, FILE_MAX);
2012         
2013         untitled(name);
2014         RNA_string_set(op->ptr, "filepath", name);
2015         
2016         WM_event_add_fileselect(C, op);
2017
2018         return OPERATOR_RUNNING_MODAL;
2019 }
2020
2021 /* function used for WM_OT_save_mainfile too */
2022 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2023 {
2024         char path[FILE_MAX];
2025         int fileflags;
2026         int copy = 0;
2027
2028         save_set_compress(op);
2029         
2030         if (RNA_struct_property_is_set(op->ptr, "filepath"))
2031                 RNA_string_get(op->ptr, "filepath", path);
2032         else {
2033                 BLI_strncpy(path, G.main->name, FILE_MAX);
2034                 untitled(path);
2035         }
2036
2037         if (RNA_struct_property_is_set(op->ptr, "copy"))
2038                 copy = RNA_boolean_get(op->ptr, "copy");
2039         
2040         fileflags = G.fileflags;
2041
2042         /* set compression flag */
2043         if (RNA_boolean_get(op->ptr, "compress")) fileflags |=  G_FILE_COMPRESS;
2044         else fileflags &= ~G_FILE_COMPRESS;
2045         if (RNA_boolean_get(op->ptr, "relative_remap")) fileflags |=  G_FILE_RELATIVE_REMAP;
2046         else fileflags &= ~G_FILE_RELATIVE_REMAP;
2047 #ifdef USE_BMESH_SAVE_AS_COMPAT
2048         /* property only exists for 'Save As' */
2049         if (RNA_struct_find_property(op->ptr, "use_mesh_compat")) {
2050                 if (RNA_boolean_get(op->ptr, "use_mesh_compat")) fileflags |=  G_FILE_MESH_COMPAT;
2051                 else fileflags &= ~G_FILE_MESH_COMPAT;
2052         }
2053         else {
2054                 fileflags &= ~G_FILE_MESH_COMPAT;
2055         }
2056 #endif
2057
2058         if (WM_file_write(C, path, fileflags, op->reports, copy) != 0)
2059                 return OPERATOR_CANCELLED;
2060
2061         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2062
2063         return OPERATOR_FINISHED;
2064 }
2065
2066 /* function used for WM_OT_save_mainfile too */
2067 static int blend_save_check(bContext *UNUSED(C), wmOperator *op)
2068 {
2069         char filepath[FILE_MAX];
2070         RNA_string_get(op->ptr, "filepath", filepath);
2071         if (!BLO_has_bfile_extension(filepath)) {
2072                 /* some users would prefer BLI_replace_extension(),
2073                  * we keep getting knit-picking bug reports about this - campbell */
2074                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
2075                 RNA_string_set(op->ptr, "filepath", filepath);
2076                 return TRUE;
2077         }
2078         return FALSE;
2079 }
2080
2081 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
2082 {
2083         ot->name = "Save As Blender File";
2084         ot->idname = "WM_OT_save_as_mainfile";
2085         ot->description = "Save the current file in the desired location";
2086         
2087         ot->invoke = wm_save_as_mainfile_invoke;
2088         ot->exec = wm_save_as_mainfile_exec;
2089         ot->check = blend_save_check;
2090         /* ommit window poll so this can work in background mode */
2091
2092         WM_operator_properties_filesel(ot, FOLDERFILE | BLENDERFILE, FILE_BLENDER, FILE_SAVE,
2093                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
2094         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2095         RNA_def_boolean(ot->srna, "relative_remap", 1, "Remap Relative",
2096                         "Remap relative paths when saving in a different directory");
2097         RNA_def_boolean(ot->srna, "copy", 0, "Save Copy",
2098                         "Save a copy of the actual working state but does not make saved file active");
2099 #ifdef USE_BMESH_SAVE_AS_COMPAT
2100         RNA_def_boolean(ot->srna, "use_mesh_compat", 0, "Legacy Mesh Format",
2101                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
2102                         "be lost (no implicit triangulation)");
2103 #endif
2104 }
2105
2106 /* *************** save file directly ******** */
2107
2108 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2109 {
2110         char name[FILE_MAX];
2111         int check_existing = 1;
2112         int ret;
2113         
2114         /* cancel if no active window */
2115         if (CTX_wm_window(C) == NULL)
2116                 return OPERATOR_CANCELLED;
2117
2118         save_set_compress(op);
2119
2120         /* if not saved before, get the name of the most recently used .blend file */
2121         if (G.main->name[0] == 0 && G.recent_files.first) {
2122                 struct RecentFile *recent = G.recent_files.first;
2123                 BLI_strncpy(name, recent->filepath, FILE_MAX);
2124         }
2125         else
2126                 BLI_strncpy(name, G.main->name, FILE_MAX);
2127
2128         untitled(name);
2129         
2130         RNA_string_set(op->ptr, "filepath", name);
2131         
2132         if (RNA_struct_find_property(op->ptr, "check_existing"))
2133                 if (RNA_boolean_get(op->ptr, "check_existing") == 0)
2134                         check_existing = 0;
2135         
2136         if (G.save_over) {
2137                 if (check_existing && BLI_exists(name)) {
2138                         uiPupMenuSaveOver(C, op, name);
2139                         ret = OPERATOR_RUNNING_MODAL;
2140                 }
2141                 else {
2142                         ret = wm_save_as_mainfile_exec(C, op);
2143                 }
2144         }
2145         else {
2146                 WM_event_add_fileselect(C, op);
2147                 ret = OPERATOR_RUNNING_MODAL;
2148         }
2149         
2150         return ret;
2151 }
2152
2153 static void WM_OT_save_mainfile(wmOperatorType *ot)
2154 {
2155         ot->name = "Save Blender File";
2156         ot->idname = "WM_OT_save_mainfile";
2157         ot->description = "Save the current Blender file";
2158         
2159         ot->invoke = wm_save_mainfile_invoke;
2160         ot->exec = wm_save_as_mainfile_exec;
2161         ot->check = blend_save_check;
2162         /* ommit window poll so this can work in background mode */
2163         
2164         WM_operator_properties_filesel(ot, FOLDERFILE | BLENDERFILE, FILE_BLENDER, FILE_SAVE,
2165                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
2166         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2167         RNA_def_boolean(ot->srna, "relative_remap", 0, "Remap Relative", "Remap relative paths when saving in a different directory");
2168 }
2169
2170 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2171 {
2172         ot->name = "Toggle Fullscreen";
2173         ot->idname = "WM_OT_window_fullscreen_toggle";
2174         ot->description = "Toggle the current window fullscreen";
2175
2176         ot->exec = wm_window_fullscreen_toggle_exec;
2177         ot->poll = WM_operator_winactive;
2178 }
2179
2180 static int wm_exit_blender_op(bContext *C, wmOperator *op)
2181 {
2182         WM_operator_free(op);
2183         
2184         WM_exit(C);     
2185         
2186         return OPERATOR_FINISHED;
2187 }
2188
2189 static void WM_OT_quit_blender(wmOperatorType *ot)
2190 {
2191         ot->name = "Quit Blender";
2192         ot->idname = "WM_OT_quit_blender";
2193         ot->description = "Quit Blender";
2194
2195         ot->invoke = WM_operator_confirm;
2196         ot->exec = wm_exit_blender_op;
2197         ot->poll = WM_operator_winactive;
2198 }
2199
2200 /* *********************** */
2201
2202 #if defined(WIN32)
2203
2204 static int wm_console_toggle_op(bContext *UNUSED(C), wmOperator *UNUSED(op))
2205 {
2206         GHOST_toggleConsole(2);
2207         return OPERATOR_FINISHED;
2208 }
2209
2210 static void WM_OT_console_toggle(wmOperatorType *ot)
2211 {
2212         /* XXX Have to mark these for xgettext, as under linux they do not exists...
2213          *     And even worth, have to give the context as text, as xgettext doesn't expand macros. :( */
2214         ot->name = CTX_N_("Operator" /* BLF_I18NCONTEXT_OPERATOR_DEFAULT */, "Toggle System Console");
2215         ot->idname = "WM_OT_console_toggle";
2216         ot->description = N_("Toggle System Console");
2217         
2218         ot->exec = wm_console_toggle_op;
2219         ot->poll = WM_operator_winactive;
2220 }
2221
2222 #endif
2223
2224 /* ************ default paint cursors, draw always around cursor *********** */
2225 /*
2226  * - returns handler to free
2227  * - poll(bContext): returns 1 if draw should happen
2228  * - draw(bContext): drawing callback for paint cursor
2229  */
2230
2231 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2232                                wmPaintCursorDraw draw, void *customdata)
2233 {
2234         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2235         
2236         BLI_addtail(&wm->paintcursors, pc);
2237         
2238         pc->customdata = customdata;
2239         pc->poll = poll;
2240         pc->draw = draw;
2241         
2242         return pc;
2243 }
2244
2245 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2246 {
2247         wmPaintCursor *pc;
2248         
2249         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
2250                 if (pc == (wmPaintCursor *)handle) {
2251                         BLI_remlink(&wm->paintcursors, pc);
2252                         MEM_freeN(pc);
2253                         return;
2254                 }
2255         }
2256 }
2257
2258 /* ************ window gesture operator-callback definitions ************** */
2259 /*
2260  * These are default callbacks for use in operators requiring gesture input
2261  */
2262
2263 /* **************** Border gesture *************** */
2264
2265 /* Border gesture has two types:
2266  * 1) WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border
2267  * 2) WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends
2268  *
2269  * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
2270  */
2271
2272 static int border_apply_rect(wmOperator *op)
2273 {
2274         wmGesture *gesture = op->customdata;
2275         rcti *rect = gesture->customdata;
2276         
2277         if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
2278                 return 0;
2279
2280         
2281         /* operator arguments and storage. */
2282         RNA_int_set(op->ptr, "xmin", MIN2(rect->xmin, rect->xmax));
2283         RNA_int_set(op->ptr, "ymin", MIN2(rect->ymin, rect->ymax));
2284         RNA_int_set(op->ptr, "xmax", MAX2(rect->xmin, rect->xmax));
2285         RNA_int_set(op->ptr, "ymax", MAX2(rect->ymin, rect->ymax));
2286
2287         return 1;
2288 }
2289
2290 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
2291 {
2292         if (!border_apply_rect(op))
2293                 return 0;
2294         
2295         /* XXX weak; border should be configured for this without reading event types */
2296         if (RNA_struct_find_property(op->ptr, "gesture_mode") )
2297                 RNA_int_set(op->ptr, "gesture_mode", gesture_mode);
2298
2299         op->type->exec(C, op);
2300         return 1;
2301 }
2302
2303 static void wm_gesture_end(bContext *C, wmOperator *op)
2304 {
2305         wmGesture *gesture = op->customdata;
2306         
2307         WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2308         op->customdata = NULL;
2309
2310         ED_area_tag_redraw(CTX_wm_area(C));
2311         
2312         if (RNA_struct_find_property(op->ptr, "cursor") )
2313                 WM_cursor_restore(CTX_wm_window(C));
2314 }
2315
2316 int WM_border_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
2317 {
2318         if (ISTWEAK(event->type))
2319                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
2320         else
2321                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
2322
2323         /* add modal handler */
2324         WM_event_add_modal_handler(C, op);
2325         
2326         wm_gesture_tag_redraw(C);
2327
2328         return OPERATOR_RUNNING_MODAL;
2329 }
2330
2331 int WM_border_select_modal(bContext *C, wmOperator *op, wmEvent *event)
2332 {
2333         wmGesture *gesture = op->customdata;
2334         rcti *rect = gesture->customdata;
2335         int sx, sy;
2336         
2337         if (event->type == MOUSEMOVE) {
2338                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2339
2340                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2341                         rect->xmin = rect->xmax = event->x - sx;
2342                         rect->ymin = rect->ymax = event->y - sy;
2343                 }
2344                 else {
2345                         rect->xmax = event->x - sx;
2346                         rect->ymax = event->y - sy;
2347                 }
2348                 border_apply_rect(op);
2349
2350                 wm_gesture_tag_redraw(C);
2351         }
2352         else if (event->type == EVT_MODAL_MAP) {
2353                 switch (event->val) {
2354                         case GESTURE_MODAL_BEGIN:
2355                                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
2356                                         gesture->mode = 1;
2357                                         wm_gesture_tag_redraw(C);
2358                                 }
2359                                 break;
2360                         case GESTURE_MODAL_SELECT:
2361                         case GESTURE_MODAL_DESELECT:
2362                         case GESTURE_MODAL_IN:
2363                         case GESTURE_MODAL_OUT:
2364                                 if (border_apply(C, op, event->val)) {
2365                                         wm_gesture_end(C, op);
2366                                         return OPERATOR_FINISHED;
2367                                 }
2368                                 wm_gesture_end(C, op);
2369                                 return OPERATOR_CANCELLED;
2370                                 break;
2371
2372                         case GESTURE_MODAL_CANCEL:
2373                                 wm_gesture_end(C, op);
2374                                 return OPERATOR_CANCELLED;
2375                 }
2376
2377         }
2378 //      /* Allow view navigation??? */
2379 //      else {
2380 //              return OPERATOR_PASS_THROUGH;
2381 //      }
2382
2383         return OPERATOR_RUNNING_MODAL;
2384 }
2385
2386 int WM_border_select_cancel(bContext *C, wmOperator *op)
2387 {
2388         wm_gesture_end(C, op);
2389
2390         return OPERATOR_CANCELLED;
2391 }
2392
2393 /* **************** circle gesture *************** */
2394 /* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
2395
2396 #ifdef GESTURE_MEMORY
2397 int circle_select_size = 25; /* XXX - need some operator memory thing! */
2398 #endif
2399
2400 int WM_gesture_circle_invoke(bContext *C, wmOperator *op, wmEvent *event)
2401 {
2402         op->customdata = WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
2403         
2404         /* add modal handler */
2405         WM_event_add_modal_handler(C, op);
2406         
2407         wm_gesture_tag_redraw(C);
2408         
2409         return OPERATOR_RUNNING_MODAL;
2410 }
2411
2412 static void gesture_circle_apply(bContext *C, wmOperator *op)
2413 {
2414         wmGesture *gesture = op->customdata;
2415         rcti *rect = gesture->customdata;
2416         
2417         if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_NOP)
2418                 return;
2419
2420         /* operator arguments and storage. */
2421         RNA_int_set(op->ptr, "x", rect->xmin);
2422         RNA_int_set(op->ptr, "y", rect->ymin);
2423         RNA_int_set(op->ptr, "radius", rect->xmax);
2424         
2425         if (op->type->exec)
2426                 op->type->exec(C, op);
2427 #ifdef GESTURE_MEMORY
2428         circle_select_size = rect->xmax;
2429 #endif
2430 }
2431
2432 int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
2433 {
2434         wmGesture *gesture = op->customdata;
2435         rcti *rect = gesture->customdata;
2436         int sx, sy;
2437
2438         if (event->type == MOUSEMOVE) {
2439                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2440
2441                 rect->xmin = event->x - sx;
2442                 rect->ymin = event->y - sy;
2443
2444                 wm_gesture_tag_redraw(C);
2445
2446                 if (gesture->mode)
2447                         gesture_circle_apply(C, op);
2448         }
2449         else if (event->type == EVT_MODAL_MAP) {
2450                 switch (event->val) {
2451                         case GESTURE_MODAL_CIRCLE_ADD:
2452                                 rect->xmax += 2 + rect->xmax / 10;
2453                                 wm_gesture_tag_redraw(C);
2454                                 break;
2455                         case GESTURE_MODAL_CIRCLE_SUB:
2456                                 rect->xmax -= 2 + rect->xmax / 10;
2457                                 if (rect->xmax < 1) rect->xmax = 1;
2458                                 wm_gesture_tag_redraw(C);
2459                                 break;
2460                         case GESTURE_MODAL_SELECT:
2461                         case GESTURE_MODAL_DESELECT:
2462                         case GESTURE_MODAL_NOP:
2463                                 if (RNA_struct_find_property(op->ptr, "gesture_mode"))
2464                                         RNA_int_set(op->ptr, "gesture_mode", event->val);
2465
2466                                 if (event->val != GESTURE_MODAL_NOP) {
2467                                         /* apply first click */
2468                                         gesture_circle_apply(C, op);
2469                                         gesture->mode = 1;
2470                                         wm_gesture_tag_redraw(C);
2471                                 }
2472                                 break;
2473
2474                         case GESTURE_MODAL_CANCEL:
2475                         case GESTURE_MODAL_CONFIRM:
2476                                 wm_gesture_end(C, op);
2477                                 return OPERATOR_FINISHED; /* use finish or we don't get an undo */
2478                 }
2479         }
2480 //      /* Allow view navigation??? */
2481 //      else {
2482 //              return OPERATOR_PASS_THROUGH;
2483 //      }
2484
2485         return OPERATOR_RUNNING_MODAL;
2486 }
2487
2488 int WM_gesture_circle_cancel(bContext *C, wmOperator *op)
2489 {
2490         wm_gesture_end(C, op);
2491
2492         return OPERATOR_CANCELLED;
2493 }
2494
2495 #if 0
2496 /* template to copy from */
2497 void WM_OT_circle_gesture(wmOperatorType *ot)
2498 {
2499         ot->name = "Circle Gesture";
2500         ot->idname = "WM_OT_circle_gesture";
2501         ot->description = "Enter rotate mode with a circular gesture";
2502         
2503         ot->invoke = WM_gesture_circle_invoke;
2504         ot->modal = WM_gesture_circle_modal;
2505         
2506         ot->poll = WM_operator_winactive;
2507         
2508         RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
2509         RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
2510         RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
2511
2512 }
2513 #endif
2514
2515 /* **************** Tweak gesture *************** */
2516
2517 static void tweak_gesture_modal(bContext *C, wmEvent *event)
2518 {
2519         wmWindow *window = CTX_wm_window(C);
2520         wmGesture *gesture = window->tweak;
2521         rcti *rect = gesture->customdata;
2522         int sx, sy, val;
2523         
2524         switch (event->type) {
2525                 case MOUSEMOVE:
2526                 case INBETWEEN_MOUSEMOVE:
2527                         
2528                         wm_subwindow_getorigin(window, gesture->swinid, &sx, &sy);
2529                         
2530                         rect->xmax = event->x - sx;
2531                         rect->ymax = event->y - sy;
2532                         
2533                         if ((val = wm_gesture_evaluate(gesture))) {
2534                                 wmEvent tevent;
2535
2536                                 tevent = *(window->eventstate);
2537                                 if (gesture->event_type == LEFTMOUSE)
2538                                         tevent.type = EVT_TWEAK_L;
2539                                 else if (gesture->event_type == RIGHTMOUSE)
2540                                         tevent.type = EVT_TWEAK_R;
2541                                 else
2542                                         tevent.type = EVT_TWEAK_M;
2543                                 tevent.val = val;
2544                                 /* mouse coords! */
2545                                 wm_event_add(window, &tevent);
2546                                 
2547                                 WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
2548                         }
2549                         
2550                         break;
2551                         
2552                 case LEFTMOUSE:
2553                 case RIGHTMOUSE:
2554                 case MIDDLEMOUSE:
2555                         if (gesture->event_type == event->type) {
2556                                 WM_gesture_end(C, gesture);
2557
2558                                 /* when tweak fails we should give the other keymap entries a chance */
2559                                 event->val = KM_RELEASE;
2560                         }
2561                         break;
2562                 default:
2563                         if (!ISTIMER(event->type)) {
2564                                 WM_gesture_end(C, gesture);
2565                         }
2566                         break;
2567         }
2568 }
2569
2570 /* standard tweak, called after window handlers passed on event */
2571 void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
2572 {
2573         wmWindow *win = CTX_wm_window(C);
2574         
2575         if (win->tweak == NULL) {
2576                 if (CTX_wm_region(C)) {
2577                         if (event->val == KM_PRESS) {
2578                                 if (ELEM3(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE) )
2579                                         win->tweak = WM_gesture_new(C, event, WM_GESTURE_TWEAK);
2580                         }
2581                 }
2582         }
2583         else {
2584                 /* no tweaks if event was handled */
2585                 if ((action & WM_HANDLER_BREAK)) {
2586                         WM_gesture_end(C, win->tweak);
2587                 }
2588                 else
2589                         tweak_gesture_modal(C, event);
2590         }
2591 }
2592
2593 /* *********************** lasso gesture ****************** */
2594
2595 int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, wmEvent *event)
2596 {
2597         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LASSO);
2598         
2599         /* add modal handler */
2600         WM_event_add_modal_handler(C, op);
2601         
2602         wm_gesture_tag_redraw(C);
2603         
2604         if (RNA_struct_find_property(op->ptr, "cursor") )
2605                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2606         
2607         return OPERATOR_RUNNING_MODAL;
2608 }
2609
2610 int WM_gesture_lines_invoke(bContext *C, wmOperator *op, wmEvent *event)
2611 {
2612         op->customdata = WM_gesture_new(C, event, WM_GESTURE_LINES);
2613         
2614         /* add modal handler */
2615         WM_event_add_modal_handler(C, op);
2616         
2617         wm_gesture_tag_redraw(C);
2618         
2619         if (RNA_struct_find_property(op->ptr, "cursor") )
2620                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2621         
2622         return OPERATOR_RUNNING_MODAL;
2623 }
2624
2625
2626 static void gesture_lasso_apply(bContext *C, wmOperator *op)
2627 {
2628         wmGesture *gesture = op->customdata;
2629         PointerRNA itemptr;
2630         float loc[2];
2631         int i;
2632         short *lasso = gesture->customdata;
2633         
2634         /* operator storage as path. */
2635
2636         RNA_collection_clear(op->ptr, "path");
2637         for (i = 0; i < gesture->points; i++, lasso += 2) {
2638                 loc[0] = lasso[0];
2639                 loc[1] = lasso[1];
2640                 RNA_collection_add(op->ptr, "path", &itemptr);
2641                 RNA_float_set_array(&itemptr, "loc", loc);
2642         }
2643         
2644         wm_gesture_end(C, op);
2645                 
2646         if (op->type->exec)
2647                 op->type->exec(C, op);
2648 }
2649
2650 int WM_gesture_lasso_modal(bContext *C, wmOperator *op, wmEvent *event)
2651 {
2652         wmGesture *gesture = op->customdata;
2653         int sx, sy;
2654         
2655         switch (event->type) {
2656                 case MOUSEMOVE:
2657                 case INBETWEEN_MOUSEMOVE:
2658                         
2659                         wm_gesture_tag_redraw(C);
2660                         
2661                         wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2662
2663                         if (gesture->points == gesture->size) {
2664                                 short *old_lasso = gesture->customdata;
2665                                 gesture->customdata = MEM_callocN(2 * sizeof(short) * (gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
2666                                 memcpy(gesture->customdata, old_lasso, 2 * sizeof(short) * gesture->size);
2667                                 gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
2668                                 MEM_freeN(old_lasso);
2669                                 // printf("realloc\n");
2670                         }
2671
2672                         {
2673                                 int x, y;
2674                                 short *lasso = gesture->customdata;
2675                                 
2676                                 lasso += (2 * gesture->points - 2);
2677                                 x = (event->x - sx - lasso[0]);
2678                                 y = (event->y - sy - lasso[1]);
2679                                 
2680                                 /* make a simple distance check to get a smoother lasso
2681                                  * add only when at least 2 pixels between this and previous location */
2682                                 if ((x * x + y * y) > 4) {
2683                                         lasso += 2;
2684                                         lasso[0] = event->x - sx;
2685                                         lasso[1] = event->y - sy;
2686                                         gesture->points++;
2687                                 }
2688                         }
2689                         break;
2690                         
2691                 case LEFTMOUSE:
2692                 case MIDDLEMOUSE:
2693                 case RIGHTMOUSE:
2694                         if (event->val == KM_RELEASE) {   /* key release */
2695                                 gesture_lasso_apply(C, op);
2696                                 return OPERATOR_FINISHED;
2697                         }
2698                         break;
2699                 case ESCKEY:
2700                         wm_gesture_end(C, op);
2701                         return OPERATOR_CANCELLED;
2702         }
2703         return OPERATOR_RUNNING_MODAL;
2704 }
2705
2706 int WM_gesture_lines_modal(bContext *C, wmOperator *op, wmEvent *event)
2707 {
2708         return WM_gesture_lasso_modal(C, op, event);
2709 }
2710
2711 int WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
2712 {
2713         wm_gesture_end(C, op);
2714
2715         return OPERATOR_CANCELLED;
2716 }
2717
2718 int WM_gesture_lines_cancel(bContext *C, wmOperator *op)
2719 {
2720         wm_gesture_end(C, op);
2721
2722         return OPERATOR_CANCELLED;
2723 }
2724
2725 /**
2726  * helper function, we may want to add options for conversion to view space
2727  *
2728  * caller must free.
2729  */
2730 int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
2731 {
2732         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
2733         int (*mcords)[2] = NULL;
2734         BLI_assert(prop != NULL);
2735
2736         if (prop) {
2737                 const int len = RNA_property_collection_length(op->ptr, prop);
2738
2739                 if (len) {
2740                         int i = 0;
2741                         mcords = MEM_mallocN(sizeof(int) * 2 * len, __func__);
2742
2743                         RNA_PROP_BEGIN(op->ptr, itemptr, prop)
2744                         {
2745                                 float loc[2];
2746
2747                                 RNA_float_get_array(&itemptr, "loc", loc);
2748                                 mcords[i][0] = (int)loc[0];
2749                                 mcords[i][1] = (int)loc[1];
2750                                 i++;
2751                         }
2752                         RNA_PROP_END;
2753                 }
2754                 *mcords_tot = len;
2755         }
2756         else {
2757                 *mcords_tot = 0;
2758         }
2759
2760         return mcords;
2761 }
2762
2763 #if 0
2764 /* template to copy from */
2765
2766 static int gesture_lasso_exec(bContext *C, wmOperator *op)
2767 {
2768         RNA_BEGIN(op->ptr, itemptr, "path")
2769         {
2770                 float loc[2];
2771                 
2772                 RNA_float_get_array(&itemptr, "loc", loc);
2773                 printf("Location: %f %f\n", loc[0], loc[1]);
2774         }
2775         RNA_END;
2776         
2777         return OPERATOR_FINISHED;
2778 }
2779
2780 void WM_OT_lasso_gesture(wmOperatorType *ot)
2781 {
2782         PropertyRNA *prop;
2783         
2784         ot->name = "Lasso Gesture";
2785         ot->idname = "WM_OT_lasso_gesture";
2786         ot->description = "Select objects within the lasso as you move the pointer";
2787         
2788         ot->invoke = WM_gesture_lasso_invoke;
2789         ot->modal = WM_gesture_lasso_modal;
2790         ot->exec = gesture_lasso_exec;
2791         
2792         ot->poll = WM_operator_winactive;
2793         
2794         prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2795         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2796 }
2797 #endif
2798
2799 /* *********************** straight line gesture ****************** */
2800
2801 static int straightline_apply(bContext *C, wmOperator *op)
2802 {
2803         wmGesture *gesture = op->customdata;
2804         rcti *rect = gesture->customdata;
2805         
2806         if (rect->xmin == rect->xmax && rect->ymin == rect->ymax)
2807                 return 0;
2808         
2809         /* operator arguments and storage. */
2810         RNA_int_set(op->ptr, "xstart", rect->xmin);
2811         RNA_int_set(op->ptr, "ystart", rect->ymin);
2812         RNA_int_set(op->ptr, "xend", rect->xmax);
2813         RNA_int_set(op->ptr, "yend", rect->ymax);
2814
2815         if (op->type->exec)
2816                 op->type->exec(C, op);
2817         
2818         return 1;
2819 }
2820
2821
2822 int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, wmEvent *event)
2823 {
2824         op->customdata = WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
2825         
2826         /* add modal handler */
2827         WM_event_add_modal_handler(C, op);
2828         
2829         wm_gesture_tag_redraw(C);
2830         
2831         if (RNA_struct_find_property(op->ptr, "cursor") )
2832                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2833                 
2834         return OPERATOR_RUNNING_MODAL;
2835 }
2836
2837 int WM_gesture_straightline_modal(bContext *C, wmOperator *op, wmEvent *event)
2838 {
2839         wmGesture *gesture = op->customdata;
2840         rcti *rect = gesture->customdata;
2841         int sx, sy;
2842         
2843         if (event->type == MOUSEMOVE) {
2844                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2845                 
2846                 if (gesture->mode == 0) {
2847                         rect->xmin = rect->xmax = event->x - sx;
2848                         rect->ymin = rect->ymax = event->y - sy;
2849                 }
2850                 else {
2851                         rect->xmax = event->x - sx;
2852                         rect->ymax = event->y - sy;
2853                         straightline_apply(C, op);
2854                 }
2855                 
2856                 wm_gesture_tag_redraw(C);
2857         }
2858         else if (event->type == EVT_MODAL_MAP) {
2859                 switch (event->val) {
2860                         case GESTURE_MODAL_BEGIN:
2861                                 if (gesture->mode == 0) {
2862                                         gesture->mode = 1;
2863                                         wm_gesture_tag_redraw(C);
2864                                 }
2865                                 break;
2866                         case GESTURE_MODAL_SELECT:
2867                                 if (straightline_apply(C, op)) {
2868                                         wm_gesture_end(C, op);
2869                                         return OPERATOR_FINISHED;
2870                                 }
2871                                 wm_gesture_end(C, op);
2872                                 return OPERATOR_CANCELLED;
2873                                 break;
2874                                 
2875                         case GESTURE_MODAL_CANCEL:
2876                                 wm_gesture_end(C, op);
2877                                 return OPERATOR_CANCELLED;
2878                 }
2879                 
2880         }
2881
2882         return OPERATOR_RUNNING_MODAL;
2883 }
2884
2885 int WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
2886 {
2887         wm_gesture_end(C, op);
2888
2889         return OPERATOR_CANCELLED;
2890 }
2891
2892 #if 0
2893 /* template to copy from */
2894 void WM_OT_straightline_gesture(wmOperatorType *ot)
2895 {
2896         PropertyRNA *prop;
2897         
2898         ot->name = "Straight Line Gesture";
2899         ot->idname = "WM_OT_straightline_gesture";
2900         ot->description = "Draw a straight line as you move the pointer";
2901         
2902         ot->invoke = WM_gesture_straightline_invoke;
2903         ot->modal = WM_gesture_straightline_modal;
2904         ot->exec = gesture_straightline_exec;
2905         
2906         ot->poll = WM_operator_winactive;
2907         
2908         WM_operator_properties_gesture_straightline(ot, 0);
2909 }
2910 #endif
2911
2912 /* *********************** radial control ****************** */
2913
2914 static const int WM_RADIAL_CONTROL_DISPLAY_SIZE = 200;
2915
2916 typedef struct {
2917         PropertyType type;
2918         PropertySubType subtype;
2919         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2920         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2921         StructRNA *image_id_srna;
2922         float initial_value, current_value, min_value, max_value;
2923         int initial_mouse[2];
2924         unsigned int gltex;
2925         ListBase orig_paintcursors;
2926         void *cursor;
2927 } RadialControl;
2928
2929 static void radial_control_set_initial_mouse(RadialControl *rc, wmEvent *event)
2930 {
2931         float d[2] = {0, 0};
2932         float zoom[2] = {1, 1};
2933
2934         rc->initial_mouse[0] = event->x;
2935         rc->initial_mouse[1] = event->y;
2936
2937         switch (rc->subtype) {
2938                 case PROP_DISTANCE:
2939                         d[0] = rc->initial_value;
2940                         break;
2941                 case PROP_FACTOR:
2942                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * (1 - rc->initial_value);
2943                         break;
2944                 case PROP_ANGLE:
2945                         d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cos(rc->initial_value);
2946                         d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sin(rc->initial_value);
2947                         break;
2948                 default:
2949                         return;
2950         }
2951
2952         if (rc->zoom_prop) {
2953                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2954                 d[0] *= zoom[0];
2955                 d[1] *= zoom[1];
2956         }
2957
2958         rc->initial_mouse[0] -= d[0];
2959         rc->initial_mouse[1] -= d[1];
2960 }
2961
2962 static void radial_control_set_tex(RadialControl *rc)
2963 {
2964         ImBuf *ibuf;
2965
2966         switch (RNA_type_to_ID_code(rc->image_id_ptr.type)) {
2967                 case ID_BR:
2968                         if ((ibuf = BKE_brush_gen_radial_control_imbuf(rc->image_id_ptr.data))) {
2969                                 glGenTextures(1, &rc->gltex);
2970                                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2971                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ibuf->x, ibuf->y, 0,
2972                                              GL_ALPHA, GL_FLOAT, ibuf->rect_float);
2973                                 MEM_freeN(ibuf->rect_float);
2974                                 MEM_freeN(ibuf);
2975                         }
2976                         break;
2977                 default:
2978                         break;
2979         }
2980 }
2981
2982 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
2983 {
2984         float col[3] = {0, 0, 0};
2985         float rot;
2986
2987         /* set fill color */
2988         if (rc->fill_col_prop)
2989                 RNA_property_float_get_array(&rc->fill_col_ptr, rc->fill_col_prop, col);
2990         glColor4f(col[0], col[1], col[2], alpha);
2991
2992         if (rc->gltex) {
2993                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2994
2995                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2996                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2997
2998                 /* set up rotation if available */
2999                 if (rc->rot_prop) {
3000                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
3001                         glPushMatrix();
3002                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
3003                 }
3004
3005                 /* draw textured quad */
3006                 glEnable(GL_TEXTURE_2D);
3007                 glBegin(GL_QUADS);
3008                 glTexCoord2f(0, 0);
3009                 glVertex2f(-radius, -radius);
3010                 glTexCoord2f(1, 0);
3011                 glVertex2f(radius, -radius);
3012                 glTexCoord2f(1, 1);
3013                 glVertex2f(radius, radius);
3014                 glTexCoord2f(0, 1);
3015                 glVertex2f(-radius, radius);
3016                 glEnd();
3017                 glDisable(GL_TEXTURE_2D);
3018
3019                 /* undo rotation */
3020                 if (rc->rot_prop)
3021                         glPopMatrix();
3022         }
3023         else {
3024                 /* flat color if no texture available */
3025                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
3026         }
3027 }
3028
3029 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
3030 {
3031         RadialControl *rc = customdata;
3032         ARegion *ar = CTX_wm_region(C);
3033         float r1 = 0.0f, r2 = 0.0f, tex_radius, alpha;
3034         float zoom[2], col[3] = {1, 1, 1};
3035
3036         switch (rc->subtype) {
3037                 case PROP_DISTANCE:
3038                         r1 = rc->current_value;
3039                         r2 = rc->initial_value;
3040                         tex_radius = r1;
3041                         alpha = 0.75;
3042                         break;
3043                 case PROP_FACTOR:
3044                         r1 = (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_SIZE;
3045                         r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
3046                         alpha = rc->current_value / 2.0f + 0.5f;
3047                         break;
3048                 case PROP_ANGLE:
3049                         r1 = r2 = tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE;
3050                         alpha = 0.75;
3051                         break;
3052                 default:
3053                         tex_radius = WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
3054                         alpha = 0.75;
3055                         break;
3056         }
3057
3058         /* Keep cursor in the original place */
3059         x = rc->initial_mouse[0] - ar->winrct.xmin;
3060         y = rc->initial_mouse[1] - ar->winrct.ymin;
3061         glTranslatef((float)x, (float)y, 0.0f);
3062
3063         glEnable(GL_BLEND);
3064         glEnable(GL_LINE_SMOOTH);
3065
3066         /* apply zoom if available */
3067         if (rc->zoom_prop) {
3068                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3069                 glScalef(zoom[0], zoom[1], 1);
3070         }
3071
3072         /* draw rotated texture */
3073         radial_control_paint_tex(rc, tex_radius, alpha);
3074
3075         /* set line color */
3076         if (rc->col_prop)
3077                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
3078         glColor4f(col[0], col[1], col[2], 0.5);
3079
3080         if (rc->subtype == PROP_ANGLE) {
3081                 glPushMatrix();
3082                 /* draw original angle line */
3083                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
3084                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3085                 /* draw new angle line */
3086                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
3087                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3088                 glPopMatrix();
3089         }
3090
3091         /* draw circles on top */
3092         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r1, 40);
3093         glutil_draw_lined_arc(0.0, (float)(M_PI * 2.0), r2, 40);
3094
3095         glDisable(GL_BLEND);
3096         glDisable(GL_LINE_SMOOTH);
3097 }
3098
3099 typedef enum {
3100         RC_PROP_ALLOW_MISSING = 1,
3101         RC_PROP_REQUIRE_FLOAT = 2,
3102         RC_PROP_REQUIRE_BOOL = 4,
3103 } RCPropFlags;
3104
3105 /* attempt to retrieve the rna pointer/property from an rna path;
3106  * returns 0 for failure, 1 for success, and also 1 if property is not
3107  * set */
3108 static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
3109                                    const char *name, PointerRNA *r_ptr,
3110                                    PropertyRNA **r_prop, int req_length, RCPropFlags flags)
3111 {
3112         PropertyRNA *unused_prop;
3113         int len;
3114         char *str;
3115
3116         /* check flags */
3117         if ((flags & RC_PROP_REQUIRE_BOOL) && (flags & RC_PROP_REQUIRE_FLOAT)) {
3118                 BKE_reportf(op->reports, RPT_ERROR, "Property can't be both boolean and float");
3119                 return 0;
3120         }
3121
3122         /* get an rna string path from the operator's properties */
3123         if (!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
3124                 return 1;
3125
3126         if (str[0] == '\0') {
3127                 if (r_prop) *r_prop = NULL;
3128                 MEM_freeN(str);
3129                 return 1;
3130         }
3131
3132         if (!r_prop)
3133                 r_prop = &unused_prop;
3134
3135         /* get rna from path */
3136         if (!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
3137                 MEM_freeN(str);
3138                 if (flags & RC_PROP_ALLOW_MISSING)
3139                         return 1;
3140                 else {
3141                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't resolve path %s", name);
3142                         return 0;
3143                 }
3144         }
3145
3146         /* check property type */
3147         if (flags & (RC_PROP_REQUIRE_BOOL | RC_PROP_REQUIRE_FLOAT)) {
3148                 PropertyType prop_type = RNA_property_type(*r_prop);
3149
3150                 if (((flags & RC_PROP_REQUIRE_BOOL) && (prop_type != PROP_BOOLEAN)) ||
3151                     ((flags & RC_PROP_REQUIRE_FLOAT) && prop_type != PROP_FLOAT))
3152                 {
3153                         MEM_freeN(str);
3154                         BKE_reportf(op->reports, RPT_ERROR,
3155                                     "Property from path %s is not a float", name);
3156                         return 0;
3157                 }
3158         }
3159         
3160         /* check property's array length */
3161         if (*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
3162                 MEM_freeN(str);
3163                 BKE_reportf(op->reports, RPT_ERROR,
3164                             "Property from path %s has length %d instead of %d",
3165                             name, len, req_length);
3166                 return 0;
3167         }
3168
3169         /* success */
3170         MEM_freeN(str);
3171         return 1;
3172 }
3173
3174 /* initialize the rna pointers and properties using rna paths */
3175 static int radial_control_get_properties(bContext *C, wmOperator *op)
3176 {
3177         RadialControl *rc = op->customdata;
3178         PointerRNA ctx_ptr, use_secondary_ptr;
3179         PropertyRNA *use_secondary_prop;
3180         const char *data_path;
3181
3182         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
3183
3184         /* check if we use primary or secondary path */
3185         if (!radial_control_get_path(&ctx_ptr, op, "use_secondary",
3186                                      &use_secondary_ptr, &use_secondary_prop,
3187                                      0, (RC_PROP_ALLOW_MISSING |
3188                                          RC_PROP_REQUIRE_BOOL)))
3189         {
3190                 return 0;
3191         }
3192         else {
3193                 if (use_secondary_prop &&
3194                     RNA_property_boolean_get(&use_secondary_ptr, use_secondary_prop))
3195                 {
3196                         data_path = "data_path_secondary";
3197                 }
3198                 else {
3199                         data_path = "data_path_primary";
3200                 }
3201         }
3202
3203         if (!radial_control_get_path(&ctx_ptr, op, data_path, &rc->ptr, &rc->prop, 0, 0))
3204                 return 0;
3205
3206         /* data path is required */
3207         if (!rc->prop)
3208                 return 0;
3209         
3210         if (!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 0, RC_PROP_REQUIRE_FLOAT))
3211                 return 0;
3212         if (!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 3, RC_PROP_REQUIRE_FLOAT))
3213                 return 0;
3214         if (!radial_control_get_path(&ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 3, RC_PROP_REQUIRE_FLOAT))
3215                 return 0;
3216         
3217         /* slightly ugly; allow this property to not resolve
3218          * correctly. needed because 3d texture paint shares the same
3219          * keymap as 2d image paint */
3220         if (!radial_control_get_path(&ctx_ptr, op, "zoom_path",
3221                                      &rc->zoom_ptr, &rc->zoom_prop, 2,
3222                                      RC_PROP_REQUIRE_FLOAT | RC_PROP_ALLOW_MISSING))
3223         {
3224                 return 0;
3225         }
3226         
3227         if (!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0))
3228                 return 0;
3229         else if (rc->image_id_ptr.data) {
3230                 /* extra check, pointer must be to an ID */
3231                 if (!RNA_struct_is_ID(rc->image_id_ptr.type)) {
3232                         BKE_report(op->reports, RPT_ERROR,
3233                                    "Pointer from path image_id is not an ID");
3234                         return 0;
3235                 }
3236         }
3237
3238         return 1;
3239 }
3240
3241 static int radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
3242 {
3243         wmWindowManager *wm;
3244         RadialControl *rc;
3245         int min_value_int, max_value_int, step_int;
3246         float step_float, precision;
3247
3248         if (!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
3249                 return OPERATOR_CANCELLED;
3250
3251         if (!radial_control_get_properties(C, op)) {
3252                 MEM_freeN(rc);
3253                 return OPERATOR_CANCELLED;
3254         }
3255
3256         /* get type, initial, min, and max values of the property */
3257         switch ((rc->type = RNA_property_type(rc->prop))) {