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