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