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