NDOF related edits
[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 typedef struct wmOpPopUp
942 {
943         wmOperator *op;
944         int width;
945         int height;
946         int free_op;
947 } wmOpPopUp;
948
949 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
950 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
951 {
952         wmOpPopUp *data= arg1;
953         uiBlock *block= arg2;
954
955         WM_operator_call(C, data->op);
956
957         /* let execute handle freeing it */
958         //data->free_op= FALSE;
959         //data->op= NULL;
960
961         /* in this case, wm_operator_ui_popup_cancel wont run */
962         MEM_freeN(data);
963
964         uiPupBlockClose(C, block);
965 }
966
967 static void dialog_check_cb(bContext *C, void *op_ptr, void *UNUSED(arg))
968 {
969         wmOperator *op= op_ptr;
970         if(op->type->check) {
971                 if(op->type->check(C, op)) {
972                         /* refresh */
973                 }
974         }
975 }
976
977 /* Dialogs are popups that require user verification (click OK) before exec */
978 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
979 {
980         wmOpPopUp *data= userData;
981         wmOperator *op= data->op;
982         uiBlock *block;
983         uiLayout *layout;
984         uiStyle *style= U.uistyles.first;
985
986         block = uiBeginBlock(C, ar, "operator dialog", UI_EMBOSS);
987         uiBlockClearFlag(block, UI_BLOCK_LOOP);
988         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN|UI_BLOCK_RET_1|UI_BLOCK_MOVEMOUSE_QUIT);
989
990         layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
991         
992         uiBlockSetFunc(block, dialog_check_cb, op, NULL);
993
994         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
995         
996         /* clear so the OK button is left alone */
997         uiBlockSetFunc(block, NULL, NULL, NULL);
998
999         /* new column so as not to interfear with custom layouts [#26436] */
1000         {
1001                 uiBlock *col_block;
1002                 uiLayout *col;
1003                 uiBut *btn;
1004
1005                 col= uiLayoutColumn(layout, FALSE);
1006                 col_block= uiLayoutGetBlock(col);
1007                 /* Create OK button, the callback of which will execute op */
1008                 btn= uiDefBut(col_block, BUT, 0, "OK", 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1009                 uiButSetFunc(btn, dialog_exec_cb, data, col_block);
1010         }
1011
1012         /* center around the mouse */
1013         uiPopupBoundsBlock(block, 4, data->width/-2, data->height/2);
1014         uiEndBlock(C, block);
1015
1016         return block;
1017 }
1018
1019 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1020 {
1021         wmOpPopUp *data= userData;
1022         wmOperator *op= data->op;
1023         uiBlock *block;
1024         uiLayout *layout;
1025         uiStyle *style= U.uistyles.first;
1026
1027         block= uiBeginBlock(C, ar, "opui_popup", UI_EMBOSS);
1028         uiBlockClearFlag(block, UI_BLOCK_LOOP);
1029         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN|UI_BLOCK_RET_1|UI_BLOCK_MOVEMOUSE_QUIT);
1030
1031         layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, style);
1032
1033         /* since ui is defined the auto-layout args are not used */
1034         uiLayoutOperatorButs(C, layout, op, NULL, 'V', 0);
1035
1036         uiPopupBoundsBlock(block, 4, 0, 0);
1037         uiEndBlock(C, block);
1038
1039         return block;
1040 }
1041
1042 static void wm_operator_ui_popup_cancel(void *userData)
1043 {
1044         wmOpPopUp *data= userData;
1045         if(data->free_op && data->op) {
1046                 wmOperator *op= data->op;
1047                 WM_operator_free(op);
1048         }
1049
1050         MEM_freeN(data);
1051 }
1052
1053 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1054 {
1055         wmOpPopUp *data= MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1056         data->op= op;
1057         data->width= width;
1058         data->height= height;
1059         data->free_op= TRUE; /* if this runs and gets registered we may want not to free it */
1060         uiPupBlockEx(C, wm_operator_ui_create, wm_operator_ui_popup_cancel, data);
1061         return OPERATOR_RUNNING_MODAL;
1062 }
1063
1064 /* operator menu needs undo, for redo callback */
1065 int WM_operator_props_popup(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1066 {
1067         
1068         if((op->type->flag & OPTYPE_REGISTER)==0) {
1069                 BKE_reportf(op->reports, RPT_ERROR, "Operator '%s' does not have register enabled, incorrect invoke function.", op->type->idname);
1070                 return OPERATOR_CANCELLED;
1071         }
1072         
1073         ED_undo_push_op(C, op);
1074         wm_operator_register(C, op);
1075
1076         uiPupBlock(C, wm_block_create_redo, op);
1077
1078         return OPERATOR_RUNNING_MODAL;
1079 }
1080
1081 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1082 {
1083         wmOpPopUp *data= MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1084         
1085         data->op= op;
1086         data->width= width;
1087         data->height= height;
1088         data->free_op= TRUE; /* if this runs and gets registered we may want not to free it */
1089
1090         /* op is not executed until popup OK but is clicked */
1091         uiPupBlockEx(C, wm_block_dialog_create, wm_operator_ui_popup_cancel, data);
1092
1093         return OPERATOR_RUNNING_MODAL;
1094 }
1095
1096 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1097 {
1098         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1099         if((op->type->flag & OPTYPE_REGISTER)==0) {
1100                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s' does not have register enabled, incorrect invoke function.", op->type->idname);
1101                 return OPERATOR_CANCELLED;
1102         }
1103         if(op->type->poll && op->type->poll(C)==0) {
1104                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context.", op->type->idname);
1105                 return OPERATOR_CANCELLED;
1106         }
1107         
1108         uiPupBlock(C, wm_block_create_redo, op);
1109
1110         return OPERATOR_CANCELLED;
1111 }
1112
1113 /* ***************** Debug menu ************************* */
1114
1115 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1116 {
1117         G.rt= RNA_int_get(op->ptr, "debug_value");
1118         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1119         WM_event_add_notifier(C, NC_WINDOW, NULL);
1120
1121         return OPERATOR_FINISHED;       
1122 }
1123
1124 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1125 {
1126         RNA_int_set(op->ptr, "debug_value", G.rt);
1127         return WM_operator_props_dialog_popup(C, op, 9*UI_UNIT_X, UI_UNIT_Y);
1128 }
1129
1130 static void WM_OT_debug_menu(wmOperatorType *ot)
1131 {
1132         ot->name= "Debug Menu";
1133         ot->idname= "WM_OT_debug_menu";
1134         ot->description= "Open a popup to set the debug level";
1135         
1136         ot->invoke= wm_debug_menu_invoke;
1137         ot->exec= wm_debug_menu_exec;
1138         ot->poll= WM_operator_winactive;
1139         
1140         RNA_def_int(ot->srna, "debug_value", 0, -10000, 10000, "Debug Value", "", INT_MIN, INT_MAX);
1141 }
1142
1143
1144 /* ***************** Splash Screen ************************* */
1145
1146 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1147 {
1148         uiPupBlockClose(C, arg_block);
1149 }
1150
1151 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1152
1153 /* XXX: hack to refresh splash screen with updated prest menu name,
1154  * since popup blocks don't get regenerated like panels do */
1155 static void wm_block_splash_refreshmenu (bContext *UNUSED(C), void *UNUSED(arg_block), void *UNUSED(arg))
1156 {
1157         /* ugh, causes crashes in other buttons, disabling for now until 
1158          * a better fix
1159         uiPupBlockClose(C, arg_block);
1160         uiPupBlock(C, wm_block_create_splash, NULL);
1161           */
1162 }
1163
1164 static int wm_resource_check_prev(void)
1165 {
1166
1167         char *res= BLI_get_folder_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, TRUE);
1168
1169         // if(res) printf("USER: %s\n", res);
1170
1171 #if 0 /* ignore the local folder */
1172         if(res == NULL) {
1173                 /* with a local dir, copying old files isnt useful since local dir get priority for config */
1174                 res= BLI_get_folder_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, TRUE);
1175         }
1176 #endif
1177
1178         // if(res) printf("LOCAL: %s\n", res);
1179         if(res) {
1180                 return FALSE;
1181         }
1182         else {
1183                 return (BLI_get_folder_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, TRUE) != NULL);
1184         }
1185 }
1186
1187 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1188 {
1189         uiBlock *block;
1190         uiBut *but;
1191         uiLayout *layout, *split, *col;
1192         uiStyle *style= U.uistyles.first;
1193         struct RecentFile *recent;
1194         int i;
1195         MenuType *mt= WM_menutype_find("USERPREF_MT_splash", TRUE);
1196         char url[96];
1197         
1198 #ifdef NAN_BUILDINFO
1199         int ver_width, rev_width;
1200         char *version_str = NULL;
1201         char *revision_str = NULL;
1202         char version_buf[128];
1203         char revision_buf[128];
1204         extern char build_rev[];
1205         
1206         version_str = &version_buf[0];
1207         revision_str = &revision_buf[0];
1208         
1209         sprintf(version_str, "%d.%02d.%d", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION);
1210         sprintf(revision_str, "r%s", build_rev);
1211         
1212         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.dpi);
1213         ver_width = (int)BLF_width(style->widgetlabel.uifont_id, version_str) + 5;
1214         rev_width = (int)BLF_width(style->widgetlabel.uifont_id, revision_str) + 5;
1215 #endif //NAN_BUILDINFO
1216
1217         block= uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
1218         uiBlockSetFlag(block, UI_BLOCK_KEEP_OPEN);
1219         
1220         but= uiDefBut(block, BUT_IMAGE, 0, "", 0, 10, 501, 282, NULL, 0.0, 0.0, 0, 0, "");
1221         uiButSetFunc(but, wm_block_splash_close, block, NULL);
1222         uiBlockSetFunc(block, wm_block_splash_refreshmenu, block, NULL);
1223         
1224 #ifdef NAN_BUILDINFO    
1225         uiDefBut(block, LABEL, 0, version_str, 494-ver_width, 282-24, ver_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1226         uiDefBut(block, LABEL, 0, revision_str, 494-rev_width, 282-36, rev_width, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
1227 #endif //NAN_BUILDINFO
1228         
1229         layout= uiBlockLayout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, 480, 110, style);
1230         
1231         uiBlockSetEmboss(block, UI_EMBOSS);
1232         /* show the splash menu (containing interaction presets), using python */
1233         if (mt) {
1234                 Menu menu= {NULL};
1235                 menu.layout= layout;
1236                 menu.type= mt;
1237                 mt->draw(C, &menu);
1238
1239 //              wmWindowManager *wm= CTX_wm_manager(C);
1240 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
1241         }
1242         
1243         uiBlockSetEmboss(block, UI_EMBOSSP);
1244         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
1245         
1246         split = uiLayoutSplit(layout, 0, 0);
1247         col = uiLayoutColumn(split, 0);
1248         uiItemL(col, "Links", ICON_NONE);
1249         uiItemStringO(col, "Donations", ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/blenderorg/blender-foundation/donation-payment/");
1250         uiItemStringO(col, "Release Log", ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/development/release-logs/blender-258/");
1251         uiItemStringO(col, "Manual", ICON_URL, "WM_OT_url_open", "url", "http://wiki.blender.org/index.php/Doc:2.5/Manual");
1252         uiItemStringO(col, "Blender Website", ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/");
1253         uiItemStringO(col, "User Community", ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org/community/user-community/"); // 
1254         if(strcmp(STRINGIFY(BLENDER_VERSION_CYCLE), "release")==0) {
1255                 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);
1256         }
1257         else {
1258                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d_%d", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION);
1259         }
1260         uiItemStringO(col, "Python API Reference", ICON_URL, "WM_OT_url_open", "url", url);
1261         uiItemL(col, "", ICON_NONE);
1262
1263         col = uiLayoutColumn(split, 0);
1264
1265         if(wm_resource_check_prev()) {
1266                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
1267                 uiItemS(col);
1268         }
1269
1270         uiItemL(col, "Recent", ICON_NONE);
1271         for(recent = G.recent_files.first, i=0; (i<5) && (recent); recent = recent->next, i++) {
1272                 uiItemStringO(col, BLI_path_basename(recent->filepath), ICON_FILE_BLEND, "WM_OT_open_mainfile", "filepath", recent->filepath);
1273         }
1274
1275         uiItemS(col);
1276         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
1277         uiItemL(col, "", ICON_NONE);
1278         
1279         uiCenteredBoundsBlock(block, 0);
1280         uiEndBlock(C, block);
1281         
1282         return block;
1283 }
1284
1285 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
1286 {
1287         uiPupBlock(C, wm_block_create_splash, NULL);
1288         
1289         return OPERATOR_FINISHED;
1290 }
1291
1292 static void WM_OT_splash(wmOperatorType *ot)
1293 {
1294         ot->name= "Splash Screen";
1295         ot->idname= "WM_OT_splash";
1296         ot->description= "Opens a blocking popup region with release info";
1297         
1298         ot->invoke= wm_splash_invoke;
1299         ot->poll= WM_operator_winactive;
1300 }
1301
1302
1303 /* ***************** Search menu ************************* */
1304 static void operator_call_cb(struct bContext *C, void *UNUSED(arg1), void *arg2)
1305 {
1306         wmOperatorType *ot= arg2;
1307         
1308         if(ot)
1309                 WM_operator_name_call(C, ot->idname, WM_OP_INVOKE_DEFAULT, NULL);
1310 }
1311
1312 static void operator_search_cb(const struct bContext *C, void *UNUSED(arg), const char *str, uiSearchItems *items)
1313 {
1314         wmOperatorType *ot = WM_operatortype_first();
1315         
1316         for(; ot; ot= ot->next) {
1317
1318                 if((ot->flag & OPTYPE_INTERNAL) && (G.f & G_DEBUG) == 0)
1319                         continue;
1320
1321                 if(BLI_strcasestr(ot->name, str)) {
1322                         if(WM_operator_poll((bContext*)C, ot)) {
1323                                 char name[256];
1324                                 int len= strlen(ot->name);
1325                                 
1326                                 /* display name for menu, can hold hotkey */
1327                                 BLI_strncpy(name, ot->name, 256);
1328                                 
1329                                 /* check for hotkey */
1330                                 if(len < 256-6) {
1331                                         if(WM_key_event_operator_string(C, ot->idname, WM_OP_EXEC_DEFAULT, NULL, &name[len+1], 256-len-1))
1332                                                 name[len]= '|';
1333                                 }
1334                                 
1335                                 if(0==uiSearchItemAdd(items, name, ot, 0))
1336                                         break;
1337                         }
1338                 }
1339         }
1340 }
1341
1342 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *UNUSED(arg_op))
1343 {
1344         static char search[256]= "";
1345         wmEvent event;
1346         wmWindow *win= CTX_wm_window(C);
1347         uiBlock *block;
1348         uiBut *but;
1349         
1350         block= uiBeginBlock(C, ar, "_popup", UI_EMBOSS);
1351         uiBlockSetFlag(block, UI_BLOCK_LOOP|UI_BLOCK_RET_1|UI_BLOCK_MOVEMOUSE_QUIT);
1352         
1353         but= uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, 256, 10, 10, 9*UI_UNIT_X, UI_UNIT_Y, 0, 0, "");
1354         uiButSetSearchFunc(but, operator_search_cb, NULL, operator_call_cb, NULL);
1355         
1356         /* fake button, it holds space for search items */
1357         uiDefBut(block, LABEL, 0, "", 10, 10 - uiSearchBoxhHeight(), 9*UI_UNIT_X, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
1358         
1359         uiPopupBoundsBlock(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1360         uiEndBlock(C, block);
1361         
1362         event= *(win->eventstate);      /* XXX huh huh? make api call */
1363         event.type= EVT_BUT_OPEN;
1364         event.val= KM_PRESS;
1365         event.customdata= but;
1366         event.customdatafree= FALSE;
1367         wm_event_add(win, &event);
1368         
1369         return block;
1370 }
1371
1372 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1373 {
1374         return OPERATOR_FINISHED;       
1375 }
1376
1377 static int wm_search_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1378 {
1379         uiPupBlock(C, wm_block_search_menu, op);
1380         
1381         return OPERATOR_CANCELLED;
1382 }
1383
1384 /* op->poll */
1385 static int wm_search_menu_poll(bContext *C)
1386 {
1387         if(CTX_wm_window(C)==NULL) {
1388                 return 0;
1389         }
1390         else {
1391                 ScrArea *sa= CTX_wm_area(C);
1392                 if(sa) {
1393                         if(sa->spacetype==SPACE_CONSOLE) return 0;  // XXX - so we can use the shortcut in the console
1394                         if(sa->spacetype==SPACE_TEXT) return 0;  // XXX - so we can use the spacebar in the text editor                 
1395                 }
1396                 else {
1397                         Object *editob= CTX_data_edit_object(C);
1398                         if(editob && editob->type==OB_FONT) return 0; // XXX - so we can use the spacebar for entering text
1399                 }
1400         }
1401         return 1;
1402 }
1403
1404 static void WM_OT_search_menu(wmOperatorType *ot)
1405 {
1406         ot->name= "Search Menu";
1407         ot->idname= "WM_OT_search_menu";
1408         
1409         ot->invoke= wm_search_menu_invoke;
1410         ot->exec= wm_search_menu_exec;
1411         ot->poll= wm_search_menu_poll;
1412 }
1413
1414 static int wm_ndof_menu_invoke(bContext *C, wmOperator *UNUSED(op), wmEvent *UNUSED(event))
1415 {
1416         uiPupMenuInvoke(C,"VIEW3D_MT_ndof_settings");
1417
1418         return OPERATOR_FINISHED; // <-- correct?
1419         return OPERATOR_CANCELLED; // <-- correct?
1420 }
1421
1422 static void WM_OT_ndof_menu(wmOperatorType *ot)
1423 {
1424         ot->name = "NDOF Menu";
1425         ot->idname = "WM_OT_ndof_menu";
1426         
1427         ot->invoke = wm_ndof_menu_invoke;
1428 }
1429
1430 static int wm_call_menu_exec(bContext *C, wmOperator *op)
1431 {
1432         char idname[BKE_ST_MAXNAME];
1433         RNA_string_get(op->ptr, "name", idname);
1434
1435         uiPupMenuInvoke(C, idname);
1436
1437         return OPERATOR_CANCELLED;
1438 }
1439
1440 static void WM_OT_call_menu(wmOperatorType *ot)
1441 {
1442         ot->name= "Call Menu";
1443         ot->idname= "WM_OT_call_menu";
1444
1445         ot->exec= wm_call_menu_exec;
1446         ot->poll= WM_operator_winactive;
1447
1448         ot->flag= OPTYPE_INTERNAL;
1449
1450         RNA_def_string(ot->srna, "name", "", BKE_ST_MAXNAME, "Name", "Name of the menu");
1451 }
1452
1453 /* ************ window / screen operator definitions ************** */
1454
1455 /* this poll functions is needed in place of WM_operator_winactive
1456  * while it crashes on full screen */
1457 static int wm_operator_winactive_normal(bContext *C)
1458 {
1459         wmWindow *win= CTX_wm_window(C);
1460
1461         if(win==NULL || win->screen==NULL || win->screen->full != SCREENNORMAL)
1462                 return 0;
1463
1464         return 1;
1465 }
1466
1467 static void WM_OT_window_duplicate(wmOperatorType *ot)
1468 {
1469         ot->name= "Duplicate Window";
1470         ot->idname= "WM_OT_window_duplicate";
1471         ot->description="Duplicate the current Blender window";
1472                 
1473         ot->exec= wm_window_duplicate_exec;
1474         ot->poll= wm_operator_winactive_normal;
1475 }
1476
1477 static void WM_OT_save_homefile(wmOperatorType *ot)
1478 {
1479         ot->name= "Save User Settings";
1480         ot->idname= "WM_OT_save_homefile";
1481         ot->description="Make the current file the default .blend file";
1482                 
1483         ot->invoke= WM_operator_confirm;
1484         ot->exec= WM_write_homefile;
1485         ot->poll= WM_operator_winactive;
1486 }
1487
1488 static void WM_OT_read_homefile(wmOperatorType *ot)
1489 {
1490         ot->name= "Reload Start-Up File";
1491         ot->idname= "WM_OT_read_homefile";
1492         ot->description="Open the default file (doesn't save the current file)";
1493         
1494         ot->invoke= WM_operator_confirm;
1495         ot->exec= WM_read_homefile_exec;
1496         /* ommit poll to run in background mode */
1497 }
1498
1499 static void WM_OT_read_factory_settings(wmOperatorType *ot)
1500 {
1501         ot->name= "Load Factory Settings";
1502         ot->idname= "WM_OT_read_factory_settings";
1503         ot->description="Load default file and user preferences";
1504         
1505         ot->invoke= WM_operator_confirm;
1506         ot->exec= WM_read_homefile_exec;
1507         /* ommit poll to run in background mode */
1508 }
1509
1510 /* *************** open file **************** */
1511
1512 static void open_set_load_ui(wmOperator *op)
1513 {
1514         if(!RNA_property_is_set(op->ptr, "load_ui"))
1515                 RNA_boolean_set(op->ptr, "load_ui", !(U.flag & USER_FILENOUI));
1516 }
1517
1518 static void open_set_use_scripts(wmOperator *op)
1519 {
1520         if(!RNA_property_is_set(op->ptr, "use_scripts")) {
1521                 /* use G_SCRIPT_AUTOEXEC rather than the userpref because this means if
1522                  * the flag has been disabled from the command line, then opening
1523                  * from the menu wont enable this setting. */
1524                 RNA_boolean_set(op->ptr, "use_scripts", (G.f & G_SCRIPT_AUTOEXEC));
1525         }
1526 }
1527
1528 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1529 {
1530         const char *openname= G.main->name;
1531
1532         if(CTX_wm_window(C) == NULL) {
1533                 /* in rare cases this could happen, when trying to invoke in background
1534                  * mode on load for example. Don't use poll for this because exec()
1535                  * can still run without a window */
1536                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
1537                 return OPERATOR_CANCELLED;
1538         }
1539
1540         /* if possible, get the name of the most recently used .blend file */
1541         if (G.recent_files.first) {
1542                 struct RecentFile *recent = G.recent_files.first;
1543                 openname = recent->filepath;
1544         }
1545
1546         RNA_string_set(op->ptr, "filepath", openname);
1547         open_set_load_ui(op);
1548         open_set_use_scripts(op);
1549
1550         WM_event_add_fileselect(C, op);
1551
1552         return OPERATOR_RUNNING_MODAL;
1553 }
1554
1555 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
1556 {
1557         char path[FILE_MAX];
1558
1559         RNA_string_get(op->ptr, "filepath", path);
1560         open_set_load_ui(op);
1561         open_set_use_scripts(op);
1562
1563         if(RNA_boolean_get(op->ptr, "load_ui"))
1564                 G.fileflags &= ~G_FILE_NO_UI;
1565         else
1566                 G.fileflags |= G_FILE_NO_UI;
1567                 
1568         if(RNA_boolean_get(op->ptr, "use_scripts"))
1569                 G.f |= G_SCRIPT_AUTOEXEC;
1570         else
1571                 G.f &= ~G_SCRIPT_AUTOEXEC;
1572         
1573         // XXX wm in context is not set correctly after WM_read_file -> crash
1574         // do it before for now, but is this correct with multiple windows?
1575         WM_event_add_notifier(C, NC_WINDOW, NULL);
1576
1577         WM_read_file(C, path, op->reports);
1578         
1579         return OPERATOR_FINISHED;
1580 }
1581
1582 static void WM_OT_open_mainfile(wmOperatorType *ot)
1583 {
1584         ot->name= "Open Blender File";
1585         ot->idname= "WM_OT_open_mainfile";
1586         ot->description="Open a Blender file";
1587         
1588         ot->invoke= wm_open_mainfile_invoke;
1589         ot->exec= wm_open_mainfile_exec;
1590         /* ommit window poll so this can work in background mode */
1591         
1592         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
1593
1594         RNA_def_boolean(ot->srna, "load_ui", 1, "Load UI", "Load user interface setup in the .blend file");
1595         RNA_def_boolean(ot->srna, "use_scripts", 1, "Trusted Source", "Allow blend file execute scripts automatically, default available from system preferences");
1596 }
1597
1598 /* **************** link/append *************** */
1599
1600 static int wm_link_append_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1601 {
1602         if(!RNA_property_is_set(op->ptr, "relative_path"))
1603                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
1604
1605         if(RNA_property_is_set(op->ptr, "filepath")) {
1606                 return WM_operator_call(C, op);
1607         } 
1608         else {
1609                 /* XXX TODO solve where to get last linked library from */
1610                 RNA_string_set(op->ptr, "filepath", G.lib);
1611                 WM_event_add_fileselect(C, op);
1612                 return OPERATOR_RUNNING_MODAL;
1613         }
1614 }
1615
1616 static short wm_link_append_flag(wmOperator *op)
1617 {
1618         short flag= 0;
1619
1620         if(RNA_boolean_get(op->ptr, "autoselect")) flag |= FILE_AUTOSELECT;
1621         if(RNA_boolean_get(op->ptr, "active_layer")) flag |= FILE_ACTIVELAY;
1622         if(RNA_boolean_get(op->ptr, "relative_path")) flag |= FILE_RELPATH;
1623         if(RNA_boolean_get(op->ptr, "link")) flag |= FILE_LINK;
1624         if(RNA_boolean_get(op->ptr, "instance_groups")) flag |= FILE_GROUP_INSTANCE;
1625
1626         return flag;
1627 }
1628
1629 static int wm_link_append_exec(bContext *C, wmOperator *op)
1630 {
1631         Main *bmain= CTX_data_main(C);
1632         Scene *scene= CTX_data_scene(C);
1633         Main *mainl= NULL;
1634         BlendHandle *bh;
1635         PropertyRNA *prop;
1636         char name[FILE_MAX], dir[FILE_MAX], libname[FILE_MAX], group[GROUP_MAX];
1637         int idcode, totfiles=0;
1638         short flag;
1639
1640         name[0] = '\0';
1641         RNA_string_get(op->ptr, "filename", name);
1642         RNA_string_get(op->ptr, "directory", dir);
1643
1644         /* test if we have a valid data */
1645         if(BLO_is_a_library(dir, libname, group) == 0) {
1646                 BKE_report(op->reports, RPT_ERROR, "Not a library");
1647                 return OPERATOR_CANCELLED;
1648         }
1649         else if(group[0] == 0) {
1650                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1651                 return OPERATOR_CANCELLED;
1652         }
1653         else if(BLI_path_cmp(bmain->name, libname) == 0) {
1654                 BKE_report(op->reports, RPT_ERROR, "Cannot use current file as library");
1655                 return OPERATOR_CANCELLED;
1656         }
1657
1658         /* check if something is indicated for append/link */
1659         prop = RNA_struct_find_property(op->ptr, "files");
1660         if(prop) {
1661                 totfiles= RNA_property_collection_length(op->ptr, prop);
1662                 if(totfiles == 0) {
1663                         if(name[0] == '\0') {
1664                                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1665                                 return OPERATOR_CANCELLED;
1666                         }
1667                 }
1668         }
1669         else if(name[0] == '\0') {
1670                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1671                 return OPERATOR_CANCELLED;
1672         }
1673
1674         bh = BLO_blendhandle_from_file(libname, op->reports);
1675
1676         if(bh == NULL) {
1677                 /* unlikely since we just browsed it, but possible
1678                  * error reports will have been made by BLO_blendhandle_from_file() */
1679                 return OPERATOR_CANCELLED;
1680         }
1681
1682
1683         /* from here down, no error returns */
1684
1685         idcode = BKE_idcode_from_name(group);
1686
1687         /* now we have or selected, or an indicated file */
1688         if(RNA_boolean_get(op->ptr, "autoselect"))
1689                 scene_deselect_all(scene);
1690
1691         
1692         flag = wm_link_append_flag(op);
1693
1694         /* sanity checks for flag */
1695         if(scene->id.lib && (flag & FILE_GROUP_INSTANCE)) {
1696                 /* TODO, user never gets this message */
1697                 BKE_reportf(op->reports, RPT_WARNING, "Scene '%s' is linked, group instance disabled", scene->id.name+2);
1698                 flag &= ~FILE_GROUP_INSTANCE;
1699         }
1700
1701
1702         /* tag everything, all untagged data can be made local
1703          * its also generally useful to know what is new
1704          *
1705          * take extra care flag_all_listbases_ids(LIB_LINK_TAG, 0) is called after! */
1706         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
1707
1708         /* here appending/linking starts */
1709         mainl = BLO_library_append_begin(C, &bh, libname);
1710         if(totfiles == 0) {
1711                 BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1712         }
1713         else {
1714                 RNA_BEGIN(op->ptr, itemptr, "files") {
1715                         RNA_string_get(&itemptr, "name", name);
1716                         BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1717                 }
1718                 RNA_END;
1719         }
1720         BLO_library_append_end(C, mainl, &bh, idcode, flag);
1721         
1722         /* mark all library linked objects to be updated */
1723         recalc_all_library_objects(bmain);
1724
1725         /* append, rather than linking */
1726         if((flag & FILE_LINK)==0) {
1727                 Library *lib= BLI_findstring(&bmain->library, libname, offsetof(Library, filepath));
1728                 if(lib) all_local(lib, 1);
1729                 else    BLI_assert(!"cant find name of just added library!");
1730         }
1731
1732         /* important we unset, otherwise these object wont
1733          * link into other scenes from this blend file */
1734         flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
1735
1736         /* recreate dependency graph to include new objects */
1737         DAG_scene_sort(bmain, scene);
1738         DAG_ids_flush_update(bmain, 0);
1739
1740         BLO_blendhandle_close(bh);
1741
1742         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
1743         BLI_strncpy(G.lib, dir, FILE_MAX);
1744
1745         WM_event_add_notifier(C, NC_WINDOW, NULL);
1746
1747         return OPERATOR_FINISHED;
1748 }
1749
1750 static void WM_OT_link_append(wmOperatorType *ot)
1751 {
1752         ot->name= "Link/Append from Library";
1753         ot->idname= "WM_OT_link_append";
1754         ot->description= "Link or Append from a Library .blend file";
1755         
1756         ot->invoke= wm_link_append_invoke;
1757         ot->exec= wm_link_append_exec;
1758         ot->poll= WM_operator_winactive;
1759         
1760         ot->flag |= OPTYPE_UNDO;
1761
1762         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_LOADLIB, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_DIRECTORY|WM_FILESEL_FILENAME| WM_FILESEL_RELPATH);
1763         
1764         RNA_def_boolean(ot->srna, "link", 1, "Link", "Link the objects or datablocks rather than appending");
1765         RNA_def_boolean(ot->srna, "autoselect", 1, "Select", "Select the linked objects");
1766         RNA_def_boolean(ot->srna, "active_layer", 1, "Active Layer", "Put the linked objects on the active layer");
1767         RNA_def_boolean(ot->srna, "instance_groups", 1, "Instance Groups", "Create instances for each group as a DupliGroup");
1768
1769         RNA_def_collection_runtime(ot->srna, "files", &RNA_OperatorFileListElement, "Files", "");
1770 }       
1771
1772 /* *************** recover last session **************** */
1773
1774 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1775 {
1776         char filename[FILE_MAX];
1777
1778         G.fileflags |= G_FILE_RECOVER;
1779
1780         // XXX wm in context is not set correctly after WM_read_file -> crash
1781         // do it before for now, but is this correct with multiple windows?
1782         WM_event_add_notifier(C, NC_WINDOW, NULL);
1783
1784         /* load file */
1785         BLI_make_file_string("/", filename, btempdir, "quit.blend");
1786         WM_read_file(C, filename, op->reports);
1787
1788         G.fileflags &= ~G_FILE_RECOVER;
1789         return OPERATOR_FINISHED;
1790 }
1791
1792 static void WM_OT_recover_last_session(wmOperatorType *ot)
1793 {
1794         ot->name= "Recover Last Session";
1795         ot->idname= "WM_OT_recover_last_session";
1796         ot->description="Open the last closed file (\"quit.blend\")";
1797         
1798         ot->exec= wm_recover_last_session_exec;
1799         ot->poll= WM_operator_winactive;
1800 }
1801
1802 /* *************** recover auto save **************** */
1803
1804 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1805 {
1806         char path[FILE_MAX];
1807
1808         RNA_string_get(op->ptr, "filepath", path);
1809
1810         G.fileflags |= G_FILE_RECOVER;
1811
1812         // XXX wm in context is not set correctly after WM_read_file -> crash
1813         // do it before for now, but is this correct with multiple windows?
1814         WM_event_add_notifier(C, NC_WINDOW, NULL);
1815
1816         /* load file */
1817         WM_read_file(C, path, op->reports);
1818
1819         G.fileflags &= ~G_FILE_RECOVER;
1820
1821         return OPERATOR_FINISHED;
1822 }
1823
1824 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1825 {
1826         char filename[FILE_MAX];
1827
1828         wm_autosave_location(filename);
1829         RNA_string_set(op->ptr, "filepath", filename);
1830         WM_event_add_fileselect(C, op);
1831
1832         return OPERATOR_RUNNING_MODAL;
1833 }
1834
1835 static void WM_OT_recover_auto_save(wmOperatorType *ot)
1836 {
1837         ot->name= "Recover Auto Save";
1838         ot->idname= "WM_OT_recover_auto_save";
1839         ot->description="Open an automatically saved file to recover it";
1840         
1841         ot->exec= wm_recover_auto_save_exec;
1842         ot->invoke= wm_recover_auto_save_invoke;
1843         ot->poll= WM_operator_winactive;
1844
1845         WM_operator_properties_filesel(ot, BLENDERFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
1846 }
1847
1848 /* *************** save file as **************** */
1849
1850 static void untitled(char *name)
1851 {
1852         if(G.save_over == 0 && strlen(name) < FILE_MAX-16) {
1853                 char *c= BLI_last_slash(name);
1854                 
1855                 if(c)
1856                         strcpy(&c[1], "untitled.blend");
1857                 else
1858                         strcpy(name, "untitled.blend");
1859         }
1860 }
1861
1862 static void save_set_compress(wmOperator *op)
1863 {
1864         if(!RNA_property_is_set(op->ptr, "compress")) {
1865                 if(G.save_over) /* keep flag for existing file */
1866                         RNA_boolean_set(op->ptr, "compress", G.fileflags & G_FILE_COMPRESS);
1867                 else /* use userdef for new file */
1868                         RNA_boolean_set(op->ptr, "compress", U.flag & USER_FILECOMPRESS);
1869         }
1870 }
1871
1872 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1873 {
1874         char name[FILE_MAX];
1875
1876         save_set_compress(op);
1877         
1878         /* if not saved before, get the name of the most recently used .blend file */
1879         if(G.main->name[0]==0 && G.recent_files.first) {
1880                 struct RecentFile *recent = G.recent_files.first;
1881                 BLI_strncpy(name, recent->filepath, FILE_MAX);
1882         }
1883         else
1884                 BLI_strncpy(name, G.main->name, FILE_MAX);
1885         
1886         untitled(name);
1887         RNA_string_set(op->ptr, "filepath", name);
1888         
1889         WM_event_add_fileselect(C, op);
1890
1891         return OPERATOR_RUNNING_MODAL;
1892 }
1893
1894 /* function used for WM_OT_save_mainfile too */
1895 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
1896 {
1897         char path[FILE_MAX];
1898         int fileflags;
1899         int copy=0;
1900
1901         save_set_compress(op);
1902         
1903         if(RNA_property_is_set(op->ptr, "filepath"))
1904                 RNA_string_get(op->ptr, "filepath", path);
1905         else {
1906                 BLI_strncpy(path, G.main->name, FILE_MAX);
1907                 untitled(path);
1908         }
1909
1910         if(RNA_property_is_set(op->ptr, "copy"))
1911                 copy = RNA_boolean_get(op->ptr, "copy");
1912         
1913         fileflags= G.fileflags;
1914
1915         /* set compression flag */
1916         if(RNA_boolean_get(op->ptr, "compress"))                fileflags |=  G_FILE_COMPRESS;
1917         else                                                                                    fileflags &= ~G_FILE_COMPRESS;
1918         if(RNA_boolean_get(op->ptr, "relative_remap"))  fileflags |=  G_FILE_RELATIVE_REMAP;
1919         else                                                                                    fileflags &= ~G_FILE_RELATIVE_REMAP;
1920
1921         if ( WM_write_file(C, path, fileflags, op->reports, copy) != 0)
1922                 return OPERATOR_CANCELLED;
1923
1924         WM_event_add_notifier(C, NC_WM|ND_FILESAVE, NULL);
1925
1926         return OPERATOR_FINISHED;
1927 }
1928
1929 /* function used for WM_OT_save_mainfile too */
1930 static int blend_save_check(bContext *UNUSED(C), wmOperator *op)
1931 {
1932         char filepath[FILE_MAX];
1933         RNA_string_get(op->ptr, "filepath", filepath);
1934         if(BLI_replace_extension(filepath, sizeof(filepath), ".blend")) {
1935                 RNA_string_set(op->ptr, "filepath", filepath);
1936                 return TRUE;
1937         }
1938         return FALSE;
1939 }
1940
1941 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
1942 {
1943         ot->name= "Save As Blender File";
1944         ot->idname= "WM_OT_save_as_mainfile";
1945         ot->description="Save the current file in the desired location";
1946         
1947         ot->invoke= wm_save_as_mainfile_invoke;
1948         ot->exec= wm_save_as_mainfile_exec;
1949         ot->check= blend_save_check;
1950         /* ommit window poll so this can work in background mode */
1951
1952         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
1953         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
1954         RNA_def_boolean(ot->srna, "relative_remap", 1, "Remap Relative", "Remap relative paths when saving in a different directory");
1955         RNA_def_boolean(ot->srna, "copy", 0, "Save Copy", "Save a copy of the actual working state but does not make saved file active.");
1956 }
1957
1958 /* *************** save file directly ******** */
1959
1960 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1961 {
1962         char name[FILE_MAX];
1963         int check_existing=1;
1964         
1965         /* cancel if no active window */
1966         if (CTX_wm_window(C) == NULL)
1967                 return OPERATOR_CANCELLED;
1968
1969         save_set_compress(op);
1970
1971         /* if not saved before, get the name of the most recently used .blend file */
1972         if(G.main->name[0]==0 && G.recent_files.first) {
1973                 struct RecentFile *recent = G.recent_files.first;
1974                 BLI_strncpy(name, recent->filepath, FILE_MAX);
1975         }
1976         else
1977                 BLI_strncpy(name, G.main->name, FILE_MAX);
1978
1979         untitled(name);
1980         
1981         RNA_string_set(op->ptr, "filepath", name);
1982         
1983         if (RNA_struct_find_property(op->ptr, "check_existing"))
1984                 if (RNA_boolean_get(op->ptr, "check_existing")==0)
1985                         check_existing = 0;
1986         
1987         if (G.save_over) {
1988                 if (check_existing)
1989                         uiPupMenuSaveOver(C, op, name);
1990                 else {
1991                         wm_save_as_mainfile_exec(C, op);
1992                 }
1993         } else {
1994                 WM_event_add_fileselect(C, op);
1995         }
1996         
1997         return OPERATOR_RUNNING_MODAL;
1998 }
1999
2000 static void WM_OT_save_mainfile(wmOperatorType *ot)
2001 {
2002         ot->name= "Save Blender File";
2003         ot->idname= "WM_OT_save_mainfile";
2004         ot->description="Save the current Blender file";
2005         
2006         ot->invoke= wm_save_mainfile_invoke;
2007         ot->exec= wm_save_as_mainfile_exec;
2008         ot->check= blend_save_check;
2009         /* ommit window poll so this can work in background mode */
2010         
2011         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
2012         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2013         RNA_def_boolean(ot->srna, "relative_remap", 0, "Remap Relative", "Remap relative paths when saving in a different directory");
2014 }
2015
2016 /* XXX: move these collada operators to a more appropriate place */
2017 #ifdef WITH_COLLADA
2018
2019 #include "../../collada/collada.h"
2020
2021 static int wm_collada_export_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2022 {       
2023         int selected = 0;
2024
2025         if(!RNA_property_is_set(op->ptr, "filepath")) {
2026                 char filepath[FILE_MAX];
2027                 BLI_strncpy(filepath, G.main->name, sizeof(filepath));
2028                 BLI_replace_extension(filepath, sizeof(filepath), ".dae");
2029                 RNA_string_set(op->ptr, "filepath", filepath);
2030         }
2031
2032         WM_event_add_fileselect(C, op);
2033
2034         return OPERATOR_RUNNING_MODAL;
2035 }
2036
2037 /* function used for WM_OT_save_mainfile too */
2038 static int wm_collada_export_exec(bContext *C, wmOperator *op)
2039 {
2040         char filename[FILE_MAX];
2041         int selected;
2042         
2043         if(!RNA_property_is_set(op->ptr, "filepath")) {
2044                 BKE_report(op->reports, RPT_ERROR, "No filename given");
2045                 return OPERATOR_CANCELLED;
2046         }
2047
2048         RNA_string_get(op->ptr, "filepath", filename);
2049         selected = RNA_boolean_get(op->ptr, "selected");
2050         if(collada_export(CTX_data_scene(C), filename, selected)) {
2051                 return OPERATOR_FINISHED;
2052         }
2053         else {
2054                 return OPERATOR_CANCELLED;
2055         }
2056 }
2057
2058 static void WM_OT_collada_export(wmOperatorType *ot)
2059 {
2060         ot->name= "Export COLLADA";
2061         ot->idname= "WM_OT_collada_export";
2062         
2063         ot->invoke= wm_collada_export_invoke;
2064         ot->exec= wm_collada_export_exec;
2065         ot->poll= WM_operator_winactive;
2066         
2067         WM_operator_properties_filesel(ot, FOLDERFILE|COLLADAFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
2068         RNA_def_boolean(ot->srna, "selected", 0, "Export only selected",
2069                 "Export only selected elements");
2070 }
2071
2072 /* function used for WM_OT_save_mainfile too */
2073 static int wm_collada_import_exec(bContext *C, wmOperator *op)
2074 {
2075         char filename[FILE_MAX];
2076         
2077         if(!RNA_property_is_set(op->ptr, "filepath")) {
2078                 BKE_report(op->reports, RPT_ERROR, "No filename given");
2079                 return OPERATOR_CANCELLED;
2080         }
2081
2082         RNA_string_get(op->ptr, "filepath", filename);
2083         collada_import(C, filename);
2084         
2085         return OPERATOR_FINISHED;
2086 }
2087
2088 static void WM_OT_collada_import(wmOperatorType *ot)
2089 {
2090         ot->name= "Import COLLADA";
2091         ot->idname= "WM_OT_collada_import";
2092         
2093         ot->invoke= WM_operator_filesel;
2094         ot->exec= wm_collada_import_exec;
2095         ot->poll= WM_operator_winactive;
2096         
2097         WM_operator_properties_filesel(ot, FOLDERFILE|COLLADAFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
2098 }
2099
2100 #endif
2101
2102
2103 /* *********************** */
2104
2105 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2106 {
2107         ot->name= "Toggle Fullscreen";
2108         ot->idname= "WM_OT_window_fullscreen_toggle";
2109         ot->description="Toggle the current window fullscreen";
2110
2111         ot->exec= wm_window_fullscreen_toggle_exec;
2112         ot->poll= WM_operator_winactive;
2113 }
2114
2115 static int wm_exit_blender_op(bContext *C, wmOperator *op)
2116 {
2117         WM_operator_free(op);
2118         
2119         WM_exit(C);     
2120         
2121         return OPERATOR_FINISHED;
2122 }
2123
2124 static void WM_OT_quit_blender(wmOperatorType *ot)
2125 {
2126         ot->name= "Quit Blender";
2127         ot->idname= "WM_OT_quit_blender";
2128         ot->description= "Quit Blender";
2129
2130         ot->invoke= WM_operator_confirm;
2131         ot->exec= wm_exit_blender_op;
2132         ot->poll= WM_operator_winactive;
2133 }
2134
2135 /* *********************** */
2136
2137 #if defined(WIN32)
2138
2139 static int wm_console_toggle_op(bContext *UNUSED(C), wmOperator *UNUSED(op))
2140 {
2141         GHOST_toggleConsole(2);
2142         return OPERATOR_FINISHED;
2143 }
2144
2145 static void WM_OT_console_toggle(wmOperatorType *ot)
2146 {
2147         ot->name= "Toggle System Console";
2148         ot->idname= "WM_OT_console_toggle";
2149         ot->description= "Toggle System Console";
2150         
2151         ot->exec= wm_console_toggle_op;
2152         ot->poll= WM_operator_winactive;
2153 }
2154
2155 #endif
2156
2157 /* ************ default paint cursors, draw always around cursor *********** */
2158 /*
2159  - returns handler to free 
2160  - poll(bContext): returns 1 if draw should happen
2161  - draw(bContext): drawing callback for paint cursor
2162 */
2163
2164 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2165                                    wmPaintCursorDraw draw, void *customdata)
2166 {
2167         wmPaintCursor *pc= MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2168         
2169         BLI_addtail(&wm->paintcursors, pc);
2170         
2171         pc->customdata = customdata;
2172         pc->poll= poll;
2173         pc->draw= draw;
2174         
2175         return pc;
2176 }
2177
2178 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2179 {
2180         wmPaintCursor *pc;
2181         
2182         for(pc= wm->paintcursors.first; pc; pc= pc->next) {
2183                 if(pc == (wmPaintCursor *)handle) {
2184                         BLI_remlink(&wm->paintcursors, pc);
2185                         MEM_freeN(pc);
2186                         return;
2187                 }
2188         }
2189 }
2190
2191 /* ************ window gesture operator-callback definitions ************** */
2192 /*
2193  * These are default callbacks for use in operators requiring gesture input
2194  */
2195
2196 /* **************** Border gesture *************** */
2197
2198 /* Border gesture has two types:
2199    1) WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border 
2200    2) WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends
2201
2202    It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
2203 */
2204
2205 static int border_apply_rect(wmOperator *op)
2206 {
2207         wmGesture *gesture= op->customdata;
2208         rcti *rect= gesture->customdata;
2209         
2210         if(rect->xmin==rect->xmax || rect->ymin==rect->ymax)
2211                 return 0;
2212
2213         
2214         /* operator arguments and storage. */
2215         RNA_int_set(op->ptr, "xmin", MIN2(rect->xmin, rect->xmax) );
2216         RNA_int_set(op->ptr, "ymin", MIN2(rect->ymin, rect->ymax) );
2217         RNA_int_set(op->ptr, "xmax", MAX2(rect->xmin, rect->xmax) );
2218         RNA_int_set(op->ptr, "ymax", MAX2(rect->ymin, rect->ymax) );
2219
2220         return 1;
2221 }
2222
2223 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
2224 {
2225         if (!border_apply_rect(op))
2226                 return 0;
2227         
2228         /* XXX weak; border should be configured for this without reading event types */
2229         if( RNA_struct_find_property(op->ptr, "gesture_mode") )
2230                 RNA_int_set(op->ptr, "gesture_mode", gesture_mode);
2231
2232         op->type->exec(C, op);
2233         return 1;
2234 }
2235
2236 static void wm_gesture_end(bContext *C, wmOperator *op)
2237 {
2238         wmGesture *gesture= op->customdata;
2239         
2240         WM_gesture_end(C, gesture);     /* frees gesture itself, and unregisters from window */
2241         op->customdata= NULL;
2242
2243         ED_area_tag_redraw(CTX_wm_area(C));
2244         
2245         if( RNA_struct_find_property(op->ptr, "cursor") )
2246                 WM_cursor_restore(CTX_wm_window(C));
2247 }
2248
2249 int WM_border_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
2250 {
2251         if(ISTWEAK(event->type))
2252                 op->customdata= WM_gesture_new(C, event, WM_GESTURE_RECT);
2253         else
2254                 op->customdata= WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
2255
2256         /* add modal handler */
2257         WM_event_add_modal_handler(C, op);
2258         
2259         wm_gesture_tag_redraw(C);
2260
2261         return OPERATOR_RUNNING_MODAL;
2262 }
2263
2264 int WM_border_select_modal(bContext *C, wmOperator *op, wmEvent *event)
2265 {
2266         wmGesture *gesture= op->customdata;
2267         rcti *rect= gesture->customdata;
2268         int sx, sy;
2269         
2270         if(event->type== MOUSEMOVE) {
2271                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2272
2273                 if(gesture->type==WM_GESTURE_CROSS_RECT && gesture->mode==0) {
2274                         rect->xmin= rect->xmax= event->x - sx;
2275                         rect->ymin= rect->ymax= event->y - sy;
2276                 }
2277                 else {
2278                         rect->xmax= event->x - sx;
2279                         rect->ymax= event->y - sy;
2280                 }
2281                 border_apply_rect(op);
2282
2283                 wm_gesture_tag_redraw(C);
2284         }
2285         else if (event->type==EVT_MODAL_MAP) {
2286                 switch (event->val) {
2287                 case GESTURE_MODAL_BEGIN:
2288                         if(gesture->type==WM_GESTURE_CROSS_RECT && gesture->mode==0) {
2289                                 gesture->mode= 1;
2290                                 wm_gesture_tag_redraw(C);
2291                         }
2292                         break;
2293                 case GESTURE_MODAL_SELECT:
2294                 case GESTURE_MODAL_DESELECT:
2295                 case GESTURE_MODAL_IN:
2296                 case GESTURE_MODAL_OUT:
2297                         if(border_apply(C, op, event->val)) {
2298                                 wm_gesture_end(C, op);
2299                                 return OPERATOR_FINISHED;
2300                         }
2301                         wm_gesture_end(C, op);
2302                         return OPERATOR_CANCELLED;
2303                         break;
2304
2305                 case GESTURE_MODAL_CANCEL:
2306                         wm_gesture_end(C, op);
2307                         return OPERATOR_CANCELLED;
2308                 }
2309
2310         }
2311 //      // Allow view navigation???
2312 //      else {
2313 //              return OPERATOR_PASS_THROUGH;
2314 //      }
2315
2316         return OPERATOR_RUNNING_MODAL;
2317 }
2318
2319 int WM_border_select_cancel(bContext *C, wmOperator *op)
2320 {
2321         wm_gesture_end(C, op);
2322
2323         return OPERATOR_CANCELLED;
2324 }
2325
2326 /* **************** circle gesture *************** */
2327 /* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
2328
2329 #ifdef GESTURE_MEMORY
2330 int circle_select_size= 25; // XXX - need some operator memory thing\!
2331 #endif
2332
2333 int WM_gesture_circle_invoke(bContext *C, wmOperator *op, wmEvent *event)
2334 {
2335         op->customdata= WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
2336         
2337         /* add modal handler */
2338         WM_event_add_modal_handler(C, op);
2339         
2340         wm_gesture_tag_redraw(C);
2341         
2342         return OPERATOR_RUNNING_MODAL;
2343 }
2344
2345 static void gesture_circle_apply(bContext *C, wmOperator *op)
2346 {
2347         wmGesture *gesture= op->customdata;
2348         rcti *rect= gesture->customdata;
2349         
2350         if(RNA_int_get(op->ptr, "gesture_mode")==GESTURE_MODAL_NOP)
2351                 return;
2352
2353         /* operator arguments and storage. */
2354         RNA_int_set(op->ptr, "x", rect->xmin);
2355         RNA_int_set(op->ptr, "y", rect->ymin);
2356         RNA_int_set(op->ptr, "radius", rect->xmax);
2357         
2358         if(op->type->exec)
2359                 op->type->exec(C, op);
2360
2361 #ifdef GESTURE_MEMORY
2362         circle_select_size= rect->xmax;
2363 #endif
2364 }
2365
2366 int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
2367 {
2368         wmGesture *gesture= op->customdata;
2369         rcti *rect= gesture->customdata;
2370         int sx, sy;
2371
2372         if(event->type== MOUSEMOVE) {
2373                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2374
2375                 rect->xmin= event->x - sx;
2376                 rect->ymin= event->y - sy;
2377
2378                 wm_gesture_tag_redraw(C);
2379
2380                 if(gesture->mode)
2381                         gesture_circle_apply(C, op);
2382         }
2383         else if (event->type==EVT_MODAL_MAP) {
2384                 switch (event->val) {
2385                 case GESTURE_MODAL_CIRCLE_ADD:
2386                         rect->xmax += 2 + rect->xmax/10;
2387                         wm_gesture_tag_redraw(C);
2388                         break;
2389                 case GESTURE_MODAL_CIRCLE_SUB:
2390                         rect->xmax -= 2 + rect->xmax/10;
2391                         if(rect->xmax < 1) rect->xmax= 1;
2392                         wm_gesture_tag_redraw(C);
2393                         break;
2394                 case GESTURE_MODAL_SELECT:
2395                 case GESTURE_MODAL_DESELECT:
2396                 case GESTURE_MODAL_NOP:
2397                         if(RNA_struct_find_property(op->ptr, "gesture_mode"))
2398                                 RNA_int_set(op->ptr, "gesture_mode", event->val);
2399
2400                         if(event->val != GESTURE_MODAL_NOP) {
2401                                 /* apply first click */
2402                                 gesture_circle_apply(C, op);
2403                                 gesture->mode= 1;
2404                                 wm_gesture_tag_redraw(C);
2405                         }
2406                         break;
2407
2408                 case GESTURE_MODAL_CANCEL:
2409                 case GESTURE_MODAL_CONFIRM:
2410                         wm_gesture_end(C, op);
2411                         return OPERATOR_FINISHED; /* use finish or we dont get an undo */
2412                 }
2413         }
2414 //      // Allow view navigation???
2415 //      else {
2416 //              return OPERATOR_PASS_THROUGH;
2417 //      }
2418
2419         return OPERATOR_RUNNING_MODAL;
2420 }
2421
2422 int WM_gesture_circle_cancel(bContext *C, wmOperator *op)
2423 {
2424         wm_gesture_end(C, op);
2425
2426         return OPERATOR_CANCELLED;
2427 }
2428
2429 #if 0
2430 /* template to copy from */
2431 void WM_OT_circle_gesture(wmOperatorType *ot)
2432 {
2433         ot->name= "Circle Gesture";
2434         ot->idname= "WM_OT_circle_gesture";
2435         ot->description="Enter rotate mode with a circular gesture";
2436         
2437         ot->invoke= WM_gesture_circle_invoke;
2438         ot->modal= WM_gesture_circle_modal;
2439         
2440         ot->poll= WM_operator_winactive;
2441         
2442         RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
2443         RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
2444         RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
2445
2446 }
2447 #endif
2448
2449 /* **************** Tweak gesture *************** */
2450
2451 static void tweak_gesture_modal(bContext *C, wmEvent *event)
2452 {
2453         wmWindow *window= CTX_wm_window(C);
2454         wmGesture *gesture= window->tweak;
2455         rcti *rect= gesture->customdata;
2456         int sx, sy, val;
2457         
2458         switch(event->type) {
2459                 case MOUSEMOVE:
2460                 case INBETWEEN_MOUSEMOVE:
2461                         
2462                         wm_subwindow_getorigin(window, gesture->swinid, &sx, &sy);
2463                         
2464                         rect->xmax= event->x - sx;
2465                         rect->ymax= event->y - sy;
2466                         
2467                         if((val= wm_gesture_evaluate(gesture))) {
2468                                 wmEvent tevent;
2469
2470                                 tevent= *(window->eventstate);
2471                                 if(gesture->event_type==LEFTMOUSE)
2472                                         tevent.type= EVT_TWEAK_L;
2473                                 else if(gesture->event_type==RIGHTMOUSE)
2474                                         tevent.type= EVT_TWEAK_R;
2475                                 else
2476                                         tevent.type= EVT_TWEAK_M;
2477                                 tevent.val= val;
2478                                 /* mouse coords! */
2479                                 wm_event_add(window, &tevent);
2480                                 
2481                                 WM_gesture_end(C, gesture);     /* frees gesture itself, and unregisters from window */
2482                         }
2483                         
2484                         break;
2485                         
2486                 case LEFTMOUSE:
2487                 case RIGHTMOUSE:
2488                 case MIDDLEMOUSE:
2489                         if(gesture->event_type==event->type) {
2490                                 WM_gesture_end(C, gesture);
2491
2492                                 /* when tweak fails we should give the other keymap entries a chance */
2493                                 event->val= KM_RELEASE;
2494                         }
2495                         break;
2496                 default:
2497                         if(!ISTIMER(event->type)) {
2498                                 WM_gesture_end(C, gesture);
2499                         }
2500                         break;
2501         }
2502 }
2503
2504 /* standard tweak, called after window handlers passed on event */
2505 void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
2506 {
2507         wmWindow *win= CTX_wm_window(C);
2508         
2509         if(win->tweak==NULL) {
2510                 if(CTX_wm_region(C)) {
2511                         if(event->val==KM_PRESS) { 
2512                                 if( ELEM3(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE) )
2513                                         win->tweak= WM_gesture_new(C, event, WM_GESTURE_TWEAK);
2514                         }
2515                 }
2516         }
2517         else {
2518                 /* no tweaks if event was handled */
2519                 if((action & WM_HANDLER_BREAK)) {
2520                         WM_gesture_end(C, win->tweak);
2521                 }
2522                 else
2523                         tweak_gesture_modal(C, event);
2524         }
2525 }
2526
2527 /* *********************** lasso gesture ****************** */
2528
2529 int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, wmEvent *event)
2530 {
2531         op->customdata= WM_gesture_new(C, event, WM_GESTURE_LASSO);
2532         
2533         /* add modal handler */
2534         WM_event_add_modal_handler(C, op);
2535         
2536         wm_gesture_tag_redraw(C);
2537         
2538         if( RNA_struct_find_property(op->ptr, "cursor") )
2539                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2540         
2541         return OPERATOR_RUNNING_MODAL;
2542 }
2543
2544 int WM_gesture_lines_invoke(bContext *C, wmOperator *op, wmEvent *event)
2545 {
2546         op->customdata= WM_gesture_new(C, event, WM_GESTURE_LINES);
2547         
2548         /* add modal handler */
2549         WM_event_add_modal_handler(C, op);
2550         
2551         wm_gesture_tag_redraw(C);
2552         
2553         if( RNA_struct_find_property(op->ptr, "cursor") )
2554                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2555         
2556         return OPERATOR_RUNNING_MODAL;
2557 }
2558
2559
2560 static void gesture_lasso_apply(bContext *C, wmOperator *op)
2561 {
2562         wmGesture *gesture= op->customdata;
2563         PointerRNA itemptr;
2564         float loc[2];
2565         int i;
2566         short *lasso= gesture->customdata;
2567         
2568         /* operator storage as path. */
2569
2570         for(i=0; i<gesture->points; i++, lasso+=2) {
2571                 loc[0]= lasso[0];
2572                 loc[1]= lasso[1];
2573                 RNA_collection_add(op->ptr, "path", &itemptr);
2574                 RNA_float_set_array(&itemptr, "loc", loc);
2575         }
2576         
2577         wm_gesture_end(C, op);
2578                 
2579         if(op->type->exec)
2580                 op->type->exec(C, op);
2581         
2582 }
2583
2584 int WM_gesture_lasso_modal(bContext *C, wmOperator *op, wmEvent *event)
2585 {
2586         wmGesture *gesture= op->customdata;
2587         int sx, sy;
2588         
2589         switch(event->type) {
2590                 case MOUSEMOVE:
2591                 case INBETWEEN_MOUSEMOVE:
2592                         
2593                         wm_gesture_tag_redraw(C);
2594                         
2595                         wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2596
2597                         if(gesture->points == gesture->size) {
2598                                 short *old_lasso = gesture->customdata;
2599                                 gesture->customdata= MEM_callocN(2*sizeof(short)*(gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
2600                                 memcpy(gesture->customdata, old_lasso, 2*sizeof(short)*gesture->size);
2601                                 gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
2602                                 MEM_freeN(old_lasso);
2603                                 printf("realloc\n");
2604                         }
2605
2606                         {
2607                                 int x, y;
2608                                 short *lasso= gesture->customdata;
2609                                 
2610                                 lasso += (2 * gesture->points - 2);
2611                                 x = (event->x - sx - lasso[0]);
2612                                 y = (event->y - sy - lasso[1]);
2613                                 
2614                                 /* make a simple distance check to get a smoother lasso
2615                                    add only when at least 2 pixels between this and previous location */
2616                                 if((x*x+y*y) > 4) {
2617                                         lasso += 2;
2618                                         lasso[0] = event->x - sx;
2619                                         lasso[1] = event->y - sy;
2620                                         gesture->points++;
2621                                 }
2622                         }
2623                         break;
2624                         
2625                 case LEFTMOUSE:
2626                 case MIDDLEMOUSE:
2627                 case RIGHTMOUSE:
2628                         if(event->val==KM_RELEASE) {    /* key release */
2629                                 gesture_lasso_apply(C, op);
2630                                 return OPERATOR_FINISHED;
2631                         }
2632                         break;
2633                 case ESCKEY:
2634                         wm_gesture_end(C, op);
2635                         return OPERATOR_CANCELLED;
2636         }
2637         return OPERATOR_RUNNING_MODAL;
2638 }
2639
2640 int WM_gesture_lines_modal(bContext *C, wmOperator *op, wmEvent *event)
2641 {
2642         return WM_gesture_lasso_modal(C, op, event);
2643 }
2644
2645 int WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
2646 {
2647         wm_gesture_end(C, op);
2648
2649         return OPERATOR_CANCELLED;
2650 }
2651
2652 int WM_gesture_lines_cancel(bContext *C, wmOperator *op)
2653 {
2654         wm_gesture_end(C, op);
2655
2656         return OPERATOR_CANCELLED;
2657 }
2658
2659 #if 0
2660 /* template to copy from */
2661
2662 static int gesture_lasso_exec(bContext *C, wmOperator *op)
2663 {
2664         RNA_BEGIN(op->ptr, itemptr, "path") {
2665                 float loc[2];
2666                 
2667                 RNA_float_get_array(&itemptr, "loc", loc);
2668                 printf("Location: %f %f\n", loc[0], loc[1]);
2669         }
2670         RNA_END;
2671         
2672         return OPERATOR_FINISHED;
2673 }
2674
2675 void WM_OT_lasso_gesture(wmOperatorType *ot)
2676 {
2677         PropertyRNA *prop;
2678         
2679         ot->name= "Lasso Gesture";
2680         ot->idname= "WM_OT_lasso_gesture";
2681         ot->description="Select objects within the lasso as you move the pointer";
2682         
2683         ot->invoke= WM_gesture_lasso_invoke;
2684         ot->modal= WM_gesture_lasso_modal;
2685         ot->exec= gesture_lasso_exec;
2686         
2687         ot->poll= WM_operator_winactive;
2688         
2689         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2690         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2691 }
2692 #endif
2693
2694 /* *********************** straight line gesture ****************** */
2695
2696 static int straightline_apply(bContext *C, wmOperator *op)
2697 {
2698         wmGesture *gesture= op->customdata;
2699         rcti *rect= gesture->customdata;
2700         
2701         if(rect->xmin==rect->xmax && rect->ymin==rect->ymax)
2702                 return 0;
2703         
2704         /* operator arguments and storage. */
2705         RNA_int_set(op->ptr, "xstart", rect->xmin);
2706         RNA_int_set(op->ptr, "ystart", rect->ymin);
2707         RNA_int_set(op->ptr, "xend", rect->xmax);
2708         RNA_int_set(op->ptr, "yend", rect->ymax);
2709
2710         if(op->type->exec)
2711                 op->type->exec(C, op);
2712         
2713         return 1;
2714 }
2715
2716
2717 int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, wmEvent *event)
2718 {
2719         op->customdata= WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
2720         
2721         /* add modal handler */
2722         WM_event_add_modal_handler(C, op);
2723         
2724         wm_gesture_tag_redraw(C);
2725         
2726         if( RNA_struct_find_property(op->ptr, "cursor") )
2727                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2728                 
2729         return OPERATOR_RUNNING_MODAL;
2730 }
2731
2732 int WM_gesture_straightline_modal(bContext *C, wmOperator *op, wmEvent *event)
2733 {
2734         wmGesture *gesture= op->customdata;
2735         rcti *rect= gesture->customdata;
2736         int sx, sy;
2737         
2738         if(event->type== MOUSEMOVE) {
2739                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2740                 
2741                 if(gesture->mode==0) {
2742                         rect->xmin= rect->xmax= event->x - sx;
2743                         rect->ymin= rect->ymax= event->y - sy;
2744                 }
2745                 else {
2746                         rect->xmax= event->x - sx;
2747                         rect->ymax= event->y - sy;
2748                         straightline_apply(C, op);
2749                 }
2750                 
2751                 wm_gesture_tag_redraw(C);
2752         }
2753         else if (event->type==EVT_MODAL_MAP) {
2754                 switch (event->val) {
2755                         case GESTURE_MODAL_BEGIN:
2756                                 if(gesture->mode==0) {
2757                                         gesture->mode= 1;
2758                                         wm_gesture_tag_redraw(C);
2759                                 }
2760                                 break;
2761                         case GESTURE_MODAL_SELECT:
2762                                 if(straightline_apply(C, op)) {
2763                                         wm_gesture_end(C, op);
2764                                         return OPERATOR_FINISHED;
2765                                 }
2766                                 wm_gesture_end(C, op);
2767                                 return OPERATOR_CANCELLED;
2768                                 break;
2769                                 
2770                         case GESTURE_MODAL_CANCEL:
2771                                 wm_gesture_end(C, op);
2772                                 return OPERATOR_CANCELLED;
2773                 }
2774                 
2775         }
2776
2777         return OPERATOR_RUNNING_MODAL;
2778 }
2779
2780 int WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
2781 {
2782         wm_gesture_end(C, op);
2783
2784         return OPERATOR_CANCELLED;
2785 }
2786
2787 #if 0
2788 /* template to copy from */
2789 void WM_OT_straightline_gesture(wmOperatorType *ot)
2790 {
2791         PropertyRNA *prop;
2792         
2793         ot->name= "Straight Line Gesture";
2794         ot->idname= "WM_OT_straightline_gesture";
2795         ot->description="Draw a straight line as you move the pointer";
2796         
2797         ot->invoke= WM_gesture_straightline_invoke;
2798         ot->modal= WM_gesture_straightline_modal;
2799         ot->exec= gesture_straightline_exec;
2800         
2801         ot->poll= WM_operator_winactive;
2802         
2803         WM_operator_properties_gesture_straightline(ot, 0);
2804 }
2805 #endif
2806
2807 /* *********************** radial control ****************** */
2808
2809 static const int WM_RADIAL_CONTROL_DISPLAY_SIZE = 200;
2810
2811 typedef struct {
2812         PropertyType type;
2813         PropertySubType subtype;
2814         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2815         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2816         StructRNA *image_id_srna;
2817         float initial_value, current_value, min_value, max_value;
2818         int initial_mouse[2];
2819         unsigned int gltex;
2820         ListBase orig_paintcursors;
2821         void *cursor;
2822 } RadialControl;
2823
2824 static void radial_control_set_initial_mouse(RadialControl *rc, wmEvent *event)
2825 {
2826         float d[2] = {0, 0};
2827         float zoom[2] = {1, 1};
2828
2829         rc->initial_mouse[0]= event->x;
2830         rc->initial_mouse[1]= event->y;
2831
2832         switch(rc->subtype) {
2833         case PROP_DISTANCE:
2834                 d[0] = rc->initial_value;
2835                 break;
2836         case PROP_FACTOR:
2837                 d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * (1 - rc->initial_value);
2838                 break;
2839         case PROP_ANGLE:
2840                 d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cos(rc->initial_value);
2841                 d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sin(rc->initial_value);
2842                 break;
2843         default:
2844                 return;
2845         }
2846
2847         if(rc->zoom_prop) {
2848                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2849                 d[0] *= zoom[0];
2850                 d[1] *= zoom[1];
2851         }
2852
2853         rc->initial_mouse[0]-= d[0];
2854         rc->initial_mouse[1]-= d[1];
2855 }
2856
2857 static void radial_control_set_tex(RadialControl *rc)
2858 {
2859         ImBuf *ibuf;
2860
2861         switch(RNA_type_to_ID_code(rc->image_id_ptr.type)) {
2862         case ID_BR:
2863                 if((ibuf = brush_gen_radial_control_imbuf(rc->image_id_ptr.data))) {
2864                         glGenTextures(1, &rc->gltex);
2865                         glBindTexture(GL_TEXTURE_2D, rc->gltex);
2866                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ibuf->x, ibuf->y, 0,
2867                                      GL_ALPHA, GL_FLOAT, ibuf->rect_float);
2868                         MEM_freeN(ibuf->rect_float);
2869                         MEM_freeN(ibuf);
2870                 }
2871                 break;
2872         default:
2873                 break;
2874         }
2875 }
2876
2877 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
2878 {
2879         float col[3] = {0, 0, 0};
2880         float rot;
2881
2882         /* set fill color */
2883         if(rc->fill_col_prop)
2884                 RNA_property_float_get_array(&rc->fill_col_ptr, rc->fill_col_prop, col);
2885         glColor4f(col[0], col[1], col[2], alpha);
2886
2887         if(rc->gltex) {
2888                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2889
2890                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2891                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2892
2893                 /* set up rotation if available */
2894                 if(rc->rot_prop) {
2895                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2896                         glPushMatrix();
2897                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
2898                 }
2899
2900                 /* draw textured quad */
2901                 glEnable(GL_TEXTURE_2D);
2902                 glBegin(GL_QUADS);
2903                 glTexCoord2f(0,0);
2904                 glVertex2f(-radius, -radius);
2905                 glTexCoord2f(1,0);
2906                 glVertex2f(radius, -radius);
2907                 glTexCoord2f(1,1);
2908                 glVertex2f(radius, radius);
2909                 glTexCoord2f(0,1);
2910                 glVertex2f(-radius, radius);
2911                 glEnd();
2912                 glDisable(GL_TEXTURE_2D);
2913
2914                 /* undo rotation */
2915                 if(rc->rot_prop)
2916                         glPopMatrix();
2917         }
2918         else {
2919                 /* flat color if no texture available */
2920                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
2921         }
2922 }
2923
2924 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
2925 {
2926         RadialControl *rc = customdata;
2927         ARegion *ar = CTX_wm_region(C);
2928         float r1=0.0f, r2=0.0f, tex_radius, alpha;
2929         float zoom[2], col[3] = {1, 1, 1};
2930
2931         switch(rc->subtype) {
2932         case PROP_DISTANCE:
2933                 r1= rc->current_value;
2934                 r2= rc->initial_value;
2935                 tex_radius= r1;
2936                 alpha = 0.75;
2937                 break;
2938         case PROP_FACTOR:
2939                 r1= (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_SIZE;
2940                 r2= tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE;
2941                 alpha = rc->current_value / 2 + 0.5;
2942                 break;
2943         case PROP_ANGLE:
2944                 r1= r2= tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE;
2945                 alpha = 0.75;
2946                 break;
2947         default:
2948                 tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
2949                 alpha = 0.75;
2950                 break;
2951         }
2952
2953         /* Keep cursor in the original place */
2954         x = rc->initial_mouse[0] - ar->winrct.xmin;
2955         y = rc->initial_mouse[1] - ar->winrct.ymin;
2956         glTranslatef((float)x, (float)y, 0.0f);
2957
2958         glEnable(GL_BLEND);
2959         glEnable(GL_LINE_SMOOTH);
2960
2961         /* apply zoom if available */
2962         if(rc->zoom_prop) {
2963                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2964                 glScalef(zoom[0], zoom[1], 1);
2965         }
2966
2967         /* draw rotated texture */
2968         radial_control_paint_tex(rc, tex_radius, alpha);
2969
2970         /* set line color */
2971         if(rc->col_prop)
2972                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
2973         glColor4f(col[0], col[1], col[2], 0.5);
2974
2975         if(rc->subtype == PROP_ANGLE) {
2976                 glPushMatrix();
2977                 /* draw original angle line */
2978                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
2979                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2980                 /* draw new angle line */
2981                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
2982                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
2983                 glPopMatrix();
2984         }
2985
2986         /* draw circles on top */
2987         glutil_draw_lined_arc(0.0, (float)(M_PI*2.0), r1, 40);
2988         glutil_draw_lined_arc(0.0, (float)(M_PI*2.0), r2, 40);
2989
2990         glDisable(GL_BLEND);
2991         glDisable(GL_LINE_SMOOTH);
2992 }
2993
2994 /* attempt to retrieve the rna pointer/property from an rna path;
2995    returns 0 for failure, 1 for success, and also 1 if property is not
2996    set */
2997 static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
2998                                    const char *name, PointerRNA *r_ptr,
2999                                    PropertyRNA **r_prop, int req_float,
3000                                    int req_length, int allow_missing)
3001 {
3002         PropertyRNA *unused_prop;
3003         int len;
3004         char *str;
3005
3006         /* get an rna string path from the operator's properties */
3007         if(!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
3008                 return 1;
3009
3010         if(str[0] == '\0') {
3011                 MEM_freeN(str);
3012                 return 1;
3013         }
3014
3015         if(!r_prop)
3016                 r_prop = &unused_prop;
3017
3018         /* get rna from path */
3019         if(!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
3020                 MEM_freeN(str);
3021                 if(allow_missing)
3022                         return 1;
3023                 else {
3024                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't resolve path %s", name);
3025                         return 0;
3026                 }
3027         }
3028
3029         /* if property is expected to be a float, check its type */
3030         if(req_float) {
3031                 if(!(*r_prop) || (RNA_property_type(*r_prop) != PROP_FLOAT)) {
3032                         MEM_freeN(str);
3033                         BKE_reportf(op->reports, RPT_ERROR,
3034                                     "Property from path %s is not a float", name);
3035                         return 0;
3036                 }
3037         }
3038         
3039         /* check property's array length */
3040         if(*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
3041                 MEM_freeN(str);
3042                 BKE_reportf(op->reports, RPT_ERROR,
3043                             "Property from path %s has length %d instead of %d",
3044                             name, len, req_length);
3045                 return 0;
3046         }
3047
3048         /* success */
3049         MEM_freeN(str);
3050         return 1;
3051 }
3052
3053 /* initialize the rna pointers and properties using rna paths */
3054 static int radial_control_get_properties(bContext *C, wmOperator *op)
3055 {
3056         RadialControl *rc = op->customdata;
3057         PointerRNA ctx_ptr;
3058
3059         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
3060
3061         if(!radial_control_get_path(&ctx_ptr, op, "data_path", &rc->ptr, &rc->prop, 0, 0, 0))
3062                 return 0;
3063
3064         /* data path is required */
3065         if(!rc->prop)
3066                 return 0;
3067         
3068         if(!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 1, 0, 0))
3069                 return 0;
3070         if(!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 1, 3, 0))
3071                 return 0;
3072         if(!radial_control_get_path(&ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 1, 3, 0))
3073                 return 0;
3074         
3075         /* slightly ugly; allow this property to not resolve
3076            correctly. needed because 3d texture paint shares the same
3077            keymap as 2d image paint */
3078         if(!radial_control_get_path(&ctx_ptr, op, "zoom_path", &rc->zoom_ptr, &rc->zoom_prop, 1, 2, 1))
3079                 return 0;
3080         
3081         if(!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0, 0))
3082                 return 0;
3083         else if(rc->image_id_ptr.data) {
3084                 /* extra check, pointer must be to an ID */
3085                 if(!RNA_struct_is_ID(rc->image_id_ptr.type)) {
3086                         BKE_report(op->reports, RPT_ERROR,
3087                                    "Pointer from path image_id is not an ID");
3088                         return 0;
3089                 }
3090         }
3091
3092         return 1;
3093 }
3094
3095 static int radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
3096 {
3097         wmWindowManager *wm;
3098         RadialControl *rc;
3099         int min_value_int, max_value_int, step_int;
3100         float step_float, precision;
3101
3102         if(!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
3103                 return OPERATOR_CANCELLED;
3104
3105         if(!radial_control_get_properties(C, op)) {
3106                 MEM_freeN(rc);
3107                 return OPERATOR_CANCELLED;
3108         }
3109
3110         /* get type, initial, min, and max values of the property */
3111         switch((rc->type = RNA_property_type(rc->prop))) {
3112         case PROP_INT:
3113                 rc->initial_value = RNA_property_int_get(&rc->ptr, rc->prop);
3114                 RNA_property_int_ui_range(&rc->ptr, rc->prop, &min_value_int,
3115                                           &max_value_int, &step_int);
3116                 rc->min_value = min_value_int;
3117                 rc->max_value = max_value_int;
3118                 break;
3119         case PROP_FLOAT:
3120                 rc->initial_value = RNA_property_float_get(&rc->ptr, rc->prop);
3121                 RNA_property_float_ui_range(&rc->ptr, rc->prop, &rc->min_value,
3122                                             &rc->max_value, &step_float, &precision);
3123                 break;
3124         default:
3125                 BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
3126                 MEM_freeN(rc);
3127                 return OPERATOR_CANCELLED;
3128         }
3129
3130         /* get subtype of property */
3131         rc->subtype = RNA_property_subtype(rc->prop);
3132         if(!ELEM3(rc->subtype, PROP_DISTANCE, PROP_FACTOR, PROP_ANGLE)) {
3133                 BKE_report(op->reports, RPT_ERROR, "Property must be a distance, a factor, or an angle");
3134                 MEM_freeN(rc);
3135                 return OPERATOR_CANCELLED;
3136         }
3137                 
3138         rc->current_value = rc->initial_value;
3139         radial_control_set_initial_mouse(rc, event);
3140         radial_control_set_tex(rc);
3141
3142         /* temporarily disable other paint cursors */
3143         wm = CTX_wm_manager(C);
3144         rc->orig_paintcursors = wm->paintcursors;
3145         wm->paintcursors.first = wm->paintcursors.last = NULL;
3146
3147         /* add radial control paint cursor */
3148         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
3149                                               radial_control_paint_cursor, rc);
3150
3151         WM_event_add_modal_handler(C, op);
3152
3153         return OPERATOR_RUNNING_MODAL;
3154 }
3155
3156 static void radial_control_set_value(RadialControl *rc, float val)
3157 {
3158         switch(rc->type) {
3159         case PROP_INT:
3160                 RNA_property_int_set(&rc->ptr, rc->prop, val);
3161                 break;
3162         case PROP_FLOAT:
3163                 RNA_property_float_set(&rc->ptr, rc->prop, val);
3164                 break;
3165         default:
3166                 break;
3167         }
3168 }
3169
3170 static int radial_control_cancel(bContext *C, wmOperator *op)
3171 {
3172         RadialControl *rc = op->customdata;
3173         wmWindowManager *wm = CTX_wm_manager(C);
3174
3175         WM_paint_cursor_end(wm, rc->cursor);
3176
3177         /* restore original paint cursors */
3178         wm->paintcursors = rc->orig_paintcursors;
3179
3180         /* not sure if this is a good notifier to use;
3181            intended purpose is to update the UI so that the
3182            new value is displayed in sliders/numfields */
3183         WM_event_add_notifier(C, NC_WINDOW, NULL);
3184
3185         glDeleteTextures(1, &rc->gltex);
3186
3187         MEM_freeN(rc);
3188
3189         return OPERATOR_CANCELLED;
3190 }
3191
3192 static int radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
3193 {
3194         RadialControl *rc = op->customdata;
3195         float new_value, dist, zoom[2];
3196         float delta[2], snap, ret = OPERATOR_RUNNING_MODAL;
3197
3198         /* TODO: fix hardcoded events */
3199
3200         snap = event->ctrl;
3201
3202         switch(event->type) {
3203         case MOUSEMOVE:
3204                 delta[0]= rc->initial_mouse[0] - event->x;
3205                 delta[1]= rc->initial_mouse[1] - event->y;
3206
3207                 if(rc->zoom_prop) {
3208                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3209                         delta[0] /= zoom[0];
3210                         delta[1] /= zoom[1];
3211                 }
3212
3213                 dist= sqrt(delta[0]*delta[0]+delta[1]*delta[1]);
3214
3215                 /* calculate new value and apply snapping  */
3216                 switch(rc->subtype) {
3217                 case PROP_DISTANCE:
3218                         new_value = dist;
3219                         if(snap) new_value = ((int)new_value + 5) / 10*10;
3220                         break;
3221                 case PROP_FACTOR:
3222                         new_value = 1 - dist / WM_RADIAL_CONTROL_DISPLAY_SIZE;
3223                         if(snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
3224                         break;
3225                 case PROP_ANGLE:
3226                         new_value = atan2(delta[1], delta[0]) + M_PI;
3227                         if(snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10*10);
3228                         break;
3229                 default:
3230                         new_value = dist; /* dummy value, should this ever happen? - campbell */
3231                         break;
3232                 }
3233
3234                 /* clamp and update */
3235                 CLAMP(new_value, rc->min_value, rc->max_value);
3236                 radial_control_set_value(rc, new_value);
3237                 rc->current_value = new_value;
3238                 break;
3239
3240         case ESCKEY:
3241         case RIGHTMOUSE:
3242                 /* cancelled; restore original value */
3243                 radial_control_set_value(rc, rc->initial_value);
3244                 ret = OPERATOR_CANCELLED;
3245                 break;
3246                 
3247         case LEFTMOUSE:
3248         case PADENTER:
3249                 /* done; value already set */
3250                 ret = OPERATOR_FINISHED;
3251                 break;
3252         }
3253
3254         ED_region_tag_redraw(CTX_wm_region(C));
3255
3256         if(ret != OPERATOR_RUNNING_MODAL)
3257                 radial_control_cancel(C, op);
3258
3259         return ret;
3260 }
3261
3262 static void WM_OT_radial_control(wmOperatorType *ot)
3263 {
3264         ot->name= "Radial Control";
3265         ot->idname= "WM_OT_radial_control";
3266
3267         ot->invoke= radial_control_invoke;
3268         ot->modal= radial_control_modal;
3269         ot->cancel= radial_control_cancel;
3270
3271         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
3272
3273         /* all paths relative to the context */
3274         RNA_def_string(ot->srna, "data_path", "", 0, "Data Path", "Path of property to be set by the radial control.");
3275         RNA_def_string(ot->srna, "rotation_path", "", 0, "Rotation Path", "Path of property used to rotate the texture display.");
3276         RNA_def_string(ot->srna, "color_path", "", 0, "Color Path", "Path of property used to set the color of the control.");
3277         RNA_def_string(ot->srna, "fill_color_path", "", 0, "Fill Color Path", "Path of property used to set the fill color of the control.");
3278         RNA_def_string(ot->srna, "zoom_path", "", 0, "Zoom Path", "Path of property used to set the zoom level for the control.");
3279         RNA_def_string(ot->srna, "image_id", "", 0, "Image ID", "Path of ID that is used to generate an image for the control.");
3280 }
3281
3282 /* ************************** timer for testing ***************** */
3283
3284 /* uses no type defines, fully local testing function anyway... ;) */
3285
3286 static void redraw_timer_window_swap(bContext *C)
3287 {
3288         wmWindow *win= CTX_wm_window(C);
3289         ScrArea *sa;
3290
3291         for(sa= CTX_wm_screen(C)->areabase.first; sa; sa= sa->next)
3292                 ED_area_tag_redraw(sa);
3293         wm_draw_update(C);
3294
3295         CTX_wm_window_set(C, win);      /* XXX context manipulation warning! */
3296 }
3297
3298 static EnumPropertyItem redraw_timer_type_items[] = {
3299         {0, "DRAW", 0, "Draw Region", "Draw Region"},
3300         {1, "DRAW_SWAP", 0, "Draw Region + Swap", "Draw Region and Swap"},
3301         {2, "DRAW_WIN", 0, "Draw Window", "Draw Window"},
3302         {3, "DRAW_WIN_SWAP", 0, "Draw Window + Swap", "Draw Window and Swap"},
3303         {4, "ANIM_STEP", 0, "Anim Step", "Animation Steps"}