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