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