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