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