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