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