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