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