NDOF: compile 3D mouse code only if WITH_INPUT_NDOF
[blender-staging.git] / source / blender / windowmanager / intern / wm_event_system.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_event_system.c
28  *  \ingroup wm
29  *
30  * Handle events and notifiers from GHOST input (mouse, keyboard, tablet, ndof).
31  *
32  * Also some operator reports utility functions.
33  */
34
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include "DNA_listBase.h"
39 #include "DNA_screen_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_windowmanager_types.h"
42 #include "DNA_userdef_types.h"
43
44 #include "MEM_guardedalloc.h"
45
46 #include "GHOST_C-api.h"
47
48 #include "BLI_blenlib.h"
49 #include "BLI_dynstr.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_math.h"
52
53 #include "BKE_context.h"
54 #include "BKE_idprop.h"
55 #include "BKE_global.h"
56 #include "BKE_main.h"
57 #include "BKE_report.h"
58 #include "BKE_scene.h"
59 #include "BKE_screen.h"
60
61 #include "BKE_sound.h"
62
63 #include "ED_fileselect.h"
64 #include "ED_info.h"
65 #include "ED_screen.h"
66 #include "ED_view3d.h"
67 #include "ED_util.h"
68
69 #include "RNA_access.h"
70
71 #include "GPU_debug.h"
72
73 #include "UI_interface.h"
74
75 #include "PIL_time.h"
76
77 #include "WM_api.h"
78 #include "WM_types.h"
79 #include "wm.h"
80 #include "wm_window.h"
81 #include "wm_event_system.h"
82 #include "wm_event_types.h"
83
84 #include "RNA_enum_types.h"
85
86 static void wm_notifier_clear(wmNotifier *note);
87 static void update_tablet_data(wmWindow *win, wmEvent *event);
88
89 static int wm_operator_call_internal(bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
90                                      const short context, const bool poll_only);
91
92 /* ************ event management ************** */
93
94 void wm_event_add_ex(wmWindow *win, const wmEvent *event_to_add, const wmEvent *event_to_add_after)
95 {
96         wmEvent *event = MEM_mallocN(sizeof(wmEvent), "wmEvent");
97         
98         *event = *event_to_add;
99
100         update_tablet_data(win, event);
101
102         if (event_to_add_after == NULL) {
103                 BLI_addtail(&win->queue, event);
104         }
105         else {
106                 /* note, strictly speaking this breaks const-correctness, however we're only changing 'next' member */
107                 BLI_insertlinkafter(&win->queue, (void *)event_to_add_after, event);
108         }
109 }
110
111 void wm_event_add(wmWindow *win, const wmEvent *event_to_add)
112 {
113         wm_event_add_ex(win, event_to_add, NULL);
114 }
115
116 void wm_event_free(wmEvent *event)
117 {
118         if (event->customdata) {
119                 if (event->customdatafree) {
120                         /* note: pointer to listbase struct elsewhere */
121                         if (event->custom == EVT_DATA_DRAGDROP) {
122                                 ListBase *lb = event->customdata;
123                                 WM_drag_free_list(lb);
124                         }
125                         else {
126                                 MEM_freeN(event->customdata);
127                         }
128                 }
129         }
130
131         if (event->tablet_data) {
132                 MEM_freeN((void *)event->tablet_data);
133         }
134
135         MEM_freeN(event);
136 }
137
138 void wm_event_free_all(wmWindow *win)
139 {
140         wmEvent *event;
141         
142         while ((event = BLI_pophead(&win->queue))) {
143                 wm_event_free(event);
144         }
145 }
146
147 void wm_event_init_from_window(wmWindow *win, wmEvent *event)
148 {
149         /* make sure we don't copy any owned pointers */
150         BLI_assert(win->eventstate->tablet_data == NULL);
151
152         *event = *(win->eventstate);
153 }
154
155 /* ********************* notifiers, listeners *************** */
156
157 static bool wm_test_duplicate_notifier(wmWindowManager *wm, unsigned int type, void *reference)
158 {
159         wmNotifier *note;
160
161         for (note = wm->queue.first; note; note = note->next)
162                 if ((note->category | note->data | note->subtype | note->action) == type && note->reference == reference)
163                         return 1;
164         
165         return 0;
166 }
167
168 /* XXX: in future, which notifiers to send to other windows? */
169 void WM_event_add_notifier(const bContext *C, unsigned int type, void *reference)
170 {
171         ARegion *ar;
172         wmWindowManager *wm = CTX_wm_manager(C);
173         wmNotifier *note;
174
175         if (wm_test_duplicate_notifier(wm, type, reference))
176                 return;
177
178         note = MEM_callocN(sizeof(wmNotifier), "notifier");
179         
180         note->wm = wm;
181         BLI_addtail(&note->wm->queue, note);
182         
183         note->window = CTX_wm_window(C);
184         
185         ar = CTX_wm_region(C);
186         if (ar)
187                 note->swinid = ar->swinid;
188         
189         note->category = type & NOTE_CATEGORY;
190         note->data = type & NOTE_DATA;
191         note->subtype = type & NOTE_SUBTYPE;
192         note->action = type & NOTE_ACTION;
193         
194         note->reference = reference;
195 }
196
197 void WM_main_add_notifier(unsigned int type, void *reference)
198 {
199         Main *bmain = G.main;
200         wmWindowManager *wm = bmain->wm.first;
201         wmNotifier *note;
202
203         if (!wm || wm_test_duplicate_notifier(wm, type, reference))
204                 return;
205
206         note = MEM_callocN(sizeof(wmNotifier), "notifier");
207         
208         note->wm = wm;
209         BLI_addtail(&note->wm->queue, note);
210         
211         note->category = type & NOTE_CATEGORY;
212         note->data = type & NOTE_DATA;
213         note->subtype = type & NOTE_SUBTYPE;
214         note->action = type & NOTE_ACTION;
215         
216         note->reference = reference;
217 }
218
219 /**
220  * Clear notifiers by reference, Used so listeners don't act on freed data.
221  */
222 void WM_main_remove_notifier_reference(const void *reference)
223 {
224         Main *bmain = G.main;
225         wmWindowManager *wm = bmain->wm.first;
226
227         if (wm) {
228                 wmNotifier *note, *note_next;
229
230                 for (note = wm->queue.first; note; note = note_next) {
231                         note_next = note->next;
232
233                         if (note->reference == reference) {
234                                 /* don't remove because this causes problems for #wm_event_do_notifiers
235                                  * which may be looping on the data (deleting screens) */
236                                 wm_notifier_clear(note);
237                         }
238                 }
239         }
240 }
241
242 void WM_main_remap_editor_id_reference(ID *old_id, ID *new_id)
243 {
244         Main *bmain = G.main;
245         bScreen *sc;
246
247         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
248                 ScrArea *sa;
249
250                 for (sa = sc->areabase.first; sa; sa = sa->next) {
251                         SpaceLink *sl;
252
253                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
254                                 ED_spacedata_id_remap(sa, sl, old_id, new_id);
255                         }
256                 }
257         }
258 }
259
260 static void wm_notifier_clear(wmNotifier *note)
261 {
262         /* NULL the entire notifier, only leaving (next, prev) members intact */
263         memset(((char *)note) + sizeof(Link), 0, sizeof(*note) - sizeof(Link));
264 }
265
266 /* called in mainloop */
267 void wm_event_do_notifiers(bContext *C)
268 {
269         wmWindowManager *wm = CTX_wm_manager(C);
270         wmNotifier *note, *next;
271         wmWindow *win;
272         uint64_t win_combine_v3d_datamask = 0;
273         
274         if (wm == NULL)
275                 return;
276         
277         /* cache & catch WM level notifiers, such as frame change, scene/screen set */
278         for (win = wm->windows.first; win; win = win->next) {
279                 bool do_anim = false;
280                 
281                 CTX_wm_window_set(C, win);
282                 
283                 for (note = wm->queue.first; note; note = next) {
284                         next = note->next;
285
286                         if (note->category == NC_WM) {
287                                 if (ELEM(note->data, ND_FILEREAD, ND_FILESAVE)) {
288                                         wm->file_saved = 1;
289                                         wm_window_title(wm, win);
290                                 }
291                                 else if (note->data == ND_DATACHANGED)
292                                         wm_window_title(wm, win);
293                         }
294                         if (note->window == win) {
295                                 if (note->category == NC_SCREEN) {
296                                         if (note->data == ND_SCREENBROWSE) {
297                                                 /* free popup handlers only [#35434] */
298                                                 UI_popup_handlers_remove_all(C, &win->modalhandlers);
299
300
301                                                 ED_screen_set(C, note->reference);  // XXX hrms, think this over!
302                                                 if (G.debug & G_DEBUG_EVENTS)
303                                                         printf("%s: screen set %p\n", __func__, note->reference);
304                                         }
305                                         else if (note->data == ND_SCREENDELETE) {
306                                                 ED_screen_delete(C, note->reference);   // XXX hrms, think this over!
307                                                 if (G.debug & G_DEBUG_EVENTS)
308                                                         printf("%s: screen delete %p\n", __func__, note->reference);
309                                         }
310                                 }
311                         }
312
313                         if (note->window == win ||
314                             (note->window == NULL && (note->reference == NULL || note->reference == win->screen->scene)))
315                         {
316                                 if (note->category == NC_SCENE) {
317                                         if (note->data == ND_FRAME)
318                                                 do_anim = true;
319                                 }
320                         }
321                         if (ELEM(note->category, NC_SCENE, NC_OBJECT, NC_GEOM, NC_WM)) {
322                                 ED_info_stats_clear(win->screen->scene);
323                                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO, NULL);
324                         }
325                 }
326                 if (do_anim) {
327
328                         /* XXX, quick frame changes can cause a crash if framechange and rendering
329                          * collide (happens on slow scenes), BKE_scene_update_for_newframe can be called
330                          * twice which can depgraph update the same object at once */
331                         if (G.is_rendering == false) {
332
333                                 /* depsgraph gets called, might send more notifiers */
334                                 ED_update_for_newframe(CTX_data_main(C), win->screen->scene, 1);
335                         }
336                 }
337         }
338         
339         /* the notifiers are sent without context, to keep it clean */
340         while ((note = BLI_pophead(&wm->queue))) {
341                 for (win = wm->windows.first; win; win = win->next) {
342                         
343                         /* filter out notifiers */
344                         if (note->category == NC_SCREEN && note->reference && note->reference != win->screen) {
345                                 /* pass */
346                         }
347                         else if (note->category == NC_SCENE && note->reference && note->reference != win->screen->scene) {
348                                 /* pass */
349                         }
350                         else {
351                                 ScrArea *sa;
352                                 ARegion *ar;
353
354                                 /* XXX context in notifiers? */
355                                 CTX_wm_window_set(C, win);
356
357                                 /* printf("notifier win %d screen %s cat %x\n", win->winid, win->screen->id.name + 2, note->category); */
358                                 ED_screen_do_listen(C, note);
359
360                                 for (ar = win->screen->regionbase.first; ar; ar = ar->next) {
361                                         ED_region_do_listen(win->screen, NULL, ar, note);
362                                 }
363                                 
364                                 for (sa = win->screen->areabase.first; sa; sa = sa->next) {
365                                         ED_area_do_listen(win->screen, sa, note);
366                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
367                                                 ED_region_do_listen(win->screen, sa, ar, note);
368                                         }
369                                 }
370                         }
371                 }
372                 
373                 MEM_freeN(note);
374         }
375         
376         /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
377         for (win = wm->windows.first; win; win = win->next) {
378                 win_combine_v3d_datamask |= ED_view3d_screen_datamask(win->screen);
379         }
380
381         /* cached: editor refresh callbacks now, they get context */
382         for (win = wm->windows.first; win; win = win->next) {
383                 ScrArea *sa;
384                 
385                 CTX_wm_window_set(C, win);
386                 for (sa = win->screen->areabase.first; sa; sa = sa->next) {
387                         if (sa->do_refresh) {
388                                 CTX_wm_area_set(C, sa);
389                                 ED_area_do_refresh(C, sa);
390                         }
391                 }
392                 
393                 /* XXX make lock in future, or separated derivedmesh users in scene */
394                 if (G.is_rendering == false) {
395                         /* depsgraph & animation: update tagged datablocks */
396                         Main *bmain = CTX_data_main(C);
397
398                         /* copied to set's in scene_update_tagged_recursive() */
399                         win->screen->scene->customdata_mask = win_combine_v3d_datamask;
400
401                         /* XXX, hack so operators can enforce datamasks [#26482], gl render */
402                         win->screen->scene->customdata_mask |= win->screen->scene->customdata_mask_modal;
403
404                         BKE_scene_update_tagged(bmain->eval_ctx, bmain, win->screen->scene);
405                 }
406         }
407
408         CTX_wm_window_set(C, NULL);
409 }
410
411 static int wm_event_always_pass(const wmEvent *event)
412 {
413         /* some events we always pass on, to ensure proper communication */
414         return ISTIMER(event->type) || (event->type == WINDEACTIVATE);
415 }
416
417 /* ********************* ui handler ******************* */
418
419 static int wm_handler_ui_call(bContext *C, wmEventHandler *handler, const wmEvent *event, int always_pass)
420 {
421         ScrArea *area = CTX_wm_area(C);
422         ARegion *region = CTX_wm_region(C);
423         ARegion *menu = CTX_wm_menu(C);
424         static bool do_wheel_ui = true;
425         const bool is_wheel = ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, MOUSEPAN);
426         int retval;
427         
428         /* UI code doesn't handle return values - it just always returns break. 
429          * to make the DBL_CLICK conversion work, we just don't send this to UI, except mouse clicks */
430         if (((handler->flag & WM_HANDLER_ACCEPT_DBL_CLICK) == 0) &&
431             (event->type != LEFTMOUSE) &&
432             (event->val == KM_DBL_CLICK))
433         {
434                 return WM_HANDLER_CONTINUE;
435         }
436         
437         /* UI is quite aggressive with swallowing events, like scrollwheel */
438         /* I realize this is not extremely nice code... when UI gets keymaps it can be maybe smarter */
439         if (do_wheel_ui == false) {
440                 if (is_wheel)
441                         return WM_HANDLER_CONTINUE;
442                 else if (wm_event_always_pass(event) == 0)
443                         do_wheel_ui = true;
444         }
445         
446         /* we set context to where ui handler came from */
447         if (handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
448         if (handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
449         if (handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
450
451         retval = handler->ui_handle(C, event, handler->ui_userdata);
452
453         /* putting back screen context */
454         if ((retval != WM_UI_HANDLER_BREAK) || always_pass) {
455                 CTX_wm_area_set(C, area);
456                 CTX_wm_region_set(C, region);
457                 CTX_wm_menu_set(C, menu);
458         }
459         else {
460                 /* this special cases is for areas and regions that get removed */
461                 CTX_wm_area_set(C, NULL);
462                 CTX_wm_region_set(C, NULL);
463                 CTX_wm_menu_set(C, NULL);
464         }
465         
466         if (retval == WM_UI_HANDLER_BREAK)
467                 return WM_HANDLER_BREAK;
468         
469         /* event not handled in UI, if wheel then we temporarily disable it */
470         if (is_wheel)
471                 do_wheel_ui = false;
472         
473         return WM_HANDLER_CONTINUE;
474 }
475
476 static void wm_handler_ui_cancel(bContext *C)
477 {
478         wmWindow *win = CTX_wm_window(C);
479         ARegion *ar = CTX_wm_region(C);
480         wmEventHandler *handler, *nexthandler;
481
482         if (!ar)
483                 return;
484
485         for (handler = ar->handlers.first; handler; handler = nexthandler) {
486                 nexthandler = handler->next;
487
488                 if (handler->ui_handle) {
489                         wmEvent event;
490
491                         wm_event_init_from_window(win, &event);
492                         event.type = EVT_BUT_CANCEL;
493                         handler->ui_handle(C, &event, handler->ui_userdata);
494                 }
495         }
496 }
497
498 /* ********************* operators ******************* */
499
500 int WM_operator_poll(bContext *C, wmOperatorType *ot)
501 {
502         wmOperatorTypeMacro *otmacro;
503         
504         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
505                 wmOperatorType *ot_macro = WM_operatortype_find(otmacro->idname, 0);
506                 
507                 if (0 == WM_operator_poll(C, ot_macro))
508                         return 0;
509         }
510         
511         /* python needs operator type, so we added exception for it */
512         if (ot->pyop_poll)
513                 return ot->pyop_poll(C, ot);
514         else if (ot->poll)
515                 return ot->poll(C);
516
517         return 1;
518 }
519
520 /* sets up the new context and calls 'wm_operator_invoke()' with poll_only */
521 int WM_operator_poll_context(bContext *C, wmOperatorType *ot, short context)
522 {
523         return wm_operator_call_internal(C, ot, NULL, NULL, context, true);
524 }
525
526 static void wm_operator_print(bContext *C, wmOperator *op)
527 {
528         /* context is needed for enum function */
529         char *buf = WM_operator_pystring(C, op, false, true);
530         puts(buf);
531         MEM_freeN(buf);
532 }
533
534 /**
535  * Sets the active region for this space from the context.
536  *
537  * \see #BKE_area_find_region_active_win
538  */
539 void WM_operator_region_active_win_set(bContext *C)
540 {
541         ScrArea *sa = CTX_wm_area(C);
542         if (sa) {
543                 ARegion *ar = CTX_wm_region(C);
544                 if (ar && ar->regiontype == RGN_TYPE_WINDOW) {
545                         sa->region_active_win = BLI_findindex(&sa->regionbase, ar);
546                 }
547         }
548 }
549
550 /* for debugging only, getting inspecting events manually is tedious */
551 void WM_event_print(const wmEvent *event)
552 {
553         if (event) {
554                 const char *unknown = "UNKNOWN";
555                 const char *type_id = unknown;
556                 const char *val_id = unknown;
557
558                 RNA_enum_identifier(rna_enum_event_type_items, event->type, &type_id);
559                 RNA_enum_identifier(rna_enum_event_value_items, event->val, &val_id);
560
561                 printf("wmEvent  type:%d / %s, val:%d / %s,\n"
562                        "         shift:%d, ctrl:%d, alt:%d, oskey:%d, keymodifier:%d,\n"
563                        "         mouse:(%d,%d), ascii:'%c', utf8:'%.*s', keymap_idname:%s, pointer:%p\n",
564                        event->type, type_id, event->val, val_id,
565                        event->shift, event->ctrl, event->alt, event->oskey, event->keymodifier,
566                        event->x, event->y, event->ascii,
567                        BLI_str_utf8_size(event->utf8_buf), event->utf8_buf,
568                        event->keymap_idname, (const void *)event);
569
570 #ifdef WITH_INPUT_NDOF
571                 if (ISNDOF(event->type)) {
572                         const wmNDOFMotionData *ndof = event->customdata;
573                         if (event->type == NDOF_MOTION) {
574                                 printf("   ndof: rot: (%.4f %.4f %.4f), tx: (%.4f %.4f %.4f), dt: %.4f, progress: %u\n",
575                                        UNPACK3(ndof->rvec), UNPACK3(ndof->tvec), ndof->dt, ndof->progress);
576                         }
577                         else {
578                                 /* ndof buttons printed already */
579                         }
580                 }
581 #endif /* WITH_INPUT_NDOF */
582
583                 if (event->tablet_data) {
584                         const wmTabletData *wmtab = event->tablet_data;
585                         printf(" tablet: active: %d, pressure %.4f, tilt: (%.4f %.4f)\n",
586                                wmtab->Active, wmtab->Pressure, wmtab->Xtilt, wmtab->Ytilt);
587                 }
588         }
589         else {
590                 printf("wmEvent - NULL\n");
591         }
592 }
593
594 /**
595  * Show the report in the info header.
596  */
597 void WM_report_banner_show(void)
598 {
599         wmWindowManager *wm = G.main->wm.first;
600         ReportList *wm_reports = &wm->reports;
601         ReportTimerInfo *rti;
602
603         /* After adding reports to the global list, reset the report timer. */
604         WM_event_remove_timer(wm, NULL, wm_reports->reporttimer);
605
606         /* Records time since last report was added */
607         wm_reports->reporttimer = WM_event_add_timer(wm, wm->winactive, TIMERREPORT, 0.05);
608
609         rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
610         wm_reports->reporttimer->customdata = rti;
611 }
612
613 bool WM_event_is_absolute(const wmEvent *event)
614 {
615         return (event->tablet_data != NULL);
616 }
617
618 #ifdef WITH_INPUT_NDOF
619 void WM_ndof_deadzone_set(float deadzone)
620 {
621         GHOST_setNDOFDeadZone(deadzone);
622 }
623 #endif
624
625 static void wm_add_reports(ReportList *reports)
626 {
627         /* if the caller owns them, handle this */
628         if (reports->list.first && (reports->flag & RPT_OP_HOLD) == 0) {
629                 wmWindowManager *wm = G.main->wm.first;
630
631                 /* add reports to the global list, otherwise they are not seen */
632                 BLI_movelisttolist(&wm->reports.list, &reports->list);
633
634                 WM_report_banner_show();
635         }
636 }
637
638 void WM_report(ReportType type, const char *message)
639 {
640         ReportList reports;
641
642         BKE_reports_init(&reports, RPT_STORE);
643         BKE_report(&reports, type, message);
644
645         wm_add_reports(&reports);
646
647         BKE_reports_clear(&reports);
648 }
649
650 void WM_reportf(ReportType type, const char *format, ...)
651 {
652         DynStr *ds;
653         va_list args;
654
655         ds = BLI_dynstr_new();
656         va_start(args, format);
657         BLI_dynstr_vappendf(ds, format, args);
658         va_end(args);
659
660         char *str = BLI_dynstr_get_cstring(ds);
661         WM_report(type, str);
662         MEM_freeN(str);
663
664         BLI_dynstr_free(ds);
665 }
666
667 /* (caller_owns_reports == true) when called from python */
668 static void wm_operator_reports(bContext *C, wmOperator *op, int retval, bool caller_owns_reports)
669 {
670         if (caller_owns_reports == false) { /* popup */
671                 if (op->reports->list.first) {
672                         /* FIXME, temp setting window, see other call to UI_popup_menu_reports for why */
673                         wmWindow *win_prev = CTX_wm_window(C);
674                         ScrArea *area_prev = CTX_wm_area(C);
675                         ARegion *ar_prev = CTX_wm_region(C);
676
677                         if (win_prev == NULL)
678                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
679
680                         UI_popup_menu_reports(C, op->reports);
681
682                         CTX_wm_window_set(C, win_prev);
683                         CTX_wm_area_set(C, area_prev);
684                         CTX_wm_region_set(C, ar_prev);
685                 }
686         }
687         
688         if (retval & OPERATOR_FINISHED) {
689                 if (G.debug & G_DEBUG_WM) {
690                         /* todo - this print may double up, might want to check more flags then the FINISHED */
691                         wm_operator_print(C, op);
692                 }
693
694                 if (caller_owns_reports == false) {
695                         BKE_reports_print(op->reports, RPT_DEBUG); /* print out reports to console. */
696                 }
697
698                 if (op->type->flag & OPTYPE_REGISTER) {
699                         if (G.background == 0) { /* ends up printing these in the terminal, gets annoying */
700                                 /* Report the python string representation of the operator */
701                                 char *buf = WM_operator_pystring(C, op, false, true);
702                                 BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
703                                 MEM_freeN(buf);
704                         }
705                 }
706         }
707
708         /* if the caller owns them, handle this */
709         wm_add_reports(op->reports);
710 }
711
712 /**
713  * This function is mainly to check that the rules for freeing
714  * an operator are kept in sync.
715  */
716 static bool wm_operator_register_check(wmWindowManager *wm, wmOperatorType *ot)
717 {
718         return wm && (wm->op_undo_depth == 0) && (ot->flag & OPTYPE_REGISTER);
719 }
720
721 static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat)
722 {
723         wmWindowManager *wm = CTX_wm_manager(C);
724
725         op->customdata = NULL;
726
727         /* we don't want to do undo pushes for operators that are being
728          * called from operators that already do an undo push. usually
729          * this will happen for python operators that call C operators */
730         if (wm->op_undo_depth == 0)
731                 if (op->type->flag & OPTYPE_UNDO)
732                         ED_undo_push_op(C, op);
733         
734         if (repeat == 0) {
735                 if (G.debug & G_DEBUG_WM) {
736                         char *buf = WM_operator_pystring(C, op, false, true);
737                         BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
738                         MEM_freeN(buf);
739                 }
740
741                 if (wm_operator_register_check(wm, op->type)) {
742                         /* take ownership of reports (in case python provided own) */
743                         op->reports->flag |= RPT_FREE;
744
745                         wm_operator_register(C, op);
746                         WM_operator_region_active_win_set(C);
747                 }
748                 else {
749                         WM_operator_free(op);
750                 }
751         }
752 }
753
754 /* if repeat is true, it doesn't register again, nor does it free */
755 static int wm_operator_exec(bContext *C, wmOperator *op, const bool repeat, const bool store)
756 {
757         wmWindowManager *wm = CTX_wm_manager(C);
758         int retval = OPERATOR_CANCELLED;
759         
760         CTX_wm_operator_poll_msg_set(C, NULL);
761         
762         if (op == NULL || op->type == NULL)
763                 return retval;
764         
765         if (0 == WM_operator_poll(C, op->type))
766                 return retval;
767         
768         if (op->type->exec) {
769                 if (op->type->flag & OPTYPE_UNDO)
770                         wm->op_undo_depth++;
771
772                 retval = op->type->exec(C, op);
773                 OPERATOR_RETVAL_CHECK(retval);
774
775                 if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
776                         wm->op_undo_depth--;
777         }
778         
779         /* XXX Disabled the repeat check to address part 2 of #31840.
780          *     Carefully checked all calls to wm_operator_exec and WM_operator_repeat, don't see any reason
781          *     why this was needed, but worth to note it in case something turns bad. (mont29) */
782         if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED) /* && repeat == 0 */)
783                 wm_operator_reports(C, op, retval, false);
784         
785         if (retval & OPERATOR_FINISHED) {
786                 if (store) {
787                         if (wm->op_undo_depth == 0) { /* not called by py script */
788                                 WM_operator_last_properties_store(op);
789                         }
790                 }
791                 wm_operator_finished(C, op, repeat);
792         }
793         else if (repeat == 0) {
794                 /* warning: modal from exec is bad practice, but avoid crashing. */
795                 if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) {
796                         WM_operator_free(op);
797                 }
798         }
799         
800         return retval | OPERATOR_HANDLED;
801         
802 }
803
804 /* simply calls exec with basic checks */
805 static int wm_operator_exec_notest(bContext *C, wmOperator *op)
806 {
807         int retval = OPERATOR_CANCELLED;
808
809         if (op == NULL || op->type == NULL || op->type->exec == NULL)
810                 return retval;
811
812         retval = op->type->exec(C, op);
813         OPERATOR_RETVAL_CHECK(retval);
814
815         return retval;
816 }
817
818 /**
819  * for running operators with frozen context (modal handlers, menus)
820  *
821  * \param store Store settings for re-use.
822  *
823  * warning: do not use this within an operator to call its self! [#29537] */
824 int WM_operator_call_ex(bContext *C, wmOperator *op,
825                         const bool store)
826 {
827         return wm_operator_exec(C, op, false, store);
828 }
829
830 int WM_operator_call(bContext *C, wmOperator *op)
831 {
832         return WM_operator_call_ex(C, op, false);
833 }
834
835 /**
836  * This is intended to be used when an invoke operator wants to call exec on its self
837  * and is basically like running op->type->exec() directly, no poll checks no freeing,
838  * since we assume whoever called invoke will take care of that
839  */
840 int WM_operator_call_notest(bContext *C, wmOperator *op)
841 {
842         return wm_operator_exec_notest(C, op);
843 }
844
845 /**
846  * Execute this operator again, put here so it can share above code
847  */
848 int WM_operator_repeat(bContext *C, wmOperator *op)
849 {
850         return wm_operator_exec(C, op, true, true);
851 }
852 /**
853  * \return true if #WM_operator_repeat can run
854  * simple check for now but may become more involved.
855  * To be sure the operator can run call `WM_operator_poll(C, op->type)` also, since this call
856  * checks if WM_operator_repeat() can run at all, not that it WILL run at any time.
857  */
858 bool WM_operator_repeat_check(const bContext *UNUSED(C), wmOperator *op)
859 {
860         if (op->type->exec != NULL) {
861                 return true;
862         }
863         else if (op->opm) {
864                 /* for macros, check all have exec() we can call */
865                 wmOperatorTypeMacro *otmacro;
866                 for (otmacro = op->opm->type->macro.first; otmacro; otmacro = otmacro->next) {
867                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
868                         if (otm && otm->exec == NULL) {
869                                 return false;
870                         }
871                 }
872                 return true;
873         }
874
875         return false;
876 }
877
878 static wmOperator *wm_operator_create(wmWindowManager *wm, wmOperatorType *ot,
879                                       PointerRNA *properties, ReportList *reports)
880 {
881         /* XXX operatortype names are static still. for debug */
882         wmOperator *op = MEM_callocN(sizeof(wmOperator), ot->idname);
883         
884         /* XXX adding new operator could be function, only happens here now */
885         op->type = ot;
886         BLI_strncpy(op->idname, ot->idname, OP_MAX_TYPENAME);
887         
888         /* initialize properties, either copy or create */
889         op->ptr = MEM_callocN(sizeof(PointerRNA), "wmOperatorPtrRNA");
890         if (properties && properties->data) {
891                 op->properties = IDP_CopyProperty(properties->data);
892         }
893         else {
894                 IDPropertyTemplate val = {0};
895                 op->properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
896         }
897         RNA_pointer_create(&wm->id, ot->srna, op->properties, op->ptr);
898
899         /* initialize error reports */
900         if (reports) {
901                 op->reports = reports; /* must be initialized already */
902         }
903         else {
904                 op->reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
905                 BKE_reports_init(op->reports, RPT_STORE | RPT_FREE);
906         }
907         
908         /* recursive filling of operator macro list */
909         if (ot->macro.first) {
910                 static wmOperator *motherop = NULL;
911                 wmOperatorTypeMacro *otmacro;
912                 int root = 0;
913                 
914                 /* ensure all ops are in execution order in 1 list */
915                 if (motherop == NULL) {
916                         motherop = op;
917                         root = 1;
918                 }
919
920                 
921                 /* if properties exist, it will contain everything needed */
922                 if (properties) {
923                         otmacro = ot->macro.first;
924
925                         RNA_STRUCT_BEGIN (properties, prop)
926                         {
927
928                                 if (otmacro == NULL)
929                                         break;
930
931                                 /* skip invalid properties */
932                                 if (STREQ(RNA_property_identifier(prop), otmacro->idname)) {
933                                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
934                                         PointerRNA someptr = RNA_property_pointer_get(properties, prop);
935                                         wmOperator *opm = wm_operator_create(wm, otm, &someptr, NULL);
936
937                                         IDP_ReplaceGroupInGroup(opm->properties, otmacro->properties);
938
939                                         BLI_addtail(&motherop->macro, opm);
940                                         opm->opm = motherop; /* pointer to mom, for modal() */
941
942                                         otmacro = otmacro->next;
943                                 }
944                         }
945                         RNA_STRUCT_END;
946                 }
947                 else {
948                         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
949                                 wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
950                                 wmOperator *opm = wm_operator_create(wm, otm, otmacro->ptr, NULL);
951
952                                 BLI_addtail(&motherop->macro, opm);
953                                 opm->opm = motherop; /* pointer to mom, for modal() */
954                         }
955                 }
956                 
957                 if (root)
958                         motherop = NULL;
959         }
960         
961         WM_operator_properties_sanitize(op->ptr, 0);
962
963         return op;
964 }
965
966 static void wm_region_mouse_co(bContext *C, wmEvent *event)
967 {
968         ARegion *ar = CTX_wm_region(C);
969         if (ar) {
970                 /* compatibility convention */
971                 event->mval[0] = event->x - ar->winrct.xmin;
972                 event->mval[1] = event->y - ar->winrct.ymin;
973         }
974         else {
975                 /* these values are invalid (avoid odd behavior by relying on old mval values) */
976                 event->mval[0] = -1;
977                 event->mval[1] = -1;
978         }
979 }
980
981 #if 1 /* may want to disable operator remembering previous state for testing */
982 bool WM_operator_last_properties_init(wmOperator *op)
983 {
984         bool changed = false;
985
986         if (op->type->last_properties) {
987                 IDPropertyTemplate val = {0};
988                 IDProperty *replaceprops = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
989                 PropertyRNA *iterprop;
990
991                 if (G.debug & G_DEBUG_WM) {
992                         printf("%s: loading previous properties for '%s'\n", __func__, op->type->idname);
993                 }
994
995                 iterprop = RNA_struct_iterator_property(op->type->srna);
996
997                 RNA_PROP_BEGIN (op->ptr, itemptr, iterprop)
998                 {
999                         PropertyRNA *prop = itemptr.data;
1000                         if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
1001                                 if (!RNA_property_is_set(op->ptr, prop)) { /* don't override a setting already set */
1002                                         const char *identifier = RNA_property_identifier(prop);
1003                                         IDProperty *idp_src = IDP_GetPropertyFromGroup(op->type->last_properties, identifier);
1004                                         if (idp_src) {
1005                                                 IDProperty *idp_dst = IDP_CopyProperty(idp_src);
1006
1007                                                 /* note - in the future this may need to be done recursively,
1008                                                  * but for now RNA doesn't access nested operators */
1009                                                 idp_dst->flag |= IDP_FLAG_GHOST;
1010
1011                                                 /* add to temporary group instead of immediate replace,
1012                                                  * because we are iterating over this group */
1013                                                 IDP_AddToGroup(replaceprops, idp_dst);
1014                                                 changed = true;
1015                                         }
1016                                 }
1017                         }
1018                 }
1019                 RNA_PROP_END;
1020
1021                 IDP_MergeGroup(op->properties, replaceprops, true);
1022                 IDP_FreeProperty(replaceprops);
1023                 MEM_freeN(replaceprops);
1024         }
1025
1026         return changed;
1027 }
1028
1029 bool WM_operator_last_properties_store(wmOperator *op)
1030 {
1031         if (op->type->last_properties) {
1032                 IDP_FreeProperty(op->type->last_properties);
1033                 MEM_freeN(op->type->last_properties);
1034                 op->type->last_properties = NULL;
1035         }
1036
1037         if (op->properties) {
1038                 if (G.debug & G_DEBUG_WM) {
1039                         printf("%s: storing properties for '%s'\n", __func__, op->type->idname);
1040                 }
1041                 op->type->last_properties = IDP_CopyProperty(op->properties);
1042                 return true;
1043         }
1044         else {
1045                 return false;
1046         }
1047 }
1048
1049 #else
1050
1051 bool WM_operator_last_properties_init(wmOperator *UNUSED(op))
1052 {
1053         return false;
1054 }
1055
1056 bool WM_operator_last_properties_store(wmOperator *UNUSED(op))
1057 {
1058         return false;
1059 }
1060
1061 #endif
1062
1063 static int wm_operator_invoke(
1064         bContext *C, wmOperatorType *ot, wmEvent *event,
1065         PointerRNA *properties, ReportList *reports, const bool poll_only)
1066 {
1067         int retval = OPERATOR_PASS_THROUGH;
1068
1069         /* this is done because complicated setup is done to call this function that is better not duplicated */
1070         if (poll_only)
1071                 return WM_operator_poll(C, ot);
1072
1073         if (WM_operator_poll(C, ot)) {
1074                 wmWindowManager *wm = CTX_wm_manager(C);
1075                 wmOperator *op = wm_operator_create(wm, ot, properties, reports); /* if reports == NULL, they'll be initialized */
1076                 const bool is_nested_call = (wm->op_undo_depth != 0);
1077                 
1078                 op->flag |= OP_IS_INVOKE;
1079
1080                 /* initialize setting from previous run */
1081                 if (!is_nested_call) { /* not called by py script */
1082                         WM_operator_last_properties_init(op);
1083                 }
1084
1085                 if ((G.debug & G_DEBUG_HANDLERS) && ((event == NULL) || (event->type != MOUSEMOVE))) {
1086                         printf("%s: handle evt %d win %d op %s\n",
1087                                __func__, event ? event->type : 0, CTX_wm_screen(C)->subwinactive, ot->idname);
1088                 }
1089                 
1090                 if (op->type->invoke && event) {
1091                         wm_region_mouse_co(C, event);
1092
1093                         if (op->type->flag & OPTYPE_UNDO)
1094                                 wm->op_undo_depth++;
1095
1096                         retval = op->type->invoke(C, op, event);
1097                         OPERATOR_RETVAL_CHECK(retval);
1098
1099                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1100                                 wm->op_undo_depth--;
1101                 }
1102                 else if (op->type->exec) {
1103                         if (op->type->flag & OPTYPE_UNDO)
1104                                 wm->op_undo_depth++;
1105
1106                         retval = op->type->exec(C, op);
1107                         OPERATOR_RETVAL_CHECK(retval);
1108
1109                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1110                                 wm->op_undo_depth--;
1111                 }
1112                 else {
1113                         /* debug, important to leave a while, should never happen */
1114                         printf("%s: invalid operator call '%s'\n", __func__, ot->idname);
1115                 }
1116                 
1117                 /* Note, if the report is given as an argument then assume the caller will deal with displaying them
1118                  * currently python only uses this */
1119                 if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED))) {
1120                         /* only show the report if the report list was not given in the function */
1121                         wm_operator_reports(C, op, retval, (reports != NULL));
1122                 }
1123
1124                 if (retval & OPERATOR_HANDLED) {
1125                         /* do nothing, wm_operator_exec() has been called somewhere */
1126                 }
1127                 else if (retval & OPERATOR_FINISHED) {
1128                         if (!is_nested_call) { /* not called by py script */
1129                                 WM_operator_last_properties_store(op);
1130                         }
1131                         wm_operator_finished(C, op, 0);
1132                 }
1133                 else if (retval & OPERATOR_RUNNING_MODAL) {
1134                         /* take ownership of reports (in case python provided own) */
1135                         op->reports->flag |= RPT_FREE;
1136
1137                         /* grab cursor during blocking modal ops (X11)
1138                          * Also check for macro
1139                          */
1140                         if (ot->flag & OPTYPE_BLOCKING || (op->opm && op->opm->type->flag & OPTYPE_BLOCKING)) {
1141                                 int bounds[4] = {-1, -1, -1, -1};
1142                                 bool wrap;
1143
1144                                 if (event == NULL) {
1145                                         wrap = false;
1146                                 }
1147                                 else if (op->opm) {
1148                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1149                                                ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR));
1150                                 }
1151                                 else {
1152                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1153                                                ((op->flag & OP_IS_MODAL_GRAB_CURSOR) || (ot->flag & OPTYPE_GRAB_CURSOR));
1154                                 }
1155
1156                                 /* exception, cont. grab in header is annoying */
1157                                 if (wrap) {
1158                                         ARegion *ar = CTX_wm_region(C);
1159                                         if (ar && ar->regiontype == RGN_TYPE_HEADER) {
1160                                                 wrap = false;
1161                                         }
1162                                 }
1163
1164                                 if (wrap) {
1165                                         const rcti *winrect = NULL;
1166                                         ARegion *ar = CTX_wm_region(C);
1167                                         ScrArea *sa = CTX_wm_area(C);
1168
1169                                         if (ar && ar->regiontype == RGN_TYPE_WINDOW &&
1170                                             BLI_rcti_isect_pt_v(&ar->winrct, &event->x))
1171                                         {
1172                                                 winrect = &ar->winrct;
1173                                         }
1174                                         else if (sa && BLI_rcti_isect_pt_v(&sa->totrct, &event->x)) {
1175                                                 winrect = &sa->totrct;
1176                                         }
1177
1178                                         if (winrect) {
1179                                                 bounds[0] = winrect->xmin;
1180                                                 bounds[1] = winrect->ymax;
1181                                                 bounds[2] = winrect->xmax;
1182                                                 bounds[3] = winrect->ymin;
1183                                         }
1184                                 }
1185
1186                                 WM_cursor_grab_enable(CTX_wm_window(C), wrap, false, bounds);
1187                         }
1188
1189                         /* cancel UI handlers, typically tooltips that can hang around
1190                          * while dragging the view or worse, that stay there permanently
1191                          * after the modal operator has swallowed all events and passed
1192                          * none to the UI handler */
1193                         wm_handler_ui_cancel(C);
1194                 }
1195                 else {
1196                         WM_operator_free(op);
1197                 }
1198         }
1199
1200         return retval;
1201 }
1202
1203 /**
1204  * #WM_operator_name_call is the main accessor function
1205  * this is for python to access since its done the operator lookup
1206  * 
1207  * invokes operator in context
1208  */
1209 static int wm_operator_call_internal(
1210         bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
1211         const short context, const bool poll_only)
1212 {
1213         wmEvent *event;
1214         
1215         int retval;
1216
1217         CTX_wm_operator_poll_msg_set(C, NULL);
1218
1219         /* dummie test */
1220         if (ot) {
1221                 wmWindow *window = CTX_wm_window(C);
1222
1223                 switch (context) {
1224                         case WM_OP_INVOKE_DEFAULT:
1225                         case WM_OP_INVOKE_REGION_WIN:
1226                         case WM_OP_INVOKE_AREA:
1227                         case WM_OP_INVOKE_SCREEN:
1228                                 /* window is needed for invoke, cancel operator */
1229                                 if (window == NULL) {
1230                                         if (poll_only) {
1231                                                 CTX_wm_operator_poll_msg_set(C, "Missing 'window' in context");
1232                                         }
1233                                         return 0;
1234                                 }
1235                                 else {
1236                                         event = window->eventstate;
1237                                 }
1238                                 break;
1239                         default:
1240                                 event = NULL;
1241                                 break;
1242                 }
1243
1244                 switch (context) {
1245                         
1246                         case WM_OP_EXEC_REGION_WIN:
1247                         case WM_OP_INVOKE_REGION_WIN: 
1248                         case WM_OP_EXEC_REGION_CHANNELS:
1249                         case WM_OP_INVOKE_REGION_CHANNELS:
1250                         case WM_OP_EXEC_REGION_PREVIEW:
1251                         case WM_OP_INVOKE_REGION_PREVIEW:
1252                         {
1253                                 /* forces operator to go to the region window/channels/preview, for header menus
1254                                  * but we stay in the same region if we are already in one 
1255                                  */
1256                                 ARegion *ar = CTX_wm_region(C);
1257                                 ScrArea *area = CTX_wm_area(C);
1258                                 int type = RGN_TYPE_WINDOW;
1259                                 
1260                                 switch (context) {
1261                                         case WM_OP_EXEC_REGION_CHANNELS:
1262                                         case WM_OP_INVOKE_REGION_CHANNELS:
1263                                                 type = RGN_TYPE_CHANNELS;
1264                                                 break;
1265                                         
1266                                         case WM_OP_EXEC_REGION_PREVIEW:
1267                                         case WM_OP_INVOKE_REGION_PREVIEW:
1268                                                 type = RGN_TYPE_PREVIEW;
1269                                                 break;
1270                                         
1271                                         case WM_OP_EXEC_REGION_WIN:
1272                                         case WM_OP_INVOKE_REGION_WIN: 
1273                                         default:
1274                                                 type = RGN_TYPE_WINDOW;
1275                                                 break;
1276                                 }
1277                                 
1278                                 if (!(ar && ar->regiontype == type) && area) {
1279                                         ARegion *ar1;
1280                                         if (type == RGN_TYPE_WINDOW) {
1281                                                 ar1 = BKE_area_find_region_active_win(area);
1282                                         }
1283                                         else {
1284                                                 ar1 = BKE_area_find_region_type(area, type);
1285                                         }
1286
1287                                         if (ar1)
1288                                                 CTX_wm_region_set(C, ar1);
1289                                 }
1290                                 
1291                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1292                                 
1293                                 /* set region back */
1294                                 CTX_wm_region_set(C, ar);
1295                                 
1296                                 return retval;
1297                         }
1298                         case WM_OP_EXEC_AREA:
1299                         case WM_OP_INVOKE_AREA:
1300                         {
1301                                 /* remove region from context */
1302                                 ARegion *ar = CTX_wm_region(C);
1303
1304                                 CTX_wm_region_set(C, NULL);
1305                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1306                                 CTX_wm_region_set(C, ar);
1307
1308                                 return retval;
1309                         }
1310                         case WM_OP_EXEC_SCREEN:
1311                         case WM_OP_INVOKE_SCREEN:
1312                         {
1313                                 /* remove region + area from context */
1314                                 ARegion *ar = CTX_wm_region(C);
1315                                 ScrArea *area = CTX_wm_area(C);
1316
1317                                 CTX_wm_region_set(C, NULL);
1318                                 CTX_wm_area_set(C, NULL);
1319                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1320                                 CTX_wm_area_set(C, area);
1321                                 CTX_wm_region_set(C, ar);
1322
1323                                 return retval;
1324                         }
1325                         case WM_OP_EXEC_DEFAULT:
1326                         case WM_OP_INVOKE_DEFAULT:
1327                                 return wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1328                 }
1329         }
1330         
1331         return 0;
1332 }
1333
1334
1335 /* invokes operator in context */
1336 int WM_operator_name_call_ptr(bContext *C, wmOperatorType *ot, short context, PointerRNA *properties)
1337 {
1338         BLI_assert(ot == WM_operatortype_find(ot->idname, true));
1339         return wm_operator_call_internal(C, ot, properties, NULL, context, false);
1340 }
1341 int WM_operator_name_call(bContext *C, const char *opstring, short context, PointerRNA *properties)
1342 {
1343         wmOperatorType *ot = WM_operatortype_find(opstring, 0);
1344         if (ot) {
1345                 return WM_operator_name_call_ptr(C, ot, context, properties);
1346         }
1347
1348         return 0;
1349 }
1350
1351 /**
1352  * Similar to #WM_operator_name_call called with #WM_OP_EXEC_DEFAULT context.
1353  *
1354  * - #wmOperatorType is used instead of operator name since python already has the operator type.
1355  * - `poll()` must be called by python before this runs.
1356  * - reports can be passed to this function (so python can report them as exceptions).
1357  */
1358 int WM_operator_call_py(
1359         bContext *C, wmOperatorType *ot, short context,
1360         PointerRNA *properties, ReportList *reports, const bool is_undo)
1361 {
1362         int retval = OPERATOR_CANCELLED;
1363
1364 #if 0
1365         wmOperator *op;
1366         op = wm_operator_create(wm, ot, properties, reports);
1367
1368         if (op->type->exec) {
1369                 if (is_undo && op->type->flag & OPTYPE_UNDO)
1370                         wm->op_undo_depth++;
1371
1372                 retval = op->type->exec(C, op);
1373                 OPERATOR_RETVAL_CHECK(retval);
1374
1375                 if (is_undo && op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1376                         wm->op_undo_depth--;
1377         }
1378         else
1379                 printf("error \"%s\" operator has no exec function, python cannot call it\n", op->type->name);
1380 #endif
1381
1382         /* not especially nice using undo depth here, its used so py never
1383          * triggers undo or stores operators last used state.
1384          *
1385          * we could have some more obvious way of doing this like passing a flag.
1386          */
1387         wmWindowManager *wm = CTX_wm_manager(C);
1388         if (!is_undo && wm) wm->op_undo_depth++;
1389
1390         retval = wm_operator_call_internal(C, ot, properties, reports, context, false);
1391         
1392         if (!is_undo && wm && (wm == CTX_wm_manager(C))) wm->op_undo_depth--;
1393
1394         return retval;
1395 }
1396
1397
1398 /* ********************* handlers *************** */
1399
1400 /* future extra customadata free? */
1401 void wm_event_free_handler(wmEventHandler *handler)
1402 {
1403         MEM_freeN(handler);
1404 }
1405
1406 /* only set context when area/region is part of screen */
1407 static void wm_handler_op_context(bContext *C, wmEventHandler *handler, const wmEvent *event)
1408 {
1409         bScreen *screen = CTX_wm_screen(C);
1410         
1411         if (screen && handler->op) {
1412                 if (handler->op_area == NULL)
1413                         CTX_wm_area_set(C, NULL);
1414                 else {
1415                         ScrArea *sa;
1416                         
1417                         for (sa = screen->areabase.first; sa; sa = sa->next)
1418                                 if (sa == handler->op_area)
1419                                         break;
1420                         if (sa == NULL) {
1421                                 /* when changing screen layouts with running modal handlers (like render display), this
1422                                  * is not an error to print */
1423                                 if (handler->op == NULL)
1424                                         printf("internal error: handler (%s) has invalid area\n", handler->op->type->idname);
1425                         }
1426                         else {
1427                                 ARegion *ar;
1428                                 wmOperator *op = handler->op ? (handler->op->opm ? handler->op->opm : handler->op) : NULL;
1429                                 CTX_wm_area_set(C, sa);
1430
1431                                 if (op && (op->flag & OP_IS_MODAL_CURSOR_REGION)) {
1432                                         ar = BKE_area_find_region_xy(sa, handler->op_region_type, event->x, event->y);
1433                                         if (ar) {
1434                                                 handler->op_region = ar;
1435                                         }
1436                                 }
1437                                 else {
1438                                         ar = NULL;
1439                                 }
1440
1441                                 if (ar == NULL) {
1442                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1443                                                 if (ar == handler->op_region) {
1444                                                         break;
1445                                                 }
1446                                         }
1447                                 }
1448
1449                                 /* XXX no warning print here, after full-area and back regions are remade */
1450                                 if (ar)
1451                                         CTX_wm_region_set(C, ar);
1452                         }
1453                 }
1454         }
1455 }
1456
1457 /* called on exit or remove area, only here call cancel callback */
1458 void WM_event_remove_handlers(bContext *C, ListBase *handlers)
1459 {
1460         wmEventHandler *handler;
1461         wmWindowManager *wm = CTX_wm_manager(C);
1462         
1463         /* C is zero on freeing database, modal handlers then already were freed */
1464         while ((handler = BLI_pophead(handlers))) {
1465                 if (handler->op) {
1466                         wmWindow *win = CTX_wm_window(C);
1467                         if (handler->op->type->cancel) {
1468                                 ScrArea *area = CTX_wm_area(C);
1469                                 ARegion *region = CTX_wm_region(C);
1470                                 
1471                                 wm_handler_op_context(C, handler, win->eventstate);
1472
1473                                 if (handler->op->type->flag & OPTYPE_UNDO)
1474                                         wm->op_undo_depth++;
1475
1476                                 handler->op->type->cancel(C, handler->op);
1477
1478                                 if (handler->op->type->flag & OPTYPE_UNDO)
1479                                         wm->op_undo_depth--;
1480
1481                                 CTX_wm_area_set(C, area);
1482                                 CTX_wm_region_set(C, region);
1483                         }
1484
1485                         WM_cursor_grab_disable(win, NULL);
1486                         WM_operator_free(handler->op);
1487                 }
1488                 else if (handler->ui_remove) {
1489                         ScrArea *area = CTX_wm_area(C);
1490                         ARegion *region = CTX_wm_region(C);
1491                         ARegion *menu = CTX_wm_menu(C);
1492                         
1493                         if (handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
1494                         if (handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
1495                         if (handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
1496
1497                         handler->ui_remove(C, handler->ui_userdata);
1498
1499                         CTX_wm_area_set(C, area);
1500                         CTX_wm_region_set(C, region);
1501                         CTX_wm_menu_set(C, menu);
1502                 }
1503
1504                 wm_event_free_handler(handler);
1505         }
1506 }
1507
1508 /* do userdef mappings */
1509 int WM_userdef_event_map(int kmitype)
1510 {
1511         switch (kmitype) {
1512                 case SELECTMOUSE:
1513                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1514                 case ACTIONMOUSE:
1515                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1516                 case EVT_TWEAK_A:
1517                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_R : EVT_TWEAK_L;
1518                 case EVT_TWEAK_S:
1519                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_L : EVT_TWEAK_R;
1520                 case WHEELOUTMOUSE:
1521                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELUPMOUSE : WHEELDOWNMOUSE;
1522                 case WHEELINMOUSE:
1523                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELDOWNMOUSE : WHEELUPMOUSE;
1524         }
1525         
1526         return kmitype;
1527 }
1528
1529
1530 static int wm_eventmatch(const wmEvent *winevent, wmKeyMapItem *kmi)
1531 {
1532         int kmitype = WM_userdef_event_map(kmi->type);
1533
1534         if (kmi->flag & KMI_INACTIVE) return 0;
1535
1536         /* the matching rules */
1537         if (kmitype == KM_TEXTINPUT)
1538                 if (winevent->val == KM_PRESS) {  /* prevent double clicks */
1539                         /* NOT using ISTEXTINPUT anymore because (at least on Windows) some key codes above 255
1540                          * could have printable ascii keys - BUG [#30479] */
1541                         if (ISKEYBOARD(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1; 
1542                 }
1543
1544         if (kmitype != KM_ANY) {
1545                 if (ELEM(kmitype, TABLET_STYLUS, TABLET_ERASER)) {
1546                         const wmTabletData *wmtab = winevent->tablet_data;
1547                         
1548                         if (wmtab == NULL)
1549                                 return 0;
1550                         else if (winevent->type != LEFTMOUSE) /* tablet events can occur on hover + keypress */
1551                                 return 0;
1552                         else if ((kmitype == TABLET_STYLUS) && (wmtab->Active != EVT_TABLET_STYLUS))
1553                                 return 0;
1554                         else if ((kmitype == TABLET_ERASER) && (wmtab->Active != EVT_TABLET_ERASER))
1555                                 return 0;
1556                 }
1557                 else {
1558                         if (winevent->type != kmitype)
1559                                 return 0;
1560                 }
1561         }
1562         
1563         if (kmi->val != KM_ANY)
1564                 if (winevent->val != kmi->val) return 0;
1565         
1566         /* modifiers also check bits, so it allows modifier order */
1567         if (kmi->shift != KM_ANY)
1568                 if (winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1569         if (kmi->ctrl != KM_ANY)
1570                 if (winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1571         if (kmi->alt != KM_ANY)
1572                 if (winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1573         if (kmi->oskey != KM_ANY)
1574                 if (winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1575         
1576         /* only keymap entry with keymodifier is checked, means all keys without modifier get handled too. */
1577         /* that is currently needed to make overlapping events work (when you press A - G fast or so). */
1578         if (kmi->keymodifier)
1579                 if (winevent->keymodifier != kmi->keymodifier) return 0;
1580         
1581         return 1;
1582 }
1583
1584
1585 /* operator exists */
1586 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event, bool *dbl_click_disabled)
1587 {
1588         /* support for modal keymap in macros */
1589         if (op->opm)
1590                 op = op->opm;
1591
1592         if (op->type->modalkeymap) {
1593                 wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1594                 wmKeyMapItem *kmi;
1595
1596                 for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1597                         if (wm_eventmatch(event, kmi)) {
1598                                         
1599                                 event->prevtype = event->type;
1600                                 event->prevval = event->val;
1601                                 event->type = EVT_MODAL_MAP;
1602                                 event->val = kmi->propvalue;
1603                                 
1604                                 break;
1605                         }
1606                 }
1607         }
1608         else {
1609                 /* modal keymap checking returns handled events fine, but all hardcoded modal
1610                  * handling typically swallows all events (OPERATOR_RUNNING_MODAL).
1611                  * This bypass just disables support for double clicks in hardcoded modal handlers */
1612                 if (event->val == KM_DBL_CLICK) {
1613                         event->val = KM_PRESS;
1614                         *dbl_click_disabled = true;
1615                 }
1616         }
1617 }
1618
1619 /**
1620  * Check whether operator is allowed to run in case interface is locked,
1621  * If interface is unlocked, will always return truth.
1622  */
1623 static bool wm_operator_check_locked_interface(bContext *C, wmOperatorType *ot)
1624 {
1625         wmWindowManager *wm = CTX_wm_manager(C);
1626
1627         if (wm->is_interface_locked) {
1628                 if ((ot->flag & OPTYPE_LOCK_BYPASS) == 0) {
1629                         return false;
1630                 }
1631         }
1632
1633         return true;
1634 }
1635
1636 /* bad hacking event system... better restore event type for checking of KM_CLICK for example */
1637 /* XXX modal maps could use different method (ton) */
1638 static void wm_event_modalmap_end(wmEvent *event, bool dbl_click_disabled)
1639 {
1640         if (event->type == EVT_MODAL_MAP) {
1641                 event->type = event->prevtype;
1642                 event->prevtype = 0;
1643                 event->val = event->prevval;
1644                 event->prevval = 0;
1645         }
1646         else if (dbl_click_disabled)
1647                 event->val = KM_DBL_CLICK;
1648
1649 }
1650
1651 /* Warning: this function removes a modal handler, when finished */
1652 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1653                                     wmEvent *event, PointerRNA *properties)
1654 {
1655         int retval = OPERATOR_PASS_THROUGH;
1656         
1657         /* derived, modal or blocking operator */
1658         if (handler->op) {
1659                 wmOperator *op = handler->op;
1660                 wmOperatorType *ot = op->type;
1661
1662                 if (!wm_operator_check_locked_interface(C, ot)) {
1663                         /* Interface is locked and operator is not allowed to run,
1664                          * nothing to do in this case.
1665                          */
1666                 }
1667                 else if (ot->modal) {
1668                         /* we set context to where modal handler came from */
1669                         wmWindowManager *wm = CTX_wm_manager(C);
1670                         ScrArea *area = CTX_wm_area(C);
1671                         ARegion *region = CTX_wm_region(C);
1672                         bool dbl_click_disabled = false;
1673
1674                         wm_handler_op_context(C, handler, event);
1675                         wm_region_mouse_co(C, event);
1676                         wm_event_modalkeymap(C, op, event, &dbl_click_disabled);
1677                         
1678                         if (ot->flag & OPTYPE_UNDO)
1679                                 wm->op_undo_depth++;
1680
1681                         /* warning, after this call all context data and 'event' may be freed. see check below */
1682                         retval = ot->modal(C, op, event);
1683                         OPERATOR_RETVAL_CHECK(retval);
1684                         
1685                         /* when this is _not_ the case the modal modifier may have loaded
1686                          * a new blend file (demo mode does this), so we have to assume
1687                          * the event, operator etc have all been freed. - campbell */
1688                         if (CTX_wm_manager(C) == wm) {
1689
1690                                 wm_event_modalmap_end(event, dbl_click_disabled);
1691
1692                                 if (ot->flag & OPTYPE_UNDO)
1693                                         wm->op_undo_depth--;
1694
1695                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1696                                         wm_operator_reports(C, op, retval, false);
1697                                 }
1698                                 else {
1699                                         /* not very common, but modal operators may report before finishing */
1700                                         if (!BLI_listbase_is_empty(&op->reports->list)) {
1701                                                 wm_add_reports(op->reports);
1702                                         }
1703                                 }
1704
1705                                 /* important to run 'wm_operator_finished' before NULLing the context members */
1706                                 if (retval & OPERATOR_FINISHED) {
1707                                         wm_operator_finished(C, op, 0);
1708                                         handler->op = NULL;
1709                                 }
1710                                 else if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1711                                         WM_operator_free(op);
1712                                         handler->op = NULL;
1713                                 }
1714
1715                                 /* putting back screen context, reval can pass trough after modal failures! */
1716                                 if ((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1717                                         CTX_wm_area_set(C, area);
1718                                         CTX_wm_region_set(C, region);
1719                                 }
1720                                 else {
1721                                         /* this special cases is for areas and regions that get removed */
1722                                         CTX_wm_area_set(C, NULL);
1723                                         CTX_wm_region_set(C, NULL);
1724                                 }
1725
1726                                 /* remove modal handler, operator itself should have been canceled and freed */
1727                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1728                                         WM_cursor_grab_disable(CTX_wm_window(C), NULL);
1729
1730                                         BLI_remlink(handlers, handler);
1731                                         wm_event_free_handler(handler);
1732
1733                                         /* prevent silly errors from operator users */
1734                                         //retval &= ~OPERATOR_PASS_THROUGH;
1735                                 }
1736                         }
1737                         
1738                 }
1739                 else {
1740                         printf("%s: error '%s' missing modal\n", __func__, op->idname);
1741                 }
1742         }
1743         else {
1744                 wmOperatorType *ot = WM_operatortype_find(event->keymap_idname, 0);
1745
1746                 if (ot) {
1747                         if (wm_operator_check_locked_interface(C, ot)) {
1748                                 retval = wm_operator_invoke(C, ot, event, properties, NULL, false);
1749                         }
1750                 }
1751         }
1752         /* Finished and pass through flag as handled */
1753
1754         /* Finished and pass through flag as handled */
1755         if (retval == (OPERATOR_FINISHED | OPERATOR_PASS_THROUGH))
1756                 return WM_HANDLER_HANDLED;
1757
1758         /* Modal unhandled, break */
1759         if (retval == (OPERATOR_PASS_THROUGH | OPERATOR_RUNNING_MODAL))
1760                 return (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
1761
1762         if (retval & OPERATOR_PASS_THROUGH)
1763                 return WM_HANDLER_CONTINUE;
1764
1765         return WM_HANDLER_BREAK;
1766 }
1767
1768 /* fileselect handlers are only in the window queue, so it's safe to switch screens or area types */
1769 static int wm_handler_fileselect_do(bContext *C, ListBase *handlers, wmEventHandler *handler, int val)
1770 {
1771         wmWindowManager *wm = CTX_wm_manager(C);
1772         SpaceFile *sfile;
1773         int action = WM_HANDLER_CONTINUE;
1774
1775         switch (val) {
1776                 case EVT_FILESELECT_FULL_OPEN: 
1777                 {
1778                         ScrArea *sa;
1779                                 
1780                         /* sa can be null when window A is active, but mouse is over window B */
1781                         /* in this case, open file select in original window A */
1782                         if (handler->op_area == NULL) {
1783                                 bScreen *screen = CTX_wm_screen(C);
1784                                 sa = (ScrArea *)screen->areabase.first;
1785                         }
1786                         else {
1787                                 sa = handler->op_area;
1788                         }
1789
1790                         if (sa->full) {
1791                                 /* ensure the first area becomes the file browser, because the second one is the small
1792                                  * top (info-)area which might be too small (in fullscreens we have max two areas) */
1793                                 if (sa->prev) {
1794                                         sa = sa->prev;
1795                                 }
1796                                 ED_area_newspace(C, sa, SPACE_FILE, true);     /* 'sa' is modified in-place */
1797                                 /* we already had a fullscreen here -> mark new space as a stacked fullscreen */
1798                                 sa->flag |= (AREA_FLAG_STACKED_FULLSCREEN | AREA_FLAG_TEMP_TYPE);
1799                         }
1800                         else if (sa->spacetype == SPACE_FILE) {
1801                                 sa = ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENMAXIMIZED);
1802                         }
1803                         else {
1804                                 sa = ED_screen_full_newspace(C, sa, SPACE_FILE);    /* sets context */
1805                         }
1806
1807                         /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
1808                          * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
1809                         /* sa = CTX_wm_area(C); */
1810
1811                         /* settings for filebrowser, sfile is not operator owner but sends events */
1812                         sfile = (SpaceFile *)sa->spacedata.first;
1813                         sfile->op = handler->op;
1814
1815                         ED_fileselect_set_params(sfile);
1816                                 
1817                         action = WM_HANDLER_BREAK;
1818                         break;
1819                 }
1820                         
1821                 case EVT_FILESELECT_EXEC:
1822                 case EVT_FILESELECT_CANCEL:
1823                 case EVT_FILESELECT_EXTERNAL_CANCEL:
1824                 {
1825                         /* remlink now, for load file case before removing*/
1826                         BLI_remlink(handlers, handler);
1827
1828                         if (val != EVT_FILESELECT_EXTERNAL_CANCEL) {
1829                                 ScrArea *sa = CTX_wm_area(C);
1830
1831                                 if (sa->full) {
1832                                         ED_screen_full_prevspace(C, sa);
1833                                 }
1834                                 /* user may have left fullscreen */
1835                                 else {
1836                                         ED_area_prevspace(C, sa);
1837                                 }
1838                         }
1839
1840                         wm_handler_op_context(C, handler, CTX_wm_window(C)->eventstate);
1841
1842                         /* needed for UI_popup_menu_reports */
1843
1844                         if (val == EVT_FILESELECT_EXEC) {
1845                                 int retval;
1846
1847                                 if (handler->op->type->flag & OPTYPE_UNDO)
1848                                         wm->op_undo_depth++;
1849
1850                                 retval = handler->op->type->exec(C, handler->op);
1851
1852                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1853                                 if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1854                                         wm->op_undo_depth--;
1855
1856                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1857                                 if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
1858                                         if (handler->op->type->flag & OPTYPE_UNDO)
1859                                                 ED_undo_push_op(C, handler->op);
1860
1861                                 if (handler->op->reports->list.first) {
1862
1863                                         /* FIXME, temp setting window, this is really bad!
1864                                          * only have because lib linking errors need to be seen by users :(
1865                                          * it can be removed without breaking anything but then no linking errors - campbell */
1866                                         wmWindow *win_prev = CTX_wm_window(C);
1867                                         ScrArea *area_prev = CTX_wm_area(C);
1868                                         ARegion *ar_prev = CTX_wm_region(C);
1869
1870                                         if (win_prev == NULL)
1871                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
1872
1873                                         BKE_report_print_level_set(handler->op->reports, RPT_WARNING);
1874                                         UI_popup_menu_reports(C, handler->op->reports);
1875
1876                                         /* XXX - copied from 'wm_operator_finished()' */
1877                                         /* add reports to the global list, otherwise they are not seen */
1878                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
1879
1880                                         /* more hacks, since we meddle with reports, banner display doesn't happen automatic */
1881                                         WM_report_banner_show();
1882
1883                                         CTX_wm_window_set(C, win_prev);
1884                                         CTX_wm_area_set(C, area_prev);
1885                                         CTX_wm_region_set(C, ar_prev);
1886                                 }
1887
1888                                 /* for WM_operator_pystring only, custom report handling is done above */
1889                                 wm_operator_reports(C, handler->op, retval, true);
1890
1891                                 if (retval & OPERATOR_FINISHED) {
1892                                         WM_operator_last_properties_store(handler->op);
1893                                 }
1894
1895                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1896                                         WM_operator_free(handler->op);
1897                                 }
1898                         }
1899                         else {
1900                                 if (handler->op->type->cancel) {
1901                                         if (handler->op->type->flag & OPTYPE_UNDO)
1902                                                 wm->op_undo_depth++;
1903
1904                                         handler->op->type->cancel(C, handler->op);
1905                                 
1906                                         if (handler->op->type->flag & OPTYPE_UNDO)
1907                                                 wm->op_undo_depth--;
1908                                 }
1909                                 
1910                                 WM_operator_free(handler->op);
1911                         }
1912
1913                         CTX_wm_area_set(C, NULL);
1914
1915                         wm_event_free_handler(handler);
1916
1917                         action = WM_HANDLER_BREAK;
1918                         break;
1919                 }
1920         }
1921         
1922         return action;
1923 }
1924
1925 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, const wmEvent *event)
1926 {
1927         int action = WM_HANDLER_CONTINUE;
1928         
1929         if (event->type != EVT_FILESELECT)
1930                 return action;
1931         if (handler->op != (wmOperator *)event->customdata)
1932                 return action;
1933         
1934         return wm_handler_fileselect_do(C, handlers, handler, event->val);
1935 }
1936
1937 static bool handler_boundbox_test(wmEventHandler *handler, const wmEvent *event)
1938 {
1939         if (handler->bbwin) {
1940                 if (handler->bblocal) {
1941                         rcti rect = *handler->bblocal;
1942                         BLI_rcti_translate(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
1943
1944                         if (BLI_rcti_isect_pt_v(&rect, &event->x))
1945                                 return 1;
1946                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(&rect, &event->prevx))
1947                                 return 1;
1948                         else
1949                                 return 0;
1950                 }
1951                 else {
1952                         if (BLI_rcti_isect_pt_v(handler->bbwin, &event->x))
1953                                 return 1;
1954                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(handler->bbwin, &event->prevx))
1955                                 return 1;
1956                         else
1957                                 return 0;
1958                 }
1959         }
1960         return 1;
1961 }
1962
1963 static int wm_action_not_handled(int action)
1964 {
1965         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
1966 }
1967
1968 static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers)
1969 {
1970         const bool do_debug_handler = (G.debug & G_DEBUG_HANDLERS) &&
1971                 /* comment this out to flood the console! (if you really want to test) */
1972                 !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
1973                 ;
1974 # define PRINT if (do_debug_handler) printf
1975
1976         wmWindowManager *wm = CTX_wm_manager(C);
1977         wmEventHandler *handler, *nexthandler;
1978         int action = WM_HANDLER_CONTINUE;
1979         int always_pass;
1980
1981         if (handlers == NULL) {
1982                 return action;
1983         }
1984
1985         /* modal handlers can get removed in this loop, we keep the loop this way
1986          *
1987          * note: check 'handlers->first' because in rare cases the handlers can be cleared
1988          * by the event thats called, for eg:
1989          *
1990          * Calling a python script which changes the area.type, see [#32232] */
1991         for (handler = handlers->first; handler && handlers->first; handler = nexthandler) {
1992
1993                 nexthandler = handler->next;
1994                 
1995                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
1996                 if (handler->flag & WM_HANDLER_DO_FREE) {
1997                         /* pass */
1998                 }
1999                 else if (handler_boundbox_test(handler, event)) { /* optional boundbox */
2000                         /* in advance to avoid access to freed event on window close */
2001                         always_pass = wm_event_always_pass(event);
2002                 
2003                         /* modal+blocking handler */
2004                         if (handler->flag & WM_HANDLER_BLOCKING)
2005                                 action |= WM_HANDLER_BREAK;
2006
2007                         if (handler->keymap) {
2008                                 wmKeyMap *keymap = WM_keymap_active(wm, handler->keymap);
2009                                 wmKeyMapItem *kmi;
2010
2011                                 PRINT("%s:   checking '%s' ...", __func__, keymap->idname);
2012
2013                                 if (!keymap->poll || keymap->poll(C)) {
2014
2015                                         PRINT("pass\n");
2016
2017                                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
2018                                                 if (wm_eventmatch(event, kmi)) {
2019
2020                                                         PRINT("%s:     item matched '%s'\n", __func__, kmi->idname);
2021
2022                                                         /* weak, but allows interactive callback to not use rawkey */
2023                                                         event->keymap_idname = kmi->idname;
2024
2025                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
2026                                                         if (action & WM_HANDLER_BREAK) {
2027                                                                 /* not always_pass here, it denotes removed handler */
2028                                                                 
2029                                                                 if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
2030                                                                         printf("%s:       handled! '%s'\n", __func__, kmi->idname);
2031
2032                                                                 break;
2033                                                         }
2034                                                         else {
2035                                                                 if (action & WM_HANDLER_HANDLED)
2036                                                                         if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
2037                                                                                 printf("%s:       handled - and pass on! '%s'\n", __func__, kmi->idname);
2038                                                                 
2039                                                                         PRINT("%s:       un-handled '%s'...", __func__, kmi->idname);
2040                                                         }
2041                                                 }
2042                                         }
2043                                 }
2044                                 else {
2045                                         PRINT("fail\n");
2046                                 }
2047                         }
2048                         else if (handler->ui_handle) {
2049                                 if (!wm->is_interface_locked) {
2050                                         action |= wm_handler_ui_call(C, handler, event, always_pass);
2051                                 }
2052                         }
2053                         else if (handler->type == WM_HANDLER_FILESELECT) {
2054                                 if (!wm->is_interface_locked) {
2055                                         /* screen context changes here */
2056                                         action |= wm_handler_fileselect_call(C, handlers, handler, event);
2057                                 }
2058                         }
2059                         else if (handler->dropboxes) {
2060                                 if (!wm->is_interface_locked && event->type == EVT_DROP) {
2061                                         wmDropBox *drop = handler->dropboxes->first;
2062                                         for (; drop; drop = drop->next) {
2063                                                 /* other drop custom types allowed */
2064                                                 if (event->custom == EVT_DATA_DRAGDROP) {
2065                                                         ListBase *lb = (ListBase *)event->customdata;
2066                                                         wmDrag *drag;
2067                                                         
2068                                                         for (drag = lb->first; drag; drag = drag->next) {
2069                                                                 if (drop->poll(C, drag, event)) {
2070                                                                         drop->copy(drag, drop);
2071                                                                         
2072                                                                         /* free the drags before calling operator */
2073                                                                         WM_drag_free_list(lb);
2074
2075                                                                         event->customdata = NULL;
2076                                                                         event->custom = 0;
2077                                                                         
2078                                                                         WM_operator_name_call_ptr(C, drop->ot, drop->opcontext, drop->ptr);
2079                                                                         action |= WM_HANDLER_BREAK;
2080                                                                         
2081                                                                         /* XXX fileread case */
2082                                                                         if (CTX_wm_window(C) == NULL)
2083                                                                                 return action;
2084                                                                         
2085                                                                         /* escape from drag loop, got freed */
2086                                                                         break;
2087                                                                 }
2088                                                         }
2089                                                 }
2090                                         }
2091                                 }
2092                         }
2093                         else {
2094                                 /* modal, swallows all */
2095                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
2096                         }
2097
2098                         if (action & WM_HANDLER_BREAK) {
2099                                 if (always_pass)
2100                                         action &= ~WM_HANDLER_BREAK;
2101                                 else
2102                                         break;
2103                         }
2104                 }
2105                 
2106                 /* XXX fileread case, if the wm is freed then the handler's
2107                  * will have been too so the code below need not run. */
2108                 if (CTX_wm_window(C) == NULL) {
2109                         return action;
2110                 }
2111
2112                 /* XXX code this for all modal ops, and ensure free only happens here */
2113                 
2114                 /* modal ui handler can be tagged to be freed */ 
2115                 if (BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
2116                         if (handler->flag & WM_HANDLER_DO_FREE) {
2117                                 BLI_remlink(handlers, handler);
2118                                 wm_event_free_handler(handler);
2119                         }
2120                 }
2121         }
2122
2123         if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
2124                 wm_cursor_arrow_move(CTX_wm_window(C), event);
2125
2126 #undef PRINT
2127
2128         return action;
2129 }
2130
2131 /* this calls handlers twice - to solve (double-)click events */
2132 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
2133 {
2134         int action = wm_handlers_do_intern(C, event, handlers);
2135                 
2136         /* fileread case */
2137         if (CTX_wm_window(C) == NULL)
2138                 return action;
2139
2140         if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE, EVENT_NONE) && !ISTIMER(event->type)) {
2141
2142                 /* test for CLICK events */
2143                 if (wm_action_not_handled(action)) {
2144                         wmWindow *win = CTX_wm_window(C);
2145                         
2146                         /* eventstate stores if previous event was a KM_PRESS, in case that 
2147                          * wasn't handled, the KM_RELEASE will become a KM_CLICK */
2148                         
2149                         if (win && event->val == KM_PRESS) {
2150                                 win->eventstate->check_click = true;
2151                         }
2152                         
2153                         if (win && win->eventstate->prevtype == event->type) {
2154                                 
2155                                 if ((event->val == KM_RELEASE) &&
2156                                     (win->eventstate->prevval == KM_PRESS) &&
2157                                     (win->eventstate->check_click == true))
2158                                 {
2159                                         event->val = KM_CLICK;
2160                                         
2161                                         if (G.debug & (G_DEBUG_HANDLERS)) {
2162                                                 printf("%s: handling CLICK\n", __func__);
2163                                         }
2164
2165                                         action |= wm_handlers_do_intern(C, event, handlers);
2166
2167                                         event->val = KM_RELEASE;
2168                                 }
2169                                 else if (event->val == KM_DBL_CLICK) {
2170                                         event->val = KM_PRESS;
2171                                         action |= wm_handlers_do_intern(C, event, handlers);
2172                                         
2173                                         /* revert value if not handled */
2174                                         if (wm_action_not_handled(action)) {
2175                                                 event->val = KM_DBL_CLICK;
2176                                         }
2177                                 }
2178                         }
2179                 }
2180                 else {
2181                         wmWindow *win = CTX_wm_window(C);
2182
2183                         if (win)
2184                                 win->eventstate->check_click = 0;
2185                 }
2186         }
2187         
2188         return action;
2189 }
2190
2191 static int wm_event_inside_i(wmEvent *event, rcti *rect)
2192 {
2193         if (wm_event_always_pass(event))
2194                 return 1;
2195         if (BLI_rcti_isect_pt_v(rect, &event->x))
2196                 return 1;
2197         return 0;
2198 }
2199
2200 static ScrArea *area_event_inside(bContext *C, const int xy[2])
2201 {
2202         bScreen *screen = CTX_wm_screen(C);
2203         ScrArea *sa;
2204         
2205         if (screen)
2206                 for (sa = screen->areabase.first; sa; sa = sa->next)
2207                         if (BLI_rcti_isect_pt_v(&sa->totrct, xy))
2208                                 return sa;
2209         return NULL;
2210 }
2211
2212 static ARegion *region_event_inside(bContext *C, const int xy[2])
2213 {
2214         bScreen *screen = CTX_wm_screen(C);
2215         ScrArea *area = CTX_wm_area(C);
2216         ARegion *ar;
2217         
2218         if (screen && area)
2219                 for (ar = area->regionbase.first; ar; ar = ar->next)
2220                         if (BLI_rcti_isect_pt_v(&ar->winrct, xy))
2221                                 return ar;
2222         return NULL;
2223 }
2224
2225 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
2226 {
2227         if (ar) {
2228                 for (; pc; pc = pc->next) {
2229                         if (pc->poll == NULL || pc->poll(C)) {
2230                                 wmWindow *win = CTX_wm_window(C);
2231                                 WM_paint_cursor_tag_redraw(win, ar);
2232                         }
2233                 }
2234         }
2235 }
2236
2237 /* called on mousemove, check updates for paintcursors */
2238 /* context was set on active area and region */
2239 static void wm_paintcursor_test(bContext *C, const wmEvent *event)
2240 {
2241         wmWindowManager *wm = CTX_wm_manager(C);
2242         
2243         if (wm->paintcursors.first) {
2244                 ARegion *ar = CTX_wm_region(C);
2245                 
2246                 if (ar)
2247                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
2248                 
2249                 /* if previous position was not in current region, we have to set a temp new context */
2250                 if (ar == NULL || !BLI_rcti_isect_pt_v(&ar->winrct, &event->prevx)) {
2251                         ScrArea *sa = CTX_wm_area(C);
2252                         
2253                         CTX_wm_area_set(C, area_event_inside(C, &event->prevx));
2254                         CTX_wm_region_set(C, region_event_inside(C, &event->prevx));
2255
2256                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
2257                         
2258                         CTX_wm_area_set(C, sa);
2259                         CTX_wm_region_set(C, ar);
2260                 }
2261         }
2262 }
2263
2264 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
2265 {
2266         if (BLI_listbase_is_empty(&wm->drags)) {
2267                 return;
2268         }
2269         
2270         if (event->type == MOUSEMOVE || ISKEYMODIFIER(event->type)) {
2271                 win->screen->do_draw_drag = true;
2272         }
2273         else if (event->type == ESCKEY) {
2274                 WM_drag_free_list(&wm->drags);
2275
2276                 win->screen->do_draw_drag = true;
2277         }
2278         else if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2279                 event->type = EVT_DROP;
2280                 
2281                 /* create customdata, first free existing */
2282                 if (event->customdata) {
2283                         if (event->customdatafree)
2284                                 MEM_freeN(event->customdata);
2285                 }
2286                 
2287                 event->custom = EVT_DATA_DRAGDROP;
2288                 event->customdata = &wm->drags;
2289                 event->customdatafree = 1;
2290                 
2291                 /* clear drop icon */
2292                 win->screen->do_draw_drag = true;
2293                 
2294                 /* restore cursor (disabled, see wm_dragdrop.c) */
2295                 // WM_cursor_modal_restore(win);
2296         }
2297         
2298         /* overlap fails otherwise */
2299         if (win->screen->do_draw_drag)
2300                 if (win->drawmethod == USER_DRAW_OVERLAP)
2301                         win->screen->do_draw = true;
2302         
2303 }
2304
2305 /* filter out all events of the pie that spawned the last pie unless it's a release event */
2306 static bool wm_event_pie_filter(wmWindow *win, const wmEvent *event)
2307 {
2308         if (win->lock_pie_event && win->lock_pie_event == event->type) {
2309                 if (event->val == KM_RELEASE) {
2310                         win->lock_pie_event = EVENT_NONE;
2311                         return false;
2312                 }
2313                 else {
2314                         return true;
2315                 }
2316         }
2317         else {
2318                 return false;
2319         }
2320 }
2321
2322 /* called in main loop */
2323 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
2324 void wm_event_do_handlers(bContext *C)
2325 {
2326         wmWindowManager *wm = CTX_wm_manager(C);
2327         wmWindow *win;
2328
2329         /* update key configuration before handling events */
2330         WM_keyconfig_update(wm);
2331
2332         for (win = wm->windows.first; win; win = win->next) {
2333                 wmEvent *event;
2334                 
2335                 if (win->screen == NULL)
2336                         wm_event_free_all(win);
2337                 else {
2338                         Scene *scene = win->screen->scene;
2339                         
2340                         if (scene) {
2341                                 int is_playing_sound = BKE_sound_scene_playing(win->screen->scene);
2342                                 
2343                                 if (is_playing_sound != -1) {
2344                                         bool is_playing_screen;
2345                                         CTX_wm_window_set(C, win);
2346                                         CTX_wm_screen_set(C, win->screen);
2347                                         CTX_data_scene_set(C, scene);
2348                                         
2349                                         is_playing_screen = (ED_screen_animation_playing(wm) != NULL);
2350
2351                                         if (((is_playing_sound == 1) && (is_playing_screen == 0)) ||
2352                                             ((is_playing_sound == 0) && (is_playing_screen == 1)))
2353                                         {
2354                                                 ED_screen_animation_play(C, -1, 1);
2355                                         }
2356                                         
2357                                         if (is_playing_sound == 0) {
2358                                                 const float time = BKE_sound_sync_scene(scene);
2359                                                 if (isfinite(time)) {
2360                                                         int ncfra = time * (float)FPS + 0.5f;
2361                                                         if (ncfra != scene->r.cfra) {
2362                                                                 scene->r.cfra = ncfra;
2363                                                                 ED_update_for_newframe(CTX_data_main(C), scene, 1);
2364                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2365                                                         }
2366                                                 }
2367                                         }
2368                                         
2369                                         CTX_data_scene_set(C, NULL);
2370                                         CTX_wm_screen_set(C, NULL);
2371                                         CTX_wm_window_set(C, NULL);
2372                                 }
2373                         }
2374                 }
2375                 
2376                 while ( (event = win->queue.first) ) {
2377                         int action = WM_HANDLER_CONTINUE;
2378
2379                         if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2380                                 printf("\n%s: Handling event\n", __func__);
2381                                 WM_event_print(event);
2382                         }
2383
2384                         /* take care of pie event filter */
2385                         if (wm_event_pie_filter(win, event)) {
2386                                 if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2387                                         printf("\n%s: event filtered due to pie button pressed\n", __func__);
2388                                 }
2389                                 BLI_remlink(&win->queue, event);
2390                                 wm_event_free(event);
2391                                 continue;
2392                         }
2393
2394                         CTX_wm_window_set(C, win);
2395
2396                         /* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
2397                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2398                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2399                         
2400                         /* MVC demands to not draw in event handlers... but we need to leave it for ogl selecting etc */
2401                         wm_window_make_drawable(wm, win);
2402                         
2403                         wm_region_mouse_co(C, event);
2404
2405
2406                         /* first we do priority handlers, modal + some limited keymaps */
2407                         action |= wm_handlers_do(C, event, &win->modalhandlers);
2408                         
2409                         /* fileread case */
2410                         if (CTX_wm_window(C) == NULL)
2411                                 return;
2412                         
2413                         /* check dragging, creates new event or frees, adds draw tag */
2414                         wm_event_drag_test(wm, win, event);
2415                         
2416                         /* builtin tweak, if action is break it removes tweak */
2417                         wm_tweakevent_test(C, event, action);
2418
2419                         if ((action & WM_HANDLER_BREAK) == 0) {
2420                                 ScrArea *sa;
2421                                 ARegion *ar;
2422         
2423                                 /* Note: setting subwin active should be done here, after modal handlers have been done */
2424                                 if (event->type == MOUSEMOVE) {
2425                                         /* state variables in screen, cursors. Also used in wm_draw.c, fails for modal handlers though */
2426                                         ED_screen_set_subwinactive(C, event);
2427                                         /* for regions having custom cursors */
2428                                         wm_paintcursor_test(C, event);
2429                                 }
2430 #ifdef WITH_INPUT_NDOF
2431                                 else if (event->type == NDOF_MOTION) {
2432                                         win->addmousemove = true;
2433                                 }
2434 #endif
2435
2436                                 for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2437                                         /* after restoring a screen from SCREENMAXIMIZED we have to wait
2438                                          * with the screen handling till the region coordinates are updated */
2439                                         if (win->screen->skip_handling == true) {
2440                                                 /* restore for the next iteration of wm_event_do_handlers */
2441                                                 win->screen->skip_handling = false;
2442                                                 break;
2443                                         }
2444
2445                                         /* update azones if needed - done here because it needs to be independent from redraws */
2446                                         if (sa->flag & AREA_FLAG_ACTIONZONES_UPDATE) {
2447                                                 ED_area_azones_update(sa, &event->x);
2448                                         }
2449
2450                                         if (wm_event_inside_i(event, &sa->totrct)) {
2451                                                 CTX_wm_area_set(C, sa);
2452
2453                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2454                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2455                                                                 if (wm_event_inside_i(event, &ar->winrct)) {
2456                                                                         CTX_wm_region_set(C, ar);
2457                                                                         
2458                                                                         /* call even on non mouse events, since the */
2459                                                                         wm_region_mouse_co(C, event);
2460
2461                                                                         if (!BLI_listbase_is_empty(&wm->drags)) {
2462                                                                                 /* does polls for drop regions and checks uibuts */
2463                                                                                 /* need to be here to make sure region context is true */
2464                                                                                 if (ELEM(event->type, MOUSEMOVE, EVT_DROP) || ISKEYMODIFIER(event->type)) {
2465                                                                                         wm_drags_check_ops(C, event);
2466                                                                                 }
2467                                                                         }
2468                                                                         
2469                                                                         action |= wm_handlers_do(C, event, &ar->handlers);
2470
2471                                                                         /* fileread case (python), [#29489] */
2472                                                                         if (CTX_wm_window(C) == NULL)
2473                                                                                 return;
2474
2475                                                                         if (action & WM_HANDLER_BREAK)
2476                                                                                 break;
2477                                                                 }
2478                                                         }
2479                                                 }
2480
2481                                                 CTX_wm_region_set(C, NULL);
2482
2483                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2484                                                         wm_region_mouse_co(C, event); /* only invalidates event->mval in this case */
2485                                                         action |= wm_handlers_do(C, event, &sa->handlers);
2486                                                 }
2487                                                 CTX_wm_area_set(C, NULL);
2488
2489                                                 /* NOTE: do not escape on WM_HANDLER_BREAK, mousemove needs handled for previous area */
2490                                         }
2491                                 }
2492                                 
2493                                 if ((action & WM_HANDLER_BREAK) == 0) {
2494                                         /* also some non-modal handlers need active area/region */
2495                                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2496                                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2497
2498                                         wm_region_mouse_co(C, event);
2499
2500                                         action |= wm_handlers_do(C, event, &win->handlers);
2501
2502                                         /* fileread case */
2503                                         if (CTX_wm_window(C) == NULL)
2504                                                 return;
2505                                 }
2506
2507                         }
2508
2509                         /* update previous mouse position for following events to use */
2510                         win->eventstate->prevx = event->x;
2511                         win->eventstate->prevy = event->y;
2512
2513                         /* unlink and free here, blender-quit then frees all */
2514                         BLI_remlink(&win->queue, event);
2515                         wm_event_free(event);
2516                         
2517                 }
2518                 
2519                 /* only add mousemove when queue was read entirely */
2520                 if (win->addmousemove && win->eventstate) {
2521                         wmEvent tevent = *(win->eventstate);
2522                         // printf("adding MOUSEMOVE %d %d\n", tevent.x, tevent.y);
2523                         tevent.type = MOUSEMOVE;
2524                         tevent.prevx = tevent.x;
2525                         tevent.prevy = tevent.y;
2526                         wm_event_add(win, &tevent);
2527                         win->addmousemove = 0;
2528                 }
2529                 
2530                 CTX_wm_window_set(C, NULL);
2531         }
2532
2533         /* update key configuration after handling events */
2534         WM_keyconfig_update(wm);
2535
2536         GPU_ASSERT_NO_GL_ERRORS("wm_event_do_handlers");
2537 }
2538
2539 /* ********** filesector handling ************ */
2540
2541 void WM_event_fileselect_event(wmWindowManager *wm, void *ophandle, int eventval)
2542 {
2543         /* add to all windows! */
2544         wmWindow *win;
2545         
2546         for (win = wm->windows.first; win; win = win->next) {
2547                 wmEvent event = *win->eventstate;
2548                 
2549                 event.type = EVT_FILESELECT;
2550                 event.val = eventval;
2551                 event.customdata = ophandle;     // only as void pointer type check
2552
2553                 wm_event_add(win, &event);
2554         }
2555 }
2556
2557 /* operator is supposed to have a filled "path" property */
2558 /* optional property: filetype (XXX enum?) */
2559
2560 /**
2561  * The idea here is to keep a handler alive on window queue, owning the operator.
2562  * The filewindow can send event to make it execute, thus ensuring
2563  * executing happens outside of lower level queues, with UI refreshed.
2564  * Should also allow multiwin solutions
2565  */
2566 void WM_event_add_fileselect(bContext *C, wmOperator *op)
2567 {
2568         wmEventHandler *handler, *handlernext;
2569         wmWindowManager *wm = CTX_wm_manager(C);
2570         wmWindow *win = CTX_wm_window(C);
2571
2572         /* only allow 1 file selector open per window */
2573         for (handler = win->modalhandlers.first; handler; handler = handlernext) {
2574                 handlernext = handler->next;
2575                 
2576                 if (handler->type == WM_HANDLER_FILESELECT) {
2577                         bScreen *screen = CTX_wm_screen(C);
2578                         ScrArea *sa;
2579
2580                         /* find the area with the file selector for this handler */
2581                         for (sa = screen->areabase.first; sa; sa = sa->next) {
2582                                 if (sa->spacetype == SPACE_FILE) {
2583                                         SpaceFile *sfile = sa->spacedata.first;
2584
2585                                         if (sfile->op == handler->op) {
2586                                                 CTX_wm_area_set(C, sa);
2587                                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_CANCEL);
2588                                                 break;
2589                                         }
2590                                 }
2591                         }
2592
2593                         /* if not found we stop the handler without changing the screen */
2594                         if (!sa)
2595                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_EXTERNAL_CANCEL);
2596                 }
2597         }
2598         
2599         handler = MEM_callocN(sizeof(wmEventHandler), "fileselect handler");
2600         
2601         handler->type = WM_HANDLER_FILESELECT;
2602         handler->op = op;
2603         handler->op_area = CTX_wm_area(C);
2604         handler->op_region = CTX_wm_region(C);
2605         
2606         BLI_addhead(&win->modalhandlers, handler);
2607         
2608         /* check props once before invoking if check is available
2609          * ensures initial properties are valid */
2610         if (op->type->check) {
2611                 op->type->check(C, op); /* ignore return value */
2612         }
2613
2614         WM_event_fileselect_event(wm, op, EVT_FILESELECT_FULL_OPEN);
2615 }
2616
2617 #if 0
2618 /* lets not expose struct outside wm? */
2619 static void WM_event_set_handler_flag(wmEventHandler *handler, int flag)
2620 {
2621         handler->flag = flag;
2622 }
2623 #endif
2624
2625 wmEventHandler *WM_event_add_modal_handler(bContext *C, wmOperator *op)
2626 {
2627         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event modal handler");
2628         wmWindow *win = CTX_wm_window(C);
2629         
2630         /* operator was part of macro */
2631         if (op->opm) {
2632                 /* give the mother macro to the handler */
2633                 handler->op = op->opm;
2634                 /* mother macro opm becomes the macro element */
2635                 handler->op->opm = op;
2636         }
2637         else
2638                 handler->op = op;
2639         
2640         handler->op_area = CTX_wm_area(C);       /* means frozen screen context for modal handlers! */
2641         handler->op_region = CTX_wm_region(C);
2642         handler->op_region_type = handler->op_region ? handler->op_region->regiontype : -1;
2643         
2644         BLI_addhead(&win->modalhandlers, handler);
2645
2646         return handler;
2647 }
2648
2649 wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2650 {
2651         wmEventHandler *handler;
2652
2653         if (!keymap) {
2654                 printf("%s: called with NULL keymap\n", __func__);
2655                 return NULL;
2656         }
2657
2658         /* only allow same keymap once */
2659         for (handler = handlers->first; handler; handler = handler->next)
2660                 if (handler->keymap == keymap)
2661                         return handler;
2662         
2663         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2664         BLI_addtail(handlers, handler);
2665         handler->keymap = keymap;
2666
2667         return handler;
2668 }
2669
2670 /* priorities not implemented yet, for time being just insert in begin of list */
2671 wmEventHandler *WM_event_add_keymap_handler_priority(ListBase *handlers, wmKeyMap *keymap, int UNUSED(priority))
2672 {
2673         wmEventHandler *handler;
2674         
2675         WM_event_remove_keymap_handler(handlers, keymap);
2676         
2677         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2678         BLI_addhead(handlers, handler);
2679         handler->keymap = keymap;
2680         
2681         return handler;
2682 }
2683
2684 wmEventHandler *WM_event_add_keymap_handler_bb(ListBase *handlers, wmKeyMap *keymap, const rcti *bblocal, const rcti *bbwin)
2685 {
2686         wmEventHandler *handler = WM_event_add_keymap_handler(handlers, keymap);
2687         
2688         if (handler) {
2689                 handler->bblocal = bblocal;
2690                 handler->bbwin = bbwin;
2691         }
2692         return handler;
2693 }
2694
2695 void WM_event_remove_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2696 {
2697         wmEventHandler *handler;
2698         
2699         for (handler = handlers->first; handler; handler = handler->next) {
2700                 if (handler->keymap == keymap) {
2701                         BLI_remlink(handlers, handler);
2702                         wm_event_free_handler(handler);
2703                         break;
2704                 }
2705         }
2706 }
2707
2708 wmEventHandler *WM_event_add_ui_handler(
2709         const bContext *C, ListBase *handlers,
2710         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove,
2711         void *userdata, const char flag)
2712 {
2713         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event ui handler");
2714         handler->ui_handle = ui_handle;
2715         handler->ui_remove = ui_remove;
2716         handler->ui_userdata = userdata;
2717         if (C) {
2718                 handler->ui_area    = CTX_wm_area(C);
2719                 handler->ui_region  = CTX_wm_region(C);
2720                 handler->ui_menu    = CTX_wm_menu(C);
2721         }
2722         else {
2723                 handler->ui_area    = NULL;
2724                 handler->ui_region  = NULL;
2725                 handler->ui_menu    = NULL;
2726         }
2727
2728         BLI_assert((flag & WM_HANDLER_DO_FREE) == 0);
2729         handler->flag = flag;
2730         
2731         BLI_addhead(handlers, handler);
2732         
2733         return handler;
2734 }
2735
2736 /* set "postpone" for win->modalhandlers, this is in a running for () loop in wm_handlers_do() */
2737 void WM_event_remove_ui_handler(
2738         ListBase *handlers,
2739         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove,
2740         void *userdata, const bool postpone)
2741 {
2742         wmEventHandler *handler;
2743         
2744         for (handler = handlers->first; handler; handler = handler->next) {
2745                 if ((handler->ui_handle == ui_handle) &&
2746                     (handler->ui_remove == ui_remove) &&
2747                     (handler->ui_userdata == userdata))
2748                 {
2749                         /* handlers will be freed in wm_handlers_do() */
2750                         if (postpone) {
2751                                 handler->flag |= WM_HANDLER_DO_FREE;
2752                         }
2753                         else {
2754                                 BLI_remlink(handlers, handler);
2755                                 wm_event_free_handler(handler);
2756                         }
2757                         break;
2758                 }
2759         }
2760 }
2761
2762 void WM_event_free_ui_handler_all(
2763         bContext *C, ListBase *handlers,
2764         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove)
2765 {
2766         wmEventHandler *handler, *handler_next;
2767
2768         for (handler = handlers->first; handler; handler = handler_next) {
2769                 handler_next = handler->next;
2770                 if ((handler->ui_handle == ui_handle) &&
2771                     (handler->ui_remove == ui_remove))
2772                 {
2773                         ui_remove(C, handler->ui_userdata);
2774                         BLI_remlink(handlers, handler);
2775                         wm_event_free_handler(handler);
2776                 }
2777         }
2778 }
2779
2780 wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase *dropboxes)