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