implemented ndof 'dead zone' around home position, fixed X11 active window determinat...
[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 #if 0
1380 static uiBlock* wm_block_ndof_menu_1st(bContext* C, ARegion* ar, void* UNUSED(arg_op))
1381 {
1382         uiBlock* block;
1383         uiBut* but;
1384
1385         block = uiBeginBlock(C, ar, "ndof_popup_menu", UI_EMBOSS);
1386         uiBlockSetFlag(block, UI_BLOCK_LOOP|UI_BLOCK_RET_1|UI_BLOCK_MOVEMOUSE_QUIT);
1387 //      uiBlockSetDirection(block, UI_DOWN);
1388 //      uiBlockBeginAlign(block);
1389
1390         // uiItemBooleanO(block->curlayout, "enable pan/zoom", ICON_NDOF_TRANS, "toggle_ndof_pan_zoom_enabled", "ndof_pan_zoom_enabled", 1);
1391         // uiBlock is used as an opaque type in this file, so can't use members...
1392
1393         int foo = 333;
1394         uiDefButI(block, TOG, 0, "foo", 10, 10, 9*UI_UNIT_X, UI_UNIT_Y, &foo, 0.f, 1.f, 0.1f, 0.9f, "15%");
1395         // 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");
1396
1397 //      uiBlockEndAlign(block);
1398 //      uiBoundsBlock(block, 6);
1399         uiEndBlock(C, block);
1400
1401         return block;
1402 }
1403
1404 static uiBlock *wm_block_ndof_menu(bContext *C, ARegion *ar, void *UNUSED(arg_op))
1405 {
1406         static char search[256]= "";
1407         wmEvent event;
1408         wmWindow *win= CTX_wm_window(C);
1409         uiBlock *block;
1410         uiBut *but;
1411         
1412         block= uiBeginBlock(C, ar, "ndof_popup", UI_EMBOSS);
1413 //      uiBlockSetFlag(block, UI_BLOCK_LOOP|UI_BLOCK_RET_1|UI_BLOCK_MOVEMOUSE_QUIT);
1414         uiBlockSetFlag(block, UI_BLOCK_LOOP|UI_BLOCK_POPUP|UI_BLOCK_MOVEMOUSE_QUIT);
1415         
1416         but= uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, 256, 10, 10, 9*UI_UNIT_X, UI_UNIT_Y, 0, 0, "");
1417         uiButSetSearchFunc(but, operator_search_cb, NULL, operator_call_cb, NULL);
1418         
1419         /* fake button, it holds space for search items */
1420         uiDefBut(block, LABEL, 0, "", 10, 10 - uiSearchBoxhHeight(), 9*UI_UNIT_X, uiSearchBoxhHeight(), NULL, 0, 0, 0, 0, NULL);
1421         
1422         uiPopupBoundsBlock(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1423         uiEndBlock(C, block);
1424         
1425         event= *(win->eventstate);      /* XXX huh huh? make api call */
1426         event.type= EVT_BUT_OPEN;
1427         event.val= KM_PRESS;
1428         event.customdata= but;
1429         event.customdatafree= FALSE;
1430         wm_event_add(win, &event);
1431         
1432         return block;
1433 }
1434
1435 static int wm_ndof_menu_poll(bContext *C)
1436 {
1437         if(CTX_wm_window(C)==NULL)
1438                 return 0;
1439
1440         // if menu is already pulled up, another button press should dismiss it
1441         // not sure if that behavior should go here or elsewhere...
1442
1443         puts("ndof: menu poll");
1444         return 1;
1445 }
1446
1447 static int wm_ndof_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1448 {
1449         puts("ndof: menu exec");
1450         return OPERATOR_FINISHED;       
1451 }
1452 #endif
1453
1454 static int wm_ndof_menu_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1455 {
1456 //      uiPupMenuNotice(C, "Hello!"); // <-- this works
1457 //      uiPupBlock(C, wm_block_ndof_menu, op); // <-- no luck!
1458 //      ui_popup_menu_create(C, NULL, NULL, NULL, NULL, "Hello!"); // <-- this works
1459
1460         uiPopupMenu* pup = uiPupMenuBegin(C,"3D mouse settings",ICON_NDOF_TURN);
1461         uiLayout* layout = uiPupMenuLayout(pup);
1462
1463         printf("ndof: menu invoked in ");
1464
1465         switch (CTX_wm_area(C)->spacetype) // diff spaces can have diff 3d mouse options
1466                 {
1467                 case SPACE_VIEW3D:
1468                         puts("3D area");
1469                         break;
1470                 case SPACE_IMAGE:
1471                         puts("image area");
1472                         break;
1473                 default:
1474                         puts("some iNDOFferent area");
1475                 }
1476
1477
1478         //uiBlock* block = uiLayoutGetBlock(layout);
1479         //int foo = 1;
1480         //uiDefButI(block, TOG, 0, "foo", 10, 10, 9*UI_UNIT_X, UI_UNIT_Y, &foo, 0.f, 1.f, 0.1f, 0.9f, "15%");
1481         
1482         uiItemS(layout); // separator
1483
1484         uiItemBooleanO(layout, "enable pan/zoom", ICON_NDOF_TRANS, "ndof_toggle_pan_zoom_enabled", "ndof_pan_zoom_enabled", 1);
1485         uiItemBooleanO(layout, "enable rotation", ICON_NDOF_TURN, "ndof_toggle_rotation_enabled", "ndof_rotation_enabled", 1);
1486         uiItemFloatO(layout, "sensitivity", 0, "ndof_adjust_sensitivity", "ndof_sensitivity", 1.f);
1487         uiItemV(layout,"sensitivity",ICON_NDOF_TRANS, 1);
1488
1489         uiItemS(layout);
1490         uiItemL(layout, "3D navigation mode", ICON_NDOF_FLY);
1491         uiItemL(layout, "...", 0);
1492
1493         uiPupMenuEnd(C,pup);
1494
1495         return OPERATOR_CANCELLED; // <-- correct?
1496 }
1497
1498 static void WM_OT_ndof_menu(wmOperatorType *ot)
1499 {
1500         puts("ndof: registering menu operator");
1501
1502         ot->name = "NDOF Menu";
1503         ot->idname = "WM_OT_ndof_menu";
1504         
1505         ot->invoke = wm_ndof_menu_invoke;
1506 }
1507
1508 // END ndof menu
1509
1510 static int wm_call_menu_exec(bContext *C, wmOperator *op)
1511 {
1512         char idname[BKE_ST_MAXNAME];
1513         RNA_string_get(op->ptr, "name", idname);
1514
1515         uiPupMenuInvoke(C, idname);
1516
1517         return OPERATOR_CANCELLED;
1518 }
1519
1520 static void WM_OT_call_menu(wmOperatorType *ot)
1521 {
1522         ot->name= "Call Menu";
1523         ot->idname= "WM_OT_call_menu";
1524
1525         ot->exec= wm_call_menu_exec;
1526         ot->poll= WM_operator_winactive;
1527
1528         ot->flag= OPTYPE_INTERNAL;
1529
1530         RNA_def_string(ot->srna, "name", "", BKE_ST_MAXNAME, "Name", "Name of the menu");
1531 }
1532
1533 /* ************ window / screen operator definitions ************** */
1534
1535 /* this poll functions is needed in place of WM_operator_winactive
1536  * while it crashes on full screen */
1537 static int wm_operator_winactive_normal(bContext *C)
1538 {
1539         wmWindow *win= CTX_wm_window(C);
1540
1541         if(win==NULL || win->screen==NULL || win->screen->full != SCREENNORMAL)
1542                 return 0;
1543
1544         return 1;
1545 }
1546
1547 static void WM_OT_window_duplicate(wmOperatorType *ot)
1548 {
1549         ot->name= "Duplicate Window";
1550         ot->idname= "WM_OT_window_duplicate";
1551         ot->description="Duplicate the current Blender window";
1552                 
1553         ot->exec= wm_window_duplicate_exec;
1554         ot->poll= wm_operator_winactive_normal;
1555 }
1556
1557 static void WM_OT_save_homefile(wmOperatorType *ot)
1558 {
1559         ot->name= "Save User Settings";
1560         ot->idname= "WM_OT_save_homefile";
1561         ot->description="Make the current file the default .blend file";
1562                 
1563         ot->invoke= WM_operator_confirm;
1564         ot->exec= WM_write_homefile;
1565         ot->poll= WM_operator_winactive;
1566 }
1567
1568 static void WM_OT_read_homefile(wmOperatorType *ot)
1569 {
1570         ot->name= "Reload Start-Up File";
1571         ot->idname= "WM_OT_read_homefile";
1572         ot->description="Open the default file (doesn't save the current file)";
1573         
1574         ot->invoke= WM_operator_confirm;
1575         ot->exec= WM_read_homefile_exec;
1576         /* ommit poll to run in background mode */
1577 }
1578
1579 static void WM_OT_read_factory_settings(wmOperatorType *ot)
1580 {
1581         ot->name= "Load Factory Settings";
1582         ot->idname= "WM_OT_read_factory_settings";
1583         ot->description="Load default file and user preferences";
1584         
1585         ot->invoke= WM_operator_confirm;
1586         ot->exec= WM_read_homefile_exec;
1587         /* ommit poll to run in background mode */
1588 }
1589
1590 /* *************** open file **************** */
1591
1592 static void open_set_load_ui(wmOperator *op)
1593 {
1594         if(!RNA_property_is_set(op->ptr, "load_ui"))
1595                 RNA_boolean_set(op->ptr, "load_ui", !(U.flag & USER_FILENOUI));
1596 }
1597
1598 static void open_set_use_scripts(wmOperator *op)
1599 {
1600         if(!RNA_property_is_set(op->ptr, "use_scripts")) {
1601                 /* use G_SCRIPT_AUTOEXEC rather than the userpref because this means if
1602                  * the flag has been disabled from the command line, then opening
1603                  * from the menu wont enable this setting. */
1604                 RNA_boolean_set(op->ptr, "use_scripts", (G.f & G_SCRIPT_AUTOEXEC));
1605         }
1606 }
1607
1608 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1609 {
1610         const char *openname= G.main->name;
1611
1612         /* if possible, get the name of the most recently used .blend file */
1613         if (G.recent_files.first) {
1614                 struct RecentFile *recent = G.recent_files.first;
1615                 openname = recent->filepath;
1616         }
1617
1618         RNA_string_set(op->ptr, "filepath", openname);
1619         open_set_load_ui(op);
1620         open_set_use_scripts(op);
1621
1622         WM_event_add_fileselect(C, op);
1623
1624         return OPERATOR_RUNNING_MODAL;
1625 }
1626
1627 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
1628 {
1629         char path[FILE_MAX];
1630
1631         RNA_string_get(op->ptr, "filepath", path);
1632         open_set_load_ui(op);
1633         open_set_use_scripts(op);
1634
1635         if(RNA_boolean_get(op->ptr, "load_ui"))
1636                 G.fileflags &= ~G_FILE_NO_UI;
1637         else
1638                 G.fileflags |= G_FILE_NO_UI;
1639                 
1640         if(RNA_boolean_get(op->ptr, "use_scripts"))
1641                 G.f |= G_SCRIPT_AUTOEXEC;
1642         else
1643                 G.f &= ~G_SCRIPT_AUTOEXEC;
1644         
1645         // XXX wm in context is not set correctly after WM_read_file -> crash
1646         // do it before for now, but is this correct with multiple windows?
1647         WM_event_add_notifier(C, NC_WINDOW, NULL);
1648
1649         WM_read_file(C, path, op->reports);
1650         
1651         return OPERATOR_FINISHED;
1652 }
1653
1654 static void WM_OT_open_mainfile(wmOperatorType *ot)
1655 {
1656         ot->name= "Open Blender File";
1657         ot->idname= "WM_OT_open_mainfile";
1658         ot->description="Open a Blender file";
1659         
1660         ot->invoke= wm_open_mainfile_invoke;
1661         ot->exec= wm_open_mainfile_exec;
1662         ot->poll= WM_operator_winactive;
1663         
1664         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
1665
1666         RNA_def_boolean(ot->srna, "load_ui", 1, "Load UI", "Load user interface setup in the .blend file");
1667         RNA_def_boolean(ot->srna, "use_scripts", 1, "Trusted Source", "Allow blend file execute scripts automatically, default available from system preferences");
1668 }
1669
1670 /* **************** link/append *************** */
1671
1672 static int wm_link_append_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1673 {
1674         if(!RNA_property_is_set(op->ptr, "relative_path"))
1675                 RNA_boolean_set(op->ptr, "relative_path", U.flag & USER_RELPATHS);
1676
1677         if(RNA_property_is_set(op->ptr, "filepath")) {
1678                 return WM_operator_call(C, op);
1679         } 
1680         else {
1681                 /* XXX TODO solve where to get last linked library from */
1682                 RNA_string_set(op->ptr, "filepath", G.lib);
1683                 WM_event_add_fileselect(C, op);
1684                 return OPERATOR_RUNNING_MODAL;
1685         }
1686 }
1687
1688 static short wm_link_append_flag(wmOperator *op)
1689 {
1690         short flag= 0;
1691
1692         if(RNA_boolean_get(op->ptr, "autoselect")) flag |= FILE_AUTOSELECT;
1693         if(RNA_boolean_get(op->ptr, "active_layer")) flag |= FILE_ACTIVELAY;
1694         if(RNA_boolean_get(op->ptr, "relative_path")) flag |= FILE_RELPATH;
1695         if(RNA_boolean_get(op->ptr, "link")) flag |= FILE_LINK;
1696         if(RNA_boolean_get(op->ptr, "instance_groups")) flag |= FILE_GROUP_INSTANCE;
1697
1698         return flag;
1699 }
1700
1701 static int wm_link_append_exec(bContext *C, wmOperator *op)
1702 {
1703         Main *bmain= CTX_data_main(C);
1704         Scene *scene= CTX_data_scene(C);
1705         Main *mainl= NULL;
1706         BlendHandle *bh;
1707         PropertyRNA *prop;
1708         char name[FILE_MAX], dir[FILE_MAX], libname[FILE_MAX], group[GROUP_MAX];
1709         int idcode, totfiles=0;
1710         short flag;
1711
1712         name[0] = '\0';
1713         RNA_string_get(op->ptr, "filename", name);
1714         RNA_string_get(op->ptr, "directory", dir);
1715
1716         /* test if we have a valid data */
1717         if(BLO_is_a_library(dir, libname, group) == 0) {
1718                 BKE_report(op->reports, RPT_ERROR, "Not a library");
1719                 return OPERATOR_CANCELLED;
1720         }
1721         else if(group[0] == 0) {
1722                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1723                 return OPERATOR_CANCELLED;
1724         }
1725         else if(BLI_path_cmp(bmain->name, libname) == 0) {
1726                 BKE_report(op->reports, RPT_ERROR, "Cannot use current file as library");
1727                 return OPERATOR_CANCELLED;
1728         }
1729
1730         /* check if something is indicated for append/link */
1731         prop = RNA_struct_find_property(op->ptr, "files");
1732         if(prop) {
1733                 totfiles= RNA_property_collection_length(op->ptr, prop);
1734                 if(totfiles == 0) {
1735                         if(name[0] == '\0') {
1736                                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1737                                 return OPERATOR_CANCELLED;
1738                         }
1739                 }
1740         }
1741         else if(name[0] == '\0') {
1742                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
1743                 return OPERATOR_CANCELLED;
1744         }
1745
1746         bh = BLO_blendhandle_from_file(libname, op->reports);
1747
1748         if(bh == NULL) {
1749                 /* unlikely since we just browsed it, but possible
1750                  * error reports will have been made by BLO_blendhandle_from_file() */
1751                 return OPERATOR_CANCELLED;
1752         }
1753
1754
1755         /* from here down, no error returns */
1756
1757         idcode = BKE_idcode_from_name(group);
1758
1759         /* now we have or selected, or an indicated file */
1760         if(RNA_boolean_get(op->ptr, "autoselect"))
1761                 scene_deselect_all(scene);
1762
1763         
1764         flag = wm_link_append_flag(op);
1765
1766         /* sanity checks for flag */
1767         if(scene->id.lib && (flag & FILE_GROUP_INSTANCE)) {
1768                 /* TODO, user never gets this message */
1769                 BKE_reportf(op->reports, RPT_WARNING, "Scene '%s' is linked, group instance disabled", scene->id.name+2);
1770                 flag &= ~FILE_GROUP_INSTANCE;
1771         }
1772
1773
1774         /* tag everything, all untagged data can be made local
1775          * its also generally useful to know what is new
1776          *
1777          * take extra care flag_all_listbases_ids(LIB_LINK_TAG, 0) is called after! */
1778         flag_all_listbases_ids(LIB_PRE_EXISTING, 1);
1779
1780         /* here appending/linking starts */
1781         mainl = BLO_library_append_begin(C, &bh, libname);
1782         if(totfiles == 0) {
1783                 BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1784         }
1785         else {
1786                 RNA_BEGIN(op->ptr, itemptr, "files") {
1787                         RNA_string_get(&itemptr, "name", name);
1788                         BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
1789                 }
1790                 RNA_END;
1791         }
1792         BLO_library_append_end(C, mainl, &bh, idcode, flag);
1793         
1794         /* mark all library linked objects to be updated */
1795         recalc_all_library_objects(bmain);
1796
1797         /* append, rather than linking */
1798         if((flag & FILE_LINK)==0) {
1799                 Library *lib= BLI_findstring(&bmain->library, libname, offsetof(Library, filepath));
1800                 if(lib) all_local(lib, 1);
1801                 else    BLI_assert(!"cant find name of just added library!");
1802         }
1803
1804         /* important we unset, otherwise these object wont
1805          * link into other scenes from this blend file */
1806         flag_all_listbases_ids(LIB_PRE_EXISTING, 0);
1807
1808         /* recreate dependency graph to include new objects */
1809         DAG_scene_sort(bmain, scene);
1810         DAG_ids_flush_update(bmain, 0);
1811
1812         BLO_blendhandle_close(bh);
1813
1814         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
1815         BLI_strncpy(G.lib, dir, FILE_MAX);
1816
1817         WM_event_add_notifier(C, NC_WINDOW, NULL);
1818
1819         return OPERATOR_FINISHED;
1820 }
1821
1822 static void WM_OT_link_append(wmOperatorType *ot)
1823 {
1824         ot->name= "Link/Append from Library";
1825         ot->idname= "WM_OT_link_append";
1826         ot->description= "Link or Append from a Library .blend file";
1827         
1828         ot->invoke= wm_link_append_invoke;
1829         ot->exec= wm_link_append_exec;
1830         ot->poll= WM_operator_winactive;
1831         
1832         ot->flag |= OPTYPE_UNDO;
1833
1834         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_LOADLIB, FILE_OPENFILE, WM_FILESEL_FILEPATH|WM_FILESEL_DIRECTORY|WM_FILESEL_FILENAME| WM_FILESEL_RELPATH);
1835         
1836         RNA_def_boolean(ot->srna, "link", 1, "Link", "Link the objects or datablocks rather than appending");
1837         RNA_def_boolean(ot->srna, "autoselect", 1, "Select", "Select the linked objects");
1838         RNA_def_boolean(ot->srna, "active_layer", 1, "Active Layer", "Put the linked objects on the active layer");
1839         RNA_def_boolean(ot->srna, "instance_groups", 1, "Instance Groups", "Create instances for each group as a DupliGroup");
1840
1841         RNA_def_collection_runtime(ot->srna, "files", &RNA_OperatorFileListElement, "Files", "");
1842 }       
1843
1844 /* *************** recover last session **************** */
1845
1846 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
1847 {
1848         char filename[FILE_MAX];
1849
1850         G.fileflags |= G_FILE_RECOVER;
1851
1852         // XXX wm in context is not set correctly after WM_read_file -> crash
1853         // do it before for now, but is this correct with multiple windows?
1854         WM_event_add_notifier(C, NC_WINDOW, NULL);
1855
1856         /* load file */
1857         BLI_make_file_string("/", filename, btempdir, "quit.blend");
1858         WM_read_file(C, filename, op->reports);
1859
1860         G.fileflags &= ~G_FILE_RECOVER;
1861         return OPERATOR_FINISHED;
1862 }
1863
1864 static void WM_OT_recover_last_session(wmOperatorType *ot)
1865 {
1866         ot->name= "Recover Last Session";
1867         ot->idname= "WM_OT_recover_last_session";
1868         ot->description="Open the last closed file (\"quit.blend\")";
1869         
1870         ot->exec= wm_recover_last_session_exec;
1871         ot->poll= WM_operator_winactive;
1872 }
1873
1874 /* *************** recover auto save **************** */
1875
1876 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
1877 {
1878         char path[FILE_MAX];
1879
1880         RNA_string_get(op->ptr, "filepath", path);
1881
1882         G.fileflags |= G_FILE_RECOVER;
1883
1884         // XXX wm in context is not set correctly after WM_read_file -> crash
1885         // do it before for now, but is this correct with multiple windows?
1886         WM_event_add_notifier(C, NC_WINDOW, NULL);
1887
1888         /* load file */
1889         WM_read_file(C, path, op->reports);
1890
1891         G.fileflags &= ~G_FILE_RECOVER;
1892
1893         return OPERATOR_FINISHED;
1894 }
1895
1896 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1897 {
1898         char filename[FILE_MAX];
1899
1900         wm_autosave_location(filename);
1901         RNA_string_set(op->ptr, "filepath", filename);
1902         WM_event_add_fileselect(C, op);
1903
1904         return OPERATOR_RUNNING_MODAL;
1905 }
1906
1907 static void WM_OT_recover_auto_save(wmOperatorType *ot)
1908 {
1909         ot->name= "Recover Auto Save";
1910         ot->idname= "WM_OT_recover_auto_save";
1911         ot->description="Open an automatically saved file to recover it";
1912         
1913         ot->exec= wm_recover_auto_save_exec;
1914         ot->invoke= wm_recover_auto_save_invoke;
1915         ot->poll= WM_operator_winactive;
1916
1917         WM_operator_properties_filesel(ot, BLENDERFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
1918 }
1919
1920 /* *************** save file as **************** */
1921
1922 static void untitled(char *name)
1923 {
1924         if(G.save_over == 0 && strlen(name) < FILE_MAX-16) {
1925                 char *c= BLI_last_slash(name);
1926                 
1927                 if(c)
1928                         strcpy(&c[1], "untitled.blend");
1929                 else
1930                         strcpy(name, "untitled.blend");
1931         }
1932 }
1933
1934 static void save_set_compress(wmOperator *op)
1935 {
1936         if(!RNA_property_is_set(op->ptr, "compress")) {
1937                 if(G.save_over) /* keep flag for existing file */
1938                         RNA_boolean_set(op->ptr, "compress", G.fileflags & G_FILE_COMPRESS);
1939                 else /* use userdef for new file */
1940                         RNA_boolean_set(op->ptr, "compress", U.flag & USER_FILECOMPRESS);
1941         }
1942 }
1943
1944 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1945 {
1946         char name[FILE_MAX];
1947
1948         save_set_compress(op);
1949         
1950         /* if not saved before, get the name of the most recently used .blend file */
1951         if(G.main->name[0]==0 && G.recent_files.first) {
1952                 struct RecentFile *recent = G.recent_files.first;
1953                 BLI_strncpy(name, recent->filepath, FILE_MAX);
1954         }
1955         else
1956                 BLI_strncpy(name, G.main->name, FILE_MAX);
1957         
1958         untitled(name);
1959         RNA_string_set(op->ptr, "filepath", name);
1960         
1961         WM_event_add_fileselect(C, op);
1962
1963         return OPERATOR_RUNNING_MODAL;
1964 }
1965
1966 /* function used for WM_OT_save_mainfile too */
1967 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
1968 {
1969         char path[FILE_MAX];
1970         int fileflags;
1971         int copy=0;
1972
1973         save_set_compress(op);
1974         
1975         if(RNA_property_is_set(op->ptr, "filepath"))
1976                 RNA_string_get(op->ptr, "filepath", path);
1977         else {
1978                 BLI_strncpy(path, G.main->name, FILE_MAX);
1979                 untitled(path);
1980         }
1981
1982         if(RNA_property_is_set(op->ptr, "copy"))
1983                 copy = RNA_boolean_get(op->ptr, "copy");
1984         
1985         fileflags= G.fileflags;
1986
1987         /* set compression flag */
1988         if(RNA_boolean_get(op->ptr, "compress"))                fileflags |=  G_FILE_COMPRESS;
1989         else                                                                                    fileflags &= ~G_FILE_COMPRESS;
1990         if(RNA_boolean_get(op->ptr, "relative_remap"))  fileflags |=  G_FILE_RELATIVE_REMAP;
1991         else                                                                                    fileflags &= ~G_FILE_RELATIVE_REMAP;
1992
1993         if ( WM_write_file(C, path, fileflags, op->reports, copy) != 0)
1994                 return OPERATOR_CANCELLED;
1995
1996         WM_event_add_notifier(C, NC_WM|ND_FILESAVE, NULL);
1997
1998         return OPERATOR_FINISHED;
1999 }
2000
2001 /* function used for WM_OT_save_mainfile too */
2002 static int blend_save_check(bContext *UNUSED(C), wmOperator *op)
2003 {
2004         char filepath[FILE_MAX];
2005         RNA_string_get(op->ptr, "filepath", filepath);
2006         if(BLI_replace_extension(filepath, sizeof(filepath), ".blend")) {
2007                 RNA_string_set(op->ptr, "filepath", filepath);
2008                 return TRUE;
2009         }
2010         return FALSE;
2011 }
2012
2013 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
2014 {
2015         ot->name= "Save As Blender File";
2016         ot->idname= "WM_OT_save_as_mainfile";
2017         ot->description="Save the current file in the desired location";
2018         
2019         ot->invoke= wm_save_as_mainfile_invoke;
2020         ot->exec= wm_save_as_mainfile_exec;
2021         ot->check= blend_save_check;
2022         /* ommit window poll so this can work in background mode */
2023
2024         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
2025         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2026         RNA_def_boolean(ot->srna, "relative_remap", 1, "Remap Relative", "Remap relative paths when saving in a different directory");
2027         RNA_def_boolean(ot->srna, "copy", 0, "Save Copy", "Save a copy of the actual working state but does not make saved file active.");
2028 }
2029
2030 /* *************** save file directly ******** */
2031
2032 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2033 {
2034         char name[FILE_MAX];
2035         int check_existing=1;
2036         
2037         /* cancel if no active window */
2038         if (CTX_wm_window(C) == NULL)
2039                 return OPERATOR_CANCELLED;
2040
2041         save_set_compress(op);
2042
2043         /* if not saved before, get the name of the most recently used .blend file */
2044         if(G.main->name[0]==0 && G.recent_files.first) {
2045                 struct RecentFile *recent = G.recent_files.first;
2046                 BLI_strncpy(name, recent->filepath, FILE_MAX);
2047         }
2048         else
2049                 BLI_strncpy(name, G.main->name, FILE_MAX);
2050
2051         untitled(name);
2052         
2053         RNA_string_set(op->ptr, "filepath", name);
2054         
2055         if (RNA_struct_find_property(op->ptr, "check_existing"))
2056                 if (RNA_boolean_get(op->ptr, "check_existing")==0)
2057                         check_existing = 0;
2058         
2059         if (G.save_over) {
2060                 if (check_existing)
2061                         uiPupMenuSaveOver(C, op, name);
2062                 else {
2063                         wm_save_as_mainfile_exec(C, op);
2064                 }
2065         } else {
2066                 WM_event_add_fileselect(C, op);
2067         }
2068         
2069         return OPERATOR_RUNNING_MODAL;
2070 }
2071
2072 static void WM_OT_save_mainfile(wmOperatorType *ot)
2073 {
2074         ot->name= "Save Blender File";
2075         ot->idname= "WM_OT_save_mainfile";
2076         ot->description="Save the current Blender file";
2077         
2078         ot->invoke= wm_save_mainfile_invoke;
2079         ot->exec= wm_save_as_mainfile_exec;
2080         ot->check= blend_save_check;
2081         ot->poll= NULL;
2082         
2083         WM_operator_properties_filesel(ot, FOLDERFILE|BLENDERFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
2084         RNA_def_boolean(ot->srna, "compress", 0, "Compress", "Write compressed .blend file");
2085         RNA_def_boolean(ot->srna, "relative_remap", 0, "Remap Relative", "Remap relative paths when saving in a different directory");
2086 }
2087
2088 /* XXX: move these collada operators to a more appropriate place */
2089 #ifdef WITH_COLLADA
2090
2091 #include "../../collada/collada.h"
2092
2093 static int wm_collada_export_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2094 {       
2095         if(!RNA_property_is_set(op->ptr, "filepath")) {
2096                 char filepath[FILE_MAX];
2097                 BLI_strncpy(filepath, G.main->name, sizeof(filepath));
2098                 BLI_replace_extension(filepath, sizeof(filepath), ".dae");
2099                 RNA_string_set(op->ptr, "filepath", filepath);
2100         }
2101
2102         WM_event_add_fileselect(C, op);
2103
2104         return OPERATOR_RUNNING_MODAL;
2105 }
2106
2107 /* function used for WM_OT_save_mainfile too */
2108 static int wm_collada_export_exec(bContext *C, wmOperator *op)
2109 {
2110         char filename[FILE_MAX];
2111         
2112         if(!RNA_property_is_set(op->ptr, "filepath")) {
2113                 BKE_report(op->reports, RPT_ERROR, "No filename given");
2114                 return OPERATOR_CANCELLED;
2115         }
2116
2117         RNA_string_get(op->ptr, "filepath", filename);
2118         if(collada_export(CTX_data_scene(C), filename)) {
2119                 return OPERATOR_FINISHED;
2120         }
2121         else {
2122                 return OPERATOR_CANCELLED;
2123         }
2124 }
2125
2126 static void WM_OT_collada_export(wmOperatorType *ot)
2127 {
2128         ot->name= "Export COLLADA";
2129         ot->idname= "WM_OT_collada_export";
2130         
2131         ot->invoke= wm_collada_export_invoke;
2132         ot->exec= wm_collada_export_exec;
2133         ot->poll= WM_operator_winactive;
2134         
2135         WM_operator_properties_filesel(ot, FOLDERFILE|COLLADAFILE, FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH);
2136 }
2137
2138 /* function used for WM_OT_save_mainfile too */
2139 static int wm_collada_import_exec(bContext *C, wmOperator *op)
2140 {
2141         char filename[FILE_MAX];
2142         
2143         if(!RNA_property_is_set(op->ptr, "filepath")) {
2144                 BKE_report(op->reports, RPT_ERROR, "No filename given");
2145                 return OPERATOR_CANCELLED;
2146         }
2147
2148         RNA_string_get(op->ptr, "filepath", filename);
2149         collada_import(C, filename);
2150         
2151         return OPERATOR_FINISHED;
2152 }
2153
2154 static void WM_OT_collada_import(wmOperatorType *ot)
2155 {
2156         ot->name= "Import COLLADA";
2157         ot->idname= "WM_OT_collada_import";
2158         
2159         ot->invoke= WM_operator_filesel;
2160         ot->exec= wm_collada_import_exec;
2161         ot->poll= WM_operator_winactive;
2162         
2163         WM_operator_properties_filesel(ot, FOLDERFILE|COLLADAFILE, FILE_BLENDER, FILE_OPENFILE, WM_FILESEL_FILEPATH);
2164 }
2165
2166 #endif
2167
2168
2169 /* *********************** */
2170
2171 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
2172 {
2173         ot->name= "Toggle Fullscreen";
2174         ot->idname= "WM_OT_window_fullscreen_toggle";
2175         ot->description="Toggle the current window fullscreen";
2176
2177         ot->exec= wm_window_fullscreen_toggle_exec;
2178         ot->poll= WM_operator_winactive;
2179 }
2180
2181 static int wm_exit_blender_op(bContext *C, wmOperator *op)
2182 {
2183         WM_operator_free(op);
2184         
2185         WM_exit(C);     
2186         
2187         return OPERATOR_FINISHED;
2188 }
2189
2190 static void WM_OT_quit_blender(wmOperatorType *ot)
2191 {
2192         ot->name= "Quit Blender";
2193         ot->idname= "WM_OT_quit_blender";
2194         ot->description= "Quit Blender";
2195
2196         ot->invoke= WM_operator_confirm;
2197         ot->exec= wm_exit_blender_op;
2198         ot->poll= WM_operator_winactive;
2199 }
2200
2201 /* *********************** */
2202
2203 #if defined(WIN32)
2204
2205 static int wm_console_toggle_op(bContext *UNUSED(C), wmOperator *UNUSED(op))
2206 {
2207         GHOST_toggleConsole(2);
2208         return OPERATOR_FINISHED;
2209 }
2210
2211 static void WM_OT_console_toggle(wmOperatorType *ot)
2212 {
2213         ot->name= "Toggle System Console";
2214         ot->idname= "WM_OT_console_toggle";
2215         ot->description= "Toggle System Console";
2216         
2217         ot->exec= wm_console_toggle_op;
2218         ot->poll= WM_operator_winactive;
2219 }
2220
2221 #endif
2222
2223 /* ************ default paint cursors, draw always around cursor *********** */
2224 /*
2225  - returns handler to free 
2226  - poll(bContext): returns 1 if draw should happen
2227  - draw(bContext): drawing callback for paint cursor
2228 */
2229
2230 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
2231                                    wmPaintCursorDraw draw, void *customdata)
2232 {
2233         wmPaintCursor *pc= MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
2234         
2235         BLI_addtail(&wm->paintcursors, pc);
2236         
2237         pc->customdata = customdata;
2238         pc->poll= poll;
2239         pc->draw= draw;
2240         
2241         return pc;
2242 }
2243
2244 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
2245 {
2246         wmPaintCursor *pc;
2247         
2248         for(pc= wm->paintcursors.first; pc; pc= pc->next) {
2249                 if(pc == (wmPaintCursor *)handle) {
2250                         BLI_remlink(&wm->paintcursors, pc);
2251                         MEM_freeN(pc);
2252                         return;
2253                 }
2254         }
2255 }
2256
2257 /* ************ window gesture operator-callback definitions ************** */
2258 /*
2259  * These are default callbacks for use in operators requiring gesture input
2260  */
2261
2262 /* **************** Border gesture *************** */
2263
2264 /* Border gesture has two types:
2265    1) WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border 
2266    2) WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends
2267
2268    It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
2269 */
2270
2271 static int border_apply_rect(wmOperator *op)
2272 {
2273         wmGesture *gesture= op->customdata;
2274         rcti *rect= gesture->customdata;
2275         
2276         if(rect->xmin==rect->xmax || rect->ymin==rect->ymax)
2277                 return 0;
2278
2279         
2280         /* operator arguments and storage. */
2281         RNA_int_set(op->ptr, "xmin", MIN2(rect->xmin, rect->xmax) );
2282         RNA_int_set(op->ptr, "ymin", MIN2(rect->ymin, rect->ymax) );
2283         RNA_int_set(op->ptr, "xmax", MAX2(rect->xmin, rect->xmax) );
2284         RNA_int_set(op->ptr, "ymax", MAX2(rect->ymin, rect->ymax) );
2285
2286         return 1;
2287 }
2288
2289 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
2290 {
2291         if (!border_apply_rect(op))
2292                 return 0;
2293         
2294         /* XXX weak; border should be configured for this without reading event types */
2295         if( RNA_struct_find_property(op->ptr, "gesture_mode") )
2296                 RNA_int_set(op->ptr, "gesture_mode", gesture_mode);
2297
2298         op->type->exec(C, op);
2299         return 1;
2300 }
2301
2302 static void wm_gesture_end(bContext *C, wmOperator *op)
2303 {
2304         wmGesture *gesture= op->customdata;
2305         
2306         WM_gesture_end(C, gesture);     /* frees gesture itself, and unregisters from window */
2307         op->customdata= NULL;
2308
2309         ED_area_tag_redraw(CTX_wm_area(C));
2310         
2311         if( RNA_struct_find_property(op->ptr, "cursor") )
2312                 WM_cursor_restore(CTX_wm_window(C));
2313 }
2314
2315 int WM_border_select_invoke(bContext *C, wmOperator *op, wmEvent *event)
2316 {
2317         if(ISTWEAK(event->type))
2318                 op->customdata= WM_gesture_new(C, event, WM_GESTURE_RECT);
2319         else
2320                 op->customdata= WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
2321
2322         /* add modal handler */
2323         WM_event_add_modal_handler(C, op);
2324         
2325         wm_gesture_tag_redraw(C);
2326
2327         return OPERATOR_RUNNING_MODAL;
2328 }
2329
2330 int WM_border_select_modal(bContext *C, wmOperator *op, wmEvent *event)
2331 {
2332         wmGesture *gesture= op->customdata;
2333         rcti *rect= gesture->customdata;
2334         int sx, sy;
2335         
2336         if(event->type== MOUSEMOVE) {
2337                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2338
2339                 if(gesture->type==WM_GESTURE_CROSS_RECT && gesture->mode==0) {
2340                         rect->xmin= rect->xmax= event->x - sx;
2341                         rect->ymin= rect->ymax= event->y - sy;
2342                 }
2343                 else {
2344                         rect->xmax= event->x - sx;
2345                         rect->ymax= event->y - sy;
2346                 }
2347                 border_apply_rect(op);
2348
2349                 wm_gesture_tag_redraw(C);
2350         }
2351         else if (event->type==EVT_MODAL_MAP) {
2352                 switch (event->val) {
2353                 case GESTURE_MODAL_BEGIN:
2354                         if(gesture->type==WM_GESTURE_CROSS_RECT && gesture->mode==0) {
2355                                 gesture->mode= 1;
2356                                 wm_gesture_tag_redraw(C);
2357                         }
2358                         break;
2359                 case GESTURE_MODAL_SELECT:
2360                 case GESTURE_MODAL_DESELECT:
2361                 case GESTURE_MODAL_IN:
2362                 case GESTURE_MODAL_OUT:
2363                         if(border_apply(C, op, event->val)) {
2364                                 wm_gesture_end(C, op);
2365                                 return OPERATOR_FINISHED;
2366                         }
2367                         wm_gesture_end(C, op);
2368                         return OPERATOR_CANCELLED;
2369                         break;
2370
2371                 case GESTURE_MODAL_CANCEL:
2372                         wm_gesture_end(C, op);
2373                         return OPERATOR_CANCELLED;
2374                 }
2375
2376         }
2377 //      // Allow view navigation???
2378 //      else {
2379 //              return OPERATOR_PASS_THROUGH;
2380 //      }
2381
2382         return OPERATOR_RUNNING_MODAL;
2383 }
2384
2385 int WM_border_select_cancel(bContext *C, wmOperator *op)
2386 {
2387         wm_gesture_end(C, op);
2388
2389         return OPERATOR_CANCELLED;
2390 }
2391
2392 /* **************** circle gesture *************** */
2393 /* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
2394
2395 #ifdef GESTURE_MEMORY
2396 int circle_select_size= 25; // XXX - need some operator memory thing\!
2397 #endif
2398
2399 int WM_gesture_circle_invoke(bContext *C, wmOperator *op, wmEvent *event)
2400 {
2401         op->customdata= WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
2402         
2403         /* add modal handler */
2404         WM_event_add_modal_handler(C, op);
2405         
2406         wm_gesture_tag_redraw(C);
2407         
2408         return OPERATOR_RUNNING_MODAL;
2409 }
2410
2411 static void gesture_circle_apply(bContext *C, wmOperator *op)
2412 {
2413         wmGesture *gesture= op->customdata;
2414         rcti *rect= gesture->customdata;
2415         
2416         if(RNA_int_get(op->ptr, "gesture_mode")==GESTURE_MODAL_NOP)
2417                 return;
2418
2419         /* operator arguments and storage. */
2420         RNA_int_set(op->ptr, "x", rect->xmin);
2421         RNA_int_set(op->ptr, "y", rect->ymin);
2422         RNA_int_set(op->ptr, "radius", rect->xmax);
2423         
2424         if(op->type->exec)
2425                 op->type->exec(C, op);
2426
2427 #ifdef GESTURE_MEMORY
2428         circle_select_size= rect->xmax;
2429 #endif
2430 }
2431
2432 int WM_gesture_circle_modal(bContext *C, wmOperator *op, wmEvent *event)
2433 {
2434         wmGesture *gesture= op->customdata;
2435         rcti *rect= gesture->customdata;
2436         int sx, sy;
2437
2438         if(event->type== MOUSEMOVE) {
2439                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2440
2441                 rect->xmin= event->x - sx;
2442                 rect->ymin= event->y - sy;
2443
2444                 wm_gesture_tag_redraw(C);
2445
2446                 if(gesture->mode)
2447                         gesture_circle_apply(C, op);
2448         }
2449         else if (event->type==EVT_MODAL_MAP) {
2450                 switch (event->val) {
2451                 case GESTURE_MODAL_CIRCLE_ADD:
2452                         rect->xmax += 2 + rect->xmax/10;
2453                         wm_gesture_tag_redraw(C);
2454                         break;
2455                 case GESTURE_MODAL_CIRCLE_SUB:
2456                         rect->xmax -= 2 + rect->xmax/10;
2457                         if(rect->xmax < 1) rect->xmax= 1;
2458                         wm_gesture_tag_redraw(C);
2459                         break;
2460                 case GESTURE_MODAL_SELECT:
2461                 case GESTURE_MODAL_DESELECT:
2462                 case GESTURE_MODAL_NOP:
2463                         if(RNA_struct_find_property(op->ptr, "gesture_mode"))
2464                                 RNA_int_set(op->ptr, "gesture_mode", event->val);
2465
2466                         if(event->val != GESTURE_MODAL_NOP) {
2467                                 /* apply first click */
2468                                 gesture_circle_apply(C, op);
2469                                 gesture->mode= 1;
2470                                 wm_gesture_tag_redraw(C);
2471                         }
2472                         break;
2473
2474                 case GESTURE_MODAL_CANCEL:
2475                 case GESTURE_MODAL_CONFIRM:
2476                         wm_gesture_end(C, op);
2477                         return OPERATOR_FINISHED; /* use finish or we dont get an undo */
2478                 }
2479         }
2480 //      // Allow view navigation???
2481 //      else {
2482 //              return OPERATOR_PASS_THROUGH;
2483 //      }
2484
2485         return OPERATOR_RUNNING_MODAL;
2486 }
2487
2488 int WM_gesture_circle_cancel(bContext *C, wmOperator *op)
2489 {
2490         wm_gesture_end(C, op);
2491
2492         return OPERATOR_CANCELLED;
2493 }
2494
2495 #if 0
2496 /* template to copy from */
2497 void WM_OT_circle_gesture(wmOperatorType *ot)
2498 {
2499         ot->name= "Circle Gesture";
2500         ot->idname= "WM_OT_circle_gesture";
2501         ot->description="Enter rotate mode with a circular gesture";
2502         
2503         ot->invoke= WM_gesture_circle_invoke;
2504         ot->modal= WM_gesture_circle_modal;
2505         
2506         ot->poll= WM_operator_winactive;
2507         
2508         RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
2509         RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
2510         RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
2511
2512 }
2513 #endif
2514
2515 /* **************** Tweak gesture *************** */
2516
2517 static void tweak_gesture_modal(bContext *C, wmEvent *event)
2518 {
2519         wmWindow *window= CTX_wm_window(C);
2520         wmGesture *gesture= window->tweak;
2521         rcti *rect= gesture->customdata;
2522         int sx, sy, val;
2523         
2524         switch(event->type) {
2525                 case MOUSEMOVE:
2526                 case INBETWEEN_MOUSEMOVE:
2527                         
2528                         wm_subwindow_getorigin(window, gesture->swinid, &sx, &sy);
2529                         
2530                         rect->xmax= event->x - sx;
2531                         rect->ymax= event->y - sy;
2532                         
2533                         if((val= wm_gesture_evaluate(gesture))) {
2534                                 wmEvent tevent;
2535
2536                                 tevent= *(window->eventstate);
2537                                 if(gesture->event_type==LEFTMOUSE)
2538                                         tevent.type= EVT_TWEAK_L;
2539                                 else if(gesture->event_type==RIGHTMOUSE)
2540                                         tevent.type= EVT_TWEAK_R;
2541                                 else
2542                                         tevent.type= EVT_TWEAK_M;
2543                                 tevent.val= val;
2544                                 /* mouse coords! */
2545                                 wm_event_add(window, &tevent);
2546                                 
2547                                 WM_gesture_end(C, gesture);     /* frees gesture itself, and unregisters from window */
2548                         }
2549                         
2550                         break;
2551                         
2552                 case LEFTMOUSE:
2553                 case RIGHTMOUSE:
2554                 case MIDDLEMOUSE:
2555                         if(gesture->event_type==event->type) {
2556                                 WM_gesture_end(C, gesture);
2557
2558                                 /* when tweak fails we should give the other keymap entries a chance */
2559                                 event->val= KM_RELEASE;
2560                         }
2561                         break;
2562                 default:
2563                         if(!ISTIMER(event->type)) {
2564                                 WM_gesture_end(C, gesture);
2565                         }
2566                         break;
2567         }
2568 }
2569
2570 /* standard tweak, called after window handlers passed on event */
2571 void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
2572 {
2573         wmWindow *win= CTX_wm_window(C);
2574         
2575         if(win->tweak==NULL) {
2576                 if(CTX_wm_region(C)) {
2577                         if(event->val==KM_PRESS) { 
2578                                 if( ELEM3(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE) )
2579                                         win->tweak= WM_gesture_new(C, event, WM_GESTURE_TWEAK);
2580                         }
2581                 }
2582         }
2583         else {
2584                 /* no tweaks if event was handled */
2585                 if((action & WM_HANDLER_BREAK)) {
2586                         WM_gesture_end(C, win->tweak);
2587                 }
2588                 else
2589                         tweak_gesture_modal(C, event);
2590         }
2591 }
2592
2593 /* *********************** lasso gesture ****************** */
2594
2595 int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, wmEvent *event)
2596 {
2597         op->customdata= WM_gesture_new(C, event, WM_GESTURE_LASSO);
2598         
2599         /* add modal handler */
2600         WM_event_add_modal_handler(C, op);
2601         
2602         wm_gesture_tag_redraw(C);
2603         
2604         if( RNA_struct_find_property(op->ptr, "cursor") )
2605                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2606         
2607         return OPERATOR_RUNNING_MODAL;
2608 }
2609
2610 int WM_gesture_lines_invoke(bContext *C, wmOperator *op, wmEvent *event)
2611 {
2612         op->customdata= WM_gesture_new(C, event, WM_GESTURE_LINES);
2613         
2614         /* add modal handler */
2615         WM_event_add_modal_handler(C, op);
2616         
2617         wm_gesture_tag_redraw(C);
2618         
2619         if( RNA_struct_find_property(op->ptr, "cursor") )
2620                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2621         
2622         return OPERATOR_RUNNING_MODAL;
2623 }
2624
2625
2626 static void gesture_lasso_apply(bContext *C, wmOperator *op)
2627 {
2628         wmGesture *gesture= op->customdata;
2629         PointerRNA itemptr;
2630         float loc[2];
2631         int i;
2632         short *lasso= gesture->customdata;
2633         
2634         /* operator storage as path. */
2635
2636         for(i=0; i<gesture->points; i++, lasso+=2) {
2637                 loc[0]= lasso[0];
2638                 loc[1]= lasso[1];
2639                 RNA_collection_add(op->ptr, "path", &itemptr);
2640                 RNA_float_set_array(&itemptr, "loc", loc);
2641         }
2642         
2643         wm_gesture_end(C, op);
2644                 
2645         if(op->type->exec)
2646                 op->type->exec(C, op);
2647         
2648 }
2649
2650 int WM_gesture_lasso_modal(bContext *C, wmOperator *op, wmEvent *event)
2651 {
2652         wmGesture *gesture= op->customdata;
2653         int sx, sy;
2654         
2655         switch(event->type) {
2656                 case MOUSEMOVE:
2657                 case INBETWEEN_MOUSEMOVE:
2658                         
2659                         wm_gesture_tag_redraw(C);
2660                         
2661                         wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2662
2663                         if(gesture->points == gesture->size) {
2664                                 short *old_lasso = gesture->customdata;
2665                                 gesture->customdata= MEM_callocN(2*sizeof(short)*(gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
2666                                 memcpy(gesture->customdata, old_lasso, 2*sizeof(short)*gesture->size);
2667                                 gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
2668                                 MEM_freeN(old_lasso);
2669                                 printf("realloc\n");
2670                         }
2671
2672                         {
2673                                 int x, y;
2674                                 short *lasso= gesture->customdata;
2675                                 
2676                                 lasso += (2 * gesture->points - 2);
2677                                 x = (event->x - sx - lasso[0]);
2678                                 y = (event->y - sy - lasso[1]);
2679                                 
2680                                 /* make a simple distance check to get a smoother lasso
2681                                    add only when at least 2 pixels between this and previous location */
2682                                 if((x*x+y*y) > 4) {
2683                                         lasso += 2;
2684                                         lasso[0] = event->x - sx;
2685                                         lasso[1] = event->y - sy;
2686                                         gesture->points++;
2687                                 }
2688                         }
2689                         break;
2690                         
2691                 case LEFTMOUSE:
2692                 case MIDDLEMOUSE:
2693                 case RIGHTMOUSE:
2694                         if(event->val==KM_RELEASE) {    /* key release */
2695                                 gesture_lasso_apply(C, op);
2696                                 return OPERATOR_FINISHED;
2697                         }
2698                         break;
2699                 case ESCKEY:
2700                         wm_gesture_end(C, op);
2701                         return OPERATOR_CANCELLED;
2702         }
2703         return OPERATOR_RUNNING_MODAL;
2704 }
2705
2706 int WM_gesture_lines_modal(bContext *C, wmOperator *op, wmEvent *event)
2707 {
2708         return WM_gesture_lasso_modal(C, op, event);
2709 }
2710
2711 int WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
2712 {
2713         wm_gesture_end(C, op);
2714
2715         return OPERATOR_CANCELLED;
2716 }
2717
2718 int WM_gesture_lines_cancel(bContext *C, wmOperator *op)
2719 {
2720         wm_gesture_end(C, op);
2721
2722         return OPERATOR_CANCELLED;
2723 }
2724
2725 #if 0
2726 /* template to copy from */
2727
2728 static int gesture_lasso_exec(bContext *C, wmOperator *op)
2729 {
2730         RNA_BEGIN(op->ptr, itemptr, "path") {
2731                 float loc[2];
2732                 
2733                 RNA_float_get_array(&itemptr, "loc", loc);
2734                 printf("Location: %f %f\n", loc[0], loc[1]);
2735         }
2736         RNA_END;
2737         
2738         return OPERATOR_FINISHED;
2739 }
2740
2741 void WM_OT_lasso_gesture(wmOperatorType *ot)
2742 {
2743         PropertyRNA *prop;
2744         
2745         ot->name= "Lasso Gesture";
2746         ot->idname= "WM_OT_lasso_gesture";
2747         ot->description="Select objects within the lasso as you move the pointer";
2748         
2749         ot->invoke= WM_gesture_lasso_invoke;
2750         ot->modal= WM_gesture_lasso_modal;
2751         ot->exec= gesture_lasso_exec;
2752         
2753         ot->poll= WM_operator_winactive;
2754         
2755         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2756         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2757 }
2758 #endif
2759
2760 /* *********************** straight line gesture ****************** */
2761
2762 static int straightline_apply(bContext *C, wmOperator *op)
2763 {
2764         wmGesture *gesture= op->customdata;
2765         rcti *rect= gesture->customdata;
2766         
2767         if(rect->xmin==rect->xmax && rect->ymin==rect->ymax)
2768                 return 0;
2769         
2770         /* operator arguments and storage. */
2771         RNA_int_set(op->ptr, "xstart", rect->xmin);
2772         RNA_int_set(op->ptr, "ystart", rect->ymin);
2773         RNA_int_set(op->ptr, "xend", rect->xmax);
2774         RNA_int_set(op->ptr, "yend", rect->ymax);
2775
2776         if(op->type->exec)
2777                 op->type->exec(C, op);
2778         
2779         return 1;
2780 }
2781
2782
2783 int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, wmEvent *event)
2784 {
2785         op->customdata= WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
2786         
2787         /* add modal handler */
2788         WM_event_add_modal_handler(C, op);
2789         
2790         wm_gesture_tag_redraw(C);
2791         
2792         if( RNA_struct_find_property(op->ptr, "cursor") )
2793                 WM_cursor_modal(CTX_wm_window(C), RNA_int_get(op->ptr, "cursor"));
2794                 
2795         return OPERATOR_RUNNING_MODAL;
2796 }
2797
2798 int WM_gesture_straightline_modal(bContext *C, wmOperator *op, wmEvent *event)
2799 {
2800         wmGesture *gesture= op->customdata;
2801         rcti *rect= gesture->customdata;
2802         int sx, sy;
2803         
2804         if(event->type== MOUSEMOVE) {
2805                 wm_subwindow_getorigin(CTX_wm_window(C), gesture->swinid, &sx, &sy);
2806                 
2807                 if(gesture->mode==0) {
2808                         rect->xmin= rect->xmax= event->x - sx;
2809                         rect->ymin= rect->ymax= event->y - sy;
2810                 }
2811                 else {
2812                         rect->xmax= event->x - sx;
2813                         rect->ymax= event->y - sy;
2814                         straightline_apply(C, op);
2815                 }
2816                 
2817                 wm_gesture_tag_redraw(C);
2818         }
2819         else if (event->type==EVT_MODAL_MAP) {
2820                 switch (event->val) {
2821                         case GESTURE_MODAL_BEGIN:
2822                                 if(gesture->mode==0) {
2823                                         gesture->mode= 1;
2824                                         wm_gesture_tag_redraw(C);
2825                                 }
2826                                 break;
2827                         case GESTURE_MODAL_SELECT:
2828                                 if(straightline_apply(C, op)) {
2829                                         wm_gesture_end(C, op);
2830                                         return OPERATOR_FINISHED;
2831                                 }
2832                                 wm_gesture_end(C, op);
2833                                 return OPERATOR_CANCELLED;
2834                                 break;
2835                                 
2836                         case GESTURE_MODAL_CANCEL:
2837                                 wm_gesture_end(C, op);
2838                                 return OPERATOR_CANCELLED;
2839                 }
2840                 
2841         }
2842
2843         return OPERATOR_RUNNING_MODAL;
2844 }
2845
2846 int WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
2847 {
2848         wm_gesture_end(C, op);
2849
2850         return OPERATOR_CANCELLED;
2851 }
2852
2853 #if 0
2854 /* template to copy from */
2855 void WM_OT_straightline_gesture(wmOperatorType *ot)
2856 {
2857         PropertyRNA *prop;
2858         
2859         ot->name= "Straight Line Gesture";
2860         ot->idname= "WM_OT_straightline_gesture";
2861         ot->description="Draw a straight line as you move the pointer";
2862         
2863         ot->invoke= WM_gesture_straightline_invoke;
2864         ot->modal= WM_gesture_straightline_modal;
2865         ot->exec= gesture_straightline_exec;
2866         
2867         ot->poll= WM_operator_winactive;
2868         
2869         WM_operator_properties_gesture_straightline(ot, 0);
2870 }
2871 #endif
2872
2873 /* *********************** radial control ****************** */
2874
2875 static const int WM_RADIAL_CONTROL_DISPLAY_SIZE = 200;
2876
2877 typedef struct {
2878         PropertyType type;
2879         PropertySubType subtype;
2880         PointerRNA ptr, col_ptr, fill_col_ptr, rot_ptr, zoom_ptr, image_id_ptr;
2881         PropertyRNA *prop, *col_prop, *fill_col_prop, *rot_prop, *zoom_prop;
2882         StructRNA *image_id_srna;
2883         float initial_value, current_value, min_value, max_value;
2884         int initial_mouse[2];
2885         unsigned int gltex;
2886         ListBase orig_paintcursors;
2887         void *cursor;
2888 } RadialControl;
2889
2890 static void radial_control_set_initial_mouse(RadialControl *rc, wmEvent *event)
2891 {
2892         float d[2] = {0, 0};
2893         float zoom[2] = {1, 1};
2894
2895         rc->initial_mouse[0]= event->x;
2896         rc->initial_mouse[1]= event->y;
2897
2898         switch(rc->subtype) {
2899         case PROP_DISTANCE:
2900                 d[0] = rc->initial_value;
2901                 break;
2902         case PROP_FACTOR:
2903                 d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * (1 - rc->initial_value);
2904                 break;
2905         case PROP_ANGLE:
2906                 d[0] = WM_RADIAL_CONTROL_DISPLAY_SIZE * cos(rc->initial_value);
2907                 d[1] = WM_RADIAL_CONTROL_DISPLAY_SIZE * sin(rc->initial_value);
2908                 break;
2909         default:
2910                 return;
2911         }
2912
2913         if(rc->zoom_prop) {
2914                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
2915                 d[0] *= zoom[0];
2916                 d[1] *= zoom[1];
2917         }
2918
2919         rc->initial_mouse[0]-= d[0];
2920         rc->initial_mouse[1]-= d[1];
2921 }
2922
2923 static void radial_control_set_tex(RadialControl *rc)
2924 {
2925         ImBuf *ibuf;
2926
2927         switch(RNA_type_to_ID_code(rc->image_id_ptr.type)) {
2928         case ID_BR:
2929                 if((ibuf = brush_gen_radial_control_imbuf(rc->image_id_ptr.data))) {
2930                         glGenTextures(1, &rc->gltex);
2931                         glBindTexture(GL_TEXTURE_2D, rc->gltex);
2932                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, ibuf->x, ibuf->y, 0,
2933                                      GL_ALPHA, GL_FLOAT, ibuf->rect_float);
2934                         MEM_freeN(ibuf->rect_float);
2935                         MEM_freeN(ibuf);
2936                 }
2937                 break;
2938         default:
2939                 break;
2940         }
2941 }
2942
2943 static void radial_control_paint_tex(RadialControl *rc, float radius, float alpha)
2944 {
2945         float col[3] = {0, 0, 0};
2946         float rot;
2947
2948         /* set fill color */
2949         if(rc->fill_col_prop)
2950                 RNA_property_float_get_array(&rc->fill_col_ptr, rc->fill_col_prop, col);
2951         glColor4f(col[0], col[1], col[2], alpha);
2952
2953         if(rc->gltex) {
2954                 glBindTexture(GL_TEXTURE_2D, rc->gltex);
2955
2956                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2957                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2958
2959                 /* set up rotation if available */
2960                 if(rc->rot_prop) {
2961                         rot = RNA_property_float_get(&rc->rot_ptr, rc->rot_prop);
2962                         glPushMatrix();
2963                         glRotatef(RAD2DEGF(rot), 0, 0, 1);
2964                 }
2965
2966                 /* draw textured quad */
2967                 glEnable(GL_TEXTURE_2D);
2968                 glBegin(GL_QUADS);
2969                 glTexCoord2f(0,0);
2970                 glVertex2f(-radius, -radius);
2971                 glTexCoord2f(1,0);
2972                 glVertex2f(radius, -radius);
2973                 glTexCoord2f(1,1);
2974                 glVertex2f(radius, radius);
2975                 glTexCoord2f(0,1);
2976                 glVertex2f(-radius, radius);
2977                 glEnd();
2978                 glDisable(GL_TEXTURE_2D);
2979
2980                 /* undo rotation */
2981                 if(rc->rot_prop)
2982                         glPopMatrix();
2983         }
2984         else {
2985                 /* flat color if no texture available */
2986                 glutil_draw_filled_arc(0, M_PI * 2, radius, 40);
2987         }
2988 }
2989
2990 static void radial_control_paint_cursor(bContext *C, int x, int y, void *customdata)
2991 {
2992         RadialControl *rc = customdata;
2993         ARegion *ar = CTX_wm_region(C);
2994         float r1=0.0f, r2=0.0f, tex_radius, alpha;
2995         float zoom[2], col[3] = {1, 1, 1};
2996
2997         switch(rc->subtype) {
2998         case PROP_DISTANCE:
2999                 r1= rc->current_value;
3000                 r2= rc->initial_value;
3001                 tex_radius= r1;
3002                 alpha = 0.75;
3003                 break;
3004         case PROP_FACTOR:
3005                 r1= (1 - rc->current_value) * WM_RADIAL_CONTROL_DISPLAY_SIZE;
3006                 r2= tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE;
3007                 alpha = rc->current_value / 2 + 0.5;
3008                 break;
3009         case PROP_ANGLE:
3010                 r1= r2= tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE;
3011                 alpha = 0.75;
3012                 break;
3013         default:
3014                 tex_radius= WM_RADIAL_CONTROL_DISPLAY_SIZE; /* note, this is a dummy value */
3015                 alpha = 0.75;
3016                 break;
3017         }
3018
3019         /* Keep cursor in the original place */
3020         x = rc->initial_mouse[0] - ar->winrct.xmin;
3021         y = rc->initial_mouse[1] - ar->winrct.ymin;
3022         glTranslatef((float)x, (float)y, 0.0f);
3023
3024         glEnable(GL_BLEND);
3025         glEnable(GL_LINE_SMOOTH);
3026
3027         /* apply zoom if available */
3028         if(rc->zoom_prop) {
3029                 RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3030                 glScalef(zoom[0], zoom[1], 1);
3031         }
3032
3033         /* draw rotated texture */
3034         radial_control_paint_tex(rc, tex_radius, alpha);
3035
3036         /* set line color */
3037         if(rc->col_prop)
3038                 RNA_property_float_get_array(&rc->col_ptr, rc->col_prop, col);
3039         glColor4f(col[0], col[1], col[2], 0.5);
3040
3041         if(rc->subtype == PROP_ANGLE) {
3042                 glPushMatrix();
3043                 /* draw original angle line */
3044                 glRotatef(RAD2DEGF(rc->initial_value), 0, 0, 1);
3045                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3046                 /* draw new angle line */
3047                 glRotatef(RAD2DEGF(rc->current_value - rc->initial_value), 0, 0, 1);
3048                 fdrawline(0.0f, 0.0f, (float)WM_RADIAL_CONTROL_DISPLAY_SIZE, 0.0f);
3049                 glPopMatrix();
3050         }
3051
3052         /* draw circles on top */
3053         glutil_draw_lined_arc(0.0, (float)(M_PI*2.0), r1, 40);
3054         glutil_draw_lined_arc(0.0, (float)(M_PI*2.0), r2, 40);
3055
3056         glDisable(GL_BLEND);
3057         glDisable(GL_LINE_SMOOTH);
3058 }
3059
3060 /* attempt to retrieve the rna pointer/property from an rna path;
3061    returns 0 for failure, 1 for success, and also 1 if property is not
3062    set */
3063 static int radial_control_get_path(PointerRNA *ctx_ptr, wmOperator *op,
3064                                    const char *name, PointerRNA *r_ptr,
3065                                    PropertyRNA **r_prop, int req_float,
3066                                    int req_length, int allow_missing)
3067 {
3068         PropertyRNA *unused_prop;
3069         int len;
3070         char *str;
3071
3072         /* get an rna string path from the operator's properties */
3073         if(!(str = RNA_string_get_alloc(op->ptr, name, NULL, 0)))
3074                 return 1;
3075
3076         if(str[0] == '\0') {
3077                 MEM_freeN(str);
3078                 return 1;
3079         }
3080
3081         if(!r_prop)
3082                 r_prop = &unused_prop;
3083
3084         /* get rna from path */
3085         if(!RNA_path_resolve(ctx_ptr, str, r_ptr, r_prop)) {
3086                 MEM_freeN(str);
3087                 if(allow_missing)
3088                         return 1;
3089                 else {
3090                         BKE_reportf(op->reports, RPT_ERROR, "Couldn't resolve path %s", name);
3091                         return 0;
3092                 }
3093         }
3094
3095         /* if property is expected to be a float, check its type */
3096         if(req_float) {
3097                 if(!(*r_prop) || (RNA_property_type(*r_prop) != PROP_FLOAT)) {
3098                         MEM_freeN(str);
3099                         BKE_reportf(op->reports, RPT_ERROR,
3100                                     "Property from path %s is not a float", name);
3101                         return 0;
3102                 }
3103         }
3104         
3105         /* check property's array length */
3106         if(*r_prop && (len = RNA_property_array_length(r_ptr, *r_prop)) != req_length) {
3107                 MEM_freeN(str);
3108                 BKE_reportf(op->reports, RPT_ERROR,
3109                             "Property from path %s has length %d instead of %d",
3110                             name, len, req_length);
3111                 return 0;
3112         }
3113
3114         /* success */
3115         MEM_freeN(str);
3116         return 1;
3117 }
3118
3119 /* initialize the rna pointers and properties using rna paths */
3120 static int radial_control_get_properties(bContext *C, wmOperator *op)
3121 {
3122         RadialControl *rc = op->customdata;
3123         PointerRNA ctx_ptr;
3124
3125         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
3126
3127         if(!radial_control_get_path(&ctx_ptr, op, "data_path", &rc->ptr, &rc->prop, 0, 0, 0))
3128                 return 0;
3129
3130         /* data path is required */
3131         if(!rc->prop)
3132                 return 0;
3133         
3134         if(!radial_control_get_path(&ctx_ptr, op, "rotation_path", &rc->rot_ptr, &rc->rot_prop, 1, 0, 0))
3135                 return 0;
3136         if(!radial_control_get_path(&ctx_ptr, op, "color_path", &rc->col_ptr, &rc->col_prop, 1, 3, 0))
3137                 return 0;
3138         if(!radial_control_get_path(&ctx_ptr, op, "fill_color_path", &rc->fill_col_ptr, &rc->fill_col_prop, 1, 3, 0))
3139                 return 0;
3140         
3141         /* slightly ugly; allow this property to not resolve
3142            correctly. needed because 3d texture paint shares the same
3143            keymap as 2d image paint */
3144         if(!radial_control_get_path(&ctx_ptr, op, "zoom_path", &rc->zoom_ptr, &rc->zoom_prop, 1, 2, 1))
3145                 return 0;
3146         
3147         if(!radial_control_get_path(&ctx_ptr, op, "image_id", &rc->image_id_ptr, NULL, 0, 0, 0))
3148                 return 0;
3149         else if(rc->image_id_ptr.data) {
3150                 /* extra check, pointer must be to an ID */
3151                 if(!RNA_struct_is_ID(rc->image_id_ptr.type)) {
3152                         BKE_report(op->reports, RPT_ERROR,
3153                                    "Pointer from path image_id is not an ID");
3154                         return 0;
3155                 }
3156         }
3157
3158         return 1;
3159 }
3160
3161 static int radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
3162 {
3163         wmWindowManager *wm;
3164         RadialControl *rc;
3165         int min_value_int, max_value_int, step_int;
3166         float step_float, precision;
3167
3168         if(!(op->customdata = rc = MEM_callocN(sizeof(RadialControl), "RadialControl")))
3169                 return OPERATOR_CANCELLED;
3170
3171         if(!radial_control_get_properties(C, op)) {
3172                 MEM_freeN(rc);
3173                 return OPERATOR_CANCELLED;
3174         }
3175
3176         /* get type, initial, min, and max values of the property */
3177         switch((rc->type = RNA_property_type(rc->prop))) {
3178         case PROP_INT:
3179                 rc->initial_value = RNA_property_int_get(&rc->ptr, rc->prop);
3180                 RNA_property_int_ui_range(&rc->ptr, rc->prop, &min_value_int,
3181                                           &max_value_int, &step_int);
3182                 rc->min_value = min_value_int;
3183                 rc->max_value = max_value_int;
3184                 break;
3185         case PROP_FLOAT:
3186                 rc->initial_value = RNA_property_float_get(&rc->ptr, rc->prop);
3187                 RNA_property_float_ui_range(&rc->ptr, rc->prop, &rc->min_value,
3188                                             &rc->max_value, &step_float, &precision);
3189                 break;
3190         default:
3191                 BKE_report(op->reports, RPT_ERROR, "Property must be an integer or a float");
3192                 MEM_freeN(rc);
3193                 return OPERATOR_CANCELLED;
3194         }
3195
3196         /* get subtype of property */
3197         rc->subtype = RNA_property_subtype(rc->prop);
3198         if(!ELEM3(rc->subtype, PROP_DISTANCE, PROP_FACTOR, PROP_ANGLE)) {
3199                 BKE_report(op->reports, RPT_ERROR, "Property must be a distance, a factor, or an angle");
3200                 MEM_freeN(rc);
3201                 return OPERATOR_CANCELLED;
3202         }
3203                 
3204         rc->current_value = rc->initial_value;
3205         radial_control_set_initial_mouse(rc, event);
3206         radial_control_set_tex(rc);
3207
3208         /* temporarily disable other paint cursors */
3209         wm = CTX_wm_manager(C);
3210         rc->orig_paintcursors = wm->paintcursors;
3211         wm->paintcursors.first = wm->paintcursors.last = NULL;
3212
3213         /* add radial control paint cursor */
3214         rc->cursor = WM_paint_cursor_activate(wm, op->type->poll,
3215                                               radial_control_paint_cursor, rc);
3216
3217         WM_event_add_modal_handler(C, op);
3218
3219         return OPERATOR_RUNNING_MODAL;
3220 }
3221
3222 static void radial_control_set_value(RadialControl *rc, float val)
3223 {
3224         switch(rc->type) {
3225         case PROP_INT:
3226                 RNA_property_int_set(&rc->ptr, rc->prop, val);
3227                 break;
3228         case PROP_FLOAT:
3229                 RNA_property_float_set(&rc->ptr, rc->prop, val);
3230                 break;
3231         default:
3232                 break;
3233         }
3234 }
3235
3236 static int radial_control_cancel(bContext *C, wmOperator *op)
3237 {
3238         RadialControl *rc = op->customdata;
3239         wmWindowManager *wm = CTX_wm_manager(C);
3240
3241         WM_paint_cursor_end(wm, rc->cursor);
3242
3243         /* restore original paint cursors */
3244         wm->paintcursors = rc->orig_paintcursors;
3245
3246         /* not sure if this is a good notifier to use;
3247            intended purpose is to update the UI so that the
3248            new value is displayed in sliders/numfields */
3249         WM_event_add_notifier(C, NC_WINDOW, NULL);
3250
3251         glDeleteTextures(1, &rc->gltex);
3252
3253         MEM_freeN(rc);
3254
3255         return OPERATOR_CANCELLED;
3256 }
3257
3258 static int radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
3259 {
3260         RadialControl *rc = op->customdata;
3261         wmWindowManager *wm;
3262         float new_value, dist, zoom[2];
3263         float delta[2], snap, ret = OPERATOR_RUNNING_MODAL;
3264
3265         /* TODO: fix hardcoded events */
3266
3267         snap = event->ctrl;
3268
3269         switch(event->type) {
3270         case MOUSEMOVE:
3271                 delta[0]= rc->initial_mouse[0] - event->x;
3272                 delta[1]= rc->initial_mouse[1] - event->y;
3273
3274                 if(rc->zoom_prop) {
3275                         RNA_property_float_get_array(&rc->zoom_ptr, rc->zoom_prop, zoom);
3276                         delta[0] /= zoom[0];
3277                         delta[1] /= zoom[1];
3278                 }
3279
3280                 dist= sqrt(delta[0]*delta[0]+delta[1]*delta[1]);
3281
3282                 /* calculate new value and apply snapping  */
3283                 switch(rc->subtype) {
3284                 case PROP_DISTANCE:
3285                         new_value = dist;
3286                         if(snap) new_value = ((int)new_value + 5) / 10*10;
3287                         break;
3288                 case PROP_FACTOR:
3289                         new_value = 1 - dist / WM_RADIAL_CONTROL_DISPLAY_SIZE;
3290                         if(snap) new_value = ((int)ceil(new_value * 10.f) * 10.0f) / 100.f;
3291                         break;
3292                 case PROP_ANGLE:
3293                         new_value = atan2(delta[1], delta[0]) + M_PI;
3294                         if(snap) new_value = DEG2RADF(((int)RAD2DEGF(new_value) + 5) / 10*10);
3295                         break;
3296                 default:
3297                         new_value = dist; /* dummy value, should this ever happen? - campbell */
3298                         break;
3299                 }
3300
3301                 /* clamp and update */
3302                 CLAMP(new_value, rc->min_value, rc->max_value);
3303                 radial_control_set_value(rc, new_value);
3304                 rc->current_value = new_value;
3305                 break;
3306