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