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