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