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