85f46d86abc8f35298c4782177f4abb3a8b4a92e
[blender.git] / source / blender / editors / screen / area.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  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/screen/area.c
28  *  \ingroup edscr
29  */
30
31
32 #include <string.h>
33 #include <stdio.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_userdef_types.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_linklist_stack.h"
43
44 #include "BKE_context.h"
45 #include "BKE_global.h"
46 #include "BKE_screen.h"
47 #include "BKE_workspace.h"
48
49 #include "RNA_access.h"
50 #include "RNA_types.h"
51
52 #include "WM_api.h"
53 #include "WM_types.h"
54 #include "WM_message.h"
55 #include "WM_toolsystem.h"
56
57 #include "ED_screen.h"
58 #include "ED_screen_types.h"
59 #include "ED_space_api.h"
60
61 #include "GPU_immediate.h"
62 #include "GPU_immediate_util.h"
63 #include "GPU_matrix.h"
64 #include "GPU_draw.h"
65 #include "GPU_state.h"
66 #include "GPU_framebuffer.h"
67
68 #include "BLF_api.h"
69
70 #include "IMB_imbuf.h"
71 #include "IMB_imbuf_types.h"
72 #include "IMB_metadata.h"
73
74 #include "UI_interface.h"
75 #include "UI_interface_icons.h"
76 #include "UI_resources.h"
77 #include "UI_view2d.h"
78
79 #include "screen_intern.h"
80
81 enum RegionEmbossSide {
82         REGION_EMBOSS_LEFT   = (1 << 0),
83         REGION_EMBOSS_TOP    = (1 << 1),
84         REGION_EMBOSS_BOTTOM = (1 << 2),
85         REGION_EMBOSS_RIGHT  = (1 << 3),
86         REGION_EMBOSS_ALL    = REGION_EMBOSS_LEFT | REGION_EMBOSS_TOP | REGION_EMBOSS_RIGHT | REGION_EMBOSS_BOTTOM,
87 };
88
89 /* general area and region code */
90
91 static void region_draw_emboss(const ARegion *ar, const rcti *scirct, int sides)
92 {
93         rcti rect;
94
95         /* translate scissor rect to region space */
96         rect.xmin = scirct->xmin - ar->winrct.xmin;
97         rect.ymin = scirct->ymin - ar->winrct.ymin;
98         rect.xmax = scirct->xmax - ar->winrct.xmin;
99         rect.ymax = scirct->ymax - ar->winrct.ymin;
100
101         /* set transp line */
102         GPU_blend(true);
103         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
104
105         float color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
106         UI_GetThemeColor3fv(TH_EDITOR_OUTLINE, color);
107
108         GPUVertFormat *format = immVertexFormat();
109         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
110         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
111         immUniformColor4fv(color);
112
113         immBeginAtMost(GPU_PRIM_LINES, 8);
114
115         /* right */
116         if (sides & REGION_EMBOSS_RIGHT) {
117                 immVertex2f(pos, rect.xmax, rect.ymax);
118                 immVertex2f(pos, rect.xmax, rect.ymin);
119         }
120
121         /* bottom */
122         if (sides & REGION_EMBOSS_BOTTOM) {
123                 immVertex2f(pos, rect.xmax, rect.ymin);
124                 immVertex2f(pos, rect.xmin, rect.ymin);
125         }
126
127         /* left */
128         if (sides & REGION_EMBOSS_LEFT) {
129                 immVertex2f(pos, rect.xmin, rect.ymin);
130                 immVertex2f(pos, rect.xmin, rect.ymax);
131         }
132
133         /* top */
134         if (sides & REGION_EMBOSS_TOP) {
135                 immVertex2f(pos, rect.xmin, rect.ymax);
136                 immVertex2f(pos, rect.xmax, rect.ymax);
137         }
138
139         immEnd();
140         immUnbindProgram();
141
142         GPU_blend(false);
143         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
144 }
145
146 void ED_region_pixelspace(ARegion *ar)
147 {
148         wmOrtho2_region_pixelspace(ar);
149         GPU_matrix_identity_set();
150 }
151
152 /* only exported for WM */
153 void ED_region_do_listen(wmWindow *win, ScrArea *sa, ARegion *ar, wmNotifier *note, const Scene *scene)
154 {
155         /* generic notes first */
156         switch (note->category) {
157                 case NC_WM:
158                         if (note->data == ND_FILEREAD)
159                                 ED_region_tag_redraw(ar);
160                         break;
161                 case NC_WINDOW:
162                         ED_region_tag_redraw(ar);
163                         break;
164         }
165
166         if (ar->type && ar->type->listener)
167                 ar->type->listener(win, sa, ar, note, scene);
168 }
169
170 /* only exported for WM */
171 void ED_area_do_listen(wmWindow *win, ScrArea *sa, wmNotifier *note, Scene *scene)
172 {
173         /* no generic notes? */
174         if (sa->type && sa->type->listener) {
175                 sa->type->listener(win, sa, note, scene);
176         }
177 }
178
179 /* only exported for WM */
180 void ED_area_do_refresh(bContext *C, ScrArea *sa)
181 {
182         /* no generic notes? */
183         if (sa->type && sa->type->refresh) {
184                 sa->type->refresh(C, sa);
185         }
186         sa->do_refresh = false;
187 }
188
189 /**
190  * Action zones are only updated if the mouse is inside of them, but in some cases (currently only fullscreen icon)
191  * it might be needed to update their properties and redraw if the mouse isn't inside.
192  */
193 void ED_area_azones_update(ScrArea *sa, const int mouse_xy[2])
194 {
195         AZone *az;
196         bool changed = false;
197
198         for (az = sa->actionzones.first; az; az = az->next) {
199                 if (az->type == AZONE_FULLSCREEN) {
200                         /* only if mouse is not hovering the azone */
201                         if (BLI_rcti_isect_pt_v(&az->rect, mouse_xy) == false) {
202                                 az->alpha = 0.0f;
203                                 changed = true;
204
205                                 /* can break since currently only this is handled here */
206                                 break;
207                         }
208                 }
209                 else if (az->type == AZONE_REGION_SCROLL) {
210                         /* only if mouse is not hovering the azone */
211                         if (BLI_rcti_isect_pt_v(&az->rect, mouse_xy) == false) {
212                                 View2D *v2d = &az->ar->v2d;
213
214                                 if (az->direction == AZ_SCROLL_VERT) {
215                                         az->alpha = v2d->alpha_vert = 0;
216                                         changed = true;
217                                 }
218                                 else if (az->direction == AZ_SCROLL_HOR) {
219                                         az->alpha = v2d->alpha_hor = 0;
220                                         changed = true;
221                                 }
222                                 else {
223                                         BLI_assert(0);
224                                 }
225                         }
226                 }
227         }
228
229         if (changed) {
230                 sa->flag &= ~AREA_FLAG_ACTIONZONES_UPDATE;
231                 ED_area_tag_redraw_no_rebuild(sa);
232         }
233 }
234
235 /**
236  * \brief Corner widget use for quitting fullscreen.
237  */
238 static void area_draw_azone_fullscreen(short x1, short y1, short x2, short y2, float alpha)
239 {
240         int x = x2 - ((float) x2 - x1) * 0.5f / UI_DPI_FAC;
241         int y = y2 - ((float) y2 - y1) * 0.5f / UI_DPI_FAC;
242
243         /* adjust the icon distance from the corner */
244         x += 36.0f / UI_DPI_FAC;
245         y += 36.0f / UI_DPI_FAC;
246
247         /* draws from the left bottom corner of the icon */
248         x -= UI_DPI_ICON_SIZE;
249         y -= UI_DPI_ICON_SIZE;
250
251         alpha = min_ff(alpha, 0.75f);
252
253         UI_icon_draw_aspect(x, y, ICON_FULLSCREEN_EXIT, 0.7f / UI_DPI_FAC, alpha, NULL);
254
255         /* debug drawing :
256          * The click_rect is the same as defined in fullscreen_click_rcti_init
257          * Keep them both in sync */
258
259         if (G.debug_value == 1) {
260                 rcti click_rect;
261                 float icon_size = UI_DPI_ICON_SIZE + 7 * UI_DPI_FAC;
262
263                 BLI_rcti_init(&click_rect, x, x + icon_size, y, y + icon_size);
264
265                 GPUVertFormat *format = immVertexFormat();
266                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
267
268                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
269
270                 immUniformColor4f(1.0f, 0.0f, 0.0f, alpha);
271                 imm_draw_box_wire_2d(pos, click_rect.xmin, click_rect.ymin, click_rect.xmax, click_rect.ymax);
272
273                 immUniformColor4f(0.0f, 1.0f, 1.0f, alpha);
274                 immBegin(GPU_PRIM_LINES, 4);
275                 immVertex2f(pos, click_rect.xmin, click_rect.ymin);
276                 immVertex2f(pos, click_rect.xmax, click_rect.ymax);
277                 immVertex2f(pos, click_rect.xmin, click_rect.ymax);
278                 immVertex2f(pos, click_rect.xmax, click_rect.ymin);
279                 immEnd();
280
281                 immUnbindProgram();
282         }
283 }
284
285 /**
286  * \brief Corner widgets use for dragging and splitting the view.
287  */
288 static void area_draw_azone(short UNUSED(x1), short UNUSED(y1), short UNUSED(x2), short UNUSED(y2))
289 {
290         /* No drawing needed since all corners are action zone, and visually distinguishable. */
291 }
292
293 static void draw_azone_plus(float x1, float y1, float x2, float y2)
294 {
295         float width = 0.1f * U.widget_unit;
296         float pad = 0.2f * U.widget_unit;
297
298         GPUVertFormat *format = immVertexFormat();
299         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
300
301         GPU_blend(true);
302         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
303         immUniformColor4f(0.8f, 0.8f, 0.8f, 0.4f);
304
305         immRectf(pos, (x1 + x2 - width) * 0.5f, y1 + pad, (x1 + x2 + width) * 0.5f, y2 - pad);
306         immRectf(pos, x1 + pad, (y1 + y2 - width) * 0.5f, (x1 + x2 - width) * 0.5f, (y1 + y2 + width) * 0.5f);
307         immRectf(pos, (x1 + x2 + width) * 0.5f, (y1 + y2 - width) * 0.5f, x2 - pad, (y1 + y2 + width) * 0.5f);
308
309         immUnbindProgram();
310         GPU_blend(false);
311 }
312
313 static void region_draw_azone_tab_plus(AZone *az)
314 {
315         GPU_blend(true);
316
317         /* add code to draw region hidden as 'too small' */
318         switch (az->edge) {
319                 case AE_TOP_TO_BOTTOMRIGHT:
320                         UI_draw_roundbox_corner_set(UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT);
321                         break;
322                 case AE_BOTTOM_TO_TOPLEFT:
323                         UI_draw_roundbox_corner_set(UI_CNR_BOTTOM_RIGHT | UI_CNR_BOTTOM_LEFT);
324                         break;
325                 case AE_LEFT_TO_TOPRIGHT:
326                         UI_draw_roundbox_corner_set(UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT);
327                         break;
328                 case AE_RIGHT_TO_TOPLEFT:
329                         UI_draw_roundbox_corner_set(UI_CNR_TOP_RIGHT | UI_CNR_BOTTOM_RIGHT);
330                         break;
331         }
332
333         float color[4] = {0.05f, 0.05f, 0.05f, 0.4f};
334         UI_draw_roundbox_aa(true, (float)az->x1, (float)az->y1, (float)az->x2, (float)az->y2, 4.0f, color);
335
336         draw_azone_plus((float)az->x1, (float)az->y1, (float)az->x2, (float)az->y2);
337 }
338
339 static void area_azone_tag_update(ScrArea *sa)
340 {
341         sa->flag |= AREA_FLAG_ACTIONZONES_UPDATE;
342 }
343
344 static void region_draw_azones(ScrArea *sa, ARegion *ar)
345 {
346         AZone *az;
347
348         if (!sa)
349                 return;
350
351         GPU_line_width(1.0f);
352         GPU_blend(true);
353         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
354
355         GPU_matrix_push();
356         GPU_matrix_translate_2f(-ar->winrct.xmin, -ar->winrct.ymin);
357
358         for (az = sa->actionzones.first; az; az = az->next) {
359                 /* test if action zone is over this region */
360                 rcti azrct;
361                 BLI_rcti_init(&azrct, az->x1, az->x2, az->y1, az->y2);
362
363                 if (BLI_rcti_isect(&ar->drawrct, &azrct, NULL)) {
364                         if (az->type == AZONE_AREA) {
365                                 area_draw_azone(az->x1, az->y1, az->x2, az->y2);
366                         }
367                         else if (az->type == AZONE_REGION) {
368                                 if (az->ar) {
369                                         /* only display tab or icons when the region is hidden */
370                                         if (az->ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
371                                                 region_draw_azone_tab_plus(az);
372                                         }
373                                 }
374                         }
375                         else if (az->type == AZONE_FULLSCREEN) {
376                                 area_draw_azone_fullscreen(az->x1, az->y1, az->x2, az->y2, az->alpha);
377
378                                 if (az->alpha != 0.0f) {
379                                         area_azone_tag_update(sa);
380                                 }
381                         }
382                         else if (az->type == AZONE_REGION_SCROLL) {
383                                 if (az->alpha != 0.0f) {
384                                         area_azone_tag_update(sa);
385                                 }
386                                 /* Don't draw this azone. */
387                         }
388                 }
389         }
390
391         GPU_matrix_pop();
392
393         GPU_blend(false);
394 }
395
396 static void region_draw_status_text(ScrArea *sa, ARegion *ar)
397 {
398         bool overlap = ED_region_is_overlap(sa->spacetype, ar->regiontype);
399
400         if (overlap) {
401                 GPU_clear_color(0.0, 0.0, 0.0, 0.0);
402                 glClear(GL_COLOR_BUFFER_BIT);
403         }
404         else {
405                 UI_ThemeClearColor(TH_HEADER);
406                 glClear(GL_COLOR_BUFFER_BIT);
407         }
408
409         int fontid = BLF_set_default();
410
411         const float width = BLF_width(fontid, ar->headerstr, BLF_DRAW_STR_DUMMY_MAX);
412         const float x = UI_UNIT_X;
413         const float y = 0.4f * UI_UNIT_Y;
414
415         if (overlap) {
416                 const float pad = 2.0f * UI_DPI_FAC;
417                 const float x1 = x - (UI_UNIT_X - pad);
418                 const float x2 = x + width + (UI_UNIT_X - pad);
419                 const float y1 = pad;
420                 const float y2 = ar->winy - pad;
421
422                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
423
424                 float color[4] = {0.0f, 0.0f, 0.0f, 0.5f};
425                 UI_GetThemeColor3fv(TH_BACK, color);
426                 UI_draw_roundbox_corner_set(UI_CNR_ALL);
427                 UI_draw_roundbox_aa(true, x1, y1, x2, y2, 4.0f, color);
428
429                 UI_FontThemeColor(fontid, TH_TEXT);
430         }
431         else {
432                 UI_FontThemeColor(fontid, TH_TEXT);
433         }
434
435         BLF_position(fontid, x, y, 0.0f);
436         BLF_draw(fontid, ar->headerstr, BLF_DRAW_STR_DUMMY_MAX);
437 }
438
439 /* Follow wmMsgNotifyFn spec */
440 void ED_region_do_msg_notify_tag_redraw(
441         bContext *UNUSED(C), wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
442 {
443         ARegion *ar = msg_val->owner;
444         ED_region_tag_redraw(ar);
445
446         /* This avoids _many_ situations where header/properties control display settings.
447          * the common case is space properties in the header */
448         if (ELEM(ar->regiontype, RGN_TYPE_HEADER, RGN_TYPE_UI)) {
449                 while (ar && ar->prev) {
450                         ar = ar->prev;
451                 }
452                 for (; ar; ar = ar->next) {
453                         if (ELEM(ar->regiontype, RGN_TYPE_WINDOW, RGN_TYPE_CHANNELS)) {
454                                 ED_region_tag_redraw(ar);
455                         }
456                 }
457         }
458 }
459 /* Follow wmMsgNotifyFn spec */
460 void ED_area_do_msg_notify_tag_refresh(
461         bContext *UNUSED(C), wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
462 {
463         ScrArea *sa = msg_val->user_data;
464         ED_area_tag_refresh(sa);
465 }
466
467 /**
468  * Although there's no general support for minimizing areas, the status-bar can
469  * be snapped to be only a few pixels high. A few pixels rather than 0 so it
470  * can be un-minimized again. We consider it pseudo-minimalized and don't draw
471  * it then.
472  */
473 static bool area_is_pseudo_minimized(const ScrArea *area)
474 {
475         return (area->winx < 3) || (area->winy < 3);
476 }
477
478 /* only exported for WM */
479 void ED_region_do_layout(bContext *C, ARegion *ar)
480 {
481         /* This is optional, only needed for dynamically sized regions. */
482         ScrArea *sa = CTX_wm_area(C);
483         ARegionType *at = ar->type;
484
485         if (!at->layout) {
486                 return;
487         }
488
489         if (at->do_lock || (sa && area_is_pseudo_minimized(sa))) {
490                 return;
491         }
492
493         ar->do_draw |= RGN_DRAWING;
494
495         UI_SetTheme(sa ? sa->spacetype : 0, at->regionid);
496         at->layout(C, ar);
497 }
498
499 /* only exported for WM */
500 void ED_region_do_draw(bContext *C, ARegion *ar)
501 {
502         wmWindow *win = CTX_wm_window(C);
503         ScrArea *sa = CTX_wm_area(C);
504         ARegionType *at = ar->type;
505
506         /* see BKE_spacedata_draw_locks() */
507         if (at->do_lock)
508                 return;
509
510         ar->do_draw |= RGN_DRAWING;
511
512         /* Set viewport, scissor, ortho and ar->drawrct. */
513         wmPartialViewport(&ar->drawrct, &ar->winrct, &ar->drawrct);
514
515         wmOrtho2_region_pixelspace(ar);
516
517         UI_SetTheme(sa ? sa->spacetype : 0, at->regionid);
518
519         if (sa && area_is_pseudo_minimized(sa)) {
520                 UI_ThemeClearColor(TH_EDITOR_OUTLINE);
521                 glClear(GL_COLOR_BUFFER_BIT);
522                 return;
523         }
524         /* optional header info instead? */
525         else if (ar->headerstr) {
526                 region_draw_status_text(sa, ar);
527         }
528         else if (at->draw) {
529                 at->draw(C, ar);
530         }
531
532         /* XXX test: add convention to end regions always in pixel space, for drawing of borders/gestures etc */
533         ED_region_pixelspace(ar);
534
535         ED_region_draw_cb_draw(C, ar, REGION_DRAW_POST_PIXEL);
536
537         region_draw_azones(sa, ar);
538
539         /* for debugging unneeded area redraws and partial redraw */
540 #if 0
541         GPU_blend(true);
542         GPUVertFormat *format = immVertexFormat();
543         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
544         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
545         immUniformColor4f(drand48(), drand48(), drand48(), 0.1f);
546         immRectf(pos, ar->drawrct.xmin - ar->winrct.xmin, ar->drawrct.ymin - ar->winrct.ymin,
547                 ar->drawrct.xmax - ar->winrct.xmin, ar->drawrct.ymax - ar->winrct.ymin);
548         immUnbindProgram();
549         GPU_blend(false);
550 #endif
551
552         memset(&ar->drawrct, 0, sizeof(ar->drawrct));
553
554         UI_blocklist_free_inactive(C, &ar->uiblocks);
555
556         if (sa) {
557                 const bScreen *screen = WM_window_get_active_screen(win);
558
559                 /* Only draw region emboss for top-bar and quad-view. */
560                 if ((screen->state != SCREENFULL) && ED_area_is_global(sa)) {
561                         region_draw_emboss(ar, &ar->winrct, (REGION_EMBOSS_LEFT | REGION_EMBOSS_RIGHT));
562                 }
563                 else if ((ar->regiontype == RGN_TYPE_WINDOW) && (ar->alignment == RGN_ALIGN_QSPLIT)) {
564                         region_draw_emboss(ar, &ar->winrct, REGION_EMBOSS_ALL);
565                 }
566         }
567
568         /* We may want to detach message-subscriptions from drawing. */
569         {
570                 WorkSpace *workspace = CTX_wm_workspace(C);
571                 wmWindowManager *wm = CTX_wm_manager(C);
572                 bScreen *screen = WM_window_get_active_screen(win);
573                 Scene *scene = CTX_data_scene(C);
574                 struct wmMsgBus *mbus = wm->message_bus;
575                 WM_msgbus_clear_by_owner(mbus, ar);
576
577                 /* Cheat, always subscribe to this space type properties.
578                  *
579                  * This covers most cases and avoids copy-paste similar code for each space type.
580                  */
581                 if (ELEM(ar->regiontype, RGN_TYPE_WINDOW, RGN_TYPE_CHANNELS, RGN_TYPE_UI, RGN_TYPE_TOOLS)) {
582                         SpaceLink *sl = sa->spacedata.first;
583
584                         PointerRNA ptr;
585                         RNA_pointer_create(&screen->id, &RNA_Space, sl, &ptr);
586
587                         wmMsgSubscribeValue msg_sub_value_region_tag_redraw = {
588                                 .owner = ar,
589                                 .user_data = ar,
590                                 .notify = ED_region_do_msg_notify_tag_redraw,
591                         };
592                         /* All properties for this space type. */
593                         WM_msg_subscribe_rna(mbus, &ptr, NULL, &msg_sub_value_region_tag_redraw, __func__);
594                 }
595
596                 ED_region_message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
597         }
598 }
599
600 /* **********************************
601  * maybe silly, but let's try for now
602  * to keep these tags protected
603  * ********************************** */
604
605 void ED_region_tag_redraw(ARegion *ar)
606 {
607         /* don't tag redraw while drawing, it shouldn't happen normally
608          * but python scripts can cause this to happen indirectly */
609         if (ar && !(ar->do_draw & RGN_DRAWING)) {
610                 /* zero region means full region redraw */
611                 ar->do_draw &= ~(RGN_DRAW_PARTIAL | RGN_DRAW_NO_REBUILD);
612                 ar->do_draw |= RGN_DRAW;
613                 memset(&ar->drawrct, 0, sizeof(ar->drawrct));
614         }
615 }
616
617 void ED_region_tag_redraw_overlay(ARegion *ar)
618 {
619         if (ar)
620                 ar->do_draw_overlay = RGN_DRAW;
621 }
622
623 void ED_region_tag_redraw_no_rebuild(ARegion *ar)
624 {
625         if (ar && !(ar->do_draw & (RGN_DRAWING | RGN_DRAW))) {
626                 ar->do_draw &= ~RGN_DRAW_PARTIAL;
627                 ar->do_draw |= RGN_DRAW_NO_REBUILD;
628                 memset(&ar->drawrct, 0, sizeof(ar->drawrct));
629         }
630 }
631
632 void ED_region_tag_refresh_ui(ARegion *ar)
633 {
634         if (ar) {
635                 ar->do_draw |= RGN_DRAW_REFRESH_UI;
636         }
637 }
638
639 void ED_region_tag_redraw_partial(ARegion *ar, const rcti *rct)
640 {
641         if (ar && !(ar->do_draw & RGN_DRAWING)) {
642                 if (!(ar->do_draw & (RGN_DRAW | RGN_DRAW_NO_REBUILD | RGN_DRAW_PARTIAL))) {
643                         /* no redraw set yet, set partial region */
644                         ar->do_draw |= RGN_DRAW_PARTIAL;
645                         ar->drawrct = *rct;
646                 }
647                 else if (ar->drawrct.xmin != ar->drawrct.xmax) {
648                         BLI_assert((ar->do_draw & RGN_DRAW_PARTIAL) != 0);
649                         /* partial redraw already set, expand region */
650                         BLI_rcti_union(&ar->drawrct, rct);
651                 }
652                 else {
653                         BLI_assert((ar->do_draw & (RGN_DRAW | RGN_DRAW_NO_REBUILD)) != 0);
654                         /* Else, full redraw is already requested, nothing to do here. */
655                 }
656         }
657 }
658
659 void ED_area_tag_redraw(ScrArea *sa)
660 {
661         ARegion *ar;
662
663         if (sa)
664                 for (ar = sa->regionbase.first; ar; ar = ar->next)
665                         ED_region_tag_redraw(ar);
666 }
667
668 void ED_area_tag_redraw_no_rebuild(ScrArea *sa)
669 {
670         ARegion *ar;
671
672         if (sa)
673                 for (ar = sa->regionbase.first; ar; ar = ar->next)
674                         ED_region_tag_redraw_no_rebuild(ar);
675 }
676
677 void ED_area_tag_redraw_regiontype(ScrArea *sa, int regiontype)
678 {
679         ARegion *ar;
680
681         if (sa) {
682                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
683                         if (ar->regiontype == regiontype) {
684                                 ED_region_tag_redraw(ar);
685                         }
686                 }
687         }
688 }
689
690 void ED_area_tag_refresh(ScrArea *sa)
691 {
692         if (sa)
693                 sa->do_refresh = true;
694 }
695
696 /* *************************************************************** */
697
698 /* use NULL to disable it */
699 void ED_area_status_text(ScrArea *sa, const char *str)
700 {
701         ARegion *ar;
702
703         /* happens when running transform operators in background mode */
704         if (sa == NULL)
705                 return;
706
707         for (ar = sa->regionbase.first; ar; ar = ar->next) {
708                 if (ar->regiontype == RGN_TYPE_HEADER) {
709                         if (str) {
710                                 if (ar->headerstr == NULL)
711                                         ar->headerstr = MEM_mallocN(UI_MAX_DRAW_STR, "headerprint");
712                                 BLI_strncpy(ar->headerstr, str, UI_MAX_DRAW_STR);
713                                 BLI_str_rstrip(ar->headerstr);
714                         }
715                         else if (ar->headerstr) {
716                                 MEM_freeN(ar->headerstr);
717                                 ar->headerstr = NULL;
718                         }
719                         ED_region_tag_redraw(ar);
720                 }
721         }
722 }
723
724 void ED_workspace_status_text(bContext *C, const char *str)
725 {
726         wmWindow *win = CTX_wm_window(C);
727         WorkSpace *workspace = CTX_wm_workspace(C);
728
729         /* Can be NULL when running operators in background mode. */
730         if (workspace == NULL)
731                 return;
732
733         if (str) {
734                 if (workspace->status_text == NULL)
735                         workspace->status_text = MEM_mallocN(UI_MAX_DRAW_STR, "headerprint");
736                 BLI_strncpy(workspace->status_text, str, UI_MAX_DRAW_STR);
737         }
738         else if (workspace->status_text) {
739                 MEM_freeN(workspace->status_text);
740                 workspace->status_text = NULL;
741         }
742
743         /* Redraw status bar. */
744         for (ScrArea *sa = win->global_areas.areabase.first; sa; sa = sa->next) {
745                 if (sa->spacetype == SPACE_STATUSBAR) {
746                         ED_area_tag_redraw(sa);
747                         break;
748                 }
749         }
750 }
751
752 /* ************************************************************ */
753
754
755 static void area_azone_initialize(wmWindow *win, const bScreen *screen, ScrArea *sa)
756 {
757         AZone *az;
758
759         /* reinitialize entirely, regions and fullscreen add azones too */
760         BLI_freelistN(&sa->actionzones);
761
762         if (screen->state != SCREENNORMAL) {
763                 return;
764         }
765
766         if (U.app_flag & USER_APP_LOCK_UI_LAYOUT) {
767                 return;
768         }
769
770         if (ED_area_is_global(sa)) {
771                 return;
772         }
773
774         float coords[4][4] = {
775             /* Bottom-left. */
776             {sa->totrct.xmin,
777              sa->totrct.ymin,
778              sa->totrct.xmin + (AZONESPOT - 1),
779              sa->totrct.ymin + (AZONESPOT - 1)},
780             /* Bottom-right. */
781             {sa->totrct.xmax - (AZONESPOT - 1),
782              sa->totrct.ymin,
783              sa->totrct.xmax,
784              sa->totrct.ymin + (AZONESPOT - 1)},
785             /* Top-left. */
786             {sa->totrct.xmin,
787              sa->totrct.ymax - (AZONESPOT - 1),
788              sa->totrct.xmin + (AZONESPOT - 1),
789              sa->totrct.ymax},
790             /* Top-right. */
791             {sa->totrct.xmax - (AZONESPOT - 1),
792              sa->totrct.ymax - (AZONESPOT - 1),
793              sa->totrct.xmax,
794              sa->totrct.ymax}};
795
796         for (int i = 0; i < 4; i++) {
797                 /* can't click on bottom corners on OS X, already used for resizing */
798 #ifdef __APPLE__
799                 if (!WM_window_is_fullscreen(win) &&
800                     ((coords[i][0] == 0 && coords[i][1] == 0) ||
801                      (coords[i][0] == WM_window_pixels_x(win) && coords[i][1] == 0)))
802                 {
803                         continue;
804                 }
805 #else
806                 (void)win;
807 #endif
808
809                 /* set area action zones */
810                 az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
811                 BLI_addtail(&(sa->actionzones), az);
812                 az->type = AZONE_AREA;
813                 az->x1 = coords[i][0];
814                 az->y1 = coords[i][1];
815                 az->x2 = coords[i][2];
816                 az->y2 = coords[i][3];
817                 BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
818         }
819 }
820
821 static void fullscreen_azone_initialize(ScrArea *sa, ARegion *ar)
822 {
823         AZone *az;
824
825         if (ED_area_is_global(sa) || (ar->regiontype != RGN_TYPE_WINDOW))
826                 return;
827
828         az = (AZone *)MEM_callocN(sizeof(AZone), "fullscreen action zone");
829         BLI_addtail(&(sa->actionzones), az);
830         az->type = AZONE_FULLSCREEN;
831         az->ar = ar;
832         az->alpha = 0.0f;
833
834         az->x1 = ar->winrct.xmax - (AZONEFADEOUT - 1);
835         az->y1 = ar->winrct.ymax - (AZONEFADEOUT - 1);
836         az->x2 = ar->winrct.xmax;
837         az->y2 = ar->winrct.ymax;
838         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
839 }
840
841 #define AZONEPAD_EDGE   (0.1f * U.widget_unit)
842 #define AZONEPAD_ICON   (0.45f * U.widget_unit)
843 static void region_azone_edge(AZone *az, ARegion *ar)
844 {
845         switch (az->edge) {
846                 case AE_TOP_TO_BOTTOMRIGHT:
847                         az->x1 = ar->winrct.xmin;
848                         az->y1 = ar->winrct.ymax - AZONEPAD_EDGE;
849                         az->x2 = ar->winrct.xmax;
850                         az->y2 = ar->winrct.ymax + AZONEPAD_EDGE;
851                         break;
852                 case AE_BOTTOM_TO_TOPLEFT:
853                         az->x1 = ar->winrct.xmin;
854                         az->y1 = ar->winrct.ymin + AZONEPAD_EDGE;
855                         az->x2 = ar->winrct.xmax;
856                         az->y2 = ar->winrct.ymin - AZONEPAD_EDGE;
857                         break;
858                 case AE_LEFT_TO_TOPRIGHT:
859                         az->x1 = ar->winrct.xmin - AZONEPAD_EDGE;
860                         az->y1 = ar->winrct.ymin;
861                         az->x2 = ar->winrct.xmin + AZONEPAD_EDGE;
862                         az->y2 = ar->winrct.ymax;
863                         break;
864                 case AE_RIGHT_TO_TOPLEFT:
865                         az->x1 = ar->winrct.xmax + AZONEPAD_EDGE;
866                         az->y1 = ar->winrct.ymin;
867                         az->x2 = ar->winrct.xmax - AZONEPAD_EDGE;
868                         az->y2 = ar->winrct.ymax;
869                         break;
870         }
871
872         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
873 }
874
875 /* region already made zero sized, in shape of edge */
876 static void region_azone_tab_plus(ScrArea *sa, AZone *az, ARegion *ar)
877 {
878         AZone *azt;
879         int tot = 0, add;
880         /* Edge offset multiplied by the  */
881
882         float edge_offset = 1.0f;
883         const float tab_size_x = 0.7f * U.widget_unit;
884         const float tab_size_y = 0.7f * U.widget_unit;
885
886
887         for (azt = sa->actionzones.first; azt; azt = azt->next) {
888                 if (azt->edge == az->edge) tot++;
889         }
890
891         switch (az->edge) {
892                 case AE_TOP_TO_BOTTOMRIGHT:
893                         add = (ar->winrct.ymax == sa->totrct.ymin) ? 1 : 0;
894                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
895                         az->y1 = ar->winrct.ymax - add;
896                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
897                         az->y2 = ar->winrct.ymax - add + tab_size_y;
898                         break;
899                 case AE_BOTTOM_TO_TOPLEFT:
900                         az->x1 = ar->winrct.xmax - ((edge_offset + 1.0f) * tab_size_x);
901                         az->y1 = ar->winrct.ymin - tab_size_y;
902                         az->x2 = ar->winrct.xmax - (edge_offset * tab_size_x);
903                         az->y2 = ar->winrct.ymin;
904                         break;
905                 case AE_LEFT_TO_TOPRIGHT:
906                         az->x1 = ar->winrct.xmin - tab_size_y;
907                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
908                         az->x2 = ar->winrct.xmin;
909                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
910                         break;
911                 case AE_RIGHT_TO_TOPLEFT:
912                         az->x1 = ar->winrct.xmax - 1;
913                         az->y1 = ar->winrct.ymax - ((edge_offset + 1.0f) * tab_size_x);
914                         az->x2 = ar->winrct.xmax - 1 + tab_size_y;
915                         az->y2 = ar->winrct.ymax - (edge_offset * tab_size_x);
916                         break;
917         }
918         /* rect needed for mouse pointer test */
919         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
920 }
921
922 static void region_azone_edge_initialize(ScrArea *sa, ARegion *ar, AZEdge edge, const bool is_fullscreen)
923 {
924         AZone *az = NULL;
925         const bool is_hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
926
927         if (is_hidden && is_fullscreen) {
928                 return;
929         }
930
931         az = (AZone *)MEM_callocN(sizeof(AZone), "actionzone");
932         BLI_addtail(&(sa->actionzones), az);
933         az->type = AZONE_REGION;
934         az->ar = ar;
935         az->edge = edge;
936
937         if (is_hidden) {
938                 region_azone_tab_plus(sa, az, ar);
939         }
940         else if (!is_hidden && (ar->regiontype != RGN_TYPE_HEADER)) {
941                 region_azone_edge(az, ar);
942         }
943 }
944
945 static void region_azone_scrollbar_initialize(ScrArea *sa, ARegion *ar, AZScrollDirection direction)
946 {
947         rcti scroller_vert = (direction == AZ_SCROLL_VERT) ? ar->v2d.vert : ar->v2d.hor;
948         AZone *az = MEM_callocN(sizeof(*az), __func__);
949
950         BLI_addtail(&sa->actionzones, az);
951         az->type = AZONE_REGION_SCROLL;
952         az->ar = ar;
953         az->direction = direction;
954
955         if (direction == AZ_SCROLL_VERT) {
956                 az->ar->v2d.alpha_vert = 0;
957         }
958         else if (direction == AZ_SCROLL_HOR) {
959                 az->ar->v2d.alpha_hor = 0;
960         }
961
962         BLI_rcti_translate(&scroller_vert, ar->winrct.xmin, ar->winrct.ymin);
963         az->x1 = scroller_vert.xmin - AZONEFADEIN;
964         az->y1 = scroller_vert.ymin - AZONEFADEIN;
965         az->x2 = scroller_vert.xmax + AZONEFADEIN;
966         az->y2 = scroller_vert.ymax + AZONEFADEIN;
967
968         BLI_rcti_init(&az->rect, az->x1, az->x2, az->y1, az->y2);
969 }
970
971 static void region_azones_scrollbars_initialize(ScrArea *sa, ARegion *ar)
972 {
973         const View2D *v2d = &ar->v2d;
974
975         if ((v2d->scroll & V2D_SCROLL_VERTICAL)   && ((v2d->scroll & V2D_SCROLL_SCALE_VERTICAL)   == 0)) {
976                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_VERT);
977         }
978         if ((v2d->scroll & V2D_SCROLL_HORIZONTAL) && ((v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) == 0)) {
979                 region_azone_scrollbar_initialize(sa, ar, AZ_SCROLL_HOR);
980         }
981 }
982
983
984 /* *************************************************************** */
985
986 static void region_azones_add(const bScreen *screen, ScrArea *sa, ARegion *ar, const int alignment)
987 {
988         const bool is_fullscreen = screen->state == SCREENFULL;
989
990         /* edge code (t b l r) is along which area edge azone will be drawn */
991
992         if (ar->regiontype == RGN_TYPE_HEADER && ar->winy + 6 > sa->winy) {
993                 /* The logic for this is: when the header takes up the full area,
994                  * disallow hiding it to view the main window.
995                  *
996                  * Without this, you can drag down the file selectors header and hide it
997                  * by accident very easily (highly annoying!), the value 6 is arbitrary
998                  * but accounts for small common rounding problems when scaling the UI,
999                  * must be minimum '4' */
1000         }
1001         else if (alignment == RGN_ALIGN_TOP)
1002                 region_azone_edge_initialize(sa, ar, AE_BOTTOM_TO_TOPLEFT, is_fullscreen);
1003         else if (alignment == RGN_ALIGN_BOTTOM)
1004                 region_azone_edge_initialize(sa, ar, AE_TOP_TO_BOTTOMRIGHT, is_fullscreen);
1005         else if (alignment == RGN_ALIGN_RIGHT)
1006                 region_azone_edge_initialize(sa, ar, AE_LEFT_TO_TOPRIGHT, is_fullscreen);
1007         else if (alignment == RGN_ALIGN_LEFT)
1008                 region_azone_edge_initialize(sa, ar, AE_RIGHT_TO_TOPLEFT, is_fullscreen);
1009
1010         if (is_fullscreen) {
1011                 fullscreen_azone_initialize(sa, ar);
1012         }
1013
1014         region_azones_scrollbars_initialize(sa, ar);
1015 }
1016
1017 /* dir is direction to check, not the splitting edge direction! */
1018 static int rct_fits(const rcti *rect, char dir, int size)
1019 {
1020         if (dir == 'h') {
1021                 return BLI_rcti_size_x(rect) + 1 - size;
1022         }
1023         else {  /* 'v' */
1024                 return BLI_rcti_size_y(rect) + 1 - size;
1025         }
1026 }
1027
1028 /* *************************************************************** */
1029
1030 /* ar should be overlapping */
1031 /* function checks if some overlapping region was defined before - on same place */
1032 static void region_overlap_fix(ScrArea *sa, ARegion *ar)
1033 {
1034         ARegion *ar1;
1035         const int align = ar->alignment & ~RGN_SPLIT_PREV;
1036         int align1 = 0;
1037
1038         /* find overlapping previous region on same place */
1039         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1040                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1041                         continue;
1042                 }
1043
1044                 if (ar1->overlap && ((ar1->alignment & RGN_SPLIT_PREV) == 0)) {
1045                         if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1046                                 continue;
1047                         }
1048                         align1 = ar1->alignment;
1049                         if (BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1050                                 if (align1 != align) {
1051                                         /* Left overlapping right or vice-versa, forbid this! */
1052                                         ar->flag |= RGN_FLAG_TOO_SMALL;
1053                                         return;
1054                                 }
1055                                 /* Else, we have our previous region on same side. */
1056                                 break;
1057                         }
1058                 }
1059         }
1060
1061         /* translate or close */
1062         if (ar1) {
1063                 if (align1 == RGN_ALIGN_LEFT) {
1064                         if (ar->winrct.xmax + ar1->winx > sa->winx - U.widget_unit) {
1065                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1066                                 return;
1067                         }
1068                         else {
1069                                 BLI_rcti_translate(&ar->winrct, ar1->winx, 0);
1070                         }
1071                 }
1072                 else if (align1 == RGN_ALIGN_RIGHT) {
1073                         if (ar->winrct.xmin - ar1->winx < U.widget_unit) {
1074                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1075                                 return;
1076                         }
1077                         else {
1078                                 BLI_rcti_translate(&ar->winrct, -ar1->winx, 0);
1079                         }
1080                 }
1081         }
1082
1083         /* At this point, 'ar' is in its final position and still open.
1084          * Make a final check it does not overlap any previous 'other side' region. */
1085         for (ar1 = ar->prev; ar1; ar1 = ar1->prev) {
1086                 if (ar1->flag & (RGN_FLAG_HIDDEN)) {
1087                         continue;
1088                 }
1089                 if (ELEM(ar1->alignment, RGN_ALIGN_FLOAT)) {
1090                         continue;
1091                 }
1092
1093                 if (ar1->overlap && (ar1->alignment & RGN_SPLIT_PREV) == 0) {
1094                         if ((ar1->alignment != align) && BLI_rcti_isect(&ar1->winrct, &ar->winrct, NULL)) {
1095                                 /* Left overlapping right or vice-versa, forbid this! */
1096                                 ar->flag |= RGN_FLAG_TOO_SMALL;
1097                                 return;
1098                         }
1099                 }
1100         }
1101 }
1102
1103 /* overlapping regions only in the following restricted cases */
1104 bool ED_region_is_overlap(int spacetype, int regiontype)
1105 {
1106         if (regiontype == RGN_TYPE_HUD) {
1107                 return true;
1108         }
1109         if (U.uiflag2 & USER_REGION_OVERLAP) {
1110                 if (spacetype == SPACE_NODE) {
1111                         if (regiontype == RGN_TYPE_TOOLS) {
1112                                 return true;
1113                         }
1114                 }
1115                 else if (ELEM(spacetype, SPACE_VIEW3D, SPACE_SEQ, SPACE_IMAGE)) {
1116                         if (ELEM(regiontype, RGN_TYPE_TOOLS, RGN_TYPE_UI, RGN_TYPE_TOOL_PROPS)) {
1117                                 return true;
1118                         }
1119
1120                         if (ELEM(spacetype, SPACE_VIEW3D, SPACE_IMAGE)) {
1121                                 if (regiontype == RGN_TYPE_HEADER) {
1122                                         return true;
1123                                 }
1124                         }
1125                 }
1126         }
1127
1128         return false;
1129 }
1130
1131 static void region_rect_recursive(ScrArea *sa, ARegion *ar, rcti *remainder, rcti *overlap_remainder, int quad)
1132 {
1133         rcti *remainder_prev = remainder;
1134
1135         if (ar == NULL)
1136                 return;
1137
1138         int prev_winx = ar->winx;
1139         int prev_winy = ar->winy;
1140
1141         /* no returns in function, winrct gets set in the end again */
1142         BLI_rcti_init(&ar->winrct, 0, 0, 0, 0);
1143
1144         /* for test; allow split of previously defined region */
1145         if (ar->alignment & RGN_SPLIT_PREV)
1146                 if (ar->prev)
1147                         remainder = &ar->prev->winrct;
1148
1149         int alignment = ar->alignment & ~RGN_SPLIT_PREV;
1150
1151         /* set here, assuming userpref switching forces to call this again */
1152         ar->overlap = ED_region_is_overlap(sa->spacetype, ar->regiontype);
1153
1154         /* clear state flags first */
1155         ar->flag &= ~RGN_FLAG_TOO_SMALL;
1156         /* user errors */
1157         if ((ar->next == NULL) && !ELEM(alignment, RGN_ALIGN_QSPLIT, RGN_ALIGN_FLOAT)) {
1158                 alignment = RGN_ALIGN_NONE;
1159         }
1160
1161         /* prefsize, taking into account DPI */
1162         int prefsizex = UI_DPI_FAC * ((ar->sizex > 1) ? ar->sizex + 0.5f : ar->type->prefsizex);
1163         int prefsizey;
1164
1165         if (ar->flag & RGN_FLAG_PREFSIZE_OR_HIDDEN) {
1166                 prefsizex = UI_DPI_FAC * ar->type->prefsizex;
1167                 prefsizey = UI_DPI_FAC * ar->type->prefsizey;
1168         }
1169         else if (ar->regiontype == RGN_TYPE_HEADER) {
1170                 prefsizey = ED_area_headersize();
1171         }
1172         else if (ED_area_is_global(sa)) {
1173                 prefsizey = ED_region_global_size_y();
1174         }
1175         else if (ar->regiontype == RGN_TYPE_UI && sa->spacetype == SPACE_FILE) {
1176                 prefsizey = UI_UNIT_Y * 2 + (UI_UNIT_Y / 2);
1177         }
1178         else {
1179                 prefsizey = UI_DPI_FAC * (ar->sizey > 1 ? ar->sizey + 0.5f : ar->type->prefsizey);
1180         }
1181
1182
1183         if (ar->flag & RGN_FLAG_HIDDEN) {
1184                 /* hidden is user flag */
1185         }
1186         else if (alignment == RGN_ALIGN_FLOAT) {
1187                 /**
1188                  * \note Currently this window type is only used for #RGN_TYPE_HUD,
1189                  * We expect the panel to resize it's self to be larger.
1190                  *
1191                  * This aligns to the lower left of the area.
1192                  */
1193                 const int size_min[2] = {UI_UNIT_X, UI_UNIT_Y};
1194                 rcti overlap_remainder_margin = *overlap_remainder;
1195                 BLI_rcti_resize(
1196                         &overlap_remainder_margin,
1197                         max_ii(0, BLI_rcti_size_x(overlap_remainder) - UI_UNIT_X / 2),
1198                         max_ii(0, BLI_rcti_size_y(overlap_remainder) - UI_UNIT_Y / 2));
1199                 ar->winrct.xmin = overlap_remainder_margin.xmin;
1200                 ar->winrct.ymin = overlap_remainder_margin.ymin;
1201                 ar->winrct.xmax = ar->winrct.xmin + ar->sizex - 1;
1202                 ar->winrct.ymax = ar->winrct.ymin + ar->sizey - 1;
1203
1204                 BLI_rcti_isect(&ar->winrct, &overlap_remainder_margin, &ar->winrct);
1205
1206                 /* We need to use a test that wont have been previously clamped. */
1207                 rcti winrct_test = {
1208                         .xmin = ar->winrct.xmin,
1209                         .ymin = ar->winrct.ymin,
1210                         .xmax = ar->winrct.xmin + size_min[0],
1211                         .ymax = ar->winrct.ymin + size_min[1],
1212                 };
1213                 BLI_rcti_isect(&winrct_test, &overlap_remainder_margin, &winrct_test);
1214                 if (BLI_rcti_size_x(&winrct_test) < size_min[0] ||
1215                     BLI_rcti_size_y(&winrct_test) < size_min[1])
1216                 {
1217                         ar->flag |= RGN_FLAG_TOO_SMALL;
1218                 }
1219         }
1220         else if (rct_fits(remainder, 'v', 1) < 0 || rct_fits(remainder, 'h', 1) < 0) {
1221                 /* remainder is too small for any usage */
1222                 ar->flag |= RGN_FLAG_TOO_SMALL;
1223         }
1224         else if (alignment == RGN_ALIGN_NONE) {
1225                 /* typically last region */
1226                 ar->winrct = *remainder;
1227                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1228         }
1229         else if (alignment == RGN_ALIGN_TOP || alignment == RGN_ALIGN_BOTTOM) {
1230                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1231
1232                 if (rct_fits(winrct, 'v', prefsizey) < 0) {
1233                         ar->flag |= RGN_FLAG_TOO_SMALL;
1234                 }
1235                 else {
1236                         int fac = rct_fits(winrct, 'v', prefsizey);
1237
1238                         if (fac < 0)
1239                                 prefsizey += fac;
1240
1241                         ar->winrct = *winrct;
1242
1243                         if (alignment == RGN_ALIGN_TOP) {
1244                                 ar->winrct.ymin = ar->winrct.ymax - prefsizey + 1;
1245                                 winrct->ymax = ar->winrct.ymin - 1;
1246                         }
1247                         else {
1248                                 ar->winrct.ymax = ar->winrct.ymin + prefsizey - 1;
1249                                 winrct->ymin = ar->winrct.ymax + 1;
1250                         }
1251                 }
1252         }
1253         else if (ELEM(alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
1254                 rcti *winrct = (ar->overlap) ? overlap_remainder : remainder;
1255
1256                 if (rct_fits(winrct, 'h', prefsizex) < 0) {
1257                         ar->flag |= RGN_FLAG_TOO_SMALL;
1258                 }
1259                 else {
1260                         int fac = rct_fits(winrct, 'h', prefsizex);
1261
1262                         if (fac < 0)
1263                                 prefsizex += fac;
1264
1265                         ar->winrct = *winrct;
1266
1267                         if (alignment == RGN_ALIGN_RIGHT) {
1268                                 ar->winrct.xmin = ar->winrct.xmax - prefsizex + 1;
1269                                 winrct->xmax = ar->winrct.xmin - 1;
1270                         }
1271                         else {
1272                                 ar->winrct.xmax = ar->winrct.xmin + prefsizex - 1;
1273                                 winrct->xmin = ar->winrct.xmax + 1;
1274                         }
1275                 }
1276         }
1277         else if (alignment == RGN_ALIGN_VSPLIT || alignment == RGN_ALIGN_HSPLIT) {
1278                 /* percentage subdiv*/
1279                 ar->winrct = *remainder;
1280
1281                 if (alignment == RGN_ALIGN_HSPLIT) {
1282                         if (rct_fits(remainder, 'h', prefsizex) > 4) {
1283                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1284                                 remainder->xmin = ar->winrct.xmax + 1;
1285                         }
1286                         else {
1287                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1288                         }
1289                 }
1290                 else {
1291                         if (rct_fits(remainder, 'v', prefsizey) > 4) {
1292                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1293                                 remainder->ymin = ar->winrct.ymax + 1;
1294                         }
1295                         else {
1296                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1297                         }
1298                 }
1299         }
1300         else if (alignment == RGN_ALIGN_QSPLIT) {
1301                 ar->winrct = *remainder;
1302
1303                 /* test if there's still 4 regions left */
1304                 if (quad == 0) {
1305                         ARegion *artest = ar->next;
1306                         int count = 1;
1307
1308                         while (artest) {
1309                                 artest->alignment = RGN_ALIGN_QSPLIT;
1310                                 artest = artest->next;
1311                                 count++;
1312                         }
1313
1314                         if (count != 4) {
1315                                 /* let's stop adding regions */
1316                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1317                                 if (G.debug & G_DEBUG)
1318                                         printf("region quadsplit failed\n");
1319                         }
1320                         else {
1321                                 quad = 1;
1322                         }
1323                 }
1324                 if (quad) {
1325                         if (quad == 1) { /* left bottom */
1326                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1327                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1328                         }
1329                         else if (quad == 2) { /* left top */
1330                                 ar->winrct.xmax = BLI_rcti_cent_x(remainder);
1331                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1332                         }
1333                         else if (quad == 3) { /* right bottom */
1334                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1335                                 ar->winrct.ymax = BLI_rcti_cent_y(remainder);
1336                         }
1337                         else {  /* right top */
1338                                 ar->winrct.xmin = BLI_rcti_cent_x(remainder) + 1;
1339                                 ar->winrct.ymin = BLI_rcti_cent_y(remainder) + 1;
1340                                 BLI_rcti_init(remainder, 0, 0, 0, 0);
1341                         }
1342
1343                         quad++;
1344                 }
1345         }
1346
1347         /* for speedup */
1348         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1349         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1350
1351         /* if region opened normally, we store this for hide/reveal usage */
1352         /* prevent rounding errors for UI_DPI_FAC mult and divide */
1353         if (ar->winx > 1) ar->sizex = (ar->winx + 0.5f) /  UI_DPI_FAC;
1354         if (ar->winy > 1) ar->sizey = (ar->winy + 0.5f) /  UI_DPI_FAC;
1355
1356         /* exception for multiple overlapping regions on same spot */
1357         if (ar->overlap && (alignment != RGN_ALIGN_FLOAT)) {
1358                 region_overlap_fix(sa, ar);
1359         }
1360
1361         /* set winrect for azones */
1362         if (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) {
1363                 ar->winrct = (ar->overlap) ? *overlap_remainder : *remainder;
1364
1365                 switch (alignment) {
1366                         case RGN_ALIGN_TOP:
1367                                 ar->winrct.ymin = ar->winrct.ymax;
1368                                 break;
1369                         case RGN_ALIGN_BOTTOM:
1370                                 ar->winrct.ymax = ar->winrct.ymin;
1371                                 break;
1372                         case RGN_ALIGN_RIGHT:
1373                                 ar->winrct.xmin = ar->winrct.xmax;
1374                                 break;
1375                         case RGN_ALIGN_LEFT:
1376                         default:
1377                                 /* prevent winrct to be valid */
1378                                 ar->winrct.xmax = ar->winrct.xmin;
1379                                 break;
1380                 }
1381         }
1382
1383         /* restore prev-split exception */
1384         if (ar->alignment & RGN_SPLIT_PREV) {
1385                 if (ar->prev) {
1386                         remainder = remainder_prev;
1387                         ar->prev->winx = BLI_rcti_size_x(&ar->prev->winrct) + 1;
1388                         ar->prev->winy = BLI_rcti_size_y(&ar->prev->winrct) + 1;
1389                 }
1390         }
1391
1392         /* After non-overlapping region, all following overlapping regions
1393          * fit within the remaining space again. */
1394         if (!ar->overlap) {
1395                 *overlap_remainder = *remainder;
1396         }
1397
1398         region_rect_recursive(sa, ar->next, remainder, overlap_remainder, quad);
1399
1400         /* Tag for redraw if size changes. */
1401         if (ar->winx != prev_winx || ar->winy != prev_winy) {
1402                 ED_region_tag_redraw(ar);
1403         }
1404 }
1405
1406 static void area_calc_totrct(ScrArea *sa, const rcti *window_rect)
1407 {
1408         short px = (short)U.pixelsize;
1409
1410         sa->totrct.xmin = sa->v1->vec.x;
1411         sa->totrct.xmax = sa->v4->vec.x;
1412         sa->totrct.ymin = sa->v1->vec.y;
1413         sa->totrct.ymax = sa->v2->vec.y;
1414
1415         /* scale down totrct by 1 pixel on all sides not matching window borders */
1416         if (sa->totrct.xmin > window_rect->xmin) {
1417                 sa->totrct.xmin += px;
1418         }
1419         if (sa->totrct.xmax < (window_rect->xmax - 1)) {
1420                 sa->totrct.xmax -= px;
1421         }
1422         if (sa->totrct.ymin > window_rect->ymin) {
1423                 sa->totrct.ymin += px;
1424         }
1425         if (sa->totrct.ymax < (window_rect->ymax - 1)) {
1426                 sa->totrct.ymax -= px;
1427         }
1428         /* Although the following asserts are correct they lead to a very unstable Blender.
1429          * And the asserts would fail even in 2.7x (they were added in 2.8x as part of the top-bar commit).
1430          * For more details see T54864. */
1431 #if 0
1432         BLI_assert(sa->totrct.xmin >= 0);
1433         BLI_assert(sa->totrct.xmax >= 0);
1434         BLI_assert(sa->totrct.ymin >= 0);
1435         BLI_assert(sa->totrct.ymax >= 0);
1436 #endif
1437
1438         /* for speedup */
1439         sa->winx = BLI_rcti_size_x(&sa->totrct) + 1;
1440         sa->winy = BLI_rcti_size_y(&sa->totrct) + 1;
1441 }
1442
1443
1444 /* used for area initialize below */
1445 static void region_subwindow(ARegion *ar)
1446 {
1447         bool hidden = (ar->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL)) != 0;
1448
1449         if ((ar->alignment & RGN_SPLIT_PREV) && ar->prev)
1450                 hidden = hidden || (ar->prev->flag & (RGN_FLAG_HIDDEN | RGN_FLAG_TOO_SMALL));
1451
1452         ar->visible = !hidden;
1453 }
1454
1455 /**
1456  * \param ar: Region, may be NULL when adding handlers for \a sa.
1457  */
1458 static void ed_default_handlers(wmWindowManager *wm, ScrArea *sa, ARegion *ar, ListBase *handlers, int flag)
1459 {
1460         BLI_assert(ar ? (&ar->handlers == handlers) : (&sa->handlers == handlers));
1461
1462         /* note, add-handler checks if it already exists */
1463
1464         /* XXX it would be good to have boundbox checks for some of these... */
1465         if (flag & ED_KEYMAP_UI) {
1466                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "User Interface", 0, 0);
1467                 WM_event_add_keymap_handler(handlers, keymap);
1468
1469                 /* user interface widgets */
1470                 UI_region_handlers_add(handlers);
1471         }
1472         if (flag & ED_KEYMAP_GIZMO) {
1473                 BLI_assert(ar && ar->type->regionid == RGN_TYPE_WINDOW);
1474                 if (ar) {
1475                         /* Anything else is confusing, only allow this. */
1476                         BLI_assert(&ar->handlers == handlers);
1477                         if (ar->gizmo_map == NULL) {
1478                                 ar->gizmo_map = WM_gizmomap_new_from_type(
1479                                         &(const struct wmGizmoMapType_Params){sa->spacetype, ar->type->regionid});
1480                         }
1481                         WM_gizmomap_add_handlers(ar, ar->gizmo_map);
1482                 }
1483         }
1484         if (flag & ED_KEYMAP_VIEW2D) {
1485                 /* 2d-viewport handling+manipulation */
1486                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "View2D", 0, 0);
1487                 WM_event_add_keymap_handler(handlers, keymap);
1488         }
1489         if (flag & ED_KEYMAP_MARKERS) {
1490                 /* time-markers */
1491                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Markers", 0, 0);
1492
1493                 /* use a boundbox restricted map */
1494                 /* same local check for all areas */
1495                 static rcti rect = {0, 10000, 0, -1};
1496                 rect.ymax = UI_MARKER_MARGIN_Y;
1497                 BLI_assert(ar->type->regionid == RGN_TYPE_WINDOW);
1498                 WM_event_add_keymap_handler_bb(handlers, keymap, &rect, &ar->winrct);
1499         }
1500         if (flag & ED_KEYMAP_ANIMATION) {
1501                 /* frame changing and timeline operators (for time spaces) */
1502                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Animation", 0, 0);
1503                 WM_event_add_keymap_handler(handlers, keymap);
1504         }
1505         if (flag & ED_KEYMAP_FRAMES) {
1506                 /* frame changing/jumping (for all spaces) */
1507                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Frames", 0, 0);
1508                 WM_event_add_keymap_handler(handlers, keymap);
1509         }
1510         if (flag & ED_KEYMAP_HEADER) {
1511                 /* standard keymap for headers regions */
1512                 wmKeyMap *keymap = WM_keymap_ensure(wm->defaultconf, "Header", 0, 0);
1513                 WM_event_add_keymap_handler(handlers, keymap);
1514         }
1515
1516         /* Keep last because of LMB/RMB handling, see: T57527. */
1517         if (flag & ED_KEYMAP_GPENCIL) {
1518                 /* grease pencil */
1519                 /* NOTE: This is now 4 keymaps - One for basic functionality,
1520                  *       and others for special stroke modes (edit, paint and sculpt).
1521                  *
1522                  *       For now, it's easier to just include all,
1523                  *       since you hardly want one without the others.
1524                  */
1525                 wmKeyMap *keymap_general = WM_keymap_ensure(wm->defaultconf, "Grease Pencil", 0, 0);
1526                 WM_event_add_keymap_handler(handlers, keymap_general);
1527
1528                 wmKeyMap *keymap_edit = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Edit Mode", 0, 0);
1529                 WM_event_add_keymap_handler(handlers, keymap_edit);
1530
1531                 wmKeyMap *keymap_paint = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint Mode", 0, 0);
1532                 WM_event_add_keymap_handler(handlers, keymap_paint);
1533
1534                 wmKeyMap *keymap_paint_draw = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Draw brush)", 0, 0);
1535                 WM_event_add_keymap_handler(handlers, keymap_paint_draw);
1536
1537                 wmKeyMap *keymap_paint_erase = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Erase)", 0, 0);
1538                 WM_event_add_keymap_handler(handlers, keymap_paint_erase);
1539
1540                 wmKeyMap *keymap_paint_fill = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Paint (Fill)", 0, 0);
1541                 WM_event_add_keymap_handler(handlers, keymap_paint_fill);
1542
1543                 wmKeyMap *keymap_sculpt = WM_keymap_ensure(wm->defaultconf, "Grease Pencil Stroke Sculpt Mode", 0, 0);
1544                 WM_event_add_keymap_handler(handlers, keymap_sculpt);
1545         }
1546 }
1547
1548 void ED_area_update_region_sizes(wmWindowManager *wm, wmWindow *win, ScrArea *area)
1549 {
1550         rcti rect, overlap_rect;
1551         rcti window_rect;
1552
1553         if (!(area->flag & AREA_FLAG_REGION_SIZE_UPDATE)) {
1554                 return;
1555         }
1556
1557         WM_window_rect_calc(win, &window_rect);
1558         area_calc_totrct(area, &window_rect);
1559
1560         /* region rect sizes */
1561         rect = area->totrct;
1562         overlap_rect = rect;
1563         region_rect_recursive(area, area->regionbase.first, &rect, &overlap_rect, 0);
1564
1565         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
1566                 region_subwindow(ar);
1567
1568                 /* region size may have changed, init does necessary adjustments */
1569                 if (ar->type->init) {
1570                         ar->type->init(wm, ar);
1571                 }
1572         }
1573
1574         area->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1575 }
1576
1577 /* called in screen_refresh, or screens_init, also area size changes */
1578 void ED_area_initialize(wmWindowManager *wm, wmWindow *win, ScrArea *sa)
1579 {
1580         WorkSpace *workspace = WM_window_get_active_workspace(win);
1581         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
1582         ViewLayer *view_layer = WM_window_get_active_view_layer(win);
1583         ARegion *ar;
1584         rcti rect, overlap_rect;
1585         rcti window_rect;
1586
1587         if (ED_area_is_global(sa) && (sa->global->flag & GLOBAL_AREA_IS_HIDDEN)) {
1588                 return;
1589         }
1590         WM_window_rect_calc(win, &window_rect);
1591
1592         /* set typedefinitions */
1593         sa->type = BKE_spacetype_from_id(sa->spacetype);
1594
1595         if (sa->type == NULL) {
1596                 sa->spacetype = SPACE_VIEW3D;
1597                 sa->type = BKE_spacetype_from_id(sa->spacetype);
1598         }
1599
1600         for (ar = sa->regionbase.first; ar; ar = ar->next)
1601                 ar->type = BKE_regiontype_from_id_or_first(sa->type, ar->regiontype);
1602
1603         /* area sizes */
1604         area_calc_totrct(sa, &window_rect);
1605
1606         /* region rect sizes */
1607         rect = sa->totrct;
1608         overlap_rect = rect;
1609         region_rect_recursive(sa, sa->regionbase.first, &rect, &overlap_rect, 0);
1610         sa->flag &= ~AREA_FLAG_REGION_SIZE_UPDATE;
1611
1612         /* default area handlers */
1613         ed_default_handlers(wm, sa, NULL, &sa->handlers, sa->type->keymapflag);
1614         /* checks spacedata, adds own handlers */
1615         if (sa->type->init)
1616                 sa->type->init(wm, sa);
1617
1618         /* clear all azones, add the area triangle widgets */
1619         area_azone_initialize(win, screen, sa);
1620
1621         /* region windows, default and own handlers */
1622         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1623                 region_subwindow(ar);
1624
1625                 if (ar->visible) {
1626                         /* default region handlers */
1627                         ed_default_handlers(wm, sa, ar, &ar->handlers, ar->type->keymapflag);
1628                         /* own handlers */
1629                         if (ar->type->init) {
1630                                 ar->type->init(wm, ar);
1631                         }
1632                 }
1633                 else {
1634                         /* prevent uiblocks to run */
1635                         UI_blocklist_free(NULL, &ar->uiblocks);
1636                 }
1637
1638                 /* Some AZones use View2D data which is only updated in region init, so call that first! */
1639                 region_azones_add(screen, sa, ar, ar->alignment & ~RGN_SPLIT_PREV);
1640         }
1641
1642
1643         /* Avoid re-initializing tools while resizing the window. */
1644         if ((G.moving & G_TRANSFORM_WM) == 0) {
1645                 if ((1 << sa->spacetype) & WM_TOOLSYSTEM_SPACE_MASK) {
1646                         WM_toolsystem_refresh_screen_area(workspace, view_layer, sa);
1647                         sa->flag |= AREA_FLAG_ACTIVE_TOOL_UPDATE;
1648                 }
1649                 else {
1650                         sa->runtime.tool = NULL;
1651                         sa->runtime.is_tool_set = true;
1652                 }
1653         }
1654 }
1655
1656 static void region_update_rect(ARegion *ar)
1657 {
1658         ar->winx = BLI_rcti_size_x(&ar->winrct) + 1;
1659         ar->winy = BLI_rcti_size_y(&ar->winrct) + 1;
1660
1661         /* v2d mask is used to subtract scrollbars from a 2d view. Needs initialize here. */
1662         BLI_rcti_init(&ar->v2d.mask, 0, ar->winx - 1, 0, ar->winy -1);
1663 }
1664
1665 /**
1666  * Call to move a popup window (keep OpenGL context free!)
1667  */
1668 void ED_region_update_rect(ARegion *ar)
1669 {
1670         region_update_rect(ar);
1671 }
1672
1673 /* externally called for floating regions like menus */
1674 void ED_region_init(ARegion *ar)
1675 {
1676         /* refresh can be called before window opened */
1677         region_subwindow(ar);
1678
1679         region_update_rect(ar);
1680 }
1681
1682 void ED_region_cursor_set(wmWindow *win, ScrArea *sa, ARegion *ar)
1683 {
1684         if (ar && sa && ar->type && ar->type->cursor) {
1685                 ar->type->cursor(win, sa, ar);
1686         }
1687         else {
1688                 if (WM_cursor_set_from_tool(win, sa, ar)) {
1689                         return;
1690                 }
1691                 WM_cursor_set(win, CURSOR_STD);
1692         }
1693 }
1694
1695 /* for use after changing visibility of regions */
1696 void ED_region_visibility_change_update(bContext *C, ARegion *ar)
1697 {
1698         ScrArea *sa = CTX_wm_area(C);
1699
1700         if (ar->flag & RGN_FLAG_HIDDEN)
1701                 WM_event_remove_handlers(C, &ar->handlers);
1702
1703         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa);
1704         ED_area_tag_redraw(sa);
1705 }
1706
1707 /* for quick toggle, can skip fades */
1708 void region_toggle_hidden(bContext *C, ARegion *ar, const bool do_fade)
1709 {
1710         ScrArea *sa = CTX_wm_area(C);
1711
1712         ar->flag ^= RGN_FLAG_HIDDEN;
1713
1714         if (do_fade && ar->overlap) {
1715                 /* starts a timer, and in end calls the stuff below itself (region_sblend_invoke()) */
1716                 region_blend_start(C, sa, ar);
1717         }
1718         else {
1719                 ED_region_visibility_change_update(C, ar);
1720         }
1721 }
1722
1723 /* exported to all editors, uses fading default */
1724 void ED_region_toggle_hidden(bContext *C, ARegion *ar)
1725 {
1726         region_toggle_hidden(C, ar, true);
1727 }
1728
1729 /**
1730  * we swap spaces for fullscreen to keep all allocated data area vertices were set
1731  */
1732 void ED_area_data_copy(ScrArea *sa_dst, ScrArea *sa_src, const bool do_free)
1733 {
1734         SpaceType *st;
1735         ARegion *ar;
1736         const char spacetype = sa_dst->spacetype;
1737         const short flag_copy = HEADER_NO_PULLDOWN;
1738
1739         sa_dst->spacetype = sa_src->spacetype;
1740         sa_dst->type = sa_src->type;
1741
1742         sa_dst->flag = (sa_dst->flag & ~flag_copy) | (sa_src->flag & flag_copy);
1743
1744         /* area */
1745         if (do_free) {
1746                 BKE_spacedata_freelist(&sa_dst->spacedata);
1747         }
1748         BKE_spacedata_copylist(&sa_dst->spacedata, &sa_src->spacedata);
1749
1750         /* Note; SPACE_EMPTY is possible on new screens */
1751
1752         /* regions */
1753         if (do_free) {
1754                 st = BKE_spacetype_from_id(spacetype);
1755                 for (ar = sa_dst->regionbase.first; ar; ar = ar->next)
1756                         BKE_area_region_free(st, ar);
1757                 BLI_freelistN(&sa_dst->regionbase);
1758         }
1759         st = BKE_spacetype_from_id(sa_src->spacetype);
1760         for (ar = sa_src->regionbase.first; ar; ar = ar->next) {
1761                 ARegion *newar = BKE_area_region_copy(st, ar);
1762                 BLI_addtail(&sa_dst->regionbase, newar);
1763         }
1764 }
1765
1766 void ED_area_data_swap(ScrArea *sa_dst, ScrArea *sa_src)
1767 {
1768         SWAP(char, sa_dst->spacetype, sa_src->spacetype);
1769         SWAP(SpaceType *, sa_dst->type, sa_src->type);
1770
1771
1772         SWAP(ListBase, sa_dst->spacedata, sa_src->spacedata);
1773         SWAP(ListBase, sa_dst->regionbase, sa_src->regionbase);
1774 }
1775
1776 /* *********** Space switching code *********** */
1777
1778 void ED_area_swapspace(bContext *C, ScrArea *sa1, ScrArea *sa2)
1779 {
1780         ScrArea *tmp = MEM_callocN(sizeof(ScrArea), "addscrarea");
1781
1782         ED_area_exit(C, sa1);
1783         ED_area_exit(C, sa2);
1784
1785         ED_area_data_copy(tmp, sa1, false);
1786         ED_area_data_copy(sa1, sa2, true);
1787         ED_area_data_copy(sa2, tmp, true);
1788         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa1);
1789         ED_area_initialize(CTX_wm_manager(C), CTX_wm_window(C), sa2);
1790
1791         BKE_screen_area_free(tmp);
1792         MEM_freeN(tmp);
1793
1794         /* tell WM to refresh, cursor types etc */
1795         WM_event_add_mousemove(C);
1796
1797         ED_area_tag_redraw(sa1);
1798         ED_area_tag_refresh(sa1);
1799         ED_area_tag_redraw(sa2);
1800         ED_area_tag_refresh(sa2);
1801 }
1802
1803 /**
1804  * \param skip_ar_exit: Skip calling area exit callback. Set for opening temp spaces.
1805  */
1806 void ED_area_newspace(bContext *C, ScrArea *sa, int type, const bool skip_ar_exit)
1807 {
1808         wmWindow *win = CTX_wm_window(C);
1809
1810         if (sa->spacetype != type) {
1811                 SpaceType *st;
1812                 SpaceLink *slold;
1813                 SpaceLink *sl;
1814                 /* store sa->type->exit callback */
1815                 void *sa_exit = sa->type ? sa->type->exit : NULL;
1816                 int header_alignment = ED_area_header_alignment(sa);
1817
1818                 /* in some cases (opening temp space) we don't want to
1819                  * call area exit callback, so we temporarily unset it */
1820                 if (skip_ar_exit && sa->type) {
1821                         sa->type->exit = NULL;
1822                 }
1823
1824                 ED_area_exit(C, sa);
1825
1826                 /* restore old area exit callback */
1827                 if (skip_ar_exit && sa->type) {
1828                         sa->type->exit = sa_exit;
1829                 }
1830
1831                 st = BKE_spacetype_from_id(type);
1832                 slold = sa->spacedata.first;
1833
1834                 sa->spacetype = type;
1835                 sa->type = st;
1836
1837                 /* If st->new may be called, don't use context until then. The
1838                  * sa->type->context() callback has changed but data may be invalid
1839                  * (e.g. with properties editor) until space-data is properly created */
1840
1841                 /* check previously stored space */
1842                 for (sl = sa->spacedata.first; sl; sl = sl->next)
1843                         if (sl->spacetype == type)
1844                                 break;
1845
1846                 /* old spacedata... happened during work on 2.50, remove */
1847                 if (sl && BLI_listbase_is_empty(&sl->regionbase)) {
1848                         st->free(sl);
1849                         BLI_freelinkN(&sa->spacedata, sl);
1850                         if (slold == sl) {
1851                                 slold = NULL;
1852                         }
1853                         sl = NULL;
1854                 }
1855
1856                 if (sl) {
1857                         /* swap regions */
1858                         slold->regionbase = sa->regionbase;
1859                         sa->regionbase = sl->regionbase;
1860                         BLI_listbase_clear(&sl->regionbase);
1861
1862                         /* put in front of list */
1863                         BLI_remlink(&sa->spacedata, sl);
1864                         BLI_addhead(&sa->spacedata, sl);
1865
1866
1867                         /* Sync header alignment. */
1868                         for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
1869                                 if (ar->regiontype == RGN_TYPE_HEADER) {
1870                                         ar->alignment = header_alignment;
1871                                         break;
1872                                 }
1873                         }
1874                 }
1875                 else {
1876                         /* new space */
1877                         if (st) {
1878                                 /* Don't get scene from context here which may depend on space-data. */
1879                                 Scene *scene = WM_window_get_active_scene(win);
1880                                 sl = st->new(sa, scene);
1881                                 BLI_addhead(&sa->spacedata, sl);
1882
1883                                 /* swap regions */
1884                                 if (slold)
1885                                         slold->regionbase = sa->regionbase;
1886                                 sa->regionbase = sl->regionbase;
1887                                 BLI_listbase_clear(&sl->regionbase);
1888                         }
1889                 }
1890
1891                 ED_area_initialize(CTX_wm_manager(C), win, sa);
1892
1893                 /* tell WM to refresh, cursor types etc */
1894                 WM_event_add_mousemove(C);
1895
1896                 /* send space change notifier */
1897                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1898
1899                 ED_area_tag_refresh(sa);
1900         }
1901
1902         /* also redraw when re-used */
1903         ED_area_tag_redraw(sa);
1904 }
1905
1906 void ED_area_prevspace(bContext *C, ScrArea *sa)
1907 {
1908         SpaceLink *sl = sa->spacedata.first;
1909
1910         if (sl && sl->next) {
1911                 ED_area_newspace(C, sa, sl->next->spacetype, false);
1912
1913                 /* keep old spacedata but move it to end, so calling
1914                  * ED_area_prevspace once more won't open it again */
1915                 BLI_remlink(&sa->spacedata, sl);
1916                 BLI_addtail(&sa->spacedata, sl);
1917         }
1918         else {
1919                 /* no change */
1920                 return;
1921         }
1922         sa->flag &= ~AREA_FLAG_STACKED_FULLSCREEN;
1923
1924         ED_area_tag_redraw(sa);
1925
1926         /* send space change notifier */
1927         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1928 }
1929
1930 /* returns offset for next button in header */
1931 int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
1932 {
1933         ScrArea *sa = CTX_wm_area(C);
1934         bScreen *scr = CTX_wm_screen(C);
1935         PointerRNA areaptr;
1936         int xco = 0.4 * U.widget_unit;
1937
1938         RNA_pointer_create(&(scr->id), &RNA_Area, sa, &areaptr);
1939
1940         uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.6 * U.widget_unit, U.widget_unit,
1941                   &areaptr, "ui_type", 0, 0.0f, 0.0f, 0.0f, 0.0f, "");
1942
1943         return xco + 1.7 * U.widget_unit;
1944 }
1945
1946 /************************ standard UI regions ************************/
1947
1948 static ThemeColorID region_background_color_id(const bContext *C, const ARegion *region)
1949 {
1950         ScrArea *area = CTX_wm_area(C);
1951
1952         switch (region->regiontype) {
1953                 case RGN_TYPE_HEADER:
1954                         if (ED_screen_area_active(C) || ED_area_is_global(area)) {
1955                                 return TH_HEADER;
1956                         }
1957                         else {
1958                                 return TH_HEADERDESEL;
1959                         }
1960                 case RGN_TYPE_PREVIEW:
1961                         return TH_PREVIEW_BACK;
1962                 default:
1963                         return TH_BACK;
1964         }
1965 }
1966
1967 static void region_clear_color(const bContext *C, const ARegion *ar, ThemeColorID colorid)
1968 {
1969         if (ar->alignment == RGN_ALIGN_FLOAT) {
1970                 /* handle our own drawing. */
1971         }
1972         else if (ar->overlap) {
1973                 /* view should be in pixelspace */
1974                 UI_view2d_view_restore(C);
1975
1976                 float back[4];
1977                 UI_GetThemeColor4fv(colorid, back);
1978                 GPU_clear_color(back[3] * back[0], back[3] * back[1], back[3] * back[2], back[3]);
1979                 GPU_clear(GPU_COLOR_BIT);
1980         }
1981         else {
1982                 UI_ThemeClearColor(colorid);
1983                 GPU_clear(GPU_COLOR_BIT);
1984         }
1985 }
1986
1987 BLI_INLINE bool streq_array_any(const char *s, const char *arr[])
1988 {
1989         for (uint i = 0; arr[i]; i++) {
1990                 if (STREQ(arr[i], s)) {
1991                         return true;
1992                 }
1993         }
1994         return false;
1995 }
1996
1997 static void ed_panel_draw(
1998         const bContext *C,
1999         ScrArea *sa,
2000         ARegion *ar,
2001         ListBase *lb,
2002         PanelType *pt,
2003         Panel *panel,
2004         int w,
2005         int em,
2006         bool vertical)
2007 {
2008         uiStyle *style = UI_style_get_dpi();
2009
2010         /* draw panel */
2011         uiBlock *block = UI_block_begin(C, ar, pt->idname, UI_EMBOSS);
2012
2013         bool open;
2014         panel = UI_panel_begin(sa, ar, lb, block, pt, panel, &open);
2015
2016         /* bad fixed values */
2017         int xco, yco, h = 0;
2018
2019         if (pt->draw_header_preset && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2020                 /* for preset menu */
2021                 panel->layout = UI_block_layout(
2022                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2023                         0, (UI_UNIT_Y * 1.1f) + style->panelspace, UI_UNIT_Y, 1, 0, style);
2024
2025                 pt->draw_header_preset(C, panel);
2026
2027                 int headerend = w - UI_UNIT_X;
2028
2029                 UI_block_layout_resolve(block, &xco, &yco);
2030                 UI_block_translate(block, headerend - xco, 0);
2031                 panel->layout = NULL;
2032         }
2033
2034         if (pt->draw_header && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2035                 int labelx, labely;
2036                 UI_panel_label_offset(block, &labelx, &labely);
2037
2038                 /* for enabled buttons */
2039                 panel->layout = UI_block_layout(
2040                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2041                         labelx, labely, UI_UNIT_Y, 1, 0, style);
2042
2043                 pt->draw_header(C, panel);
2044
2045                 UI_block_layout_resolve(block, &xco, &yco);
2046                 panel->labelofs = xco - labelx;
2047                 panel->layout = NULL;
2048         }
2049         else {
2050                 panel->labelofs = 0;
2051         }
2052
2053         if (open) {
2054                 short panelContext;
2055
2056                 /* panel context can either be toolbar region or normal panels region */
2057                 if (pt->flag & PNL_LAYOUT_VERT_BAR) {
2058                         panelContext = UI_LAYOUT_VERT_BAR;
2059                 }
2060                 else if (ar->regiontype == RGN_TYPE_TOOLS) {
2061                         panelContext = UI_LAYOUT_TOOLBAR;
2062                 }
2063                 else {
2064                         panelContext = UI_LAYOUT_PANEL;
2065                 }
2066
2067                 panel->layout = UI_block_layout(
2068                         block, UI_LAYOUT_VERTICAL, panelContext,
2069                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : style->panelspace, 0,
2070                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : w - 2 * style->panelspace,
2071                         em, 0, style);
2072
2073                 pt->draw(C, panel);
2074
2075                 UI_block_layout_resolve(block, &xco, &yco);
2076                 panel->layout = NULL;
2077
2078                 if (yco != 0) {
2079                         h = -yco + 2 * style->panelspace;
2080                 }
2081         }
2082
2083         UI_block_end(C, block);
2084
2085         /* Draw child panels. */
2086         if (open) {
2087                 for (LinkData *link = pt->children.first; link; link = link->next) {
2088                         PanelType *child_pt = link->data;
2089                         Panel *child_panel = UI_panel_find_by_type(&panel->children, child_pt);
2090
2091                         if (child_pt->draw && (!child_pt->poll || child_pt->poll(C, child_pt))) {
2092                                 ed_panel_draw(C, sa, ar, &panel->children, child_pt, child_panel, w, em, vertical);
2093                         }
2094                 }
2095         }
2096
2097         UI_panel_end(block, w, h);
2098 }
2099
2100 /**
2101  * \param contexts: A NULL terminated array of context strings to match against.
2102  * Matching against any of these strings will draw the panel.
2103  * Can be NULL to skip context checks.
2104  */
2105 void ED_region_panels_layout_ex(
2106         const bContext *C, ARegion *ar,
2107         const char *contexts[], int contextnr, const bool vertical)
2108 {
2109         ar->runtime.category = NULL;
2110
2111         const WorkSpace *workspace = CTX_wm_workspace(C);
2112         ScrArea *sa = CTX_wm_area(C);
2113         PanelType *pt;
2114         View2D *v2d = &ar->v2d;
2115         int x, y, w, em;
2116         bool is_context_new = 0;
2117         int scroll;
2118
2119         /* XXX, should use some better check? */
2120         /* For now also has hardcoded check for clip editor until it supports actual toolbar. */
2121         bool use_category_tabs = ((1 << ar->regiontype) & RGN_TYPE_HAS_CATEGORY_MASK) ||
2122                                  (ar->regiontype == RGN_TYPE_TOOLS && sa->spacetype == SPACE_CLIP);
2123         /* offset panels for small vertical tab area */
2124         const char *category = NULL;
2125         const int category_tabs_width = UI_PANEL_CATEGORY_MARGIN_WIDTH;
2126         int margin_x = 0;
2127         const bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2128
2129         BLI_SMALLSTACK_DECLARE(pt_stack, PanelType *);
2130
2131         if (contextnr != -1)
2132                 is_context_new = UI_view2d_tab_set(v2d, contextnr);
2133
2134         /* before setting the view */
2135         if (vertical) {
2136                 /* only allow scrolling in vertical direction */
2137                 v2d->keepofs |= V2D_LOCKOFS_X | V2D_KEEPOFS_Y;
2138                 v2d->keepofs &= ~(V2D_LOCKOFS_Y | V2D_KEEPOFS_X);
2139                 v2d->scroll &= ~(V2D_SCROLL_BOTTOM);
2140                 v2d->scroll |= (V2D_SCROLL_RIGHT);
2141         }
2142         else {
2143                 /* for now, allow scrolling in both directions (since layouts are optimized for vertical,
2144                  * they often don't fit in horizontal layout)
2145                  */
2146                 v2d->keepofs &= ~(V2D_LOCKOFS_X | V2D_LOCKOFS_Y | V2D_KEEPOFS_X | V2D_KEEPOFS_Y);
2147                 v2d->scroll |= (V2D_SCROLL_BOTTOM);
2148                 v2d->scroll &= ~(V2D_SCROLL_RIGHT);
2149         }
2150
2151         scroll = v2d->scroll;
2152
2153
2154         /* collect panels to draw */
2155         for (pt = ar->type->paneltypes.last; pt; pt = pt->prev) {
2156                 /* Only draw top level panels. */
2157                 if (pt->parent) {
2158                         continue;
2159                 }
2160
2161                 /* verify context */
2162                 if (contexts && pt->context[0] && !streq_array_any(pt->context, contexts)) {
2163                         continue;
2164                 }
2165
2166                 /* If we're tagged, only use compatible. */
2167                 if (pt->owner_id[0] && BKE_workspace_owner_id_check(workspace, pt->owner_id) == false) {
2168                         continue;
2169                 }
2170
2171                 /* draw panel */
2172                 if (pt->draw && (!pt->poll || pt->poll(C, pt))) {
2173                         BLI_SMALLSTACK_PUSH(pt_stack, pt);
2174                 }
2175         }
2176
2177
2178         /* collect categories */
2179         if (use_category_tabs) {
2180                 UI_panel_category_clear_all(ar);
2181
2182                 /* gather unique categories */
2183                 BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2184                 {
2185                         if (pt->category[0]) {
2186                                 if (!UI_panel_category_find(ar, pt->category)) {
2187                                         UI_panel_category_add(ar, pt->category);
2188                                 }
2189                         }
2190                 }
2191                 BLI_SMALLSTACK_ITER_END;
2192
2193                 if (!UI_panel_category_is_visible(ar)) {
2194                         use_category_tabs = false;
2195                 }
2196                 else {
2197                         category = UI_panel_category_active_get(ar, true);
2198                         margin_x = category_tabs_width;
2199                 }
2200         }
2201
2202
2203         if (vertical) {
2204                 w = BLI_rctf_size_x(&v2d->cur);
2205                 em = (ar->type->prefsizex) ? 10 : 20; /* works out to 10*UI_UNIT_X or 20*UI_UNIT_X */
2206         }
2207         else {
2208                 w = UI_PANEL_WIDTH;
2209                 em = (ar->type->prefsizex) ? 10 : 20;
2210         }
2211
2212         w -= margin_x;
2213
2214         /* create panels */
2215         UI_panels_begin(C, ar);
2216
2217         /* set view2d view matrix  - UI_block_begin() stores it */
2218         UI_view2d_view_ortho(v2d);
2219
2220         BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2221         {
2222                 Panel *panel = UI_panel_find_by_type(&ar->panels, pt);
2223
2224                 if (use_category_tabs && pt->category[0] && !STREQ(category, pt->category)) {
2225                         if ((panel == NULL) || ((panel->flag & PNL_PIN) == 0)) {
2226                                 continue;
2227                         }
2228                 }
2229
2230                 ed_panel_draw(C, sa, ar, &ar->panels, pt, panel, w, em, vertical);
2231         }
2232         BLI_SMALLSTACK_ITER_END;
2233
2234         /* align panels and return size */
2235         UI_panels_end(C, ar, &x, &y);
2236
2237         /* before setting the view */
2238         if (region_layout_based) {
2239                 /* XXX, only single panel support atm.
2240                  * Can't use x/y values calculated above because they're not using the real height of panels,
2241                  * instead they calculate offsets for the next panel to start drawing. */
2242                 Panel *panel = ar->panels.last;
2243                 if (panel != NULL) {
2244                         int size_dyn[2] = {
2245                                 UI_UNIT_X * ((panel->flag & PNL_CLOSED) ? 8 : 14),
2246                                 UI_panel_size_y(panel),
2247                         };
2248                         /* region size is layout based and needs to be updated */
2249                         if ((ar->sizex != size_dyn[0]) ||
2250                             (ar->sizey != size_dyn[1]))
2251                         {
2252                                 ar->sizex = size_dyn[0];
2253                                 ar->sizey = size_dyn[1];
2254                                 sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2255                         }
2256                         y = ABS(ar->sizey - 1);
2257                 }
2258         }
2259         else if (vertical) {
2260                 /* we always keep the scroll offset - so the total view gets increased with the scrolled away part */
2261                 if (v2d->cur.ymax < -FLT_EPSILON) {
2262                         /* Clamp to lower view boundary */
2263                         if (v2d->tot.ymin < -v2d->winy) {
2264                                 y = min_ii(y, 0);
2265                         }
2266                         else {
2267                                 y = min_ii(y, v2d->cur.ymin);
2268                         }
2269                 }
2270
2271                 y = -y;
2272         }
2273         else {
2274                 /* don't jump back when panels close or hide */
2275                 if (!is_context_new) {
2276                         if (v2d->tot.xmax > v2d->winx) {
2277                                 x = max_ii(x, 0);
2278                         }
2279                         else {
2280                                 x = max_ii(x, v2d->cur.xmax);
2281                         }
2282                 }
2283
2284                 y = -y;
2285         }
2286
2287         /* this also changes the 'cur' */
2288         UI_view2d_totRect_set(v2d, x, y);
2289
2290         if (scroll != v2d->scroll) {
2291                 /* Note: this code scales fine, but because of rounding differences, positions of elements
2292                  * flip +1 or -1 pixel compared to redoing the entire layout again.
2293                  * Leaving in commented code for future tests */
2294 #if 0
2295                 UI_panels_scale(ar, BLI_rctf_size_x(&v2d->cur));
2296                 break;
2297 #endif
2298         }
2299
2300         if (use_category_tabs) {
2301                 ar->runtime.category = category;
2302         }
2303 }
2304 void ED_region_panels_layout(const bContext *C, ARegion *ar)
2305 {
2306         ED_region_panels_layout_ex(C, ar, NULL, -1, true);
2307 }
2308
2309 void ED_region_panels_draw(const bContext *C, ARegion *ar)
2310 {
2311         View2D *v2d = &ar->v2d;
2312
2313         if (ar->alignment != RGN_ALIGN_FLOAT) {
2314                 region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK);
2315         }
2316
2317         /* reset line width for drawing tabs */
2318         GPU_line_width(1.0f);
2319
2320         /* set the view */
2321         UI_view2d_view_ortho(v2d);
2322
2323         /* draw panels */
2324         UI_panels_draw(C, ar);
2325
2326         /* restore view matrix */
2327         UI_view2d_view_restore(C);
2328
2329         /* Set in layout. */
2330         if (ar->runtime.category) {
2331                 UI_panel_category_draw_all(ar, ar->runtime.category);
2332         }
2333
2334         /* scrollers */
2335         const rcti *mask = NULL;
2336         rcti        mask_buf;
2337         if (ar->runtime.category && (ar->alignment == RGN_ALIGN_RIGHT)) {
2338                 UI_view2d_mask_from_win(v2d, &mask_buf);
2339                 mask_buf.xmax -= UI_PANEL_CATEGORY_MARGIN_WIDTH;
2340                 mask = &mask_buf;
2341         }
2342         View2DScrollers *scrollers = UI_view2d_scrollers_calc(
2343                 C, v2d, mask, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
2344         UI_view2d_scrollers_draw(C, v2d, scrollers);
2345         UI_view2d_scrollers_free(scrollers);
2346 }
2347
2348 void ED_region_panels_ex(
2349         const bContext *C, ARegion *ar,
2350         const char *contexts[], int contextnr, const bool vertical)
2351 {
2352         /* TODO: remove? */
2353         ED_region_panels_layout_ex(C, ar, contexts, contextnr, vertical);
2354         ED_region_panels_draw(C, ar);
2355 }
2356
2357 void ED_region_panels(const bContext *C, ARegion *ar)
2358 {
2359         /* TODO: remove? */
2360         ED_region_panels_layout(C, ar);
2361         ED_region_panels_draw(C, ar);
2362 }
2363
2364 void ED_region_panels_init(wmWindowManager *wm, ARegion *ar)
2365 {
2366         wmKeyMap *keymap;
2367
2368         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy);
2369
2370         keymap = WM_keymap_ensure(wm->defaultconf, "View2D Buttons List", 0, 0);
2371         WM_event_add_keymap_handler(&ar->handlers, keymap);
2372 }
2373
2374 void ED_region_header_layout(const bContext *C, ARegion *ar)
2375 {
2376         uiStyle *style = UI_style_get_dpi();
2377         uiBlock *block;
2378         uiLayout *layout;
2379         HeaderType *ht;
2380         Header header = {NULL};
2381         bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2382
2383         /* Height of buttons and scaling needed to achieve it. */
2384         const int buttony = min_ii(UI_UNIT_Y, ar->winy - 2 * UI_DPI_FAC);
2385         const float buttony_scale = buttony / (float)UI_UNIT_Y;
2386
2387         /* Vertically center buttons. */
2388         int xco = UI_HEADER_OFFSET;
2389         int yco = buttony + (ar->winy - buttony) / 2;
2390         int maxco = xco;
2391
2392         /* XXX workaround for 1 px alignment issue. Not sure what causes it... Would prefer a proper fix - Julian */
2393         if (!ELEM(CTX_wm_area(C)->spacetype, SPACE_TOPBAR, SPACE_STATUSBAR)) {
2394                 yco -= 1;
2395         }
2396
2397         /* set view2d view matrix for scrolling (without scrollers) */
2398         UI_view2d_view_ortho(&ar->v2d);
2399
2400         /* draw all headers types */
2401         for (ht = ar->type->headertypes.first; ht; ht = ht->next) {
2402                 if (ht->poll && !ht->poll(C, ht)) {
2403                         continue;
2404                 }
2405
2406                 block = UI_block_begin(C, ar, ht->idname, UI_EMBOSS);
2407                 layout = UI_block_layout(block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER, xco, yco, buttony, 1, 0, style);
2408
2409                 if (buttony_scale != 1.0f) {
2410                         uiLayoutSetScaleY(layout, buttony_scale);
2411                 }
2412
2413                 if (ht->draw) {
2414                         header.type = ht;
2415                         header.layout = layout;
2416                         ht->draw(C, &header);
2417                         if (ht->next) {
2418                                 uiItemS(layout);
2419                         }
2420
2421                         /* for view2d */
2422                         xco = uiLayoutGetWidth(layout);
2423                         if (xco > maxco)
2424                                 maxco = xco;
2425                 }
2426
2427                 UI_block_layout_resolve(block, &xco, &yco);
2428
2429                 /* for view2d */
2430                 if (xco > maxco)
2431                         maxco = xco;
2432
2433                 int new_sizex = (maxco + UI_HEADER_OFFSET) / UI_DPI_FAC;
2434
2435                 if (region_layout_based && (ar->sizex != new_sizex)) {
2436                         /* region size is layout based and needs to be updated */
2437                         ScrArea *sa = CTX_wm_area(C);
2438
2439                         ar->sizex = new_sizex;
2440                         sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2441                 }
2442
2443                 UI_block_end(C, block);
2444         }
2445
2446         if (!region_layout_based) {
2447                 maxco += UI_HEADER_OFFSET;
2448         }
2449
2450         /* always as last  */
2451         UI_view2d_totRect_set(&ar->v2d, maxco, ar->winy);
2452
2453         /* restore view matrix */
2454         UI_view2d_view_restore(C);
2455 }
2456
2457 void ED_region_header_draw(const bContext *C, ARegion *ar)
2458 {
2459         /* clear */
2460         region_clear_color(C, ar, region_background_color_id(C, ar));
2461
2462         UI_view2d_view_ortho(&ar->v2d);
2463
2464         /* View2D matrix might have changed due to dynamic sized regions. */
2465         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2466
2467         /* draw blocks */
2468         UI_blocklist_draw(C, &ar->uiblocks);
2469
2470         /* restore view matrix */
2471         UI_view2d_view_restore(C);
2472 }
2473
2474 void ED_region_header(const bContext *C, ARegion *ar)
2475 {
2476         /* TODO: remove? */
2477         ED_region_header_layout(C, ar);
2478         ED_region_header_draw(C, ar);
2479 }
2480
2481 void ED_region_header_init(ARegion *ar)
2482 {
2483         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_HEADER, ar->winx, ar->winy);
2484 }
2485
2486 /* UI_UNIT_Y is defined as U variable now, depending dpi */
2487 int ED_area_headersize(void)
2488 {
2489         return (int)(HEADERY * UI_DPI_FAC);
2490 }
2491
2492
2493 int ED_area_header_alignment(const ScrArea *area)
2494 {
2495         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
2496                 if (ar->regiontype == RGN_TYPE_HEADER) {
2497                         return ar->alignment;
2498                 }
2499         }
2500
2501         return RGN_ALIGN_TOP;
2502 }
2503
2504 /**
2505  * \return the final height of a global \a area, accounting for DPI.
2506  */
2507 int ED_area_global_size_y(const ScrArea *area)
2508 {
2509         BLI_assert(ED_area_is_global(area));
2510         return round_fl_to_int(area->global->cur_fixed_height * UI_DPI_FAC);
2511 }
2512 int ED_area_global_min_size_y(const ScrArea *area)
2513 {
2514         BLI_assert(ED_area_is_global(area));
2515         return round_fl_to_int(area->global->size_min * UI_DPI_FAC);
2516 }
2517 int ED_area_global_max_size_y(const ScrArea *area)
2518 {
2519         BLI_assert(ED_area_is_global(area));
2520         return round_fl_to_int(area->global->size_max * UI_DPI_FAC);
2521 }
2522
2523 bool ED_area_is_global(const ScrArea *area)
2524 {
2525         return area->global != NULL;
2526 }
2527
2528 ScrArea *ED_screen_areas_iter_first(const wmWindow *win, const bScreen *screen)
2529 {
2530         ScrArea *global_area = win->global_areas.areabase.first;
2531
2532         if (!global_area) {
2533                 return screen->areabase.first;
2534         }
2535         else if ((global_area->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2536                 return global_area;
2537         }
2538         /* Find next visible area. */
2539         return ED_screen_areas_iter_next(screen, global_area);
2540 }
2541 ScrArea *ED_screen_areas_iter_next(const bScreen *screen, const ScrArea *area)
2542 {
2543         if (area->global) {
2544                 for (ScrArea *area_iter = area->next; area_iter; area_iter = area_iter->next) {
2545                         if ((area_iter->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2546                                 return area_iter;
2547                         }
2548                 }
2549                 /* No visible next global area found, start iterating over layout areas. */
2550                 return screen->areabase.first;
2551         }
2552
2553         return area->next;
2554 }
2555
2556 /**
2557  * For now we just assume all global areas are made up out of horizontal bars
2558  * with the same size. A fixed size could be stored in ARegion instead if needed.
2559  *
2560  * \return the DPI aware height of a single bar/region in global areas.
2561  */
2562 int ED_region_global_size_y(void)
2563 {
2564         return ED_area_headersize(); /* same size as header */
2565 }
2566
2567 void ED_region_info_draw_multiline(ARegion *ar, const char *text_array[], float fill_color[4], const bool full_redraw)
2568 {
2569         const int header_height = UI_UNIT_Y;
2570         uiStyle *style = UI_style_get_dpi();
2571         int fontid = style->widget.uifont_id;
2572         int scissor[4];
2573         rcti rect;
2574         int num_lines = 0;
2575
2576         /* background box */
2577         ED_region_visible_rect(ar, &rect);
2578
2579         /* Box fill entire width or just around text. */
2580         if (!full_redraw) {
2581                 const char **text = &text_array[0];
2582                 while (*text) {
2583                         rect.xmax = min_ii(rect.xmax, rect.xmin + BLF_width(fontid, *text, BLF_DRAW_STR_DUMMY_MAX) + 1.2f * U.widget_unit);
2584                         text++;
2585                         num_lines++;
2586                 }
2587         }
2588         /* Just count the line number. */
2589         else {
2590                 const char **text = &text_array[0];
2591                 while (*text) {
2592                         text++;
2593                         num_lines++;
2594                 }
2595         }
2596
2597         rect.ymin = rect.ymax - header_height * num_lines;
2598
2599         /* setup scissor */
2600         GPU_scissor_get_i(scissor);
2601         GPU_scissor(rect.xmin, rect.ymin,
2602                   BLI_rcti_size_x(&rect) + 1, BLI_rcti_size_y(&rect) + 1);
2603
2604         GPU_blend(true);
2605         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2606         GPUVertFormat *format = immVertexFormat();
2607         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
2608         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2609         immUniformColor4fv(fill_color);
2610         immRecti(pos, rect.xmin, rect.ymin, rect.xmax + 1, rect.ymax + 1);
2611         immUnbindProgram();
2612         GPU_blend(false);
2613
2614         /* text */
2615         UI_FontThemeColor(fontid, TH_TEXT_HI);
2616         BLF_clipping(fontid, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2617         BLF_enable(fontid, BLF_CLIPPING);
2618         int offset = num_lines - 1;
2619         {
2620                 const char **text = &text_array[0];
2621                 while (*text) {
2622                         BLF_position(fontid, rect.xmin + 0.6f * U.widget_unit, rect.ymin + 0.3f * U.widget_unit + offset * header_height, 0.0f);
2623                         BLF_draw(fontid, *text, BLF_DRAW_STR_DUMMY_MAX);
2624                         text++;
2625                         offset--;
2626                 }
2627         }
2628
2629         BLF_disable(fontid, BLF_CLIPPING);
2630
2631         /* restore scissor as it was before */
2632         GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2633 }
2634
2635 void ED_region_info_draw(ARegion *ar, const char *text, float fill_color[4], const bool full_redraw)
2636 {
2637         ED_region_info_draw_multiline(ar, (const char *[2]){text, NULL}, fill_color, full_redraw);
2638 }
2639
2640 #define MAX_METADATA_STR    1024
2641
2642 static const char *meta_data_list[] =
2643 {
2644         "File",
2645         "Strip",
2646         "Date",
2647         "RenderTime",
2648         "Note",
2649         "Marker",
2650         "Time",
2651         "Frame",
2652         "Camera",
2653         "Scene"
2654 };
2655
2656 BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset)
2657 {
2658         return (IMB_metadata_get_field(ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
2659 }
2660
2661 static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top)
2662 {
2663         char temp_str[MAX_METADATA_STR];
2664         int line_width;
2665         int ofs_y = 0;
2666         short i;
2667         int len;
2668         const float height = BLF_height_max(fontid);
2669         const float margin = height / 8;
2670         const float vertical_offset = (height + margin);
2671
2672         /* values taking margins into account */
2673         const float descender = BLF_descender(fontid);
2674         const float xmin = (rect->xmin + margin);
2675         const float xmax = (rect->xmax - margin);
2676         const float ymin = (rect->ymin + margin) - descender;
2677         const float ymax = (rect->ymax - margin) - descender;
2678
2679         if (is_top) {
2680                 for (i = 0; i < 4; i++) {
2681                         /* first line */
2682                         if (i == 0) {
2683                                 bool do_newline = false;
2684                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]);
2685                                 if (metadata_is_valid(ibuf, temp_str, 0, len)) {
2686                                         BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f);
2687                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2688                                         do_newline = true;
2689                                 }
2690
2691                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]);
2692                                 if (metadata_is_valid(ibuf, temp_str, 1, len)) {
2693                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2694                                         BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f);
2695                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2696                                         do_newline = true;
2697                                 }
2698
2699                                 if (do_newline)
2700                                         ofs_y += vertical_offset;
2701                         } /* Strip */
2702                         else if (i == 1 || i == 2) {
2703                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2704                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2705                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2706                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2707                                         ofs_y += vertical_offset;
2708                                 }
2709                         } /* Note (wrapped) */
2710                         else if (i == 3) {
2711                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2712                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2713                                         struct ResultBLF info;
2714                                         BLF_enable(fontid, BLF_WORD_WRAP);
2715                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2716                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2717                                         BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info);
2718                                         BLF_wordwrap(fontid, 0);
2719                                         BLF_disable(fontid, BLF_WORD_WRAP);
2720                                         ofs_y += vertical_offset * info.lines;
2721                                 }
2722                         }
2723                         else {
2724                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2725                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2726                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2727                                         BLF_position(fontid, xmax  - line_width, ymax - vertical_offset - ofs_y, 0.0f);
2728                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2729                                         ofs_y += vertical_offset;
2730                                 }
2731                         }
2732                 }
2733         }
2734         else {
2735                 int ofs_x = 0;
2736                 for (i = 5; i < 10; i++) {
2737                         len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]);
2738                         if (metadata_is_valid(ibuf, temp_str, i, len)) {
2739                                 BLF_position(fontid, xmin + ofs_x, ymin, 0.0f);
2740                                 BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2741
2742                                 ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X;
2743                         }
2744                 }
2745         }
2746 }
2747
2748 static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top)
2749 {
2750         const float height = BLF_height_max(fontid);
2751         const float margin = (height / 8);
2752         char str[MAX_METADATA_STR] = "";
2753         short i, count = 0;
2754
2755         if (is_top) {
2756                 if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) {
2757                         count++;
2758                 }
2759                 for (i = 2; i < 5; i++) {
2760                         if (metadata_is_valid(ibuf, str, i, 0)) {
2761                                 if (i == 4) {
2762                                         struct {
2763                                                 struct ResultBLF info;
2764                                                 rctf rect;
2765                                         } wrap;
2766
2767                                         BLF_enable(fontid, BLF_WORD_WRAP);
2768                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2769                                         BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info);
2770                                         BLF_wordwrap(fontid, 0);
2771                                         BLF_disable(fontid, BLF_WORD_WRAP);
2772
2773                                         count += wrap.info.lines;
2774                                 }
2775                                 else {
2776                                         count++;
2777                                 }
2778                         }
2779                 }
2780         }
2781         else {
2782                 for (i = 5; i < 10; i++) {
2783                         if (metadata_is_valid(ibuf, str, i, 0)) {
2784                                 count = 1;
2785                         }
2786                 }
2787         }
2788
2789         if (count) {
2790                 return (height + margin) * count;
2791         }
2792
2793         return 0;
2794 }
2795
2796 #undef MAX_METADATA_STR
2797
2798 void ED_region_image_metadata_draw(int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy)
2799 {
2800         float box_y;
2801         rctf rect;
2802         uiStyle *style = UI_style_get_dpi();
2803
2804         if (!ibuf->metadata)
2805                 return;
2806
2807         /* find window pixel coordinates of origin */
2808         GPU_matrix_push();
2809
2810         /* offset and zoom using ogl */
2811         GPU_matrix_translate_2f(x, y);
2812         GPU_matrix_scale_2f(zoomx, zoomy);
2813
2814         BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi);
2815
2816         /* *** upper box*** */
2817
2818         /* get needed box height */
2819         box_y = metadata_box_height_get(ibuf, blf_mono_font, true);
2820
2821         if (box_y) {
2822                 /* set up rect */
2823                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y);
2824                 /* draw top box */
2825                 GPUVertFormat *format = immVertexFormat();
2826                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2827                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2828                 immUniformThemeColor(TH_METADATA_BG);
2829                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2830                 immUnbindProgram();
2831
2832                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2833                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2834
2835                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2836                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true);
2837
2838                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2839         }
2840
2841
2842         /* *** lower box*** */
2843
2844         box_y = metadata_box_height_get(ibuf, blf_mono_font, false);
2845
2846         if (box_y) {
2847                 /* set up box rect */
2848                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin);
2849                 /* draw top box */
2850                 GPUVertFormat *format = immVertexFormat();
2851                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2852                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2853                 immUniformThemeColor(TH_METADATA_BG);
2854                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2855                 immUnbindProgram();
2856
2857                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2858                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2859
2860                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2861                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false);
2862
2863                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2864         }
2865
2866         GPU_matrix_pop();
2867 }
2868
2869 void ED_region_grid_draw(ARegion *ar, float zoomx, float zoomy)
2870 {
2871         float gridsize, gridstep = 1.0f / 32.0f;
2872         float fac, blendfac;
2873         int x1, y1, x2, y2;
2874
2875         /* the image is located inside (0, 0), (1, 1) as set by view2d */
2876         UI_view2d_view_to_region(&ar->v2d, 0.0f, 0.0f, &x1, &y1);
2877         UI_view2d_view_to_region(&ar->v2d, 1.0f, 1.0f, &x2, &y2);
2878
2879         GPUVertFormat *format = immVertexFormat();
2880         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2881
2882         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2883         immUniformThemeColorShade(TH_BACK, 20);
2884         immRectf(pos, x1, y1, x2, y2);
2885         immUnbindProgram();
2886
2887         /* gridsize adapted to zoom level */
2888         gridsize = 0.5f * (zoomx + zoomy);
2889         if (gridsize <= 0.0f)
2890                 return;
2891
2892         if (gridsize < 1.0f) {
2893                 while (gridsize < 1.0f) {
2894                         gridsize *= 4.0f;
2895                         gridstep *= 4.0f;
2896                 }
2897         }
2898         else {
2899                 while (gridsize >= 4.0f) {
2900                         gridsize /= 4.0f;
2901                         gridstep /= 4.0f;
2902                 }
2903         }
2904
2905         blendfac = 0.25f * gridsize - floorf(0.25f * gridsize);
2906         CLAMP(blendfac, 0.0f, 1.0f);
2907
2908         int count_fine = 1.0f / gridstep;
2909         int count_large = 1.0f / (4.0f * gridstep);
2910
2911         if (count_fine > 0) {
2912                 GPU_vertformat_clear(format);
2913                 pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2914                 unsigned color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2915
2916                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
2917                 immBegin(GPU_PRIM_LINES, 4 * count_fine + 4 * count_large);
2918
2919                 float theme_color[3];
2920                 UI_GetThemeColorShade3fv(TH_BACK, (int)(20.0f * (1.0f - blendfac)), theme_color);
2921                 fac = 0.0f;
2922
2923                 /* the fine resolution level */
2924                 for (int i = 0; i < count_fine; i++) {
2925                         immAttr3fv(color, theme_color);
2926                         immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
2927                         immAttr3fv(color, theme_color);
2928                         immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
2929                         immAttr3fv(color, theme_color);
2930                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
2931                         immAttr3fv(color, theme_color);
2932                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
2933                         fac += gridstep;
2934                 }
2935
2936                 if (count_large > 0) {
2937                         UI_GetThemeColor3fv(TH_BACK, theme_color);
2938                         fac = 0.0f;
2939
2940                         /* the large resolution level */
2941                         for (int i = 0; i < count_large; i++) {
2942                                 immAttr3fv(color, theme_color);
2943                                 immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
2944                                 immAttr3fv(color, theme_color);
2945                                 immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
2946                                 immAttr3fv(color, theme_color);
2947                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
2948                                 immAttr3fv(color, theme_color);
2949                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
2950                                 fac += 4.0f * gridstep;
2951                         }
2952                 }
2953
2954                 immEnd();
2955                 immUnbindProgram();
2956         }
2957 }
2958
2959 /* If the area has overlapping regions, it returns visible rect for Region *ar */
2960 /* rect gets returned in local region coordinates */
2961 void ED_region_visible_rect(ARegion *ar, rcti *rect)
2962 {
2963         ARegion *arn = ar;
2964
2965         /* allow function to be called without area */
2966         while (arn->prev)
2967                 arn = arn->prev;
2968
2969         *rect = ar->winrct;
2970
2971         /* check if a region overlaps with the current one */
2972         for (; arn; arn = arn->next) {
2973                 if (ar != arn && arn->overlap) {
2974                         if (BLI_rcti_isect(rect, &arn->winrct, NULL)) {
2975                                 if (ELEM(arn->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
2976                                         /* Overlap left, also check 1 pixel offset (2 regions on one side). */
2977                                         if (ABS(rect->xmin - arn->winrct.xmin) < 2) {
2978                                                 rect->xmin = arn->winrct.xmax;
2979                                         }
2980
2981                                         /* Overlap right. */
2982                                         if (ABS(rect->xmax - arn->winrct.xmax) < 2) {
2983                                                 rect->xmax = arn->winrct.xmin;
2984                                         }
2985                                 }
2986                                 else if (ELEM(arn->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
2987                                         /* Same logic as above for vertical regions. */
2988                                         if (ABS(rect->ymin - arn->winrct.ymin) < 2) {
2989                                                 rect->ymin = arn->winrct.ymax;
2990                                         }
2991                                         if (ABS(rect->ymax - arn->winrct.ymax) < 2) {
2992                                                 rect->ymax = arn->winrct.ymin;
2993                                         }
2994                                 }
2995                                 else if (arn->alignment == RGN_ALIGN_FLOAT) {
2996                                         /* Skip floating. */
2997                                 }
2998                                 else {
2999                                         BLI_assert(!"Region overlap with unknown alignment");
3000                                 }
3001                         }
3002                 }
3003         }
3004         BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
3005 }
3006
3007 /* Cache display helpers */
3008
3009 void ED_region_cache_draw_background(const ARegion *ar)
3010 {
3011         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3012         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3013         immUniformColor4ub(128, 128, 255, 64);
3014         immRecti(pos, 0, 0, ar->winx, 8 * UI_DPI_FAC);
3015         immUnbindProgram();
3016 }
3017
3018 void ED_region_cache_draw_curfra_label(const int framenr, const float x, const float y)
3019 {
3020         uiStyle *style = UI_style_get();
3021         int fontid = style->widget.uifont_id;
3022         char numstr[32];
3023         float font_dims[2] = {0.0f, 0.0f};
3024
3025         /* frame number */
3026         BLF_size(fontid, 11.0f * U.pixelsize, U.dpi);
3027         BLI_snprintf(numstr, sizeof(numstr), "%d", framenr);
3028
3029         BLF_width_and_height(fontid, numstr, sizeof(numstr), &font_dims[0], &font_dims[1]);
3030
3031         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3032         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3033         immUniformThemeColor(TH_CFRAME);
3034         immRecti(pos, x, y, x + font_dims[0] + 6.0f, y + font_dims[1] + 4.0f);
3035         immUnbindProgram();
3036
3037         UI_FontThemeColor(fontid, TH_TEXT);
3038         BLF_position(fontid, x + 2.0f, y + 2.0f, 0.0f);
3039         BLF_draw(fontid, numstr, sizeof(numstr));
3040 }
3041
3042 void ED_region_cache_draw_cached_segments(const ARegion *ar, const int num_segments, const int *points, const int sfra, const int efra)
3043 {
3044         if (num_segments) {
3045                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3046                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3047                 immUniformColor4ub(128, 128, 255, 128);
3048
3049                 for (int a = 0; a < num_segments; a++) {
3050                         float x1 = (float)(points[a * 2] - sfra) / (efra - sfra + 1) * ar->winx;
3051                         float x2 = (float)(points[a * 2 + 1] - sfra + 1) / (efra - sfra + 1) * ar->winx;
3052
3053                         immRecti(pos, x1, 0, x2, 8 * UI_DPI_FAC);
3054                         /* TODO(merwin): use primitive restart to draw multiple rects more efficiently */
3055                 }
3056
3057                 immUnbindProgram();
3058         }
3059 }
3060
3061 /**
3062  * Generate subscriptions for this region.
3063  */
3064 void ED_region_message_subscribe(
3065         bContext *C,
3066         struct WorkSpace *workspace, struct Scene *scene,
3067         struct bScreen *screen, struct ScrArea *sa, struct ARegion *ar,
3068         struct wmMsgBus *mbus)
3069 {
3070         if (ar->gizmo_map != NULL) {
3071                 WM_gizmomap_message_subscribe(C, ar->gizmo_map, ar, mbus);
3072         }
3073
3074         if (!BLI_listbase_is_empty(&ar->uiblocks)) {
3075                 UI_region_message_subscribe(ar, mbus);
3076         }
3077
3078         if (ar->type->message_subscribe != NULL) {
3079                 ar->type->message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
3080         }
3081 }
3082
3083 int ED_region_snap_size_test(const ARegion *ar)
3084 {
3085         /* Use a larger value because toggling scrollbars can jump in size. */
3086         const int snap_match_threshold = 16;
3087         if (ar->type->snap_size != NULL) {
3088                 return ((((ar->sizex - ar->type->snap_size(ar, ar->sizex, 0)) <= snap_match_threshold) << 0) |
3089                         (((ar->sizey - ar->type->snap_size(ar, ar->sizey, 1)) <= snap_match_threshold) << 1));
3090         }
3091         return 0;
3092 }
3093
3094 bool ED_region_snap_size_apply(ARegion *ar, int snap_flag)
3095 {
3096         bool changed = false;
3097         if (ar->type->snap_size != NULL) {
3098                 if (snap_flag & (1 << 0)) {
3099                         short snap_size = ar->type->snap_size(ar, ar->sizex, 0);
3100                         if (snap_size != ar->sizex) {
3101                                 ar->sizex = snap_size;
3102                                 changed = true;
3103                         }
3104                 }
3105                 if (snap_flag & (1 << 1)) {
3106                         short snap_size = ar->type->snap_size(ar, ar->sizey, 1);
3107                         if (snap_size != ar->sizey) {
3108                                 ar->sizey = snap_size;
3109                                 changed = true;
3110                         }
3111                 }
3112         }
3113         return changed;
3114 }