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