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