d517fb280d1604bb1e9b34961cc0c427aa4ad560
[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  * Use so we can check if 'wmEvent.type' is released in modal operators.
1615  *
1616  * An alternative would be to add a 'wmEvent.type_nokeymap'... or similar.
1617  */
1618 int WM_userdef_event_type_from_keymap_type(int kmitype)
1619 {
1620         switch (kmitype) {
1621                 case SELECTMOUSE:
1622                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1623                 case ACTIONMOUSE:
1624                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1625                 case EVT_TWEAK_S:
1626                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1627                 case EVT_TWEAK_A:
1628                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1629                 case EVT_TWEAK_L:
1630                         return LEFTMOUSE;
1631                 case EVT_TWEAK_M:
1632                         return MIDDLEMOUSE;
1633                 case EVT_TWEAK_R:
1634                         return RIGHTMOUSE;
1635                 case WHEELOUTMOUSE:
1636                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELUPMOUSE : WHEELDOWNMOUSE;
1637                 case WHEELINMOUSE:
1638                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELDOWNMOUSE : WHEELUPMOUSE;
1639         }
1640
1641         return kmitype;
1642 }
1643
1644 static int wm_eventmatch(const wmEvent *winevent, wmKeyMapItem *kmi)
1645 {
1646         int kmitype = WM_userdef_event_map(kmi->type);
1647
1648         if (kmi->flag & KMI_INACTIVE) return 0;
1649
1650         /* the matching rules */
1651         if (kmitype == KM_TEXTINPUT)
1652                 if (winevent->val == KM_PRESS) {  /* prevent double clicks */
1653                         /* NOT using ISTEXTINPUT anymore because (at least on Windows) some key codes above 255
1654                          * could have printable ascii keys - BUG [#30479] */
1655                         if (ISKEYBOARD(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1;
1656                 }
1657
1658         if (kmitype != KM_ANY) {
1659                 if (ELEM(kmitype, TABLET_STYLUS, TABLET_ERASER)) {
1660                         const wmTabletData *wmtab = winevent->tablet_data;
1661
1662                         if (wmtab == NULL)
1663                                 return 0;
1664                         else if (winevent->type != LEFTMOUSE) /* tablet events can occur on hover + keypress */
1665                                 return 0;
1666                         else if ((kmitype == TABLET_STYLUS) && (wmtab->Active != EVT_TABLET_STYLUS))
1667                                 return 0;
1668                         else if ((kmitype == TABLET_ERASER) && (wmtab->Active != EVT_TABLET_ERASER))
1669                                 return 0;
1670                 }
1671                 else {
1672                         if (winevent->type != kmitype)
1673                                 return 0;
1674                 }
1675         }
1676
1677         if (kmi->val != KM_ANY)
1678                 if (winevent->val != kmi->val) return 0;
1679
1680         /* modifiers also check bits, so it allows modifier order */
1681         if (kmi->shift != KM_ANY)
1682                 if (winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1683         if (kmi->ctrl != KM_ANY)
1684                 if (winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1685         if (kmi->alt != KM_ANY)
1686                 if (winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1687         if (kmi->oskey != KM_ANY)
1688                 if (winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1689
1690         /* only keymap entry with keymodifier is checked, means all keys without modifier get handled too. */
1691         /* that is currently needed to make overlapping events work (when you press A - G fast or so). */
1692         if (kmi->keymodifier)
1693                 if (winevent->keymodifier != kmi->keymodifier) return 0;
1694
1695         return 1;
1696 }
1697
1698
1699 /* operator exists */
1700 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event, bool *dbl_click_disabled)
1701 {
1702         /* support for modal keymap in macros */
1703         if (op->opm)
1704                 op = op->opm;
1705
1706         if (op->type->modalkeymap) {
1707                 wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1708                 wmKeyMapItem *kmi;
1709
1710                 for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1711                         if (wm_eventmatch(event, kmi)) {
1712
1713                                 event->prevtype = event->type;
1714                                 event->prevval = event->val;
1715                                 event->type = EVT_MODAL_MAP;
1716                                 event->val = kmi->propvalue;
1717
1718                                 break;
1719                         }
1720                 }
1721         }
1722         else {
1723                 /* modal keymap checking returns handled events fine, but all hardcoded modal
1724                  * handling typically swallows all events (OPERATOR_RUNNING_MODAL).
1725                  * This bypass just disables support for double clicks in hardcoded modal handlers */
1726                 if (event->val == KM_DBL_CLICK) {
1727                         event->val = KM_PRESS;
1728                         *dbl_click_disabled = true;
1729                 }
1730         }
1731 }
1732
1733 /**
1734  * Check whether operator is allowed to run in case interface is locked,
1735  * If interface is unlocked, will always return truth.
1736  */
1737 static bool wm_operator_check_locked_interface(bContext *C, wmOperatorType *ot)
1738 {
1739         wmWindowManager *wm = CTX_wm_manager(C);
1740
1741         if (wm->is_interface_locked) {
1742                 if ((ot->flag & OPTYPE_LOCK_BYPASS) == 0) {
1743                         return false;
1744                 }
1745         }
1746
1747         return true;
1748 }
1749
1750 /* bad hacking event system... better restore event type for checking of KM_CLICK for example */
1751 /* XXX modal maps could use different method (ton) */
1752 static void wm_event_modalmap_end(wmEvent *event, bool dbl_click_disabled)
1753 {
1754         if (event->type == EVT_MODAL_MAP) {
1755                 event->type = event->prevtype;
1756                 event->prevtype = 0;
1757                 event->val = event->prevval;
1758                 event->prevval = 0;
1759         }
1760         else if (dbl_click_disabled)
1761                 event->val = KM_DBL_CLICK;
1762
1763 }
1764
1765 /* Warning: this function removes a modal handler, when finished */
1766 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1767                                     wmEvent *event, PointerRNA *properties)
1768 {
1769         int retval = OPERATOR_PASS_THROUGH;
1770
1771         /* derived, modal or blocking operator */
1772         if (handler->op) {
1773                 wmOperator *op = handler->op;
1774                 wmOperatorType *ot = op->type;
1775
1776                 if (!wm_operator_check_locked_interface(C, ot)) {
1777                         /* Interface is locked and operator is not allowed to run,
1778                          * nothing to do in this case.
1779                          */
1780                 }
1781                 else if (ot->modal) {
1782                         /* we set context to where modal handler came from */
1783                         wmWindowManager *wm = CTX_wm_manager(C);
1784                         ScrArea *area = CTX_wm_area(C);
1785                         ARegion *region = CTX_wm_region(C);
1786                         bool dbl_click_disabled = false;
1787
1788                         wm_handler_op_context(C, handler, event);
1789                         wm_region_mouse_co(C, event);
1790                         wm_event_modalkeymap(C, op, event, &dbl_click_disabled);
1791
1792                         if (ot->flag & OPTYPE_UNDO)
1793                                 wm->op_undo_depth++;
1794
1795                         /* warning, after this call all context data and 'event' may be freed. see check below */
1796                         retval = ot->modal(C, op, event);
1797                         OPERATOR_RETVAL_CHECK(retval);
1798
1799                         /* when this is _not_ the case the modal modifier may have loaded
1800                          * a new blend file (demo mode does this), so we have to assume
1801                          * the event, operator etc have all been freed. - campbell */
1802                         if (CTX_wm_manager(C) == wm) {
1803
1804                                 wm_event_modalmap_end(event, dbl_click_disabled);
1805
1806                                 if (ot->flag & OPTYPE_UNDO)
1807                                         wm->op_undo_depth--;
1808
1809                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1810                                         wm_operator_reports(C, op, retval, false);
1811                                 }
1812                                 else {
1813                                         /* not very common, but modal operators may report before finishing */
1814                                         if (!BLI_listbase_is_empty(&op->reports->list)) {
1815                                                 wm_add_reports(op->reports);
1816                                         }
1817                                 }
1818
1819                                 /* important to run 'wm_operator_finished' before NULLing the context members */
1820                                 if (retval & OPERATOR_FINISHED) {
1821                                         wm_operator_finished(C, op, false, true);
1822                                         handler->op = NULL;
1823                                 }
1824                                 else if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1825                                         WM_operator_free(op);
1826                                         handler->op = NULL;
1827                                 }
1828
1829                                 /* putting back screen context, reval can pass trough after modal failures! */
1830                                 if ((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1831                                         CTX_wm_area_set(C, area);
1832                                         CTX_wm_region_set(C, region);
1833                                 }
1834                                 else {
1835                                         /* this special cases is for areas and regions that get removed */
1836                                         CTX_wm_area_set(C, NULL);
1837                                         CTX_wm_region_set(C, NULL);
1838                                 }
1839
1840                                 /* remove modal handler, operator itself should have been canceled and freed */
1841                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1842                                         WM_cursor_grab_disable(CTX_wm_window(C), NULL);
1843
1844                                         BLI_remlink(handlers, handler);
1845                                         wm_event_free_handler(handler);
1846
1847                                         /* prevent silly errors from operator users */
1848                                         //retval &= ~OPERATOR_PASS_THROUGH;
1849                                 }
1850                         }
1851                 }
1852                 else {
1853                         CLOG_ERROR(WM_LOG_HANDLERS, "missing modal '%s'", op->idname);
1854                 }
1855         }
1856         else {
1857                 wmOperatorType *ot = WM_operatortype_find(event->keymap_idname, 0);
1858
1859                 if (ot) {
1860                         if (wm_operator_check_locked_interface(C, ot)) {
1861                                 retval = wm_operator_invoke(C, ot, event, properties, NULL, false);
1862                         }
1863                 }
1864         }
1865         /* Finished and pass through flag as handled */
1866
1867         /* Finished and pass through flag as handled */
1868         if (retval == (OPERATOR_FINISHED | OPERATOR_PASS_THROUGH))
1869                 return WM_HANDLER_HANDLED;
1870
1871         /* Modal unhandled, break */
1872         if (retval == (OPERATOR_PASS_THROUGH | OPERATOR_RUNNING_MODAL))
1873                 return (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
1874
1875         if (retval & OPERATOR_PASS_THROUGH)
1876                 return WM_HANDLER_CONTINUE;
1877
1878         return WM_HANDLER_BREAK;
1879 }
1880
1881 /* fileselect handlers are only in the window queue, so it's safe to switch screens or area types */
1882 static int wm_handler_fileselect_do(bContext *C, ListBase *handlers, wmEventHandler *handler, int val)
1883 {
1884         wmWindowManager *wm = CTX_wm_manager(C);
1885         SpaceFile *sfile;
1886         int action = WM_HANDLER_CONTINUE;
1887
1888         switch (val) {
1889                 case EVT_FILESELECT_FULL_OPEN:
1890                 {
1891                         ScrArea *sa;
1892
1893                         /* sa can be null when window A is active, but mouse is over window B */
1894                         /* in this case, open file select in original window A */
1895                         if (handler->op_area == NULL) {
1896                                 bScreen *screen = CTX_wm_screen(C);
1897                                 sa = (ScrArea *)screen->areabase.first;
1898                         }
1899                         else {
1900                                 sa = handler->op_area;
1901                         }
1902
1903                         if (sa->full) {
1904                                 /* ensure the first area becomes the file browser, because the second one is the small
1905                                  * top (info-)area which might be too small (in fullscreens we have max two areas) */
1906                                 if (sa->prev) {
1907                                         sa = sa->prev;
1908                                 }
1909                                 ED_area_newspace(C, sa, SPACE_FILE, true);     /* 'sa' is modified in-place */
1910                                 /* we already had a fullscreen here -> mark new space as a stacked fullscreen */
1911                                 sa->flag |= (AREA_FLAG_STACKED_FULLSCREEN | AREA_FLAG_TEMP_TYPE);
1912                         }
1913                         else if (sa->spacetype == SPACE_FILE) {
1914                                 sa = ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENMAXIMIZED);
1915                         }
1916                         else {
1917                                 sa = ED_screen_full_newspace(C, sa, SPACE_FILE);    /* sets context */
1918                         }
1919
1920                         /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
1921                          * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
1922                         /* sa = CTX_wm_area(C); */
1923
1924                         /* settings for filebrowser, sfile is not operator owner but sends events */
1925                         sfile = (SpaceFile *)sa->spacedata.first;
1926                         sfile->op = handler->op;
1927
1928                         ED_fileselect_set_params(sfile);
1929
1930                         action = WM_HANDLER_BREAK;
1931                         break;
1932                 }
1933
1934                 case EVT_FILESELECT_EXEC:
1935                 case EVT_FILESELECT_CANCEL:
1936                 case EVT_FILESELECT_EXTERNAL_CANCEL:
1937                 {
1938                         /* remlink now, for load file case before removing*/
1939                         BLI_remlink(handlers, handler);
1940
1941                         if (val != EVT_FILESELECT_EXTERNAL_CANCEL) {
1942                                 ScrArea *sa = CTX_wm_area(C);
1943
1944                                 if (sa->full) {
1945                                         ED_screen_full_prevspace(C, sa);
1946                                 }
1947                                 /* user may have left fullscreen */
1948                                 else {
1949                                         ED_area_prevspace(C, sa);
1950                                 }
1951                         }
1952
1953                         wm_handler_op_context(C, handler, CTX_wm_window(C)->eventstate);
1954
1955                         /* needed for UI_popup_menu_reports */
1956
1957                         if (val == EVT_FILESELECT_EXEC) {
1958                                 int retval;
1959
1960                                 if (handler->op->type->flag & OPTYPE_UNDO)
1961                                         wm->op_undo_depth++;
1962
1963                                 retval = handler->op->type->exec(C, handler->op);
1964
1965                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1966                                 if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1967                                         wm->op_undo_depth--;
1968
1969                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1970                                 if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0) {
1971                                         if (handler->op->type->flag & OPTYPE_UNDO)
1972                                                 ED_undo_push_op(C, handler->op);
1973                                         else if (handler->op->type->flag & OPTYPE_UNDO_GROUPED)
1974                                                 ED_undo_grouped_push_op(C, handler->op);
1975                                 }
1976
1977                                 if (handler->op->reports->list.first) {
1978
1979                                         /* FIXME, temp setting window, this is really bad!
1980                                          * only have because lib linking errors need to be seen by users :(
1981                                          * it can be removed without breaking anything but then no linking errors - campbell */
1982                                         wmWindow *win_prev = CTX_wm_window(C);
1983                                         ScrArea *area_prev = CTX_wm_area(C);
1984                                         ARegion *ar_prev = CTX_wm_region(C);
1985
1986                                         if (win_prev == NULL)
1987                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
1988
1989                                         BKE_report_print_level_set(handler->op->reports, RPT_WARNING);
1990                                         UI_popup_menu_reports(C, handler->op->reports);
1991
1992                                         /* XXX - copied from 'wm_operator_finished()' */
1993                                         /* add reports to the global list, otherwise they are not seen */
1994                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
1995
1996                                         /* more hacks, since we meddle with reports, banner display doesn't happen automatic */
1997                                         WM_report_banner_show();
1998
1999                                         CTX_wm_window_set(C, win_prev);
2000                                         CTX_wm_area_set(C, area_prev);
2001                                         CTX_wm_region_set(C, ar_prev);
2002                                 }
2003
2004                                 /* for WM_operator_pystring only, custom report handling is done above */
2005                                 wm_operator_reports(C, handler->op, retval, true);
2006
2007                                 if (retval & OPERATOR_FINISHED) {
2008                                         WM_operator_last_properties_store(handler->op);
2009                                 }
2010
2011                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
2012                                         WM_operator_free(handler->op);
2013                                 }
2014                         }
2015                         else {
2016                                 if (handler->op->type->cancel) {
2017                                         if (handler->op->type->flag & OPTYPE_UNDO)
2018                                                 wm->op_undo_depth++;
2019
2020                                         handler->op->type->cancel(C, handler->op);
2021
2022                                         if (handler->op->type->flag & OPTYPE_UNDO)
2023                                                 wm->op_undo_depth--;
2024                                 }
2025
2026                                 WM_operator_free(handler->op);
2027                         }
2028
2029                         CTX_wm_area_set(C, NULL);
2030
2031                         wm_event_free_handler(handler);
2032
2033                         action = WM_HANDLER_BREAK;
2034                         break;
2035                 }
2036         }
2037
2038         return action;
2039 }
2040
2041 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, const wmEvent *event)
2042 {
2043         int action = WM_HANDLER_CONTINUE;
2044
2045         if (event->type != EVT_FILESELECT)
2046                 return action;
2047         if (handler->op != (wmOperator *)event->customdata)
2048                 return action;
2049
2050         return wm_handler_fileselect_do(C, handlers, handler, event->val);
2051 }
2052
2053 static bool handler_boundbox_test(wmEventHandler *handler, const wmEvent *event)
2054 {
2055         if (handler->bbwin) {
2056                 if (handler->bblocal) {
2057                         rcti rect = *handler->bblocal;
2058                         BLI_rcti_translate(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
2059
2060                         if (BLI_rcti_isect_pt_v(&rect, &event->x))
2061                                 return 1;
2062                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(&rect, &event->prevx))
2063                                 return 1;
2064                         else
2065                                 return 0;
2066                 }
2067                 else {
2068                         if (BLI_rcti_isect_pt_v(handler->bbwin, &event->x))
2069                                 return 1;
2070                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(handler->bbwin, &event->prevx))
2071                                 return 1;
2072                         else
2073                                 return 0;
2074                 }
2075         }
2076         return 1;
2077 }
2078
2079 static int wm_action_not_handled(int action)
2080 {
2081         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
2082 }
2083
2084 static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers)
2085 {
2086         const bool do_debug_handler = (G.debug & G_DEBUG_HANDLERS) &&
2087                 /* comment this out to flood the console! (if you really want to test) */
2088                 !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
2089                 ;
2090 # define PRINT if (do_debug_handler) printf
2091
2092         wmWindowManager *wm = CTX_wm_manager(C);
2093         wmEventHandler *handler, *nexthandler;
2094         int action = WM_HANDLER_CONTINUE;
2095         int always_pass;
2096
2097         if (handlers == NULL) {
2098                 return action;
2099         }
2100
2101         /* modal handlers can get removed in this loop, we keep the loop this way
2102          *
2103          * note: check 'handlers->first' because in rare cases the handlers can be cleared
2104          * by the event thats called, for eg:
2105          *
2106          * Calling a python script which changes the area.type, see [#32232] */
2107         for (handler = handlers->first; handler && handlers->first; handler = nexthandler) {
2108
2109                 nexthandler = handler->next;
2110
2111                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
2112                 if (handler->flag & WM_HANDLER_DO_FREE) {
2113                         /* pass */
2114                 }
2115                 else if (handler_boundbox_test(handler, event)) { /* optional boundbox */
2116                         /* in advance to avoid access to freed event on window close */
2117                         always_pass = wm_event_always_pass(event);
2118
2119                         /* modal+blocking handler */
2120                         if (handler->flag & WM_HANDLER_BLOCKING)
2121                                 action |= WM_HANDLER_BREAK;
2122
2123                         if (handler->keymap) {
2124                                 wmKeyMap *keymap = WM_keymap_active(wm, handler->keymap);
2125                                 wmKeyMapItem *kmi;
2126
2127                                 PRINT("%s:   checking '%s' ...", __func__, keymap->idname);
2128
2129                                 if (WM_keymap_poll(C, keymap)) {
2130
2131                                         PRINT("pass\n");
2132
2133                                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
2134                                                 if (wm_eventmatch(event, kmi)) {
2135
2136                                                         PRINT("%s:     item matched '%s'\n", __func__, kmi->idname);
2137
2138                                                         /* weak, but allows interactive callback to not use rawkey */
2139                                                         event->keymap_idname = kmi->idname;
2140
2141                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
2142                                                         if (action & WM_HANDLER_BREAK) {
2143                                                                 /* not always_pass here, it denotes removed handler */
2144                                                                 CLOG_INFO(WM_LOG_HANDLERS, 2, "handled! '%s'", kmi->idname);
2145                                                                 break;
2146                                                         }
2147                                                         else {
2148                                                                 if (action & WM_HANDLER_HANDLED) {
2149                                                                         CLOG_INFO(WM_LOG_HANDLERS, 2, "handled - and pass on! '%s'", kmi->idname);
2150                                                                 }
2151                                                                 else {
2152                                                                         CLOG_INFO(WM_LOG_HANDLERS, 2, "un-handled '%s'", kmi->idname);
2153                                                                 }
2154                                                         }
2155                                                 }
2156                                         }
2157                                 }
2158                                 else {
2159                                         PRINT("fail\n");
2160                                 }
2161                         }
2162                         else if (handler->ui_handle) {
2163                                 if (!wm->is_interface_locked) {
2164                                         action |= wm_handler_ui_call(C, handler, event, always_pass);
2165                                 }
2166                         }
2167                         else if (handler->type == WM_HANDLER_FILESELECT) {
2168                                 if (!wm->is_interface_locked) {
2169                                         /* screen context changes here */
2170                                         action |= wm_handler_fileselect_call(C, handlers, handler, event);
2171                                 }
2172                         }
2173                         else if (handler->dropboxes) {
2174                                 if (!wm->is_interface_locked && event->type == EVT_DROP) {
2175                                         wmDropBox *drop = handler->dropboxes->first;
2176                                         for (; drop; drop = drop->next) {
2177                                                 /* other drop custom types allowed */
2178                                                 if (event->custom == EVT_DATA_DRAGDROP) {
2179                                                         ListBase *lb = (ListBase *)event->customdata;
2180                                                         wmDrag *drag;
2181
2182                                                         for (drag = lb->first; drag; drag = drag->next) {
2183                                                                 if (drop->poll(C, drag, event)) {
2184                                                                         drop->copy(drag, drop);
2185
2186                                                                         /* free the drags before calling operator */
2187                                                                         WM_drag_free_list(lb);
2188
2189                                                                         event->customdata = NULL;
2190                                                                         event->custom = 0;
2191
2192                                                                         WM_operator_name_call_ptr(C, drop->ot, drop->opcontext, drop->ptr);
2193                                                                         action |= WM_HANDLER_BREAK;
2194
2195                                                                         /* XXX fileread case */
2196                                                                         if (CTX_wm_window(C) == NULL)
2197                                                                                 return action;
2198
2199                                                                         /* escape from drag loop, got freed */
2200                                                                         break;
2201                                                                 }
2202                                                         }
2203                                                 }
2204                                         }
2205                                 }
2206                         }
2207                         else {
2208                                 /* modal, swallows all */
2209                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
2210                         }
2211
2212                         if (action & WM_HANDLER_BREAK) {
2213                                 if (always_pass)
2214                                         action &= ~WM_HANDLER_BREAK;
2215                                 else
2216                                         break;
2217                         }
2218                 }
2219
2220                 /* XXX fileread case, if the wm is freed then the handler's
2221                  * will have been too so the code below need not run. */
2222                 if (CTX_wm_window(C) == NULL) {
2223                         return action;
2224                 }
2225
2226                 /* XXX code this for all modal ops, and ensure free only happens here */
2227
2228                 /* modal ui handler can be tagged to be freed */
2229                 if (BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
2230                         if (handler->flag & WM_HANDLER_DO_FREE) {
2231                                 BLI_remlink(handlers, handler);
2232                                 wm_event_free_handler(handler);
2233                         }
2234                 }
2235         }
2236
2237         if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
2238                 wm_cursor_arrow_move(CTX_wm_window(C), event);
2239
2240 #undef PRINT
2241
2242         return action;
2243 }
2244
2245 /* this calls handlers twice - to solve (double-)click events */
2246 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
2247 {
2248         int action = wm_handlers_do_intern(C, event, handlers);
2249
2250         /* fileread case */
2251         if (CTX_wm_window(C) == NULL)
2252                 return action;
2253
2254         if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2255                 if (event->check_drag) {
2256                         wmWindow *win = CTX_wm_window(C);
2257                         if ((abs(event->x - win->eventstate->prevclickx)) >= U.tweak_threshold ||
2258                             (abs(event->y - win->eventstate->prevclicky)) >= U.tweak_threshold)
2259                         {
2260                                 short val = event->val;
2261                                 short type = event->type;
2262                                 event->val = KM_CLICK_DRAG;
2263                                 event->type = win->eventstate->type;
2264
2265                                 CLOG_INFO(WM_LOG_HANDLERS, 1, "handling PRESS_DRAG");
2266
2267                                 action |= wm_handlers_do_intern(C, event, handlers);
2268
2269                                 event->val = val;
2270                                 event->type = type;
2271
2272                                 win->eventstate->check_click = 0;
2273                                 win->eventstate->check_drag = 0;
2274                         }
2275                 }
2276         }
2277         else if (ISMOUSE(event->type) || ISKEYBOARD(event->type)) {
2278                 /* All events that don't set wmEvent.prevtype must be ignored. */
2279
2280                 /* test for CLICK events */
2281                 if (wm_action_not_handled(action)) {
2282                         wmWindow *win = CTX_wm_window(C);
2283
2284                         /* eventstate stores if previous event was a KM_PRESS, in case that
2285                          * wasn't handled, the KM_RELEASE will become a KM_CLICK */
2286
2287                         if (win != NULL) {
2288                                 if (event->val == KM_PRESS) {
2289                                         win->eventstate->check_click = true;
2290                                         win->eventstate->check_drag = true;
2291                                 }
2292                                 else if (event->val == KM_RELEASE) {
2293                                         win->eventstate->check_drag = false;
2294                                 }
2295                         }
2296
2297                         if (win && win->eventstate->prevtype == event->type) {
2298
2299                                 if ((event->val == KM_RELEASE) &&
2300                                     (win->eventstate->prevval == KM_PRESS) &&
2301                                     (win->eventstate->check_click == true))
2302                                 {
2303                                         if ((abs(event->x - win->eventstate->prevclickx)) <= WM_EVENT_CLICK_WIGGLE_ROOM &&
2304                                             (abs(event->y - win->eventstate->prevclicky)) <= WM_EVENT_CLICK_WIGGLE_ROOM)
2305                                         {
2306                                                 event->val = KM_CLICK;
2307
2308                                                 CLOG_INFO(WM_LOG_HANDLERS, 1, "handling CLICK");
2309
2310                                                 action |= wm_handlers_do_intern(C, event, handlers);
2311
2312                                                 event->val = KM_RELEASE;
2313                                         }
2314                                         else {
2315                                                 win->eventstate->check_click = 0;
2316                                                 win->eventstate->check_drag = 0;
2317                                         }
2318                                 }
2319                                 else if (event->val == KM_DBL_CLICK) {
2320                                         event->val = KM_PRESS;
2321                                         action |= wm_handlers_do_intern(C, event, handlers);
2322
2323                                         /* revert value if not handled */
2324                                         if (wm_action_not_handled(action)) {
2325                                                 event->val = KM_DBL_CLICK;
2326                                         }
2327                                 }
2328                         }
2329                 }
2330                 else {
2331                         wmWindow *win = CTX_wm_window(C);
2332
2333                         if (win)
2334                                 win->eventstate->check_click = 0;
2335                 }
2336         }
2337
2338         return action;
2339 }
2340
2341 static int wm_event_inside_i(wmEvent *event, rcti *rect)
2342 {
2343         if (wm_event_always_pass(event))
2344                 return 1;
2345         if (BLI_rcti_isect_pt_v(rect, &event->x))
2346                 return 1;
2347         return 0;
2348 }
2349
2350 static ScrArea *area_event_inside(bContext *C, const int xy[2])
2351 {
2352         bScreen *screen = CTX_wm_screen(C);
2353         ScrArea *sa;
2354
2355         if (screen)
2356                 for (sa = screen->areabase.first; sa; sa = sa->next)
2357                         if (BLI_rcti_isect_pt_v(&sa->totrct, xy))
2358                                 return sa;
2359         return NULL;
2360 }
2361
2362 static ARegion *region_event_inside(bContext *C, const int xy[2])
2363 {
2364         bScreen *screen = CTX_wm_screen(C);
2365         ScrArea *area = CTX_wm_area(C);
2366         ARegion *ar;
2367
2368         if (screen && area)
2369                 for (ar = area->regionbase.first; ar; ar = ar->next)
2370                         if (BLI_rcti_isect_pt_v(&ar->winrct, xy))
2371                                 return ar;
2372         return NULL;
2373 }
2374
2375 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
2376 {
2377         if (ar) {
2378                 for (; pc; pc = pc->next) {
2379                         if (pc->poll == NULL || pc->poll(C)) {
2380                                 wmWindow *win = CTX_wm_window(C);
2381                                 WM_paint_cursor_tag_redraw(win, ar);
2382                         }
2383                 }
2384         }
2385 }
2386
2387 /* called on mousemove, check updates for paintcursors */
2388 /* context was set on active area and region */
2389 static void wm_paintcursor_test(bContext *C, const wmEvent *event)
2390 {
2391         wmWindowManager *wm = CTX_wm_manager(C);
2392
2393         if (wm->paintcursors.first) {
2394                 ARegion *ar = CTX_wm_region(C);
2395
2396                 if (ar)
2397                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
2398
2399                 /* if previous position was not in current region, we have to set a temp new context */
2400                 if (ar == NULL || !BLI_rcti_isect_pt_v(&ar->winrct, &event->prevx)) {
2401                         ScrArea *sa = CTX_wm_area(C);
2402
2403                         CTX_wm_area_set(C, area_event_inside(C, &event->prevx));
2404                         CTX_wm_region_set(C, region_event_inside(C, &event->prevx));
2405
2406                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
2407
2408                         CTX_wm_area_set(C, sa);
2409                         CTX_wm_region_set(C, ar);
2410                 }
2411         }
2412 }
2413
2414 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
2415 {
2416         if (BLI_listbase_is_empty(&wm->drags)) {
2417                 return;
2418         }
2419
2420         if (event->type == MOUSEMOVE || ISKEYMODIFIER(event->type)) {
2421                 win->screen->do_draw_drag = true;
2422         }
2423         else if (event->type == ESCKEY) {
2424                 WM_drag_free_list(&wm->drags);
2425
2426                 win->screen->do_draw_drag = true;
2427         }
2428         else if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2429                 event->type = EVT_DROP;
2430
2431                 /* create customdata, first free existing */
2432                 if (event->customdata) {
2433                         if (event->customdatafree)
2434                                 MEM_freeN(event->customdata);
2435                 }
2436
2437                 event->custom = EVT_DATA_DRAGDROP;
2438                 event->customdata = &wm->drags;
2439                 event->customdatafree = 1;
2440
2441                 /* clear drop icon */
2442                 win->screen->do_draw_drag = true;
2443
2444                 /* restore cursor (disabled, see wm_dragdrop.c) */
2445                 // WM_cursor_modal_restore(win);
2446         }
2447
2448         /* overlap fails otherwise */
2449         if (win->screen->do_draw_drag)
2450                 if (win->drawmethod == USER_DRAW_OVERLAP)
2451                         win->screen->do_draw = true;
2452
2453 }
2454
2455 /* filter out all events of the pie that spawned the last pie unless it's a release event */
2456 static bool wm_event_pie_filter(wmWindow *win, const wmEvent *event)
2457 {
2458         if (win->lock_pie_event && win->lock_pie_event == event->type) {
2459                 if (event->val == KM_RELEASE) {
2460                         win->lock_pie_event = EVENT_NONE;
2461                         return false;
2462                 }
2463                 else {
2464                         return true;
2465                 }
2466         }
2467         else {
2468                 return false;
2469         }
2470 }
2471
2472 /* called in main loop */
2473 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
2474 void wm_event_do_handlers(bContext *C)
2475 {
2476         wmWindowManager *wm = CTX_wm_manager(C);
2477         wmWindow *win;
2478
2479         /* update key configuration before handling events */
2480         WM_keyconfig_update(wm);
2481
2482         for (win = wm->windows.first; win; win = win->next) {
2483                 wmEvent *event;
2484
2485                 if (win->screen == NULL)
2486                         wm_event_free_all(win);
2487                 else {
2488                         Scene *scene = win->screen->scene;
2489
2490                         if (scene) {
2491                                 int is_playing_sound = BKE_sound_scene_playing(win->screen->scene);
2492
2493                                 if (is_playing_sound != -1) {
2494                                         bool is_playing_screen;
2495                                         CTX_wm_window_set(C, win);
2496                                         CTX_wm_screen_set(C, win->screen);
2497                                         CTX_data_scene_set(C, scene);
2498
2499                                         is_playing_screen = (ED_screen_animation_playing(wm) != NULL);
2500
2501                                         if (((is_playing_sound == 1) && (is_playing_screen == 0)) ||
2502                                             ((is_playing_sound == 0) && (is_playing_screen == 1)))
2503                                         {
2504                                                 ED_screen_animation_play(C, -1, 1);
2505                                         }
2506
2507                                         if (is_playing_sound == 0) {
2508                                                 const float time = BKE_sound_sync_scene(scene);
2509                                                 if (isfinite(time)) {
2510                                                         int ncfra = time * (float)FPS + 0.5f;
2511                                                         if (ncfra != scene->r.cfra) {
2512                                                                 scene->r.cfra = ncfra;
2513                                                                 ED_update_for_newframe(CTX_data_main(C), scene, 1);
2514                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2515                                                         }
2516                                                 }
2517                                         }
2518
2519                                         CTX_data_scene_set(C, NULL);
2520                                         CTX_wm_screen_set(C, NULL);
2521                                         CTX_wm_window_set(C, NULL);
2522                                 }
2523                         }
2524                 }
2525
2526                 while ( (event = win->queue.first) ) {
2527                         int action = WM_HANDLER_CONTINUE;
2528
2529                         if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2530                                 printf("\n%s: Handling event\n", __func__);
2531
2532                                 WM_event_print(event);
2533                         }
2534
2535                         /* take care of pie event filter */
2536                         if (wm_event_pie_filter(win, event)) {
2537                                 if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2538                                         CLOG_INFO(WM_LOG_HANDLERS, 1, "event filtered due to pie button pressed");
2539                                 }
2540                                 BLI_remlink(&win->queue, event);
2541                                 wm_event_free(event);
2542                                 continue;
2543                         }
2544
2545                         CTX_wm_window_set(C, win);
2546
2547                         /* Clear tool-tip on mouse move. */
2548                         if (win->screen->tool_tip && win->screen->tool_tip->exit_on_event) {
2549                                 if (ISMOUSE(event->type)) {
2550                                         WM_tooltip_clear(C, win);
2551                                 }
2552                         }
2553
2554                         /* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
2555                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2556                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2557
2558                         /* MVC demands to not draw in event handlers... but we need to leave it for ogl selecting etc */
2559                         wm_window_make_drawable(wm, win);
2560
2561                         wm_region_mouse_co(C, event);
2562
2563
2564                         /* first we do priority handlers, modal + some limited keymaps */
2565                         action |= wm_handlers_do(C, event, &win->modalhandlers);
2566
2567                         /* fileread case */
2568                         if (CTX_wm_window(C) == NULL)
2569                                 return;
2570
2571                         /* check for a tooltip */
2572                         {
2573                                 bScreen *screen = CTX_wm_window(C)->screen;
2574                                 if (screen->tool_tip && screen->tool_tip->timer) {
2575                                         if ((event->type == TIMER) && (event->customdata == screen->tool_tip->timer)) {
2576                                                 WM_tooltip_init(C, win);
2577                                         }
2578                                 }
2579                         }
2580
2581                         /* check dragging, creates new event or frees, adds draw tag */
2582                         wm_event_drag_test(wm, win, event);
2583
2584                         /* builtin tweak, if action is break it removes tweak */
2585                         wm_tweakevent_test(C, event, action);
2586
2587                         if ((action & WM_HANDLER_BREAK) == 0) {
2588                                 ScrArea *sa;
2589                                 ARegion *ar;
2590
2591                                 /* Note: setting subwin active should be done here, after modal handlers have been done */
2592                                 if (event->type == MOUSEMOVE) {
2593                                         /* state variables in screen, cursors. Also used in wm_draw.c, fails for modal handlers though */
2594                                         ED_screen_set_subwinactive(C, event);
2595                                         /* for regions having custom cursors */
2596                                         wm_paintcursor_test(C, event);
2597                                 }
2598 #ifdef WITH_INPUT_NDOF
2599                                 else if (event->type == NDOF_MOTION) {
2600                                         win->addmousemove = true;
2601                                 }
2602 #endif
2603
2604                                 for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2605                                         /* after restoring a screen from SCREENMAXIMIZED we have to wait
2606                                          * with the screen handling till the region coordinates are updated */
2607                                         if (win->screen->skip_handling == true) {
2608                                                 /* restore for the next iteration of wm_event_do_handlers */
2609                                                 win->screen->skip_handling = false;
2610                                                 break;
2611                                         }
2612
2613                                         /* update azones if needed - done here because it needs to be independent from redraws */
2614                                         if (sa->flag & AREA_FLAG_ACTIONZONES_UPDATE) {
2615                                                 ED_area_azones_update(sa, &event->x);
2616                                         }
2617
2618                                         if (wm_event_inside_i(event, &sa->totrct)) {
2619                                                 CTX_wm_area_set(C, sa);
2620
2621                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2622                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2623                                                                 if (wm_event_inside_i(event, &ar->winrct)) {
2624                                                                         CTX_wm_region_set(C, ar);
2625
2626                                                                         /* call even on non mouse events, since the */
2627                                                                         wm_region_mouse_co(C, event);
2628
2629                                                                         if (!BLI_listbase_is_empty(&wm->drags)) {
2630                                                                                 /* does polls for drop regions and checks uibuts */
2631                                                                                 /* need to be here to make sure region context is true */
2632                                                                                 if (ELEM(event->type, MOUSEMOVE, EVT_DROP) || ISKEYMODIFIER(event->type)) {
2633                                                                                         wm_drags_check_ops(C, event);
2634                                                                                 }
2635                                                                         }
2636
2637                                                                         action |= wm_handlers_do(C, event, &ar->handlers);
2638
2639                                                                         /* fileread case (python), [#29489] */
2640                                                                         if (CTX_wm_window(C) == NULL)
2641                                                                                 return;
2642
2643                                                                         if (action & WM_HANDLER_BREAK)
2644                                                                                 break;
2645                                                                 }
2646                                                         }
2647                                                 }
2648
2649                                                 CTX_wm_region_set(C, NULL);
2650
2651                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2652                                                         wm_region_mouse_co(C, event); /* only invalidates event->mval in this case */
2653                                                         action |= wm_handlers_do(C, event, &sa->handlers);
2654                                                 }
2655                                                 CTX_wm_area_set(C, NULL);
2656
2657                                                 /* NOTE: do not escape on WM_HANDLER_BREAK, mousemove needs handled for previous area */
2658                                         }
2659                                 }
2660
2661                                 if ((action & WM_HANDLER_BREAK) == 0) {
2662                                         /* also some non-modal handlers need active area/region */
2663                                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2664                                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2665
2666                                         wm_region_mouse_co(C, event);
2667
2668                                         action |= wm_handlers_do(C, event, &win->handlers);
2669
2670                                         /* fileread case */
2671                                         if (CTX_wm_window(C) == NULL)
2672                                                 return;
2673                                 }
2674
2675                         }
2676
2677                         /* update previous mouse position for following events to use */
2678                         win->eventstate->prevx = event->x;
2679                         win->eventstate->prevy = event->y;
2680
2681                         /* unlink and free here, blender-quit then frees all */
2682                         BLI_remlink(&win->queue, event);
2683                         wm_event_free(event);
2684
2685                 }
2686
2687                 /* only add mousemove when queue was read entirely */
2688                 if (win->addmousemove && win->eventstate) {
2689                         wmEvent tevent = *(win->eventstate);
2690                         // printf("adding MOUSEMOVE %d %d\n", tevent.x, tevent.y);
2691                         tevent.type = MOUSEMOVE;
2692                         tevent.prevx = tevent.x;
2693                         tevent.prevy = tevent.y;
2694                         wm_event_add(win, &tevent);
2695                         win->addmousemove = 0;
2696                 }
2697
2698                 CTX_wm_window_set(C, NULL);
2699         }
2700
2701         /* update key configuration after handling events */
2702         WM_keyconfig_update(wm);
2703
2704         GPU_ASSERT_NO_GL_ERRORS("wm_event_do_handlers");
2705 }
2706
2707 /* ********** filesector handling ************ */
2708
2709 void WM_event_fileselect_event(wmWindowManager *wm, void *ophandle, int eventval)
2710 {
2711         /* add to all windows! */
2712         wmWindow *win;
2713
2714         for (win = wm->windows.first; win; win = win->next) {
2715                 wmEvent event = *win->eventstate;
2716
2717                 event.type = EVT_FILESELECT;
2718                 event.val = eventval;
2719                 event.customdata = ophandle;     // only as void pointer type check
2720
2721                 wm_event_add(win, &event);
2722         }
2723 }
2724
2725 /* operator is supposed to have a filled "path" property */
2726 /* optional property: filetype (XXX enum?) */
2727
2728 /**
2729  * The idea here is to keep a handler alive on window queue, owning the operator.
2730  * The filewindow can send event to make it execute, thus ensuring
2731  * executing happens outside of lower level queues, with UI refreshed.
2732  * Should also allow multiwin solutions
2733  */
2734 void WM_event_add_fileselect(bContext *C, wmOperator *op)
2735 {
2736         wmEventHandler *handler, *handlernext;
2737         wmWindowManager *wm = CTX_wm_manager(C);
2738         wmWindow *win = CTX_wm_window(C);
2739
2740         /* only allow 1 file selector open per window */
2741         for (handler = win->modalhandlers.first; handler; handler = handlernext) {
2742                 handlernext = handler->next;
2743
2744                 if (handler->type == WM_HANDLER_FILESELECT) {
2745                         bScreen *screen = CTX_wm_screen(C);
2746                         ScrArea *sa;
2747
2748                         /* find the area with the file selector for this handler */
2749                         for (sa = screen->areabase.first; sa; sa = sa->next) {
2750                                 if (sa->spacetype == SPACE_FILE) {
2751                                         SpaceFile *sfile = sa->spacedata.first;
2752
2753                                         if (sfile->op == handler->op) {
2754                                                 CTX_wm_area_set(C, sa);
2755                                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_CANCEL);
2756                                                 break;
2757                                         }
2758                                 }
2759                         }
2760
2761                         /* if not found we stop the handler without changing the screen */
2762                         if (!sa)
2763                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_EXTERNAL_CANCEL);
2764                 }
2765         }
2766
2767         handler = MEM_callocN(sizeof(wmEventHandler), "fileselect handler");
2768
2769         handler->type = WM_HANDLER_FILESELECT;
2770         handler->op = op;
2771         handler->op_area = CTX_wm_area(C);
2772         handler->op_region = CTX_wm_region(C);
2773
2774         BLI_addhead(&win->modalhandlers, handler);
2775
2776         /* check props once before invoking if check is available
2777          * ensures initial properties are valid */
2778         if (op->type->check) {
2779                 op->type->check(C, op); /* ignore return value */
2780         }
2781
2782         WM_event_fileselect_event(wm, op, EVT_FILESELECT_FULL_OPEN);
2783 }
2784
2785 #if 0
2786 /* lets not expose struct outside wm? */
2787 static void WM_event_set_handler_flag(wmEventHandler *handler, int flag)
2788 {
2789         handler->flag = flag;
2790 }
2791 #endif
2792
2793 wmEventHandler *WM_event_add_modal_handler(bContext *C, wmOperator *op)
2794 {
2795         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event modal handler");
2796         wmWindow *win = CTX_wm_window(C);
2797
2798         /* operator was part of macro */
2799         if (op->opm) {
2800                 /* give the mother macro to the handler */
2801                 handler->op = op->opm;
2802                 /* mother macro opm becomes the macro element */
2803                 handler->op->opm = op;
2804         }
2805         else
2806                 handler->op = op;
2807
2808         handler->op_area = CTX_wm_area(C);       /* means frozen screen context for modal handlers! */
2809         handler->op_region = CTX_wm_region(C);
2810         handler->op_region_type = handler->op_region ? handler->op_region->regiontype : -1;
2811
2812         BLI_addhead(&win->modalhandlers, handler);
2813
2814         return handler;
2815 }
2816
2817 wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2818 {
2819         wmEventHandler *handler;
2820
2821         if (!keymap) {
2822                 CLOG_WARN(WM_LOG_HANDLERS, "called with NULL keymap");
2823                 return NULL;
2824         }
2825
2826         /* only allow same keymap once */
2827         for (handler = handlers->first; handler; handler = handler->next)
2828                 if (handler->keymap == keymap)
2829                         return handler;
2830
2831         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2832         BLI_addtail(handlers, handler);
2833         handler->keymap = keymap;
2834
2835         return handler;
2836 }
2837
2838 /* priorities not implemented yet, for time being just insert in begin of list */
2839 wmEventHandler *WM_event_add_keymap_handler_priority(ListBase *handlers, wmKeyMap *keymap, int UNUSED(priority))
2840 {
2841         wmEventHandler *handler;
2842
2843         WM_event_remove_keymap_handler(handlers, keymap);
2844
2845         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2846         BLI_addhead(handlers, handler);
2847         handler->keymap = keymap;
2848
2849         return handler;
2850 }
2851
2852 wmEventHandler *WM_event_add_keymap_handler_bb(ListBase *handlers, wmKeyMap *keymap, const rcti *bblocal, const rcti *bbwin)
2853 {
2854         wmEventHandler *handler = WM_event_add_keymap_handler(handlers, keymap);
2855
2856         if (handler) {
2857                 handler->bblocal = bblocal;
2858                 handler->bbwin = bbwin;
2859         }
2860         return handler;
2861 }
2862
2863 void WM_event_remove_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2864 {
2865         wmEventHandler *handler;
2866
2867         for (handler = handlers->first; handler; handler = handler->next) {
2868                 if (handler->keymap == keymap) {
2869                         BLI_remlink(handlers, handler);
2870                         wm_event_free_handler(handler);
2871                         break;
2872                 }
2873         }
2874 }
2875
2876 wmEventHandler *WM_event_add_ui_handler(
2877         const bContext *C, ListBase *handlers,
2878         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove,
2879         void *userdata, const char flag)
2880 {
2881         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event ui handler");
2882         handler->ui_handle = ui_handle;
2883         handler->ui_remove = ui_remove;