d31c20f7eab16ed65c7d5777be8f4b47b7741714
[blender.git] / source / blender / windowmanager / intern / wm_event_system.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_event_system.c
28  *  \ingroup wm
29  *
30  * Handle events and notifiers from GHOST input (mouse, keyboard, tablet, ndof).
31  *
32  * Also some operator reports utility functions.
33  */
34
35 #include <stdlib.h>
36 #include <string.h>
37
38 #include "DNA_listBase.h"
39 #include "DNA_screen_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_windowmanager_types.h"
42 #include "DNA_userdef_types.h"
43
44 #include "MEM_guardedalloc.h"
45
46 #include "GHOST_C-api.h"
47
48 #include "BLI_blenlib.h"
49 #include "BLI_dynstr.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_math.h"
52
53 #include "BKE_context.h"
54 #include "BKE_idprop.h"
55 #include "BKE_global.h"
56 #include "BKE_main.h"
57 #include "BKE_report.h"
58 #include "BKE_scene.h"
59 #include "BKE_screen.h"
60
61 #include "BKE_sound.h"
62
63 #include "ED_fileselect.h"
64 #include "ED_info.h"
65 #include "ED_screen.h"
66 #include "ED_view3d.h"
67 #include "ED_util.h"
68
69 #include "RNA_access.h"
70
71 #include "GPU_debug.h"
72
73 #include "UI_interface.h"
74
75 #include "PIL_time.h"
76
77 #include "WM_api.h"
78 #include "WM_types.h"
79 #include "wm.h"
80 #include "wm_window.h"
81 #include "wm_event_system.h"
82 #include "wm_event_types.h"
83
84 #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) || (event->type == EVT_BUT_OPEN);
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(const bContext *C)
602 {
603         wmWindowManager *wm = CTX_wm_manager(C);
604         ReportList *wm_reports = CTX_wm_reports(C);
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, CTX_wm_window(C), 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(const bContext *C, ReportList *reports)
628 {
629         /* if the caller owns them, handle this */
630         if (reports->list.first && (reports->flag & RPT_OP_HOLD) == 0) {
631                 ReportList *wm_reports = CTX_wm_reports(C);
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(C);
637         }
638 }
639
640 void WM_report(const bContext *C, 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(C, &reports);
648
649         BKE_reports_clear(&reports);
650 }
651
652 void WM_reportf(const bContext *C, 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         WM_report(C, type, BLI_dynstr_get_cstring(ds));
663
664         BLI_dynstr_free(ds);
665 }
666
667 /* (caller_owns_reports == true) when called from python */
668 static void wm_operator_reports(bContext *C, wmOperator *op, int retval, bool caller_owns_reports)
669 {
670         if (caller_owns_reports == false) { /* popup */
671                 if (op->reports->list.first) {
672                         /* FIXME, temp setting window, see other call to UI_popup_menu_reports for why */
673                         wmWindow *win_prev = CTX_wm_window(C);
674                         ScrArea *area_prev = CTX_wm_area(C);
675                         ARegion *ar_prev = CTX_wm_region(C);
676
677                         if (win_prev == NULL)
678                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
679
680                         UI_popup_menu_reports(C, op->reports);
681
682                         CTX_wm_window_set(C, win_prev);
683                         CTX_wm_area_set(C, area_prev);
684                         CTX_wm_region_set(C, ar_prev);
685                 }
686         }
687         
688         if (retval & OPERATOR_FINISHED) {
689                 if (G.debug & G_DEBUG_WM) {
690                         /* todo - this print may double up, might want to check more flags then the FINISHED */
691                         wm_operator_print(C, op);
692                 }
693
694                 if (caller_owns_reports == false) {
695                         BKE_reports_print(op->reports, RPT_DEBUG); /* print out reports to console. */
696                 }
697
698                 if (op->type->flag & OPTYPE_REGISTER) {
699                         if (G.background == 0) { /* ends up printing these in the terminal, gets annoying */
700                                 /* Report the python string representation of the operator */
701                                 char *buf = WM_operator_pystring(C, op, false, true);
702                                 BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
703                                 MEM_freeN(buf);
704                         }
705                 }
706         }
707
708         /* if the caller owns them, handle this */
709         wm_add_reports(C, op->reports);
710 }
711
712 /**
713  * This function is mainly to check that the rules for freeing
714  * an operator are kept in sync.
715  */
716 static bool wm_operator_register_check(wmWindowManager *wm, wmOperatorType *ot)
717 {
718         return wm && (wm->op_undo_depth == 0) && (ot->flag & OPTYPE_REGISTER);
719 }
720
721 static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat)
722 {
723         wmWindowManager *wm = CTX_wm_manager(C);
724
725         op->customdata = NULL;
726
727         /* we don't want to do undo pushes for operators that are being
728          * called from operators that already do an undo push. usually
729          * this will happen for python operators that call C operators */
730         if (wm->op_undo_depth == 0)
731                 if (op->type->flag & OPTYPE_UNDO)
732                         ED_undo_push_op(C, op);
733         
734         if (repeat == 0) {
735                 if (G.debug & G_DEBUG_WM) {
736                         char *buf = WM_operator_pystring(C, op, false, true);
737                         BKE_report(CTX_wm_reports(C), RPT_OPERATOR, buf);
738                         MEM_freeN(buf);
739                 }
740
741                 if (wm_operator_register_check(wm, op->type)) {
742                         /* take ownership of reports (in case python provided own) */
743                         op->reports->flag |= RPT_FREE;
744
745                         wm_operator_register(C, op);
746                         WM_operator_region_active_win_set(C);
747                 }
748                 else {
749                         WM_operator_free(op);
750                 }
751         }
752 }
753
754 /* if repeat is true, it doesn't register again, nor does it free */
755 static int wm_operator_exec(bContext *C, wmOperator *op, const bool repeat, const bool store)
756 {
757         wmWindowManager *wm = CTX_wm_manager(C);
758         int retval = OPERATOR_CANCELLED;
759         
760         CTX_wm_operator_poll_msg_set(C, NULL);
761         
762         if (op == NULL || op->type == NULL)
763                 return retval;
764         
765         if (0 == WM_operator_poll(C, op->type))
766                 return retval;
767         
768         if (op->type->exec) {
769                 if (op->type->flag & OPTYPE_UNDO)
770                         wm->op_undo_depth++;
771
772                 retval = op->type->exec(C, op);
773                 OPERATOR_RETVAL_CHECK(retval);
774
775                 if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
776                         wm->op_undo_depth--;
777         }
778         
779         /* XXX Disabled the repeat check to address part 2 of #31840.
780          *     Carefully checked all calls to wm_operator_exec and WM_operator_repeat, don't see any reason
781          *     why this was needed, but worth to note it in case something turns bad. (mont29) */
782         if (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED) /* && repeat == 0 */)
783                 wm_operator_reports(C, op, retval, false);
784         
785         if (retval & OPERATOR_FINISHED) {
786                 if (store) {
787                         if (wm->op_undo_depth == 0) { /* not called by py script */
788                                 WM_operator_last_properties_store(op);
789                         }
790                 }
791                 wm_operator_finished(C, op, repeat);
792         }
793         else if (repeat == 0) {
794                 WM_operator_free(op);
795         }
796         
797         return retval | OPERATOR_HANDLED;
798         
799 }
800
801 /* simply calls exec with basic checks */
802 static int wm_operator_exec_notest(bContext *C, wmOperator *op)
803 {
804         int retval = OPERATOR_CANCELLED;
805
806         if (op == NULL || op->type == NULL || op->type->exec == NULL)
807                 return retval;
808
809         retval = op->type->exec(C, op);
810         OPERATOR_RETVAL_CHECK(retval);
811
812         return retval;
813 }
814
815 /**
816  * for running operators with frozen context (modal handlers, menus)
817  *
818  * \param store Store settings for re-use.
819  *
820  * warning: do not use this within an operator to call its self! [#29537] */
821 int WM_operator_call_ex(bContext *C, wmOperator *op,
822                         const bool store)
823 {
824         return wm_operator_exec(C, op, false, store);
825 }
826
827 int WM_operator_call(bContext *C, wmOperator *op)
828 {
829         return WM_operator_call_ex(C, op, false);
830 }
831
832 /**
833  * This is intended to be used when an invoke operator wants to call exec on its self
834  * and is basically like running op->type->exec() directly, no poll checks no freeing,
835  * since we assume whoever called invoke will take care of that
836  */
837 int WM_operator_call_notest(bContext *C, wmOperator *op)
838 {
839         return wm_operator_exec_notest(C, op);
840 }
841
842 /**
843  * Execute this operator again, put here so it can share above code
844  */
845 int WM_operator_repeat(bContext *C, wmOperator *op)
846 {
847         return wm_operator_exec(C, op, true, true);
848 }
849 /**
850  * \return true if #WM_operator_repeat can run
851  * simple check for now but may become more involved.
852  * To be sure the operator can run call `WM_operator_poll(C, op->type)` also, since this call
853  * checks if WM_operator_repeat() can run at all, not that it WILL run at any time.
854  */
855 bool WM_operator_repeat_check(const bContext *UNUSED(C), wmOperator *op)
856 {
857         if (op->type->exec != NULL) {
858                 return true;
859         }
860         else if (op->opm) {
861                 /* for macros, check all have exec() we can call */
862                 wmOperatorTypeMacro *otmacro;
863                 for (otmacro = op->opm->type->macro.first; otmacro; otmacro = otmacro->next) {
864                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
865                         if (otm && otm->exec == NULL) {
866                                 return false;
867                         }
868                 }
869                 return true;
870         }
871
872         return false;
873 }
874
875 static wmOperator *wm_operator_create(wmWindowManager *wm, wmOperatorType *ot,
876                                       PointerRNA *properties, ReportList *reports)
877 {
878         /* XXX operatortype names are static still. for debug */
879         wmOperator *op = MEM_callocN(sizeof(wmOperator), ot->idname);
880         
881         /* XXX adding new operator could be function, only happens here now */
882         op->type = ot;
883         BLI_strncpy(op->idname, ot->idname, OP_MAX_TYPENAME);
884         
885         /* initialize properties, either copy or create */
886         op->ptr = MEM_callocN(sizeof(PointerRNA), "wmOperatorPtrRNA");
887         if (properties && properties->data) {
888                 op->properties = IDP_CopyProperty(properties->data);
889         }
890         else {
891                 IDPropertyTemplate val = {0};
892                 op->properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
893         }
894         RNA_pointer_create(&wm->id, ot->srna, op->properties, op->ptr);
895
896         /* initialize error reports */
897         if (reports) {
898                 op->reports = reports; /* must be initialized already */
899         }
900         else {
901                 op->reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
902                 BKE_reports_init(op->reports, RPT_STORE | RPT_FREE);
903         }
904         
905         /* recursive filling of operator macro list */
906         if (ot->macro.first) {
907                 static wmOperator *motherop = NULL;
908                 wmOperatorTypeMacro *otmacro;
909                 int root = 0;
910                 
911                 /* ensure all ops are in execution order in 1 list */
912                 if (motherop == NULL) {
913                         motherop = op;
914                         root = 1;
915                 }
916
917                 
918                 /* if properties exist, it will contain everything needed */
919                 if (properties) {
920                         otmacro = ot->macro.first;
921
922                         RNA_STRUCT_BEGIN (properties, prop)
923                         {
924
925                                 if (otmacro == NULL)
926                                         break;
927
928                                 /* skip invalid properties */
929                                 if (STREQ(RNA_property_identifier(prop), otmacro->idname)) {
930                                         wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
931                                         PointerRNA someptr = RNA_property_pointer_get(properties, prop);
932                                         wmOperator *opm = wm_operator_create(wm, otm, &someptr, NULL);
933
934                                         IDP_ReplaceGroupInGroup(opm->properties, otmacro->properties);
935
936                                         BLI_addtail(&motherop->macro, opm);
937                                         opm->opm = motherop; /* pointer to mom, for modal() */
938
939                                         otmacro = otmacro->next;
940                                 }
941                         }
942                         RNA_STRUCT_END;
943                 }
944                 else {
945                         for (otmacro = ot->macro.first; otmacro; otmacro = otmacro->next) {
946                                 wmOperatorType *otm = WM_operatortype_find(otmacro->idname, 0);
947                                 wmOperator *opm = wm_operator_create(wm, otm, otmacro->ptr, NULL);
948
949                                 BLI_addtail(&motherop->macro, opm);
950                                 opm->opm = motherop; /* pointer to mom, for modal() */
951                         }
952                 }
953                 
954                 if (root)
955                         motherop = NULL;
956         }
957         
958         WM_operator_properties_sanitize(op->ptr, 0);
959
960         return op;
961 }
962
963 static void wm_region_mouse_co(bContext *C, wmEvent *event)
964 {
965         ARegion *ar = CTX_wm_region(C);
966         if (ar) {
967                 /* compatibility convention */
968                 event->mval[0] = event->x - ar->winrct.xmin;
969                 event->mval[1] = event->y - ar->winrct.ymin;
970         }
971         else {
972                 /* these values are invalid (avoid odd behavior by relying on old mval values) */
973                 event->mval[0] = -1;
974                 event->mval[1] = -1;
975         }
976 }
977
978 #if 1 /* may want to disable operator remembering previous state for testing */
979 bool WM_operator_last_properties_init(wmOperator *op)
980 {
981         bool changed = false;
982
983         if (op->type->last_properties) {
984                 IDPropertyTemplate val = {0};
985                 IDProperty *replaceprops = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
986                 PropertyRNA *iterprop;
987
988                 if (G.debug & G_DEBUG_WM) {
989                         printf("%s: loading previous properties for '%s'\n", __func__, op->type->idname);
990                 }
991
992                 iterprop = RNA_struct_iterator_property(op->type->srna);
993
994                 RNA_PROP_BEGIN (op->ptr, itemptr, iterprop)
995                 {
996                         PropertyRNA *prop = itemptr.data;
997                         if ((RNA_property_flag(prop) & PROP_SKIP_SAVE) == 0) {
998                                 if (!RNA_property_is_set(op->ptr, prop)) { /* don't override a setting already set */
999                                         const char *identifier = RNA_property_identifier(prop);
1000                                         IDProperty *idp_src = IDP_GetPropertyFromGroup(op->type->last_properties, identifier);
1001                                         if (idp_src) {
1002                                                 IDProperty *idp_dst = IDP_CopyProperty(idp_src);
1003
1004                                                 /* note - in the future this may need to be done recursively,
1005                                                  * but for now RNA doesn't access nested operators */
1006                                                 idp_dst->flag |= IDP_FLAG_GHOST;
1007
1008                                                 /* add to temporary group instead of immediate replace,
1009                                                  * because we are iterating over this group */
1010                                                 IDP_AddToGroup(replaceprops, idp_dst);
1011                                                 changed = true;
1012                                         }
1013                                 }
1014                         }
1015                 }
1016                 RNA_PROP_END;
1017
1018                 IDP_MergeGroup(op->properties, replaceprops, true);
1019                 IDP_FreeProperty(replaceprops);
1020                 MEM_freeN(replaceprops);
1021         }
1022
1023         return changed;
1024 }
1025
1026 bool WM_operator_last_properties_store(wmOperator *op)
1027 {
1028         if (op->type->last_properties) {
1029                 IDP_FreeProperty(op->type->last_properties);
1030                 MEM_freeN(op->type->last_properties);
1031                 op->type->last_properties = NULL;
1032         }
1033
1034         if (op->properties) {
1035                 if (G.debug & G_DEBUG_WM) {
1036                         printf("%s: storing properties for '%s'\n", __func__, op->type->idname);
1037                 }
1038                 op->type->last_properties = IDP_CopyProperty(op->properties);
1039                 return true;
1040         }
1041         else {
1042                 return false;
1043         }
1044 }
1045
1046 #else
1047
1048 bool WM_operator_last_properties_init(wmOperator *UNUSED(op))
1049 {
1050         return false;
1051 }
1052
1053 bool WM_operator_last_properties_store(wmOperator *UNUSED(op))
1054 {
1055         return false;
1056 }
1057
1058 #endif
1059
1060 static int wm_operator_invoke(
1061         bContext *C, wmOperatorType *ot, wmEvent *event,
1062         PointerRNA *properties, ReportList *reports, const bool poll_only)
1063 {
1064         int retval = OPERATOR_PASS_THROUGH;
1065
1066         /* this is done because complicated setup is done to call this function that is better not duplicated */
1067         if (poll_only)
1068                 return WM_operator_poll(C, ot);
1069
1070         if (WM_operator_poll(C, ot)) {
1071                 wmWindowManager *wm = CTX_wm_manager(C);
1072                 wmOperator *op = wm_operator_create(wm, ot, properties, reports); /* if reports == NULL, they'll be initialized */
1073                 const bool is_nested_call = (wm->op_undo_depth != 0);
1074                 
1075                 op->flag |= OP_IS_INVOKE;
1076
1077                 /* initialize setting from previous run */
1078                 if (!is_nested_call) { /* not called by py script */
1079                         WM_operator_last_properties_init(op);
1080                 }
1081
1082                 if ((G.debug & G_DEBUG_HANDLERS) && ((event == NULL) || (event->type != MOUSEMOVE))) {
1083                         printf("%s: handle evt %d win %d op %s\n",
1084                                __func__, event ? event->type : 0, CTX_wm_screen(C)->subwinactive, ot->idname);
1085                 }
1086                 
1087                 if (op->type->invoke && event) {
1088                         wm_region_mouse_co(C, event);
1089
1090                         if (op->type->flag & OPTYPE_UNDO)
1091                                 wm->op_undo_depth++;
1092
1093                         retval = op->type->invoke(C, op, event);
1094                         OPERATOR_RETVAL_CHECK(retval);
1095
1096                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1097                                 wm->op_undo_depth--;
1098                 }
1099                 else if (op->type->exec) {
1100                         if (op->type->flag & OPTYPE_UNDO)
1101                                 wm->op_undo_depth++;
1102
1103                         retval = op->type->exec(C, op);
1104                         OPERATOR_RETVAL_CHECK(retval);
1105
1106                         if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1107                                 wm->op_undo_depth--;
1108                 }
1109                 else {
1110                         /* debug, important to leave a while, should never happen */
1111                         printf("%s: invalid operator call '%s'\n", __func__, ot->idname);
1112                 }
1113                 
1114                 /* Note, if the report is given as an argument then assume the caller will deal with displaying them
1115                  * currently python only uses this */
1116                 if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED))) {
1117                         /* only show the report if the report list was not given in the function */
1118                         wm_operator_reports(C, op, retval, (reports != NULL));
1119                 }
1120
1121                 if (retval & OPERATOR_HANDLED) {
1122                         /* do nothing, wm_operator_exec() has been called somewhere */
1123                 }
1124                 else if (retval & OPERATOR_FINISHED) {
1125                         if (!is_nested_call) { /* not called by py script */
1126                                 WM_operator_last_properties_store(op);
1127                         }
1128                         wm_operator_finished(C, op, 0);
1129                 }
1130                 else if (retval & OPERATOR_RUNNING_MODAL) {
1131                         /* take ownership of reports (in case python provided own) */
1132                         op->reports->flag |= RPT_FREE;
1133
1134                         /* grab cursor during blocking modal ops (X11)
1135                          * Also check for macro
1136                          */
1137                         if (ot->flag & OPTYPE_BLOCKING || (op->opm && op->opm->type->flag & OPTYPE_BLOCKING)) {
1138                                 int bounds[4] = {-1, -1, -1, -1};
1139                                 bool wrap;
1140
1141                                 if (event == NULL) {
1142                                         wrap = false;
1143                                 }
1144                                 else if (op->opm) {
1145                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1146                                                ((op->opm->flag & OP_IS_MODAL_GRAB_CURSOR) || (op->opm->type->flag & OPTYPE_GRAB_CURSOR));
1147                                 }
1148                                 else {
1149                                         wrap = (U.uiflag & USER_CONTINUOUS_MOUSE) &&
1150                                                ((op->flag & OP_IS_MODAL_GRAB_CURSOR) || (ot->flag & OPTYPE_GRAB_CURSOR));
1151                                 }
1152
1153                                 /* exception, cont. grab in header is annoying */
1154                                 if (wrap) {
1155                                         ARegion *ar = CTX_wm_region(C);
1156                                         if (ar && ar->regiontype == RGN_TYPE_HEADER) {
1157                                                 wrap = false;
1158                                         }
1159                                 }
1160
1161                                 if (wrap) {
1162                                         const rcti *winrect = NULL;
1163                                         ARegion *ar = CTX_wm_region(C);
1164                                         ScrArea *sa = CTX_wm_area(C);
1165
1166                                         if (ar && ar->regiontype == RGN_TYPE_WINDOW &&
1167                                             BLI_rcti_isect_pt_v(&ar->winrct, &event->x))
1168                                         {
1169                                                 winrect = &ar->winrct;
1170                                         }
1171                                         else if (sa && BLI_rcti_isect_pt_v(&sa->totrct, &event->x)) {
1172                                                 winrect = &sa->totrct;
1173                                         }
1174
1175                                         if (winrect) {
1176                                                 bounds[0] = winrect->xmin;
1177                                                 bounds[1] = winrect->ymax;
1178                                                 bounds[2] = winrect->xmax;
1179                                                 bounds[3] = winrect->ymin;
1180                                         }
1181                                 }
1182
1183                                 WM_cursor_grab_enable(CTX_wm_window(C), wrap, false, bounds);
1184                         }
1185
1186                         /* cancel UI handlers, typically tooltips that can hang around
1187                          * while dragging the view or worse, that stay there permanently
1188                          * after the modal operator has swallowed all events and passed
1189                          * none to the UI handler */
1190                         wm_handler_ui_cancel(C);
1191                 }
1192                 else {
1193                         WM_operator_free(op);
1194                 }
1195         }
1196
1197         return retval;
1198 }
1199
1200 /**
1201  * #WM_operator_name_call is the main accessor function
1202  * this is for python to access since its done the operator lookup
1203  * 
1204  * invokes operator in context
1205  */
1206 static int wm_operator_call_internal(
1207         bContext *C, wmOperatorType *ot, PointerRNA *properties, ReportList *reports,
1208         const short context, const bool poll_only)
1209 {
1210         wmEvent *event;
1211         
1212         int retval;
1213
1214         CTX_wm_operator_poll_msg_set(C, NULL);
1215
1216         /* dummie test */
1217         if (ot) {
1218                 wmWindow *window = CTX_wm_window(C);
1219
1220                 switch (context) {
1221                         case WM_OP_INVOKE_DEFAULT:
1222                         case WM_OP_INVOKE_REGION_WIN:
1223                         case WM_OP_INVOKE_AREA:
1224                         case WM_OP_INVOKE_SCREEN:
1225                                 /* window is needed for invoke, cancel operator */
1226                                 if (window == NULL) {
1227                                         if (poll_only) {
1228                                                 CTX_wm_operator_poll_msg_set(C, "Missing 'window' in context");
1229                                         }
1230                                         return 0;
1231                                 }
1232                                 else {
1233                                         event = window->eventstate;
1234                                 }
1235                                 break;
1236                         default:
1237                                 event = NULL;
1238                                 break;
1239                 }
1240
1241                 switch (context) {
1242                         
1243                         case WM_OP_EXEC_REGION_WIN:
1244                         case WM_OP_INVOKE_REGION_WIN: 
1245                         case WM_OP_EXEC_REGION_CHANNELS:
1246                         case WM_OP_INVOKE_REGION_CHANNELS:
1247                         case WM_OP_EXEC_REGION_PREVIEW:
1248                         case WM_OP_INVOKE_REGION_PREVIEW:
1249                         {
1250                                 /* forces operator to go to the region window/channels/preview, for header menus
1251                                  * but we stay in the same region if we are already in one 
1252                                  */
1253                                 ARegion *ar = CTX_wm_region(C);
1254                                 ScrArea *area = CTX_wm_area(C);
1255                                 int type = RGN_TYPE_WINDOW;
1256                                 
1257                                 switch (context) {
1258                                         case WM_OP_EXEC_REGION_CHANNELS:
1259                                         case WM_OP_INVOKE_REGION_CHANNELS:
1260                                                 type = RGN_TYPE_CHANNELS;
1261                                                 break;
1262                                         
1263                                         case WM_OP_EXEC_REGION_PREVIEW:
1264                                         case WM_OP_INVOKE_REGION_PREVIEW:
1265                                                 type = RGN_TYPE_PREVIEW;
1266                                                 break;
1267                                         
1268                                         case WM_OP_EXEC_REGION_WIN:
1269                                         case WM_OP_INVOKE_REGION_WIN: 
1270                                         default:
1271                                                 type = RGN_TYPE_WINDOW;
1272                                                 break;
1273                                 }
1274                                 
1275                                 if (!(ar && ar->regiontype == type) && area) {
1276                                         ARegion *ar1;
1277                                         if (type == RGN_TYPE_WINDOW) {
1278                                                 ar1 = BKE_area_find_region_active_win(area);
1279                                         }
1280                                         else {
1281                                                 ar1 = BKE_area_find_region_type(area, type);
1282                                         }
1283
1284                                         if (ar1)
1285                                                 CTX_wm_region_set(C, ar1);
1286                                 }
1287                                 
1288                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1289                                 
1290                                 /* set region back */
1291                                 CTX_wm_region_set(C, ar);
1292                                 
1293                                 return retval;
1294                         }
1295                         case WM_OP_EXEC_AREA:
1296                         case WM_OP_INVOKE_AREA:
1297                         {
1298                                 /* remove region from context */
1299                                 ARegion *ar = CTX_wm_region(C);
1300
1301                                 CTX_wm_region_set(C, NULL);
1302                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1303                                 CTX_wm_region_set(C, ar);
1304
1305                                 return retval;
1306                         }
1307                         case WM_OP_EXEC_SCREEN:
1308                         case WM_OP_INVOKE_SCREEN:
1309                         {
1310                                 /* remove region + area from context */
1311                                 ARegion *ar = CTX_wm_region(C);
1312                                 ScrArea *area = CTX_wm_area(C);
1313
1314                                 CTX_wm_region_set(C, NULL);
1315                                 CTX_wm_area_set(C, NULL);
1316                                 retval = wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1317                                 CTX_wm_area_set(C, area);
1318                                 CTX_wm_region_set(C, ar);
1319
1320                                 return retval;
1321                         }
1322                         case WM_OP_EXEC_DEFAULT:
1323                         case WM_OP_INVOKE_DEFAULT:
1324                                 return wm_operator_invoke(C, ot, event, properties, reports, poll_only);
1325                 }
1326         }
1327         
1328         return 0;
1329 }
1330
1331
1332 /* invokes operator in context */
1333 int WM_operator_name_call_ptr(bContext *C, wmOperatorType *ot, short context, PointerRNA *properties)
1334 {
1335         BLI_assert(ot == WM_operatortype_find(ot->idname, true));
1336         return wm_operator_call_internal(C, ot, properties, NULL, context, false);
1337 }
1338 int WM_operator_name_call(bContext *C, const char *opstring, short context, PointerRNA *properties)
1339 {
1340         wmOperatorType *ot = WM_operatortype_find(opstring, 0);
1341         if (ot) {
1342                 return WM_operator_name_call_ptr(C, ot, context, properties);
1343         }
1344
1345         return 0;
1346 }
1347
1348 /**
1349  * Similar to #WM_operator_name_call called with #WM_OP_EXEC_DEFAULT context.
1350  *
1351  * - #wmOperatorType is used instead of operator name since python already has the operator type.
1352  * - `poll()` must be called by python before this runs.
1353  * - reports can be passed to this function (so python can report them as exceptions).
1354  */
1355 int WM_operator_call_py(
1356         bContext *C, wmOperatorType *ot, short context,
1357         PointerRNA *properties, ReportList *reports, const bool is_undo)
1358 {
1359         int retval = OPERATOR_CANCELLED;
1360
1361 #if 0
1362         wmOperator *op;
1363         op = wm_operator_create(wm, ot, properties, reports);
1364
1365         if (op->type->exec) {
1366                 if (is_undo && op->type->flag & OPTYPE_UNDO)
1367                         wm->op_undo_depth++;
1368
1369                 retval = op->type->exec(C, op);
1370                 OPERATOR_RETVAL_CHECK(retval);
1371
1372                 if (is_undo && op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1373                         wm->op_undo_depth--;
1374         }
1375         else
1376                 printf("error \"%s\" operator has no exec function, python cannot call it\n", op->type->name);
1377 #endif
1378
1379         /* not especially nice using undo depth here, its used so py never
1380          * triggers undo or stores operators last used state.
1381          *
1382          * we could have some more obvious way of doing this like passing a flag.
1383          */
1384         wmWindowManager *wm = CTX_wm_manager(C);
1385         if (!is_undo && wm) wm->op_undo_depth++;
1386
1387         retval = wm_operator_call_internal(C, ot, properties, reports, context, false);
1388         
1389         if (!is_undo && wm && (wm == CTX_wm_manager(C))) wm->op_undo_depth--;
1390
1391         return retval;
1392 }
1393
1394
1395 /* ********************* handlers *************** */
1396
1397 /* future extra customadata free? */
1398 void wm_event_free_handler(wmEventHandler *handler)
1399 {
1400         MEM_freeN(handler);
1401 }
1402
1403 /* only set context when area/region is part of screen */
1404 static void wm_handler_op_context(bContext *C, wmEventHandler *handler, const wmEvent *event)
1405 {
1406         bScreen *screen = CTX_wm_screen(C);
1407         
1408         if (screen && handler->op) {
1409                 if (handler->op_area == NULL)
1410                         CTX_wm_area_set(C, NULL);
1411                 else {
1412                         ScrArea *sa;
1413                         
1414                         for (sa = screen->areabase.first; sa; sa = sa->next)
1415                                 if (sa == handler->op_area)
1416                                         break;
1417                         if (sa == NULL) {
1418                                 /* when changing screen layouts with running modal handlers (like render display), this
1419                                  * is not an error to print */
1420                                 if (handler->op == NULL)
1421                                         printf("internal error: handler (%s) has invalid area\n", handler->op->type->idname);
1422                         }
1423                         else {
1424                                 ARegion *ar;
1425                                 wmOperator *op = handler->op ? (handler->op->opm ? handler->op->opm : handler->op) : NULL;
1426                                 CTX_wm_area_set(C, sa);
1427
1428                                 if (op && (op->flag & OP_IS_MODAL_CURSOR_REGION)) {
1429                                         ar = BKE_area_find_region_xy(sa, handler->op_region_type, event->x, event->y);
1430                                         if (ar) {
1431                                                 handler->op_region = ar;
1432                                         }
1433                                 }
1434                                 else {
1435                                         ar = NULL;
1436                                 }
1437
1438                                 if (ar == NULL) {
1439                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1440                                                 if (ar == handler->op_region) {
1441                                                         break;
1442                                                 }
1443                                         }
1444                                 }
1445
1446                                 /* XXX no warning print here, after full-area and back regions are remade */
1447                                 if (ar)
1448                                         CTX_wm_region_set(C, ar);
1449                         }
1450                 }
1451         }
1452 }
1453
1454 /* called on exit or remove area, only here call cancel callback */
1455 void WM_event_remove_handlers(bContext *C, ListBase *handlers)
1456 {
1457         wmEventHandler *handler;
1458         wmWindowManager *wm = CTX_wm_manager(C);
1459         
1460         /* C is zero on freeing database, modal handlers then already were freed */
1461         while ((handler = BLI_pophead(handlers))) {
1462                 if (handler->op) {
1463                         wmWindow *win = CTX_wm_window(C);
1464                         if (handler->op->type->cancel) {
1465                                 ScrArea *area = CTX_wm_area(C);
1466                                 ARegion *region = CTX_wm_region(C);
1467                                 
1468                                 wm_handler_op_context(C, handler, win->eventstate);
1469
1470                                 if (handler->op->type->flag & OPTYPE_UNDO)
1471                                         wm->op_undo_depth++;
1472
1473                                 handler->op->type->cancel(C, handler->op);
1474
1475                                 if (handler->op->type->flag & OPTYPE_UNDO)
1476                                         wm->op_undo_depth--;
1477
1478                                 CTX_wm_area_set(C, area);
1479                                 CTX_wm_region_set(C, region);
1480                         }
1481
1482                         WM_cursor_grab_disable(win, NULL);
1483                         WM_operator_free(handler->op);
1484                 }
1485                 else if (handler->ui_remove) {
1486                         ScrArea *area = CTX_wm_area(C);
1487                         ARegion *region = CTX_wm_region(C);
1488                         ARegion *menu = CTX_wm_menu(C);
1489                         
1490                         if (handler->ui_area) CTX_wm_area_set(C, handler->ui_area);
1491                         if (handler->ui_region) CTX_wm_region_set(C, handler->ui_region);
1492                         if (handler->ui_menu) CTX_wm_menu_set(C, handler->ui_menu);
1493
1494                         handler->ui_remove(C, handler->ui_userdata);
1495
1496                         CTX_wm_area_set(C, area);
1497                         CTX_wm_region_set(C, region);
1498                         CTX_wm_menu_set(C, menu);
1499                 }
1500
1501                 wm_event_free_handler(handler);
1502         }
1503 }
1504
1505 /* do userdef mappings */
1506 int WM_userdef_event_map(int kmitype)
1507 {
1508         switch (kmitype) {
1509                 case SELECTMOUSE:
1510                         return (U.flag & USER_LMOUSESELECT) ? LEFTMOUSE : RIGHTMOUSE;
1511                 case ACTIONMOUSE:
1512                         return (U.flag & USER_LMOUSESELECT) ? RIGHTMOUSE : LEFTMOUSE;
1513                 case EVT_TWEAK_A:
1514                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_R : EVT_TWEAK_L;
1515                 case EVT_TWEAK_S:
1516                         return (U.flag & USER_LMOUSESELECT) ? EVT_TWEAK_L : EVT_TWEAK_R;
1517                 case WHEELOUTMOUSE:
1518                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELUPMOUSE : WHEELDOWNMOUSE;
1519                 case WHEELINMOUSE:
1520                         return (U.uiflag & USER_WHEELZOOMDIR) ? WHEELDOWNMOUSE : WHEELUPMOUSE;
1521         }
1522         
1523         return kmitype;
1524 }
1525
1526
1527 static int wm_eventmatch(wmEvent *winevent, wmKeyMapItem *kmi)
1528 {
1529         int kmitype = WM_userdef_event_map(kmi->type);
1530
1531         if (kmi->flag & KMI_INACTIVE) return 0;
1532
1533         /* the matching rules */
1534         if (kmitype == KM_TEXTINPUT)
1535                 if (winevent->val == KM_PRESS) {  /* prevent double clicks */
1536                         /* NOT using ISTEXTINPUT anymore because (at least on Windows) some key codes above 255
1537                          * could have printable ascii keys - BUG [#30479] */
1538                         if (ISKEYBOARD(winevent->type) && (winevent->ascii || winevent->utf8_buf[0])) return 1; 
1539                 }
1540
1541         if (kmitype != KM_ANY) {
1542                 if (ELEM(kmitype, TABLET_STYLUS, TABLET_ERASER)) {
1543                         const wmTabletData *wmtab = winevent->tablet_data;
1544                         
1545                         if (wmtab == NULL)
1546                                 return 0;
1547                         else if (winevent->type != LEFTMOUSE) /* tablet events can occur on hover + keypress */
1548                                 return 0;
1549                         else if ((kmitype == TABLET_STYLUS) && (wmtab->Active != EVT_TABLET_STYLUS))
1550                                 return 0;
1551                         else if ((kmitype == TABLET_ERASER) && (wmtab->Active != EVT_TABLET_ERASER))
1552                                 return 0;
1553                 }
1554                 else {
1555                         if (winevent->type != kmitype)
1556                                 return 0;
1557                 }
1558         }
1559         
1560         if (kmi->val != KM_ANY)
1561                 if (winevent->val != kmi->val) return 0;
1562         
1563         /* modifiers also check bits, so it allows modifier order */
1564         if (kmi->shift != KM_ANY)
1565                 if (winevent->shift != kmi->shift && !(winevent->shift & kmi->shift)) return 0;
1566         if (kmi->ctrl != KM_ANY)
1567                 if (winevent->ctrl != kmi->ctrl && !(winevent->ctrl & kmi->ctrl)) return 0;
1568         if (kmi->alt != KM_ANY)
1569                 if (winevent->alt != kmi->alt && !(winevent->alt & kmi->alt)) return 0;
1570         if (kmi->oskey != KM_ANY)
1571                 if (winevent->oskey != kmi->oskey && !(winevent->oskey & kmi->oskey)) return 0;
1572         
1573         /* only keymap entry with keymodifier is checked, means all keys without modifier get handled too. */
1574         /* that is currently needed to make overlapping events work (when you press A - G fast or so). */
1575         if (kmi->keymodifier)
1576                 if (winevent->keymodifier != kmi->keymodifier) return 0;
1577         
1578         return 1;
1579 }
1580
1581
1582 /* operator exists */
1583 static void wm_event_modalkeymap(const bContext *C, wmOperator *op, wmEvent *event, bool *dbl_click_disabled)
1584 {
1585         /* support for modal keymap in macros */
1586         if (op->opm)
1587                 op = op->opm;
1588
1589         if (op->type->modalkeymap) {
1590                 wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1591                 wmKeyMapItem *kmi;
1592
1593                 for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1594                         if (wm_eventmatch(event, kmi)) {
1595                                         
1596                                 event->prevtype = event->type;
1597                                 event->prevval = event->val;
1598                                 event->type = EVT_MODAL_MAP;
1599                                 event->val = kmi->propvalue;
1600                                 
1601                                 break;
1602                         }
1603                 }
1604         }
1605         else {
1606                 /* modal keymap checking returns handled events fine, but all hardcoded modal
1607                  * handling typically swallows all events (OPERATOR_RUNNING_MODAL).
1608                  * This bypass just disables support for double clicks in hardcoded modal handlers */
1609                 if (event->val == KM_DBL_CLICK) {
1610                         event->val = KM_PRESS;
1611                         *dbl_click_disabled = true;
1612                 }
1613         }
1614 }
1615
1616 /**
1617  * Check whether operator is allowed to run in case interface is locked,
1618  * If interface is unlocked, will always return truth.
1619  */
1620 static bool wm_operator_check_locked_interface(bContext *C, wmOperatorType *ot)
1621 {
1622         wmWindowManager *wm = CTX_wm_manager(C);
1623
1624         if (wm->is_interface_locked) {
1625                 if ((ot->flag & OPTYPE_LOCK_BYPASS) == 0) {
1626                         return false;
1627                 }
1628         }
1629
1630         return true;
1631 }
1632
1633 /* bad hacking event system... better restore event type for checking of KM_CLICK for example */
1634 /* XXX modal maps could use different method (ton) */
1635 static void wm_event_modalmap_end(wmEvent *event, bool dbl_click_disabled)
1636 {
1637         if (event->type == EVT_MODAL_MAP) {
1638                 event->type = event->prevtype;
1639                 event->prevtype = 0;
1640                 event->val = event->prevval;
1641                 event->prevval = 0;
1642         }
1643         else if (dbl_click_disabled)
1644                 event->val = KM_DBL_CLICK;
1645
1646 }
1647
1648 /* Warning: this function removes a modal handler, when finished */
1649 static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHandler *handler,
1650                                     wmEvent *event, PointerRNA *properties)
1651 {
1652         int retval = OPERATOR_PASS_THROUGH;
1653         
1654         /* derived, modal or blocking operator */
1655         if (handler->op) {
1656                 wmOperator *op = handler->op;
1657                 wmOperatorType *ot = op->type;
1658
1659                 if (!wm_operator_check_locked_interface(C, ot)) {
1660                         /* Interface is locked and operator is not allowed to run,
1661                          * nothing to do in this case.
1662                          */
1663                 }
1664                 else if (ot->modal) {
1665                         /* we set context to where modal handler came from */
1666                         wmWindowManager *wm = CTX_wm_manager(C);
1667                         ScrArea *area = CTX_wm_area(C);
1668                         ARegion *region = CTX_wm_region(C);
1669                         bool dbl_click_disabled = false;
1670
1671                         wm_handler_op_context(C, handler, event);
1672                         wm_region_mouse_co(C, event);
1673                         wm_event_modalkeymap(C, op, event, &dbl_click_disabled);
1674                         
1675                         if (ot->flag & OPTYPE_UNDO)
1676                                 wm->op_undo_depth++;
1677
1678                         /* warning, after this call all context data and 'event' may be freed. see check below */
1679                         retval = ot->modal(C, op, event);
1680                         OPERATOR_RETVAL_CHECK(retval);
1681                         
1682                         /* when this is _not_ the case the modal modifier may have loaded
1683                          * a new blend file (demo mode does this), so we have to assume
1684                          * the event, operator etc have all been freed. - campbell */
1685                         if (CTX_wm_manager(C) == wm) {
1686
1687                                 wm_event_modalmap_end(event, dbl_click_disabled);
1688
1689                                 if (ot->flag & OPTYPE_UNDO)
1690                                         wm->op_undo_depth--;
1691
1692                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED))
1693                                         wm_operator_reports(C, op, retval, false);
1694
1695                                 /* important to run 'wm_operator_finished' before NULLing the context members */
1696                                 if (retval & OPERATOR_FINISHED) {
1697                                         wm_operator_finished(C, op, 0);
1698                                         handler->op = NULL;
1699                                 }
1700                                 else if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1701                                         WM_operator_free(op);
1702                                         handler->op = NULL;
1703                                 }
1704
1705                                 /* putting back screen context, reval can pass trough after modal failures! */
1706                                 if ((retval & OPERATOR_PASS_THROUGH) || wm_event_always_pass(event)) {
1707                                         CTX_wm_area_set(C, area);
1708                                         CTX_wm_region_set(C, region);
1709                                 }
1710                                 else {
1711                                         /* this special cases is for areas and regions that get removed */
1712                                         CTX_wm_area_set(C, NULL);
1713                                         CTX_wm_region_set(C, NULL);
1714                                 }
1715
1716                                 /* remove modal handler, operator itself should have been canceled and freed */
1717                                 if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
1718                                         WM_cursor_grab_disable(CTX_wm_window(C), NULL);
1719
1720                                         BLI_remlink(handlers, handler);
1721                                         wm_event_free_handler(handler);
1722
1723                                         /* prevent silly errors from operator users */
1724                                         //retval &= ~OPERATOR_PASS_THROUGH;
1725                                 }
1726                         }
1727                         
1728                 }
1729                 else {
1730                         printf("%s: error '%s' missing modal\n", __func__, op->idname);
1731                 }
1732         }
1733         else {
1734                 wmOperatorType *ot = WM_operatortype_find(event->keymap_idname, 0);
1735
1736                 if (ot) {
1737                         if (wm_operator_check_locked_interface(C, ot)) {
1738                                 retval = wm_operator_invoke(C, ot, event, properties, NULL, false);
1739                         }
1740                 }
1741         }
1742         /* Finished and pass through flag as handled */
1743
1744         /* Finished and pass through flag as handled */
1745         if (retval == (OPERATOR_FINISHED | OPERATOR_PASS_THROUGH))
1746                 return WM_HANDLER_HANDLED;
1747
1748         /* Modal unhandled, break */
1749         if (retval == (OPERATOR_PASS_THROUGH | OPERATOR_RUNNING_MODAL))
1750                 return (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
1751
1752         if (retval & OPERATOR_PASS_THROUGH)
1753                 return WM_HANDLER_CONTINUE;
1754
1755         return WM_HANDLER_BREAK;
1756 }
1757
1758 /* fileselect handlers are only in the window queue, so it's safe to switch screens or area types */
1759 static int wm_handler_fileselect_do(bContext *C, ListBase *handlers, wmEventHandler *handler, int val)
1760 {
1761         wmWindowManager *wm = CTX_wm_manager(C);
1762         SpaceFile *sfile;
1763         int action = WM_HANDLER_CONTINUE;
1764
1765         switch (val) {
1766                 case EVT_FILESELECT_FULL_OPEN: 
1767                 {
1768                         ScrArea *sa;
1769                                 
1770                         /* sa can be null when window A is active, but mouse is over window B */
1771                         /* in this case, open file select in original window A */
1772                         if (handler->op_area == NULL) {
1773                                 bScreen *screen = CTX_wm_screen(C);
1774                                 sa = (ScrArea *)screen->areabase.first;
1775                         }
1776                         else {
1777                                 sa = handler->op_area;
1778                         }
1779
1780                         if (sa->full) {
1781                                 /* ensure the first area becomes the file browser, because the second one is the small
1782                                  * top (info-)area which might be too small (in fullscreens we have max two areas) */
1783                                 if (sa->prev) {
1784                                         sa = sa->prev;
1785                                 }
1786                                 ED_area_newspace(C, sa, SPACE_FILE);     /* 'sa' is modified in-place */
1787                                 /* we already had a fullscreen here -> mark new space as a stacked fullscreen */
1788                                 sa->flag |= AREA_FLAG_STACKED_FULLSCREEN;
1789                         }
1790                         else {
1791                                 sa = ED_screen_full_newspace(C, sa, SPACE_FILE);    /* sets context */
1792                         }
1793
1794                         /* note, getting the 'sa' back from the context causes a nasty bug where the newly created
1795                          * 'sa' != CTX_wm_area(C). removed the line below and set 'sa' in the 'if' above */
1796                         /* sa = CTX_wm_area(C); */
1797
1798                         /* settings for filebrowser, sfile is not operator owner but sends events */
1799                         sfile = (SpaceFile *)sa->spacedata.first;
1800                         sfile->op = handler->op;
1801
1802                         ED_fileselect_set_params(sfile);
1803                                 
1804                         action = WM_HANDLER_BREAK;
1805                         break;
1806                 }
1807                         
1808                 case EVT_FILESELECT_EXEC:
1809                 case EVT_FILESELECT_CANCEL:
1810                 case EVT_FILESELECT_EXTERNAL_CANCEL:
1811                 {
1812                         /* remlink now, for load file case before removing*/
1813                         BLI_remlink(handlers, handler);
1814
1815                         if (val != EVT_FILESELECT_EXTERNAL_CANCEL) {
1816                                 ScrArea *sa = CTX_wm_area(C);
1817                                 const SpaceLink *sl = sa->spacedata.first;
1818                                 const bool was_prev_temp = (sl->next && sl->next->spacetype == SPACE_IMAGE);
1819
1820                                 if (sa->full) {
1821                                         ED_screen_full_prevspace(C, sa, was_prev_temp);
1822                                 }
1823                                 /* user may have left fullscreen */
1824                                 else {
1825                                         ED_area_prevspace(C, sa);
1826                                 }
1827                         }
1828
1829                         wm_handler_op_context(C, handler, CTX_wm_window(C)->eventstate);
1830
1831                         /* needed for UI_popup_menu_reports */
1832
1833                         if (val == EVT_FILESELECT_EXEC) {
1834                                 int retval;
1835
1836                                 if (handler->op->type->flag & OPTYPE_UNDO)
1837                                         wm->op_undo_depth++;
1838
1839                                 retval = handler->op->type->exec(C, handler->op);
1840
1841                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1842                                 if (handler->op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
1843                                         wm->op_undo_depth--;
1844
1845                                 /* XXX check this carefully, CTX_wm_manager(C) == wm is a bit hackish */
1846                                 if (CTX_wm_manager(C) == wm && wm->op_undo_depth == 0)
1847                                         if (handler->op->type->flag & OPTYPE_UNDO)
1848                                                 ED_undo_push_op(C, handler->op);
1849
1850                                 if (handler->op->reports->list.first) {
1851
1852                                         /* FIXME, temp setting window, this is really bad!
1853                                          * only have because lib linking errors need to be seen by users :(
1854                                          * it can be removed without breaking anything but then no linking errors - campbell */
1855                                         wmWindow *win_prev = CTX_wm_window(C);
1856                                         ScrArea *area_prev = CTX_wm_area(C);
1857                                         ARegion *ar_prev = CTX_wm_region(C);
1858
1859                                         if (win_prev == NULL)
1860                                                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
1861
1862                                         BKE_report_print_level_set(handler->op->reports, RPT_WARNING);
1863                                         UI_popup_menu_reports(C, handler->op->reports);
1864
1865                                         /* XXX - copied from 'wm_operator_finished()' */
1866                                         /* add reports to the global list, otherwise they are not seen */
1867                                         BLI_movelisttolist(&CTX_wm_reports(C)->list, &handler->op->reports->list);
1868
1869                                         /* more hacks, since we meddle with reports, banner display doesn't happen automatic */
1870                                         WM_report_banner_show(C);
1871
1872                                         CTX_wm_window_set(C, win_prev);
1873                                         CTX_wm_area_set(C, area_prev);
1874                                         CTX_wm_region_set(C, ar_prev);
1875                                 }
1876
1877                                 /* for WM_operator_pystring only, custom report handling is done above */
1878                                 wm_operator_reports(C, handler->op, retval, true);
1879
1880                                 if (retval & OPERATOR_FINISHED) {
1881                                         WM_operator_last_properties_store(handler->op);
1882                                 }
1883
1884                                 WM_operator_free(handler->op);
1885                         }
1886                         else {
1887                                 if (handler->op->type->cancel) {
1888                                         if (handler->op->type->flag & OPTYPE_UNDO)
1889                                                 wm->op_undo_depth++;
1890
1891                                         handler->op->type->cancel(C, handler->op);
1892                                 
1893                                         if (handler->op->type->flag & OPTYPE_UNDO)
1894                                                 wm->op_undo_depth--;
1895                                 }
1896                                 
1897                                 WM_operator_free(handler->op);
1898                         }
1899
1900                         CTX_wm_area_set(C, NULL);
1901
1902                         wm_event_free_handler(handler);
1903
1904                         action = WM_HANDLER_BREAK;
1905                         break;
1906                 }
1907         }
1908         
1909         return action;
1910 }
1911
1912 static int wm_handler_fileselect_call(bContext *C, ListBase *handlers, wmEventHandler *handler, wmEvent *event)
1913 {
1914         int action = WM_HANDLER_CONTINUE;
1915         
1916         if (event->type != EVT_FILESELECT)
1917                 return action;
1918         if (handler->op != (wmOperator *)event->customdata)
1919                 return action;
1920         
1921         return wm_handler_fileselect_do(C, handlers, handler, event->val);
1922 }
1923
1924 static bool handler_boundbox_test(wmEventHandler *handler, wmEvent *event)
1925 {
1926         if (handler->bbwin) {
1927                 if (handler->bblocal) {
1928                         rcti rect = *handler->bblocal;
1929                         BLI_rcti_translate(&rect, handler->bbwin->xmin, handler->bbwin->ymin);
1930
1931                         if (BLI_rcti_isect_pt_v(&rect, &event->x))
1932                                 return 1;
1933                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(&rect, &event->prevx))
1934                                 return 1;
1935                         else
1936                                 return 0;
1937                 }
1938                 else {
1939                         if (BLI_rcti_isect_pt_v(handler->bbwin, &event->x))
1940                                 return 1;
1941                         else if (event->type == MOUSEMOVE && BLI_rcti_isect_pt_v(handler->bbwin, &event->prevx))
1942                                 return 1;
1943                         else
1944                                 return 0;
1945                 }
1946         }
1947         return 1;
1948 }
1949
1950 static int wm_action_not_handled(int action)
1951 {
1952         return action == WM_HANDLER_CONTINUE || action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL);
1953 }
1954
1955 static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers)
1956 {
1957 #ifndef NDEBUG
1958         const bool do_debug_handler = (G.debug & G_DEBUG_HANDLERS) &&
1959                 /* comment this out to flood the console! (if you really want to test) */
1960                 !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)
1961                 ;
1962 #    define PRINT if (do_debug_handler) printf
1963 #else
1964 #  define PRINT(format, ...)
1965 #endif
1966
1967         wmWindowManager *wm = CTX_wm_manager(C);
1968         wmEventHandler *handler, *nexthandler;
1969         int action = WM_HANDLER_CONTINUE;
1970         int always_pass;
1971
1972         if (handlers == NULL) {
1973                 return action;
1974         }
1975
1976         /* modal handlers can get removed in this loop, we keep the loop this way
1977          *
1978          * note: check 'handlers->first' because in rare cases the handlers can be cleared
1979          * by the event thats called, for eg:
1980          *
1981          * Calling a python script which changes the area.type, see [#32232] */
1982         for (handler = handlers->first; handler && handlers->first; handler = nexthandler) {
1983
1984                 nexthandler = handler->next;
1985                 
1986                 /* during this loop, ui handlers for nested menus can tag multiple handlers free */
1987                 if (handler->flag & WM_HANDLER_DO_FREE) {
1988                         /* pass */
1989                 }
1990                 else if (handler_boundbox_test(handler, event)) { /* optional boundbox */
1991                         /* in advance to avoid access to freed event on window close */
1992                         always_pass = wm_event_always_pass(event);
1993                 
1994                         /* modal+blocking handler */
1995                         if (handler->flag & WM_HANDLER_BLOCKING)
1996                                 action |= WM_HANDLER_BREAK;
1997
1998                         if (handler->keymap) {
1999                                 wmKeyMap *keymap = WM_keymap_active(wm, handler->keymap);
2000                                 wmKeyMapItem *kmi;
2001
2002                                 PRINT("%s:   checking '%s' ...", __func__, keymap->idname);
2003
2004                                 if (!keymap->poll || keymap->poll(C)) {
2005
2006                                         PRINT("pass\n");
2007
2008                                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
2009                                                 if (wm_eventmatch(event, kmi)) {
2010
2011                                                         PRINT("%s:     item matched '%s'\n", __func__, kmi->idname);
2012
2013                                                         /* weak, but allows interactive callback to not use rawkey */
2014                                                         event->keymap_idname = kmi->idname;
2015
2016                                                         action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
2017                                                         if (action & WM_HANDLER_BREAK) {
2018                                                                 /* not always_pass here, it denotes removed handler */
2019                                                                 
2020                                                                 if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
2021                                                                         printf("%s:       handled! '%s'\n", __func__, kmi->idname);
2022
2023                                                                 break;
2024                                                         }
2025                                                         else {
2026                                                                 if (action & WM_HANDLER_HANDLED)
2027                                                                         if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
2028                                                                                 printf("%s:       handled - and pass on! '%s'\n", __func__, kmi->idname);
2029                                                                 
2030                                                                         PRINT("%s:       un-handled '%s'...", __func__, kmi->idname);
2031                                                         }
2032                                                 }
2033                                         }
2034                                 }
2035                                 else {
2036                                         PRINT("fail\n");
2037                                 }
2038                         }
2039                         else if (handler->ui_handle) {
2040                                 if (!wm->is_interface_locked) {
2041                                         action |= wm_handler_ui_call(C, handler, event, always_pass);
2042                                 }
2043                         }
2044                         else if (handler->type == WM_HANDLER_FILESELECT) {
2045                                 if (!wm->is_interface_locked) {
2046                                         /* screen context changes here */
2047                                         action |= wm_handler_fileselect_call(C, handlers, handler, event);
2048                                 }
2049                         }
2050                         else if (handler->dropboxes) {
2051                                 if (!wm->is_interface_locked && event->type == EVT_DROP) {
2052                                         wmDropBox *drop = handler->dropboxes->first;
2053                                         for (; drop; drop = drop->next) {
2054                                                 /* other drop custom types allowed */
2055                                                 if (event->custom == EVT_DATA_DRAGDROP) {
2056                                                         ListBase *lb = (ListBase *)event->customdata;
2057                                                         wmDrag *drag;
2058                                                         
2059                                                         for (drag = lb->first; drag; drag = drag->next) {
2060                                                                 if (drop->poll(C, drag, event)) {
2061                                                                         drop->copy(drag, drop);
2062                                                                         
2063                                                                         /* free the drags before calling operator */
2064                                                                         WM_drag_free_list(lb);
2065
2066                                                                         event->customdata = NULL;
2067                                                                         event->custom = 0;
2068                                                                         
2069                                                                         WM_operator_name_call_ptr(C, drop->ot, drop->opcontext, drop->ptr);
2070                                                                         action |= WM_HANDLER_BREAK;
2071                                                                         
2072                                                                         /* XXX fileread case */
2073                                                                         if (CTX_wm_window(C) == NULL)
2074                                                                                 return action;
2075                                                                         
2076                                                                         /* escape from drag loop, got freed */
2077                                                                         break;
2078                                                                 }
2079                                                         }
2080                                                 }
2081                                         }
2082                                 }
2083                         }
2084                         else {
2085                                 /* modal, swallows all */
2086                                 action |= wm_handler_operator_call(C, handlers, handler, event, NULL);
2087                         }
2088
2089                         if (action & WM_HANDLER_BREAK) {
2090                                 if (always_pass)
2091                                         action &= ~WM_HANDLER_BREAK;
2092                                 else
2093                                         break;
2094                         }
2095                 }
2096                 
2097                 /* XXX fileread case, if the wm is freed then the handler's
2098                  * will have been too so the code below need not run. */
2099                 if (CTX_wm_window(C) == NULL) {
2100                         return action;
2101                 }
2102
2103                 /* XXX code this for all modal ops, and ensure free only happens here */
2104                 
2105                 /* modal ui handler can be tagged to be freed */ 
2106                 if (BLI_findindex(handlers, handler) != -1) { /* could be freed already by regular modal ops */
2107                         if (handler->flag & WM_HANDLER_DO_FREE) {
2108                                 BLI_remlink(handlers, handler);
2109                                 wm_event_free_handler(handler);
2110                         }
2111                 }
2112         }
2113
2114         if (action == (WM_HANDLER_BREAK | WM_HANDLER_MODAL))
2115                 wm_cursor_arrow_move(CTX_wm_window(C), event);
2116
2117 #undef PRINT
2118
2119         return action;
2120 }
2121
2122 /* this calls handlers twice - to solve (double-)click events */
2123 static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
2124 {
2125         int action = wm_handlers_do_intern(C, event, handlers);
2126                 
2127         /* fileread case */
2128         if (CTX_wm_window(C) == NULL)
2129                 return action;
2130
2131         if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE, EVENT_NONE) && !ISTIMER(event->type)) {
2132
2133                 /* test for CLICK events */
2134                 if (wm_action_not_handled(action)) {
2135                         wmWindow *win = CTX_wm_window(C);
2136                         
2137                         /* eventstate stores if previous event was a KM_PRESS, in case that 
2138                          * wasn't handled, the KM_RELEASE will become a KM_CLICK */
2139                         
2140                         if (win && event->val == KM_PRESS) {
2141                                 win->eventstate->check_click = true;
2142                         }
2143                         
2144                         if (win && win->eventstate->prevtype == event->type) {
2145                                 
2146                                 if ((event->val == KM_RELEASE) &&
2147                                     (win->eventstate->prevval == KM_PRESS) &&
2148                                     (win->eventstate->check_click == true))
2149                                 {
2150                                         event->val = KM_CLICK;
2151                                         
2152                                         if (G.debug & (G_DEBUG_HANDLERS)) {
2153                                                 printf("%s: handling CLICK\n", __func__);
2154                                         }
2155
2156                                         action |= wm_handlers_do_intern(C, event, handlers);
2157
2158                                         event->val = KM_RELEASE;
2159                                 }
2160                                 else if (event->val == KM_DBL_CLICK) {
2161                                         event->val = KM_PRESS;
2162                                         action |= wm_handlers_do_intern(C, event, handlers);
2163                                         
2164                                         /* revert value if not handled */
2165                                         if (wm_action_not_handled(action)) {
2166                                                 event->val = KM_DBL_CLICK;
2167                                         }
2168                                 }
2169                         }
2170                 }
2171                 else {
2172                         wmWindow *win = CTX_wm_window(C);
2173
2174                         if (win)
2175                                 win->eventstate->check_click = 0;
2176                 }
2177         }
2178         
2179         return action;
2180 }
2181
2182 static int wm_event_inside_i(wmEvent *event, rcti *rect)
2183 {
2184         if (wm_event_always_pass(event))
2185                 return 1;
2186         if (BLI_rcti_isect_pt_v(rect, &event->x))
2187                 return 1;
2188         if (event->type == MOUSEMOVE) {
2189                 if (BLI_rcti_isect_pt_v(rect, &event->prevx)) {
2190                         return 1;
2191                 }
2192                 return 0;
2193         }
2194         return 0;
2195 }
2196
2197 static ScrArea *area_event_inside(bContext *C, const int xy[2])
2198 {
2199         bScreen *screen = CTX_wm_screen(C);
2200         ScrArea *sa;
2201         
2202         if (screen)
2203                 for (sa = screen->areabase.first; sa; sa = sa->next)
2204                         if (BLI_rcti_isect_pt_v(&sa->totrct, xy))
2205                                 return sa;
2206         return NULL;
2207 }
2208
2209 static ARegion *region_event_inside(bContext *C, const int xy[2])
2210 {
2211         bScreen *screen = CTX_wm_screen(C);
2212         ScrArea *area = CTX_wm_area(C);
2213         ARegion *ar;
2214         
2215         if (screen && area)
2216                 for (ar = area->regionbase.first; ar; ar = ar->next)
2217                         if (BLI_rcti_isect_pt_v(&ar->winrct, xy))
2218                                 return ar;
2219         return NULL;
2220 }
2221
2222 static void wm_paintcursor_tag(bContext *C, wmPaintCursor *pc, ARegion *ar)
2223 {
2224         if (ar) {
2225                 for (; pc; pc = pc->next) {
2226                         if (pc->poll == NULL || pc->poll(C)) {
2227                                 wmWindow *win = CTX_wm_window(C);
2228                                 WM_paint_cursor_tag_redraw(win, ar);
2229                         }
2230                 }
2231         }
2232 }
2233
2234 /* called on mousemove, check updates for paintcursors */
2235 /* context was set on active area and region */
2236 static void wm_paintcursor_test(bContext *C, wmEvent *event)
2237 {
2238         wmWindowManager *wm = CTX_wm_manager(C);
2239         
2240         if (wm->paintcursors.first) {
2241                 ARegion *ar = CTX_wm_region(C);
2242                 
2243                 if (ar)
2244                         wm_paintcursor_tag(C, wm->paintcursors.first, ar);
2245                 
2246                 /* if previous position was not in current region, we have to set a temp new context */
2247                 if (ar == NULL || !BLI_rcti_isect_pt_v(&ar->winrct, &event->prevx)) {
2248                         ScrArea *sa = CTX_wm_area(C);
2249                         
2250                         CTX_wm_area_set(C, area_event_inside(C, &event->prevx));
2251                         CTX_wm_region_set(C, region_event_inside(C, &event->prevx));
2252
2253                         wm_paintcursor_tag(C, wm->paintcursors.first, CTX_wm_region(C));
2254                         
2255                         CTX_wm_area_set(C, sa);
2256                         CTX_wm_region_set(C, ar);
2257                 }
2258         }
2259 }
2260
2261 static void wm_event_drag_test(wmWindowManager *wm, wmWindow *win, wmEvent *event)
2262 {
2263         if (BLI_listbase_is_empty(&wm->drags)) {
2264                 return;
2265         }
2266         
2267         if (event->type == MOUSEMOVE || ISKEYMODIFIER(event->type)) {
2268                 win->screen->do_draw_drag = true;
2269         }
2270         else if (event->type == ESCKEY) {
2271                 WM_drag_free_list(&wm->drags);
2272
2273                 win->screen->do_draw_drag = true;
2274         }
2275         else if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2276                 event->type = EVT_DROP;
2277                 
2278                 /* create customdata, first free existing */
2279                 if (event->customdata) {
2280                         if (event->customdatafree)
2281                                 MEM_freeN(event->customdata);
2282                 }
2283                 
2284                 event->custom = EVT_DATA_DRAGDROP;
2285                 event->customdata = &wm->drags;
2286                 event->customdatafree = 1;
2287                 
2288                 /* clear drop icon */
2289                 win->screen->do_draw_drag = true;
2290                 
2291                 /* restore cursor (disabled, see wm_dragdrop.c) */
2292                 // WM_cursor_modal_restore(win);
2293         }
2294         
2295         /* overlap fails otherwise */
2296         if (win->screen->do_draw_drag)
2297                 if (win->drawmethod == USER_DRAW_OVERLAP)
2298                         win->screen->do_draw = true;
2299         
2300 }
2301
2302 /* filter out all events of the pie that spawned the last pie unless it's a release event */
2303 static bool wm_event_pie_filter(wmWindow *win, wmEvent *event)
2304 {
2305         if (win->lock_pie_event && win->lock_pie_event == event->type) {
2306                 if (event->val == KM_RELEASE) {
2307                         win->lock_pie_event = EVENT_NONE;
2308                         return false;
2309                 }
2310                 else {
2311                         return true;
2312                 }
2313         }
2314         else {
2315                 return false;
2316         }
2317 }
2318
2319 /* called in main loop */
2320 /* goes over entire hierarchy:  events -> window -> screen -> area -> region */
2321 void wm_event_do_handlers(bContext *C)
2322 {
2323         wmWindowManager *wm = CTX_wm_manager(C);
2324         wmWindow *win;
2325
2326         /* update key configuration before handling events */
2327         WM_keyconfig_update(wm);
2328
2329         for (win = wm->windows.first; win; win = win->next) {
2330                 wmEvent *event;
2331                 
2332                 if (win->screen == NULL)
2333                         wm_event_free_all(win);
2334                 else {
2335                         Scene *scene = win->screen->scene;
2336                         
2337                         if (scene) {
2338                                 int is_playing_sound = BKE_sound_scene_playing(win->screen->scene);
2339                                 
2340                                 if (is_playing_sound != -1) {
2341                                         bool is_playing_screen;
2342                                         CTX_wm_window_set(C, win);
2343                                         CTX_wm_screen_set(C, win->screen);
2344                                         CTX_data_scene_set(C, scene);
2345                                         
2346                                         is_playing_screen = (ED_screen_animation_playing(wm) != NULL);
2347
2348                                         if (((is_playing_sound == 1) && (is_playing_screen == 0)) ||
2349                                             ((is_playing_sound == 0) && (is_playing_screen == 1)))
2350                                         {
2351                                                 ED_screen_animation_play(C, -1, 1);
2352                                         }
2353                                         
2354                                         if (is_playing_sound == 0) {
2355                                                 const float time = BKE_sound_sync_scene(scene);
2356                                                 if (finite(time)) {
2357                                                         int ncfra = time * (float)FPS + 0.5f;
2358                                                         if (ncfra != scene->r.cfra) {
2359                                                                 scene->r.cfra = ncfra;
2360                                                                 ED_update_for_newframe(CTX_data_main(C), scene, 1);
2361                                                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2362                                                         }
2363                                                 }
2364                                         }
2365                                         
2366                                         CTX_data_scene_set(C, NULL);
2367                                         CTX_wm_screen_set(C, NULL);
2368                                         CTX_wm_window_set(C, NULL);
2369                                 }
2370                         }
2371                 }
2372                 
2373                 while ( (event = win->queue.first) ) {
2374                         int action = WM_HANDLER_CONTINUE;
2375
2376 #ifndef NDEBUG
2377                         if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2378                                 printf("\n%s: Handling event\n", __func__);
2379                                 WM_event_print(event);
2380                         }
2381 #endif
2382
2383                         /* take care of pie event filter */
2384                         if (wm_event_pie_filter(win, event)) {
2385 #ifndef NDEBUG
2386                                 if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
2387                                         printf("\n%s: event filtered due to pie button pressed\n", __func__);
2388                                 }
2389 #endif
2390                                 BLI_remlink(&win->queue, event);
2391                                 wm_event_free(event);
2392                                 continue;
2393                         }
2394
2395                         CTX_wm_window_set(C, win);
2396
2397                         /* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
2398                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2399                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2400                         
2401                         /* MVC demands to not draw in event handlers... but we need to leave it for ogl selecting etc */
2402                         wm_window_make_drawable(wm, win);
2403                         
2404                         wm_region_mouse_co(C, event);
2405
2406
2407                         /* first we do priority handlers, modal + some limited keymaps */
2408                         action |= wm_handlers_do(C, event, &win->modalhandlers);
2409                         
2410                         /* fileread case */
2411                         if (CTX_wm_window(C) == NULL)
2412                                 return;
2413                         
2414                         /* check dragging, creates new event or frees, adds draw tag */
2415                         wm_event_drag_test(wm, win, event);
2416                         
2417                         /* builtin tweak, if action is break it removes tweak */
2418                         wm_tweakevent_test(C, event, action);
2419
2420                         if ((action & WM_HANDLER_BREAK) == 0) {
2421                                 ScrArea *sa;
2422                                 ARegion *ar;
2423                                 int doit = 0;
2424         
2425                                 /* Note: setting subwin active should be done here, after modal handlers have been done */
2426                                 if (event->type == MOUSEMOVE) {
2427                                         /* state variables in screen, cursors. Also used in wm_draw.c, fails for modal handlers though */
2428                                         ED_screen_set_subwinactive(C, event);
2429                                         /* for regions having custom cursors */
2430                                         wm_paintcursor_test(C, event);
2431                                 }
2432                                 else if (event->type == NDOF_MOTION) {
2433                                         win->addmousemove = true;
2434                                 }
2435
2436                                 for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2437                                         /* after restoring a screen from SCREENMAXIMIZED we have to wait
2438                                          * with the screen handling till the region coordinates are updated */
2439                                         if (win->screen->skip_handling == true) {
2440                                                 /* restore for the next iteration of wm_event_do_handlers */
2441                                                 win->screen->skip_handling = false;
2442                                                 break;
2443                                         }
2444
2445                                         /* update azones if needed - done here because it needs to be independent from redraws */
2446                                         if (sa->flag & AREA_FLAG_ACTIONZONES_UPDATE) {
2447                                                 ED_area_azones_update(sa, &event->x);
2448                                         }
2449
2450                                         if (wm_event_inside_i(event, &sa->totrct)) {
2451                                                 CTX_wm_area_set(C, sa);
2452
2453                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2454                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2455                                                                 if (wm_event_inside_i(event, &ar->winrct)) {
2456                                                                         CTX_wm_region_set(C, ar);
2457                                                                         
2458                                                                         /* call even on non mouse events, since the */
2459                                                                         wm_region_mouse_co(C, event);
2460
2461                                                                         if (!BLI_listbase_is_empty(&wm->drags)) {
2462                                                                                 /* does polls for drop regions and checks uibuts */
2463                                                                                 /* need to be here to make sure region context is true */
2464                                                                                 if (ELEM(event->type, MOUSEMOVE, EVT_DROP) || ISKEYMODIFIER(event->type)) {
2465                                                                                         wm_drags_check_ops(C, event);
2466                                                                                 }
2467                                                                         }
2468                                                                         
2469                                                                         action |= wm_handlers_do(C, event, &ar->handlers);
2470
2471                                                                         /* fileread case (python), [#29489] */
2472                                                                         if (CTX_wm_window(C) == NULL)
2473                                                                                 return;
2474
2475                                                                         doit |= (BLI_rcti_isect_pt_v(&ar->winrct, &event->x));
2476                                                                         
2477                                                                         if (action & WM_HANDLER_BREAK)
2478                                                                                 break;
2479                                                                 }
2480                                                         }
2481                                                 }
2482
2483                                                 CTX_wm_region_set(C, NULL);
2484
2485                                                 if ((action & WM_HANDLER_BREAK) == 0) {
2486                                                         wm_region_mouse_co(C, event); /* only invalidates event->mval in this case */
2487                                                         action |= wm_handlers_do(C, event, &sa->handlers);
2488                                                 }
2489                                                 CTX_wm_area_set(C, NULL);
2490
2491                                                 /* NOTE: do not escape on WM_HANDLER_BREAK, mousemove needs handled for previous area */
2492                                         }
2493                                 }
2494                                 
2495                                 if ((action & WM_HANDLER_BREAK) == 0) {
2496                                         /* also some non-modal handlers need active area/region */
2497                                         CTX_wm_area_set(C, area_event_inside(C, &event->x));
2498                                         CTX_wm_region_set(C, region_event_inside(C, &event->x));
2499
2500                                         wm_region_mouse_co(C, event);
2501
2502                                         action |= wm_handlers_do(C, event, &win->handlers);
2503
2504                                         /* fileread case */
2505                                         if (CTX_wm_window(C) == NULL)
2506                                                 return;
2507                                 }
2508
2509                                 /* XXX hrmf, this gives reliable previous mouse coord for area change, feels bad? 
2510                                  * doing it on ghost queue gives errors when mousemoves go over area borders */
2511                                 if (doit && win->screen->subwinactive != win->screen->mainwin) {
2512                                         win->eventstate->prevx = event->x;
2513                                         win->eventstate->prevy = event->y;
2514                                         //printf("win->eventstate->prev = %d %d\n", event->x, event->y);
2515                                 }
2516                                 else {
2517                                         //printf("not setting prev to %d %d\n", event->x, event->y);
2518                                 }
2519                         }
2520                         
2521                         /* unlink and free here, blender-quit then frees all */
2522                         BLI_remlink(&win->queue, event);
2523                         wm_event_free(event);
2524                         
2525                 }
2526                 
2527                 /* only add mousemove when queue was read entirely */
2528                 if (win->addmousemove && win->eventstate) {
2529                         wmEvent tevent = *(win->eventstate);
2530                         // printf("adding MOUSEMOVE %d %d\n", tevent.x, tevent.y);
2531                         tevent.type = MOUSEMOVE;
2532                         tevent.prevx = tevent.x;
2533                         tevent.prevy = tevent.y;
2534                         wm_event_add(win, &tevent);
2535                         win->addmousemove = 0;
2536                 }
2537                 
2538                 CTX_wm_window_set(C, NULL);
2539         }
2540
2541         /* update key configuration after handling events */
2542         WM_keyconfig_update(wm);
2543
2544         GPU_ASSERT_NO_GL_ERRORS("wm_event_do_handlers");
2545 }
2546
2547 /* ********** filesector handling ************ */
2548
2549 void WM_event_fileselect_event(wmWindowManager *wm, void *ophandle, int eventval)
2550 {
2551         /* add to all windows! */
2552         wmWindow *win;
2553         
2554         for (win = wm->windows.first; win; win = win->next) {
2555                 wmEvent event = *win->eventstate;
2556                 
2557                 event.type = EVT_FILESELECT;
2558                 event.val = eventval;
2559                 event.customdata = ophandle;     // only as void pointer type check
2560
2561                 wm_event_add(win, &event);
2562         }
2563 }
2564
2565 /* operator is supposed to have a filled "path" property */
2566 /* optional property: filetype (XXX enum?) */
2567
2568 /**
2569  * The idea here is to keep a handler alive on window queue, owning the operator.
2570  * The filewindow can send event to make it execute, thus ensuring
2571  * executing happens outside of lower level queues, with UI refreshed.
2572  * Should also allow multiwin solutions
2573  */
2574 void WM_event_add_fileselect(bContext *C, wmOperator *op)
2575 {
2576         wmEventHandler *handler, *handlernext;
2577         wmWindowManager *wm = CTX_wm_manager(C);
2578         wmWindow *win = CTX_wm_window(C);
2579
2580         /* only allow 1 file selector open per window */
2581         for (handler = win->modalhandlers.first; handler; handler = handlernext) {
2582                 handlernext = handler->next;
2583                 
2584                 if (handler->type == WM_HANDLER_FILESELECT) {
2585                         bScreen *screen = CTX_wm_screen(C);
2586                         ScrArea *sa;
2587
2588                         /* find the area with the file selector for this handler */
2589                         for (sa = screen->areabase.first; sa; sa = sa->next) {
2590                                 if (sa->spacetype == SPACE_FILE) {
2591                                         SpaceFile *sfile = sa->spacedata.first;
2592
2593                                         if (sfile->op == handler->op) {
2594                                                 CTX_wm_area_set(C, sa);
2595                                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_CANCEL);
2596                                                 break;
2597                                         }
2598                                 }
2599                         }
2600
2601                         /* if not found we stop the handler without changing the screen */
2602                         if (!sa)
2603                                 wm_handler_fileselect_do(C, &win->modalhandlers, handler, EVT_FILESELECT_EXTERNAL_CANCEL);
2604                 }
2605         }
2606         
2607         handler = MEM_callocN(sizeof(wmEventHandler), "fileselect handler");
2608         
2609         handler->type = WM_HANDLER_FILESELECT;
2610         handler->op = op;
2611         handler->op_area = CTX_wm_area(C);
2612         handler->op_region = CTX_wm_region(C);
2613         
2614         BLI_addhead(&win->modalhandlers, handler);
2615         
2616         /* check props once before invoking if check is available
2617          * ensures initial properties are valid */
2618         if (op->type->check) {
2619                 op->type->check(C, op); /* ignore return value */
2620         }
2621
2622         WM_event_fileselect_event(wm, op, EVT_FILESELECT_FULL_OPEN);
2623 }
2624
2625 #if 0
2626 /* lets not expose struct outside wm? */
2627 static void WM_event_set_handler_flag(wmEventHandler *handler, int flag)
2628 {
2629         handler->flag = flag;
2630 }
2631 #endif
2632
2633 wmEventHandler *WM_event_add_modal_handler(bContext *C, wmOperator *op)
2634 {
2635         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event modal handler");
2636         wmWindow *win = CTX_wm_window(C);
2637         
2638         /* operator was part of macro */
2639         if (op->opm) {
2640                 /* give the mother macro to the handler */
2641                 handler->op = op->opm;
2642                 /* mother macro opm becomes the macro element */
2643                 handler->op->opm = op;
2644         }
2645         else
2646                 handler->op = op;
2647         
2648         handler->op_area = CTX_wm_area(C);       /* means frozen screen context for modal handlers! */
2649         handler->op_region = CTX_wm_region(C);
2650         handler->op_region_type = handler->op_region ? handler->op_region->regiontype : -1;
2651         
2652         BLI_addhead(&win->modalhandlers, handler);
2653
2654         return handler;
2655 }
2656
2657 wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2658 {
2659         wmEventHandler *handler;
2660
2661         if (!keymap) {
2662                 printf("%s: called with NULL keymap\n", __func__);
2663                 return NULL;
2664         }
2665
2666         /* only allow same keymap once */
2667         for (handler = handlers->first; handler; handler = handler->next)
2668                 if (handler->keymap == keymap)
2669                         return handler;
2670         
2671         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2672         BLI_addtail(handlers, handler);
2673         handler->keymap = keymap;
2674
2675         return handler;
2676 }
2677
2678 /* priorities not implemented yet, for time being just insert in begin of list */
2679 wmEventHandler *WM_event_add_keymap_handler_priority(ListBase *handlers, wmKeyMap *keymap, int UNUSED(priority))
2680 {
2681         wmEventHandler *handler;
2682         
2683         WM_event_remove_keymap_handler(handlers, keymap);
2684         
2685         handler = MEM_callocN(sizeof(wmEventHandler), "event keymap handler");
2686         BLI_addhead(handlers, handler);
2687         handler->keymap = keymap;
2688         
2689         return handler;
2690 }
2691
2692 wmEventHandler *WM_event_add_keymap_handler_bb(ListBase *handlers, wmKeyMap *keymap, const rcti *bblocal, const rcti *bbwin)
2693 {
2694         wmEventHandler *handler = WM_event_add_keymap_handler(handlers, keymap);
2695         
2696         if (handler) {
2697                 handler->bblocal = bblocal;
2698                 handler->bbwin = bbwin;
2699         }
2700         return handler;
2701 }
2702
2703 void WM_event_remove_keymap_handler(ListBase *handlers, wmKeyMap *keymap)
2704 {
2705         wmEventHandler *handler;
2706         
2707         for (handler = handlers->first; handler; handler = handler->next) {
2708                 if (handler->keymap == keymap) {
2709                         BLI_remlink(handlers, handler);
2710                         wm_event_free_handler(handler);
2711                         break;
2712                 }
2713         }
2714 }
2715
2716 wmEventHandler *WM_event_add_ui_handler(
2717         const bContext *C, ListBase *handlers,
2718         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove,
2719         void *userdata, const char flag)
2720 {
2721         wmEventHandler *handler = MEM_callocN(sizeof(wmEventHandler), "event ui handler");
2722         handler->ui_handle = ui_handle;
2723         handler->ui_remove = ui_remove;
2724         handler->ui_userdata = userdata;
2725         if (C) {
2726                 handler->ui_area    = CTX_wm_area(C);
2727                 handler->ui_region  = CTX_wm_region(C);
2728                 handler->ui_menu    = CTX_wm_menu(C);
2729         }
2730         else {
2731                 handler->ui_area    = NULL;
2732                 handler->ui_region  = NULL;
2733                 handler->ui_menu    = NULL;
2734         }
2735
2736         BLI_assert((flag & WM_HANDLER_DO_FREE) == 0);
2737         handler->flag = flag;
2738         
2739         BLI_addhead(handlers, handler);
2740         
2741         return handler;
2742 }
2743
2744 /* set "postpone" for win->modalhandlers, this is in a running for () loop in wm_handlers_do() */
2745 void WM_event_remove_ui_handler(
2746         ListBase *handlers,
2747         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove,
2748         void *userdata, const bool postpone)
2749 {
2750         wmEventHandler *handler;
2751         
2752         for (handler = handlers->first; handler; handler = handler->next) {
2753                 if ((handler->ui_handle == ui_handle) &&
2754                     (handler->ui_remove == ui_remove) &&
2755                     (handler->ui_userdata == userdata))
2756                 {
2757                         /* handlers will be freed in wm_handlers_do() */
2758                         if (postpone) {
2759                                 handler->flag |= WM_HANDLER_DO_FREE;
2760                         }
2761                         else {
2762                                 BLI_remlink(handlers, handler);
2763                                 wm_event_free_handler(handler);
2764                         }
2765                         break;
2766                 }
2767         }
2768 }
2769
2770 void WM_event_free_ui_handler_all(
2771         bContext *C, ListBase *handlers,
2772         wmUIHandlerFunc ui_handle, wmUIHandlerRemoveFunc ui_remove)
2773 {
2774         wmEventHandler *handler, *handler_next;
2775
2776         for (handler = handlers->first; handler; handler = handler_next) {
2777                 handler_next = handler->next;
2778                 if ((handler->ui_handle == ui_handle) &&
2779                     (handler->ui_remove == ui_remove))
2780                 {
2781                         ui_remove(C, handler->ui_userdata);
2782                         BLI_remlink(handlers, handler);
2783                         wm_event_free_handler(handler);
2784                 }
2785         }
2786 }
2787
2788 wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase *dropboxes)
2789 {
2790         wmEventHandler *handler;
2791
2792         /* only allow same dropbox once */
2793         for (handler = handlers->first; handler; handler = handler->next)
2794                 if (handler->dropboxes == dropboxes)
2795                         return handler;
2796         
2797         handler = MEM_callocN(sizeof(wmEventHandler), "dropbox handler");
2798         
2799         /* dropbox stored static, no free or copy */
2800         handler->dropboxes = dropboxes;
2801         BLI_addhead(handlers, handler);
2802         
2803         return handler;
2804 }
2805
2806 /* XXX solution works, still better check the real cause (ton) */
2807 void WM_event_remove_area_handler(ListBase *handlers, void *area)
2808 {
2809         wmEventHandler *handler, *nexthandler;
2810
2811         for (handler = handlers->first; handler; handler = nexthandler) {
2812                 nexthandler = handler->next;
2813                 if (handler->type != WM_HANDLER_FILESELECT) {
2814                         if (handler->ui_area == area) {
2815                                 BLI_remlink(handlers, handler);
2816                                 wm_event_free_handler(handler);
2817                         }
2818                 }
2819         }
2820 }
2821
2822 #if 0
2823 static void WM_event_remove_handler(ListBase *handlers, wmEventHandler *handler)
2824 {
2825         BLI_remlink(handlers, handler);
2826         wm_event_free_handler(handler);
2827 }
2828 #endif
2829
2830 void WM_event_add_mousemove(bContext *C)
2831 {
2832         wmWindow *window = CTX_wm_window(C);
2833         
2834         window->addmousemove = 1;
2835 }
2836
2837
2838 /* for modal callbacks, check configuration for how to interpret exit with tweaks  */
2839 bool WM_modal_tweak_exit(const wmEvent *event, int tweak_event)
2840 {
2841         /* if the release-confirm userpref setting is enabled, 
2842          * tweak events can be canceled when mouse is released
2843          */
2844         if (U.flag & USER_RELEASECONFIRM) {
2845                 /* option on, so can exit with km-release */
2846                 if (event->val == KM_RELEASE) {