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