UI: Add search-create callback
[blender.git] / source / blender / windowmanager / intern / wm_operators.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_operators.c
28  *  \ingroup wm
29  *
30  * Functions for dealing with wmOperator, adding, removing, calling
31  * as well as some generic operators and shared operator properties.
32  */
33
34
35 #include <float.h>
36 #include <string.h>
37 #include <ctype.h>
38 #include <stdio.h>
39 #include <stddef.h>
40 #include <assert.h>
41 #include <errno.h>
42
43 #ifdef WIN32
44 #  include "GHOST_C-api.h"
45 #endif
46
47 #include "MEM_guardedalloc.h"
48
49 #include "DNA_ID.h"
50 #include "DNA_object_types.h"
51 #include "DNA_screen_types.h"
52 #include "DNA_scene_types.h"
53 #include "DNA_userdef_types.h"
54 #include "DNA_windowmanager_types.h"
55 #include "DNA_mesh_types.h" /* only for USE_BMESH_SAVE_AS_COMPAT */
56
57 #include "BLT_translation.h"
58
59 #include "PIL_time.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_bitmap.h"
63 #include "BLI_dial.h"
64 #include "BLI_dynstr.h" /*for WM_operator_pystring */
65 #include "BLI_linklist.h"
66 #include "BLI_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
1904 struct SearchPopupInit_Data {
1905         int size[2];
1906 };
1907
1908 static uiBlock *wm_block_search_menu(bContext *C, ARegion *ar, void *userdata)
1909 {
1910         const struct SearchPopupInit_Data *init_data = userdata;
1911         static char search[256] = "";
1912         wmEvent event;
1913         wmWindow *win = CTX_wm_window(C);
1914         uiBlock *block;
1915         uiBut *but;
1916         
1917         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
1918         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
1919         
1920         but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, init_data->size[0], UI_UNIT_Y, 0, 0, "");
1921         UI_but_func_operator_search(but);
1922         
1923         /* fake button, it holds space for search items */
1924         uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - init_data->size[1],
1925                  init_data->size[0], init_data->size[1], NULL, 0, 0, 0, 0, NULL);
1926         
1927         UI_block_bounds_set_popup(block, 6, 0, -UI_UNIT_Y); /* move it downwards, mouse over button */
1928         
1929         wm_event_init_from_window(win, &event);
1930         event.type = EVT_BUT_OPEN;
1931         event.val = KM_PRESS;
1932         event.customdata = but;
1933         event.customdatafree = false;
1934         wm_event_add(win, &event);
1935         
1936         return block;
1937 }
1938
1939 static int wm_search_menu_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
1940 {
1941         return OPERATOR_FINISHED;
1942 }
1943
1944 static int wm_search_menu_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
1945 {
1946         struct SearchPopupInit_Data data = {
1947                 .size = {
1948                     UI_searchbox_size_x(),
1949                     UI_searchbox_size_y(),
1950                 },
1951         };
1952
1953         UI_popup_block_invoke(C, wm_block_search_menu, &data);
1954         
1955         return OPERATOR_INTERFACE;
1956 }
1957
1958 /* op->poll */
1959 static int wm_search_menu_poll(bContext *C)
1960 {
1961         if (CTX_wm_window(C) == NULL) {
1962                 return 0;
1963         }
1964         else {
1965                 ScrArea *sa = CTX_wm_area(C);
1966                 if (sa) {
1967                         if (sa->spacetype == SPACE_CONSOLE) return 0;  /* XXX - so we can use the shortcut in the console */
1968                         if (sa->spacetype == SPACE_TEXT) return 0;     /* XXX - so we can use the spacebar in the text editor */
1969                 }
1970                 else {
1971                         Object *editob = CTX_data_edit_object(C);
1972                         if (editob && editob->type == OB_FONT) return 0;  /* XXX - so we can use the spacebar for entering text */
1973                 }
1974         }
1975         return 1;
1976 }
1977
1978 static void WM_OT_search_menu(wmOperatorType *ot)
1979 {
1980         ot->name = "Search Menu";
1981         ot->idname = "WM_OT_search_menu";
1982         ot->description = "Pop-up a search menu over all available operators in current context";
1983         
1984         ot->invoke = wm_search_menu_invoke;
1985         ot->exec = wm_search_menu_exec;
1986         ot->poll = wm_search_menu_poll;
1987 }
1988
1989 static int wm_call_menu_exec(bContext *C, wmOperator *op)
1990 {
1991         char idname[BKE_ST_MAXNAME];
1992         RNA_string_get(op->ptr, "name", idname);
1993
1994         return UI_popup_menu_invoke(C, idname, op->reports);
1995 }
1996
1997 static void WM_OT_call_menu(wmOperatorType *ot)
1998 {
1999         ot->name = "Call Menu";
2000         ot->idname = "WM_OT_call_menu";
2001         ot->description = "Call (draw) a pre-defined menu";
2002
2003         ot->exec = wm_call_menu_exec;
2004         ot->poll = WM_operator_winactive;
2005
2006         ot->flag = OPTYPE_INTERNAL;
2007
2008         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the menu");
2009 }
2010
2011 static int wm_call_pie_menu_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2012 {
2013         char idname[BKE_ST_MAXNAME];
2014         RNA_string_get(op->ptr, "name", idname);
2015
2016         return UI_pie_menu_invoke(C, idname, event);
2017 }
2018
2019 static int wm_call_pie_menu_exec(bContext *C, wmOperator *op)
2020 {
2021         char idname[BKE_ST_MAXNAME];
2022         RNA_string_get(op->ptr, "name", idname);
2023
2024         return UI_pie_menu_invoke(C, idname, CTX_wm_window(C)->eventstate);
2025 }
2026
2027 static void WM_OT_call_menu_pie(wmOperatorType *ot)
2028 {
2029         ot->name = "Call Pie Menu";
2030         ot->idname = "WM_OT_call_menu_pie";
2031         ot->description = "Call (draw) a pre-defined pie menu";
2032
2033         ot->invoke = wm_call_pie_menu_invoke;
2034         ot->exec = wm_call_pie_menu_exec;
2035         ot->poll = WM_operator_winactive;
2036
2037         ot->flag = OPTYPE_INTERNAL;
2038
2039         RNA_def_string(ot->srna, "name", NULL, BKE_ST_MAXNAME, "Name", "Name of the pie menu");
2040 }
2041
2042 /* ************ window / screen operator definitions ************** */
2043
2044 /* this poll functions is needed in place of WM_operator_winactive
2045  * while it crashes on full screen */
2046 static int wm_operator_winactive_normal(bContext *C)
2047 {
2048         wmWindow *win = CTX_wm_window(C);
2049
2050         if (win == NULL || win->screen == NULL || win->screen->state != SCREENNORMAL)
2051                 return 0;
2052
2053         return 1;
2054 }
2055
2056 /* included for script-access */
2057 static void WM_OT_window_close(wmOperatorType *ot)
2058 {
2059         ot->name = "Close Window";
2060         ot->idname = "WM_OT_window_close";
2061         ot->description = "Close the current Blender window";
2062
2063         ot->exec = wm_window_close_exec;
2064         ot->poll = WM_operator_winactive;
2065 }
2066
2067 static void WM_OT_window_duplicate(wmOperatorType *ot)
2068 {
2069         ot->name = "Duplicate Window";
2070         ot->idname = "WM_OT_window_duplicate";
2071         ot->description = "Duplicate the current Blender window";
2072                 
2073         ot->exec = wm_window_duplicate_exec;
2074         ot->poll = wm_operator_winactive_normal;
2075 }
2076
2077 static void WM_OT_save_homefile(wmOperatorType *ot)
2078 {
2079         ot->name = "Save Startup File";
2080         ot->idname = "WM_OT_save_homefile";
2081         ot->description = "Make the current file the default .blend file, includes preferences";
2082                 
2083         ot->invoke = WM_operator_confirm;
2084         ot->exec = wm_homefile_write_exec;
2085 }
2086
2087 static int wm_userpref_autoexec_add_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
2088 {
2089         bPathCompare *path_cmp = MEM_callocN(sizeof(bPathCompare), "bPathCompare");
2090         BLI_addtail(&U.autoexec_paths, path_cmp);
2091         return OPERATOR_FINISHED;
2092 }
2093
2094 static void WM_OT_userpref_autoexec_path_add(wmOperatorType *ot)
2095 {
2096         ot->name = "Add Autoexec Path";
2097         ot->idname = "WM_OT_userpref_autoexec_path_add";
2098         ot->description = "Add path to exclude from autoexecution";
2099
2100         ot->exec = wm_userpref_autoexec_add_exec;
2101
2102         ot->flag = OPTYPE_INTERNAL;
2103 }
2104
2105 static int wm_userpref_autoexec_remove_exec(bContext *UNUSED(C), wmOperator *op)
2106 {
2107         const int index = RNA_int_get(op->ptr, "index");
2108         bPathCompare *path_cmp = BLI_findlink(&U.autoexec_paths, index);
2109         if (path_cmp) {
2110                 BLI_freelinkN(&U.autoexec_paths, path_cmp);
2111         }
2112         return OPERATOR_FINISHED;
2113 }
2114
2115 static void WM_OT_userpref_autoexec_path_remove(wmOperatorType *ot)
2116 {
2117         ot->name = "Remove Autoexec Path";
2118         ot->idname = "WM_OT_userpref_autoexec_path_remove";
2119         ot->description = "Remove path to exclude from autoexecution";
2120
2121         ot->exec = wm_userpref_autoexec_remove_exec;
2122
2123         ot->flag = OPTYPE_INTERNAL;
2124
2125         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
2126 }
2127
2128 static void WM_OT_save_userpref(wmOperatorType *ot)
2129 {
2130         ot->name = "Save User Settings";
2131         ot->idname = "WM_OT_save_userpref";
2132         ot->description = "Save user preferences separately, overrides startup file preferences";
2133         
2134         ot->invoke = WM_operator_confirm;
2135         ot->exec = wm_userpref_write_exec;
2136 }
2137
2138 static void WM_OT_read_history(wmOperatorType *ot)
2139 {
2140         ot->name = "Reload History File";
2141         ot->idname = "WM_OT_read_history";
2142         ot->description = "Reloads history and bookmarks";
2143
2144         ot->invoke = WM_operator_confirm;
2145         ot->exec = wm_history_file_read_exec;
2146
2147         /* this operator is only used for loading settings from a previous blender install */
2148         ot->flag = OPTYPE_INTERNAL;
2149 }
2150
2151 static void WM_OT_read_homefile(wmOperatorType *ot)
2152 {
2153         PropertyRNA *prop;
2154         ot->name = "Reload Start-Up File";
2155         ot->idname = "WM_OT_read_homefile";
2156         ot->description = "Open the default file (doesn't save the current file)";
2157         
2158         ot->invoke = WM_operator_confirm;
2159         ot->exec = wm_homefile_read_exec;
2160
2161         prop = RNA_def_string_file_path(ot->srna, "filepath", NULL,
2162                                         FILE_MAX, "File Path", 
2163                                         "Path to an alternative start-up file");
2164         RNA_def_property_flag(prop, PROP_HIDDEN);
2165
2166         /* So scripts can use an alternative start-up file without the UI */
2167         prop = RNA_def_boolean(ot->srna, "load_ui", true, "Load UI",
2168                                "Load user interface setup from the .blend file");
2169         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2170
2171         /* omit poll to run in background mode */
2172 }
2173
2174 static void WM_OT_read_factory_settings(wmOperatorType *ot)
2175 {
2176         ot->name = "Load Factory Settings";
2177         ot->idname = "WM_OT_read_factory_settings";
2178         ot->description = "Load default file and user preferences";
2179         
2180         ot->invoke = WM_operator_confirm;
2181         ot->exec = wm_homefile_read_exec;
2182         /* omit poll to run in background mode */
2183 }
2184
2185 /* *************** open file **************** */
2186
2187 /**
2188  * Wrap #WM_file_read, shared by file reading operators.
2189  */
2190 static bool wm_file_read_opwrap(bContext *C, const char *filepath, ReportList *reports,
2191                                 const bool autoexec_init)
2192 {
2193         bool success;
2194
2195         /* XXX wm in context is not set correctly after WM_file_read -> crash */
2196         /* do it before for now, but is this correct with multiple windows? */
2197         WM_event_add_notifier(C, NC_WINDOW, NULL);
2198
2199         if (autoexec_init) {
2200                 WM_file_autoexec_init(filepath);
2201         }
2202
2203         success = WM_file_read(C, filepath, reports);
2204
2205         return success;
2206 }
2207
2208 /* currently fits in a pointer */
2209 struct FileRuntime {
2210         bool is_untrusted;
2211 };
2212
2213 static int wm_open_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2214 {
2215         const char *openname = G.main->name;
2216
2217         if (CTX_wm_window(C) == NULL) {
2218                 /* in rare cases this could happen, when trying to invoke in background
2219                  * mode on load for example. Don't use poll for this because exec()
2220                  * can still run without a window */
2221                 BKE_report(op->reports, RPT_ERROR, "Context window not set");
2222                 return OPERATOR_CANCELLED;
2223         }
2224
2225         /* if possible, get the name of the most recently used .blend file */
2226         if (G.recent_files.first) {
2227                 struct RecentFile *recent = G.recent_files.first;
2228                 openname = recent->filepath;
2229         }
2230
2231         RNA_string_set(op->ptr, "filepath", openname);
2232         wm_open_init_load_ui(op, true);
2233         wm_open_init_use_scripts(op, true);
2234         op->customdata = NULL;
2235
2236         WM_event_add_fileselect(C, op);
2237
2238         return OPERATOR_RUNNING_MODAL;
2239 }
2240
2241 static int wm_open_mainfile_exec(bContext *C, wmOperator *op)
2242 {
2243         char filepath[FILE_MAX];
2244         bool success;
2245
2246         RNA_string_get(op->ptr, "filepath", filepath);
2247
2248         /* re-use last loaded setting so we can reload a file without changing */
2249         wm_open_init_load_ui(op, false);
2250         wm_open_init_use_scripts(op, false);
2251
2252         if (RNA_boolean_get(op->ptr, "load_ui"))
2253                 G.fileflags &= ~G_FILE_NO_UI;
2254         else
2255                 G.fileflags |= G_FILE_NO_UI;
2256                 
2257         if (RNA_boolean_get(op->ptr, "use_scripts"))
2258                 G.f |= G_SCRIPT_AUTOEXEC;
2259         else
2260                 G.f &= ~G_SCRIPT_AUTOEXEC;
2261         
2262         success = wm_file_read_opwrap(C, filepath, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
2263
2264         /* for file open also popup for warnings, not only errors */
2265         BKE_report_print_level_set(op->reports, RPT_WARNING);
2266
2267         if (success) {
2268                 return OPERATOR_FINISHED;
2269         }
2270         else {
2271                 return OPERATOR_CANCELLED;
2272         }
2273 }
2274
2275 static bool wm_open_mainfile_check(bContext *UNUSED(C), wmOperator *op)
2276 {
2277         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
2278         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "use_scripts");
2279         bool is_untrusted = false;
2280         char path[FILE_MAX];
2281         char *lslash;
2282
2283         RNA_string_get(op->ptr, "filepath", path);
2284
2285         /* get the dir */
2286         lslash = (char *)BLI_last_slash(path);
2287         if (lslash) *(lslash + 1) = '\0';
2288
2289         if ((U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0) {
2290                 if (BKE_autoexec_match(path) == true) {
2291                         RNA_property_boolean_set(op->ptr, prop, false);
2292                         is_untrusted = true;
2293                 }
2294         }
2295
2296         if (file_info) {
2297                 file_info->is_untrusted = is_untrusted;
2298         }
2299
2300         return is_untrusted;
2301 }
2302
2303 static void wm_open_mainfile_ui(bContext *UNUSED(C), wmOperator *op)
2304 {
2305         struct FileRuntime *file_info = (struct FileRuntime *)&op->customdata;
2306         uiLayout *layout = op->layout;
2307         uiLayout *col = op->layout;
2308         const char *autoexec_text;
2309
2310         uiItemR(layout, op->ptr, "load_ui", 0, NULL, ICON_NONE);
2311
2312         col = uiLayoutColumn(layout, false);
2313         if (file_info->is_untrusted) {
2314                 autoexec_text = IFACE_("Trusted Source [Untrusted Path]");
2315                 uiLayoutSetActive(col, false);
2316                 uiLayoutSetEnabled(col, false);
2317         }
2318         else {
2319                 autoexec_text = IFACE_("Trusted Source");
2320         }
2321
2322         uiItemR(col, op->ptr, "use_scripts", 0, autoexec_text, ICON_NONE);
2323 }
2324
2325 static void WM_OT_open_mainfile(wmOperatorType *ot)
2326 {
2327         ot->name = "Open Blender File";
2328         ot->idname = "WM_OT_open_mainfile";
2329         ot->description = "Open a Blender file";
2330
2331         ot->invoke = wm_open_mainfile_invoke;
2332         ot->exec = wm_open_mainfile_exec;
2333         ot->check = wm_open_mainfile_check;
2334         ot->ui = wm_open_mainfile_ui;
2335         /* omit window poll so this can work in background mode */
2336
2337         WM_operator_properties_filesel(
2338                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
2339                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2340
2341         RNA_def_boolean(ot->srna, "load_ui", true, "Load UI", "Load user interface setup in the .blend file");
2342         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
2343                         "Allow .blend file to execute scripts automatically, default available from system preferences");
2344 }
2345
2346
2347 /* *************** revert file **************** */
2348
2349 static int wm_revert_mainfile_exec(bContext *C, wmOperator *op)
2350 {
2351         bool success;
2352
2353         wm_open_init_use_scripts(op, false);
2354
2355         if (RNA_boolean_get(op->ptr, "use_scripts"))
2356                 G.f |= G_SCRIPT_AUTOEXEC;
2357         else
2358                 G.f &= ~G_SCRIPT_AUTOEXEC;
2359
2360         success = wm_file_read_opwrap(C, G.main->name, op->reports, !(G.f & G_SCRIPT_AUTOEXEC));
2361
2362         if (success) {
2363                 return OPERATOR_FINISHED;
2364         }
2365         else {
2366                 return OPERATOR_CANCELLED;
2367         }
2368 }
2369
2370 static int wm_revert_mainfile_poll(bContext *UNUSED(C))
2371 {
2372         return G.relbase_valid;
2373 }
2374
2375 static void WM_OT_revert_mainfile(wmOperatorType *ot)
2376 {
2377         ot->name = "Revert";
2378         ot->idname = "WM_OT_revert_mainfile";
2379         ot->description = "Reload the saved file";
2380         ot->invoke = WM_operator_confirm;
2381
2382         RNA_def_boolean(ot->srna, "use_scripts", true, "Trusted Source",
2383                         "Allow .blend file to execute scripts automatically, default available from system preferences");
2384
2385         ot->exec = wm_revert_mainfile_exec;
2386         ot->poll = wm_revert_mainfile_poll;
2387 }
2388
2389 /* **************** link/append *************** */
2390
2391 static int wm_link_append_poll(bContext *C)
2392 {
2393         if (WM_operator_winactive(C)) {
2394                 /* linking changes active object which is pretty useful in general,
2395                  * but which totally confuses edit mode (i.e. it becoming not so obvious
2396                  * to leave from edit mode and invalid tools in toolbar might be displayed)
2397                  * so disable link/append when in edit mode (sergey) */
2398                 if (CTX_data_edit_object(C))
2399                         return 0;
2400
2401                 return 1;
2402         }
2403
2404         return 0;
2405 }
2406
2407 static int wm_link_append_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2408 {
2409         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2410                 return WM_operator_call_notest(C, op);
2411         }
2412         else {
2413                 /* XXX TODO solve where to get last linked library from */
2414                 if (G.lib[0] != '\0') {
2415                         RNA_string_set(op->ptr, "filepath", G.lib);
2416                 }
2417                 else if (G.relbase_valid) {
2418                         char path[FILE_MAX];
2419                         BLI_strncpy(path, G.main->name, sizeof(G.main->name));
2420                         BLI_parent_dir(path);
2421                         RNA_string_set(op->ptr, "filepath", path);
2422                 }
2423                 WM_event_add_fileselect(C, op);
2424                 return OPERATOR_RUNNING_MODAL;
2425         }
2426 }
2427
2428 static short wm_link_append_flag(wmOperator *op)
2429 {
2430         PropertyRNA *prop;
2431         short flag = 0;
2432
2433         if (RNA_boolean_get(op->ptr, "autoselect"))
2434                 flag |= FILE_AUTOSELECT;
2435         if (RNA_boolean_get(op->ptr, "active_layer"))
2436                 flag |= FILE_ACTIVELAY;
2437         if ((prop = RNA_struct_find_property(op->ptr, "relative_path")) && RNA_property_boolean_get(op->ptr, prop))
2438                 flag |= FILE_RELPATH;
2439         if (RNA_boolean_get(op->ptr, "link"))
2440                 flag |= FILE_LINK;
2441         if (RNA_boolean_get(op->ptr, "instance_groups"))
2442                 flag |= FILE_GROUP_INSTANCE;
2443
2444         return flag;
2445 }
2446
2447 typedef struct WMLinkAppendDataItem {
2448         char *name;
2449         BLI_bitmap *libraries;  /* All libs (from WMLinkAppendData.libraries) to try to load this ID from. */
2450         short idcode;
2451
2452         ID *new_id;
2453         void *customdata;
2454 } WMLinkAppendDataItem;
2455
2456 typedef struct WMLinkAppendData {
2457         LinkNodePair libraries;
2458         LinkNodePair items;
2459         int num_libraries;
2460         int num_items;
2461         short flag;
2462
2463         /* Internal 'private' data */
2464         MemArena *memarena;
2465 } WMLinkAppendData;
2466
2467 static WMLinkAppendData *wm_link_append_data_new(const int flag)
2468 {
2469         MemArena *ma = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
2470         WMLinkAppendData *lapp_data = BLI_memarena_calloc(ma, sizeof(*lapp_data));
2471
2472         lapp_data->flag = flag;
2473         lapp_data->memarena = ma;
2474
2475         return lapp_data;
2476 }
2477
2478 static void wm_link_append_data_free(WMLinkAppendData *lapp_data)
2479 {
2480         BLI_memarena_free(lapp_data->memarena);
2481 }
2482
2483 /* WARNING! *Never* call wm_link_append_data_library_add() after having added some items! */
2484
2485 static void wm_link_append_data_library_add(WMLinkAppendData *lapp_data, const char *libname)
2486 {
2487         size_t len = strlen(libname) + 1;
2488         char *libpath = BLI_memarena_alloc(lapp_data->memarena, len);
2489
2490         BLI_strncpy(libpath, libname, len);
2491         BLI_linklist_append_arena(&lapp_data->libraries, libpath, lapp_data->memarena);
2492         lapp_data->num_libraries++;
2493 }
2494
2495 static WMLinkAppendDataItem *wm_link_append_data_item_add(
2496         WMLinkAppendData *lapp_data, const char *idname, const short idcode, void *customdata)
2497 {
2498         WMLinkAppendDataItem *item = BLI_memarena_alloc(lapp_data->memarena, sizeof(*item));
2499         size_t len = strlen(idname) + 1;
2500
2501         item->name = BLI_memarena_alloc(lapp_data->memarena, len);
2502         BLI_strncpy(item->name, idname, len);
2503         item->idcode = idcode;
2504         item->libraries = BLI_BITMAP_NEW_MEMARENA(lapp_data->memarena, lapp_data->num_libraries);
2505
2506         item->new_id = NULL;
2507         item->customdata = customdata;
2508
2509         BLI_linklist_append_arena(&lapp_data->items, item, lapp_data->memarena);
2510         lapp_data->num_items++;
2511
2512         return item;
2513 }
2514
2515 static void wm_link_do(
2516         WMLinkAppendData *lapp_data, ReportList *reports, Main *bmain, Scene *scene, View3D *v3d)
2517 {
2518         Main *mainl;
2519         BlendHandle *bh;
2520         Library *lib;
2521
2522         const int flag = lapp_data->flag;
2523
2524         LinkNode *liblink, *itemlink;
2525         int lib_idx, item_idx;
2526
2527         BLI_assert(lapp_data->num_items && lapp_data->num_libraries);
2528
2529         for (lib_idx = 0, liblink = lapp_data->libraries.list; liblink; lib_idx++, liblink = liblink->next) {
2530                 char *libname = liblink->link;
2531
2532                 bh = BLO_blendhandle_from_file(libname, reports);
2533
2534                 if (bh == NULL) {
2535                         /* Unlikely since we just browsed it, but possible
2536                          * Error reports will have been made by BLO_blendhandle_from_file() */
2537                         continue;
2538                 }
2539
2540                 /* here appending/linking starts */
2541                 mainl = BLO_library_link_begin(bmain, &bh, libname);
2542                 lib = mainl->curlib;
2543                 BLI_assert(lib);
2544                 UNUSED_VARS_NDEBUG(lib);
2545
2546                 if (mainl->versionfile < 250) {
2547                         BKE_reportf(reports, RPT_WARNING,
2548                                     "Linking or appending from a very old .blend file format (%d.%d), no animation conversion will "
2549                                     "be done! You may want to re-save your lib file with current Blender",
2550                                     mainl->versionfile, mainl->subversionfile);
2551                 }
2552
2553                 /* For each lib file, we try to link all items belonging to that lib,
2554                  * and tag those successful to not try to load them again with the other libs. */
2555                 for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
2556                         WMLinkAppendDataItem *item = itemlink->link;
2557                         ID *new_id;
2558
2559                         if (!BLI_BITMAP_TEST(item->libraries, lib_idx)) {
2560                                 continue;
2561                         }
2562
2563                         new_id = BLO_library_link_named_part_ex(mainl, &bh, item->idcode, item->name, flag, scene, v3d);
2564                         if (new_id) {
2565                                 /* If the link is sucessful, clear item's libs 'todo' flags.
2566                                  * This avoids trying to link same item with other libraries to come. */
2567                                 BLI_BITMAP_SET_ALL(item->libraries, false, lapp_data->num_libraries);
2568                                 item->new_id = new_id;
2569                         }
2570                 }
2571
2572                 BLO_library_link_end(mainl, &bh, flag, scene, v3d);
2573                 BLO_blendhandle_close(bh);
2574         }
2575 }
2576
2577 static int wm_link_append_exec(bContext *C, wmOperator *op)
2578 {
2579         Main *bmain = CTX_data_main(C);
2580         Scene *scene = CTX_data_scene(C);
2581         PropertyRNA *prop;
2582         WMLinkAppendData *lapp_data;
2583         char path[FILE_MAX_LIBEXTRA], root[FILE_MAXDIR], libname[FILE_MAX], relname[FILE_MAX];
2584         char *group, *name;
2585         int totfiles = 0;
2586         short flag;
2587
2588         RNA_string_get(op->ptr, "filename", relname);
2589         RNA_string_get(op->ptr, "directory", root);
2590
2591         BLI_join_dirfile(path, sizeof(path), root, relname);
2592
2593         /* test if we have a valid data */
2594         if (!BLO_library_path_explode(path, libname, &group, &name)) {
2595                 BKE_reportf(op->reports, RPT_ERROR, "'%s': not a library", path);
2596                 return OPERATOR_CANCELLED;
2597         }
2598         else if (!group) {
2599                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
2600                 return OPERATOR_CANCELLED;
2601         }
2602         else if (BLI_path_cmp(bmain->name, libname) == 0) {
2603                 BKE_reportf(op->reports, RPT_ERROR, "'%s': cannot use current file as library", path);
2604                 return OPERATOR_CANCELLED;
2605         }
2606
2607         /* check if something is indicated for append/link */
2608         prop = RNA_struct_find_property(op->ptr, "files");
2609         if (prop) {
2610                 totfiles = RNA_property_collection_length(op->ptr, prop);
2611                 if (totfiles == 0) {
2612                         if (!name) {
2613                                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
2614                                 return OPERATOR_CANCELLED;
2615                         }
2616                 }
2617         }
2618         else if (!name) {
2619                 BKE_reportf(op->reports, RPT_ERROR, "'%s': nothing indicated", path);
2620                 return OPERATOR_CANCELLED;
2621         }
2622
2623         flag = wm_link_append_flag(op);
2624
2625         /* sanity checks for flag */
2626         if (scene && scene->id.lib) {
2627                 BKE_reportf(op->reports, RPT_WARNING,
2628                             "Scene '%s' is linked, instantiation of objects & groups is disabled", scene->id.name + 2);
2629                 flag &= ~FILE_GROUP_INSTANCE;
2630                 scene = NULL;
2631         }
2632
2633         /* from here down, no error returns */
2634
2635         if (scene && RNA_boolean_get(op->ptr, "autoselect")) {
2636                 BKE_scene_base_deselect_all(scene);
2637         }
2638         
2639         /* tag everything, all untagged data can be made local
2640          * its also generally useful to know what is new
2641          *
2642          * take extra care BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false) is called after! */
2643         BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
2644
2645         /* We define our working data...
2646          * Note that here, each item 'uses' one library, and only one. */
2647         lapp_data = wm_link_append_data_new(flag);
2648         if (totfiles != 0) {
2649                 GHash *libraries = BLI_ghash_new(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, __func__);
2650                 int lib_idx = 0;
2651
2652                 RNA_BEGIN (op->ptr, itemptr, "files")
2653                 {
2654                         RNA_string_get(&itemptr, "name", relname);
2655
2656                         BLI_join_dirfile(path, sizeof(path), root, relname);
2657
2658                         if (BLO_library_path_explode(path, libname, &group, &name)) {
2659                                 if (!group || !name) {
2660                                         continue;
2661                                 }
2662
2663                                 if (!BLI_ghash_haskey(libraries, libname)) {
2664                                         BLI_ghash_insert(libraries, BLI_strdup(libname), SET_INT_IN_POINTER(lib_idx));
2665                                         lib_idx++;
2666                                         wm_link_append_data_library_add(lapp_data, libname);
2667                                 }
2668                         }
2669                 }
2670                 RNA_END;
2671
2672                 RNA_BEGIN (op->ptr, itemptr, "files")
2673                 {
2674                         RNA_string_get(&itemptr, "name", relname);
2675
2676                         BLI_join_dirfile(path, sizeof(path), root, relname);
2677
2678                         if (BLO_library_path_explode(path, libname, &group, &name)) {
2679                                 WMLinkAppendDataItem *item;
2680                                 if (!group || !name) {
2681                                         printf("skipping %s\n", path);
2682                                         continue;
2683                                 }
2684
2685                                 lib_idx = GET_INT_FROM_POINTER(BLI_ghash_lookup(libraries, libname));
2686
2687                                 item = wm_link_append_data_item_add(lapp_data, name, BKE_idcode_from_name(group), NULL);
2688                                 BLI_BITMAP_ENABLE(item->libraries, lib_idx);
2689                         }
2690                 }
2691                 RNA_END;
2692
2693                 BLI_ghash_free(libraries, MEM_freeN, NULL);
2694         }
2695         else {
2696                 WMLinkAppendDataItem *item;
2697
2698                 wm_link_append_data_library_add(lapp_data, libname);
2699                 item = wm_link_append_data_item_add(lapp_data, name, BKE_idcode_from_name(group), NULL);
2700                 BLI_BITMAP_ENABLE(item->libraries, 0);
2701         }
2702
2703         /* XXX We'd need re-entrant locking on Main for this to work... */
2704         /* BKE_main_lock(bmain); */
2705
2706         wm_link_do(lapp_data, op->reports, bmain, scene, CTX_wm_view3d(C));
2707
2708         /* BKE_main_unlock(bmain); */
2709
2710         wm_link_append_data_free(lapp_data);
2711
2712         /* mark all library linked objects to be updated */
2713         BKE_main_lib_objects_recalc_all(bmain);
2714         IMB_colormanagement_check_file_config(bmain);
2715
2716         /* append, rather than linking */
2717         if ((flag & FILE_LINK) == 0) {
2718                 bool set_fake = RNA_boolean_get(op->ptr, "set_fake");
2719                 BKE_library_make_local(bmain, NULL, true, set_fake);
2720         }
2721
2722         /* important we unset, otherwise these object wont
2723          * link into other scenes from this blend file */
2724         BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
2725
2726         /* recreate dependency graph to include new objects */
2727         DAG_scene_relations_rebuild(bmain, scene);
2728         
2729         /* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
2730         GPU_materials_free();
2731
2732         /* XXX TODO: align G.lib with other directory storage (like last opened image etc...) */
2733         BLI_strncpy(G.lib, root, FILE_MAX);
2734
2735         WM_event_add_notifier(C, NC_WINDOW, NULL);
2736
2737         return OPERATOR_FINISHED;
2738 }
2739
2740 static void wm_link_append_properties_common(wmOperatorType *ot, bool is_link)
2741 {
2742         PropertyRNA *prop;
2743
2744         /* better not save _any_ settings for this operator */
2745         /* properties */
2746         prop = RNA_def_boolean(ot->srna, "link", is_link,
2747                                "Link", "Link the objects or datablocks rather than appending");
2748         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
2749         prop = RNA_def_boolean(ot->srna, "autoselect", true,
2750                                "Select", "Select new objects");
2751         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2752         prop = RNA_def_boolean(ot->srna, "active_layer", true,
2753                                "Active Layer", "Put new objects on the active layer");
2754         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2755         prop = RNA_def_boolean(ot->srna, "instance_groups", is_link,
2756                                "Instance Groups", "Create Dupli-Group instances for each group");
2757         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2758 }
2759
2760 static void WM_OT_link(wmOperatorType *ot)
2761 {
2762         ot->name = "Link from Library";
2763         ot->idname = "WM_OT_link";
2764         ot->description = "Link from a Library .blend file";
2765         
2766         ot->invoke = wm_link_append_invoke;
2767         ot->exec = wm_link_append_exec;
2768         ot->poll = wm_link_append_poll;
2769         
2770         ot->flag |= OPTYPE_UNDO;
2771
2772         WM_operator_properties_filesel(
2773                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER | FILE_TYPE_BLENDERLIB, FILE_LOADLIB, FILE_OPENFILE,
2774                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_RELPATH | WM_FILESEL_FILES,
2775                 FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2776         
2777         wm_link_append_properties_common(ot, true);
2778 }
2779
2780 static void WM_OT_append(wmOperatorType *ot)
2781 {
2782         ot->name = "Append from Library";
2783         ot->idname = "WM_OT_append";
2784         ot->description = "Append from a Library .blend file";
2785
2786         ot->invoke = wm_link_append_invoke;
2787         ot->exec = wm_link_append_exec;
2788         ot->poll = wm_link_append_poll;
2789
2790         ot->flag |= OPTYPE_UNDO;
2791
2792         WM_operator_properties_filesel(
2793                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER | FILE_TYPE_BLENDERLIB, FILE_LOADLIB, FILE_OPENFILE,
2794                 WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILENAME | WM_FILESEL_FILES,
2795                 FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
2796
2797         wm_link_append_properties_common(ot, false);
2798         RNA_def_boolean(ot->srna, "set_fake", false, "Fake User", "Set Fake User for appended items (except Objects and Groups)");
2799 }
2800
2801 /* *************** recover last session **************** */
2802
2803 void WM_recover_last_session(bContext *C, ReportList *reports)
2804 {
2805         char filepath[FILE_MAX];
2806         
2807         BLI_make_file_string("/", filepath, BKE_tempdir_base(), BLENDER_QUIT_FILE);
2808         /* if reports==NULL, it's called directly without operator, we add a quick check here */
2809         if (reports || BLI_exists(filepath)) {
2810                 G.fileflags |= G_FILE_RECOVER;
2811                 
2812                 wm_file_read_opwrap(C, filepath, reports, true);
2813         
2814                 G.fileflags &= ~G_FILE_RECOVER;
2815                 
2816                 /* XXX bad global... fixme */
2817                 if (G.main->name[0])
2818                         G.file_loaded = 1;      /* prevents splash to show */
2819                 else {
2820                         G.relbase_valid = 0;
2821                         G.save_over = 0;    /* start with save preference untitled.blend */
2822                 }
2823
2824         }
2825 }
2826
2827 static int wm_recover_last_session_exec(bContext *C, wmOperator *op)
2828 {
2829         WM_recover_last_session(C, op->reports);
2830         return OPERATOR_FINISHED;
2831 }
2832
2833 static void WM_OT_recover_last_session(wmOperatorType *ot)
2834 {
2835         ot->name = "Recover Last Session";
2836         ot->idname = "WM_OT_recover_last_session";
2837         ot->description = "Open the last closed file (\"" BLENDER_QUIT_FILE "\")";
2838         ot->invoke = WM_operator_confirm;
2839         
2840         ot->exec = wm_recover_last_session_exec;
2841 }
2842
2843 /* *************** recover auto save **************** */
2844
2845 static int wm_recover_auto_save_exec(bContext *C, wmOperator *op)
2846 {
2847         char filepath[FILE_MAX];
2848         bool success;
2849
2850         RNA_string_get(op->ptr, "filepath", filepath);
2851
2852         G.fileflags |= G_FILE_RECOVER;
2853
2854         success = wm_file_read_opwrap(C, filepath, op->reports, true);
2855
2856         G.fileflags &= ~G_FILE_RECOVER;
2857         
2858         if (success) {
2859                 return OPERATOR_FINISHED;
2860         }
2861         else {
2862                 return OPERATOR_CANCELLED;
2863         }
2864 }
2865
2866 static int wm_recover_auto_save_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2867 {
2868         char filename[FILE_MAX];
2869
2870         wm_autosave_location(filename);
2871         RNA_string_set(op->ptr, "filepath", filename);
2872         WM_event_add_fileselect(C, op);
2873
2874         return OPERATOR_RUNNING_MODAL;
2875 }
2876
2877 static void WM_OT_recover_auto_save(wmOperatorType *ot)
2878 {
2879         ot->name = "Recover Auto Save";
2880         ot->idname = "WM_OT_recover_auto_save";
2881         ot->description = "Open an automatically saved file to recover it";
2882         
2883         ot->exec = wm_recover_auto_save_exec;
2884         ot->invoke = wm_recover_auto_save_invoke;
2885
2886         WM_operator_properties_filesel(
2887                 ot, FILE_TYPE_BLENDER, FILE_BLENDER, FILE_OPENFILE,
2888                 WM_FILESEL_FILEPATH, FILE_LONGDISPLAY, FILE_SORT_TIME);
2889 }
2890
2891 /* *************** save file as **************** */
2892
2893 static void wm_filepath_default(char *filepath)
2894 {
2895         if (G.save_over == false) {
2896                 BLI_ensure_filename(filepath, FILE_MAX, "untitled.blend");
2897         }
2898 }
2899
2900 static void save_set_compress(wmOperator *op)
2901 {
2902         PropertyRNA *prop;
2903
2904         prop = RNA_struct_find_property(op->ptr, "compress");
2905         if (!RNA_property_is_set(op->ptr, prop)) {
2906                 if (G.save_over) {  /* keep flag for existing file */
2907                         RNA_property_boolean_set(op->ptr, prop, (G.fileflags & G_FILE_COMPRESS) != 0);
2908                 }
2909                 else {  /* use userdef for new file */
2910                         RNA_property_boolean_set(op->ptr, prop, (U.flag & USER_FILECOMPRESS) != 0);
2911                 }
2912         }
2913 }
2914
2915 static void save_set_filepath(wmOperator *op)
2916 {
2917         PropertyRNA *prop;
2918         char name[FILE_MAX];
2919
2920         prop = RNA_struct_find_property(op->ptr, "filepath");
2921         if (!RNA_property_is_set(op->ptr, prop)) {
2922                 /* if not saved before, get the name of the most recently used .blend file */
2923                 if (G.main->name[0] == 0 && G.recent_files.first) {
2924                         struct RecentFile *recent = G.recent_files.first;
2925                         BLI_strncpy(name, recent->filepath, FILE_MAX);
2926                 }
2927                 else {
2928                         BLI_strncpy(name, G.main->name, FILE_MAX);
2929                 }
2930
2931                 wm_filepath_default(name);
2932                 RNA_property_string_set(op->ptr, prop, name);
2933         }
2934 }
2935
2936 static int wm_save_as_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
2937 {
2938
2939         save_set_compress(op);
2940         save_set_filepath(op);
2941         
2942         WM_event_add_fileselect(C, op);
2943
2944         return OPERATOR_RUNNING_MODAL;
2945 }
2946
2947 /* function used for WM_OT_save_mainfile too */
2948 static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
2949 {
2950         char path[FILE_MAX];
2951         int fileflags;
2952
2953         save_set_compress(op);
2954         
2955         if (RNA_struct_property_is_set(op->ptr, "filepath")) {
2956                 RNA_string_get(op->ptr, "filepath", path);
2957         }
2958         else {
2959                 BLI_strncpy(path, G.main->name, FILE_MAX);
2960                 wm_filepath_default(path);
2961         }
2962         
2963         fileflags = G.fileflags & ~G_FILE_USERPREFS;
2964
2965         /* set compression flag */
2966         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "compress"),
2967                          G_FILE_COMPRESS);
2968         BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
2969                          G_FILE_RELATIVE_REMAP);
2970         BKE_BIT_TEST_SET(fileflags,
2971                          (RNA_struct_property_is_set(op->ptr, "copy") &&
2972                           RNA_boolean_get(op->ptr, "copy")),
2973                          G_FILE_SAVE_COPY);
2974
2975 #ifdef USE_BMESH_SAVE_AS_COMPAT
2976         BKE_BIT_TEST_SET(fileflags,
2977                          (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
2978                           RNA_boolean_get(op->ptr, "use_mesh_compat")),
2979                          G_FILE_MESH_COMPAT);
2980 #else
2981 #  error "don't remove by accident"
2982 #endif
2983
2984         if (wm_file_write(C, path, fileflags, op->reports) != 0)
2985                 return OPERATOR_CANCELLED;
2986
2987         WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
2988
2989         return OPERATOR_FINISHED;
2990 }
2991
2992 /* function used for WM_OT_save_mainfile too */
2993 static bool blend_save_check(bContext *UNUSED(C), wmOperator *op)
2994 {
2995         char filepath[FILE_MAX];
2996         RNA_string_get(op->ptr, "filepath", filepath);
2997         if (!BLO_has_bfile_extension(filepath)) {
2998                 /* some users would prefer BLI_replace_extension(),
2999                  * we keep getting nitpicking bug reports about this - campbell */
3000                 BLI_ensure_extension(filepath, FILE_MAX, ".blend");
3001                 RNA_string_set(op->ptr, "filepath", filepath);
3002                 return true;
3003         }
3004         return false;
3005 }
3006
3007 static void WM_OT_save_as_mainfile(wmOperatorType *ot)
3008 {
3009         PropertyRNA *prop;
3010
3011         ot->name = "Save As Blender File";
3012         ot->idname = "WM_OT_save_as_mainfile";
3013         ot->description = "Save the current file in the desired location";
3014         
3015         ot->invoke = wm_save_as_mainfile_invoke;
3016         ot->exec = wm_save_as_mainfile_exec;
3017         ot->check = blend_save_check;
3018         /* omit window poll so this can work in background mode */
3019
3020         WM_operator_properties_filesel(
3021                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
3022                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
3023         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
3024         RNA_def_boolean(ot->srna, "relative_remap", true, "Remap Relative",
3025                         "Remap relative paths when saving in a different directory");
3026         prop = RNA_def_boolean(ot->srna, "copy", false, "Save Copy",
3027                         "Save a copy of the actual working state but does not make saved file active");
3028         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3029 #ifdef USE_BMESH_SAVE_AS_COMPAT
3030         RNA_def_boolean(ot->srna, "use_mesh_compat", false, "Legacy Mesh Format",
3031                         "Save using legacy mesh format (no ngons) - WARNING: only saves tris and quads, other ngons will "
3032                         "be lost (no implicit triangulation)");
3033 #endif
3034 }
3035
3036 /* *************** save file directly ******** */
3037
3038 static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
3039 {
3040         int ret;
3041         
3042         /* cancel if no active window */
3043         if (CTX_wm_window(C) == NULL)
3044                 return OPERATOR_CANCELLED;
3045
3046         save_set_compress(op);
3047         save_set_filepath(op);
3048
3049         /* if we're saving for the first time and prefer relative paths - any existing paths will be absolute,
3050          * enable the option to remap paths to avoid confusion [#37240] */
3051         if ((G.relbase_valid == false) && (U.flag & USER_RELPATHS)) {
3052                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "relative_remap");
3053                 if (!RNA_property_is_set(op->ptr, prop)) {
3054                         RNA_property_boolean_set(op->ptr, prop, true);
3055                 }
3056         }
3057
3058         if (G.save_over) {
3059                 char path[FILE_MAX];
3060
3061                 RNA_string_get(op->ptr, "filepath", path);
3062                 if (BLI_exists(path)) {
3063                         ret = WM_operator_confirm_message_ex(C, op, IFACE_("Save Over?"), ICON_QUESTION, path);
3064                 }
3065                 else {
3066                         ret = wm_save_as_mainfile_exec(C, op);
3067                 }
3068         }
3069         else {
3070                 WM_event_add_fileselect(C, op);
3071                 ret = OPERATOR_RUNNING_MODAL;
3072         }
3073         
3074         return ret;
3075 }
3076
3077 static void WM_OT_save_mainfile(wmOperatorType *ot)
3078 {
3079         ot->name = "Save Blender File";
3080         ot->idname = "WM_OT_save_mainfile";
3081         ot->description = "Save the current Blender file";
3082         
3083         ot->invoke = wm_save_mainfile_invoke;
3084         ot->exec = wm_save_as_mainfile_exec;
3085         ot->check = blend_save_check;
3086         /* omit window poll so this can work in background mode */
3087         
3088         WM_operator_properties_filesel(
3089                 ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
3090                 WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
3091         RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
3092         RNA_def_boolean(ot->srna, "relative_remap", false, "Remap Relative",
3093                         "Remap relative paths when saving in a different directory");
3094 }
3095
3096 static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
3097 {
3098         ot->name = "Toggle Window Fullscreen";
3099         ot->idname = "WM_OT_window_fullscreen_toggle";
3100         ot->description = "Toggle the current window fullscreen";
3101
3102         ot->exec = wm_window_fullscreen_toggle_exec;
3103         ot->poll = WM_operator_winactive;
3104 }
3105
3106 static int wm_exit_blender_exec(bContext *C, wmOperator *op)
3107 {
3108         WM_operator_free(op);
3109         
3110         WM_exit(C);
3111         
3112         return OPERATOR_FINISHED;
3113 }
3114
3115 static void WM_OT_quit_blender(wmOperatorType *ot)
3116 {
3117         ot->name = "Quit Blender";
3118         ot->idname = "WM_OT_quit_blender";
3119         ot->description = "Quit Blender";
3120
3121         ot->invoke = WM_operator_confirm;
3122         ot->exec = wm_exit_blender_exec;
3123 }
3124
3125 /* *********************** */
3126
3127 #if defined(WIN32)
3128
3129 static int wm_console_toggle_exec(bContext *UNUSED(C), wmOperator *UNUSED(op))
3130 {
3131         GHOST_toggleConsole(2);
3132         return OPERATOR_FINISHED;
3133 }
3134
3135 static void WM_OT_console_toggle(wmOperatorType *ot)
3136 {
3137         /* XXX Have to mark these for xgettext, as under linux they do not exists... */
3138         ot->name = CTX_N_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Toggle System Console");
3139         ot->idname = "WM_OT_console_toggle";
3140         ot->description = N_("Toggle System Console");
3141         
3142         ot->exec = wm_console_toggle_exec;
3143         ot->poll = WM_operator_winactive;
3144 }
3145
3146 #endif
3147
3148 /* ************ default paint cursors, draw always around cursor *********** */
3149 /*
3150  * - returns handler to free
3151  * - poll(bContext): returns 1 if draw should happen
3152  * - draw(bContext): drawing callback for paint cursor
3153  */
3154
3155 void *WM_paint_cursor_activate(wmWindowManager *wm, int (*poll)(bContext *C),
3156                                wmPaintCursorDraw draw, void *customdata)
3157 {
3158         wmPaintCursor *pc = MEM_callocN(sizeof(wmPaintCursor), "paint cursor");
3159         
3160         BLI_addtail(&wm->paintcursors, pc);
3161         
3162         pc->customdata = customdata;
3163         pc->poll = poll;
3164         pc->draw = draw;
3165         
3166         return pc;
3167 }
3168
3169 void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
3170 {
3171         wmPaintCursor *pc;
3172         
3173         for (pc = wm->paintcursors.first; pc; pc = pc->next) {
3174                 if (pc == (wmPaintCursor *)handle) {
3175                         BLI_remlink(&wm->paintcursors, pc);
3176                         MEM_freeN(pc);
3177                         return;
3178                 }
3179         }
3180 }
3181
3182 /* ************ window gesture operator-callback definitions ************** */
3183 /*
3184  * These are default callbacks for use in operators requiring gesture input
3185  */
3186
3187 /* **************** Border gesture *************** */
3188
3189 /**
3190  * Border gesture has two types:
3191  * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
3192  * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
3193  *
3194  * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
3195  */
3196
3197 static int border_apply_rect(wmOperator *op)
3198 {
3199         wmGesture *gesture = op->customdata;
3200         rcti *rect = gesture->customdata;
3201         
3202         if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
3203                 return 0;
3204
3205         
3206         /* operator arguments and storage. */
3207         RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
3208         RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
3209         RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
3210         RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
3211
3212         return 1;
3213 }
3214
3215 static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
3216 {
3217         PropertyRNA *prop;
3218
3219         int retval;
3220
3221         if (!border_apply_rect(op))
3222                 return 0;
3223         
3224         /* XXX weak; border should be configured for this without reading event types */
3225         if ((prop = RNA_struct_find_property(op->ptr, "gesture_mode"))) {
3226                 RNA_property_int_set(op->ptr, prop, gesture_mode);
3227         }
3228
3229         retval = op->type->exec(C, op);
3230         OPERATOR_RETVAL_CHECK(retval);
3231
3232         return 1;
3233 }
3234
3235 static void wm_gesture_end(bContext *C, wmOperator *op)
3236 {
3237         wmGesture *gesture = op->customdata;
3238         
3239         WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
3240         op->customdata = NULL;
3241
3242         ED_area_tag_redraw(CTX_wm_area(C));
3243         
3244         if (RNA_struct_find_property(op->ptr, "cursor")) {
3245                 WM_cursor_modal_restore(CTX_wm_window(C));
3246         }
3247 }
3248
3249 int WM_border_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
3250 {
3251         if (ISTWEAK(event->type))
3252                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
3253         else
3254                 op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
3255
3256         /* add modal handler */
3257         WM_event_add_modal_handler(C, op);
3258         
3259         wm_gesture_tag_redraw(C);
3260
3261         return OPERATOR_RUNNING_MODAL;
3262 }
3263
3264 int WM_border_select_modal(bContext *C, wmOperator *op, const wmEvent *event)
3265 {
3266         wmGesture *gesture = op->customdata;
3267         rcti *rect = gesture->customdata;
3268         int sx, sy;
3269         
3270         if (event->type == MOUSEMOVE) {
3271                 wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
3272
3273                 if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
3274                         rect->xmin = rect->xmax = event->x - sx;
3275                         rect->ymin = rect->ymax = event->y - sy;
3276                 }
3277                 else {
3278                         rect->xmax = event->x - sx;