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