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