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