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