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