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