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