Fix typo in previous commit
[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_NUMSELECT for layer buttons */
1521         UI_block_flag_enable(block, UI_BLOCK_NUMSELECT | UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1522
1523         /* if register is not enabled, the operator gets freed on OPERATOR_FINISHED
1524          * ui_apply_but_funcs_after calls ED_undo_operator_repeate_cb and crashes */
1525         assert(op->type->flag & OPTYPE_REGISTER);
1526
1527         UI_block_func_handle_set(block, wm_block_redo_cb, arg_op);
1528         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, width, UI_UNIT_Y, 0, style);
1529
1530         if (op == WM_operator_last_redo(C))
1531                 if (!WM_operator_check_ui_enabled(C, op->type->name))
1532                         uiLayoutSetEnabled(layout, false);
1533
1534         if (op->type->flag & OPTYPE_MACRO) {
1535                 for (op = op->macro.first; op; op = op->next) {
1536                         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1537                 }
1538         }
1539         else {
1540                 uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1541         }
1542         
1543         UI_block_bounds_set_popup(block, 4, 0, 0);
1544
1545         return block;
1546 }
1547
1548 typedef struct wmOpPopUp {
1549         wmOperator *op;
1550         int width;
1551         int height;
1552         int free_op;
1553 } wmOpPopUp;
1554
1555 /* Only invoked by OK button in popups created with wm_block_dialog_create() */
1556 static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
1557 {
1558         wmWindowManager *wm = CTX_wm_manager(C);
1559         wmWindow *win = CTX_wm_window(C);
1560
1561         wmOpPopUp *data = arg1;
1562         uiBlock *block = arg2;
1563
1564         WM_operator_call_ex(C, data->op, true);
1565
1566         /* let execute handle freeing it */
1567         //data->free_op = false;
1568         //data->op = NULL;
1569
1570         /* in this case, wm_operator_ui_popup_cancel wont run */
1571         MEM_freeN(data);
1572
1573         /* check window before 'block->handle' incase the
1574          * popup execution closed the window and freed the block. see T44688. */
1575         if (BLI_findindex(&wm->windows, win) != -1) {
1576                 UI_popup_block_close(C, win, block);
1577         }
1578 }
1579
1580 static void dialog_check_cb(bContext *C, void *op_ptr, void *UNUSED(arg))
1581 {
1582         wmOperator *op = op_ptr;
1583         if (op->type->check) {
1584                 if (op->type->check(C, op)) {
1585                         /* check for popup and re-layout buttons */
1586                         ARegion *ar_menu = CTX_wm_menu(C);
1587                         if (ar_menu) {
1588                                 ED_region_tag_refresh_ui(ar_menu);
1589                         }
1590                 }
1591         }
1592 }
1593
1594 /* Dialogs are popups that require user verification (click OK) before exec */
1595 static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
1596 {
1597         wmOpPopUp *data = userData;
1598         wmOperator *op = data->op;
1599         uiBlock *block;
1600         uiLayout *layout;
1601         uiStyle *style = UI_style_get();
1602
1603         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1604         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1605
1606         /* intentionally don't use 'UI_BLOCK_MOVEMOUSE_QUIT', some dialogues have many items
1607          * where quitting by accident is very annoying */
1608         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN);
1609
1610         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1611         
1612         UI_block_func_set(block, dialog_check_cb, op, NULL);
1613
1614         uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
1615         
1616         /* clear so the OK button is left alone */
1617         UI_block_func_set(block, NULL, NULL, NULL);
1618
1619         /* new column so as not to interfere with custom layouts [#26436] */
1620         {
1621                 uiBlock *col_block;
1622                 uiLayout *col;
1623                 uiBut *btn;
1624
1625                 col = uiLayoutColumn(layout, false);
1626                 col_block = uiLayoutGetBlock(col);
1627                 /* Create OK button, the callback of which will execute op */
1628                 btn = uiDefBut(col_block, UI_BTYPE_BUT, 0, IFACE_("OK"), 0, -30, 0, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
1629                 UI_but_func_set(btn, dialog_exec_cb, data, col_block);
1630         }
1631
1632         /* center around the mouse */
1633         UI_block_bounds_set_popup(block, 4, data->width / -2, data->height / 2);
1634
1635         return block;
1636 }
1637
1638 static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
1639 {
1640         wmOpPopUp *data = userData;
1641         wmOperator *op = data->op;
1642         uiBlock *block;
1643         uiLayout *layout;
1644         uiStyle *style = UI_style_get();
1645
1646         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
1647         UI_block_flag_disable(block, UI_BLOCK_LOOP);
1648         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_MOVEMOUSE_QUIT);
1649
1650         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
1651
1652         /* since ui is defined the auto-layout args are not used */
1653         uiLayoutOperatorButs(C, layout, op, NULL, 'V', 0);
1654
1655         UI_block_bounds_set_popup(block, 4, 0, 0);
1656
1657         return block;
1658 }
1659
1660 static void wm_operator_ui_popup_cancel(struct bContext *C, void *userData)
1661 {
1662         wmOpPopUp *data = userData;
1663         wmOperator *op = data->op;
1664
1665         if (op) {
1666                 if (op->type->cancel) {
1667                         op->type->cancel(C, op);
1668                 }
1669
1670                 if (data->free_op) {
1671                         WM_operator_free(op);
1672                 }
1673         }
1674
1675         MEM_freeN(data);
1676 }
1677
1678 static void wm_operator_ui_popup_ok(struct bContext *C, void *arg, int retval)
1679 {
1680         wmOpPopUp *data = arg;
1681         wmOperator *op = data->op;
1682
1683         if (op && retval > 0)
1684                 WM_operator_call_ex(C, op, true);
1685         
1686         MEM_freeN(data);
1687 }
1688
1689 int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
1690 {
1691         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_ui_popup");
1692         data->op = op;
1693         data->width = width;
1694         data->height = height;
1695         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1696         UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data);
1697         return OPERATOR_RUNNING_MODAL;
1698 }
1699
1700 /**
1701  * For use by #WM_operator_props_popup_call, #WM_operator_props_popup only.
1702  *
1703  * \note operator menu needs undo flag enabled, for redo callback */
1704 static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
1705                                       const bool do_call, const bool do_redo)
1706 {
1707         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1708                 BKE_reportf(op->reports, RPT_ERROR,
1709                             "Operator '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1710                 return OPERATOR_CANCELLED;
1711         }
1712
1713         if (do_redo) {
1714                 if ((op->type->flag & OPTYPE_UNDO) == 0) {
1715                         BKE_reportf(op->reports, RPT_ERROR,
1716                                     "Operator '%s' does not have undo enabled, incorrect invoke function", op->type->idname);
1717                         return OPERATOR_CANCELLED;
1718                 }
1719         }
1720
1721         /* if we don't have global undo, we can't do undo push for automatic redo,
1722          * so we require manual OK clicking in this popup */
1723         if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
1724                 return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
1725
1726         UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op);
1727
1728         if (do_call)
1729                 wm_block_redo_cb(C, op, 0);
1730
1731         return OPERATOR_RUNNING_MODAL;
1732 }
1733
1734 /**
1735  * Same as #WM_operator_props_popup but don't use operator redo.
1736  * just wraps #WM_operator_props_dialog_popup.
1737  */
1738 int WM_operator_props_popup_confirm(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1739 {
1740         return wm_operator_props_popup_ex(C, op, false, false);
1741 }
1742
1743 /**
1744  * Same as #WM_operator_props_popup but call the operator first,
1745  * This way - the button values correspond to the result of the operator.
1746  * Without this, first access to a button will make the result jump, see T32452.
1747  */
1748 int WM_operator_props_popup_call(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1749 {
1750         return wm_operator_props_popup_ex(C, op, true, true);
1751 }
1752
1753 int WM_operator_props_popup(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1754 {
1755         return wm_operator_props_popup_ex(C, op, false, true);
1756 }
1757
1758 int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int height)
1759 {
1760         wmOpPopUp *data = MEM_callocN(sizeof(wmOpPopUp), "WM_operator_props_dialog_popup");
1761         
1762         data->op = op;
1763         data->width = width;
1764         data->height = height;
1765         data->free_op = true; /* if this runs and gets registered we may want not to free it */
1766
1767         /* op is not executed until popup OK but is clicked */
1768         UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data);
1769
1770         return OPERATOR_RUNNING_MODAL;
1771 }
1772
1773 int WM_operator_redo_popup(bContext *C, wmOperator *op)
1774 {
1775         /* CTX_wm_reports(C) because operator is on stack, not active in event system */
1776         if ((op->type->flag & OPTYPE_REGISTER) == 0) {
1777                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR,
1778                             "Operator redo '%s' does not have register enabled, incorrect invoke function", op->type->idname);
1779                 return OPERATOR_CANCELLED;
1780         }
1781         if (op->type->poll && op->type->poll(C) == 0) {
1782                 BKE_reportf(CTX_wm_reports(C), RPT_ERROR, "Operator redo '%s': wrong context", op->type->idname);
1783                 return OPERATOR_CANCELLED;
1784         }
1785         
1786         UI_popup_block_invoke(C, wm_block_create_redo, op);
1787
1788         return OPERATOR_CANCELLED;
1789 }
1790
1791 /* ***************** Debug menu ************************* */
1792
1793 static int wm_debug_menu_exec(bContext *C, wmOperator *op)
1794 {
1795         G.debug_value = RNA_int_get(op->ptr, "debug_value");
1796         ED_screen_refresh(CTX_wm_manager(C), CTX_wm_window(C));
1797         WM_event_add_notifier(C, NC_WINDOW, NULL);
1798
1799         return OPERATOR_FINISHED;
1800 }
1801
1802 static int wm_debug_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1803 {
1804         RNA_int_set(op->ptr, "debug_value", G.debug_value);
1805         return WM_operator_props_dialog_popup(C, op, 9 * UI_UNIT_X, UI_UNIT_Y);
1806 }
1807
1808 static void WM_OT_debug_menu(wmOperatorType *ot)
1809 {
1810         ot->name = "Debug Menu";
1811         ot->idname = "WM_OT_debug_menu";
1812         ot->description = "Open a popup to set the debug level";
1813         
1814         ot->invoke = wm_debug_menu_invoke;
1815         ot->exec = wm_debug_menu_exec;
1816         ot->poll = WM_operator_winactive;
1817         
1818         RNA_def_int(ot->srna, "debug_value", 0, SHRT_MIN, SHRT_MAX, "Debug Value", "", -10000, 10000);
1819 }
1820
1821 /* ***************** Operator defaults ************************* */
1822 static int wm_operator_defaults_exec(bContext *C, wmOperator *op)
1823 {
1824         PointerRNA ptr = CTX_data_pointer_get_type(C, "active_operator", &RNA_Operator);
1825
1826         if (!ptr.data) {
1827                 BKE_report(op->reports, RPT_ERROR, "No operator in context");
1828                 return OPERATOR_CANCELLED;
1829         }
1830
1831         WM_operator_properties_reset((wmOperator *)ptr.data);
1832         return OPERATOR_FINISHED;
1833 }
1834
1835 /* used by operator preset menu. pre-2.65 this was a 'Reset' button */
1836 static void WM_OT_operator_defaults(wmOperatorType *ot)
1837 {
1838         ot->name = "Restore Defaults";
1839         ot->idname = "WM_OT_operator_defaults";
1840         ot->description = "Set the active operator to its default values";
1841
1842         ot->exec = wm_operator_defaults_exec;
1843
1844         ot->flag = OPTYPE_INTERNAL;
1845 }
1846
1847 /* ***************** Splash Screen ************************* */
1848
1849 static void wm_block_splash_close(bContext *C, void *arg_block, void *UNUSED(arg))
1850 {
1851         wmWindow *win = CTX_wm_window(C);
1852         UI_popup_block_close(C, win, arg_block);
1853 }
1854
1855 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *arg_unused);
1856
1857 static void wm_block_splash_refreshmenu(bContext *C, void *UNUSED(arg_block), void *UNUSED(arg))
1858 {
1859         ARegion *ar_menu = CTX_wm_menu(C);
1860         ED_region_tag_refresh_ui(ar_menu);
1861 }
1862
1863 static int wm_resource_check_prev(void)
1864 {
1865
1866         const char *res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION, true);
1867
1868         // if (res) printf("USER: %s\n", res);
1869
1870 #if 0 /* ignore the local folder */
1871         if (res == NULL) {
1872                 /* with a local dir, copying old files isn't useful since local dir get priority for config */
1873                 res = BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_LOCAL, BLENDER_VERSION, true);
1874         }
1875 #endif
1876
1877         // if (res) printf("LOCAL: %s\n", res);
1878         if (res) {
1879                 return false;
1880         }
1881         else {
1882                 return (BKE_appdir_folder_id_version(BLENDER_RESOURCE_PATH_USER, BLENDER_VERSION - 1, true) != NULL);
1883         }
1884 }
1885
1886 static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(arg))
1887 {
1888         uiBlock *block;
1889         uiBut *but;
1890         uiLayout *layout, *split, *col;
1891         uiStyle *style = UI_style_get();
1892         const struct RecentFile *recent;
1893         int i;
1894         MenuType *mt = WM_menutype_find("USERPREF_MT_splash", true);
1895         char url[96];
1896         const char *version_suffix = NULL;
1897
1898 #ifndef WITH_HEADLESS
1899         extern char datatoc_splash_png[];
1900         extern int datatoc_splash_png_size;
1901
1902         extern char datatoc_splash_2x_png[];
1903         extern int datatoc_splash_2x_png_size;
1904         ImBuf *ibuf;
1905 #else
1906         ImBuf *ibuf = NULL;
1907 #endif
1908
1909 #ifdef WITH_BUILDINFO
1910         int label_delta = 0;
1911         int hash_width, date_width;
1912         char date_buf[128] = "\0";
1913         char hash_buf[128] = "\0";
1914         extern unsigned long build_commit_timestamp;
1915         extern char build_hash[], build_commit_date[], build_commit_time[], build_branch[];
1916
1917         /* Builds made from tag only shows tag sha */
1918         BLI_snprintf(hash_buf, sizeof(hash_buf), "Hash: %s", build_hash);
1919         BLI_snprintf(date_buf, sizeof(date_buf), "Date: %s %s", build_commit_date, build_commit_time);
1920         
1921         BLF_size(style->widgetlabel.uifont_id, style->widgetlabel.points, U.pixelsize * U.dpi);
1922         hash_width = (int)BLF_width(style->widgetlabel.uifont_id, hash_buf, sizeof(hash_buf)) + U.widget_unit;
1923         date_width = (int)BLF_width(style->widgetlabel.uifont_id, date_buf, sizeof(date_buf)) + U.widget_unit;
1924 #endif  /* WITH_BUILDINFO */
1925
1926 #ifndef WITH_HEADLESS
1927         if (U.pixelsize == 2) {
1928                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_2x_png,
1929                                              datatoc_splash_2x_png_size, IB_rect, NULL, "<splash screen>");
1930         }
1931         else {
1932                 ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
1933                                              datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
1934         }
1935 #endif
1936
1937         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1938
1939         /* note on UI_BLOCK_NO_WIN_CLIP, the window size is not always synchronized
1940          * with the OS when the splash shows, window clipping in this case gives
1941          * ugly results and clipping the splash isn't useful anyway, just disable it [#32938] */
1942         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_NO_WIN_CLIP);
1943
1944         /* XXX splash scales with pixelsize, should become widget-units */
1945         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 */
1946         UI_but_func_set(but, wm_block_splash_close, block, NULL);
1947         UI_block_func_set(block, wm_block_splash_refreshmenu, block, NULL);
1948
1949         /* label for 'a' bugfix releases, or 'Release Candidate 1'...
1950          *  avoids recreating splash for version updates */
1951         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "rc")) {
1952                 version_suffix = "Release Candidate";
1953         }
1954         else if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
1955                 version_suffix = STRINGIFY(BLENDER_VERSION_CHAR);
1956         }
1957         if (version_suffix != NULL && version_suffix[0]) {
1958                 /* placed after the version number in the image,
1959                  * placing y is tricky to match baseline */
1960                 int x = 260 - (2 * UI_DPI_WINDOW_FAC);
1961                 int y = 242 + (4 * UI_DPI_WINDOW_FAC);
1962                 int w = 240;
1963
1964                 /* hack to have text draw 'text_sel' */
1965                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1966                 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);
1967                 /* XXX, set internal flag - UI_SELECT */
1968                 UI_but_flag_enable(but, 1);
1969                 UI_block_emboss_set(block, UI_EMBOSS);
1970         }
1971
1972 #ifdef WITH_BUILDINFO
1973         if (build_commit_timestamp != 0) {
1974                 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);
1975                 label_delta = 12;
1976         }
1977         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);
1978
1979         if (!STREQ(build_branch, "master")) {
1980                 char branch_buf[128] = "\0";
1981                 int branch_width;
1982                 BLI_snprintf(branch_buf, sizeof(branch_buf), "Branch: %s", build_branch);
1983                 branch_width = (int)BLF_width(style->widgetlabel.uifont_id, branch_buf, sizeof(branch_buf)) + U.widget_unit;
1984                 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);
1985         }
1986 #endif  /* WITH_BUILDINFO */
1987         
1988         layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.pixelsize * 480, U.pixelsize * 110, 0, style);
1989         
1990         UI_block_emboss_set(block, UI_EMBOSS);
1991         /* show the splash menu (containing interaction presets), using python */
1992         if (mt) {
1993                 Menu menu = {NULL};
1994                 menu.layout = layout;
1995                 menu.type = mt;
1996                 mt->draw(C, &menu);
1997
1998 //              wmWindowManager *wm = CTX_wm_manager(C);
1999 //              uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
2000         }
2001         
2002         UI_block_emboss_set(block, UI_EMBOSS_PULLDOWN);
2003         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_REGION_WIN);
2004         
2005         split = uiLayoutSplit(layout, 0.0f, false);
2006         col = uiLayoutColumn(split, false);
2007         uiItemL(col, IFACE_("Links"), ICON_NONE);
2008 #if 0
2009         uiItemStringO(col, IFACE_("Support an Open Animation Movie"), ICON_URL, "WM_OT_url_open", "url",
2010                       "https://cloud.blender.org/join");
2011 #endif
2012         uiItemStringO(col, IFACE_("Donations"), ICON_URL, "WM_OT_url_open", "url",
2013                       "http://www.blender.org/foundation/donation-payment/");
2014         uiItemStringO(col, IFACE_("Credits"), ICON_URL, "WM_OT_url_open", "url",
2015                       "http://www.blender.org/about/credits/");
2016         BLI_snprintf(url, sizeof(url), "http://wiki.blender.org/index.php/Dev:Ref/Release_Notes/%d.%d",
2017                      BLENDER_VERSION / 100, BLENDER_VERSION % 100);
2018         uiItemStringO(col, IFACE_("Release Log"), ICON_URL, "WM_OT_url_open", "url", url);
2019         uiItemStringO(col, IFACE_("Manual"), ICON_URL, "WM_OT_url_open", "url",
2020                       "http://www.blender.org/manual");
2021         uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
2022         if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
2023                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d"
2024                                                STRINGIFY(BLENDER_VERSION_CHAR) "_release",
2025                              BLENDER_VERSION / 100, BLENDER_VERSION % 100);
2026         }
2027         else {
2028                 BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d_%d",
2029                              BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
2030         }
2031         uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
2032         uiItemL(col, "", ICON_NONE);
2033
2034         col = uiLayoutColumn(split, false);
2035
2036         if (wm_resource_check_prev()) {
2037                 uiItemO(col, NULL, ICON_NEW, "WM_OT_copy_prev_settings");
2038                 uiItemS(col);
2039         }
2040
2041         uiItemL(col, IFACE_("Recent"), ICON_NONE);
2042         for (recent = G.recent_files.first, i = 0; (i < 5) && (recent); recent = recent->next, i++) {
2043                 const char *filename = BLI_path_basename(recent->filepath);
2044                 uiItemStringO(col, filename,
2045                               BLO_has_bfile_extension(filename) ? ICON_FILE_BLEND : ICON_FILE_BACKUP,
2046                               "WM_OT_open_mainfile", "filepath", recent->filepath);
2047         }
2048
2049         uiItemS(col);
2050         uiItemO(col, NULL, ICON_RECOVER_LAST, "WM_OT_recover_last_session");
2051         uiItemL(col, "", ICON_NONE);
2052         
2053         mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
2054         if (mt) {
2055                 Menu menu = {NULL};
2056                 menu.layout = uiLayoutColumn(layout, false);
2057                 menu.type = mt;
2058                 mt->draw(C, &menu);
2059         }
2060
2061         UI_block_bounds_set_centered(block, 0);
2062         
2063         return block;
2064 }
2065
2066 static int wm_splash_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
2067 {
2068         UI_popup_block_invoke(C, wm_block_create_splash, NULL);
2069         
2070         return OPERATOR_FINISHED;
2071 }
2072
2073 static void WM_OT_splash(wmOperatorType *ot)
2074 {
2075         ot->name = "Splash Screen";
2076         ot->idname = "WM_OT_splash";
2077         ot->description = "Open the splash screen with release info";
2078         
2079         ot->invoke = wm_splash_invoke;
2080         ot->poll = WM_operator_winactive;
2081 }
2082
2083
2084 /* ***************** Search menu ************************* */
2085 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *UNUSED(arg_op))
2086 {
2087         static char search[256] = "";
2088         wmEvent event;
2089         wmWindow *win = CTX_wm_window(C);
2090         uiBlock *block;
2091         uiBut *but;
2092         
2093         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
2094         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
2095         
2096         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, UI_searchbox_size_x(), UI_UNIT_Y, 0, 0, "");
2097         UI_but_func_operator_search(but);
2098         
2099         /* fake button, it holds space for search items */
2100         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);
2101         
2102         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
2103         
2104         wm_event_init_from_window(win, &event);
2105         event.type = EVT_BUT_OPEN;
2106         event.val = KM_PRESS;
2107         event.customdata = but;
2108         event.customdatafree = false;
2109         wm_event_add(win, &event);
2110         
2111         return block;
2112 }
2113
2114 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2115 {
2116         return OPERATOR_FINISHED;
2117 }
2118
2119 static int wm_search_menu_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2120 {
2121         UI_popup_block_invoke(C, wm_block_search_menu, op);
2122         
2123         return OPERATOR_INTERFACE;
2124 }
2125
2126 /* op->poll */
2127 static int wm_search_menu_poll(bContext *C)
2128 {
2129         if (CTX_wm_window(C) == NULL) {
2130                 return 0;
2131         }
2132         else {
2133                 ScrArea *sa = CTX_wm_area(C);
2134                 if (sa) {
2135                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
2136                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
2137                 }
2138                 else {
2139                         Object *editob = CTX_data_edit_object(C);
2140                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
2141                 }
2142         }
2143         return 1;
2144 }
2145
2146 static void WM_OT_search_menu(wmOperatorType *ot)
2147 {
2148         ot->name = "Search Menu";
2149         ot->idname = "WM_OT_search_menu";
2150         ot->description = "Pop-up a search menu over all available operators in current context";
2151         
2152         ot->invoke = wm_search_menu_invoke;
2153         ot->exec = wm_search_menu_exec;
2154         ot->poll = wm_search_menu_poll;
2155 }
2156
2157 static int wm_call_menu_exec(bContext *C, wmOperator *op)
2158 {
2159         char idname[BKE_ST_MAXNAME];
2160         RNA_string_get(op->ptr, "name", idname);
2161
2162         return UI_popup_menu_invoke(C, idname, op->reports);
2163 }
2164
2165 static void WM_OT_call_menu(wmOperatorType *ot)
2166 {
2167         ot->name = "Call Menu";
2168         ot->idname = "WM_OT_call_menu";
2169         ot->description = "Call (draw) a pre-defined menu";
2170
2171         ot->exec = wm_call_menu_exec;
2172         ot->poll = WM_operator_winactive;
2173
2174         ot->flag = OPTYPE_INTERNAL;
2175
2176         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
2177 }
2178
2179 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2180 {
2181         char idname[BKE_ST_MAXNAME];
2182         RNA_string_get(op->ptr, "name", idname);
2183
2184         return UI_pie_menu_invoke(C, idname, event);
2185 }
2186
2187 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
2188 {
2189         char idname[BKE_ST_MAXNAME];
2190         RNA_string_get(op->ptr, "name", idname);
2191
2192         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
2193 }
2194
2195 static void WM_OT_call_menu_pie(wmOperatorType *ot)
2196 {
2197         ot->name = "Call Pie Menu";
2198         ot->idname = "WM_OT_call_menu_pie";
2199         ot->description = "Call (draw) a pre-defined pie menu";
2200
2201         ot->invoke = wm_call_pie_menu_invoke;
2202         ot->exec = wm_call_pie_menu_exec;
2203         ot->poll = WM_operator_winactive;
2204
2205         ot->flag = OPTYPE_INTERNAL;
2206
2207         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
2208 }
2209
2210 /* ************ window / screen operator definitions ************** */
2211
2212 /* this poll functions is needed in place of WM_operator_winactive
2213  * while it crashes on full screen */
2214 static int wm_operator_winactive_normal(bContext *C)
2215 {
2216         wmWindow *win = CTX_wm_window(C);
2217
2218         if (win == NULL || win->screen == NULL || win->screen->state != SCREENNORMAL)
2219                 return 0;
2220
2221         return 1;
2222 }
2223
2224 static void WM_OT_window_duplicate(wmOperatorType *ot)
2225 {
2226         ot->name = "Duplicate Window";
2227         ot->idname = "WM_OT_window_duplicate";
2228         ot->description = "Duplicate the current Blender window";
2229                 
2230         ot->exec = wm_window_duplicate_exec;
2231         ot->poll = wm_operator_winactive_normal;
2232 }
2233
2234 static void WM_OT_save_homefile(wmOperatorType *ot)
2235 {
2236         ot->name = "Save Startup File";
2237         ot->idname = "WM_OT_save_homefile";
2238         ot->description = "Make the current file the default .blend file, includes preferences";
2239                 
2240         ot->invoke = WM_operator_confirm;
2241         ot->exec = wm_homefile_write_exec;
2242 }
2243
2244 static int wm_userpref_autoexec_add_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2245 {
2246         bPathCompare *path_cmp = MEM_callocN(sizeof(bPathCompare), "bPathCompare");
2247         BLI_addtail(&U.autoexec_paths, path_cmp);
2248         return OPERATOR_FINISHED;
2249 }
2250
2251 static void WM_OT_userpref_autoexec_path_add(wmOperatorType *ot)
2252 {
2253         ot->name = "Add Autoexec Path";
2254         ot->idname = "WM_OT_userpref_autoexec_path_add";
2255         ot->description = "Add path to exclude from autoexecution";
2256
2257         ot->exec = wm_userpref_autoexec_add_exec;
2258
2259         ot->flag = OPTYPE_INTERNAL;
2260 }
2261
2262 static int wm_userpref_autoexec_remove_exec(bContext *UNUSED(C), wmOperator *op)
2263 {
2264         const int index = RNA_int_get(op->ptr, "index");
2265         bPathCompare *path_cmp = BLI_findlink(&U.autoexec_paths, index);
2266         if (path_cmp) {
2267                 BLI_freelinkN(&U.autoexec_paths, path_cmp);
2268         }
2269         return OPERATOR_FINISHED;
2270 }
2271
2272 static void WM_OT_userpref_autoexec_path_remove(wmOperatorType *ot)
2273 {
2274         ot->name = "Remove Autoexec Path";
2275         ot->idname = "WM_OT_userpref_autoexec_path_remove";
2276         ot->description = "Remove path to exclude from autoexecution";
2277
2278         ot->exec = wm_userpref_autoexec_remove_exec;
2279
2280         ot->flag = OPTYPE_INTERNAL;
2281
2282         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
2283 }
2284
2285 static void WM_OT_save_userpref(wmOperatorType *ot)
2286 {
2287         ot->name = "Save User Settings";
2288         ot->idname = "WM_OT_save_userpref";
2289         ot->description = "Save user preferences separately, overrides startup file preferences";
2290         
2291         ot->invoke = WM_operator_confirm;
2292         ot->exec = wm_userpref_write_exec;
2293 }
2294
2295 static void WM_OT_read_history(wmOperatorType *ot)
2296 {
2297         ot->name = "Reload History File";
2298         ot->idname = "WM_OT_read_history";
2299         ot->description = "Reloads history and bookmarks";
2300
2301         ot->invoke = WM_operator_confirm;
2302         ot->exec = wm_history_read_exec;
2303
2304         /* this operator is only used for loading settings from a previous blender install */
2305         ot->flag = OPTYPE_INTERNAL;
2306 }
2307
2308 static void WM_OT_read_homefile(wmOperatorType *ot)
2309 {
2310         PropertyRNA *prop;
2311         ot->name = "Reload Start-Up File";
2312         ot->idname = "WM_OT_read_homefile";
2313         ot->description = "Open the default file (doesn't save the current file)";
2314         
2315         ot->invoke = WM_operator_confirm;
2316         ot->exec = wm_homefile_read_exec;
2317
2318         prop = RNA_def_string_file_path(ot->srna, "filepath", NULL,
2319                                         FILE_MAX, "File Path", 
2320                                         "Path to an alternative start-up file");
2321         RNA_def_property_flag(prop, PROP_HIDDEN);
2322
2323         /* So scripts can use an alternative start-up file without the UI */
2324         prop = RNA_def_boolean(ot->srna, "load_ui", true, "Load UI",
2325                                "Load user interface setup from the .blend file");
2326         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2327
2328         /* omit poll to run in background mode */
2329 }
2330
2331 static void WM_OT_read_factory_settings(wmOperatorType *ot)
2332 {
2333         ot->name = "Load Factory Settings";
2334         ot->idname = "WM_OT_read_factory_settings";
2335         ot->description = "Load default file and user preferences";
2336         
2337         ot->invoke = WM_operator_confirm;
2338         ot->exec = wm_homefile_read_exec;
2339         /* omit poll to run in background mode */
2340 }
2341
2342 /* *************** open file **************** */
2343
2344 /**
2345  * Wrap #WM_file_read, shared by file reading operators.
2346  */
2347 static bool wm_file_read_opwrap(bContext *C, const char *filepath, ReportList *reports,
2348                                 const bool autoexec_init)
2349 {
2350         bool success;
2351
2352         /* XXX wm in context is not set correctly after WM_file_read -> crash */
2353         /* do it before for now, but is this correct with multiple windows? */
2354         WM_event_add_notifier(C, NC_WINDOW, NULL);
2355
2356         if (autoexec_init) {
2357                 WM_file_autoexec_init(filepath);
2358         }
2359
2360         success = WM_file_read(C, filepath, reports);
2361
2362         return success;
2363 }
2364
2365 /* currently fits in a pointer */
2366 struct FileRuntime {
2367         bool is_untrusted;
2368 };
2369
2370 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2371 {
2372         const char *openname = G.main->name;
2373
2374         if (CTX_wm_window(C) == NULL) {
2375                 /* in rare cases this could happen, when trying to invoke in background
2376                  * mode on load for example. Don't use poll for this because exec()
2377                  * can still run without a window */
2378                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
2379                 return OPERATOR_CANCELLED;
2380         }
2381
2382         /* if possible, get the name of the most recently used .blend file */
2383         if (G.recent_files.first) {
2384                 struct RecentFile *recent = G.recent_files.first;
2385                 openname = recent->filepath;
2386         }
2387
2388         RNA_string_set(op->ptr, "filepath", openname);
2389         wm_open_init_load_ui(op, true);
2390         wm_open_init_use_scripts(op, true);
2391         op->customdata = NULL;
2392
2393         WM_event_add_fileselect(C, op);
2394
2395         return OPERATOR_RUNNING_MODAL;
2396 }
2397
2398 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
2399 {
2400         char filepath[FILE_MAX];
2401         bool success;
2402
2403         RNA_string_get(op->ptr, "filepath", filepath);
2404
2405         /* re-use last loaded setting so we can reload a file without changing */
2406         wm_open_init_load_ui(op, false);
2407         wm_open_init_use_scripts(op, false);
2408
2409         if (RNA_boolean_get(op->ptr, "load_ui"))
2410                 G.fileflags &= ~G_FILE_NO_UI;
2411         else
2412                 G.fileflags |= G_FILE_NO_UI;
2413                 
2414         if (RNA_boolean_get(op->ptr, "use_scripts"))
2415                 G.f |= G_SCRIPT_AUTOEXEC;
2416         else
2417                 G.f &= ~G_SCRIPT_AUTOEXEC;
2418         
2419         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
2420
2421         /* for file open also popup for warnings, not only errors */
2422         BKE_report_print_level_set(op->reports, RPT_WARNING);
2423
2424         if (success) {
2425                 return OPERATOR_FINISHED;
2426         }
2427         else {
2428                 return OPERATOR_CANCELLED;
2429         }
2430 }
2431
2432 static bool wm_open_mainfile_check(bContext *UNUSED(C), wmOperator *op)
2433 {
2434         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
2435         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "use_scripts");
2436         bool is_untrusted = false;
2437         char path[FILE_MAX];
2438         char *lslash;
2439
2440         RNA_string_get(op->ptr, "filepath", path);
2441
2442         /* get the dir */
2443         lslash = (char *)BLI_last_slash(path);
2444         if (lslash) *(lslash + 1) = '\0';
2445
2446         if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) {
2447                 if (BKE_autoexec_match(path) == true) {
2448                         RNA_property_boolean_set(op->ptr, prop, false);
2449                         is_untrusted = true;
2450                 }
2451         }
2452
2453         if (file_info) {
2454                 file_info->is_untrusted = is_untrusted;
2455         }
2456
2457         return is_untrusted;
2458 }
2459
2460 static void wm_open_mainfile_ui(bContext *UNUSED(C), wmOperator *op)
2461 {
2462         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
2463         uiLayout *layout = op->layout;
2464         uiLayout *col = op->layout;
2465         const char *autoexec_text;
2466
2467         uiItemR(layout, op->ptr, "load_ui", 0, NULL, ICON_NONE);
2468
2469         col = uiLayoutColumn(layout, false);
2470         if (file_info->is_untrusted) {
2471                 autoexec_text = IFACE_("Trusted Source [Untrusted Path]");
2472                 uiLayoutSetActive(col, false);
2473                 uiLayoutSetEnabled(col, false);
2474         }
2475         else {
2476                 autoexec_text = IFACE_("Trusted Source");
2477         }
2478
2479         uiItemR(col, op->ptr, "use_scripts", 0, autoexec_text, ICON_NONE);
2480 }
2481
2482 static void WM_OT_open_mainfile(wmOperatorType *ot)
2483 {
2484         ot->name = "Open Blender File";
2485         ot->idname = "WM_OT_open_mainfile";
2486         ot->description = "Open a Blender file";
2487
2488         ot->invoke = wm_open_mainfile_invoke;
2489         ot->exec = wm_open_mainfile_exec;
2490         ot->check = wm_open_mainfile_check;
2491         ot->ui = wm_open_mainfile_ui;
2492         /* omit window poll so this can work in background mode */
2493
2494         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
2495                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
2496
2497         RNA_def_boolean(ot->srna, "load_ui", true, "Load UI", "Load user interface setup in the .blend file");
2498         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
2499                         "Allow .blend file to execute scripts automatically, default available from system preferences");
2500 }
2501
2502
2503 /* *************** revert file **************** */
2504
2505 static int wm_revert_mainfile_exec(bContext *C, wmOperator *op)
2506 {
2507         bool success;
2508
2509         wm_open_init_use_scripts(op, false);
2510
2511         if (RNA_boolean_get(op->ptr, "use_scripts"))
2512                 G.f |= G_SCRIPT_AUTOEXEC;
2513         else
2514                 G.f &= ~G_SCRIPT_AUTOEXEC;
2515
2516         success = wm_file_read_opwrap(C, G.main->name, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
2517
2518         if (success) {
2519                 return OPERATOR_FINISHED;
2520         }
2521         else {
2522                 return OPERATOR_CANCELLED;
2523         }
2524 }
2525
2526 static int wm_revert_mainfile_poll(bContext *UNUSED(C))
2527 {
2528         return G.relbase_valid;
2529 }
2530
2531 static void WM_OT_revert_mainfile(wmOperatorType *ot)
2532 {
2533         ot->name = "Revert";
2534         ot->idname = "WM_OT_revert_mainfile";
2535         ot->description = "Reload the saved file";
2536         ot->invoke = WM_operator_confirm;
2537
2538         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
2539                         "Allow .blend file to execute scripts automatically, default available from system preferences");
2540
2541         ot->exec = wm_revert_mainfile_exec;
2542         ot->poll = wm_revert_mainfile_poll;
2543 }
2544
2545 /* **************** link/append *************** */
2546
2547 static int wm_link_append_poll(bContext *C)
2548 {
2549         if (WM_operator_winactive(C)) {
2550                 /* linking changes active object which is pretty useful in general,
2551                  * but which totally confuses edit mode (i.e. it becoming not so obvious
2552                  * to leave from edit mode and invalid tools in toolbar might be displayed)
2553                  * so disable link/append when in edit mode (sergey) */
2554                 if (CTX_data_edit_object(C))
2555                         return 0;
2556
2557                 return 1;
2558         }
2559
2560         return 0;
2561 }
2562
2563 static int wm_link_append_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2564 {
2565         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2566                 return WM_operator_call_notest(C, op);
2567         }
2568         else {
2569                 /* XXX TODO solve where to get last linked library from */
2570                 if (G.lib[0] != '\0') {
2571                         RNA_string_set(op->ptr, "filepath", G.lib);
2572                 }
2573                 else if (G.relbase_valid) {
2574                         char path[FILE_MAX];
2575                         BLI_strncpy(path, G.main->name, sizeof(G.main->name));
2576                         BLI_parent_dir(path);
2577                         RNA_string_set(op->ptr, "filepath", path);
2578                 }
2579                 WM_event_add_fileselect(C, op);
2580                 return OPERATOR_RUNNING_MODAL;
2581         }
2582 }
2583
2584 static short wm_link_append_flag(wmOperator *op)
2585 {
2586         short flag = 0;
2587
2588         if (RNA_boolean_get(op->ptr, "autoselect")) flag |= FILE_AUTOSELECT;
2589         if (RNA_boolean_get(op->ptr, "active_layer")) flag |= FILE_ACTIVELAY;
2590         if (RNA_struct_find_property(op->ptr, "relative_path") && RNA_boolean_get(op->ptr, "relative_path")) flag |= FILE_RELPATH;
2591         if (RNA_boolean_get(op->ptr, "link")) flag |= FILE_LINK;
2592         if (RNA_boolean_get(op->ptr, "instance_groups")) flag |= FILE_GROUP_INSTANCE;
2593
2594         return flag;
2595 }
2596
2597 static int wm_link_append_exec(bContext *C, wmOperator *op)
2598 {
2599         Main *bmain = CTX_data_main(C);
2600         Scene *scene = CTX_data_scene(C);
2601         Main *mainl = NULL;
2602         BlendHandle *bh;
2603         Library *lib;
2604         PropertyRNA *prop;
2605         char name[FILE_MAX], dir[FILE_MAX], libname[FILE_MAX], group[BLO_GROUP_MAX];
2606         int idcode, totfiles = 0;
2607         short flag;
2608
2609         RNA_string_get(op->ptr, "filename", name);
2610         RNA_string_get(op->ptr, "directory", dir);
2611
2612         /* test if we have a valid data */
2613         if (BLO_is_a_library(dir, libname, group) == 0) {
2614                 BKE_report(op->reports, RPT_ERROR, "Not a library");
2615                 return OPERATOR_CANCELLED;
2616         }
2617         else if (group[0] == 0) {
2618                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
2619                 return OPERATOR_CANCELLED;
2620         }
2621         else if (BLI_path_cmp(bmain->name, libname) == 0) {
2622                 BKE_report(op->reports, RPT_ERROR, "Cannot use current file as library");
2623                 return OPERATOR_CANCELLED;
2624         }
2625
2626         /* check if something is indicated for append/link */
2627         prop = RNA_struct_find_property(op->ptr, "files");
2628         if (prop) {
2629                 totfiles = RNA_property_collection_length(op->ptr, prop);
2630                 if (totfiles == 0) {
2631                         if (name[0] == '\0') {
2632                                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
2633                                 return OPERATOR_CANCELLED;
2634                         }
2635                 }
2636         }
2637         else if (name[0] == '\0') {
2638                 BKE_report(op->reports, RPT_ERROR, "Nothing indicated");
2639                 return OPERATOR_CANCELLED;
2640         }
2641
2642         bh = BLO_blendhandle_from_file(libname, op->reports);
2643
2644         if (bh == NULL) {
2645                 /* unlikely since we just browsed it, but possible
2646                  * error reports will have been made by BLO_blendhandle_from_file() */
2647                 return OPERATOR_CANCELLED;
2648         }
2649
2650
2651         /* from here down, no error returns */
2652
2653         idcode = BKE_idcode_from_name(group);
2654
2655         /* now we have or selected, or an indicated file */
2656         if (RNA_boolean_get(op->ptr, "autoselect"))
2657                 BKE_scene_base_deselect_all(scene);
2658
2659         
2660         flag = wm_link_append_flag(op);
2661
2662         /* sanity checks for flag */
2663         if (scene->id.lib && (flag & FILE_GROUP_INSTANCE)) {
2664                 /* TODO, user never gets this message */
2665                 BKE_reportf(op->reports, RPT_WARNING, "Scene '%s' is linked, group instance disabled", scene->id.name + 2);
2666                 flag &= ~FILE_GROUP_INSTANCE;
2667         }
2668
2669
2670         /* tag everything, all untagged data can be made local
2671          * its also generally useful to know what is new
2672          *
2673          * take extra care BKE_main_id_flag_all(LIB_LINK_TAG, false) is called after! */
2674         BKE_main_id_flag_all(bmain, LIB_PRE_EXISTING, 1);
2675
2676         /* here appending/linking starts */
2677         mainl = BLO_library_append_begin(bmain, &bh, libname);
2678         lib = mainl->curlib;
2679         BLI_assert(lib);
2680
2681         if (mainl->versionfile < 250) {
2682                 BKE_reportf(op->reports, RPT_WARNING,
2683                             "Linking or appending from a very old .blend file format (%d.%d), no animation conversion will "
2684                             "be done! You may want to re-save your lib file with current Blender",
2685                             mainl->versionfile, mainl->subversionfile);
2686         }
2687
2688         if (totfiles == 0) {
2689                 BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
2690         }
2691         else {
2692                 RNA_BEGIN (op->ptr, itemptr, "files")
2693                 {
2694                         RNA_string_get(&itemptr, "name", name);
2695                         BLO_library_append_named_part_ex(C, mainl, &bh, name, idcode, flag);
2696                 }
2697                 RNA_END;
2698         }
2699         BLO_library_append_end(C, mainl, &bh, idcode, flag);
2700         
2701         /* mark all library linked objects to be updated */
2702         BKE_main_lib_objects_recalc_all(bmain);
2703         IMB_colormanagement_check_file_config(bmain);
2704
2705         /* append, rather than linking */
2706         if ((flag & FILE_LINK) == 0) {
2707                 BLI_assert(BLI_findindex(&bmain->library, lib) != -1);
2708                 BKE_library_make_local(bmain, lib, true);
2709         }
2710
2711         /* important we unset, otherwise these object wont
2712          * link into other scenes from this blend file */
2713         BKE_main_id_flag_all(bmain, LIB_PRE_EXISTING, false);
2714
2715         /* recreate dependency graph to include new objects */
2716         DAG_scene_relations_rebuild(bmain, scene);
2717         
2718         /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
2719         GPU_materials_free();
2720         BLO_blendhandle_close(bh);
2721
2722         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
2723         BLI_strncpy(G.lib, dir, FILE_MAX);
2724
2725         WM_event_add_notifier(C, NC_WINDOW, NULL);
2726
2727         return OPERATOR_FINISHED;
2728 }
2729
2730 static void wm_link_append_properties_common(wmOperatorType *ot, bool is_link)
2731 {
2732         PropertyRNA *prop;
2733
2734         /* better not save _any_ settings for this operator */
2735         /* properties */
2736         prop = RNA_def_boolean(ot->srna, "link", is_link,
2737                                "Link", "Link the objects or datablocks rather than appending");
2738         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
2739         prop = RNA_def_boolean(ot->srna, "autoselect", true,
2740                                "Select", "Select new objects");
2741         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2742         prop = RNA_def_boolean(ot->srna, "active_layer", true,
2743                                "Active Layer", "Put new objects on the active layer");
2744         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2745         prop = RNA_def_boolean(ot->srna, "instance_groups", is_link,
2746                                "Instance Groups", "Create Dupli-Group instances for each group");
2747         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2748 }
2749
2750 static void WM_OT_link(wmOperatorType *ot)
2751 {
2752         ot->name = "Link from Library";
2753         ot->idname = "WM_OT_link";
2754         ot->description = "Link from a Library .blend file";
2755         
2756         ot->invoke = wm_link_append_invoke;
2757         ot->exec = wm_link_append_exec;
2758         ot->poll = wm_link_append_poll;
2759         
2760         ot->flag |= OPTYPE_UNDO;
2761
2762         WM_operator_properties_filesel(
2763                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_LOADLIB, FILE_OPENFILE,
2764                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH | WM_FILESEL_FILES,
2765                 FILE_DEFAULTDISPLAY);
2766         
2767         wm_link_append_properties_common(ot, true);
2768 }
2769
2770 static void WM_OT_append(wmOperatorType *ot)
2771 {
2772         ot->name = "Append from Library";
2773         ot->idname = "WM_OT_append";
2774         ot->description = "Append from a Library .blend file";
2775
2776         ot->invoke = wm_link_append_invoke;
2777         ot->exec = wm_link_append_exec;
2778         ot->poll = wm_link_append_poll;
2779
2780         ot->flag |= OPTYPE_UNDO;
2781
2782         WM_operator_properties_filesel(
2783                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_LOADLIB, FILE_OPENFILE,
2784                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_FILES,
2785                 FILE_DEFAULTDISPLAY);
2786
2787         wm_link_append_properties_common(ot, false);
2788 }
2789
2790 /* *************** recover last session **************** */
2791
2792 void WM_recover_last_session(bContext *C, ReportList *reports)
2793 {
2794         char filepath[FILE_MAX];
2795         
2796         BLI_make_file_string("/", filepath, BKE_tempdir_base(), BLENDER_QUIT_FILE);
2797         /* if reports==NULL, it's called directly without operator, we add a quick check here */
2798         if (reports || BLI_exists(filepath)) {
2799                 G.fileflags |= G_FILE_RECOVER;
2800                 
2801                 wm_file_read_opwrap(C, filepath, reports, true);
2802         
2803                 G.fileflags &= ~G_FILE_RECOVER;
2804                 
2805                 /* XXX bad global... fixme */
2806                 if (G.main->name[0])
2807                         G.file_loaded = 1;      /* prevents splash to show */
2808                 else {
2809                         G.relbase_valid = 0;
2810                         G.save_over = 0;    /* start with save preference untitled.blend */
2811                 }
2812
2813         }
2814 }
2815
2816 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
2817 {
2818         WM_recover_last_session(C, op->reports);
2819         return OPERATOR_FINISHED;
2820 }
2821
2822 static void WM_OT_recover_last_session(wmOperatorType *ot)
2823 {
2824         ot->name = "Recover Last Session";
2825         ot->idname = "WM_OT_recover_last_session";
2826         ot->description = "Open the last closed file (\"" BLENDER_QUIT_FILE "\")";
2827         ot->invoke = WM_operator_confirm;
2828         
2829         ot->exec = wm_recover_last_session_exec;
2830 }
2831
2832 /* *************** recover auto save **************** */
2833
2834 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
2835 {
2836         char filepath[FILE_MAX];
2837         bool success;
2838
2839         RNA_string_get(op->ptr, "filepath", filepath);
2840
2841         G.fileflags |= G_FILE_RECOVER;
2842
2843         success = wm_file_read_opwrap(C, filepath, op->reports, true);
2844
2845         G.fileflags &= ~G_FILE_RECOVER;
2846         
2847         if (success) {
2848                 return OPERATOR_FINISHED;
2849         }
2850         else {
2851                 return OPERATOR_CANCELLED;
2852         }
2853 }
2854
2855 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2856 {
2857         char filename[FILE_MAX];
2858
2859         wm_autosave_location(filename);
2860         RNA_string_set(op->ptr, "filepath", filename);
2861         WM_event_add_fileselect(C, op);
2862
2863         return OPERATOR_RUNNING_MODAL;
2864 }
2865
2866 static void WM_OT_recover_auto_save(wmOperatorType *ot)
2867 {
2868         ot->name = "Recover Auto Save";
2869         ot->idname = "WM_OT_recover_auto_save";
2870         ot->description = "Open an automatically saved file to recover it";
2871         
2872         ot->exec = wm_recover_auto_save_exec;
2873         ot->invoke = wm_recover_auto_save_invoke;
2874
2875         WM_operator_properties_filesel(ot, FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
2876                                        WM_FILESEL_FILEPATH, FILE_LONGDISPLAY);
2877 }
2878
2879 /* *************** save file as **************** */
2880
2881 static void wm_filepath_default(char *filepath)
2882 {
2883         if (G.save_over == false) {
2884                 BLI_ensure_filename(filepath, FILE_MAX, "untitled.blend");
2885         }
2886 }
2887
2888 static void save_set_compress(wmOperator *op)
2889 {
2890         PropertyRNA *prop;
2891
2892         prop = RNA_struct_find_property(op->ptr, "compress");
2893         if (!RNA_property_is_set(op->ptr, prop)) {
2894                 if (G.save_over) {  /* keep flag for existing file */
2895                         RNA_property_boolean_set(op->ptr, prop, (G.fileflags & G_FILE_COMPRESS) != 0);
2896                 }
2897                 else {  /* use userdef for new file */
2898                         RNA_property_boolean_set(op->ptr, prop, (U.flag & USER_FILECOMPRESS) != 0);
2899                 }
2900         }
2901 }
2902
2903 static void save_set_filepath(wmOperator *op)
2904 {
2905         PropertyRNA *prop;
2906         char name[FILE_MAX];
2907
2908         prop = RNA_struct_find_property(op->ptr, "filepath");
2909         if (!RNA_property_is_set(op->ptr, prop)) {
2910                 /* if not saved before, get the name of the most recently used .blend file */
2911                 if (G.main->name[0] == 0 && G.recent_files.first) {
2912                         struct RecentFile *recent = G.recent_files.first;
2913                         BLI_strncpy(name, recent->filepath, FILE_MAX);
2914                 }
2915                 else {
2916                         BLI_strncpy(name, G.main->name, FILE_MAX);
2917                 }
2918
2919                 wm_filepath_default(name);
2920                 RNA_property_string_set(op->ptr, prop, name);
2921         }
2922 }
2923
2924 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2925 {
2926
2927         save_set_compress(op);
2928         save_set_filepath(op);
2929         
2930         WM_event_add_fileselect(C, op);
2931
2932         return OPERATOR_RUNNING_MODAL;
2933 }
2934
2935 /* function used for WM_OT_save_mainfile too */
2936 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2937 {
2938         char path[FILE_MAX];
2939         int fileflags;
2940
2941         save_set_compress(op);
2942         
2943         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2944                 RNA_string_get(op->ptr, "filepath", path);
2945         }
2946         else {
2947                 BLI_strncpy(path, G.main->name, FILE_MAX);
2948                 wm_filepath_default(path);
2949         }
2950         
2951         fileflags = G.fileflags & ~G_FILE_USERPREFS;
2952
2953         /* set compression flag */
2954         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "compress"),
2955                          G_FILE_COMPRESS);
2956         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
2957                          G_FILE_RELATIVE_REMAP);
2958         BKE_BIT_TEST_SET(fileflags,
2959                          (RNA_struct_property_is_set(op->ptr, "copy") &&
2960                           RNA_boolean_get(op->ptr, "copy")),
2961                          G_FILE_SAVE_COPY);
2962
2963 #ifdef USE_BMESH_SAVE_AS_COMPAT
2964         BKE_BIT_TEST_SET(fileflags,
2965                          (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
2966                           RNA_boolean_get(op->ptr, "use_mesh_compat")),
2967                          G_FILE_MESH_COMPAT);
2968 #else
2969 #  error "don't remove by accident"
2970 #endif
2971
2972         if (wm_file_write(C, path, fileflags, op->reports) != 0)
2973                 return OPERATOR_CANCELLED;
2974
2975         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2976
2977         return OPERATOR_FINISHED;
2978 }
2979
2980 /* function used for WM_OT_save_mainfile too */
2981 static bool blend_save_check(bContext *UNUSED(C), wmOperator *op)
2982 {
2983         char filepath[FILE_MAX];
2984         RNA_string_get(op->ptr, "filepath", filepath);
2985         if (!BLO_has_bfile_extension(filepath)) {
2986                 /* some users would prefer BLI_replace_extension(),
2987                  * we keep getting nitpicking bug reports about this - campbell */
2988                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
2989                 RNA_string_set(op->ptr, "filepath", filepath);
2990                 return true;
2991         }
2992         return false;
2993 }
2994
2995 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
2996 {
2997         PropertyRNA *prop;
2998
2999         ot->name = "Save As Blender File";
3000         ot->idname = "WM_OT_save_as_mainfile";
3001         ot->description = "Save the current file in the desired location";
3002         
3003         ot->invoke = wm_save_as_mainfile_invoke;
3004         ot->exec = wm_save_as_mainfile_exec;
3005         ot->check = blend_save_check;
3006         /* omit window poll so this can work in background mode */
3007
3008         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
3009                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
3010         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
3011         RNA_def_boolean(ot->srna, "relative_remap", true, "Remap Relative",
3012                         "Remap relative paths when saving in a different directory");
3013         prop = RNA_def_boolean(ot->srna, "copy", false, "Save Copy",
3014                         "Save a copy of the actual working state but does not make saved file active");
3015         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3016 #ifdef USE_BMESH_SAVE_AS_COMPAT
3017         RNA_def_boolean(ot->srna, "use_mesh_compat", false, "Legacy Mesh Format",
3018                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
3019                         "be lost (no implicit triangulation)");
3020 #endif
3021 }
3022
3023 /* *************** save file directly ******** */
3024
3025 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
3026 {
3027         int ret;
3028         
3029         /* cancel if no active window */
3030         if (CTX_wm_window(C) == NULL)
3031                 return OPERATOR_CANCELLED;
3032
3033         save_set_compress(op);
3034         save_set_filepath(op);
3035
3036         /* if we're saving for the first time and prefer relative paths - any existing paths will be absolute,
3037          * enable the option to remap paths to avoid confusion [#37240] */
3038         if ((G.relbase_valid == false) && (U.flag & USER_RELPATHS)) {
3039                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "relative_remap");
3040                 if (!RNA_property_is_set(op->ptr, prop)) {
3041                         RNA_property_boolean_set(op->ptr, prop, true);
3042                 }
3043         }
3044
3045         if (G.save_over) {
3046                 char path[FILE_MAX];
3047
3048                 RNA_string_get(op->ptr, "filepath", path);
3049                 if (BLI_exists(path)) {
3050                         ret = WM_operator_confirm_message_ex(C, op, IFACE_("Save Over?"), ICON_QUESTION, path);
3051                 }
3052                 else {
3053                         ret = wm_save_as_mainfile_exec(C, op);
3054                 }
3055         }
3056         else {
3057                 WM_event_add_fileselect(C, op);
3058                 ret = OPERATOR_RUNNING_MODAL;
3059         }
3060         
3061         return ret;
3062 }
3063
3064 static void WM_OT_save_mainfile(wmOperatorType *ot)
3065 {
3066         ot->name = "Save Blender File";
3067         ot->idname = "WM_OT_save_mainfile";
3068         ot->description = "Save the current Blender file";
3069         
3070         ot->invoke = wm_save_mainfile_invoke;
3071         ot->exec = wm_save_as_mainfile_exec;
3072         ot->check = blend_save_check;
3073         /* omit window poll so this can work in background mode */
3074         
3075         WM_operator_properties_filesel(ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
3076                                        WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY);
3077         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
3078         RNA_def_boolean(ot->srna, "relative_remap", false, "Remap Relative",
3079                         "Remap relative paths when saving in a different directory");
3080 }
3081
3082 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
3083 {
3084         ot->name = "Toggle Window Fullscreen";
3085         ot->idname = "WM_OT_window_fullscreen_toggle";
3086         ot->description = "Toggle the current window fullscreen";
3087
3088         ot->exec = wm_window_fullscreen_toggle_exec;
3089         ot->poll = WM_operator_winactive;
3090 }
3091
3092 static int wm_exit_blender_exec(bContext *C, wmOperator *op)
3093 {
3094         WM_operator_free(op);
3095         
3096         WM_exit(C);
3097         
3098         return OPERATOR_FINISHED;
3099 }
3100
3101 static void WM_OT_quit_blender(wmOperatorType *ot)
3102 {
3103         ot->name = "Quit Blender";
3104         ot->idname = "WM_OT_quit_blender";
3105         ot->description = "Quit Blender";
3106
3107         ot->invoke = WM_operator_confirm;
3108         ot->exec = wm_exit_blender_exec;
3109 }
3110
3111 /* *********************** */
3112
3113 #if defined(WIN32)
3114
3115 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
3116 {
3117         GHOST_toggleConsole(2);
3118         return OPERATOR_FINISHED;
3119 }
3120
3121 static void WM_OT_console_toggle(wmOperatorType *ot)
3122 {
3123         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
3124         ot->name = CTX_N_(BLF_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
3125         ot->idname = "WM_OT_console_toggle";
3126         ot->description = N_("Toggle System Console");
3127         
3128         ot->exec = wm_console_toggle_exec;
3129         ot->poll = WM_operator_winactive;
3130 }
3131
3132 #endif
3133
3134 /* ************ default paint cursors, draw always around cursor *********** */
3135 /*
3136  * - returns handler to free
3137  * - poll(bContext): returns 1 if draw should happen
3138  * - draw(bContext): drawing callback for paint cursor
3139  */
3140
3141 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
3142                                wmPaintCursorDraw draw, void *customdata)
3143 {
3144         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
3145         
3146         BLI_addtail(&wm->paintcursors, pc);
3147         
3148         pc->customdata = customdata;
3149         pc->poll = poll;
3150         pc->draw = draw;
3151         
3152         return pc;
3153 }
3154
3155 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
3156 {
3157         wmPaintCursor *pc;
3158         
3159         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
3160                 if (pc == (wmPaintCursor *)handle) {
3161                         BLI_remlink(&wm->paintcursors, pc);
3162                         MEM_freeN(pc);
3163                         return;
3164                 }
3165         }
3166 }
3167
3168 /* ************ window gesture operator-callback definitions ************** */
3169 /*
3170  * These are default callbacks for use in operators requiring gesture input
3171  */
3172
3173 /* **************** Border gesture *************** */
3174
3175 /**
3176  * Border gesture has two types:
3177  * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
3178  * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
3179  *
3180  * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
3181  */
3182
3183 static int border_apply_rect(wmOperator *op)
3184 {
3185         wmGesture *gesture = op->customdata;
3186         rcti *rect = gesture->customdata;
3187