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