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