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