Fix T57724: Opening file browser flips user-prefs header
[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                 /* When the user switches between space-types from the type-selector,
1817                  * changing the header-type is jarring (especially when using Ctrl-MouseWheel).
1818                  *
1819                  * However, add-on install for example -forces the header to the top which shouldn't
1820                  * be applied back to the previous space type when closing - see: T57724
1821                  */
1822                 const bool sync_header_alignment = (sa->flag & AREA_FLAG_TEMP_TYPE) == 0;
1823                 int header_alignment = ED_area_header_alignment(sa);
1824
1825                 /* in some cases (opening temp space) we don't want to
1826                  * call area exit callback, so we temporarily unset it */
1827                 if (skip_ar_exit && sa->type) {
1828                         sa->type->exit = NULL;
1829                 }
1830
1831                 ED_area_exit(C, sa);
1832
1833                 /* restore old area exit callback */
1834                 if (skip_ar_exit && sa->type) {
1835                         sa->type->exit = sa_exit;
1836                 }
1837
1838                 st = BKE_spacetype_from_id(type);
1839                 slold = sa->spacedata.first;
1840
1841                 sa->spacetype = type;
1842                 sa->type = st;
1843
1844                 /* If st->new may be called, don't use context until then. The
1845                  * sa->type->context() callback has changed but data may be invalid
1846                  * (e.g. with properties editor) until space-data is properly created */
1847
1848                 /* check previously stored space */
1849                 for (sl = sa->spacedata.first; sl; sl = sl->next)
1850                         if (sl->spacetype == type)
1851                                 break;
1852
1853                 /* old spacedata... happened during work on 2.50, remove */
1854                 if (sl && BLI_listbase_is_empty(&sl->regionbase)) {
1855                         st->free(sl);
1856                         BLI_freelinkN(&sa->spacedata, sl);
1857                         if (slold == sl) {
1858                                 slold = NULL;
1859                         }
1860                         sl = NULL;
1861                 }
1862
1863                 if (sl) {
1864                         /* swap regions */
1865                         slold->regionbase = sa->regionbase;
1866                         sa->regionbase = sl->regionbase;
1867                         BLI_listbase_clear(&sl->regionbase);
1868
1869                         /* put in front of list */
1870                         BLI_remlink(&sa->spacedata, sl);
1871                         BLI_addhead(&sa->spacedata, sl);
1872
1873
1874                         /* Sync header alignment. */
1875                         if (sync_header_alignment) {
1876                                 for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) {
1877                                         if (ar->regiontype == RGN_TYPE_HEADER) {
1878                                                 ar->alignment = header_alignment;
1879                                                 break;
1880                                         }
1881                                 }
1882                         }
1883                 }
1884                 else {
1885                         /* new space */
1886                         if (st) {
1887                                 /* Don't get scene from context here which may depend on space-data. */
1888                                 Scene *scene = WM_window_get_active_scene(win);
1889                                 sl = st->new(sa, scene);
1890                                 BLI_addhead(&sa->spacedata, sl);
1891
1892                                 /* swap regions */
1893                                 if (slold)
1894                                         slold->regionbase = sa->regionbase;
1895                                 sa->regionbase = sl->regionbase;
1896                                 BLI_listbase_clear(&sl->regionbase);
1897                         }
1898                 }
1899
1900                 ED_area_initialize(CTX_wm_manager(C), win, sa);
1901
1902                 /* tell WM to refresh, cursor types etc */
1903                 WM_event_add_mousemove(C);
1904
1905                 /* send space change notifier */
1906                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1907
1908                 ED_area_tag_refresh(sa);
1909         }
1910
1911         /* also redraw when re-used */
1912         ED_area_tag_redraw(sa);
1913 }
1914
1915 void ED_area_prevspace(bContext *C, ScrArea *sa)
1916 {
1917         SpaceLink *sl = sa->spacedata.first;
1918
1919         if (sl && sl->next) {
1920                 ED_area_newspace(C, sa, sl->next->spacetype, false);
1921
1922                 /* keep old spacedata but move it to end, so calling
1923                  * ED_area_prevspace once more won't open it again */
1924                 BLI_remlink(&sa->spacedata, sl);
1925                 BLI_addtail(&sa->spacedata, sl);
1926         }
1927         else {
1928                 /* no change */
1929                 return;
1930         }
1931         sa->flag &= ~AREA_FLAG_STACKED_FULLSCREEN;
1932
1933         ED_area_tag_redraw(sa);
1934
1935         /* send space change notifier */
1936         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_CHANGED, sa);
1937 }
1938
1939 /* returns offset for next button in header */
1940 int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
1941 {
1942         ScrArea *sa = CTX_wm_area(C);
1943         bScreen *scr = CTX_wm_screen(C);
1944         PointerRNA areaptr;
1945         int xco = 0.4 * U.widget_unit;
1946
1947         RNA_pointer_create(&(scr->id), &RNA_Area, sa, &areaptr);
1948
1949         uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.6 * U.widget_unit, U.widget_unit,
1950                   &areaptr, "ui_type", 0, 0.0f, 0.0f, 0.0f, 0.0f, "");
1951
1952         return xco + 1.7 * U.widget_unit;
1953 }
1954
1955 /************************ standard UI regions ************************/
1956
1957 static ThemeColorID region_background_color_id(const bContext *C, const ARegion *region)
1958 {
1959         ScrArea *area = CTX_wm_area(C);
1960
1961         switch (region->regiontype) {
1962                 case RGN_TYPE_HEADER:
1963                         if (ED_screen_area_active(C) || ED_area_is_global(area)) {
1964                                 return TH_HEADER;
1965                         }
1966                         else {
1967                                 return TH_HEADERDESEL;
1968                         }
1969                 case RGN_TYPE_PREVIEW:
1970                         return TH_PREVIEW_BACK;
1971                 default:
1972                         return TH_BACK;
1973         }
1974 }
1975
1976 static void region_clear_color(const bContext *C, const ARegion *ar, ThemeColorID colorid)
1977 {
1978         if (ar->alignment == RGN_ALIGN_FLOAT) {
1979                 /* handle our own drawing. */
1980         }
1981         else if (ar->overlap) {
1982                 /* view should be in pixelspace */
1983                 UI_view2d_view_restore(C);
1984
1985                 float back[4];
1986                 UI_GetThemeColor4fv(colorid, back);
1987                 GPU_clear_color(back[3] * back[0], back[3] * back[1], back[3] * back[2], back[3]);
1988                 GPU_clear(GPU_COLOR_BIT);
1989         }
1990         else {
1991                 UI_ThemeClearColor(colorid);
1992                 GPU_clear(GPU_COLOR_BIT);
1993         }
1994 }
1995
1996 BLI_INLINE bool streq_array_any(const char *s, const char *arr[])
1997 {
1998         for (uint i = 0; arr[i]; i++) {
1999                 if (STREQ(arr[i], s)) {
2000                         return true;
2001                 }
2002         }
2003         return false;
2004 }
2005
2006 static void ed_panel_draw(
2007         const bContext *C,
2008         ScrArea *sa,
2009         ARegion *ar,
2010         ListBase *lb,
2011         PanelType *pt,
2012         Panel *panel,
2013         int w,
2014         int em,
2015         bool vertical)
2016 {
2017         uiStyle *style = UI_style_get_dpi();
2018
2019         /* draw panel */
2020         uiBlock *block = UI_block_begin(C, ar, pt->idname, UI_EMBOSS);
2021
2022         bool open;
2023         panel = UI_panel_begin(sa, ar, lb, block, pt, panel, &open);
2024
2025         /* bad fixed values */
2026         int xco, yco, h = 0;
2027
2028         if (pt->draw_header_preset && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2029                 /* for preset menu */
2030                 panel->layout = UI_block_layout(
2031                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2032                         0, (UI_UNIT_Y * 1.1f) + style->panelspace, UI_UNIT_Y, 1, 0, style);
2033
2034                 pt->draw_header_preset(C, panel);
2035
2036                 int headerend = w - UI_UNIT_X;
2037
2038                 UI_block_layout_resolve(block, &xco, &yco);
2039                 UI_block_translate(block, headerend - xco, 0);
2040                 panel->layout = NULL;
2041         }
2042
2043         if (pt->draw_header && !(pt->flag & PNL_NO_HEADER) && (open || vertical)) {
2044                 int labelx, labely;
2045                 UI_panel_label_offset(block, &labelx, &labely);
2046
2047                 /* for enabled buttons */
2048                 panel->layout = UI_block_layout(
2049                         block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER,
2050                         labelx, labely, UI_UNIT_Y, 1, 0, style);
2051
2052                 pt->draw_header(C, panel);
2053
2054                 UI_block_layout_resolve(block, &xco, &yco);
2055                 panel->labelofs = xco - labelx;
2056                 panel->layout = NULL;
2057         }
2058         else {
2059                 panel->labelofs = 0;
2060         }
2061
2062         if (open) {
2063                 short panelContext;
2064
2065                 /* panel context can either be toolbar region or normal panels region */
2066                 if (pt->flag & PNL_LAYOUT_VERT_BAR) {
2067                         panelContext = UI_LAYOUT_VERT_BAR;
2068                 }
2069                 else if (ar->regiontype == RGN_TYPE_TOOLS) {
2070                         panelContext = UI_LAYOUT_TOOLBAR;
2071                 }
2072                 else {
2073                         panelContext = UI_LAYOUT_PANEL;
2074                 }
2075
2076                 panel->layout = UI_block_layout(
2077                         block, UI_LAYOUT_VERTICAL, panelContext,
2078                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : style->panelspace, 0,
2079                         (pt->flag & PNL_LAYOUT_VERT_BAR) ? 0 : w - 2 * style->panelspace,
2080                         em, 0, style);
2081
2082                 pt->draw(C, panel);
2083
2084                 UI_block_layout_resolve(block, &xco, &yco);
2085                 panel->layout = NULL;
2086
2087                 if (yco != 0) {
2088                         h = -yco + 2 * style->panelspace;
2089                 }
2090         }
2091
2092         UI_block_end(C, block);
2093
2094         /* Draw child panels. */
2095         if (open) {
2096                 for (LinkData *link = pt->children.first; link; link = link->next) {
2097                         PanelType *child_pt = link->data;
2098                         Panel *child_panel = UI_panel_find_by_type(&panel->children, child_pt);
2099
2100                         if (child_pt->draw && (!child_pt->poll || child_pt->poll(C, child_pt))) {
2101                                 ed_panel_draw(C, sa, ar, &panel->children, child_pt, child_panel, w, em, vertical);
2102                         }
2103                 }
2104         }
2105
2106         UI_panel_end(block, w, h);
2107 }
2108
2109 /**
2110  * \param contexts: A NULL terminated array of context strings to match against.
2111  * Matching against any of these strings will draw the panel.
2112  * Can be NULL to skip context checks.
2113  */
2114 void ED_region_panels_layout_ex(
2115         const bContext *C, ARegion *ar,
2116         const char *contexts[], int contextnr, const bool vertical)
2117 {
2118         ar->runtime.category = NULL;
2119
2120         const WorkSpace *workspace = CTX_wm_workspace(C);
2121         ScrArea *sa = CTX_wm_area(C);
2122         PanelType *pt;
2123         View2D *v2d = &ar->v2d;
2124         int x, y, w, em;
2125         bool is_context_new = 0;
2126         int scroll;
2127
2128         /* XXX, should use some better check? */
2129         /* For now also has hardcoded check for clip editor until it supports actual toolbar. */
2130         bool use_category_tabs = ((1 << ar->regiontype) & RGN_TYPE_HAS_CATEGORY_MASK) ||
2131                                  (ar->regiontype == RGN_TYPE_TOOLS && sa->spacetype == SPACE_CLIP);
2132         /* offset panels for small vertical tab area */
2133         const char *category = NULL;
2134         const int category_tabs_width = UI_PANEL_CATEGORY_MARGIN_WIDTH;
2135         int margin_x = 0;
2136         const bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2137
2138         BLI_SMALLSTACK_DECLARE(pt_stack, PanelType *);
2139
2140         if (contextnr != -1)
2141                 is_context_new = UI_view2d_tab_set(v2d, contextnr);
2142
2143         /* before setting the view */
2144         if (vertical) {
2145                 /* only allow scrolling in vertical direction */
2146                 v2d->keepofs |= V2D_LOCKOFS_X | V2D_KEEPOFS_Y;
2147                 v2d->keepofs &= ~(V2D_LOCKOFS_Y | V2D_KEEPOFS_X);
2148                 v2d->scroll &= ~(V2D_SCROLL_BOTTOM);
2149                 v2d->scroll |= (V2D_SCROLL_RIGHT);
2150         }
2151         else {
2152                 /* for now, allow scrolling in both directions (since layouts are optimized for vertical,
2153                  * they often don't fit in horizontal layout)
2154                  */
2155                 v2d->keepofs &= ~(V2D_LOCKOFS_X | V2D_LOCKOFS_Y | V2D_KEEPOFS_X | V2D_KEEPOFS_Y);
2156                 v2d->scroll |= (V2D_SCROLL_BOTTOM);
2157                 v2d->scroll &= ~(V2D_SCROLL_RIGHT);
2158         }
2159
2160         scroll = v2d->scroll;
2161
2162
2163         /* collect panels to draw */
2164         for (pt = ar->type->paneltypes.last; pt; pt = pt->prev) {
2165                 /* Only draw top level panels. */
2166                 if (pt->parent) {
2167                         continue;
2168                 }
2169
2170                 /* verify context */
2171                 if (contexts && pt->context[0] && !streq_array_any(pt->context, contexts)) {
2172                         continue;
2173                 }
2174
2175                 /* If we're tagged, only use compatible. */
2176                 if (pt->owner_id[0] && BKE_workspace_owner_id_check(workspace, pt->owner_id) == false) {
2177                         continue;
2178                 }
2179
2180                 /* draw panel */
2181                 if (pt->draw && (!pt->poll || pt->poll(C, pt))) {
2182                         BLI_SMALLSTACK_PUSH(pt_stack, pt);
2183                 }
2184         }
2185
2186
2187         /* collect categories */
2188         if (use_category_tabs) {
2189                 UI_panel_category_clear_all(ar);
2190
2191                 /* gather unique categories */
2192                 BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2193                 {
2194                         if (pt->category[0]) {
2195                                 if (!UI_panel_category_find(ar, pt->category)) {
2196                                         UI_panel_category_add(ar, pt->category);
2197                                 }
2198                         }
2199                 }
2200                 BLI_SMALLSTACK_ITER_END;
2201
2202                 if (!UI_panel_category_is_visible(ar)) {
2203                         use_category_tabs = false;
2204                 }
2205                 else {
2206                         category = UI_panel_category_active_get(ar, true);
2207                         margin_x = category_tabs_width;
2208                 }
2209         }
2210
2211
2212         if (vertical) {
2213                 w = BLI_rctf_size_x(&v2d->cur);
2214                 em = (ar->type->prefsizex) ? 10 : 20; /* works out to 10*UI_UNIT_X or 20*UI_UNIT_X */
2215         }
2216         else {
2217                 w = UI_PANEL_WIDTH;
2218                 em = (ar->type->prefsizex) ? 10 : 20;
2219         }
2220
2221         w -= margin_x;
2222
2223         /* create panels */
2224         UI_panels_begin(C, ar);
2225
2226         /* set view2d view matrix  - UI_block_begin() stores it */
2227         UI_view2d_view_ortho(v2d);
2228
2229         BLI_SMALLSTACK_ITER_BEGIN(pt_stack, pt)
2230         {
2231                 Panel *panel = UI_panel_find_by_type(&ar->panels, pt);
2232
2233                 if (use_category_tabs && pt->category[0] && !STREQ(category, pt->category)) {
2234                         if ((panel == NULL) || ((panel->flag & PNL_PIN) == 0)) {
2235                                 continue;
2236                         }
2237                 }
2238
2239                 ed_panel_draw(C, sa, ar, &ar->panels, pt, panel, w, em, vertical);
2240         }
2241         BLI_SMALLSTACK_ITER_END;
2242
2243         /* align panels and return size */
2244         UI_panels_end(C, ar, &x, &y);
2245
2246         /* before setting the view */
2247         if (region_layout_based) {
2248                 /* XXX, only single panel support atm.
2249                  * Can't use x/y values calculated above because they're not using the real height of panels,
2250                  * instead they calculate offsets for the next panel to start drawing. */
2251                 Panel *panel = ar->panels.last;
2252                 if (panel != NULL) {
2253                         int size_dyn[2] = {
2254                                 UI_UNIT_X * ((panel->flag & PNL_CLOSED) ? 8 : 14),
2255                                 UI_panel_size_y(panel),
2256                         };
2257                         /* region size is layout based and needs to be updated */
2258                         if ((ar->sizex != size_dyn[0]) ||
2259                             (ar->sizey != size_dyn[1]))
2260                         {
2261                                 ar->sizex = size_dyn[0];
2262                                 ar->sizey = size_dyn[1];
2263                                 sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2264                         }
2265                         y = ABS(ar->sizey - 1);
2266                 }
2267         }
2268         else if (vertical) {
2269                 /* we always keep the scroll offset - so the total view gets increased with the scrolled away part */
2270                 if (v2d->cur.ymax < -FLT_EPSILON) {
2271                         /* Clamp to lower view boundary */
2272                         if (v2d->tot.ymin < -v2d->winy) {
2273                                 y = min_ii(y, 0);
2274                         }
2275                         else {
2276                                 y = min_ii(y, v2d->cur.ymin);
2277                         }
2278                 }
2279
2280                 y = -y;
2281         }
2282         else {
2283                 /* don't jump back when panels close or hide */
2284                 if (!is_context_new) {
2285                         if (v2d->tot.xmax > v2d->winx) {
2286                                 x = max_ii(x, 0);
2287                         }
2288                         else {
2289                                 x = max_ii(x, v2d->cur.xmax);
2290                         }
2291                 }
2292
2293                 y = -y;
2294         }
2295
2296         /* this also changes the 'cur' */
2297         UI_view2d_totRect_set(v2d, x, y);
2298
2299         if (scroll != v2d->scroll) {
2300                 /* Note: this code scales fine, but because of rounding differences, positions of elements
2301                  * flip +1 or -1 pixel compared to redoing the entire layout again.
2302                  * Leaving in commented code for future tests */
2303 #if 0
2304                 UI_panels_scale(ar, BLI_rctf_size_x(&v2d->cur));
2305                 break;
2306 #endif
2307         }
2308
2309         if (use_category_tabs) {
2310                 ar->runtime.category = category;
2311         }
2312 }
2313 void ED_region_panels_layout(const bContext *C, ARegion *ar)
2314 {
2315         ED_region_panels_layout_ex(C, ar, NULL, -1, true);
2316 }
2317
2318 void ED_region_panels_draw(const bContext *C, ARegion *ar)
2319 {
2320         View2D *v2d = &ar->v2d;
2321
2322         if (ar->alignment != RGN_ALIGN_FLOAT) {
2323                 region_clear_color(C, ar, (ar->type->regionid == RGN_TYPE_PREVIEW) ? TH_PREVIEW_BACK : TH_BACK);
2324         }
2325
2326         /* reset line width for drawing tabs */
2327         GPU_line_width(1.0f);
2328
2329         /* set the view */
2330         UI_view2d_view_ortho(v2d);
2331
2332         /* draw panels */
2333         UI_panels_draw(C, ar);
2334
2335         /* restore view matrix */
2336         UI_view2d_view_restore(C);
2337
2338         /* Set in layout. */
2339         if (ar->runtime.category) {
2340                 UI_panel_category_draw_all(ar, ar->runtime.category);
2341         }
2342
2343         /* scrollers */
2344         const rcti *mask = NULL;
2345         rcti        mask_buf;
2346         if (ar->runtime.category && (ar->alignment == RGN_ALIGN_RIGHT)) {
2347                 UI_view2d_mask_from_win(v2d, &mask_buf);
2348                 mask_buf.xmax -= UI_PANEL_CATEGORY_MARGIN_WIDTH;
2349                 mask = &mask_buf;
2350         }
2351         View2DScrollers *scrollers = UI_view2d_scrollers_calc(
2352                 C, v2d, mask, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY, V2D_ARG_DUMMY);
2353         UI_view2d_scrollers_draw(C, v2d, scrollers);
2354         UI_view2d_scrollers_free(scrollers);
2355 }
2356
2357 void ED_region_panels_ex(
2358         const bContext *C, ARegion *ar,
2359         const char *contexts[], int contextnr, const bool vertical)
2360 {
2361         /* TODO: remove? */
2362         ED_region_panels_layout_ex(C, ar, contexts, contextnr, vertical);
2363         ED_region_panels_draw(C, ar);
2364 }
2365
2366 void ED_region_panels(const bContext *C, ARegion *ar)
2367 {
2368         /* TODO: remove? */
2369         ED_region_panels_layout(C, ar);
2370         ED_region_panels_draw(C, ar);
2371 }
2372
2373 void ED_region_panels_init(wmWindowManager *wm, ARegion *ar)
2374 {
2375         wmKeyMap *keymap;
2376
2377         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_PANELS_UI, ar->winx, ar->winy);
2378
2379         keymap = WM_keymap_ensure(wm->defaultconf, "View2D Buttons List", 0, 0);
2380         WM_event_add_keymap_handler(&ar->handlers, keymap);
2381 }
2382
2383 void ED_region_header_layout(const bContext *C, ARegion *ar)
2384 {
2385         uiStyle *style = UI_style_get_dpi();
2386         uiBlock *block;
2387         uiLayout *layout;
2388         HeaderType *ht;
2389         Header header = {NULL};
2390         bool region_layout_based = ar->flag & RGN_FLAG_DYNAMIC_SIZE;
2391
2392         /* Height of buttons and scaling needed to achieve it. */
2393         const int buttony = min_ii(UI_UNIT_Y, ar->winy - 2 * UI_DPI_FAC);
2394         const float buttony_scale = buttony / (float)UI_UNIT_Y;
2395
2396         /* Vertically center buttons. */
2397         int xco = UI_HEADER_OFFSET;
2398         int yco = buttony + (ar->winy - buttony) / 2;
2399         int maxco = xco;
2400
2401         /* XXX workaround for 1 px alignment issue. Not sure what causes it... Would prefer a proper fix - Julian */
2402         if (!ELEM(CTX_wm_area(C)->spacetype, SPACE_TOPBAR, SPACE_STATUSBAR)) {
2403                 yco -= 1;
2404         }
2405
2406         /* set view2d view matrix for scrolling (without scrollers) */
2407         UI_view2d_view_ortho(&ar->v2d);
2408
2409         /* draw all headers types */
2410         for (ht = ar->type->headertypes.first; ht; ht = ht->next) {
2411                 if (ht->poll && !ht->poll(C, ht)) {
2412                         continue;
2413                 }
2414
2415                 block = UI_block_begin(C, ar, ht->idname, UI_EMBOSS);
2416                 layout = UI_block_layout(block, UI_LAYOUT_HORIZONTAL, UI_LAYOUT_HEADER, xco, yco, buttony, 1, 0, style);
2417
2418                 if (buttony_scale != 1.0f) {
2419                         uiLayoutSetScaleY(layout, buttony_scale);
2420                 }
2421
2422                 if (ht->draw) {
2423                         header.type = ht;
2424                         header.layout = layout;
2425                         ht->draw(C, &header);
2426                         if (ht->next) {
2427                                 uiItemS(layout);
2428                         }
2429
2430                         /* for view2d */
2431                         xco = uiLayoutGetWidth(layout);
2432                         if (xco > maxco)
2433                                 maxco = xco;
2434                 }
2435
2436                 UI_block_layout_resolve(block, &xco, &yco);
2437
2438                 /* for view2d */
2439                 if (xco > maxco)
2440                         maxco = xco;
2441
2442                 int new_sizex = (maxco + UI_HEADER_OFFSET) / UI_DPI_FAC;
2443
2444                 if (region_layout_based && (ar->sizex != new_sizex)) {
2445                         /* region size is layout based and needs to be updated */
2446                         ScrArea *sa = CTX_wm_area(C);
2447
2448                         ar->sizex = new_sizex;
2449                         sa->flag |= AREA_FLAG_REGION_SIZE_UPDATE;
2450                 }
2451
2452                 UI_block_end(C, block);
2453         }
2454
2455         if (!region_layout_based) {
2456                 maxco += UI_HEADER_OFFSET;
2457         }
2458
2459         /* always as last  */
2460         UI_view2d_totRect_set(&ar->v2d, maxco, ar->winy);
2461
2462         /* restore view matrix */
2463         UI_view2d_view_restore(C);
2464 }
2465
2466 void ED_region_header_draw(const bContext *C, ARegion *ar)
2467 {
2468         /* clear */
2469         region_clear_color(C, ar, region_background_color_id(C, ar));
2470
2471         UI_view2d_view_ortho(&ar->v2d);
2472
2473         /* View2D matrix might have changed due to dynamic sized regions. */
2474         UI_blocklist_update_window_matrix(C, &ar->uiblocks);
2475
2476         /* draw blocks */
2477         UI_blocklist_draw(C, &ar->uiblocks);
2478
2479         /* restore view matrix */
2480         UI_view2d_view_restore(C);
2481 }
2482
2483 void ED_region_header(const bContext *C, ARegion *ar)
2484 {
2485         /* TODO: remove? */
2486         ED_region_header_layout(C, ar);
2487         ED_region_header_draw(C, ar);
2488 }
2489
2490 void ED_region_header_init(ARegion *ar)
2491 {
2492         UI_view2d_region_reinit(&ar->v2d, V2D_COMMONVIEW_HEADER, ar->winx, ar->winy);
2493 }
2494
2495 /* UI_UNIT_Y is defined as U variable now, depending dpi */
2496 int ED_area_headersize(void)
2497 {
2498         return (int)(HEADERY * UI_DPI_FAC);
2499 }
2500
2501
2502 int ED_area_header_alignment(const ScrArea *area)
2503 {
2504         for (ARegion *ar = area->regionbase.first; ar; ar = ar->next) {
2505                 if (ar->regiontype == RGN_TYPE_HEADER) {
2506                         return ar->alignment;
2507                 }
2508         }
2509
2510         return RGN_ALIGN_TOP;
2511 }
2512
2513 /**
2514  * \return the final height of a global \a area, accounting for DPI.
2515  */
2516 int ED_area_global_size_y(const ScrArea *area)
2517 {
2518         BLI_assert(ED_area_is_global(area));
2519         return round_fl_to_int(area->global->cur_fixed_height * UI_DPI_FAC);
2520 }
2521 int ED_area_global_min_size_y(const ScrArea *area)
2522 {
2523         BLI_assert(ED_area_is_global(area));
2524         return round_fl_to_int(area->global->size_min * UI_DPI_FAC);
2525 }
2526 int ED_area_global_max_size_y(const ScrArea *area)
2527 {
2528         BLI_assert(ED_area_is_global(area));
2529         return round_fl_to_int(area->global->size_max * UI_DPI_FAC);
2530 }
2531
2532 bool ED_area_is_global(const ScrArea *area)
2533 {
2534         return area->global != NULL;
2535 }
2536
2537 ScrArea *ED_screen_areas_iter_first(const wmWindow *win, const bScreen *screen)
2538 {
2539         ScrArea *global_area = win->global_areas.areabase.first;
2540
2541         if (!global_area) {
2542                 return screen->areabase.first;
2543         }
2544         else if ((global_area->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2545                 return global_area;
2546         }
2547         /* Find next visible area. */
2548         return ED_screen_areas_iter_next(screen, global_area);
2549 }
2550 ScrArea *ED_screen_areas_iter_next(const bScreen *screen, const ScrArea *area)
2551 {
2552         if (area->global) {
2553                 for (ScrArea *area_iter = area->next; area_iter; area_iter = area_iter->next) {
2554                         if ((area_iter->global->flag & GLOBAL_AREA_IS_HIDDEN) == 0) {
2555                                 return area_iter;
2556                         }
2557                 }
2558                 /* No visible next global area found, start iterating over layout areas. */
2559                 return screen->areabase.first;
2560         }
2561
2562         return area->next;
2563 }
2564
2565 /**
2566  * For now we just assume all global areas are made up out of horizontal bars
2567  * with the same size. A fixed size could be stored in ARegion instead if needed.
2568  *
2569  * \return the DPI aware height of a single bar/region in global areas.
2570  */
2571 int ED_region_global_size_y(void)
2572 {
2573         return ED_area_headersize(); /* same size as header */
2574 }
2575
2576 void ED_region_info_draw_multiline(ARegion *ar, const char *text_array[], float fill_color[4], const bool full_redraw)
2577 {
2578         const int header_height = UI_UNIT_Y;
2579         uiStyle *style = UI_style_get_dpi();
2580         int fontid = style->widget.uifont_id;
2581         int scissor[4];
2582         rcti rect;
2583         int num_lines = 0;
2584
2585         /* background box */
2586         ED_region_visible_rect(ar, &rect);
2587
2588         /* Box fill entire width or just around text. */
2589         if (!full_redraw) {
2590                 const char **text = &text_array[0];
2591                 while (*text) {
2592                         rect.xmax = min_ii(rect.xmax, rect.xmin + BLF_width(fontid, *text, BLF_DRAW_STR_DUMMY_MAX) + 1.2f * U.widget_unit);
2593                         text++;
2594                         num_lines++;
2595                 }
2596         }
2597         /* Just count the line number. */
2598         else {
2599                 const char **text = &text_array[0];
2600                 while (*text) {
2601                         text++;
2602                         num_lines++;
2603                 }
2604         }
2605
2606         rect.ymin = rect.ymax - header_height * num_lines;
2607
2608         /* setup scissor */
2609         GPU_scissor_get_i(scissor);
2610         GPU_scissor(rect.xmin, rect.ymin,
2611                   BLI_rcti_size_x(&rect) + 1, BLI_rcti_size_y(&rect) + 1);
2612
2613         GPU_blend(true);
2614         GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2615         GPUVertFormat *format = immVertexFormat();
2616         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
2617         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2618         immUniformColor4fv(fill_color);
2619         immRecti(pos, rect.xmin, rect.ymin, rect.xmax + 1, rect.ymax + 1);
2620         immUnbindProgram();
2621         GPU_blend(false);
2622
2623         /* text */
2624         UI_FontThemeColor(fontid, TH_TEXT_HI);
2625         BLF_clipping(fontid, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2626         BLF_enable(fontid, BLF_CLIPPING);
2627         int offset = num_lines - 1;
2628         {
2629                 const char **text = &text_array[0];
2630                 while (*text) {
2631                         BLF_position(fontid, rect.xmin + 0.6f * U.widget_unit, rect.ymin + 0.3f * U.widget_unit + offset * header_height, 0.0f);
2632                         BLF_draw(fontid, *text, BLF_DRAW_STR_DUMMY_MAX);
2633                         text++;
2634                         offset--;
2635                 }
2636         }
2637
2638         BLF_disable(fontid, BLF_CLIPPING);
2639
2640         /* restore scissor as it was before */
2641         GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]);
2642 }
2643
2644 void ED_region_info_draw(ARegion *ar, const char *text, float fill_color[4], const bool full_redraw)
2645 {
2646         ED_region_info_draw_multiline(ar, (const char *[2]){text, NULL}, fill_color, full_redraw);
2647 }
2648
2649 #define MAX_METADATA_STR    1024
2650
2651 static const char *meta_data_list[] =
2652 {
2653         "File",
2654         "Strip",
2655         "Date",
2656         "RenderTime",
2657         "Note",
2658         "Marker",
2659         "Time",
2660         "Frame",
2661         "Camera",
2662         "Scene"
2663 };
2664
2665 BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset)
2666 {
2667         return (IMB_metadata_get_field(ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
2668 }
2669
2670 static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top)
2671 {
2672         char temp_str[MAX_METADATA_STR];
2673         int line_width;
2674         int ofs_y = 0;
2675         short i;
2676         int len;
2677         const float height = BLF_height_max(fontid);
2678         const float margin = height / 8;
2679         const float vertical_offset = (height + margin);
2680
2681         /* values taking margins into account */
2682         const float descender = BLF_descender(fontid);
2683         const float xmin = (rect->xmin + margin);
2684         const float xmax = (rect->xmax - margin);
2685         const float ymin = (rect->ymin + margin) - descender;
2686         const float ymax = (rect->ymax - margin) - descender;
2687
2688         if (is_top) {
2689                 for (i = 0; i < 4; i++) {
2690                         /* first line */
2691                         if (i == 0) {
2692                                 bool do_newline = false;
2693                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]);
2694                                 if (metadata_is_valid(ibuf, temp_str, 0, len)) {
2695                                         BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f);
2696                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2697                                         do_newline = true;
2698                                 }
2699
2700                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]);
2701                                 if (metadata_is_valid(ibuf, temp_str, 1, len)) {
2702                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2703                                         BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f);
2704                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2705                                         do_newline = true;
2706                                 }
2707
2708                                 if (do_newline)
2709                                         ofs_y += vertical_offset;
2710                         } /* Strip */
2711                         else if (i == 1 || i == 2) {
2712                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2713                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2714                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2715                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2716                                         ofs_y += vertical_offset;
2717                                 }
2718                         } /* Note (wrapped) */
2719                         else if (i == 3) {
2720                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2721                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2722                                         struct ResultBLF info;
2723                                         BLF_enable(fontid, BLF_WORD_WRAP);
2724                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2725                                         BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f);
2726                                         BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info);
2727                                         BLF_wordwrap(fontid, 0);
2728                                         BLF_disable(fontid, BLF_WORD_WRAP);
2729                                         ofs_y += vertical_offset * info.lines;
2730                                 }
2731                         }
2732                         else {
2733                                 len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]);
2734                                 if (metadata_is_valid(ibuf, temp_str, i + 1, len)) {
2735                                         line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2736                                         BLF_position(fontid, xmax  - line_width, ymax - vertical_offset - ofs_y, 0.0f);
2737                                         BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2738                                         ofs_y += vertical_offset;
2739                                 }
2740                         }
2741                 }
2742         }
2743         else {
2744                 int ofs_x = 0;
2745                 for (i = 5; i < 10; i++) {
2746                         len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]);
2747                         if (metadata_is_valid(ibuf, temp_str, i, len)) {
2748                                 BLF_position(fontid, xmin + ofs_x, ymin, 0.0f);
2749                                 BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX);
2750
2751                                 ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X;
2752                         }
2753                 }
2754         }
2755 }
2756
2757 static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top)
2758 {
2759         const float height = BLF_height_max(fontid);
2760         const float margin = (height / 8);
2761         char str[MAX_METADATA_STR] = "";
2762         short i, count = 0;
2763
2764         if (is_top) {
2765                 if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) {
2766                         count++;
2767                 }
2768                 for (i = 2; i < 5; i++) {
2769                         if (metadata_is_valid(ibuf, str, i, 0)) {
2770                                 if (i == 4) {
2771                                         struct {
2772                                                 struct ResultBLF info;
2773                                                 rctf rect;
2774                                         } wrap;
2775
2776                                         BLF_enable(fontid, BLF_WORD_WRAP);
2777                                         BLF_wordwrap(fontid, ibuf->x - (margin * 2));
2778                                         BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info);
2779                                         BLF_wordwrap(fontid, 0);
2780                                         BLF_disable(fontid, BLF_WORD_WRAP);
2781
2782                                         count += wrap.info.lines;
2783                                 }
2784                                 else {
2785                                         count++;
2786                                 }
2787                         }
2788                 }
2789         }
2790         else {
2791                 for (i = 5; i < 10; i++) {
2792                         if (metadata_is_valid(ibuf, str, i, 0)) {
2793                                 count = 1;
2794                         }
2795                 }
2796         }
2797
2798         if (count) {
2799                 return (height + margin) * count;
2800         }
2801
2802         return 0;
2803 }
2804
2805 #undef MAX_METADATA_STR
2806
2807 void ED_region_image_metadata_draw(int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy)
2808 {
2809         float box_y;
2810         rctf rect;
2811         uiStyle *style = UI_style_get_dpi();
2812
2813         if (!ibuf->metadata)
2814                 return;
2815
2816         /* find window pixel coordinates of origin */
2817         GPU_matrix_push();
2818
2819         /* offset and zoom using ogl */
2820         GPU_matrix_translate_2f(x, y);
2821         GPU_matrix_scale_2f(zoomx, zoomy);
2822
2823         BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi);
2824
2825         /* *** upper box*** */
2826
2827         /* get needed box height */
2828         box_y = metadata_box_height_get(ibuf, blf_mono_font, true);
2829
2830         if (box_y) {
2831                 /* set up rect */
2832                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y);
2833                 /* draw top box */
2834                 GPUVertFormat *format = immVertexFormat();
2835                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2836                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2837                 immUniformThemeColor(TH_METADATA_BG);
2838                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2839                 immUnbindProgram();
2840
2841                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2842                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2843
2844                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2845                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true);
2846
2847                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2848         }
2849
2850
2851         /* *** lower box*** */
2852
2853         box_y = metadata_box_height_get(ibuf, blf_mono_font, false);
2854
2855         if (box_y) {
2856                 /* set up box rect */
2857                 BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin);
2858                 /* draw top box */
2859                 GPUVertFormat *format = immVertexFormat();
2860                 uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2861                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2862                 immUniformThemeColor(TH_METADATA_BG);
2863                 immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2864                 immUnbindProgram();
2865
2866                 BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
2867                 BLF_enable(blf_mono_font, BLF_CLIPPING);
2868
2869                 UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT);
2870                 metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false);
2871
2872                 BLF_disable(blf_mono_font, BLF_CLIPPING);
2873         }
2874
2875         GPU_matrix_pop();
2876 }
2877
2878 void ED_region_grid_draw(ARegion *ar, float zoomx, float zoomy)
2879 {
2880         float gridsize, gridstep = 1.0f / 32.0f;
2881         float fac, blendfac;
2882         int x1, y1, x2, y2;
2883
2884         /* the image is located inside (0, 0), (1, 1) as set by view2d */
2885         UI_view2d_view_to_region(&ar->v2d, 0.0f, 0.0f, &x1, &y1);
2886         UI_view2d_view_to_region(&ar->v2d, 1.0f, 1.0f, &x2, &y2);
2887
2888         GPUVertFormat *format = immVertexFormat();
2889         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2890
2891         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2892         immUniformThemeColorShade(TH_BACK, 20);
2893         immRectf(pos, x1, y1, x2, y2);
2894         immUnbindProgram();
2895
2896         /* gridsize adapted to zoom level */
2897         gridsize = 0.5f * (zoomx + zoomy);
2898         if (gridsize <= 0.0f)
2899                 return;
2900
2901         if (gridsize < 1.0f) {
2902                 while (gridsize < 1.0f) {
2903                         gridsize *= 4.0f;
2904                         gridstep *= 4.0f;
2905                 }
2906         }
2907         else {
2908                 while (gridsize >= 4.0f) {
2909                         gridsize /= 4.0f;
2910                         gridstep /= 4.0f;
2911                 }
2912         }
2913
2914         blendfac = 0.25f * gridsize - floorf(0.25f * gridsize);
2915         CLAMP(blendfac, 0.0f, 1.0f);
2916
2917         int count_fine = 1.0f / gridstep;
2918         int count_large = 1.0f / (4.0f * gridstep);
2919
2920         if (count_fine > 0) {
2921                 GPU_vertformat_clear(format);
2922                 pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2923                 unsigned color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
2924
2925                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
2926                 immBegin(GPU_PRIM_LINES, 4 * count_fine + 4 * count_large);
2927
2928                 float theme_color[3];
2929                 UI_GetThemeColorShade3fv(TH_BACK, (int)(20.0f * (1.0f - blendfac)), theme_color);
2930                 fac = 0.0f;
2931
2932                 /* the fine resolution level */
2933                 for (int i = 0; i < count_fine; i++) {
2934                         immAttr3fv(color, theme_color);
2935                         immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
2936                         immAttr3fv(color, theme_color);
2937                         immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
2938                         immAttr3fv(color, theme_color);
2939                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
2940                         immAttr3fv(color, theme_color);
2941                         immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
2942                         fac += gridstep;
2943                 }
2944
2945                 if (count_large > 0) {
2946                         UI_GetThemeColor3fv(TH_BACK, theme_color);
2947                         fac = 0.0f;
2948
2949                         /* the large resolution level */
2950                         for (int i = 0; i < count_large; i++) {
2951                                 immAttr3fv(color, theme_color);
2952                                 immVertex2f(pos, x1, y1 * (1.0f - fac) + y2 * fac);
2953                                 immAttr3fv(color, theme_color);
2954                                 immVertex2f(pos, x2, y1 * (1.0f - fac) + y2 * fac);
2955                                 immAttr3fv(color, theme_color);
2956                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y1);
2957                                 immAttr3fv(color, theme_color);
2958                                 immVertex2f(pos, x1 * (1.0f - fac) + x2 * fac, y2);
2959                                 fac += 4.0f * gridstep;
2960                         }
2961                 }
2962
2963                 immEnd();
2964                 immUnbindProgram();
2965         }
2966 }
2967
2968 /* If the area has overlapping regions, it returns visible rect for Region *ar */
2969 /* rect gets returned in local region coordinates */
2970 void ED_region_visible_rect(ARegion *ar, rcti *rect)
2971 {
2972         ARegion *arn = ar;
2973
2974         /* allow function to be called without area */
2975         while (arn->prev)
2976                 arn = arn->prev;
2977
2978         *rect = ar->winrct;
2979
2980         /* check if a region overlaps with the current one */
2981         for (; arn; arn = arn->next) {
2982                 if (ar != arn && arn->overlap) {
2983                         if (BLI_rcti_isect(rect, &arn->winrct, NULL)) {
2984                                 if (ELEM(arn->alignment, RGN_ALIGN_LEFT, RGN_ALIGN_RIGHT)) {
2985                                         /* Overlap left, also check 1 pixel offset (2 regions on one side). */
2986                                         if (ABS(rect->xmin - arn->winrct.xmin) < 2) {
2987                                                 rect->xmin = arn->winrct.xmax;
2988                                         }
2989
2990                                         /* Overlap right. */
2991                                         if (ABS(rect->xmax - arn->winrct.xmax) < 2) {
2992                                                 rect->xmax = arn->winrct.xmin;
2993                                         }
2994                                 }
2995                                 else if (ELEM(arn->alignment, RGN_ALIGN_TOP, RGN_ALIGN_BOTTOM)) {
2996                                         /* Same logic as above for vertical regions. */
2997                                         if (ABS(rect->ymin - arn->winrct.ymin) < 2) {
2998                                                 rect->ymin = arn->winrct.ymax;
2999                                         }
3000                                         if (ABS(rect->ymax - arn->winrct.ymax) < 2) {
3001                                                 rect->ymax = arn->winrct.ymin;
3002                                         }
3003                                 }
3004                                 else if (arn->alignment == RGN_ALIGN_FLOAT) {
3005                                         /* Skip floating. */
3006                                 }
3007                                 else {
3008                                         BLI_assert(!"Region overlap with unknown alignment");
3009                                 }
3010                         }
3011                 }
3012         }
3013         BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
3014 }
3015
3016 /* Cache display helpers */
3017
3018 void ED_region_cache_draw_background(const ARegion *ar)
3019 {
3020         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3021         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3022         immUniformColor4ub(128, 128, 255, 64);
3023         immRecti(pos, 0, 0, ar->winx, 8 * UI_DPI_FAC);
3024         immUnbindProgram();
3025 }
3026
3027 void ED_region_cache_draw_curfra_label(const int framenr, const float x, const float y)
3028 {
3029         uiStyle *style = UI_style_get();
3030         int fontid = style->widget.uifont_id;
3031         char numstr[32];
3032         float font_dims[2] = {0.0f, 0.0f};
3033
3034         /* frame number */
3035         BLF_size(fontid, 11.0f * U.pixelsize, U.dpi);
3036         BLI_snprintf(numstr, sizeof(numstr), "%d", framenr);
3037
3038         BLF_width_and_height(fontid, numstr, sizeof(numstr), &font_dims[0], &font_dims[1]);
3039
3040         uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3041         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3042         immUniformThemeColor(TH_CFRAME);
3043         immRecti(pos, x, y, x + font_dims[0] + 6.0f, y + font_dims[1] + 4.0f);
3044         immUnbindProgram();
3045
3046         UI_FontThemeColor(fontid, TH_TEXT);
3047         BLF_position(fontid, x + 2.0f, y + 2.0f, 0.0f);
3048         BLF_draw(fontid, numstr, sizeof(numstr));
3049 }
3050
3051 void ED_region_cache_draw_cached_segments(const ARegion *ar, const int num_segments, const int *points, const int sfra, const int efra)
3052 {
3053         if (num_segments) {
3054                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT);
3055                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
3056                 immUniformColor4ub(128, 128, 255, 128);
3057
3058                 for (int a = 0; a < num_segments; a++) {
3059                         float x1 = (float)(points[a * 2] - sfra) / (efra - sfra + 1) * ar->winx;
3060                         float x2 = (float)(points[a * 2 + 1] - sfra + 1) / (efra - sfra + 1) * ar->winx;
3061
3062                         immRecti(pos, x1, 0, x2, 8 * UI_DPI_FAC);
3063                         /* TODO(merwin): use primitive restart to draw multiple rects more efficiently */
3064                 }
3065
3066                 immUnbindProgram();
3067         }
3068 }
3069
3070 /**
3071  * Generate subscriptions for this region.
3072  */
3073 void ED_region_message_subscribe(
3074         bContext *C,
3075         struct WorkSpace *workspace, struct Scene *scene,
3076         struct bScreen *screen, struct ScrArea *sa, struct ARegion *ar,
3077         struct wmMsgBus *mbus)
3078 {
3079         if (ar->gizmo_map != NULL) {
3080                 WM_gizmomap_message_subscribe(C, ar->gizmo_map, ar, mbus);
3081         }
3082
3083         if (!BLI_listbase_is_empty(&ar->uiblocks)) {
3084                 UI_region_message_subscribe(ar, mbus);
3085         }
3086
3087         if (ar->type->message_subscribe != NULL) {
3088                 ar->type->message_subscribe(C, workspace, scene, screen, sa, ar, mbus);
3089         }
3090 }
3091
3092 int ED_region_snap_size_test(const ARegion *ar)
3093 {
3094         /* Use a larger value because toggling scrollbars can jump in size. */
3095         const int snap_match_threshold = 16;
3096         if (ar->type->snap_size != NULL) {
3097                 return ((((ar->sizex - ar->type->snap_size(ar, ar->sizex, 0)) <= snap_match_threshold) << 0) |
3098                         (((ar->sizey - ar->type->snap_size(ar, ar->sizey, 1)) <= snap_match_threshold) << 1));
3099         }
3100         return 0;
3101 }
3102
3103 bool ED_region_snap_size_apply(ARegion *ar, int snap_flag)
3104 {
3105         bool changed = false;
3106         if (ar->type->snap_size != NULL) {
3107                 if (snap_flag & (1 << 0)) {
3108                         short snap_size = ar->type->snap_size(ar, ar->sizex, 0);
3109                         if (snap_size != ar->sizex) {
3110                                 ar->sizex = snap_size;
3111                                 changed = true;
3112                         }
3113                 }
3114                 if (snap_flag & (1 << 1)) {
3115                         short snap_size = ar->type->snap_size(ar, ar->sizey, 1);
3116                         if (snap_size != ar->sizey) {
3117                                 ar->sizey = snap_size;
3118                                 changed = true;
3119                         }
3120                 }
3121         }
3122         return changed;
3123 }