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