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