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