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