Fix mixed weight-paint & pose mode
[blender.git] / source / blender / editors / screen / screen_ops.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) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/screen/screen_ops.c
26  *  \ingroup edscr
27  */
28
29
30 #include <math.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_math.h"
36 #include "BLI_blenlib.h"
37 #include "BLI_dlrbTree.h"
38 #include "BLI_utildefines.h"
39
40 #include "BLT_translation.h"
41
42 #include "DNA_armature_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_object_types.h"
45 #include "DNA_curve_types.h"
46 #include "DNA_gpencil_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_meta_types.h"
49 #include "DNA_mask_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_workspace_types.h"
52 #include "DNA_userdef_types.h"
53
54 #include "BKE_context.h"
55 #include "BKE_customdata.h"
56 #include "BKE_global.h"
57 #include "BKE_icons.h"
58 #include "BKE_main.h"
59 #include "BKE_object.h"
60 #include "BKE_report.h"
61 #include "BKE_scene.h"
62 #include "BKE_screen.h"
63 #include "BKE_editmesh.h"
64 #include "BKE_sound.h"
65 #include "BKE_mask.h"
66 #include "BKE_workspace.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "DEG_depsgraph.h"
72
73 #include "ED_armature.h"
74 #include "ED_clip.h"
75 #include "ED_image.h"
76 #include "ED_keyframes_draw.h"
77 #include "ED_object.h"
78 #include "ED_screen.h"
79 #include "ED_screen_types.h"
80 #include "ED_sequencer.h"
81 #include "ED_util.h"
82 #include "ED_view3d.h"
83
84 #include "RNA_access.h"
85 #include "RNA_define.h"
86
87 #include "UI_interface.h"
88 #include "UI_resources.h"
89 #include "UI_view2d.h"
90
91 #include "screen_intern.h"  /* own module include */
92
93 #define KM_MODAL_CANCEL     1
94 #define KM_MODAL_APPLY      2
95 #define KM_MODAL_SNAP_ON    3
96 #define KM_MODAL_SNAP_OFF   4
97
98 /* -------------------------------------------------------------------- */
99 /** \name Public Poll API
100  * \{ */
101
102 int ED_operator_regionactive(bContext *C)
103 {
104         if (CTX_wm_window(C) == NULL) return 0;
105         if (CTX_wm_screen(C) == NULL) return 0;
106         if (CTX_wm_region(C) == NULL) return 0;
107         return 1;
108 }
109
110 int ED_operator_areaactive(bContext *C)
111 {
112         if (CTX_wm_window(C) == NULL) return 0;
113         if (CTX_wm_screen(C) == NULL) return 0;
114         if (CTX_wm_area(C) == NULL) return 0;
115         return 1;
116 }
117
118 int ED_operator_screenactive(bContext *C)
119 {
120         if (CTX_wm_window(C) == NULL) return 0;
121         if (CTX_wm_screen(C) == NULL) return 0;
122         return 1;
123 }
124
125 /* XXX added this to prevent anim state to change during renders */
126 static int ED_operator_screenactive_norender(bContext *C)
127 {
128         if (G.is_rendering) return 0;
129         if (CTX_wm_window(C) == NULL) return 0;
130         if (CTX_wm_screen(C) == NULL) return 0;
131         return 1;
132 }
133
134 /* when mouse is over area-edge */
135 int ED_operator_screen_mainwinactive(bContext *C)
136 {
137         bScreen *screen;
138         if (CTX_wm_window(C) == NULL) return 0;
139         screen = CTX_wm_screen(C);
140         if (screen == NULL) return 0;
141         if (screen->subwinactive != screen->mainwin) return 0;
142         return 1;
143 }
144
145 int ED_operator_scene_editable(bContext *C)
146 {
147         Scene *scene = CTX_data_scene(C);
148         if (scene && !ID_IS_LINKED(scene))
149                 return 1;
150         return 0;
151 }
152
153 int ED_operator_objectmode(bContext *C)
154 {
155         EvaluationContext eval_ctx;
156         CTX_data_eval_ctx(C, &eval_ctx);
157         Scene *scene = CTX_data_scene(C);
158         Object *obact = CTX_data_active_object(C);
159
160         if (scene == NULL || ID_IS_LINKED(scene))
161                 return 0;
162         if (CTX_data_edit_object(C))
163                 return 0;
164         
165         /* add a check for ob->mode too? */
166         if (obact && (eval_ctx.object_mode != OB_MODE_OBJECT))
167                 return 0;
168         
169         return 1;
170 }
171
172
173 static bool ed_spacetype_test(bContext *C, int type)
174 {
175         if (ED_operator_areaactive(C)) {
176                 SpaceLink *sl = (SpaceLink *)CTX_wm_space_data(C);
177                 return sl && (sl->spacetype == type);
178         }
179         return 0;
180 }
181
182 int ED_operator_view3d_active(bContext *C)
183 {
184         return ed_spacetype_test(C, SPACE_VIEW3D);
185 }
186
187 int ED_operator_region_view3d_active(bContext *C)
188 {
189         if (CTX_wm_region_view3d(C))
190                 return true;
191
192         CTX_wm_operator_poll_msg_set(C, "expected a view3d region");
193         return false;
194 }
195
196 /* generic for any view2d which uses anim_ops */
197 int ED_operator_animview_active(bContext *C)
198 {
199         if (ED_operator_areaactive(C)) {
200                 SpaceLink *sl = (SpaceLink *)CTX_wm_space_data(C);
201                 if (sl && (ELEM(sl->spacetype, SPACE_SEQ, SPACE_ACTION, SPACE_NLA, SPACE_IPO, SPACE_TIME)))
202                         return true;
203         }
204
205         CTX_wm_operator_poll_msg_set(C, "expected a timeline/animation area to be active");
206         return 0;
207 }
208
209 int ED_operator_timeline_active(bContext *C)
210 {
211         return ed_spacetype_test(C, SPACE_TIME);
212 }
213
214 int ED_operator_outliner_active(bContext *C)
215 {
216         return ed_spacetype_test(C, SPACE_OUTLINER);
217 }
218
219 int ED_operator_outliner_active_no_editobject(bContext *C)
220 {
221         if (ed_spacetype_test(C, SPACE_OUTLINER)) {
222                 Object *ob = ED_object_active_context(C);
223                 Object *obedit = CTX_data_edit_object(C);
224                 if (ob && ob == obedit)
225                         return 0;
226                 else
227                         return 1;
228         }
229         return 0;
230 }
231
232 int ED_operator_file_active(bContext *C)
233 {
234         return ed_spacetype_test(C, SPACE_FILE);
235 }
236
237 int ED_operator_action_active(bContext *C)
238 {
239         return ed_spacetype_test(C, SPACE_ACTION);
240 }
241
242 int ED_operator_buttons_active(bContext *C)
243 {
244         return ed_spacetype_test(C, SPACE_BUTS);
245 }
246
247 int ED_operator_node_active(bContext *C)
248 {
249         SpaceNode *snode = CTX_wm_space_node(C);
250         
251         if (snode && snode->edittree)
252                 return 1;
253         
254         return 0;
255 }
256
257 int ED_operator_node_editable(bContext *C)
258 {
259         SpaceNode *snode = CTX_wm_space_node(C);
260         
261         if (snode && snode->edittree && !ID_IS_LINKED(snode->edittree))
262                 return 1;
263         
264         return 0;
265 }
266
267 int ED_operator_graphedit_active(bContext *C)
268 {
269         return ed_spacetype_test(C, SPACE_IPO);
270 }
271
272 int ED_operator_sequencer_active(bContext *C)
273 {
274         return ed_spacetype_test(C, SPACE_SEQ);
275 }
276
277 int ED_operator_sequencer_active_editable(bContext *C)
278 {
279         return ed_spacetype_test(C, SPACE_SEQ) && ED_operator_scene_editable(C);
280 }
281
282 int ED_operator_image_active(bContext *C)
283 {
284         return ed_spacetype_test(C, SPACE_IMAGE);
285 }
286
287 int ED_operator_nla_active(bContext *C)
288 {
289         return ed_spacetype_test(C, SPACE_NLA);
290 }
291
292 int ED_operator_logic_active(bContext *C)
293 {
294         return ed_spacetype_test(C, SPACE_LOGIC);
295 }
296
297 int ED_operator_info_active(bContext *C)
298 {
299         return ed_spacetype_test(C, SPACE_INFO);
300 }
301
302
303 int ED_operator_console_active(bContext *C)
304 {
305         return ed_spacetype_test(C, SPACE_CONSOLE);
306 }
307
308 static int ed_object_hidden(const EvaluationContext *eval_ctx, Object *ob)
309 {
310         /* if hidden but in edit mode, we still display, can happen with animation */
311         return ((ob->restrictflag & OB_RESTRICT_VIEW) && !(eval_ctx->object_mode & OB_MODE_EDIT));
312 }
313
314 int ED_operator_object_active(bContext *C)
315 {
316         EvaluationContext eval_ctx;
317         CTX_data_eval_ctx(C, &eval_ctx);
318         Object *ob = ED_object_active_context(C);
319         return ((ob != NULL) && !ed_object_hidden(&eval_ctx, ob));
320 }
321
322 int ED_operator_object_active_editable(bContext *C)
323 {
324         EvaluationContext eval_ctx;
325         CTX_data_eval_ctx(C, &eval_ctx);
326         Object *ob = ED_object_active_context(C);
327         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(&eval_ctx, ob));
328 }
329
330 int ED_operator_object_active_editable_mesh(bContext *C)
331 {
332         EvaluationContext eval_ctx;
333         CTX_data_eval_ctx(C, &eval_ctx);
334         Object *ob = ED_object_active_context(C);
335         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(&eval_ctx, ob) &&
336                 (ob->type == OB_MESH) && !ID_IS_LINKED(ob->data));
337 }
338
339 int ED_operator_object_active_editable_font(bContext *C)
340 {
341         EvaluationContext eval_ctx;
342         CTX_data_eval_ctx(C, &eval_ctx);
343         Object *ob = ED_object_active_context(C);
344         return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(&eval_ctx, ob) &&
345                 (ob->type == OB_FONT));
346 }
347
348 int ED_operator_editmesh(bContext *C)
349 {
350         Object *obedit = CTX_data_edit_object(C);
351         if (obedit && obedit->type == OB_MESH)
352                 return NULL != BKE_editmesh_from_object(obedit);
353         return 0;
354 }
355
356 int ED_operator_editmesh_view3d(bContext *C)
357 {
358         return ED_operator_editmesh(C) && ED_operator_view3d_active(C);
359 }
360
361 int ED_operator_editmesh_region_view3d(bContext *C)
362 {
363         if (ED_operator_editmesh(C) && CTX_wm_region_view3d(C))
364                 return 1;
365
366         CTX_wm_operator_poll_msg_set(C, "expected a view3d region & editmesh");
367         return 0;
368 }
369
370 int ED_operator_editarmature(bContext *C)
371 {
372         Object *obedit = CTX_data_edit_object(C);
373         if (obedit && obedit->type == OB_ARMATURE)
374                 return NULL != ((bArmature *)obedit->data)->edbo;
375         return 0;
376 }
377
378 /**
379  * \brief check for pose mode (no mixed modes)
380  *
381  * We want to enable most pose operations in weight paint mode,
382  * when it comes to transforming bones, but managing bones layers/groups
383  * can be left for pose mode only. (not weight paint mode)
384  */
385 int ED_operator_posemode_exclusive(bContext *C)
386 {
387         Object *obact = CTX_data_active_object(C);
388
389         if (obact) {
390                 EvaluationContext eval_ctx;
391                 CTX_data_eval_ctx(C, &eval_ctx);
392                 if ((eval_ctx.object_mode & OB_MODE_EDIT) == 0) {
393                         Object *obpose;
394                         if ((obpose = BKE_object_pose_armature_get(obact))) {
395                                 if (obact == obpose) {
396                                         return 1;
397                                 }
398                         }
399                 }
400         }
401
402         return 0;
403 }
404
405 /* allows for pinned pose objects to be used in the object buttons
406  * and the non-active pose object to be used in the 3D view */
407 int ED_operator_posemode_context(bContext *C)
408 {
409         Object *obpose = ED_pose_object_from_context(C);
410
411         if (obpose) {
412                 const WorkSpace *workspace = CTX_wm_workspace(C);
413                 /* TODO, should we allow this out of pose mode? */
414                 if (workspace->object_mode & OB_MODE_POSE) {
415                         // if ((workspace->object_mode & OB_MODE_EDIT) == 0) {
416                         if (BKE_object_pose_context_check(obpose)) {
417                                 return 1;
418                         }
419                         // }
420                 }
421         }
422
423         return 0;
424 }
425
426 int ED_operator_posemode(bContext *C)
427 {
428         Object *obact = CTX_data_active_object(C);
429
430
431         if (obact) {
432                 const WorkSpace *workspace = CTX_wm_workspace(C);
433                 if ((workspace->object_mode & OB_MODE_EDIT) == 0) {
434                         Object *obpose;
435                         if ((obpose = BKE_object_pose_armature_get(obact))) {
436                                 if (((workspace->object_mode & OB_MODE_POSE) && (obact == obpose)) ||
437                                     (workspace->object_mode & OB_MODE_WEIGHT_PAINT))
438                                 {
439                                         return 1;
440                                 }
441                         }
442                 }
443         }
444
445         return 0;
446 }
447
448 int ED_operator_posemode_local(bContext *C)
449 {
450         if (ED_operator_posemode(C)) {
451                 Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
452                 bArmature *arm = ob->data;
453                 return !(ID_IS_LINKED(&ob->id) ||
454                          ID_IS_LINKED(&arm->id));
455         }
456         return false;
457 }
458
459 /* wrapper for ED_space_image_show_uvedit */
460 int ED_operator_uvedit(bContext *C)
461 {
462         SpaceImage *sima = CTX_wm_space_image(C);
463         Object *obedit = CTX_data_edit_object(C);
464         return ED_space_image_show_uvedit(sima, obedit);
465 }
466
467 int ED_operator_uvedit_space_image(bContext *C)
468 {
469         SpaceImage *sima = CTX_wm_space_image(C);
470         Object *obedit = CTX_data_edit_object(C);
471         return sima && ED_space_image_show_uvedit(sima, obedit);
472 }
473
474 int ED_operator_uvmap(bContext *C)
475 {
476         Object *obedit = CTX_data_edit_object(C);
477         BMEditMesh *em = NULL;
478         
479         if (obedit && obedit->type == OB_MESH) {
480                 em = BKE_editmesh_from_object(obedit);
481         }
482         
483         if (em && (em->bm->totface)) {
484                 return true;
485         }
486         
487         return false;
488 }
489
490 int ED_operator_editsurfcurve(bContext *C)
491 {
492         Object *obedit = CTX_data_edit_object(C);
493         if (obedit && ELEM(obedit->type, OB_CURVE, OB_SURF))
494                 return NULL != ((Curve *)obedit->data)->editnurb;
495         return 0;
496 }
497
498 int ED_operator_editsurfcurve_region_view3d(bContext *C)
499 {
500         if (ED_operator_editsurfcurve(C) && CTX_wm_region_view3d(C))
501                 return 1;
502
503         CTX_wm_operator_poll_msg_set(C, "expected a view3d region & editcurve");
504         return 0;
505 }
506
507 int ED_operator_editcurve(bContext *C)
508 {
509         Object *obedit = CTX_data_edit_object(C);
510         if (obedit && obedit->type == OB_CURVE)
511                 return NULL != ((Curve *)obedit->data)->editnurb;
512         return 0;
513 }
514
515 int ED_operator_editcurve_3d(bContext *C)
516 {
517         Object *obedit = CTX_data_edit_object(C);
518         if (obedit && obedit->type == OB_CURVE) {
519                 Curve *cu = (Curve *)obedit->data;
520
521                 return (cu->flag & CU_3D) && (NULL != cu->editnurb);
522         }
523         return 0;
524 }
525
526 int ED_operator_editsurf(bContext *C)
527 {
528         Object *obedit = CTX_data_edit_object(C);
529         if (obedit && obedit->type == OB_SURF)
530                 return NULL != ((Curve *)obedit->data)->editnurb;
531         return 0;
532 }
533
534 int ED_operator_editfont(bContext *C)
535 {
536         Object *obedit = CTX_data_edit_object(C);
537         if (obedit && obedit->type == OB_FONT)
538                 return NULL != ((Curve *)obedit->data)->editfont;
539         return 0;
540 }
541
542 int ED_operator_editlattice(bContext *C)
543 {
544         Object *obedit = CTX_data_edit_object(C);
545         if (obedit && obedit->type == OB_LATTICE)
546                 return NULL != ((Lattice *)obedit->data)->editlatt;
547         return 0;
548 }
549
550 int ED_operator_editmball(bContext *C)
551 {
552         Object *obedit = CTX_data_edit_object(C);
553         if (obedit && obedit->type == OB_MBALL)
554                 return NULL != ((MetaBall *)obedit->data)->editelems;
555         return 0;
556 }
557
558 int ED_operator_mask(bContext *C)
559 {
560         EvaluationContext eval_ctx;
561         CTX_data_eval_ctx(C, &eval_ctx);
562         ScrArea *sa = CTX_wm_area(C);
563         if (sa && sa->spacedata.first) {
564                 switch (sa->spacetype) {
565                         case SPACE_CLIP:
566                         {
567                                 SpaceClip *sc = sa->spacedata.first;
568                                 return ED_space_clip_check_show_maskedit(sc);
569                         }
570                         case SPACE_SEQ:
571                         {
572                                 SpaceSeq *sseq = sa->spacedata.first;
573                                 Scene *scene = CTX_data_scene(C);
574                                 return ED_space_sequencer_check_show_maskedit(sseq, scene);
575                         }
576                         case SPACE_IMAGE:
577                         {
578                                 WorkSpace *workspace = CTX_wm_workspace(C);
579                                 SpaceImage *sima = sa->spacedata.first;
580                                 ViewLayer *view_layer = CTX_data_view_layer(C);
581                                 return ED_space_image_check_show_maskedit(sima, workspace, view_layer);
582                         }
583                 }
584         }
585
586         return false;
587 }
588
589 int ED_operator_camera(bContext *C)
590 {
591         struct Camera *cam = CTX_data_pointer_get_type(C, "camera", &RNA_Camera).data;
592         return (cam != NULL);
593 }
594
595 /** \} */
596
597 /* -------------------------------------------------------------------- */
598 /** \name Internal Screen Utilities
599  * \{ */
600
601 static int screen_active_editable(bContext *C)
602 {
603         if (ED_operator_screenactive(C)) {
604                 /* no full window splitting allowed */
605                 if (CTX_wm_screen(C)->state != SCREENNORMAL)
606                         return 0;
607                 return 1;
608         }
609         return 0;
610 }
611
612 static ARegion *screen_find_region_type(bContext *C, int type)
613 {
614         ARegion *ar = CTX_wm_region(C);
615
616         /* find the header region
617          * - try context first, but upon failing, search all regions in area...
618          */
619         if ((ar == NULL) || (ar->regiontype != type)) {
620                 ScrArea *sa = CTX_wm_area(C);
621                 ar = BKE_area_find_region_type(sa, type);
622         }
623         else {
624                 ar = NULL;
625         }
626
627         return ar;
628 }
629
630 /** \} */
631
632 /* -------------------------------------------------------------------- */
633 /** \name Action Zone Operator
634  * \{ */
635
636 /* operator state vars used:  
637  * none
638  * 
639  * functions:
640  * 
641  * apply() set actionzone event
642  * 
643  * exit()       free customdata
644  * 
645  * callbacks:
646  * 
647  * exec()       never used
648  * 
649  * invoke() check if in zone  
650  * add customdata, put mouseco and area in it
651  * add modal handler
652  * 
653  * modal()      accept modal events while doing it
654  * call apply() with gesture info, active window, nonactive window
655  * call exit() and remove handler when LMB confirm
656  */
657
658 typedef struct sActionzoneData {
659         ScrArea *sa1, *sa2;
660         AZone *az;
661         int x, y, gesture_dir, modifier;
662 } sActionzoneData;
663
664 /* quick poll to save operators to be created and handled */
665 static int actionzone_area_poll(bContext *C)
666 {
667         wmWindow *win = CTX_wm_window(C);
668         ScrArea *sa = CTX_wm_area(C);
669         
670         if (sa && win && win->eventstate) {
671                 const int *xy = &win->eventstate->x;
672                 AZone *az;
673                 
674                 for (az = sa->actionzones.first; az; az = az->next)
675                         if (BLI_rcti_isect_pt_v(&az->rect, xy))
676                                 return 1;
677         }
678         return 0;
679 }
680
681 /* the debug drawing of the click_rect is in area_draw_azone_fullscreen, keep both in sync */
682 static void fullscreen_click_rcti_init(rcti *rect, const short x1, const short y1, const short x2, const short y2)
683 {
684         int x = x2 - ((float) x2 - x1) * 0.5f / UI_DPI_FAC;
685         int y = y2 - ((float) y2 - y1) * 0.5f / UI_DPI_FAC;
686         float icon_size = UI_DPI_ICON_SIZE + 7 * UI_DPI_FAC;
687
688         /* adjust the icon distance from the corner */
689         x += 36.0f / UI_DPI_FAC;
690         y += 36.0f / UI_DPI_FAC;
691
692         /* draws from the left bottom corner of the icon */
693         x -= UI_DPI_ICON_SIZE;
694         y -= UI_DPI_ICON_SIZE;
695
696         BLI_rcti_init(rect, x, x + icon_size, y, y + icon_size);
697 }
698
699 AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2])
700 {
701         AZone *az = NULL;
702         
703         for (az = sa->actionzones.first; az; az = az->next) {
704                 if (BLI_rcti_isect_pt_v(&az->rect, xy)) {
705                         if (az->type == AZONE_AREA) {
706                                 /* no triangle intersect but a hotspot circle based on corner */
707                                 int radius = (xy[0] - az->x1) * (xy[0] - az->x1) + (xy[1] - az->y1) * (xy[1] - az->y1);
708                                 
709                                 if (radius <= AZONESPOT * AZONESPOT)
710                                         break;
711                         }
712                         else if (az->type == AZONE_REGION) {
713                                 break;
714                         }
715                         else if (az->type == AZONE_FULLSCREEN) {
716                                 int mouse_radius, spot_radius, fadein_radius, fadeout_radius;
717                                 rcti click_rect;
718
719                                 fullscreen_click_rcti_init(&click_rect, az->x1, az->y1, az->x2, az->y2);
720
721                                 if (BLI_rcti_isect_pt_v(&click_rect, xy)) {
722                                         az->alpha = 1.0f;
723                                 }
724                                 else {
725                                         mouse_radius = (xy[0] - az->x2) * (xy[0] - az->x2) + (xy[1] - az->y2) * (xy[1] - az->y2);
726                                         spot_radius = AZONESPOT * AZONESPOT;
727                                         fadein_radius = AZONEFADEIN * AZONEFADEIN;
728                                         fadeout_radius = AZONEFADEOUT * AZONEFADEOUT;
729
730                                         if (mouse_radius < spot_radius) {
731                                                 az->alpha = 1.0f;
732                                         }
733                                         else if (mouse_radius < fadein_radius) {
734                                                 az->alpha = 1.0f;
735                                         }
736                                         else if (mouse_radius < fadeout_radius) {
737                                                 az->alpha = 1.0f - ((float)(mouse_radius - fadein_radius)) / ((float)(fadeout_radius - fadein_radius));
738                                         }
739                                         else {
740                                                 az->alpha = 0.0f;
741                                         }
742
743                                         /* fade in/out but no click */
744                                         az = NULL;
745                                 }
746
747                                 /* XXX force redraw to show/hide the action zone */
748                                 ED_area_tag_redraw(sa);
749                                 break;
750                         }
751                 }
752         }
753         
754         return az;
755 }
756
757
758 static void actionzone_exit(wmOperator *op)
759 {
760         if (op->customdata)
761                 MEM_freeN(op->customdata);
762         op->customdata = NULL;
763 }
764
765 /* send EVT_ACTIONZONE event */
766 static void actionzone_apply(bContext *C, wmOperator *op, int type)
767 {
768         wmEvent event;
769         wmWindow *win = CTX_wm_window(C);
770         sActionzoneData *sad = op->customdata;
771         
772         sad->modifier = RNA_int_get(op->ptr, "modifier");
773         
774         wm_event_init_from_window(win, &event);
775
776         if (type == AZONE_AREA)
777                 event.type = EVT_ACTIONZONE_AREA;
778         else if (type == AZONE_FULLSCREEN)
779                 event.type = EVT_ACTIONZONE_FULLSCREEN;
780         else
781                 event.type = EVT_ACTIONZONE_REGION;
782
783         event.val = KM_NOTHING;
784         event.customdata = op->customdata;
785         event.customdatafree = true;
786         op->customdata = NULL;
787         
788         wm_event_add(win, &event);
789 }
790
791 static int actionzone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
792 {
793         ScrArea *sa = CTX_wm_area(C);
794         AZone *az = is_in_area_actionzone(sa, &event->x);
795         sActionzoneData *sad;
796         
797         /* quick escape */
798         if (az == NULL)
799                 return OPERATOR_PASS_THROUGH;
800         
801         /* ok we do the actionzone */
802         sad = op->customdata = MEM_callocN(sizeof(sActionzoneData), "sActionzoneData");
803         sad->sa1 = sa;
804         sad->az = az;
805         sad->x = event->x; sad->y = event->y;
806         
807         /* region azone directly reacts on mouse clicks */
808         if (ELEM(sad->az->type, AZONE_REGION, AZONE_FULLSCREEN)) {
809                 actionzone_apply(C, op, sad->az->type);
810                 actionzone_exit(op);
811                 return OPERATOR_FINISHED;
812         }
813         else {
814                 /* add modal handler */
815                 WM_event_add_modal_handler(C, op);
816                 
817                 return OPERATOR_RUNNING_MODAL;
818         }
819 }
820
821
822 static int actionzone_modal(bContext *C, wmOperator *op, const wmEvent *event)
823 {
824         wmWindow *win = CTX_wm_window(C);
825         bScreen *sc = CTX_wm_screen(C);
826         sActionzoneData *sad = op->customdata;
827         const int winsize_x = WM_window_pixels_x(win);
828         const int winsize_y = WM_window_pixels_y(win);
829
830         switch (event->type) {
831                 case MOUSEMOVE:
832                 {
833                         bool is_gesture;
834
835                         const int delta_x = (event->x - sad->x);
836                         const int delta_y = (event->y - sad->y);
837
838                         /* calculate gesture direction */
839                         if (delta_y > ABS(delta_x))
840                                 sad->gesture_dir = 'n';
841                         else if (delta_x > ABS(delta_y))
842                                 sad->gesture_dir = 'e';
843                         else if (delta_y < -ABS(delta_x))
844                                 sad->gesture_dir = 's';
845                         else
846                                 sad->gesture_dir = 'w';
847                         
848                         if (sad->az->type == AZONE_AREA) {
849                                 /* once we drag outside the actionzone, register a gesture
850                                  * check we're not on an edge so join finds the other area */
851                                 is_gesture = ((is_in_area_actionzone(sad->sa1, &event->x) != sad->az) &&
852                                               (screen_find_active_scredge(sc, winsize_x, winsize_y, event->x, event->y) == NULL));
853                         }
854                         else {
855                                 const int delta_min = 1;
856                                 is_gesture = (ABS(delta_x) > delta_min || ABS(delta_y) > delta_min);
857                         }
858
859                         /* gesture is large enough? */
860                         if (is_gesture) {
861                                 /* second area, for join when (sa1 != sa2) */
862                                 sad->sa2 = BKE_screen_find_area_xy(sc, SPACE_TYPE_ANY, event->x, event->y);
863                                 /* apply sends event */
864                                 actionzone_apply(C, op, sad->az->type);
865                                 actionzone_exit(op);
866                                 
867                                 return OPERATOR_FINISHED;
868                         }
869                         break;
870                 }
871                 case ESCKEY:
872                         actionzone_exit(op);
873                         return OPERATOR_CANCELLED;
874                 case LEFTMOUSE:
875                         actionzone_exit(op);
876                         return OPERATOR_CANCELLED;
877                         
878         }
879         
880         return OPERATOR_RUNNING_MODAL;
881 }
882
883 static void actionzone_cancel(bContext *UNUSED(C), wmOperator *op)
884 {
885         actionzone_exit(op);
886 }
887
888 static void SCREEN_OT_actionzone(wmOperatorType *ot)
889 {
890         /* identifiers */
891         ot->name = "Handle Area Action Zones";
892         ot->description = "Handle area action zones for mouse actions/gestures";
893         ot->idname = "SCREEN_OT_actionzone";
894         
895         ot->invoke = actionzone_invoke;
896         ot->modal = actionzone_modal;
897         ot->poll = actionzone_area_poll;
898         ot->cancel = actionzone_cancel;
899         
900         /* flags */
901         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
902         
903         RNA_def_int(ot->srna, "modifier", 0, 0, 2, "Modifier", "Modifier state", 0, 2);
904 }
905
906 /** \} */
907
908 /* -------------------------------------------------------------------- */
909 /** \name Swap Area Operator
910  * \{ */
911
912 /* operator state vars used:  
913  * sa1          start area
914  * sa2          area to swap with
915  * 
916  * functions:
917  * 
918  * init()   set custom data for operator, based on actionzone event custom data
919  * 
920  * cancel()     cancel the operator
921  * 
922  * exit()       cleanup, send notifier
923  * 
924  * callbacks:
925  * 
926  * invoke() gets called on shift+lmb drag in actionzone
927  * call init(), add handler
928  * 
929  * modal()  accept modal events while doing it
930  */
931
932 typedef struct sAreaSwapData {
933         ScrArea *sa1, *sa2;
934 } sAreaSwapData;
935
936 static int area_swap_init(wmOperator *op, const wmEvent *event)
937 {
938         sAreaSwapData *sd = NULL;
939         sActionzoneData *sad = event->customdata;
940         
941         if (sad == NULL || sad->sa1 == NULL)
942                 return 0;
943         
944         sd = MEM_callocN(sizeof(sAreaSwapData), "sAreaSwapData");
945         sd->sa1 = sad->sa1;
946         sd->sa2 = sad->sa2;
947         op->customdata = sd;
948         
949         return 1;
950 }
951
952
953 static void area_swap_exit(bContext *C, wmOperator *op)
954 {
955         WM_cursor_modal_restore(CTX_wm_window(C));
956         if (op->customdata)
957                 MEM_freeN(op->customdata);
958         op->customdata = NULL;
959 }
960
961 static void area_swap_cancel(bContext *C, wmOperator *op)
962 {
963         area_swap_exit(C, op);
964 }
965
966 static int area_swap_invoke(bContext *C, wmOperator *op, const wmEvent *event)
967 {
968         
969         if (!area_swap_init(op, event))
970                 return OPERATOR_PASS_THROUGH;
971         
972         /* add modal handler */
973         WM_cursor_modal_set(CTX_wm_window(C), BC_SWAPAREA_CURSOR);
974         WM_event_add_modal_handler(C, op);
975         
976         return OPERATOR_RUNNING_MODAL;
977         
978 }
979
980 static int area_swap_modal(bContext *C, wmOperator *op, const wmEvent *event)
981 {
982         sActionzoneData *sad = op->customdata;
983         
984         switch (event->type) {
985                 case MOUSEMOVE:
986                         /* second area, for join */
987                         sad->sa2 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
988                         break;
989                 case LEFTMOUSE: /* release LMB */
990                         if (event->val == KM_RELEASE) {
991                                 if (!sad->sa2 || sad->sa1 == sad->sa2) {
992                                         area_swap_cancel(C, op);
993                                         return OPERATOR_CANCELLED;
994                                 }
995
996                                 ED_area_tag_redraw(sad->sa1);
997                                 ED_area_tag_redraw(sad->sa2);
998
999                                 ED_area_swapspace(C, sad->sa1, sad->sa2);
1000                                 
1001                                 area_swap_exit(C, op);
1002                                 
1003                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1004                                 
1005                                 return OPERATOR_FINISHED;
1006                         }
1007                         break;
1008                         
1009                 case ESCKEY:
1010                         area_swap_cancel(C, op);
1011                         return OPERATOR_CANCELLED;
1012         }
1013         return OPERATOR_RUNNING_MODAL;
1014 }
1015
1016 static void SCREEN_OT_area_swap(wmOperatorType *ot)
1017 {
1018         ot->name = "Swap Areas";
1019         ot->description = "Swap selected areas screen positions";
1020         ot->idname = "SCREEN_OT_area_swap";
1021         
1022         ot->invoke = area_swap_invoke;
1023         ot->modal = area_swap_modal;
1024         ot->poll = ED_operator_areaactive;
1025         ot->cancel = area_swap_cancel;
1026         
1027         ot->flag = OPTYPE_BLOCKING;
1028 }
1029
1030 /** \} */
1031
1032 /* -------------------------------------------------------------------- */
1033 /** \name Area Duplicate Operator
1034  *
1035  * Create new window from area.
1036  * \{ */
1037
1038 /* operator callback */
1039 static int area_dupli_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1040 {
1041         wmWindow *newwin, *win = CTX_wm_window(C);
1042         Scene *scene;
1043         WorkSpace *workspace = WM_window_get_active_workspace(win);
1044         WorkSpaceLayout *layout_old = WM_window_get_active_layout(win);
1045         WorkSpaceLayout *layout_new;
1046         bScreen *newsc;
1047         ScrArea *sa;
1048         rcti rect;
1049         
1050         win = CTX_wm_window(C);
1051         scene = CTX_data_scene(C);
1052         sa = CTX_wm_area(C);
1053         
1054         /* XXX hrmf! */
1055         if (event->type == EVT_ACTIONZONE_AREA) {
1056                 sActionzoneData *sad = event->customdata;
1057                 
1058                 if (sad == NULL)
1059                         return OPERATOR_PASS_THROUGH;
1060                 
1061                 sa = sad->sa1;
1062         }
1063
1064         /* adds window to WM */
1065         rect = sa->totrct;
1066         BLI_rcti_translate(&rect, win->posx, win->posy);
1067         rect.xmax = rect.xmin + BLI_rcti_size_x(&rect) / U.pixelsize;
1068         rect.ymax = rect.ymin + BLI_rcti_size_y(&rect) / U.pixelsize;
1069
1070         newwin = WM_window_open(C, &rect);
1071         if (newwin == NULL) {
1072                 BKE_report(op->reports, RPT_ERROR, "Failed to open window!");
1073                 goto finally;
1074         }
1075
1076         *newwin->stereo3d_format = *win->stereo3d_format;
1077
1078         newwin->scene = scene;
1079
1080         WM_window_set_active_workspace(newwin, workspace);
1081         /* allocs new screen and adds to newly created window, using window size */
1082         layout_new = ED_workspace_layout_add(workspace, newwin, BKE_workspace_layout_name_get(layout_old));
1083         newsc = BKE_workspace_layout_screen_get(layout_new);
1084         WM_window_set_active_layout(newwin, workspace, layout_new);
1085
1086         /* copy area to new screen */
1087         ED_area_data_copy((ScrArea *)newsc->areabase.first, sa, true);
1088
1089         ED_area_tag_redraw((ScrArea *)newsc->areabase.first);
1090
1091         /* screen, areas init */
1092         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1093
1094
1095 finally:
1096         if (event->type == EVT_ACTIONZONE_AREA)
1097                 actionzone_exit(op);
1098         
1099         if (newwin) {
1100                 return OPERATOR_FINISHED;
1101         }
1102         else {
1103                 return OPERATOR_CANCELLED;
1104         }
1105 }
1106
1107 static void SCREEN_OT_area_dupli(wmOperatorType *ot)
1108 {
1109         ot->name = "Duplicate Area into New Window";
1110         ot->description = "Duplicate selected area into new window";
1111         ot->idname = "SCREEN_OT_area_dupli";
1112         
1113         ot->invoke = area_dupli_invoke;
1114         ot->poll = ED_operator_areaactive;
1115 }
1116
1117 /** \} */
1118
1119 /* -------------------------------------------------------------------- */
1120 /** \name Move Area Edge Operator
1121  * \{ */
1122
1123 /* operator state vars used:  
1124  * x, y             mouse coord near edge
1125  * delta            movement of edge
1126  * 
1127  * functions:
1128  * 
1129  * init()   set default property values, find edge based on mouse coords, test
1130  * if the edge can be moved, select edges, calculate min and max movement
1131  * 
1132  * apply()      apply delta on selection
1133  * 
1134  * exit()       cleanup, send notifier
1135  * 
1136  * cancel() cancel moving
1137  * 
1138  * callbacks:
1139  * 
1140  * exec()   execute without any user interaction, based on properties
1141  * call init(), apply(), exit()
1142  * 
1143  * invoke() gets called on mouse click near edge
1144  * call init(), add handler
1145  * 
1146  * modal()  accept modal events while doing it
1147  * call apply() with delta motion
1148  * call exit() and remove handler
1149  */
1150
1151 typedef struct sAreaMoveData {
1152         int bigger, smaller, origval;
1153         char dir;
1154         bool do_snap;
1155 } sAreaMoveData;
1156
1157 /* helper call to move area-edge, sets limits
1158  * need window size in order to get correct limits */
1159 static void area_move_set_limits(bScreen *sc, int dir,
1160                                  const int winsize_x, const int winsize_y,
1161                                  int *bigger, int *smaller)
1162 {
1163         ScrArea *sa;
1164         int areaminy = ED_area_headersize();
1165         int areamin;
1166         
1167         /* we check all areas and test for free space with MINSIZE */
1168         *bigger = *smaller = 100000;
1169         
1170         for (sa = sc->areabase.first; sa; sa = sa->next) {
1171                 if (dir == 'h') {
1172                         int y1;
1173                         areamin = areaminy;
1174                         
1175                         if (sa->v1->vec.y > 0)
1176                                 areamin += U.pixelsize;
1177                         if (sa->v2->vec.y < winsize_y - 1)
1178                                 areamin += U.pixelsize;
1179                         
1180                         y1 = sa->v2->vec.y - sa->v1->vec.y + 1 - areamin;
1181                         
1182                         /* if top or down edge selected, test height */
1183                         if (sa->v1->editflag && sa->v4->editflag)
1184                                 *bigger = min_ii(*bigger, y1);
1185                         else if (sa->v2->editflag && sa->v3->editflag)
1186                                 *smaller = min_ii(*smaller, y1);
1187                 }
1188                 else {
1189                         int x1;
1190                         areamin = AREAMINX;
1191                         
1192                         if (sa->v1->vec.x > 0)
1193                                 areamin += U.pixelsize;
1194                         if (sa->v4->vec.x < winsize_x - 1)
1195                                 areamin += U.pixelsize;
1196                         
1197                         x1 = sa->v4->vec.x - sa->v1->vec.x + 1 - areamin;
1198                         
1199                         /* if left or right edge selected, test width */
1200                         if (sa->v1->editflag && sa->v2->editflag)
1201                                 *bigger = min_ii(*bigger, x1);
1202                         else if (sa->v3->editflag && sa->v4->editflag)
1203                                 *smaller = min_ii(*smaller, x1);
1204                 }
1205         }
1206 }
1207
1208 /* validate selection inside screen, set variables OK */
1209 /* return 0: init failed */
1210 static int area_move_init(bContext *C, wmOperator *op)
1211 {
1212         bScreen *sc = CTX_wm_screen(C);
1213         wmWindow *win = CTX_wm_window(C);
1214         ScrEdge *actedge;
1215         sAreaMoveData *md;
1216         ScrVert *v1;
1217         const int winsize_x = WM_window_pixels_x(win);
1218         const int winsize_y = WM_window_pixels_y(win);
1219         int x, y;
1220         
1221         /* required properties */
1222         x = RNA_int_get(op->ptr, "x");
1223         y = RNA_int_get(op->ptr, "y");
1224         
1225         /* setup */
1226         actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, x, y);
1227         if (actedge == NULL) return 0;
1228         
1229         md = MEM_callocN(sizeof(sAreaMoveData), "sAreaMoveData");
1230         op->customdata = md;
1231         
1232         md->dir = scredge_is_horizontal(actedge) ? 'h' : 'v';
1233         if (md->dir == 'h') md->origval = actedge->v1->vec.y;
1234         else md->origval = actedge->v1->vec.x;
1235         
1236         select_connected_scredge(sc, actedge);
1237         /* now all vertices with 'flag==1' are the ones that can be moved. Move this to editflag */
1238         for (v1 = sc->vertbase.first; v1; v1 = v1->next)
1239                 v1->editflag = v1->flag;
1240         
1241         area_move_set_limits(sc, md->dir, winsize_x, winsize_y, &md->bigger, &md->smaller);
1242         
1243         return 1;
1244 }
1245
1246 static int area_snap_calc_location(
1247         const bScreen *sc, const int delta,
1248         const int origval, const int dir,
1249         const int bigger, const int smaller)
1250 {
1251         int final_loc = -1;
1252
1253         const int m_loc = origval + delta;
1254         const int axis = (dir == 'v') ? 0 : 1;
1255         int snap_dist;
1256         int dist;
1257         {
1258                 /* Test the snap to middle. */
1259                 int middle = origval + (bigger - smaller) / 2;
1260                 middle -= (middle % AREAGRID);
1261
1262                 snap_dist = abs(m_loc - middle);
1263                 final_loc = middle;
1264         }
1265
1266         for (const ScrVert *v1 = sc->vertbase.first; v1; v1 = v1->next) {
1267                 if (v1->editflag) {
1268                         const int v_loc = (&v1->vec.x)[!axis];
1269
1270                         for (const ScrVert *v2 = sc->vertbase.first; v2; v2 = v2->next) {
1271                                 if (!v2->editflag) {
1272                                         if (v_loc == (&v2->vec.x)[!axis]) {
1273                                                 const int v_loc2 = (&v2->vec.x)[axis];
1274                                                 /* Do not snap to the vertices at the ends. */
1275                                                 if ((origval - smaller) < v_loc2 && v_loc2 < (origval + bigger)) {
1276                                                         dist = abs(m_loc - v_loc2);
1277                                                         if (dist <= snap_dist) {
1278                                                                 snap_dist = dist;
1279                                                                 final_loc = v_loc2;
1280                                                         }
1281                                                 }
1282                                         }
1283                                 }
1284                         }
1285                 }
1286         }
1287
1288         return final_loc;
1289 }
1290
1291 /* moves selected screen edge amount of delta, used by split & move */
1292 static void area_move_apply_do(
1293         const bContext *C, int delta,
1294         const int origval, const int dir,
1295         const int bigger, const int smaller,
1296         const bool do_snap)
1297 {
1298         bScreen *sc = CTX_wm_screen(C);
1299         ScrVert *v1;
1300         bool doredraw = false;
1301         CLAMP(delta, -smaller, bigger);
1302
1303         short final_loc = -1;
1304
1305         if (do_snap) {
1306                 final_loc = area_snap_calc_location(sc, delta, origval, dir, bigger, smaller);
1307         }
1308         else {
1309                 final_loc = origval + delta;
1310                 if (delta != bigger && delta != -smaller) {
1311                         final_loc -= (final_loc % AREAGRID);
1312                 }
1313         }
1314
1315         BLI_assert(final_loc != -1);
1316         short axis = (dir == 'v') ? 0 : 1;
1317
1318         for (v1 = sc->vertbase.first; v1; v1 = v1->next) {
1319                 if (v1->editflag) {
1320                         short oldval = (&v1->vec.x)[axis];
1321                         (&v1->vec.x)[axis] = final_loc;
1322
1323                         if (oldval == final_loc) {
1324                                 /* nothing will change to the other vertices either. */
1325                                 break;
1326                         }
1327                         doredraw = true;
1328                 }
1329         }
1330
1331         /* only redraw if we actually moved a screen vert, for AREAGRID */
1332         if (doredraw) {
1333                 for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
1334                         if (sa->v1->editflag || sa->v2->editflag || sa->v3->editflag || sa->v4->editflag) {
1335                                 ED_area_tag_redraw(sa);
1336                         }
1337                 }
1338                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL); /* redraw everything */
1339                 /* Update preview thumbnail */
1340                 BKE_icon_changed(sc->id.icon_id);
1341         }
1342 }
1343
1344 static void area_move_apply(bContext *C, wmOperator *op)
1345 {
1346         sAreaMoveData *md = op->customdata;
1347         int delta = RNA_int_get(op->ptr, "delta");
1348
1349         area_move_apply_do(C, delta, md->origval, md->dir, md->bigger, md->smaller, md->do_snap);
1350 }
1351
1352 static void area_move_exit(bContext *C, wmOperator *op)
1353 {
1354         if (op->customdata)
1355                 MEM_freeN(op->customdata);
1356         op->customdata = NULL;
1357         
1358         /* this makes sure aligned edges will result in aligned grabbing */
1359         removedouble_scrverts(CTX_wm_screen(C));
1360         removedouble_scredges(CTX_wm_screen(C));
1361 }
1362
1363 static int area_move_exec(bContext *C, wmOperator *op)
1364 {
1365         if (!area_move_init(C, op))
1366                 return OPERATOR_CANCELLED;
1367         
1368         area_move_apply(C, op);
1369         area_move_exit(C, op);
1370         
1371         return OPERATOR_FINISHED;
1372 }
1373
1374 /* interaction callback */
1375 static int area_move_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1376 {
1377         RNA_int_set(op->ptr, "x", event->x);
1378         RNA_int_set(op->ptr, "y", event->y);
1379         
1380         if (!area_move_init(C, op)) 
1381                 return OPERATOR_PASS_THROUGH;
1382         
1383         /* add temp handler */
1384         WM_event_add_modal_handler(C, op);
1385         
1386         return OPERATOR_RUNNING_MODAL;
1387 }
1388
1389 static void area_move_cancel(bContext *C, wmOperator *op)
1390 {
1391         
1392         RNA_int_set(op->ptr, "delta", 0);
1393         area_move_apply(C, op);
1394         area_move_exit(C, op);
1395 }
1396
1397 /* modal callback for while moving edges */
1398 static int area_move_modal(bContext *C, wmOperator *op, const wmEvent *event)
1399 {
1400         sAreaMoveData *md = op->customdata;
1401         int delta, x, y;
1402         
1403         /* execute the events */
1404         switch (event->type) {
1405                 case MOUSEMOVE:
1406                 {
1407                         x = RNA_int_get(op->ptr, "x");
1408                         y = RNA_int_get(op->ptr, "y");
1409                         
1410                         delta = (md->dir == 'v') ? event->x - x : event->y - y;
1411                         RNA_int_set(op->ptr, "delta", delta);
1412                         
1413                         area_move_apply(C, op);
1414                         break;
1415                 }
1416                 case EVT_MODAL_MAP:
1417                 {
1418                         switch (event->val) {
1419                                 case KM_MODAL_APPLY:
1420                                         area_move_exit(C, op);
1421                                         return OPERATOR_FINISHED;
1422                                         
1423                                 case KM_MODAL_CANCEL:
1424                                         area_move_cancel(C, op);
1425                                         return OPERATOR_CANCELLED;
1426
1427                                 case KM_MODAL_SNAP_ON:
1428                                         md->do_snap = true;
1429                                         break;
1430                                 case KM_MODAL_SNAP_OFF:
1431                                         md->do_snap = false;
1432                                         break;
1433                         }
1434                         break;
1435                 }
1436         }
1437         
1438         return OPERATOR_RUNNING_MODAL;
1439 }
1440
1441 static void SCREEN_OT_area_move(wmOperatorType *ot)
1442 {
1443         /* identifiers */
1444         ot->name = "Move Area Edges";
1445         ot->description = "Move selected area edges";
1446         ot->idname = "SCREEN_OT_area_move";
1447         
1448         ot->exec = area_move_exec;
1449         ot->invoke = area_move_invoke;
1450         ot->cancel = area_move_cancel;
1451         ot->modal = area_move_modal;
1452         ot->poll = ED_operator_screen_mainwinactive; /* when mouse is over area-edge */
1453         
1454         /* flags */
1455         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
1456         
1457         /* rna */
1458         RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
1459         RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
1460         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
1461 }
1462
1463 /** \} */
1464
1465 /* -------------------------------------------------------------------- */
1466 /** \name Split Area Operator
1467  * \{ */
1468
1469 /* 
1470  * operator state vars:  
1471  * fac              spit point
1472  * dir              direction 'v' or 'h'
1473  * 
1474  * operator customdata:
1475  * area             pointer to (active) area
1476  * x, y                 last used mouse pos
1477  * (more, see below)
1478  * 
1479  * functions:
1480  * 
1481  * init()   set default property values, find area based on context
1482  * 
1483  * apply()      split area based on state vars
1484  * 
1485  * exit()       cleanup, send notifier
1486  * 
1487  * cancel() remove duplicated area
1488  * 
1489  * callbacks:
1490  * 
1491  * exec()   execute without any user interaction, based on state vars
1492  * call init(), apply(), exit()
1493  * 
1494  * invoke() gets called on mouse click in action-widget
1495  * call init(), add modal handler
1496  * call apply() with initial motion
1497  * 
1498  * modal()  accept modal events while doing it
1499  * call move-areas code with delta motion
1500  * call exit() or cancel() and remove handler
1501  */
1502
1503 typedef struct sAreaSplitData {
1504         int origval;            /* for move areas */
1505         int bigger, smaller;    /* constraints for moving new edge */
1506         int delta;              /* delta move edge */
1507         int origmin, origsize;  /* to calculate fac, for property storage */
1508         int previewmode;        /* draw previewline, then split */
1509         void *draw_callback;    /* call `ED_screen_draw_split_preview` */
1510         bool do_snap;
1511
1512         ScrEdge *nedge;         /* new edge */
1513         ScrArea *sarea;         /* start area */
1514         ScrArea *narea;         /* new area */
1515         
1516 } sAreaSplitData;
1517
1518 static void area_split_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
1519 {
1520         const wmOperator *op = userdata;
1521
1522         sAreaSplitData *sd = op->customdata;
1523         if (sd->sarea) {
1524                 int dir = RNA_enum_get(op->ptr, "direction");
1525                 float fac = RNA_float_get(op->ptr, "factor");
1526
1527                 ED_screen_draw_split_preview(sd->sarea, dir, fac);
1528         }
1529 }
1530
1531 /* generic init, menu case, doesn't need active area */
1532 static int area_split_menu_init(bContext *C, wmOperator *op)
1533 {
1534         sAreaSplitData *sd;
1535         
1536         /* custom data */
1537         sd = (sAreaSplitData *)MEM_callocN(sizeof(sAreaSplitData), "op_area_split");
1538         op->customdata = sd;
1539         
1540         sd->sarea = CTX_wm_area(C);
1541
1542         return 1;
1543 }
1544
1545 /* generic init, no UI stuff here, assumes active area */
1546 static int area_split_init(bContext *C, wmOperator *op)
1547 {
1548         ScrArea *sa = CTX_wm_area(C);
1549         sAreaSplitData *sd;
1550         int areaminy = ED_area_headersize() + 1;
1551         int dir;
1552         
1553         /* required context */
1554         if (sa == NULL) return 0;
1555         
1556         /* required properties */
1557         dir = RNA_enum_get(op->ptr, "direction");
1558         
1559         /* minimal size */
1560         if (dir == 'v' && sa->winx < 2 * AREAMINX) return 0;
1561         if (dir == 'h' && sa->winy < 2 * areaminy) return 0;
1562         
1563         /* custom data */
1564         sd = (sAreaSplitData *)MEM_callocN(sizeof(sAreaSplitData), "op_area_split");
1565         op->customdata = sd;
1566         
1567         sd->sarea = sa;
1568         sd->origsize = dir == 'v' ? sa->winx : sa->winy;
1569         sd->origmin = dir == 'v' ? sa->totrct.xmin : sa->totrct.ymin;
1570         
1571         return 1;
1572 }
1573
1574 /* with sa as center, sb is located at: 0=W, 1=N, 2=E, 3=S */
1575 /* used with split operator */
1576 static ScrEdge *area_findsharededge(bScreen *screen, ScrArea *sa, ScrArea *sb)
1577 {
1578         ScrVert *sav1 = sa->v1;
1579         ScrVert *sav2 = sa->v2;
1580         ScrVert *sav3 = sa->v3;
1581         ScrVert *sav4 = sa->v4;
1582         ScrVert *sbv1 = sb->v1;
1583         ScrVert *sbv2 = sb->v2;
1584         ScrVert *sbv3 = sb->v3;
1585         ScrVert *sbv4 = sb->v4;
1586         
1587         if (sav1 == sbv4 && sav2 == sbv3) { /* sa to right of sb = W */
1588                 return screen_findedge(screen, sav1, sav2);
1589         }
1590         else if (sav2 == sbv1 && sav3 == sbv4) { /* sa to bottom of sb = N */
1591                 return screen_findedge(screen, sav2, sav3);
1592         }
1593         else if (sav3 == sbv2 && sav4 == sbv1) { /* sa to left of sb = E */
1594                 return screen_findedge(screen, sav3, sav4);
1595         }
1596         else if (sav1 == sbv2 && sav4 == sbv3) { /* sa on top of sb = S*/
1597                 return screen_findedge(screen, sav1, sav4);
1598         }
1599         
1600         return NULL;
1601 }
1602
1603
1604 /* do the split, return success */
1605 static int area_split_apply(bContext *C, wmOperator *op)
1606 {
1607         bScreen *sc = CTX_wm_screen(C);
1608         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1609         float fac;
1610         int dir;
1611         
1612         fac = RNA_float_get(op->ptr, "factor");
1613         dir = RNA_enum_get(op->ptr, "direction");
1614         
1615         sd->narea = area_split(sc, sd->sarea, dir, fac, 0); /* 0 = no merge */
1616         
1617         if (sd->narea) {
1618                 ScrVert *sv;
1619                 
1620                 sd->nedge = area_findsharededge(sc, sd->sarea, sd->narea);
1621                 
1622                 /* select newly created edge, prepare for moving edge */
1623                 for (sv = sc->vertbase.first; sv; sv = sv->next)
1624                         sv->editflag = 0;
1625                 
1626                 sd->nedge->v1->editflag = 1;
1627                 sd->nedge->v2->editflag = 1;
1628                 
1629                 if (dir == 'h') sd->origval = sd->nedge->v1->vec.y;
1630                 else sd->origval = sd->nedge->v1->vec.x;
1631
1632                 ED_area_tag_redraw(sd->sarea);
1633                 ED_area_tag_redraw(sd->narea);
1634
1635                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1636                 /* Update preview thumbnail */
1637                 BKE_icon_changed(sc->id.icon_id);
1638
1639                 return 1;
1640         }
1641         
1642         return 0;
1643 }
1644
1645 static void area_split_exit(bContext *C, wmOperator *op)
1646 {
1647         if (op->customdata) {
1648                 sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1649                 if (sd->sarea) ED_area_tag_redraw(sd->sarea);
1650                 if (sd->narea) ED_area_tag_redraw(sd->narea);
1651
1652                 if (sd->draw_callback)
1653                         WM_draw_cb_exit(CTX_wm_window(C), sd->draw_callback);
1654
1655                 MEM_freeN(op->customdata);
1656                 op->customdata = NULL;
1657         }
1658         
1659         WM_cursor_modal_restore(CTX_wm_window(C));
1660         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1661         
1662         /* this makes sure aligned edges will result in aligned grabbing */
1663         removedouble_scrverts(CTX_wm_screen(C));
1664         removedouble_scredges(CTX_wm_screen(C));
1665 }
1666
1667 static void area_split_preview_update_cursor(bContext *C, wmOperator *op)
1668 {
1669         wmWindow *win = CTX_wm_window(C);
1670         int dir = RNA_enum_get(op->ptr, "direction");
1671         WM_cursor_set(win, (dir == 'v') ? CURSOR_X_MOVE : CURSOR_Y_MOVE);
1672 }
1673
1674 /* UI callback, adds new handler */
1675 static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1676 {
1677         wmWindow *win = CTX_wm_window(C);
1678         bScreen *sc = CTX_wm_screen(C);
1679         sAreaSplitData *sd;
1680         const int winsize_x = WM_window_pixels_x(win);
1681         const int winsize_y = WM_window_pixels_y(win);
1682         int dir;
1683         
1684         /* no full window splitting allowed */
1685         if (sc->state != SCREENNORMAL)
1686                 return OPERATOR_CANCELLED;
1687         
1688         if (event->type == EVT_ACTIONZONE_AREA) {
1689                 sActionzoneData *sad = event->customdata;
1690                 
1691                 if (sad == NULL || sad->modifier > 0) {
1692                         return OPERATOR_PASS_THROUGH;
1693                 }
1694                 
1695                 /* verify *sad itself */
1696                 if (sad->sa1 == NULL || sad->az == NULL)
1697                         return OPERATOR_PASS_THROUGH;
1698                 
1699                 /* is this our *sad? if areas not equal it should be passed on */
1700                 if (CTX_wm_area(C) != sad->sa1 || sad->sa1 != sad->sa2)
1701                         return OPERATOR_PASS_THROUGH;
1702                 
1703                 /* prepare operator state vars */
1704                 if (sad->gesture_dir == 'n' || sad->gesture_dir == 's') {
1705                         dir = 'h';
1706                         RNA_float_set(op->ptr, "factor", ((float)(event->x - sad->sa1->v1->vec.x)) / (float)sad->sa1->winx);
1707                 }
1708                 else {
1709                         dir = 'v';
1710                         RNA_float_set(op->ptr, "factor", ((float)(event->y - sad->sa1->v1->vec.y)) / (float)sad->sa1->winy);
1711                 }
1712                 RNA_enum_set(op->ptr, "direction", dir);
1713                 
1714                 /* general init, also non-UI case, adds customdata, sets area and defaults */
1715                 if (!area_split_init(C, op))
1716                         return OPERATOR_PASS_THROUGH;
1717                 
1718         }
1719         else {
1720                 ScrEdge *actedge;
1721                 int x, y;
1722                 
1723                 /* retrieve initial mouse coord, so we can find the active edge */
1724                 if (RNA_struct_property_is_set(op->ptr, "mouse_x"))
1725                         x = RNA_int_get(op->ptr, "mouse_x");
1726                 else
1727                         x = event->x;
1728                 
1729                 if (RNA_struct_property_is_set(op->ptr, "mouse_y"))
1730                         y = RNA_int_get(op->ptr, "mouse_y");
1731                 else
1732                         y = event->x;
1733                 
1734                 actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, x, y);
1735                 if (actedge == NULL)
1736                         return OPERATOR_CANCELLED;
1737                 
1738                 dir = scredge_is_horizontal(actedge) ? 'v' : 'h';
1739                 
1740                 RNA_enum_set(op->ptr, "direction", dir);
1741                 
1742                 /* special case, adds customdata, sets defaults */
1743                 if (!area_split_menu_init(C, op))
1744                         return OPERATOR_CANCELLED;
1745                 
1746         }
1747         
1748         sd = (sAreaSplitData *)op->customdata;
1749         
1750         if (event->type == EVT_ACTIONZONE_AREA) {
1751                 
1752                 /* do the split */
1753                 if (area_split_apply(C, op)) {
1754                         area_move_set_limits(sc, dir, winsize_x, winsize_y, &sd->bigger, &sd->smaller);
1755                         
1756                         /* add temp handler for edge move or cancel */
1757                         WM_event_add_modal_handler(C, op);
1758                         
1759                         return OPERATOR_RUNNING_MODAL;
1760                 }
1761         }
1762         else {
1763                 sd->previewmode = 1;
1764                 sd->draw_callback = WM_draw_cb_activate(win, area_split_draw_cb, op);
1765                 /* add temp handler for edge move or cancel */
1766                 WM_event_add_modal_handler(C, op);
1767                 area_split_preview_update_cursor(C, op);
1768
1769                 return OPERATOR_RUNNING_MODAL;
1770                 
1771         }
1772         
1773         return OPERATOR_PASS_THROUGH;
1774 }
1775
1776 /* function to be called outside UI context, or for redo */
1777 static int area_split_exec(bContext *C, wmOperator *op)
1778 {
1779         
1780         if (!area_split_init(C, op))
1781                 return OPERATOR_CANCELLED;
1782         
1783         area_split_apply(C, op);
1784         area_split_exit(C, op);
1785         
1786         return OPERATOR_FINISHED;
1787 }
1788
1789
1790 static void area_split_cancel(bContext *C, wmOperator *op)
1791 {
1792         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1793         
1794         if (sd->previewmode) {
1795         }
1796         else {
1797                 if (screen_area_join(C, CTX_wm_screen(C), sd->sarea, sd->narea)) {
1798                         if (CTX_wm_area(C) == sd->narea) {
1799                                 CTX_wm_area_set(C, NULL);
1800                                 CTX_wm_region_set(C, NULL);
1801                         }
1802                         sd->narea = NULL;
1803                 }
1804         }
1805         area_split_exit(C, op);
1806 }
1807
1808 static int area_split_modal(bContext *C, wmOperator *op, const wmEvent *event)
1809 {
1810         sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
1811         PropertyRNA *prop_dir = RNA_struct_find_property(op->ptr, "direction");
1812         bool update_factor = false;
1813
1814         /* execute the events */
1815         switch (event->type) {
1816                 case MOUSEMOVE:
1817                         update_factor = true;
1818                         break;
1819
1820                 case LEFTMOUSE:
1821                         if (sd->previewmode) {
1822                                 area_split_apply(C, op);
1823                                 area_split_exit(C, op);
1824                                 return OPERATOR_FINISHED;
1825                         }
1826                         else {
1827                                 if (event->val == KM_RELEASE) { /* mouse up */
1828                                         area_split_exit(C, op);
1829                                         return OPERATOR_FINISHED;
1830                                 }
1831                         }
1832                         break;
1833                         
1834                 case MIDDLEMOUSE:
1835                 case TABKEY:
1836                         if (sd->previewmode == 0) {
1837                                 /* pass */
1838                         }
1839                         else {
1840                                 if (event->val == KM_PRESS) {
1841                                         if (sd->sarea) {
1842                                                 int dir = RNA_property_enum_get(op->ptr, prop_dir);
1843                                                 RNA_property_enum_set(op->ptr, prop_dir, (dir == 'v') ? 'h' : 'v');
1844                                                 area_split_preview_update_cursor(C, op);
1845                                                 update_factor = true;
1846                                         }
1847                                 }
1848                         }
1849                         
1850                         break;
1851                         
1852                 case RIGHTMOUSE: /* cancel operation */
1853                 case ESCKEY:
1854                         area_split_cancel(C, op);
1855                         return OPERATOR_CANCELLED;
1856
1857                 case LEFTCTRLKEY:
1858                         sd->do_snap = event->val == KM_PRESS;
1859                         update_factor = true;
1860                         break;
1861         }
1862
1863         if (update_factor) {
1864                 const int dir = RNA_property_enum_get(op->ptr, prop_dir);
1865
1866                 sd->delta = (dir == 'v') ? event->x - sd->origval : event->y - sd->origval;
1867
1868                 if (sd->previewmode == 0) {
1869                         if (sd->do_snap) {
1870                                 const int snap_loc = area_snap_calc_location(
1871                                         CTX_wm_screen(C), sd->delta, sd->origval, dir, sd->bigger, sd->smaller);
1872                                 sd->delta = snap_loc - sd->origval;
1873                         }
1874                         area_move_apply_do(C, sd->delta, sd->origval, dir, sd->bigger, sd->smaller, false);
1875                 }
1876                 else {
1877                         if (sd->sarea) {
1878                                 ED_area_tag_redraw(sd->sarea);
1879                         }
1880                         /* area context not set */
1881                         sd->sarea = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
1882
1883                         if (sd->sarea) {
1884                                 ScrArea *sa = sd->sarea;
1885                                 if (dir == 'v') {
1886                                         sd->origsize = sa->winx;
1887                                         sd->origmin = sa->totrct.xmin;
1888                                 }
1889                                 else {
1890                                         sd->origsize = sa->winy;
1891                                         sd->origmin = sa->totrct.ymin;
1892                                 }
1893
1894                                 if (sd->do_snap) {
1895                                         sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 1;
1896
1897                                         const int snap_loc = area_snap_calc_location(
1898                                                 CTX_wm_screen(C), sd->delta, sd->origval, dir, sd->origmin + sd->origsize, -sd->origmin);
1899
1900                                         sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 0;
1901                                         sd->delta = snap_loc - sd->origval;
1902                                 }
1903
1904                                 ED_area_tag_redraw(sd->sarea);
1905                         }
1906
1907                         CTX_wm_screen(C)->do_draw = true;
1908                 }
1909
1910                 float fac = (float)(sd->delta + sd->origval - sd->origmin) / sd->origsize;
1911                 RNA_float_set(op->ptr, "factor", fac);
1912         }
1913
1914         return OPERATOR_RUNNING_MODAL;
1915 }
1916
1917 static const EnumPropertyItem prop_direction_items[] = {
1918         {'h', "HORIZONTAL", 0, "Horizontal", ""},
1919         {'v', "VERTICAL", 0, "Vertical", ""},
1920         {0, NULL, 0, NULL, NULL}
1921 };
1922
1923 static void SCREEN_OT_area_split(wmOperatorType *ot)
1924 {
1925         ot->name = "Split Area";
1926         ot->description = "Split selected area into new windows";
1927         ot->idname = "SCREEN_OT_area_split";
1928         
1929         ot->exec = area_split_exec;
1930         ot->invoke = area_split_invoke;
1931         ot->modal = area_split_modal;
1932         ot->cancel = area_split_cancel;
1933         
1934         ot->poll = screen_active_editable;
1935
1936         /* flags */
1937         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
1938         
1939         /* rna */
1940         RNA_def_enum(ot->srna, "direction", prop_direction_items, 'h', "Direction", "");
1941         RNA_def_float(ot->srna, "factor", 0.5f, 0.0, 1.0, "Factor", "", 0.0, 1.0);
1942         RNA_def_int(ot->srna, "mouse_x", -100, INT_MIN, INT_MAX, "Mouse X", "", INT_MIN, INT_MAX);
1943         RNA_def_int(ot->srna, "mouse_y", -100, INT_MIN, INT_MAX, "Mouse Y", "", INT_MIN, INT_MAX);
1944 }
1945
1946 /** \} */
1947
1948 /* -------------------------------------------------------------------- */
1949 /** \name Scale Region Edge Operator
1950  * \{ */
1951
1952 typedef struct RegionMoveData {
1953         AZone *az;
1954         ARegion *ar;
1955         ScrArea *sa;
1956         int bigger, smaller, origval;
1957         int origx, origy;
1958         int maxsize;
1959         AZEdge edge;
1960         
1961 } RegionMoveData;
1962
1963
1964 static int area_max_regionsize(ScrArea *sa, ARegion *scalear, AZEdge edge)
1965 {
1966         ARegion *ar;
1967         int dist;
1968         
1969         if (edge == AE_RIGHT_TO_TOPLEFT || edge == AE_LEFT_TO_TOPRIGHT) {
1970                 dist = BLI_rcti_size_x(&sa->totrct);
1971         }
1972         else {  /* AE_BOTTOM_TO_TOPLEFT, AE_TOP_TO_BOTTOMRIGHT */
1973                 dist = BLI_rcti_size_y(&sa->totrct);
1974         }
1975         
1976         /* subtractwidth of regions on opposite side 
1977          * prevents dragging regions into other opposite regions */
1978         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1979                 if (ar == scalear)
1980                         continue;
1981                 
1982                 if (scalear->alignment == RGN_ALIGN_TOP && ar->alignment == RGN_ALIGN_BOTTOM)
1983                         dist -= ar->winy;
1984                 else if (scalear->alignment == RGN_ALIGN_BOTTOM && ar->alignment == RGN_ALIGN_TOP)
1985                         dist -= ar->winy;
1986                 else if (scalear->alignment == RGN_ALIGN_LEFT && ar->alignment == RGN_ALIGN_RIGHT)
1987                         dist -= ar->winx;
1988                 else if (scalear->alignment == RGN_ALIGN_RIGHT && ar->alignment == RGN_ALIGN_LEFT)
1989                         dist -= ar->winx;
1990                 
1991                 /* case of regions in regions, like operator properties panel */
1992                 /* these can sit on top of other regions such as headers, so account for this */
1993                 else if (edge == AE_BOTTOM_TO_TOPLEFT && scalear->alignment & RGN_ALIGN_TOP &&
1994                          ar->alignment == RGN_ALIGN_TOP && ar->regiontype == RGN_TYPE_HEADER)
1995                 {
1996                         dist -= ar->winy;
1997                 }
1998                 else if (edge == AE_TOP_TO_BOTTOMRIGHT && scalear->alignment & RGN_ALIGN_BOTTOM &&
1999                          ar->alignment == RGN_ALIGN_BOTTOM && ar->regiontype == RGN_TYPE_HEADER)
2000                 {
2001                         dist -= ar->winy;
2002                 }
2003         }
2004
2005         return dist;
2006 }
2007
2008 static int region_scale_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2009 {
2010         sActionzoneData *sad = event->customdata;
2011         AZone *az;
2012         
2013         if (event->type != EVT_ACTIONZONE_REGION) {
2014                 BKE_report(op->reports, RPT_ERROR, "Can only scale region size from an action zone");
2015                 return OPERATOR_CANCELLED;
2016         }
2017         
2018         az = sad->az;
2019         
2020         if (az->ar) {
2021                 RegionMoveData *rmd = MEM_callocN(sizeof(RegionMoveData), "RegionMoveData");
2022                 int maxsize;
2023                 
2024                 op->customdata = rmd;
2025                 
2026                 rmd->az = az;
2027                 rmd->ar = az->ar;
2028                 rmd->sa = sad->sa1;
2029                 rmd->edge = az->edge;
2030                 rmd->origx = event->x;
2031                 rmd->origy = event->y;
2032                 rmd->maxsize = area_max_regionsize(rmd->sa, rmd->ar, rmd->edge);
2033                 
2034                 /* if not set we do now, otherwise it uses type */
2035                 if (rmd->ar->sizex == 0)
2036                         rmd->ar->sizex = rmd->ar->winx;
2037                 if (rmd->ar->sizey == 0)
2038                         rmd->ar->sizey = rmd->ar->winy;
2039                 
2040                 /* now copy to regionmovedata */
2041                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
2042                         rmd->origval = rmd->ar->sizex;
2043                 }
2044                 else {
2045                         rmd->origval = rmd->ar->sizey;
2046                 }
2047                 
2048                 /* limit headers to standard height for now */
2049                 if (rmd->ar->regiontype == RGN_TYPE_HEADER)
2050                         maxsize = ED_area_headersize();
2051                 else
2052                         maxsize = 1000;
2053                 
2054                 CLAMP(rmd->maxsize, 0, maxsize);
2055                 
2056                 /* add temp handler */
2057                 WM_event_add_modal_handler(C, op);
2058                 
2059                 return OPERATOR_RUNNING_MODAL;
2060         }
2061         
2062         return OPERATOR_FINISHED;
2063 }
2064
2065 static int region_scale_get_maxsize(RegionMoveData *rmd)
2066 {
2067         int maxsize = 0;
2068
2069         if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
2070                 return  (int) ( (rmd->sa->winx / UI_DPI_FAC) - UI_UNIT_X);
2071         }
2072
2073         if (rmd->ar->regiontype == RGN_TYPE_TOOL_PROPS) {
2074                 /* this calculation seems overly verbose
2075                  * can someone explain why this method is necessary? - campbell */
2076                 maxsize = rmd->maxsize - ((rmd->sa->headertype == HEADERTOP) ? UI_UNIT_Y * 2 : UI_UNIT_Y) - (UI_UNIT_Y / 4);
2077         }
2078
2079         return maxsize;
2080 }
2081
2082 static void region_scale_validate_size(RegionMoveData *rmd)
2083 {
2084         if ((rmd->ar->flag & RGN_FLAG_HIDDEN) == 0) {
2085                 short *size, maxsize = -1;
2086
2087
2088                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT)
2089                         size = &rmd->ar->sizex;
2090                 else
2091                         size = &rmd->ar->sizey;
2092
2093                 maxsize = region_scale_get_maxsize(rmd);
2094
2095                 if (*size > maxsize && maxsize > 0)
2096                         *size = maxsize;
2097         }
2098 }
2099
2100 static void region_scale_toggle_hidden(bContext *C, RegionMoveData *rmd)
2101 {
2102         /* hidden areas may have bad 'View2D.cur' value,
2103          * correct before displaying. see T45156 */
2104         if (rmd->ar->flag & RGN_FLAG_HIDDEN) {
2105                 UI_view2d_curRect_validate(&rmd->ar->v2d);
2106         }
2107
2108         region_toggle_hidden(C, rmd->ar, 0);
2109         region_scale_validate_size(rmd);
2110 }
2111
2112 static int region_scale_modal(bContext *C, wmOperator *op, const wmEvent *event)
2113 {
2114         RegionMoveData *rmd = op->customdata;
2115         int delta;
2116         
2117         /* execute the events */
2118         switch (event->type) {
2119                 case MOUSEMOVE:
2120                         
2121                         if (rmd->edge == AE_LEFT_TO_TOPRIGHT || rmd->edge == AE_RIGHT_TO_TOPLEFT) {
2122                                 delta = event->x - rmd->origx;
2123                                 if (rmd->edge == AE_LEFT_TO_TOPRIGHT) delta = -delta;
2124                                 
2125                                 /* region sizes now get multiplied */
2126                                 delta /= UI_DPI_FAC;
2127                                 
2128                                 rmd->ar->sizex = rmd->origval + delta;
2129                                 CLAMP(rmd->ar->sizex, 0, rmd->maxsize);
2130                                 
2131                                 if (rmd->ar->sizex < UI_UNIT_X) {
2132                                         rmd->ar->sizex = rmd->origval;
2133                                         if (!(rmd->ar->flag & RGN_FLAG_HIDDEN))
2134                                                 region_scale_toggle_hidden(C, rmd);
2135                                 }
2136                                 else if (rmd->ar->flag & RGN_FLAG_HIDDEN)
2137                                         region_scale_toggle_hidden(C, rmd);
2138                         }
2139                         else {
2140                                 int maxsize = region_scale_get_maxsize(rmd);
2141                                 delta = event->y - rmd->origy;
2142                                 if (rmd->edge == AE_BOTTOM_TO_TOPLEFT) delta = -delta;
2143                                 
2144                                 /* region sizes now get multiplied */
2145                                 delta /= UI_DPI_FAC;
2146
2147                                 rmd->ar->sizey = rmd->origval + delta;
2148                                 CLAMP(rmd->ar->sizey, 0, rmd->maxsize);
2149
2150                                 /* note, 'UI_UNIT_Y/4' means you need to drag the header almost
2151                                  * all the way down for it to become hidden, this is done
2152                                  * otherwise its too easy to do this by accident */
2153                                 if (rmd->ar->sizey < UI_UNIT_Y / 4) {
2154                                         rmd->ar->sizey = rmd->origval;
2155                                         if (!(rmd->ar->flag & RGN_FLAG_HIDDEN))
2156                                                 region_scale_toggle_hidden(C, rmd);
2157                                 }
2158                                 else if (maxsize > 0 && (rmd->ar->sizey > maxsize)) 
2159                                         rmd->ar->sizey = maxsize;
2160                                 else if (rmd->ar->flag & RGN_FLAG_HIDDEN)
2161                                         region_scale_toggle_hidden(C, rmd);
2162                         }
2163                         ED_area_tag_redraw(rmd->sa);
2164                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2165                         
2166                         break;
2167                         
2168                 case LEFTMOUSE:
2169                         if (event->val == KM_RELEASE) {
2170                                 
2171                                 if (ABS(event->x - rmd->origx) < 2 && ABS(event->y - rmd->origy) < 2) {
2172                                         if (rmd->ar->flag & RGN_FLAG_HIDDEN) {
2173                                                 region_scale_toggle_hidden(C, rmd);
2174                                         }
2175                                         else if (rmd->ar->flag & RGN_FLAG_TOO_SMALL) {
2176                                                 region_scale_validate_size(rmd);
2177                                         }
2178
2179                                         ED_area_tag_redraw(rmd->sa);
2180                                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2181                                 }
2182                                 MEM_freeN(op->customdata);
2183                                 op->customdata = NULL;
2184                                 
2185                                 return OPERATOR_FINISHED;
2186                         }
2187                         break;
2188                         
2189                 case ESCKEY:
2190                         break;
2191         }
2192         
2193         return OPERATOR_RUNNING_MODAL;
2194 }
2195
2196 static void region_scale_cancel(bContext *UNUSED(C), wmOperator *op)
2197 {
2198         MEM_freeN(op->customdata);
2199         op->customdata = NULL;
2200 }
2201
2202 static void SCREEN_OT_region_scale(wmOperatorType *ot)
2203 {
2204         /* identifiers */
2205         ot->name = "Scale Region Size";
2206         ot->description = "Scale selected area";
2207         ot->idname = "SCREEN_OT_region_scale";
2208         
2209         ot->invoke = region_scale_invoke;
2210         ot->modal = region_scale_modal;
2211         ot->cancel = region_scale_cancel;
2212         
2213         ot->poll = ED_operator_areaactive;
2214         
2215         /* flags */
2216         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
2217 }
2218
2219 /** \} */
2220
2221 /* -------------------------------------------------------------------- */
2222 /** \name Frame Change Operator
2223  * \{ */
2224
2225 static void areas_do_frame_follow(bContext *C, bool middle)
2226 {
2227         bScreen *scr = CTX_wm_screen(C);
2228         Scene *scene = CTX_data_scene(C);
2229         wmWindowManager *wm = CTX_wm_manager(C);
2230         for (wmWindow *window = wm->windows.first; window; window = window->next) {
2231                 const bScreen *screen = WM_window_get_active_screen(window);
2232
2233                 for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2234                         for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
2235                                 /* do follow here if editor type supports it */
2236                                 if ((scr->redraws_flag & TIME_FOLLOW)) {
2237                                         if ((ar->regiontype == RGN_TYPE_WINDOW &&
2238                                              ELEM(sa->spacetype, SPACE_SEQ, SPACE_TIME, SPACE_IPO, SPACE_ACTION, SPACE_NLA)) ||
2239                                             (sa->spacetype == SPACE_CLIP && ar->regiontype == RGN_TYPE_PREVIEW))
2240                                         {
2241                                                 float w = BLI_rctf_size_x(&ar->v2d.cur);
2242
2243                                                 if (middle) {
2244                                                         if ((scene->r.cfra < ar->v2d.cur.xmin) || (scene->r.cfra > ar->v2d.cur.xmax)) {
2245                                                                 ar->v2d.cur.xmax = scene->r.cfra + (w / 2);
2246                                                                 ar->v2d.cur.xmin = scene->r.cfra - (w / 2);
2247                                                         }
2248                                                 }
2249                                                 else {
2250                                                         if (scene->r.cfra < ar->v2d.cur.xmin) {
2251                                                                 ar->v2d.cur.xmax = scene->r.cfra;
2252                                                                 ar->v2d.cur.xmin = ar->v2d.cur.xmax - w;
2253                                                         }
2254                                                         else if (scene->r.cfra > ar->v2d.cur.xmax) {
2255                                                                 ar->v2d.cur.xmin = scene->r.cfra;
2256                                                                 ar->v2d.cur.xmax = ar->v2d.cur.xmin + w;
2257                                                         }
2258                                                 }
2259                                         }
2260                                 }
2261                         }
2262                 }
2263         }
2264 }
2265
2266 /* function to be called outside UI context, or for redo */
2267 static int frame_offset_exec(bContext *C, wmOperator *op)
2268 {
2269         Main *bmain = CTX_data_main(C);
2270         Scene *scene = CTX_data_scene(C);
2271         int delta;
2272         
2273         delta = RNA_int_get(op->ptr, "delta");
2274
2275         CFRA += delta;
2276         FRAMENUMBER_MIN_CLAMP(CFRA);
2277         SUBFRA = 0.f;
2278         
2279         areas_do_frame_follow(C, false);
2280
2281         BKE_sound_seek_scene(bmain, scene);
2282
2283         WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2284         
2285         return OPERATOR_FINISHED;
2286 }
2287
2288 static void SCREEN_OT_frame_offset(wmOperatorType *ot)
2289 {
2290         ot->name = "Frame Offset";
2291         ot->idname = "SCREEN_OT_frame_offset";
2292         ot->description = "Move current frame forward/backward by a given number";
2293         
2294         ot->exec = frame_offset_exec;
2295         
2296         ot->poll = ED_operator_screenactive_norender;
2297         ot->flag = OPTYPE_UNDO_GROUPED;
2298         ot->undo_group = "FRAME_CHANGE";
2299         
2300         /* rna */
2301         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2302 }
2303
2304 /** \} */
2305
2306 /* -------------------------------------------------------------------- */
2307 /** \name Frame Jump Operator
2308  * \{ */
2309
2310 /* function to be called outside UI context, or for redo */
2311 static int frame_jump_exec(bContext *C, wmOperator *op)
2312 {
2313         Main *bmain = CTX_data_main(C);
2314         Scene *scene = CTX_data_scene(C);
2315         wmTimer *animtimer = CTX_wm_screen(C)->animtimer;
2316
2317         /* Don't change CFRA directly if animtimer is running as this can cause
2318          * first/last frame not to be actually shown (bad since for example physics
2319          * simulations aren't reset properly).
2320          */
2321         if (animtimer) {
2322                 ScreenAnimData *sad = animtimer->customdata;
2323                 
2324                 sad->flag |= ANIMPLAY_FLAG_USE_NEXT_FRAME;
2325                 
2326                 if (RNA_boolean_get(op->ptr, "end"))
2327                         sad->nextfra = PEFRA;
2328                 else
2329                         sad->nextfra = PSFRA;
2330         }
2331         else {
2332                 if (RNA_boolean_get(op->ptr, "end"))
2333                         CFRA = PEFRA;
2334                 else
2335                         CFRA = PSFRA;
2336                 
2337                 areas_do_frame_follow(C, true);
2338
2339                 BKE_sound_seek_scene(bmain, scene);
2340
2341                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2342         }
2343         
2344         return OPERATOR_FINISHED;
2345 }
2346
2347 static void SCREEN_OT_frame_jump(wmOperatorType *ot)
2348 {
2349         ot->name = "Jump to Endpoint";
2350         ot->description = "Jump to first/last frame in frame range";
2351         ot->idname = "SCREEN_OT_frame_jump";
2352         
2353         ot->exec = frame_jump_exec;
2354         
2355         ot->poll = ED_operator_screenactive_norender;
2356         ot->flag = OPTYPE_UNDO_GROUPED;
2357         ot->undo_group = "FRAME_CHANGE";
2358         
2359         /* rna */
2360         RNA_def_boolean(ot->srna, "end", 0, "Last Frame", "Jump to the last frame of the frame range");
2361 }
2362
2363 /** \} */
2364
2365 /* -------------------------------------------------------------------- */
2366 /** \name Jump to Key-Frame Operator
2367  * \{ */
2368
2369 /* function to be called outside UI context, or for redo */
2370 static int keyframe_jump_exec(bContext *C, wmOperator *op)
2371 {
2372         Main *bmain = CTX_data_main(C);
2373         Scene *scene = CTX_data_scene(C);
2374         Object *ob = CTX_data_active_object(C);
2375         bDopeSheet ads = {NULL};
2376         DLRBT_Tree keys;
2377         ActKeyColumn *ak;
2378         float cfra;
2379         const bool next = RNA_boolean_get(op->ptr, "next");
2380         bool done = false;
2381         
2382         /* sanity checks */
2383         if (scene == NULL)
2384                 return OPERATOR_CANCELLED;
2385
2386         cfra = (float)(CFRA);
2387
2388         /* init binarytree-list for getting keyframes */
2389         BLI_dlrbTree_init(&keys);
2390         
2391         /* seed up dummy dopesheet context with flags to perform necessary filtering */
2392         if ((scene->flag & SCE_KEYS_NO_SELONLY) == 0) {
2393                 /* only selected channels are included */
2394                 ads.filterflag |= ADS_FILTER_ONLYSEL;
2395         }
2396         
2397         /* populate tree with keyframe nodes */
2398         scene_to_keylist(&ads, scene, &keys, NULL);
2399         gpencil_to_keylist(&ads, scene->gpd, &keys);
2400
2401         if (ob) {
2402                 ob_to_keylist(&ads, ob, &keys, NULL);
2403                 gpencil_to_keylist(&ads, ob->gpd, &keys);
2404         }
2405         
2406         {
2407                 Mask *mask = CTX_data_edit_mask(C);
2408                 if (mask) {
2409                         MaskLayer *masklay = BKE_mask_layer_active(mask);
2410                         mask_to_keylist(&ads, masklay, &keys);
2411                 }
2412         }
2413
2414         /* build linked-list for searching */
2415         BLI_dlrbTree_linkedlist_sync(&keys);
2416         
2417         /* find matching keyframe in the right direction */
2418         if (next)
2419                 ak = (ActKeyColumn *)BLI_dlrbTree_search_next(&keys, compare_ak_cfraPtr, &cfra);
2420         else
2421                 ak = (ActKeyColumn *)BLI_dlrbTree_search_prev(&keys, compare_ak_cfraPtr, &cfra);
2422         
2423         while ((ak != NULL) && (done == false)) {
2424                 if (CFRA != (int)ak->cfra) {
2425                         /* this changes the frame, so set the frame and we're done */
2426                         CFRA = (int)ak->cfra;
2427                         done = true;
2428                 }
2429                 else {
2430                         /* take another step... */
2431                         if (next) {
2432                                 ak = ak->next;
2433                         }
2434                         else {
2435                                 ak = ak->prev;
2436                         }
2437                 }
2438         }
2439         
2440         /* free temp stuff */
2441         BLI_dlrbTree_free(&keys);
2442
2443         /* any success? */
2444         if (done == false) {
2445                 BKE_report(op->reports, RPT_INFO, "No more keyframes to jump to in this direction");
2446
2447                 return OPERATOR_CANCELLED;
2448         }
2449         else {
2450                 areas_do_frame_follow(C, true);
2451
2452                 BKE_sound_seek_scene(bmain, scene);
2453
2454                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2455
2456                 return OPERATOR_FINISHED;
2457         }
2458 }
2459
2460 static void SCREEN_OT_keyframe_jump(wmOperatorType *ot)
2461 {
2462         ot->name = "Jump to Keyframe";
2463         ot->description = "Jump to previous/next keyframe";
2464         ot->idname = "SCREEN_OT_keyframe_jump";
2465         
2466         ot->exec = keyframe_jump_exec;
2467         
2468         ot->poll = ED_operator_screenactive_norender;
2469         ot->flag = OPTYPE_UNDO_GROUPED;
2470         ot->undo_group = "FRAME_CHANGE";
2471         
2472         /* properties */
2473         RNA_def_boolean(ot->srna, "next", true, "Next Keyframe", "");
2474 }
2475
2476 /** \} */
2477
2478 /* -------------------------------------------------------------------- */
2479 /** \name Jump to Marker Operator
2480  * \{ */
2481
2482 /* function to be called outside UI context, or for redo */
2483 static int marker_jump_exec(bContext *C, wmOperator *op)
2484 {
2485         Main *bmain = CTX_data_main(C);
2486         Scene *scene = CTX_data_scene(C);
2487         TimeMarker *marker;
2488         int closest = CFRA;
2489         const bool next = RNA_boolean_get(op->ptr, "next");
2490         bool found = false;
2491
2492         /* find matching marker in the right direction */
2493         for (marker = scene->markers.first; marker; marker = marker->next) {
2494                 if (next) {
2495                         if ((marker->frame > CFRA) && (!found || closest > marker->frame)) {
2496                                 closest = marker->frame;
2497                                 found = true;
2498                         }
2499                 }
2500                 else {
2501                         if ((marker->frame < CFRA) && (!found || closest < marker->frame)) {
2502                                 closest = marker->frame;
2503                                 found = true;
2504                         }
2505                 }
2506         }
2507
2508         /* any success? */
2509         if (!found) {
2510                 BKE_report(op->reports, RPT_INFO, "No more markers to jump to in this direction");
2511
2512                 return OPERATOR_CANCELLED;
2513         }
2514         else {
2515                 CFRA = closest;
2516
2517                 areas_do_frame_follow(C, true);
2518
2519                 BKE_sound_seek_scene(bmain, scene);
2520
2521                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2522
2523                 return OPERATOR_FINISHED;
2524         }
2525 }
2526
2527 static void SCREEN_OT_marker_jump(wmOperatorType *ot)
2528 {
2529         ot->name = "Jump to Marker";
2530         ot->description = "Jump to previous/next marker";
2531         ot->idname = "SCREEN_OT_marker_jump";
2532
2533         ot->exec = marker_jump_exec;
2534
2535         ot->poll = ED_operator_screenactive_norender;
2536         ot->flag = OPTYPE_UNDO_GROUPED;
2537         ot->undo_group = "FRAME_CHANGE";
2538
2539         /* properties */
2540         RNA_def_boolean(ot->srna, "next", true, "Next Marker", "");
2541 }
2542
2543 /** \} */
2544
2545 /* -------------------------------------------------------------------- */
2546 /** \name Set Screen Operator
2547  * \{ */
2548
2549 /* function to be called outside UI context, or for redo */
2550 static int screen_set_exec(bContext *C, wmOperator *op)
2551 {
2552         WorkSpace *workspace = CTX_wm_workspace(C);
2553         int delta = RNA_int_get(op->ptr, "delta");
2554
2555         if (ED_workspace_layout_cycle(workspace, delta, C)) {
2556                 return OPERATOR_FINISHED;
2557         }
2558
2559         return OPERATOR_CANCELLED;
2560 }
2561
2562 static void SCREEN_OT_screen_set(wmOperatorType *ot)
2563 {
2564         ot->name = "Set Screen";
2565         ot->description = "Cycle through available screens";
2566         ot->idname = "SCREEN_OT_screen_set";
2567         
2568         ot->exec = screen_set_exec;
2569         ot->poll = ED_operator_screenactive;
2570
2571         /* rna */
2572         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2573 }
2574
2575 /** \} */
2576
2577 /* -------------------------------------------------------------------- */
2578 /** \name Screen Full-Area Operator
2579  * \{ */
2580
2581 /* function to be called outside UI context, or for redo */
2582 static int screen_maximize_area_exec(bContext *C, wmOperator *op)
2583 {
2584         bScreen *screen = CTX_wm_screen(C);
2585         ScrArea *sa = NULL;
2586         const bool hide_panels = RNA_boolean_get(op->ptr, "use_hide_panels");
2587         
2588         /* search current screen for 'fullscreen' areas */
2589         /* prevents restoring info header, when mouse is over it */
2590         for (sa = screen->areabase.first; sa; sa = sa->next) {
2591                 if (sa->full) break;
2592         }
2593         
2594         if (sa == NULL) {
2595                 sa = CTX_wm_area(C);
2596         }
2597         
2598         if (hide_panels) {
2599                 if (!ELEM(screen->state, SCREENNORMAL, SCREENFULL)) {
2600                         return OPERATOR_CANCELLED;
2601                 }
2602                 ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENFULL);
2603         }
2604         else {
2605                 if (!ELEM(screen->state, SCREENNORMAL, SCREENMAXIMIZED)) {
2606                         return OPERATOR_CANCELLED;
2607                 }
2608                 ED_screen_state_toggle(C, CTX_wm_window(C), sa, SCREENMAXIMIZED);
2609         }
2610
2611         return OPERATOR_FINISHED;
2612 }
2613
2614 static void SCREEN_OT_screen_full_area(wmOperatorType *ot)
2615 {
2616         PropertyRNA *prop;
2617
2618         ot->name = "Toggle Maximize Area";
2619         ot->description = "Toggle display selected area as fullscreen/maximized";
2620         ot->idname = "SCREEN_OT_screen_full_area";
2621         
2622         ot->exec = screen_maximize_area_exec;
2623         ot->poll = ED_operator_areaactive;
2624         ot->flag = 0;
2625
2626         prop = RNA_def_boolean(ot->srna, "use_hide_panels", false, "Hide Panels", "Hide all the panels");
2627         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2628 }
2629
2630 /** \} */
2631
2632 /* -------------------------------------------------------------------- */
2633 /** \name Screen Join-Area Operator
2634  * \{ */
2635
2636 /* operator state vars used:  
2637  * x1, y1     mouse coord in first area, which will disappear
2638  * x2, y2     mouse coord in 2nd area, which will become joined
2639  * 
2640  * functions:
2641  * 
2642  * init()   find edge based on state vars 
2643  * test if the edge divides two areas, 
2644  * store active and nonactive area,
2645  * 
2646  * apply()  do the actual join
2647  * 
2648  * exit()       cleanup, send notifier
2649  * 
2650  * callbacks:
2651  * 
2652  * exec()       calls init, apply, exit 
2653  * 
2654  * invoke() sets mouse coords in x,y
2655  * call init()
2656  * add modal handler
2657  * 
2658  * modal()      accept modal events while doing it
2659  * call apply() with active window and nonactive window
2660  * call exit() and remove handler when LMB confirm
2661  */
2662
2663 typedef struct sAreaJoinData {
2664         ScrArea *sa1;        /* first area to be considered */
2665         ScrArea *sa2;        /* second area to be considered */
2666         void *draw_callback; /* call `ED_screen_draw_join_shape` */
2667
2668 } sAreaJoinData;
2669
2670
2671 static void area_join_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
2672 {
2673         const wmOperator *op = userdata;
2674
2675         sAreaJoinData *sd = op->customdata;
2676         if (sd->sa1 && sd->sa2) {
2677                 ED_screen_draw_join_shape(sd->sa1, sd->sa2);
2678         }
2679 }
2680
2681 /* validate selection inside screen, set variables OK */
2682 /* return 0: init failed */
2683 /* XXX todo: find edge based on (x,y) and set other area? */
2684 static int area_join_init(bContext *C, wmOperator *op)
2685 {
2686         ScrArea *sa1, *sa2;
2687         sAreaJoinData *jd = NULL;
2688         int x1, y1;
2689         int x2, y2;
2690         int shared = 0;
2691         
2692         /* required properties, make negative to get return 0 if not set by caller */
2693         x1 = RNA_int_get(op->ptr, "min_x");
2694         y1 = RNA_int_get(op->ptr, "min_y");
2695         x2 = RNA_int_get(op->ptr, "max_x");
2696         y2 = RNA_int_get(op->ptr, "max_y");
2697         
2698         sa1 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, x1, y1);
2699         sa2 = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, x2, y2);
2700         if (sa1 == NULL || sa2 == NULL || sa1 == sa2)
2701                 return 0;
2702         
2703         /* do areas share an edge? */
2704         if (sa1->v1 == sa2->v1 || sa1->v1 == sa2->v2 || sa1->v1 == sa2->v3 || sa1->v1 == sa2->v4) shared++;
2705         if (sa1->v2 == sa2->v1 || sa1->v2 == sa2->v2 || sa1->v2 == sa2->v3 || sa1->v2 == sa2->v4) shared++;
2706         if (sa1->v3 == sa2->v1 || sa1->v3 == sa2->v2 || sa1->v3 == sa2->v3 || sa1->v3 == sa2->v4) shared++;
2707         if (sa1->v4 == sa2->v1 || sa1->v4 == sa2->v2 || sa1->v4 == sa2->v3 || sa1->v4 == sa2->v4) shared++;
2708         if (shared != 2) {
2709                 printf("areas don't share edge\n");
2710                 return 0;
2711         }
2712         
2713         jd = (sAreaJoinData *)MEM_callocN(sizeof(sAreaJoinData), "op_area_join");
2714
2715         jd->sa1 = sa1;
2716         jd->sa2 = sa2;
2717
2718         op->customdata = jd;
2719
2720         jd->draw_callback = WM_draw_cb_activate(CTX_wm_window(C), area_join_draw_cb, op);
2721
2722         return 1;
2723 }
2724
2725 /* apply the join of the areas (space types) */
2726 static int area_join_apply(bContext *C, wmOperator *op)
2727 {
2728         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2729         if (!jd) return 0;
2730         
2731         if (!screen_area_join(C, CTX_wm_screen(C), jd->sa1, jd->sa2)) {
2732                 return 0;
2733         }
2734         if (CTX_wm_area(C) == jd->sa2) {
2735                 CTX_wm_area_set(C, NULL);
2736                 CTX_wm_region_set(C, NULL);
2737         }
2738         
2739         return 1;
2740 }
2741
2742 /* finish operation */
2743 static void area_join_exit(bContext *C, wmOperator *op)
2744 {
2745         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2746
2747         if (jd) {
2748                 if (jd->draw_callback)
2749                         WM_draw_cb_exit(CTX_wm_window(C), jd->draw_callback);
2750
2751                 MEM_freeN(jd);
2752                 op->customdata = NULL;
2753         }
2754         
2755         /* this makes sure aligned edges will result in aligned grabbing */
2756         removedouble_scredges(CTX_wm_screen(C));
2757         removenotused_scredges(CTX_wm_screen(C));
2758         removenotused_scrverts(CTX_wm_screen(C));
2759 }
2760
2761 static int area_join_exec(bContext *C, wmOperator *op)
2762 {
2763         if (!area_join_init(C, op)) 
2764                 return OPERATOR_CANCELLED;
2765         
2766         area_join_apply(C, op);
2767         area_join_exit(C, op);
2768         
2769         return OPERATOR_FINISHED;
2770 }
2771
2772 /* interaction callback */
2773 static int area_join_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2774 {
2775         
2776         if (event->type == EVT_ACTIONZONE_AREA) {
2777                 sActionzoneData *sad = event->customdata;
2778                 
2779                 if (sad == NULL || sad->modifier > 0) {
2780                         return OPERATOR_PASS_THROUGH;
2781                 }
2782                 
2783                 /* verify *sad itself */
2784                 if (sad->sa1 == NULL || sad->sa2 == NULL)
2785                         return OPERATOR_PASS_THROUGH;
2786                 
2787                 /* is this our *sad? if areas equal it should be passed on */
2788                 if (sad->sa1 == sad->sa2)
2789                         return OPERATOR_PASS_THROUGH;
2790                 
2791                 /* prepare operator state vars */
2792                 RNA_int_set(op->ptr, "min_x", sad->x);
2793                 RNA_int_set(op->ptr, "min_y", sad->y);
2794                 RNA_int_set(op->ptr, "max_x", event->x);
2795                 RNA_int_set(op->ptr, "max_y", event->y);
2796         }
2797         
2798         
2799         if (!area_join_init(C, op)) 
2800                 return OPERATOR_PASS_THROUGH;
2801         
2802         /* add temp handler */
2803         WM_event_add_modal_handler(C, op);
2804         
2805         return OPERATOR_RUNNING_MODAL;
2806 }
2807
2808 static void area_join_cancel(bContext *C, wmOperator *op)
2809 {
2810         WM_event_add_notifier(C, NC_WINDOW, NULL);
2811         
2812         area_join_exit(C, op);
2813 }
2814
2815 /* modal callback while selecting area (space) that will be removed */
2816 static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
2817 {
2818         bScreen *sc = CTX_wm_screen(C);
2819         sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
2820         
2821         /* execute the events */
2822         switch (event->type) {
2823                         
2824                 case MOUSEMOVE: 
2825                 {
2826                         ScrArea *sa = BKE_screen_find_area_xy(sc, SPACE_TYPE_ANY, event->x, event->y);
2827                         int dir;
2828                         
2829                         if (sa) {
2830                                 if (jd->sa1 != sa) {
2831                                         dir = area_getorientation(jd->sa1, sa);
2832                                         if (dir != -1) {
2833                                                 jd->sa2 = sa;
2834                                         }
2835                                         else {
2836                                                 /* we are not bordering on the previously selected area 
2837                                                  * we check if area has common border with the one marked for removal
2838                                                  * in this case we can swap areas.
2839                                                  */
2840                                                 dir = area_getorientation(sa, jd->sa2);
2841                                                 if (dir != -1) {
2842                                                         jd->sa1 = jd->sa2;
2843                                                         jd->sa2 = sa;
2844                                                 }
2845                                                 else {
2846                                                         jd->sa2 = NULL;
2847                                                 }
2848                                         }
2849                                         WM_event_add_notifier(C, NC_WINDOW, NULL);
2850                                 }
2851                                 else {
2852                                         /* we are back in the area previously selected for keeping 
2853                                          * we swap the areas if possible to allow user to choose */
2854                                         if (jd->sa2 != NULL) {
2855                                                 jd->sa1 = jd->sa2;
2856                                                 jd->sa2 = sa;
2857                                                 dir = area_getorientation(jd->sa1, jd->sa2);
2858                                                 if (dir == -1) {
2859                                                         printf("oops, didn't expect that!\n");
2860                                                 }
2861                                         }
2862                                         else {
2863                                                 dir = area_getorientation(jd->sa1, sa);
2864                                                 if (dir != -1) {
2865                                                         jd->sa2 = sa;
2866                                                 }
2867                                         }
2868                                         WM_event_add_notifier(C, NC_WINDOW, NULL);
2869                                 }
2870                         }
2871                         break;
2872                 }
2873                 case LEFTMOUSE:
2874                         if (event->val == KM_RELEASE) {
2875                                 ED_area_tag_redraw(jd->sa1);
2876                                 ED_area_tag_redraw(jd->sa2);
2877
2878                                 area_join_apply(C, op);
2879                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
2880                                 area_join_exit(C, op);
2881                                 return OPERATOR_FINISHED;
2882                         }
2883                         break;
2884                         
2885                 case RIGHTMOUSE:
2886                 case ESCKEY:
2887                         area_join_cancel(C, op);
2888                         return OPERATOR_CANCELLED;
2889         }
2890         
2891         return OPERATOR_RUNNING_MODAL;
2892 }
2893
2894 /* Operator for joining two areas (space types) */
2895 static void SCREEN_OT_area_join(wmOperatorType *ot)
2896 {
2897         /* identifiers */
2898         ot->name = "Join Area";
2899         ot->description = "Join selected areas into new window";
2900         ot->idname = "SCREEN_OT_area_join";
2901         
2902         /* api callbacks */
2903         ot->exec = area_join_exec;
2904         ot->invoke = area_join_invoke;
2905         ot->modal = area_join_modal;
2906         ot->poll = screen_active_editable;
2907         ot->cancel = area_join_cancel;
2908         
2909         /* flags */
2910         ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
2911         
2912         /* rna */
2913         RNA_def_int(ot->srna, "min_x", -100, INT_MIN, INT_MAX, "X 1", "", INT_MIN, INT_MAX);
2914         RNA_def_int(ot->srna, "min_y", -100, INT_MIN, INT_MAX, "Y 1", "", INT_MIN, INT_MAX);
2915         RNA_def_int(ot->srna, "max_x", -100, INT_MIN, INT_MAX, "X 2", "", INT_MIN, INT_MAX);
2916         RNA_def_int(ot->srna, "max_y", -100, INT_MIN, INT_MAX, "Y 2", "", INT_MIN, INT_MAX);
2917 }
2918
2919 /** \} */
2920
2921 /* -------------------------------------------------------------------- */
2922 /** \name Screen Area Options Operator
2923  * \{ */
2924
2925 static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2926 {
2927         wmWindow *win = CTX_wm_window(C);
2928         bScreen *sc = CTX_wm_screen(C);
2929         uiPopupMenu *pup;
2930         uiLayout *layout;
2931         PointerRNA ptr;
2932         ScrEdge *actedge;
2933         const int winsize_x = WM_window_pixels_x(win);
2934         const int winsize_y = WM_window_pixels_y(win);
2935
2936         actedge = screen_find_active_scredge(sc, winsize_x, winsize_y, event->x, event->y);
2937         
2938         if (actedge == NULL) return OPERATOR_CANCELLED;
2939         
2940         pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
2941         layout = UI_popup_menu_layout(pup);
2942         
2943         uiItemFullO(layout, "SCREEN_OT_area_split", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
2944         /* store initial mouse cursor position */
2945         RNA_int_set(&ptr, "mouse_x", event->x);
2946         RNA_int_set(&ptr, "mouse_y", event->y);
2947
2948         uiItemFullO(layout, "SCREEN_OT_area_join", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
2949         /* mouse cursor on edge, '4' can fail on wide edges... */
2950         RNA_int_set(&ptr, "min_x", event->x + 4);
2951         RNA_int_set(&ptr, "min_y", event->y + 4);
2952         RNA_int_set(&ptr, "max_x", event->x - 4);
2953         RNA_int_set(&ptr, "max_y", event->y - 4);
2954         
2955         UI_popup_menu_end(C, pup);
2956         
2957         return OPERATOR_INTERFACE;
2958 }
2959
2960 static void SCREEN_OT_area_options(wmOperatorType *ot)
2961 {
2962         /* identifiers */
2963         ot->name = "Area Options";
2964         ot->description = "Operations for splitting and merging";
2965         ot->idname = "SCREEN_OT_area_options";
2966         
2967         /* api callbacks */
2968         ot->invoke = screen_area_options_invoke;
2969         
2970         ot->poll = ED_operator_screen_mainwinactive;
2971
2972         /* flags */
2973         ot->flag = OPTYPE_INTERNAL;
2974 }
2975
2976 /** \} */
2977
2978 /* -------------------------------------------------------------------- */
2979 /** \name Space Data Cleanup Operator
2980  * \{ */
2981
2982 static int spacedata_cleanup_exec(bContext *C, wmOperator *op)
2983 {
2984         Main *bmain = CTX_data_main(C);
2985         bScreen *screen;
2986         ScrArea *sa;
2987         int tot = 0;
2988         
2989         for (screen = bmain->screen.first; screen; screen = screen->id.next) {
2990                 for (sa = screen->areabase.first; sa; sa = sa->next) {
2991                         if (sa->spacedata.first != sa->spacedata.last) {
2992                                 SpaceLink *sl = sa->spacedata.first;
2993
2994                                 BLI_remlink(&sa->spacedata, sl);
2995                                 tot += BLI_listbase_count(&sa->spacedata);
2996                                 BKE_spacedata_freelist(&sa->spacedata);
2997                                 BLI_addtail(&sa->spacedata, sl);
2998                         }
2999                 }
3000         }
3001         BKE_reportf(op->reports, RPT_INFO, "Removed amount of editors: %d", tot);
3002         
3003         return OPERATOR_FINISHED;
3004 }
3005
3006 static void SCREEN_OT_spacedata_cleanup(wmOperatorType *ot)
3007 {
3008         /* identifiers */
3009         ot->name = "Clean-up Space-data";
3010         ot->description = "Remove unused settings for invisible editors";
3011         ot->idname = "SCREEN_OT_spacedata_cleanup";
3012         
3013         /* api callbacks */
3014         ot->exec = spacedata_cleanup_exec;
3015         ot->poll = WM_operator_winactive;
3016         
3017 }
3018
3019 /** \} */
3020
3021 /* -------------------------------------------------------------------- */
3022 /** \name Repeat Last Operator
3023  * \{ */
3024
3025 static int repeat_last_exec(bContext *C, wmOperator *UNUSED(op))
3026 {
3027         wmWindowManager *wm = CTX_wm_manager(C);
3028         wmOperator *lastop = wm->operators.last;
3029
3030         /* Seek last registered operator */
3031         while (lastop) {
3032                 if (lastop->type->flag & OPTYPE_REGISTER) {
3033                         break;
3034                 }
3035                 else {
3036                         lastop = lastop->prev;
3037                 }
3038         }
3039
3040         if (lastop) {
3041                 WM_operator_free_all_after(wm, lastop);
3042                 WM_operator_repeat(C, lastop);
3043         }
3044         
3045         return OPERATOR_CANCELLED;
3046 }
3047
3048 static void SCREEN_OT_repeat_last(wmOperatorType *ot)
3049 {
3050         /* identifiers */
3051         ot->name = "Repeat Last";
3052         ot->description = "Repeat last action";
3053         ot->idname = "SCREEN_OT_repeat_last";
3054         
3055         /* api callbacks */
3056         ot->exec = repeat_last_exec;
3057         
3058         ot->poll = ED_operator_screenactive;
3059         
3060 }
3061
3062 /** \} */
3063
3064 /* -------------------------------------------------------------------- */
3065 /** \name Repeat History Operator
3066  * \{ */
3067
3068 static int repeat_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
3069 {
3070         wmWindowManager *wm = CTX_wm_manager(C);
3071         wmOperator *lastop;
3072         uiPopupMenu *pup;
3073         uiLayout *layout;
3074         int items, i;
3075         
3076         items = BLI_listbase_count(&wm->operators);
3077         if (items == 0)
3078                 return OPERATOR_CANCELLED;
3079         
3080         pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
3081         layout = UI_popup_menu_layout(pup);
3082         
3083         for (i = items - 1, lastop = wm->operators.last; lastop; lastop = lastop->prev, i--)
3084                 if ((lastop->type->flag & OPTYPE_REGISTER) && WM_operator_repeat_check(C, lastop)) {
3085                         uiItemIntO(layout, RNA_struct_ui_name(lastop->type->srna), ICON_NONE, op->type->idname, "index", i);
3086                 }
3087         
3088         UI_popup_menu_end(C, pup);
3089         
3090         return OPERATOR_INTERFACE;
3091 }
3092
3093 static int repeat_history_exec(bContext *C, wmOperator *op)
3094 {
3095         wmWindowManager *wm = CTX_wm_manager(C);
3096         
3097         op = BLI_findlink(&wm->operators, RNA_int_get(op->ptr, "index"));
3098         if (op) {
3099                 /* let's put it as last operator in list */
3100                 BLI_remlink(&wm->operators, op);
3101                 BLI_addtail(&wm->operators, op);
3102                 
3103                 WM_operator_repeat(C, op);
3104         }
3105         
3106         return OPERATOR_FINISHED;
3107 }
3108
3109 static void SCREEN_OT_repeat_history(wmOperatorType *ot)
3110 {
3111         /* identifiers */
3112         ot->name = "Repeat History";
3113         ot->description = "Display menu for previous actions performed";
3114         ot->idname = "SCREEN_OT_repeat_history";
3115         
3116         /* api callbacks */
3117         ot->invoke = repeat_history_invoke;
3118         ot->exec = repeat_history_exec;
3119         
3120         ot->poll = ED_operator_screenactive;
3121         
3122         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
3123 }
3124
3125 /** \} */
3126
3127 /* -------------------------------------------------------------------- */
3128 /** \name Redo Operator
3129  * \{ */
3130
3131 static int redo_last_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
3132 {
3133         wmOperator *lastop = WM_operator_last_redo(C);
3134         
3135         if (lastop)
3136                 WM_operator_redo_popup(C, lastop);
3137         
3138         return OPERATOR_CANCELLED;
3139 }
3140
3141 static void SCREEN_OT_redo_last(wmOperatorType *ot)
3142 {
3143         /* identifiers */
3144         ot->name = "Redo Last";
3145         ot->description = "Display menu for last action performed";
3146         ot->idname = "SCREEN_OT_redo_last";
3147         
3148         /* api callbacks */
3149         ot->invoke = redo_last_invoke;
3150         
3151         ot->poll = ED_operator_screenactive;
3152 }
3153
3154 /** \} */
3155
3156 /* -------------------------------------------------------------------- */
3157 /** \name Region Quad-View Operator
3158  * \{ */
3159
3160 static void view3d_localview_update_rv3d(struct RegionView3D *rv3d)
3161 {
3162         if (rv3d->localvd) {
3163                 rv3d->localvd->view = rv3d->view;
3164                 rv3d->localvd->persp = rv3d->persp;
3165                 copy_qt_qt(rv3d->localvd->viewquat, rv3d->viewquat);
3166         }
3167 }
3168
3169 static void region_quadview_init_rv3d(ScrArea *sa, ARegion *ar,
3170                                       const char viewlock, const char view, const char persp)
3171 {
3172         RegionView3D *rv3d = ar->regiondata;
3173
3174         if (persp == RV3D_CAMOB) {
3175                 ED_view3d_lastview_store(rv3d);
3176         }
3177
3178         rv3d->viewlock = viewlock;
3179         rv3d->view = view;
3180         rv3d->persp = persp;
3181
3182         ED_view3d_lock(rv3d);
3183         view3d_localview_update_rv3d(rv3d);
3184         if ((viewlock & RV3D_BOXCLIP) && (persp == RV3D_ORTHO)) {
3185                 ED_view3d_quadview_update(sa, ar, true);
3186         }
3187 }
3188
3189 /* insert a region in the area region list */
3190 static int region_quadview_exec(bContext *C, wmOperator *op)
3191 {
3192         ARegion *ar = CTX_wm_region(C);
3193         
3194         /* some rules... */
3195         if (ar->regiontype != RGN_TYPE_WINDOW) {
3196                 BKE_report(op->reports, RPT_ERROR, "Only window region can be 4-splitted");
3197         }
3198         else if (ar->alignment == RGN_ALIGN_QSPLIT) {
3199                 /* Exit quad-view */
3200                 ScrArea *sa = CTX_wm_area(C);
3201                 ARegion *arn;
3202                 
3203                 /* keep current region */
3204                 ar->alignment = 0;
3205                 
3206                 if (sa->spacetype == SPACE_VIEW3D) {
3207                         ARegion *ar_iter;
3208                         RegionView3D *rv3d = ar->regiondata;
3209
3210                         /* if this is a locked view, use settings from 'User' view */
3211                         if (rv3d->viewlock) {
3212                                 View3D *v3d_user;
3213                                 ARegion *ar_user;
3214
3215                                 if (ED_view3d_context_user_region(C, &v3d_user, &ar_user)) {
3216                                         if (ar != ar_user) {
3217                                                 SWAP(void *, ar->regiondata, ar_user->regiondata);
3218                                                 rv3d = ar->regiondata;
3219                                         }
3220                                 }
3221                         }
3222
3223                         rv3d->viewlock_quad = RV3D_VIEWLOCK_INIT;
3224                         rv3d->viewlock = 0;
3225                         rv3d->rflag &= ~RV3D_CLIPPING;
3226
3227                         /* accumulate locks, incase they're mixed */
3228                         for (ar_iter = sa->regionbase.first; ar_iter; ar_iter = ar_iter->next) {
3229                                 if (ar_iter->regiontype == RGN_TYPE_WINDOW) {
3230                                         RegionView3D *rv3d_iter = ar_iter->regiondata;
3231                                         rv3d->viewlock_quad |= rv3d_iter->viewlock;
3232                                 }
3233                         }
3234                 }
3235                 
3236                 for (ar = sa->regionbase.first; ar; ar = arn) {
3237                         arn = ar->next;
3238                         if (ar->alignment == RGN_ALIGN_QSPLIT) {
3239                                 ED_region_exit(C, ar);
3240                                 BKE_area_region_free(sa->type, ar);
3241                                 BLI_remlink(&sa->regionbase, ar);
3242                                 MEM_freeN(ar);
3243                         }
3244                 }
3245                 ED_area_tag_redraw(sa);
3246                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
3247         }
3248         else if (ar->next) {
3249                 BKE_report(op->reports, RPT_ERROR, "Only last region can be 4-splitted");
3250         }
3251         else {
3252                 /* Enter quad-view */
3253                 ScrArea *sa = CTX_wm_area(C);
3254                 ARegion *newar;
3255                 int count;
3256                 
3257                 ar->alignment = RGN_ALIGN_QSPLIT;
3258                 
3259                 for (count = 0; count < 3; count++) {
3260                         newar = BKE_area_region_copy(sa->type, ar);
3261                         BLI_addtail(&sa->regionbase, newar);
3262                 }
3263                 
3264                 /* lock views and set them */
3265                 if (sa->spacetype == SPACE_VIEW3D) {
3266                         View3D *v3d = sa->spacedata.first;
3267                         int index_qsplit = 0;
3268
3269                         /* run ED_view3d_lock() so the correct 'rv3d->viewquat' is set,
3270                          * otherwise when restoring rv3d->localvd the 'viewquat' won't
3271                          * match the 'view', set on entering localview See: [#26315],
3272                          *
3273                          * We could avoid manipulating rv3d->localvd here if exiting
3274                          * localview with a 4-split would assign these view locks */
3275                         RegionView3D *rv3d = ar->regiondata;
3276                         const char viewlock = (rv3d->viewlock_quad & RV3D_VIEWLOCK_INIT) ?
3277                                               (rv3d->viewlock_quad & ~RV3D_VIEWLOCK_INIT) : RV3D_LOCKED;
3278
3279                         region_quadview_init_rv3d(sa, ar,              viewlock, ED_view3d_lock_view_from_index(index_qsplit++), RV3D_ORTHO);
3280    &n