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