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