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