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