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