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