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