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