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