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