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