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