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