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