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