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         enum { NOP, SET, CLEAR, } hud_status = NOP;
847
848         op->customdata = NULL;
849
850         if (store) {
851                 WM_operator_last_properties_store(op);
852         }
853
854         /* we don't want to do undo pushes for operators that are being
855          * called from operators that already do an undo push. usually
856          * this will happen for python operators that call C operators */
857         if (wm->op_undo_depth == 0) {
858                 if (op->type->flag & OPTYPE_UNDO) {
859                         ED_undo_push_op(C, op);
860                         if (repeat == 0) {
861                                 hud_status = CLEAR;
862                         }
863                 }
864                 else if (op->type->flag & OPTYPE_UNDO_GROUPED) {
865                         ED_undo_grouped_push_op(C, op);
866                         if (repeat == 0) {
867                                 hud_status = CLEAR;
868                         }
869                 }
870
871         }
872
873         if (repeat == 0) {
874                 if (G.debug & G_DEBUG_WM) {
875                         char *buf = WM_operator_pystring(C, op, false, true);
876                         BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
877                         MEM_freeN(buf);
878                 }
879
880                 if (wm_operator_register_check(wm, op->type)) {
881                         /* take ownership of reports (in case python provided own) */
882                         op->reports->flag |= RPT_FREE;
883
884                         wm_operator_register(C, op);
885                         WM_operator_region_active_win_set(C);
886
887                         /* Show the redo panel. */
888                         hud_status = SET;
889                 }
890                 else {
891                         WM_operator_free(op);
892                 }
893         }
894
895         if (hud_status != NOP) {
896                 if (hud_status == SET) {
897                         ScrArea *sa = CTX_wm_area(C);
898                         if (sa) {
899                                 ED_area_type_hud_ensure(C, sa);
900                         }
901                 }
902                 else if (hud_status == CLEAR) {
903                         ED_area_type_hud_clear(wm, NULL);
904                 }
905                 else {
906                         BLI_assert(0);
907                 }
908         }
909 }
910
911 /* if repeat is true, it doesn't register again, nor does it free */
912 static int wm_operator_exec(bContext *C, wmOperator *op, const bool repeat, const bool store)
913 {
914         wmWindowManager *wm = CTX_wm_manager(C);
915         int retval = OPERATOR_CANCELLED;
916
917         CTX_wm_operator_poll_msg_set(C, NULL);
918
919         if (op == NULL || op->type == NULL)
920                 return retval;
921
922         if (0 == WM_operator_poll(C, op->type))
923                 return retval;
924
925         if (op->type->exec) {
926                 if (op->type->flag & OPTYPE_UNDO) {
927                         wm->op_undo_depth++;
928                 }
929
930                 if (repeat) {
931                         op->flag |= OP_IS_REPEAT;
932                 }
933                 retval = op->type->exec(C, op);
934                 OPERATOR_RETVAL_CHECK(retval);
935                 if (repeat) {
936                         op->flag &= ~OP_IS_REPEAT;
937                 }
938
939                 if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm) {
940                         wm->op_undo_depth--;
941                 }
942         }
943
944         /* XXX Disabled the repeat check to address part 2 of #31840.
945          *     Carefully checked all calls to wm_operator_exec and WM_operator_repeat, don't see any reason
946          *     why this was needed, but worth to note it in case something turns bad. (mont29) */
947         if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED) /* && repeat == 0 */)
948                 wm_operator_reports(C, op, retval, false);
949
950         if (retval & OPERATOR_FINISHED) {
951                 wm_operator_finished(C, op, repeat, store && wm->op_undo_depth == 0);
952         }
953         else if (repeat == 0) {
954                 /* warning: modal from exec is bad practice, but avoid crashing. */
955                 if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED)) {
956                         WM_operator_free(op);
957                 }
958         }
959
960         return retval | OPERATOR_HANDLED;
961
962 }
963
964 /* simply calls exec with basic checks */
965 static int wm_operator_exec_notest(bContext *C, wmOperator *op)
966 {
967         int retval = OPERATOR_CANCELLED;
968
969         if (op == NULL || op->type == NULL || op->type->exec == NULL)
970                 return retval;
971
972         retval = op->type->exec(C, op);
973         OPERATOR_RETVAL_CHECK(retval);
974
975         return retval;
976 }
977
978 /**
979  * for running operators with frozen context (modal handlers, menus)
980  *
981  * \param store Store settings for re-use.
982  *
983  * warning: do not use this within an operator to call its self! [#29537] */
984 int WM_operator_call_ex(bContext *C, wmOperator *op,
985                         const bool store)
986 {
987         return wm_operator_exec(C, op, false, store);
988 }
989
990 int WM_operator_call(bContext *C, wmOperator *op)
991 {
992         return WM_operator_call_ex(C, op, false);
993 }
994
995 /**
996  * This is intended to be used when an invoke operator wants to call exec on its self
997  * and is basically like running op->type->exec() directly, no poll checks no freeing,
998  * since we assume whoever called invoke will take care of that
999  */
1000 int WM_operator_call_notest(bContext *C, wmOperator *op)
1001 {
1002         return wm_operator_exec_notest(C, op);
1003 }
1004
1005 /**
1006  * Execute this operator again, put here so it can share above code
1007  */
1008 int WM_operator_repeat(bContext *C, wmOperator *op)
1009 {
1010         return wm_operator_exec(C, op, true, true);
1011 }
1012 /**
1013  * \return true if #WM_operator_repeat can run
1014  * simple check for now but may become more involved.
1015  * To be sure the operator can run call `WM_operator_poll(C, op->type)` also, since this call
1016  * checks if WM_operator_repeat() can run at all, not that it WILL run at any time.
1017  */
1018 bool WM_operator_repeat_check(const bContext *UNUSED(C), wmOperator *op)
1019 {
1020         if (op->type->exec != NULL) {
1021                 return true;
1022         }
1023         else if (op->opm) {
1024                 /* for macros, check all have exec() we can call */
1025                 wmOperatorTypeMacro *otmacro;
1026                 for (otmacro = op->opm->type->macro.first; otmacro; otmacro = otmacro->next) {
1027                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
1028                         if (otm && otm->exec == NULL) {
1029                                 return false;
1030                         }
1031                 }
1032                 return true;
1033         }
1034
1035         return false;
1036 }
1037
1038 bool WM_operator_is_repeat(const bContext *C, const wmOperator *op)
1039 {
1040         /* may be in the operators list or not */
1041         wmOperator *op_prev;
1042         if (op->prev == NULL && op->next == NULL) {
1043                 wmWindowManager *wm = CTX_wm_manager(C);
1044                 op_prev = wm->operators.last;
1045         }
1046         else {
1047                 op_prev = op->prev;
1048         }
1049         return (op_prev && (op->type == op_prev->type));
1050 }
1051
1052 static wmOperator *wm_operator_create(wmWindowManager *wm, wmOperatorType *ot,
1053                                       PointerRNA *properties, ReportList *reports)
1054 {
1055         /* XXX operatortype names are static still. for debug */
1056         wmOperator *op = MEM_callocN(sizeof(wmOperator), ot->idname);
1057
1058         /* XXX adding new operator could be function, only happens here now */
1059         op->type = ot;
1060         BLI_strncpy(op->idname, ot->idname, OP_MAX_TYPENAME);
1061
1062         /* initialize properties, either copy or create */
1063         op->ptr = MEM_callocN(sizeof(PointerRNA), "wmOperatorPtrRNA");
1064         if (properties && properties->data) {
1065                 op->properties = IDP_CopyProperty(properties->data);
1066         }
1067         else {
1068                 IDPropertyTemplate val = {0};
1069                 op->properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
1070         }
1071         RNA_pointer_create(&wm->id, ot->srna, op->properties, op->ptr);
1072
1073         /* initialize error reports */
1074         if (reports) {
1075                 op->reports = reports; /* must be initialized already */
1076         }
1077         else {
1078                 op->reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
1079                 BKE_reports_init(op->reports, RPT_STORE | RPT_FREE);
1080         }
1081
1082         /* recursive filling of operator macro list */
1083         if (ot->macro.first) {
1084                 static wmOperator *motherop = NULL;
1085                 wmOperatorTypeMacro *otmacro;
1086                 int root = 0;
1087
1088                 /* ensure all ops are in execution order in 1 list */
1089                 if (motherop == NULL) {
1090                         motherop = op;
1091                         root = 1;
1092                 }
1093
1094
1095                 /* if properties exist, it will contain everything needed */
1096                 if (properties) {
1097                         otmacro = ot->macro.first;
1098
1099                         RNA_STRUCT_BEGIN (properties, prop)
1100                         {
1101
1102                                 if (otmacro == NULL)
1103                                         break;
1104
1105                                 /* skip invalid properties */
1106                                 if (STREQ(RNA_property_identifier(prop), otmacro->idname)) {
1107                                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
1108                                         PointerRNA someptr = RNA_property_pointer_get(properties, prop);
1109                                         wmOperator *opm = wm_operator_create(wm, otm, &someptr, NULL);
1110
1111                                         IDP_ReplaceGroupInGroup(opm->properties, otmacro->properties);
1112
1113                                         BLI_addtail(&motherop->macro, opm);
1114                                         opm->opm = motherop; /* pointer to mom, for modal() */
1115
1116                                         otmacro = otmacro->next;
1117                                 }
1118                         }
1119                         RNA_STRUCT_END;
1120                 }
1121                 else {
1122                         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
1123                                 wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
1124                                 wmOperator *opm = wm_operator_create(wm, otm, otmacro->ptr, NULL);
1125
1126                                 BLI_addtail(&motherop->macro, opm);
1127                                 opm->opm = motherop; /* pointer to mom, for modal() */
1128                         }
1129                 }
1130
1131                 if (root)
1132                         motherop = NULL;
1133         }
1134
1135         WM_operator_properties_sanitize(op->ptr, 0);
1136
1137         return op;
1138 }
1139
1140 static void wm_region_mouse_co(bContext *C, wmEvent *event)
1141 {
1142         ARegion *ar = CTX_wm_region(C);
1143         if (ar) {
1144                 /* compatibility convention */
1145                 event->mval[0] = event->x - ar->winrct.xmin;
1146                 event->mval[1] = event->y - ar->winrct.ymin;
1147         }
1148         else {
1149                 /* these values are invalid (avoid odd behavior by relying on old mval values) */
1150                 event->mval[0] = -1;
1151                 event->mval[1] = -1;
1152         }
1153 }
1154
1155 #if 1 /* may want to disable operator remembering previous state for testing */
1156
1157 static bool operator_last_properties_init_impl(wmOperator *op, IDProperty *last_properties)
1158 {
1159         bool changed = false;
1160         IDPropertyTemplate val = {0};
1161         IDProperty *replaceprops = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
1162         PropertyRNA *iterprop;
1163
1164         CLOG_INFO(WM_LOG_OPERATORS, 1, "loading previous properties for '%s'", op->type->idname);
1165
1166         iterprop = RNA_struct_iterator_property(op->type->srna);
1167
1168         RNA_PROP_BEGIN (op->ptr, itemptr, iterprop)
1169         {
1170                 PropertyRNA *prop = itemptr.data;
1171                 if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
1172                         if (!RNA_property_is_set(op->ptr, prop)) { /* don't override a setting already set */
1173                                 const char *identifier = RNA_property_identifier(prop);
1174                                 IDProperty *idp_src = IDP_GetPropertyFromGroup(last_properties, identifier);
1175                                 if (idp_src) {
1176                                         IDProperty *idp_dst = IDP_CopyProperty(idp_src);
1177
1178                                         /* note - in the future this may need to be done recursively,
1179                                          * but for now RNA doesn't access nested operators */
1180                                         idp_dst->flag |= IDP_FLAG_GHOST;
1181
1182                                         /* add to temporary group instead of immediate replace,
1183                                          * because we are iterating over this group */
1184                                         IDP_AddToGroup(replaceprops, idp_dst);
1185                                         changed = true;
1186                                 }
1187                         }
1188                 }
1189         }
1190         RNA_PROP_END;
1191
1192         IDP_MergeGroup(op->properties, replaceprops, true);
1193         IDP_FreeProperty(replaceprops);
1194         MEM_freeN(replaceprops);
1195         return changed;
1196 }
1197
1198 bool WM_operator_last_properties_init(wmOperator *op)
1199 {
1200         bool changed = false;
1201         if (op->type->last_properties) {
1202                 changed |= operator_last_properties_init_impl(op, op->type->last_properties);
1203                 for (wmOperator *opm = op->macro.first; opm; opm = opm->next) {
1204                         IDProperty *idp_src = IDP_GetPropertyFromGroup(op->type->last_properties, opm->idname);
1205                         if (idp_src) {
1206                                 changed |= operator_last_properties_init_impl(opm, idp_src);
1207                         }
1208                 }
1209         }
1210         return changed;
1211 }
1212
1213 bool WM_operator_last_properties_store(wmOperator *op)
1214 {
1215         if (op->type->last_properties) {
1216                 IDP_FreeProperty(op->type->last_properties);
1217                 MEM_freeN(op->type->last_properties);
1218                 op->type->last_properties = NULL;
1219         }
1220
1221         if (op->properties) {
1222                 CLOG_INFO(WM_LOG_OPERATORS, 1, "storing properties for '%s'", op->type->idname);
1223                 op->type->last_properties = IDP_CopyProperty(op->properties);
1224         }
1225
1226         if (op->macro.first != NULL) {
1227                 for (wmOperator *opm = op->macro.first; opm; opm = opm->next) {
1228                         if (opm->properties) {
1229                                 if (op->type->last_properties == NULL) {
1230                                         op->type->last_properties = IDP_New(IDP_GROUP, &(IDPropertyTemplate){0}, "wmOperatorProperties");
1231                                 }
1232                                 IDProperty *idp_macro = IDP_CopyProperty(opm->properties);
1233                                 STRNCPY(idp_macro->name, opm->idname);
1234                                 IDP_ReplaceInGroup(op->type->last_properties, idp_macro);
1235                         }
1236                 }
1237         }
1238
1239         return (op->type->last_properties != NULL);
1240 }
1241
1242 #else
1243
1244 bool WM_operator_last_properties_init(wmOperator *UNUSED(op))
1245 {
1246         return false;
1247 }
1248
1249 bool WM_operator_last_properties_store(wmOperator *UNUSED(op))
1250 {
1251         return false;
1252 }
1253
1254 #endif
1255
1256 /**
1257  * Also used for exec when 'event' is NULL.
1258  */
1259 static int wm_operator_invoke(
1260         bContext *C, wmOperatorType *ot, wmEvent *event,
1261         PointerRNA *properties, ReportList *reports,
1262         const bool poll_only, bool use_last_properties)
1263 {
1264         int retval = OPERATOR_PASS_THROUGH;
1265
1266         /* this is done because complicated setup is done to call this function that is better not duplicated */
1267         if (poll_only)
1268                 return WM_operator_poll(C, ot);
1269
1270         if (WM_operator_poll(C, ot)) {
1271                 wmWindowManager *wm = CTX_wm_manager(C);
1272                 wmOperator *op = wm_operator_create(wm, ot, properties, reports); /* if reports == NULL, they'll be initialized */
1273                 const bool is_nested_call = (wm->op_undo_depth != 0);
1274
1275                 if (event != NULL) {
1276                         op->flag |= OP_IS_INVOKE;
1277                 }
1278
1279                 /* initialize setting from previous run */
1280                 if (!is_nested_call && use_last_properties) { /* not called by py script */
1281                         WM_operator_last_properties_init(op);
1282                 }
1283
1284                 if ((event == NULL) || (event->type != MOUSEMOVE)) {
1285                         CLOG_INFO(WM_LOG_HANDLERS, 2,
1286                                   "handle evt %d win %p op %s",
1287                                   event ? event->type : 0, CTX_wm_screen(C)->active_region, ot->idname);
1288                 }
1289
1290                 if (op->type->invoke && event) {
1291                         wm_region_mouse_co(C, event);
1292
1293                         if (op->type->flag & OPTYPE_UNDO)
1294                                 wm->op_undo_depth++;
1295
1296                         retval = op->type->invoke(C, op, event);
1297                         OPERATOR_RETVAL_CHECK(retval);
1298
1299                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1300                                 wm->op_undo_depth--;
1301                 }
1302                 else if (op->type->exec) {
1303                         if (op->type->flag & OPTYPE_UNDO)
1304                                 wm->op_undo_depth++;
1305
1306                         retval = op->type->exec(C, op);
1307                         OPERATOR_RETVAL_CHECK(retval);
1308
1309                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1310                                 wm->op_undo_depth--;
1311                 }
1312                 else {
1313                         /* debug, important to leave a while, should never happen */
1314                         CLOG_ERROR(WM_LOG_OPERATORS, "invalid operator call '%s'", op->idname);
1315                 }
1316
1317                 /* Note, if the report is given as an argument then assume the caller will deal with displaying them
1318                  * currently python only uses this */
1319                 if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED))) {
1320                         /* only show the report if the report list was not given in the function */
1321                         wm_operator_reports(C, op, retval, (reports != NULL));
1322                 }
1323
1324                 if (retval & OPERATOR_HANDLED) {
1325                         /* do nothing, wm_operator_exec() has been called somewhere */
1326                 }
1327                 else if (retval & OPERATOR_FINISHED) {
1328                         const bool store = !is_nested_call && use_last_properties;
1329                         wm_operator_finished(C, op, false, store);
1330                 }
1331                 else if (retval & OPERATOR_RUNNING_MODAL) {
1332                         /* take ownership of reports (in case python provided own) */
1333                         op->reports->flag |= RPT_FREE;
1334
1335                         /* grab cursor during blocking modal ops (X11)
1336                          * Also check for macro
1337                          */
1338                         if (ot->flag & OPTYPE_BLOCKING || (op->opm && op->opm->type->flag & OPTYPE_BLOCKING)) {
1339                                 int bounds[4] = {-1, -1, -1, -1};
1340                                 bool wrap;
1341
1342                                 if (event == NULL) {
1343                                         wrap = false;
1344                                 }
1345                                 else if (op->opm) {
1346                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1347                                                ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR));
1348                                 }
1349                                 else {
1350                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1351                                                ((op->flag & OP_IS_MODAL_GRAB_CURSOR) || (ot->flag & OPTYPE_GRAB_CURSOR));
1352                                 }
1353
1354                                 /* exception, cont. grab in header is annoying */
1355                                 if (wrap) {
1356                                         ARegion *ar = CTX_wm_region(C);
1357                                         if (ar && ar->regiontype == RGN_TYPE_HEADER) {
1358                                                 wrap = false;
1359                                         }
1360                                 }
1361
1362                                 if (wrap) {
1363                                         const rcti *winrect = NULL;
1364                                         ARegion *ar = CTX_wm_region(C);
1365                                         ScrArea *sa = CTX_wm_area(C);
1366
1367                                         if (ar && ar->regiontype == RGN_TYPE_WINDOW &&
1368                                             BLI_rcti_isect_pt_v(&ar->winrct, &event->x))
1369                                         {
1370                                                 winrect = &ar->winrct;
1371                                         }
1372                                         else if (sa && BLI_rcti_isect_pt_v(&sa->totrct, &event->x)) {
1373                                                 winrect = &sa->totrct;
1374                                         }
1375
1376                                         if (winrect) {
1377                                                 bounds[0] = winrect->xmin;
1378                                                 bounds[1] = winrect->ymax;
1379                                                 bounds[2] = winrect->xmax;
1380                                                 bounds[3] = winrect->ymin;
1381                                         }
1382                                 }
1383
1384                                 WM_cursor_grab_enable(CTX_wm_window(C), wrap, false, bounds);
1385                         }
1386
1387                         /* cancel UI handlers, typically tooltips that can hang around
1388                          * while dragging the view or worse, that stay there permanently
1389                          * after the modal operator has swallowed all events and passed
1390                          * none to the UI handler */
1391                         wm_handler_ui_cancel(C);
1392                 }
1393                 else {
1394                         WM_operator_free(op);
1395                 }
1396         }
1397
1398         return retval;
1399 }
1400
1401 /**
1402  * #WM_operator_name_call is the main accessor function
1403  * this is for python to access since its done the operator lookup
1404  *
1405  * invokes operator in context
1406  */
1407 static int wm_operator_call_internal(
1408         bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
1409         const short context, const bool poll_only)
1410 {
1411         wmEvent *event;
1412
1413         int retval;
1414
1415         CTX_wm_operator_poll_msg_set(C, NULL);
1416
1417         /* dummie test */
1418         if (ot) {
1419                 wmWindow *window = CTX_wm_window(C);
1420
1421                 switch (context) {
1422                         case WM_OP_INVOKE_DEFAULT:
1423                         case WM_OP_INVOKE_REGION_WIN:
1424                         case WM_OP_INVOKE_REGION_PREVIEW:
1425                         case WM_OP_INVOKE_REGION_CHANNELS:
1426                         case WM_OP_INVOKE_AREA:
1427                         case WM_OP_INVOKE_SCREEN:
1428                                 /* window is needed for invoke, cancel operator */
1429                                 if (window == NULL) {
1430                                         if (poll_only) {
1431                                                 CTX_wm_operator_poll_msg_set(C, "Missing 'window' in context");
1432                                         }
1433                                         return 0;
1434                                 }
1435                                 else {
1436                                         event = window->eventstate;
1437                                 }
1438                                 break;
1439                         default:
1440                                 event = NULL;
1441                                 break;
1442                 }
1443
1444                 switch (context) {
1445
1446                         case WM_OP_EXEC_REGION_WIN:
1447                         case WM_OP_INVOKE_REGION_WIN:
1448                         case WM_OP_EXEC_REGION_CHANNELS:
1449                         case WM_OP_INVOKE_REGION_CHANNELS:
1450                         case WM_OP_EXEC_REGION_PREVIEW:
1451                         case WM_OP_INVOKE_REGION_PREVIEW:
1452                         {
1453                                 /* forces operator to go to the region window/channels/preview, for header menus
1454                                  * but we stay in the same region if we are already in one
1455                                  */
1456                                 ARegion *ar = CTX_wm_region(C);
1457                                 ScrArea *area = CTX_wm_area(C);
1458                                 int type = RGN_TYPE_WINDOW;
1459
1460                                 switch (context) {
1461                                         case WM_OP_EXEC_REGION_CHANNELS:
1462                                         case WM_OP_INVOKE_REGION_CHANNELS:
1463                                                 type = RGN_TYPE_CHANNELS;
1464                                                 break;
1465
1466                                         case WM_OP_EXEC_REGION_PREVIEW:
1467                                         case WM_OP_INVOKE_REGION_PREVIEW:
1468                                                 type = RGN_TYPE_PREVIEW;
1469                                                 break;
1470
1471                                         case WM_OP_EXEC_REGION_WIN:
1472                                         case WM_OP_INVOKE_REGION_WIN:
1473                                         default:
1474                                                 type = RGN_TYPE_WINDOW;
1475                                                 break;
1476                                 }
1477
1478                                 if (!(ar && ar->regiontype == type) && area) {
1479                                         ARegion *ar1;
1480                                         if (type == RGN_TYPE_WINDOW) {
1481                                                 ar1 = BKE_area_find_region_active_win(area);
1482                                         }
1483                                         else {
1484                                                 ar1 = BKE_area_find_region_type(area, type);
1485                                         }
1486
1487                                         if (ar1)
1488                                                 CTX_wm_region_set(C, ar1);
1489                                 }
1490
1491                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only, true);
1492
1493                                 /* set region back */
1494                                 CTX_wm_region_set(C, ar);
1495
1496                                 return retval;
1497                         }
1498                         case WM_OP_EXEC_AREA:
1499                         case WM_OP_INVOKE_AREA:
1500                         {
1501                                 /* remove region from context */
1502                                 ARegion *ar = CTX_wm_region(C);
1503
1504                                 CTX_wm_region_set(C, NULL);
1505                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only, true);
1506                                 CTX_wm_region_set(C, ar);
1507
1508                                 return retval;
1509                         }
1510                         case WM_OP_EXEC_SCREEN:
1511                         case WM_OP_INVOKE_SCREEN:
1512                         {
1513                                 /* remove region + area from context */
1514                                 ARegion *ar = CTX_wm_region(C);
1515                                 ScrArea *area = CTX_wm_area(C);
1516
1517                                 CTX_wm_region_set(C, NULL);
1518                                 CTX_wm_area_set(C, NULL);
1519                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only, true);
1520                                 CTX_wm_area_set(C, area);
1521                                 CTX_wm_region_set(C, ar);
1522
1523                                 return retval;
1524                         }
1525                         case WM_OP_EXEC_DEFAULT:
1526                         case WM_OP_INVOKE_DEFAULT:
1527                                 return wm_operator_invoke(C, ot, event, properties, reports, poll_only, true);
1528                 }
1529         }
1530
1531         return 0;
1532 }
1533
1534
1535 /* invokes operator in context */
1536 int WM_operator_name_call_ptr(bContext *C, wmOperatorType *ot, short context, PointerRNA *properties)
1537 {
1538         BLI_assert(ot == WM_operatortype_find(ot->idname, true));
1539         return wm_operator_call_internal(C, ot, properties, NULL, context, false);
1540 }
1541 int WM_operator_name_call(bContext *C, const char *opstring, short context, PointerRNA *properties)
1542 {
1543         wmOperatorType *ot = WM_operatortype_find(opstring, 0);
1544         if (ot) {
1545                 return WM_operator_name_call_ptr(C, ot, context, properties);
1546         }
1547
1548         return 0;
1549 }
1550
1551 /**
1552  * Call an existent menu. The menu can be created in C or Python.
1553  */
1554 void WM_menu_name_call(bContext *C, const char *menu_name, short context)
1555 {
1556         wmOperatorType *ot = WM_operatortype_find("WM_OT_call_menu", false);
1557         PointerRNA ptr;
1558         WM_operator_properties_create_ptr(&ptr, ot);
1559         RNA_string_set(&ptr, "name", menu_name);
1560         WM_operator_name_call_ptr(C, ot, context, &ptr);
1561         WM_operator_properties_free(&ptr);
1562 }
1563
1564 /**
1565  * Similar to #WM_operator_name_call called with #WM_OP_EXEC_DEFAULT context.
1566  *
1567  * - #wmOperatorType is used instead of operator name since python already has the operator type.
1568  * - `poll()` must be called by python before this runs.
1569  * - reports can be passed to this function (so python can report them as exceptions).
1570  */
1571 int WM_operator_call_py(
1572         bContext *C, wmOperatorType *ot, short context,
1573         PointerRNA *properties, ReportList *reports, const bool is_undo)
1574 {
1575         int retval = OPERATOR_CANCELLED;
1576
1577 #if 0
1578         wmOperator *op;
1579         op = wm_operator_create(wm, ot, properties, reports);
1580
1581         if (op->type->exec) {
1582                 if (is_undo && op->type->flag & OPTYPE_UNDO)
1583                         wm->op_undo_depth++;
1584
1585                 retval = op->type->exec(C, op);
1586                 OPERATOR_RETVAL_CHECK(retval);
1587
1588                 if (is_undo && op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1589                         wm->op_undo_depth--;
1590         }
1591         else {
1592                 CLOG_WARN(WM_LOG_OPERATORS, "\"%s\" operator has no exec function, Python cannot call it", op->type->name);
1593         }
1594
1595 #endif
1596
1597         /* not especially nice using undo depth here, its used so py never
1598          * triggers undo or stores operators last used state.
1599          *
1600          * we could have some more obvious way of doing this like passing a flag.
1601          */
1602         wmWindowManager *wm = CTX_wm_manager(C);
1603         if (!is_undo && wm) wm->op_undo_depth++;
1604
1605         retval = wm_operator_call_internal(C, ot, properties, reports, context, false);
1606
1607         if (!is_undo && wm && (wm == CTX_wm_manager(C))) wm->op_undo_depth--;
1608
1609         return retval;
1610 }
1611
1612
1613 /* ********************* handlers *************** */
1614
1615 /* future extra customadata free? */
1616 void wm_event_free_handler(wmEventHandler *handler)
1617 {
1618         MEM_freeN(handler);
1619 }
1620
1621 /* only set context when area/region is part of screen */
1622 static void wm_handler_op_context(bContext *C, wmEventHandler *handler, const wmEvent *event)
1623 {
1624         wmWindow *win = CTX_wm_window(C);
1625         bScreen *screen = CTX_wm_screen(C);
1626
1627         if (screen && handler->op) {
1628                 if (handler->op_area == NULL)
1629                         CTX_wm_area_set(C, NULL);
1630                 else {
1631                         ScrArea *sa = NULL;
1632
1633                         ED_screen_areas_iter(win, screen, sa_iter) {
1634                                 if (sa_iter == handler->op_area) {
1635                                         sa = sa_iter;
1636                                         break;
1637                                 }
1638                         }
1639
1640                         if (sa == NULL) {
1641                                 /* when changing screen layouts with running modal handlers (like render display), this
1642                                  * is not an error to print */
1643                                 if (handler->op == NULL) {
1644                                         CLOG_ERROR(WM_LOG_HANDLERS, "internal error: handler (%s) has invalid area", handler->op->type->idname);
1645                                 }
1646                         }
1647                         else {
1648                                 ARegion *ar;
1649                                 wmOperator *op = handler->op ? (handler->op->opm ? handler->op->opm : handler->op) : NULL;
1650                                 CTX_wm_area_set(C, sa);
1651
1652                                 if (op && (op->flag & OP_IS_MODAL_CURSOR_REGION)) {
1653                                         ar = BKE_area_find_region_xy(sa, handler->op_region_type, event->x, event->y);
1654                                         if (ar) {
1655                                                 handler->op_region = ar;
1656                                         }
1657                                 }
1658                                 else {
1659                                         ar = NULL;
1660                                 }
1661
1662                                 if (ar == NULL) {
1663                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1664                                                 if (ar == handler->op_region) {
1665                                                         break;
1666                                                 }
1667                                         }
1668                                 }
1669
1670                                 /* XXX no warning print here, after full-area and back regions are remade */
1671                                 if (ar)
1672                                         CTX_wm_region_set(C, ar);
1673                         }
1674                 }
1675         }
1676 }
1677
1678 /* called on exit or remove area, only here call cancel callback */
1679 void WM_event_remove_handlers(bContext *C, ListBase *handlers)
1680 {
1681         wmEventHandler *handler;
1682         wmWindowManager *wm = CTX_wm_manager(C);
1683
1684         /* C is zero on freeing database, modal handlers then already were freed */
1685         while ((handler = BLI_pophead(handlers))) {
1686                 if (handler->op) {
1687                         wmWindow *win = CTX_wm_window(C);
1688                         if (handler->op->type->cancel) {
1689                                 ScrArea *area = CTX_wm_area(C);
1690                                 ARegion *region = CTX_wm_region(C);
1691
1692                                 wm_handler_op_context(C, handler, win->eventstate);
1693
1694                                 if (handler->op->type->flag & OPTYPE_UNDO)
1695                                         wm->op_undo_depth++;
1696
1697                                 handler->op->type->cancel(C, handler->op);
1698
1699                                 if (handler->op->type->flag & OPTYPE_UNDO)
1700                                         wm->op_undo_depth--;
1701
1702                                 CTX_wm_area_set(C, area);
1703                                 CTX_wm_region_set(C, region);
1704                         }
1705
1706                         WM_cursor_grab_disable(win, NULL);
1707                         WM_operator_free(handler->op);
1708                 }
1709                 else if (handler->ui_remove) {
1710                         ScrArea *area = CTX_wm_area(C);
1711                         ARegion *region = CTX_wm_region(C);
1712                         ARegion *menu = CTX_wm_menu(C);
1713
1714                         if (handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
1715                         if (handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
1716                         if (handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
1717
1718                         handler->ui_remove(C, handler->ui_userdata);
1719
1720                         CTX_wm_area_set(C, area);
1721                         CTX_wm_region_set(C, region);
1722                         CTX_wm_menu_set(C, menu);
1723                 }
1724
1725                 wm_event_free_handler(handler);
1726         }
1727 }
1728
1729 /* do userdef mappings */
1730 int WM_userdef_event_map(int kmitype)
1731 {
1732         switch (kmitype) {
1733                 case SELECTMOUSE:
1734                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1735                 case ACTIONMOUSE:
1736                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1737                 case EVT_TWEAK_A:
1738                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_R : EVT_TWEAK_L;
1739                 case EVT_TWEAK_S:
1740                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_L : EVT_TWEAK_R;
1741                 case WHEELOUTMOUSE:
1742                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELUPMOUSE : WHEELDOWNMOUSE;
1743                 case WHEELINMOUSE:
1744                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELDOWNMOUSE : WHEELUPMOUSE;
1745         }
1746
1747         return kmitype;
1748 }
1749
1750 /**
1751  * Use so we can check if 'wmEvent.type' is released in modal operators.
1752  *
1753  * An alternative would be to add a 'wmEvent.type_nokeymap'... or similar.
1754  */
1755 int WM_userdef_event_type_from_keymap_type(int kmitype)
1756 {
1757         switch (kmitype) {
1758                 case SELECTMOUSE:
1759                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1760                 case ACTIONMOUSE:
1761                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1762                 case EVT_TWEAK_S:
1763                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1764                 case EVT_TWEAK_A:
1765                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1766                 case EVT_TWEAK_L:
1767                         return LEFTMOUSE;
1768                 case EVT_TWEAK_M:
1769                         return MIDDLEMOUSE;
1770                 case EVT_TWEAK_R:
1771                         return RIGHTMOUSE;
1772                 case WHEELOUTMOUSE:
1773                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELUPMOUSE : WHEELDOWNMOUSE;
1774                 case WHEELINMOUSE:
1775                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELDOWNMOUSE : WHEELUPMOUSE;
1776         }
1777
1778         return kmitype;
1779 }
1780
1781 static int wm_eventmatch(const wmEvent *winevent, wmKeyMapItem *kmi)
1782 {
1783         int kmitype = WM_userdef_event_map(kmi->type);
1784
1785         if (kmi->flag & KMI_INACTIVE) return 0;
1786
1787         /* the matching rules */
1788         if (kmitype == KM_TEXTINPUT)
1789                 if (winevent->val == KM_PRESS) {  /* prevent double clicks */
1790                         /* NOT using ISTEXTINPUT anymore because (at least on Windows) some key codes above 255
1791                          * could have printable ascii keys - BUG [#30479] */
1792                         if (ISKEYBOARD(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
1793                 }
1794
1795         if (kmitype != KM_ANY) {
1796                 if (ELEM(kmitype, TABLET_STYLUS, TABLET_ERASER)) {
1797                         const wmTabletData *wmtab = winevent->tablet_data;
1798
1799                         if (wmtab == NULL)
1800                                 return 0;
1801                         else if (winevent->type != LEFTMOUSE) /* tablet events can occur on hover + keypress */
1802                                 return 0;
1803                         else if ((kmitype == TABLET_STYLUS) && (wmtab->Active != EVT_TABLET_STYLUS))
1804                                 return 0;
1805                         else if ((kmitype == TABLET_ERASER) && (wmtab->Active != EVT_TABLET_ERASER))
1806                                 return 0;
1807                 }
1808                 else {
1809                         if (winevent->type != kmitype)
1810                                 return 0;
1811                 }
1812         }
1813
1814         if (kmi->val != KM_ANY)
1815                 if (winevent->val != kmi->val) return 0;
1816
1817         /* modifiers also check bits, so it allows modifier order */
1818         if (kmi->shift != KM_ANY)
1819                 if (winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1820         if (kmi->ctrl != KM_ANY)
1821                 if (winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1822         if (kmi->alt != KM_ANY)
1823                 if (winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1824         if (kmi->oskey != KM_ANY)
1825                 if (winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1826
1827         /* only keymap entry with keymodifier is checked, means all keys without modifier get handled too. */
1828         /* that is currently needed to make overlapping events work (when you press A - G fast or so). */
1829         if (kmi->keymodifier)
1830                 if (winevent->keymodifier != kmi->keymodifier) return 0;
1831
1832         return 1;
1833 }
1834
1835
1836 /* operator exists */
1837 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event, bool *dbl_click_disabled)
1838 {
1839         /* support for modal keymap in macros */
1840         if (op->opm)
1841                 op = op->opm;
1842
1843         if (op->type->modalkeymap) {
1844                 wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1845                 wmKeyMapItem *kmi;
1846
1847                 for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1848                         if (wm_eventmatch(event, kmi)) {
1849
1850                                 event->prevtype = event->type;
1851                                 event->prevval = event->val;
1852                                 event->type = EVT_MODAL_MAP;
1853                                 event->val = kmi->propvalue;
1854
1855                                 break;
1856                         }
1857                 }
1858         }
1859         else {
1860                 /* modal keymap checking returns handled events fine, but all hardcoded modal
1861                  * handling typically swallows all events (OPERATOR_RUNNING_MODAL).
1862                  * This bypass just disables support for double clicks in hardcoded modal handlers */
1863                 if (event->val == KM_DBL_CLICK) {
1864                         event->val = KM_PRESS;
1865                         *dbl_click_disabled = true;
1866                 }
1867         }
1868 }
1869
1870 /**
1871  * Check whether operator is allowed to run in case interface is locked,
1872  * If interface is unlocked, will always return truth.
1873  */
1874 static bool wm_operator_check_locked_interface(bContext *C, wmOperatorType *ot)
1875 {
1876         wmWindowManager *wm = CTX_wm_manager(C);
1877
1878         if (wm->is_interface_locked) {
1879                 if ((ot->flag & OPTYPE_LOCK_BYPASS) == 0) {
1880                         return false;
1881                 }
1882         }
1883
1884         return true;
1885 }
1886
1887 /* bad hacking event system... better restore event type for checking of KM_CLICK for example */
1888 /* XXX modal maps could use different method (ton) */
1889 static void wm_event_modalmap_end(wmEvent *event, bool dbl_click_disabled)
1890 {
1891         if (event->type == EVT_MODAL_MAP) {
1892                 event->type = event->prevtype;
1893                 event->prevtype = 0;
1894                 event->val = event->prevval;
1895                 event->prevval = 0;
1896         }
1897         else if (dbl_click_disabled)
1898                 event->val = KM_DBL_CLICK;
1899
1900 }
1901
1902 /* Warning: this function removes a modal handler, when finished */
1903 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1904                                     wmEvent *event, PointerRNA *properties)
1905 {
1906         int retval = OPERATOR_PASS_THROUGH;
1907
1908         /* derived, modal or blocking operator */
1909         if (handler->op) {
1910                 wmOperator *op = handler->op;
1911                 wmOperatorType *ot = op->type;
1912
1913                 if (!wm_operator_check_locked_interface(C, ot)) {
1914                         /* Interface is locked and operator is not allowed to run,
1915                          * nothing to do in this case.
1916                          */
1917                 }
1918                 else if (ot->modal) {
1919                         /* we set context to where modal handler came from */
1920                         wmWindowManager *wm = CTX_wm_manager(C);
1921                         ScrArea *area = CTX_wm_area(C);
1922                         ARegion *region = CTX_wm_region(C);
1923                         bool dbl_click_disabled = false;
1924
1925                         wm_handler_op_context(C, handler, event);
1926                         wm_region_mouse_co(C, event);
1927                         wm_event_modalkeymap(C, op, event, &dbl_click_disabled);
1928
1929                         if (ot->flag & OPTYPE_UNDO)
1930                                 wm->op_undo_depth++;
1931
1932                         /* warning, after this call all context data and 'event' may be freed. see check below */
1933                         retval = ot->modal(C, op, event);
1934                         OPERATOR_RETVAL_CHECK(retval);
1935
1936                         /* when this is _not_ the case the modal modifier may have loaded
1937                          * a new blend file (demo mode does this), so we have to assume
1938                          * the event, operator etc have all been freed. - campbell */
1939                         if (CTX_wm_manager(C) == wm) {
1940
1941                                 wm_event_modalmap_end(event, dbl_click_disabled);
1942
1943                                 if (ot->flag & OPTYPE_UNDO)
1944                                         wm->op_undo_depth--;
1945
1946                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1947                                         wm_operator_reports(C, op, retval, false);
1948                                 }
1949                                 else {
1950                                         /* not very common, but modal operators may report before finishing */
1951                                         if (!BLI_listbase_is_empty(&op->reports->list)) {
1952                                                 wm_add_reports(op->reports);
1953                                         }
1954                                 }
1955
1956                                 /* important to run 'wm_operator_finished' before NULLing the context members */
1957                                 if (retval & OPERATOR_FINISHED) {
1958                                         wm_operator_finished(C, op, false, true);
1959                                         handler->op = NULL;
1960                                 }
1961                                 else if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1962                                         WM_operator_free(op);
1963                                         handler->op = NULL;
1964                                 }
1965
1966                                 /* putting back screen context, reval can pass trough after modal failures! */
1967                                 if ((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1968                                         CTX_wm_area_set(C, area);
1969                                         CTX_wm_region_set(C, region);
1970                                 }
1971                                 else {
1972                                         /* this special cases is for areas and regions that get removed */
1973                                         CTX_wm_area_set(C, NULL);
1974                                         CTX_wm_region_set(C, NULL);
1975                                 }
1976
1977                                 /* update manipulators during modal handlers */
1978                                 wm_manipulatormaps_handled_modal_update(C, event, handler);
1979
1980                                 /* remove modal handler, operator itself should have been canceled and freed */
1981                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1982                                         WM_cursor_grab_disable(CTX_wm_window(C), NULL);
1983
1984                                         BLI_remlink(handlers, handler);
1985                                         wm_event_free_handler(handler);
1986
1987                                         /* prevent silly errors from operator users */
1988                                         //retval &= ~OPERATOR_PASS_THROUGH;
1989                                 }
1990                         }
1991                 }
1992                 else {
1993                         CLOG_ERROR(WM_LOG_HANDLERS, "missing modal '%s'", op->idname);
1994                 }
1995         }
1996         else {
1997                 wmOperatorType *ot = WM_operatortype_find(event->keymap_idname, 0);
1998
1999                 if (ot && wm_operator_check_locked_interface(C, ot)) {
2000                         bool use_last_properties = true;
2001                         PointerRNA tool_properties = {{0}};
2002                         bool use_tool_properties = (handler->keymap_tool != NULL);
2003
2004                         if (use_tool_properties) {
2005                                 WM_toolsystem_ref_properties_init_for_keymap(handler->keymap_tool, &tool_properties, properties, ot);
2006                                 properties = &tool_properties;
2007                                 use_last_properties = false;
2008                         }
2009
2010                         retval = wm_operator_invoke(C, ot, event, properties, NULL, false, use_last_properties);
2011
2012                         if (use_tool_properties) {
2013                                 WM_operator_properties_free(&tool_properties);
2014                         }
2015                 }
2016         }
2017         /* Finished and pass through flag as handled */
2018
2019         /* Finished and pass through flag as handled */
2020         if (retval == (OPERATOR_FINISHED | OPERATOR_PASS_THROUGH))
2021                 return WM_HANDLER_HANDLED;
2022
2023         /* Modal unhandled, break */
2024         if (retval == (OPERATOR_PASS_THROUGH | OPERATOR_RUNNING_MODAL))
2025                 return (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
2026
2027         if (retval & OPERATOR_PASS_THROUGH)
2028                 return WM_HANDLER_CONTINUE;
2029
2030         return WM_HANDLER_BREAK;
2031 }
2032
2033 /* fileselect handlers are only in the window queue, so it's safe to switch screens or area types */
2034 static int wm_handler_fileselect_do(bContext *C, ListBase *handlers, wmEventHandler *handler, int val)
2035 {
2036         wmWindowManager *wm = CTX_wm_manager(C);
2037         SpaceFile *sfile;
2038         int action = WM_HANDLER_CONTINUE;
2039
2040         switch (val) {
2041                 case EVT_FILESELECT_FULL_OPEN:
2042                 {
2043                         ScrArea *sa;
2044
2045                         /* sa can be null when window A is active, but mouse is over window B
2046                          * in this case, open file select in original window A. Also don't
2047                          * use global areas. */
2048                         if (handler->op_area == NULL || ED_area_is_global(handler->op_area)) {
2049                                 bScreen *screen = CTX_wm_screen(C);
2050                                 sa = (ScrArea *)screen->areabase.first;
2051                         }
2052                         else {
2053                                 sa = handler->op_area;
2054                         }
2055
2056                         if (sa->full) {
2057                                 /* ensure the first area becomes the file browser, because the second one is the small
2058                                  * top (info-)area which might be too small (in fullscreens we have max two areas) */
2059                                 if (sa->prev) {
2060                                         sa = sa->prev;
2061                                 }
2062                                 ED_area_newspace(C, sa, SPACE_FILE, true);     /* 'sa' is modified in-place */
2063                                 /* we already had a fullscreen here -> mark new space as a stacked fullscreen */
2064                                 sa->flag |= (AREA_FLAG_STACKED_FULLSCREEN | AREA_FLAG_TEMP_TYPE);
2065                         }
2066                         else if (sa->spacetype == SPACE_FILE) {
2067                                 sa = ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENMAXIMIZED);
2068                         }
2069                         else {
2070                                 sa = ED_screen_full_newspace(C, sa, SPACE_FILE);    /* sets context */
2071                         }
2072
2073                         /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
2074                          * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
2075                         /* sa = CTX_wm_area(C); */
2076
2077                         /* settings for filebrowser, sfile is not operator owner but sends events */
2078                         sfile = (SpaceFile *)sa->spacedata.first;
2079                         sfile->op = handler->op;
2080
2081                         ED_fileselect_set_params(sfile);
2082
2083                         action = WM_HANDLER_BREAK;
2084                         break;
2085                 }
2086
2087                 case EVT_FILESELECT_EXEC:
2088                 case EVT_FILESELECT_CANCEL:
2089                 case EVT_FILESELECT_EXTERNAL_CANCEL:
2090                 {
2091                         /* remlink now, for load file case before removing*/
2092                         BLI_remlink(handlers, handler);
2093
2094                         if (val != EVT_FILESELECT_EXTERNAL_CANCEL) {
2095                                 ScrArea *sa = CTX_wm_area(C);
2096
2097                                 if (sa->full) {
2098                                         ED_screen_full_prevspace(C, sa);
2099                                 }
2100                                 /* user may have left fullscreen */
2101                                 else {
2102                                         ED_area_prevspace(C, sa);
2103                                 }
2104                         }
2105
2106                         wm_handler_op_context(C, handler, CTX_wm_window(C)->eventstate);
2107
2108                         /* needed for UI_popup_menu_reports */
2109
2110                         if (val == EVT_FILESELECT_EXEC) {
2111                                 int retval;
2112
2113                                 if (handler->op->type->flag & OPTYPE_UNDO)
2114                                         wm->op_undo_depth++;
2115
2116                                 retval = handler->op->type->exec(C, handler->op);
2117
2118                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
2119                                 if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
2120                                         wm->op_undo_depth--;
2121
2122                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
2123                                 if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0) {
2124                                         if (handler->op->type->flag & OPTYPE_UNDO)
2125                                                 ED_undo_push_op(C, handler->op);
2126                                         else if (handler->op->type->flag & OPTYPE_UNDO_GROUPED)
2127                                                 ED_undo_grouped_push_op(C, handler->op);
2128                                 }
2129
2130                                 if (handler->op->reports->list.first) {
2131
2132                                         /* FIXME, temp setting window, this is really bad!
2133                                          * only have because lib linking errors need to be seen by users :(
2134                                          * it can be removed without breaking anything but then no linking errors - campbell */
2135                                         wmWindow *win_prev = CTX_wm_window(C);
2136                                         ScrArea *area_prev = CTX_wm_area(C);
2137                                         ARegion *ar_prev = CTX_wm_region(C);
2138
2139                                         if (win_prev == NULL)
2140                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
2141
2142                                         BKE_report_print_level_set(handler->op->reports, RPT_WARNING);
2143                                         UI_popup_menu_reports(C, handler->op->reports);
2144
2145                                         /* XXX - copied from 'wm_operator_finished()' */
2146                                         /* add reports to the global list, otherwise they are not seen */
2147                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
2148
2149                                         /* more hacks, since we meddle with reports, banner display doesn't happen automatic */
2150                                         WM_report_banner_show();
2151
2152                                         CTX_wm_window_set(C, win_prev);
2153                                         CTX_wm_area_set(C, area_prev);
2154                                         CTX_wm_region_set(C, ar_prev);
2155                                 }
2156
2157                                 /* for WM_operator_pystring only, custom report handling is done above */
2158                                 wm_operator_reports(C, handler->op, retval, true);
2159
2160                                 if (retval & OPERATOR_FINISHED) {
2161                                         WM_operator_last_properties_store(handler->op);
2162                                 }
2163
2164                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
2165                                         WM_operator_free(handler->op);
2166                                 }
2167                         }
2168                         else {
2169                                 if (handler->op->type->cancel) {
2170                                         if (handler->op->type->flag & OPTYPE_UNDO)
2171                                                 wm->op_undo_depth++;
2172
2173                                         handler->op->type->cancel(C, handler->op);
2174
2175                                         if (handler->op->type->flag & OPTYPE_UNDO)
2176                                                 wm->op_undo_depth--;
2177                                 }
2178
2179                                 WM_operator_free(handler->op);
2180                         }
2181
2182                         CTX_wm_area_set(C, NULL);
2183
2184                         wm_event_free_handler(handler);
2185
2186                         action = WM_HANDLER_BREAK;
2187                         break;
2188                 }
2189         }
2190
2191         return action;
2192 }
2193
2194 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, const wmEvent *event)
2195 {
2196         int action = WM_HANDLER_CONTINUE;
2197
2198         if (event->type != EVT_FILESELECT)
2199                 return action;
2200         if (handler->op != (wmOperator *)event->customdata)
2201                 return action;
2202
2203         return wm_handler_fileselect_do(C, handlers, handler, event->val);
2204 }
2205
2206 static bool handler_boundbox_test(wmEventHandler *handler, const wmEvent *event)
2207 {
2208         if (handler->bbwin) {
2209                 if (handler->bblocal) {
2210                         rcti rect = *handler->bblocal;
2211                         BLI_rcti_translate(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
2212
2213                         if (BLI_rcti_isect_pt_v(&rect, &event->x))
2214                                 return 1;
2215                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(&rect, &event->prevx))
2216                                 return 1;
2217                         else
2218                                 return 0;
2219                 }
2220                 else {
2221                         if (BLI_rcti_isect_pt_v(handler->bbwin, &event->x))
2222                                 return 1;
2223                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(handler->bbwin, &event->prevx))
2224                                 return 1;
2225                         else
2226                                 return 0;
2227                 }
2228         }
2229         return 1;
2230 }
2231
2232 static int wm_action_not_handled(int action)
2233 {
2234         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
2235 }
2236
2237 static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers)
2238 {
2239         const bool do_debug_handler = (G.debug & G_DEBUG_HANDLERS) &&
2240                 /* comment this out to flood the console! (if you really want to test) */
2241                 !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
2242                 ;
2243 # define PRINT if (do_debug_handler) printf
2244
2245         wmWindowManager *wm = CTX_wm_manager(C);
2246         wmEventHandler *handler, *nexthandler;
2247         int action = WM_HANDLER_CONTINUE;
2248         int always_pass;
2249
2250         if (handlers == NULL) {
2251                 return action;
2252         }
2253
2254         /* modal handlers can get removed in this loop, we keep the loop this way
2255          *
2256          * note: check 'handlers->first' because in rare cases the handlers can be cleared
2257          * by the event thats called, for eg:
2258          *
2259          * Calling a python script which changes the area.type, see [#32232] */
2260         for (handler = handlers->first; handler && handlers->first; handler = nexthandler) {
2261
2262                 nexthandler = handler->next;
2263
2264                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
2265                 if (handler->flag & WM_HANDLER_DO_FREE) {
2266                         /* pass */
2267                 }
2268                 else if (handler_boundbox_test(handler, event)) { /* optional boundbox */
2269                         /* in advance to avoid access to freed event on window close */
2270                         always_pass = wm_event_always_pass(event);
2271
2272                         /* modal+blocking handler */
2273                         if (handler->flag & WM_HANDLER_BLOCKING)
2274                                 action |= WM_HANDLER_BREAK;
2275
2276                         if (handler->keymap) {
2277                                 wmKeyMap *keymap = WM_keymap_active(wm, handler->keymap);
2278                                 wmKeyMapItem *kmi;
2279
2280                                 PRINT("%s:   checking '%s' ...", __func__, keymap->idname);
2281
2282                                 if (WM_keymap_poll(C, keymap)) {
2283
2284                                         PRINT("pass\n");
2285
2286                                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
2287                                                 if (wm_eventmatch(event, kmi)) {
2288                                                         struct wmEventHandler_KeymapFn keymap_callback = handler->keymap_callback;
2289
2290                                                         PRINT("%s:     item matched '%s'\n", __func__, kmi->idname);
2291
2292                                                         /* weak, but allows interactive callback to not use rawkey */
2293                                                         event->keymap_idname = kmi->idname;
2294
2295                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
2296
2297                                                         if (action & WM_HANDLER_BREAK) {
2298                                                                 /* not always_pass here, it denotes removed handler */
2299                                                                 CLOG_INFO(WM_LOG_HANDLERS, 2, "handled! '%s'", kmi->idname);
2300                                                                 if (keymap_callback.handle_post_fn != NULL) {
2301                                                                         keymap_callback.handle_post_fn(keymap, kmi, keymap_callback.user_data);
2302                                                                 }
2303                                                                 break;
2304                                                         }
2305                                                         else {
2306                                                                 if (action & WM_HANDLER_HANDLED) {
2307                                                                         CLOG_INFO(WM_LOG_HANDLERS, 2, "handled - and pass on! '%s'", kmi->idname);
2308                                                                 }
2309                                                                 else {
2310                                                                         CLOG_INFO(WM_LOG_HANDLERS, 2, "un-handled '%s'", kmi->idname);
2311                                                                 }
2312                                                         }
2313                                                 }
2314                                         }
2315                                 }
2316                                 else {
2317                                         PRINT("fail\n");
2318                                 }
2319                         }
2320                         else if (handler->ui_handle) {
2321                                 if (!wm->is_interface_locked) {
2322                                         action |= wm_handler_ui_call(C, handler, event, always_pass);
2323                                 }
2324                         }
2325                         else if (handler->type == WM_HANDLER_FILESELECT) {
2326                                 if (!wm->is_interface_locked) {
2327                                         /* screen context changes here */
2328                                         action |= wm_handler_fileselect_call(C, handlers, handler, event);
2329                                 }
2330                         }
2331                         else if (handler->dropboxes) {
2332                                 if (!wm->is_interface_locked && event->type == EVT_DROP) {
2333                                         wmDropBox *drop = handler->dropboxes->first;
2334                                         for (; drop; drop = drop->next) {
2335                                                 /* other drop custom types allowed */
2336                                                 if (event->custom == EVT_DATA_DRAGDROP) {
2337                                                         ListBase *lb = (ListBase *)event->customdata;
2338                                                         wmDrag *drag;
2339
2340                                                         for (drag = lb->first; drag; drag = drag->next) {
2341                                                                 if (drop->poll(C, drag, event)) {
2342                                                                         drop->copy(drag, drop);
2343
2344                                                                         /* free the drags before calling operator */
2345                                                                         WM_drag_free_list(lb);
2346
2347                                                                         event->customdata = NULL;
2348                                                                         event->custom = 0;
2349
2350                                                                         WM_operator_name_call_ptr(C, drop->ot, drop->opcontext, drop->ptr);
2351                                                                         action |= WM_HANDLER_BREAK;
2352
2353                                                                         /* XXX fileread case */
2354                                                                         if (CTX_wm_window(C) == NULL)
2355                                                                                 return action;
2356
2357                                                                         /* escape from drag loop, got freed */
2358                                                                         break;
2359                                                                 }
2360                                                         }
2361                                                 }
2362                                         }
2363                                 }
2364                         }
2365                         else if (handler->manipulator_map) {
2366                                 ScrArea *area = CTX_wm_area(C);
2367                                 ARegion *region = CTX_wm_region(C);
2368                                 wmManipulatorMap *mmap = handler->manipulator_map;
2369                                 wmManipulator *mpr = wm_manipulatormap_highlight_get(mmap);
2370
2371                                 if (region->manipulator_map != handler->manipulator_map) {
2372                                         WM_manipulatormap_tag_refresh(handler->manipulator_map);
2373                                 }
2374
2375                                 wm_manipulatormap_handler_context(C, handler);
2376                                 wm_region_mouse_co(C, event);
2377
2378                                 /* handle manipulator highlighting */
2379                                 if (event->type == MOUSEMOVE && !wm_manipulatormap_modal_get(mmap)) {
2380                                         int part;
2381                                         mpr = wm_manipulatormap_highlight_find(mmap, C, event, &part);
2382                                         if (wm_manipulatormap_highlight_set(mmap, C, mpr, part) && mpr != NULL) {
2383                                                 WM_tooltip_timer_init(C, CTX_wm_window(C), region, WM_manipulatormap_tooltip_init);
2384                                         }
2385                                 }
2386                                 else {
2387                                         /* Either we operate on a single highlighted item
2388                                          * or groups attached to the selected manipulators.
2389                                          * To simplify things both cases loop over an array of items. */
2390                                         wmManipulatorGroup *mgroup_first;
2391                                         bool is_mgroup_single;
2392
2393                                         if (ISMOUSE(event->type)) {
2394                                                 /* Keep mpr set as-is, just fake single selection. */
2395                                                 if (mpr) {
2396                                                         mgroup_first = mpr->parent_mgroup;
2397                                                 }
2398                                                 else {
2399                                                         mgroup_first = NULL;
2400                                                 }
2401                                                 is_mgroup_single = true;
2402                                         }
2403                                         else {
2404                                                 if (WM_manipulatormap_is_any_selected(mmap)) {
2405                                                         const ListBase *groups = WM_manipulatormap_group_list(mmap);
2406                                                         mgroup_first = groups->first;
2407                                                 }
2408                                                 else {
2409                                                         mgroup_first = NULL;
2410                                                 }
2411                                                 is_mgroup_single = false;
2412                                         }
2413
2414                                         /* Don't use from now on. */
2415                                         mpr = NULL;
2416
2417                                         for (wmManipulatorGroup *mgroup = mgroup_first; mgroup; mgroup = mgroup->next) {
2418                                                 /* get user customized keymap from default one */
2419
2420                                                 if ((is_mgroup_single == false) &&
2421                                                     /* We might want to change the logic here and use some kind of manipulator edit-mode.
2422                                                      * For now just use keymap when a selection exists. */
2423                                                     wm_manipulatorgroup_is_any_selected(mgroup) == false)
2424                                                 {
2425                                                         continue;
2426                                                 }
2427
2428                                                 wmKeyMap *keymap = WM_keymap_active(wm, mgroup->type->keymap);
2429                                                 wmKeyMapItem *kmi;
2430
2431                                                 PRINT("%s:   checking '%s' ...", __func__, keymap->idname);
2432
2433                                                 if (WM_keymap_poll(C, keymap)) {
2434                                                         PRINT("pass\n");
2435                                                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
2436                                                                 if (wm_eventmatch(event, kmi)) {
2437                                                                         struct wmEventHandler_KeymapFn keymap_callback = handler->keymap_callback;
2438                                                                         wmOperator *op = handler->op;
2439
2440                                                                         PRINT("%s:     item matched '%s'\n", __func__, kmi->idname);
2441
2442                                                                         /* weak, but allows interactive callback to not use rawkey */
2443                                                                         event->keymap_idname = kmi->idname;
2444
2445                                                                         CTX_wm_manipulator_group_set(C, mgroup);
2446
2447                                                                         /* handler->op is called later, we want keymap op to be triggered here */
2448                                                                         handler->op = NULL;
2449                                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
2450                                                                         handler->op = op;
2451
2452                                                                         CTX_wm_manipulator_group_set(C, NULL);
2453
2454                                                                         if (action & WM_HANDLER_BREAK) {
2455                                                                                 if (keymap_callback.handle_post_fn != NULL) {
2456                                                                                         keymap_callback.handle_post_fn(keymap, kmi, keymap_callback.user_data);
2457                                                                                 }
2458
2459                                                                                 if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS)) {
2460                                                                                         printf("%s:       handled - and pass on! '%s'\n",
2461                                                                                                __func__, kmi->idname);
2462                                                                                 }
2463                                                                                 break;
2464                                                                         }
2465                                                                         else {
2466                                                                                 if (action & WM_HANDLER_HANDLED) {
2467                                                                                         if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS)) {
2468                                                                                                 printf("%s:       handled - and pass on! '%s'\n",
2469                                                                                                        __func__, kmi->idname);
2470                                                                                         }
2471                                                                                 }
2472                                                                                 else {
2473                                                                                         PRINT("%s:       un-handled '%s'\n",
2474                                                                                               __func__, kmi->idname);
2475                                                                                 }
2476                                                                         }
2477                                                                 }
2478                                                         }
2479                                                 }
2480                                                 else {
2481                                                         PRINT("fail\n");
2482                                                 }
2483
2484                                                 if (action & WM_HANDLER_BREAK) {
2485                                                         break;
2486                                                 }
2487
2488                                                 if (is_mgroup_single) {
2489                                                         break;
2490                                                 }
2491                                         }
2492                                 }
2493
2494                                 /* restore the area */
2495                                 CTX_wm_area_set(C, area);
2496                                 CTX_wm_region_set(C, region);
2497
2498                                 if (handler->op) {
2499                                         action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
2500                                 }
2501                         }
2502                         else {
2503                                 /* modal, swallows all */
2504                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
2505                         }
2506
2507                         if (action & WM_HANDLER_BREAK) {
2508                                 if (always_pass)
2509                                         action &= ~WM_HANDLER_BREAK;
2510                                 else
2511                                         break;
2512                         }
2513                 }
2514
2515                 /* XXX fileread case, if the wm is freed then the handler's
2516                  * will have been too so the code below need not run. */
2517                 if (CTX_wm_window(C) == NULL) {
2518                         return action;
2519                 }
2520
2521                 /* XXX code this for all modal ops, and ensure free only happens here */
2522
2523                 /* modal ui handler can be tagged to be freed */
2524                 if (BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
2525                         if (handler->flag & WM_HANDLER_DO_FREE) {
2526                                 BLI_remlink(handlers, handler);
2527                                 wm_event_free_handler(handler);
2528                         }
2529                 }
2530         }
2531
2532         if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
2533                 wm_cursor_arrow_move(CTX_wm_window(C), event);
2534
2535 #undef PRINT
2536
2537         return action;
2538 }
2539
2540 /* this calls handlers twice - to solve (double-)click events */
2541 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
2542 {
2543         int action = wm_handlers_do_intern(C, event, handlers);
2544
2545         /* fileread case */
2546         if (CTX_wm_window(C) == NULL)
2547                 return action;
2548
2549         if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2550
2551                 /* Test for CLICK_DRAG events. */
2552                 if (wm_action_not_handled(action)) {
2553                         if (event->check_drag) {
2554                                 wmWindow *win = CTX_wm_window(C);
2555                                 if ((abs(event->x - win->eventstate->prevclickx)) >= U.tweak_threshold ||
2556                                     (abs(event->y - win->eventstate->prevclicky)) >= U.tweak_threshold)
2557                                 {
2558                                         short val = event->val;
2559                                         short type = event->type;
2560                                         event->val = KM_CLICK_DRAG;
2561                                         event->type = win->eventstate->type;
2562
2563                                         CLOG_INFO(WM_LOG_HANDLERS, 1, "handling PRESS_DRAG");
2564
2565                                         action |= wm_handlers_do_intern(C, event, handlers);
2566
2567                                         event->val = val;
2568                                         event->type = type;
2569
2570                                         win->eventstate->check_click = 0;
2571                                         win->eventstate->check_drag = 0;
2572                                 }
2573                         }
2574                 }
2575                 else {
2576                         wmWindow *win = CTX_wm_window(C);
2577                         if (win) {
2578                                 win->eventstate->check_drag = 0;
2579                         }
2580                 }
2581         }
2582         else if (ISMOUSE_BUTTON(event->type) || ISKEYBOARD(event->type)) {
2583                 /* All events that don't set wmEvent.prevtype must be ignored. */
2584
2585                 /* Test for CLICK events. */
2586                 if (wm_action_not_handled(action)) {
2587                         wmWindow *win = CTX_wm_window(C);
2588
2589                         /* eventstate stores if previous event was a KM_PRESS, in case that
2590                          * wasn't handled, the KM_RELEASE will become a KM_CLICK */
2591
2592                         if (win != NULL) {
2593                                 if (event->val == KM_PRESS) {
2594                                         win->eventstate->check_click = true;
2595                                         win->eventstate->check_drag = true;
2596                                 }
2597                                 else if (event->val == KM_RELEASE) {
2598                                         win->eventstate->check_drag = false;
2599                                 }
2600                         }
2601
2602                         if (win && win->eventstate->prevtype == event->type) {
2603
2604                                 if ((event->val == KM_RELEASE) &&
2605                                     (win->eventstate->prevval == KM_PRESS) &&
2606                                     (win->eventstate->check_click == true))
2607                                 {
2608                                         if ((abs(event->x - win->eventstate->prevclickx)) <= WM_EVENT_CLICK_WIGGLE_ROOM &&
2609                                             (abs(event->y - win->eventstate->prevclicky)) <= WM_EVENT_CLICK_WIGGLE_ROOM)
2610                                         {
2611                                                 event->val = KM_CLICK;
2612
2613                                                 CLOG_INFO(WM_LOG_HANDLERS, 1, "handling CLICK");
2614
2615                                                 action |= wm_handlers_do_intern(C, event, handlers);
2616
2617                                                 event->val = KM_RELEASE;
2618                                         }
2619                                         else {
2620                                                 win->eventstate->check_click = 0;
2621                                                 win->eventstate->check_drag = 0;
2622                                         }
2623                                 }
2624                                 else if (event->val == KM_DBL_CLICK) {
2625                                         event->val = KM_PRESS;
2626                                         action |= wm_handlers_do_intern(C, event, handlers);
2627
2628                                         /* revert value if not handled */
2629                                         if (wm_action_not_handled(action)) {
2630                                                 event->val = KM_DBL_CLICK;
2631                                         }
2632                                 }
2633                         }
2634                 }
2635                 else {
2636                         wmWindow *win = CTX_wm_window(C);
2637                         if (win) {
2638                                 win->eventstate->check_click = 0;
2639                         }
2640                 }
2641         }
2642
2643         return action;
2644 }
2645
2646 static int wm_event_inside_i(wmEvent *event, rcti *rect)
2647 {
2648         if (wm_event_always_pass(event))
2649                 return 1;
2650         if (BLI_rcti_isect_pt_v(rect, &event->x))
2651                 return 1;
2652         return 0;
2653 }
2654
2655 static ScrArea *area_event_inside(bContext *C, const int xy[2])
2656 {
2657         wmWindow *win = CTX_wm_window(C);
2658         bScreen *screen = CTX_wm_screen(C);
2659
2660         if (screen) {
2661                 ED_screen_areas_iter(win, screen, sa) {
2662                         if (BLI_rcti_isect_pt_v(&sa->totrct, xy))
2663                                 return sa;
2664                 }
2665         }
2666         return NULL;
2667 }
2668
2669 static ARegion *region_event_inside(bContext *C, const int xy[2])
2670 {
2671         bScreen *screen = CTX_wm_screen(C);
2672         ScrArea *area = CTX_wm_area(C);
2673         ARegion *ar;
2674
2675         if (screen && area)
2676                 for (ar = area->regionbase.first; ar; ar = ar->next)
2677                         if (BLI_rcti_isect_pt_v(&ar->winrct, xy))
2678                                 return ar;
2679         return NULL;
2680 }
2681
2682 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
2683 {
2684         if (ar) {
2685                 for (; pc; pc = pc->next) {
2686                         if (pc->poll == NULL || pc->poll(C)) {
2687                                 wmWindow *win = CTX_wm_window(C);
2688                                 WM_paint_cursor_tag_redraw(win, ar);
2689                         }
2690                 }
2691         }
2692 }
2693
2694 /* called on mousemove, check updates for paintcursors */
2695 /* context was set on active area and region */
2696 static void wm_paintcursor_test(bContext *C, const wmEvent *event)
2697 {
2698         wmWindowManager *wm = CTX_wm_manager(C);
2699
2700         if (wm->paintcursors.first) {
2701                 ARegion *ar = CTX_wm_region(C);
2702
2703                 if (ar)
2704                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
2705
2706                 /* if previous position was not in current region, we have to set a temp new context */
2707                 if (ar == NULL || !BLI_rcti_isect_pt_v(&ar->winrct, &event->prevx)) {
2708                         ScrArea *sa = CTX_wm_area(C);
2709
2710                         CTX_wm_area_set(C, area_event_inside(C, &event->prevx));
2711                         CTX_wm_region_set(C, region_event_inside(C, &event->prevx));
2712
2713                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
2714
2715                         CTX_wm_area_set(C, sa);
2716                         CTX_wm_region_set(C, ar);
2717                 }
2718         }
2719 }
2720
2721 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
2722 {
2723         bScreen *screen = WM_window_get_active_screen(win);
2724
2725         if (BLI_listbase_is_empty(&wm->drags)) {
2726                 return;
2727         }
2728
2729         if (event->type == MOUSEMOVE || ISKEYMODIFIER(event->type)) {
2730                 screen->do_draw_drag = true;
2731         }
2732         else if (event->type == ESCKEY) {
2733                 WM_drag_free_list(&wm->drags);
2734
2735                 screen->do_draw_drag = true;
2736         }
2737         else if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2738                 event->type = EVT_DROP;
2739
2740                 /* create customdata, first free existing */
2741                 if (event->customdata) {
2742                         if (event->customdatafree)
2743                                 MEM_freeN(event->customdata);
2744                 }
2745
2746                 event->custom = EVT_DATA_DRAGDROP;
2747                 event->customdata = &wm->drags;
2748                 event->customdatafree = 1;
2749
2750                 /* clear drop icon */
2751                 screen->do_draw_drag = true;
2752
2753                 /* restore cursor (disabled, see wm_dragdrop.c) */
2754                 // WM_cursor_modal_restore(win);
2755         }
2756 }
2757
2758 /* filter out all events of the pie that spawned the last pie unless it's a release event */
2759 static bool wm_event_pie_filter(wmWindow *win, const wmEvent *event)
2760 {
2761         if (win->lock_pie_event && win->lock_pie_event == event->type) {
2762                 if (event->val == KM_RELEASE) {
2763                         win->lock_pie_event = EVENT_NONE;
2764                         return false;
2765                 }
2766                 else {
2767                         return true;
2768                 }
2769         }
2770         else {
2771                 return false;
2772         }
2773 }
2774
2775 /* called in main loop */
2776 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
2777 void wm_event_do_handlers(bContext *C)
2778 {
2779         wmWindowManager *wm = CTX_wm_manager(C);
2780         wmWindow *win;
2781
2782         /* update key configuration before handling events */
2783         WM_keyconfig_update(wm);
2784         WM_manipulatorconfig_update(CTX_data_main(C));
2785
2786         for (win = wm->windows.first; win; win = win->next) {
2787                 bScreen *screen = WM_window_get_active_screen(win);
2788                 wmEvent *event;
2789
2790                 /* some safty checks - these should always be set! */
2791                 BLI_assert(WM_window_get_active_scene(win));
2792                 BLI_assert(WM_window_get_active_screen(win));
2793                 BLI_assert(WM_window_get_active_workspace(win));
2794
2795                 if (screen == NULL)
2796                         wm_event_free_all(win);
2797                 else {
2798                         Scene *scene = WM_window_get_active_scene(win);
2799
2800                         if (scene) {
2801                                 int is_playing_sound = BKE_sound_scene_playing(scene);
2802
2803                                 if (is_playing_sound != -1) {
2804                                         bool is_playing_screen;
2805                                         CTX_wm_window_set(C, win);
2806                                         CTX_data_scene_set(C, scene);
2807
2808                                         is_playing_screen = (ED_screen_animation_playing(wm) != NULL);
2809
2810                                         if (((is_playing_sound == 1) && (is_playing_screen == 0)) ||
2811                                             ((is_playing_sound == 0) && (is_playing_screen == 1)))
2812                                         {
2813                                                 ED_screen_animation_play(C, -1, 1);
2814                                         }
2815
2816                                         if (is_playing_sound == 0) {
2817                                                 const float time = BKE_sound_sync_scene(scene);
2818                                                 if (isfinite(time)) {
2819                                                         int ncfra = time * (float)FPS + 0.5f;
2820                                                         if (ncfra != scene->r.cfra) {
2821                                                                 scene->r.cfra = ncfra;
2822                                                                 Depsgraph *depsgraph = CTX_data_depsgraph(C);
2823                                                                 ED_update_for_newframe(CTX_data_main(C), depsgraph);
2824                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2825                                                         }
2826                                                 }