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