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