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