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