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