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