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