Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / interface / view2d.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  * Contributor(s): Blender Foundation, Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/view2d.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_scene_types.h"
39 #include "DNA_userdef_types.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_link_utils.h"
43 #include "BLI_rect.h"
44 #include "BLI_math.h"
45 #include "BLI_memarena.h"
46 #include "BLI_timecode.h"
47
48 #include "BKE_context.h"
49 #include "BKE_screen.h"
50 #include "BKE_global.h"
51
52 #include "GPU_immediate.h"
53 #include "GPU_matrix.h"
54
55 #include "WM_api.h"
56
57 #include "BLF_api.h"
58
59 #include "ED_screen.h"
60
61 #include "UI_interface.h"
62 #include "UI_view2d.h"
63
64 #include "interface_intern.h"
65
66 static void ui_view2d_curRect_validate_resize(View2D *v2d, bool resize, bool mask_scrollers);
67
68 /* *********************************************************************** */
69
70 BLI_INLINE int clamp_float_to_int(const float f)
71 {
72         const float min = INT_MIN;
73         const float max = INT_MAX;
74
75         if (UNLIKELY(f < min)) {
76                 return min;
77         }
78         else if (UNLIKELY(f > max)) {
79                 return max;
80         }
81         else {
82                 return (int)f;
83         }
84 }
85
86 /**
87  * use instead of #BLI_rcti_rctf_copy so we have consistent behavior
88  * with users of #clamp_float_to_int.
89  */
90 BLI_INLINE void clamp_rctf_to_rcti(rcti *dst, const rctf *src)
91 {
92         dst->xmin = clamp_float_to_int(src->xmin);
93         dst->xmax = clamp_float_to_int(src->xmax);
94         dst->ymin = clamp_float_to_int(src->ymin);
95         dst->ymax = clamp_float_to_int(src->ymax);
96 }
97
98
99 /* XXX still unresolved: scrolls hide/unhide vs region mask handling */
100 /* XXX there's V2D_SCROLL_HORIZONTAL_HIDE and V2D_SCROLL_HORIZONTAL_FULLR ... */
101
102 /**
103  * helper to allow scrollbars to dynamically hide
104  * - returns a copy of the scrollbar settings with the flags to display
105  *   horizontal/vertical scrollbars removed
106  * - input scroll value is the v2d->scroll var
107  * - hide flags are set per region at drawtime
108  */
109 static int view2d_scroll_mapped(int scroll)
110 {
111         if (scroll & V2D_SCROLL_HORIZONTAL_FULLR)
112                 scroll &= ~(V2D_SCROLL_HORIZONTAL);
113         if (scroll & V2D_SCROLL_VERTICAL_FULLR)
114                 scroll &= ~(V2D_SCROLL_VERTICAL);
115         return scroll;
116 }
117
118 /* called each time cur changes, to dynamically update masks */
119 static void view2d_masks(View2D *v2d, bool check_scrollers)
120 {
121         int scroll;
122         
123         /* mask - view frame */
124         v2d->mask.xmin = v2d->mask.ymin = 0;
125         v2d->mask.xmax = v2d->winx - 1; /* -1 yes! masks are pixels */
126         v2d->mask.ymax = v2d->winy - 1;
127
128         if (check_scrollers) {
129                 /* check size if hiding flag is set: */
130                 if (v2d->scroll & V2D_SCROLL_HORIZONTAL_HIDE) {
131                         if (!(v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL)) {
132                                 if (BLI_rctf_size_x(&v2d->tot) > BLI_rctf_size_x(&v2d->cur))
133                                         v2d->scroll &= ~V2D_SCROLL_HORIZONTAL_FULLR;
134                                 else
135                                         v2d->scroll |= V2D_SCROLL_HORIZONTAL_FULLR;
136                         }
137                 }
138                 if (v2d->scroll & V2D_SCROLL_VERTICAL_HIDE) {
139                         if (!(v2d->scroll & V2D_SCROLL_SCALE_VERTICAL)) {
140                                 if (BLI_rctf_size_y(&v2d->tot) + 0.01f > BLI_rctf_size_y(&v2d->cur))
141                                         v2d->scroll &= ~V2D_SCROLL_VERTICAL_FULLR;
142                                 else
143                                         v2d->scroll |= V2D_SCROLL_VERTICAL_FULLR;
144                         }
145                 }
146         }
147         
148         scroll = view2d_scroll_mapped(v2d->scroll);
149         
150         /* scrollers shrink mask area, but should be based off regionsize 
151          *      - they can only be on one to two edges of the region they define
152          *      - if they overlap, they must not occupy the corners (which are reserved for other widgets)
153          */
154         if (scroll) {
155                 /* vertical scroller */
156                 if (scroll & V2D_SCROLL_LEFT) {
157                         /* on left-hand edge of region */
158                         v2d->vert = v2d->mask;
159                         v2d->vert.xmax = V2D_SCROLL_WIDTH;
160                         v2d->mask.xmin = v2d->vert.xmax + 1;
161                 }
162                 else if (scroll & V2D_SCROLL_RIGHT) {
163                         /* on right-hand edge of region */
164                         v2d->vert = v2d->mask;
165                         v2d->vert.xmax++; /* one pixel extra... was leaving a minor gap... */
166                         v2d->vert.xmin = v2d->vert.xmax - V2D_SCROLL_WIDTH;
167                         v2d->mask.xmax = v2d->vert.xmin - 1;
168                 }
169                 
170                 /* horizontal scroller */
171                 if (scroll & (V2D_SCROLL_BOTTOM)) {
172                         /* on bottom edge of region */
173                         v2d->hor = v2d->mask;
174                         v2d->hor.ymax = V2D_SCROLL_HEIGHT;
175                         v2d->mask.ymin = v2d->hor.ymax + 1;
176                 }
177                 else if (scroll & V2D_SCROLL_TOP) {
178                         /* on upper edge of region */
179                         v2d->hor = v2d->mask;
180                         v2d->hor.ymin = v2d->hor.ymax - V2D_SCROLL_HEIGHT;
181                         v2d->mask.ymax = v2d->hor.ymin - 1;
182                 }
183                 
184                 /* adjust vertical scroller if there's a horizontal scroller, to leave corner free */
185                 if (scroll & V2D_SCROLL_VERTICAL) {
186                         /* just set y min/max for vertical scroller to y min/max of mask as appropriate */
187                         if (scroll & (V2D_SCROLL_BOTTOM)) {
188                                 /* on bottom edge of region */
189                                 v2d->vert.ymin = v2d->mask.ymin;
190                         }
191                         else if (scroll & V2D_SCROLL_TOP) {
192                                 /* on upper edge of region */
193                                 v2d->vert.ymax = v2d->mask.ymax;
194                         }
195                 }
196         }
197 }
198
199 /* Refresh and Validation */
200
201 /**
202  * Initialize all relevant View2D data (including view rects if first time) and/or refresh mask sizes after view resize
203  * - for some of these presets, it is expected that the region will have defined some
204  *   additional settings necessary for the customization of the 2D viewport to its requirements
205  * - this function should only be called from region init() callbacks, where it is expected that
206  *   this is called before UI_view2d_size_update(), as this one checks that the rects are properly initialized.
207  */
208 void UI_view2d_region_reinit(View2D *v2d, short type, int winx, int winy)
209 {
210         bool tot_changed = false, do_init;
211         uiStyle *style = UI_style_get();
212
213         do_init = (v2d->flag & V2D_IS_INITIALISED) == 0;
214
215         /* see eView2D_CommonViewTypes in UI_view2d.h for available view presets */
216         switch (type) {
217                 /* 'standard view' - optimum setup for 'standard' view behavior,
218                  *  that should be used new views as basis for their
219                  *  own unique View2D settings, which should be used instead of this in most cases...
220                  */
221                 case V2D_COMMONVIEW_STANDARD:
222                 {
223                         /* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
224                         v2d->keepzoom = (V2D_KEEPASPECT | V2D_LIMITZOOM);
225                         v2d->minzoom = 0.01f;
226                         v2d->maxzoom = 1000.0f;
227                         
228                         /* tot rect and cur should be same size, and aligned using 'standard' OpenGL coordinates for now 
229                          *      - region can resize 'tot' later to fit other data
230                          *      - keeptot is only within bounds, as strict locking is not that critical
231                          *      - view is aligned for (0,0) -> (winx-1, winy-1) setup
232                          */
233                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
234                         v2d->keeptot = V2D_KEEPTOT_BOUNDS;
235                         
236                         if (do_init) {
237                                 v2d->tot.xmin = v2d->tot.ymin = 0.0f;
238                                 v2d->tot.xmax = (float)(winx - 1);
239                                 v2d->tot.ymax = (float)(winy - 1);
240                                 
241                                 v2d->cur = v2d->tot;
242                         }
243                         /* scrollers - should we have these by default? */
244                         /* XXX for now, we don't override this, or set it either! */
245                         break;
246                 }
247                 /* 'list/channel view' - zoom, aspect ratio, and alignment restrictions are set here */
248                 case V2D_COMMONVIEW_LIST:
249                 {
250                         /* zoom + aspect ratio are locked */
251                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
252                         v2d->minzoom = v2d->maxzoom = 1.0f;
253                         
254                         /* tot rect has strictly regulated placement, and must only occur in +/- quadrant */
255                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_POS_Y);
256                         v2d->keeptot = V2D_KEEPTOT_STRICT;
257                         tot_changed = do_init;
258                         
259                         /* scroller settings are currently not set here... that is left for regions... */
260                         break;
261                 }
262                 /* 'stack view' - practically the same as list/channel view, except is located in the pos y half instead. 
263                  *  zoom, aspect ratio, and alignment restrictions are set here */
264                 case V2D_COMMONVIEW_STACK:
265                 {
266                         /* zoom + aspect ratio are locked */
267                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
268                         v2d->minzoom = v2d->maxzoom = 1.0f;
269                         
270                         /* tot rect has strictly regulated placement, and must only occur in +/+ quadrant */
271                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
272                         v2d->keeptot = V2D_KEEPTOT_STRICT;
273                         tot_changed = do_init;
274                         
275                         /* scroller settings are currently not set here... that is left for regions... */
276                         break;
277                 }
278                 /* 'header' regions - zoom, aspect ratio, alignment, and panning restrictions are set here */
279                 case V2D_COMMONVIEW_HEADER:
280                 {
281                         /* zoom + aspect ratio are locked */
282                         v2d->keepzoom = (V2D_LOCKZOOM_X | V2D_LOCKZOOM_Y | V2D_LIMITZOOM | V2D_KEEPASPECT);
283                         v2d->minzoom = v2d->maxzoom = 1.0f;
284                         
285                         if (do_init) {
286                                 v2d->tot.xmin = 0.0f;
287                                 v2d->tot.xmax = winx;
288                                 v2d->tot.ymin = 0.0f;
289                                 v2d->tot.ymax = winy;
290                                 v2d->cur = v2d->tot;
291                                 
292                                 v2d->min[0] = v2d->max[0] = (float)(winx - 1);
293                                 v2d->min[1] = v2d->max[1] = (float)(winy - 1);
294                         }
295                         /* tot rect has strictly regulated placement, and must only occur in +/+ quadrant */
296                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_NEG_Y);
297                         v2d->keeptot = V2D_KEEPTOT_STRICT;
298                         tot_changed = do_init;
299                         
300                         /* panning in y-axis is prohibited */
301                         v2d->keepofs = V2D_LOCKOFS_Y;
302                         
303                         /* absolutely no scrollers allowed */
304                         v2d->scroll = 0;
305                         break;
306                 }
307                 /* panels view, with horizontal/vertical align */
308                 case V2D_COMMONVIEW_PANELS_UI:
309                 {
310                         
311                         /* for now, aspect ratio should be maintained, and zoom is clamped within sane default limits */
312                         v2d->keepzoom = (V2D_KEEPASPECT | V2D_LIMITZOOM | V2D_KEEPZOOM);
313                         v2d->minzoom = 0.5f;
314                         v2d->maxzoom = 2.0f;
315                         
316                         v2d->align = (V2D_ALIGN_NO_NEG_X | V2D_ALIGN_NO_POS_Y);
317                         v2d->keeptot = V2D_KEEPTOT_BOUNDS;
318                         
319                         /* note, scroll is being flipped in ED_region_panels() drawing */
320                         v2d->scroll |= (V2D_SCROLL_HORIZONTAL_HIDE | V2D_SCROLL_VERTICAL_HIDE);
321
322                         /* initialize without scroll bars (interferes with zoom level see: T47047) */
323                         if (do_init) {
324                                 v2d->scroll |= (V2D_SCROLL_VERTICAL_FULLR | V2D_SCROLL_HORIZONTAL_FULLR);
325                         }
326
327                         if (do_init) {
328                                 float panelzoom = (style) ? style->panelzoom : 1.0f;
329                                 
330                                 v2d->tot.xmin = 0.0f;
331                                 v2d->tot.xmax = winx;
332                                 
333                                 v2d->tot.ymax = 0.0f;
334                                 v2d->tot.ymin = -winy;
335                                 
336                                 v2d->cur.xmin = 0.0f;
337                                 v2d->cur.xmax = (winx) * panelzoom;
338                                 
339                                 v2d->cur.ymax = 0.0f;
340                                 v2d->cur.ymin = (-winy) * panelzoom;
341                         }
342                         break;
343                 }
344                 /* other view types are completely defined using their own settings already */
345                 default:
346                         /* we don't do anything here, as settings should be fine, but just make sure that rect */
347                         break;
348         }
349         
350         /* set initialized flag so that View2D doesn't get reinitialised next time again */
351         v2d->flag |= V2D_IS_INITIALISED;
352
353         /* store view size */
354         v2d->winx = winx;
355         v2d->winy = winy;
356         
357         /* set masks (always do), but leave scroller scheck to totrect_set */
358         view2d_masks(v2d, 0);
359         
360         /* set 'tot' rect before setting cur? */
361         /* XXX confusing stuff here still - I made this function not check scroller hide - that happens in totrect_set */
362         if (tot_changed)
363                 UI_view2d_totRect_set_resize(v2d, winx, winy, !do_init);
364         else
365                 ui_view2d_curRect_validate_resize(v2d, !do_init, 0);
366         
367 }
368
369 /**
370  * Ensure View2D rects remain in a viable configuration
371  * 'cur' is not allowed to be: larger than max, smaller than min, or outside of 'tot'
372  */
373 // XXX pre2.5 -> this used to be called  test_view2d()
374 static void ui_view2d_curRect_validate_resize(View2D *v2d, bool resize, bool mask_scrollers)
375 {
376         float totwidth, totheight, curwidth, curheight, width, height;
377         float winx, winy;
378         rctf *cur, *tot;
379         
380         /* use mask as size of region that View2D resides in, as it takes into account
381          * scrollbars already - keep in sync with zoomx/zoomy in view_zoomstep_apply_ex! */
382         winx = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
383         winy = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
384         
385         /* get pointers to rcts for less typing */
386         cur = &v2d->cur;
387         tot = &v2d->tot;
388         
389         /* we must satisfy the following constraints (in decreasing order of importance):
390          *      - alignment restrictions are respected
391          *      - cur must not fall outside of tot
392          *      - axis locks (zoom and offset) must be maintained
393          *      - zoom must not be excessive (check either sizes or zoom values)
394          *      - aspect ratio should be respected (NOTE: this is quite closely related to zoom too)
395          */
396         
397         /* Step 1: if keepzoom, adjust the sizes of the rects only
398          *      - firstly, we calculate the sizes of the rects
399          *      - curwidth and curheight are saved as reference... modify width and height values here
400          */
401         totwidth  = BLI_rctf_size_x(tot);
402         totheight = BLI_rctf_size_y(tot);
403         /* keep in sync with zoomx/zoomy in view_zoomstep_apply_ex! */
404         curwidth  = width  = BLI_rctf_size_x(cur);
405         curheight = height = BLI_rctf_size_y(cur);
406         
407         /* if zoom is locked, size on the appropriate axis is reset to mask size */
408         if (v2d->keepzoom & V2D_LOCKZOOM_X)
409                 width = winx;
410         if (v2d->keepzoom & V2D_LOCKZOOM_Y)
411                 height = winy;
412                 
413         /* values used to divide, so make it safe 
414          * NOTE: width and height must use FLT_MIN instead of 1, otherwise it is impossible to
415          *       get enough resolution in Graph Editor for editing some curves
416          */
417         if (width < FLT_MIN) width = 1;
418         if (height < FLT_MIN) height = 1;
419         if (winx < 1) winx = 1;
420         if (winy < 1) winy = 1;
421         
422         /* V2D_LIMITZOOM indicates that zoom level should be preserved when the window size changes */
423         if (resize && (v2d->keepzoom & V2D_KEEPZOOM)) {
424                 float zoom, oldzoom;
425
426                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0) {
427                         zoom = winx / width;
428                         oldzoom = v2d->oldwinx / curwidth;
429
430                         if (oldzoom != zoom)
431                                 width *= zoom / oldzoom;
432                 }
433
434                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0) {
435                         zoom = winy / height;
436                         oldzoom = v2d->oldwiny / curheight;
437
438                         if (oldzoom != zoom)
439                                 height *= zoom / oldzoom;
440                 }
441         }
442         /* keepzoom (V2D_LIMITZOOM set), indicates that zoom level on each axis must not exceed limits 
443          * NOTE: in general, it is not expected that the lock-zoom will be used in conjunction with this
444          */
445         else if (v2d->keepzoom & V2D_LIMITZOOM) {
446                 
447                 /* check if excessive zoom on x-axis */
448                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0) {
449                         const float zoom = winx / width;
450                         if (zoom < v2d->minzoom) {
451                                 width = winx / v2d->minzoom;
452                         }
453                         else if (zoom > v2d->maxzoom) {
454                                 width = winx / v2d->maxzoom;
455                         }
456                 }
457                 
458                 /* check if excessive zoom on y-axis */
459                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0) {
460                         const float zoom = winy / height;
461                         if (zoom < v2d->minzoom) {
462                                 height = winy / v2d->minzoom;
463                         }
464                         else if (zoom > v2d->maxzoom) {
465                                 height = winy / v2d->maxzoom;
466                         }
467                 }
468         }
469         else {
470                 /* make sure sizes don't exceed that of the min/max sizes (even though we're not doing zoom clamping) */
471                 CLAMP(width, v2d->min[0], v2d->max[0]);
472                 CLAMP(height, v2d->min[1], v2d->max[1]);
473         }
474         
475         /* check if we should restore aspect ratio (if view size changed) */
476         if (v2d->keepzoom & V2D_KEEPASPECT) {
477                 bool do_x = false, do_y = false, do_cur /* , do_win */ /* UNUSED */;
478                 float curRatio, winRatio;
479                 
480                 /* when a window edge changes, the aspect ratio can't be used to
481                  * find which is the best new 'cur' rect. thats why it stores 'old' 
482                  */
483                 if (winx != v2d->oldwinx) do_x = true;
484                 if (winy != v2d->oldwiny) do_y = true;
485                 
486                 curRatio = height / width;
487                 winRatio = winy / winx;
488                 
489                 /* both sizes change (area/region maximized)  */
490                 if (do_x == do_y) {
491                         if (do_x && do_y) {
492                                 /* here is 1,1 case, so all others must be 0,0 */
493                                 if (fabsf(winx - v2d->oldwinx) > fabsf(winy - v2d->oldwiny)) do_y = false;
494                                 else do_x = false;
495                         }
496                         else if (winRatio > curRatio) {
497                                 do_x = false;
498                         }
499                         else {
500                                 do_x = true;
501                         }
502                 }
503                 do_cur = do_x;
504                 /* do_win = do_y; */ /* UNUSED */
505                 
506                 if (do_cur) {
507                         if ((v2d->keeptot == V2D_KEEPTOT_STRICT) && (winx != v2d->oldwinx)) {
508                                 /* special exception for Outliner (and later channel-lists):
509                                  *  - The view may be moved left to avoid contents being pushed out of view when view shrinks.
510                                  *      - The keeptot code will make sure cur->xmin will not be less than tot->xmin (which cannot be allowed)
511                                  *      - width is not adjusted for changed ratios here...
512                                  */
513                                 if (winx < v2d->oldwinx) {
514                                         float temp = v2d->oldwinx - winx;
515                                         
516                                         cur->xmin -= temp;
517                                         cur->xmax -= temp;
518                                         
519                                         /* width does not get modified, as keepaspect here is just set to make 
520                                          * sure visible area adjusts to changing view shape! 
521                                          */
522                                 }
523                         }
524                         else {
525                                 /* portrait window: correct for x */
526                                 width = height / winRatio;
527                         }
528                 }
529                 else {
530                         if ((v2d->keeptot == V2D_KEEPTOT_STRICT) && (winy != v2d->oldwiny)) {
531                                 /* special exception for Outliner (and later channel-lists):
532                                  *      - Currently, no actions need to be taken here...
533                                  */
534
535                                 if (winy < v2d->oldwiny) {
536                                         float temp = v2d->oldwiny - winy;
537                                         
538                                         if (v2d->align & V2D_ALIGN_NO_NEG_Y) {
539                                                 cur->ymin -= temp;
540                                                 cur->ymax -= temp;
541                                         }
542                                         else { /* Assume V2D_ALIGN_NO_POS_Y or combination */
543                                                 cur->ymin += temp;
544                                                 cur->ymax += temp;
545                                         }
546                                 }
547
548                         }
549                         else {
550                                 /* landscape window: correct for y */
551                                 height = width * winRatio;
552                         }
553                 }
554                 
555                 /* store region size for next time */
556                 v2d->oldwinx = (short)winx;
557                 v2d->oldwiny = (short)winy;
558         }
559         
560         /* Step 2: apply new sizes to cur rect, but need to take into account alignment settings here... */
561         if ((width != curwidth) || (height != curheight)) {
562                 float temp, dh;
563                 
564                 /* resize from centerpoint, unless otherwise specified */
565                 if (width != curwidth) {
566                         if (v2d->keepofs & V2D_LOCKOFS_X) {
567                                 cur->xmax += width - BLI_rctf_size_x(cur);
568                         }
569                         else if (v2d->keepofs & V2D_KEEPOFS_X) {
570                                 if (v2d->align & V2D_ALIGN_NO_POS_X)
571                                         cur->xmin -= width - BLI_rctf_size_x(cur);
572                                 else
573                                         cur->xmax += width - BLI_rctf_size_x(cur);
574                         }
575                         else {
576                                 temp = BLI_rctf_cent_x(cur);
577                                 dh = width * 0.5f;
578                                 
579                                 cur->xmin = temp - dh;
580                                 cur->xmax = temp + dh;
581                         }
582                 }
583                 if (height != curheight) {
584                         if (v2d->keepofs & V2D_LOCKOFS_Y) {
585                                 cur->ymax += height - BLI_rctf_size_y(cur);
586                         }
587                         else if (v2d->keepofs & V2D_KEEPOFS_Y) {
588                                 if (v2d->align & V2D_ALIGN_NO_POS_Y)
589                                         cur->ymin -= height - BLI_rctf_size_y(cur);
590                                 else
591                                         cur->ymax += height - BLI_rctf_size_y(cur);
592                         }
593                         else {
594                                 temp = BLI_rctf_cent_y(cur);
595                                 dh = height * 0.5f;
596                                 
597                                 cur->ymin = temp - dh;
598                                 cur->ymax = temp + dh;
599                         }
600                 }
601         }
602         
603         /* Step 3: adjust so that it doesn't fall outside of bounds of 'tot' */
604         if (v2d->keeptot) {
605                 float temp, diff;
606                 
607                 /* recalculate extents of cur */
608                 curwidth  = BLI_rctf_size_x(cur);
609                 curheight = BLI_rctf_size_y(cur);
610                 
611                 /* width */
612                 if ((curwidth > totwidth) && !(v2d->keepzoom & (V2D_KEEPZOOM | V2D_LOCKZOOM_X | V2D_LIMITZOOM))) {
613                         /* if zoom doesn't have to be maintained, just clamp edges */
614                         if (cur->xmin < tot->xmin) cur->xmin = tot->xmin;
615                         if (cur->xmax > tot->xmax) cur->xmax = tot->xmax;
616                 }
617                 else if (v2d->keeptot == V2D_KEEPTOT_STRICT) {
618                         /* This is an exception for the outliner (and later channel-lists, headers) 
619                          *      - must clamp within tot rect (absolutely no excuses)
620                          *      --> therefore, cur->xmin must not be less than tot->xmin
621                          */
622                         if (cur->xmin < tot->xmin) {
623                                 /* move cur across so that it sits at minimum of tot */
624                                 temp = tot->xmin - cur->xmin;
625                                 
626                                 cur->xmin += temp;
627                                 cur->xmax += temp;
628                         }
629                         else if (cur->xmax > tot->xmax) {
630                                 /* - only offset by difference of cur-xmax and tot-xmax if that would not move 
631                                  *  cur-xmin to lie past tot-xmin
632                                  * - otherwise, simply shift to tot-xmin???
633                                  */
634                                 temp = cur->xmax - tot->xmax;
635                                 
636                                 if ((cur->xmin - temp) < tot->xmin) {
637                                         /* only offset by difference from cur-min and tot-min */
638                                         temp = cur->xmin - tot->xmin;
639                                         
640                                         cur->xmin -= temp;
641                                         cur->xmax -= temp;
642                                 }
643                                 else {
644                                         cur->xmin -= temp;
645                                         cur->xmax -= temp;
646                                 }
647                         }
648                 }
649                 else {
650                         /* This here occurs when:
651                          *  - width too big, but maintaining zoom (i.e. widths cannot be changed)
652                          *      - width is OK, but need to check if outside of boundaries
653                          * 
654                          * So, resolution is to just shift view by the gap between the extremities.
655                          * We favour moving the 'minimum' across, as that's origin for most things
656                          * (XXX - in the past, max was favored... if there are bugs, swap!)
657                          */
658                         if ((cur->xmin < tot->xmin) && (cur->xmax > tot->xmax)) {
659                                 /* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
660                                 temp = BLI_rctf_cent_x(tot);
661                                 diff = curwidth * 0.5f;
662                                 
663                                 cur->xmin = temp - diff;
664                                 cur->xmax = temp + diff;
665                         }
666                         else if (cur->xmin < tot->xmin) {
667                                 /* move cur across so that it sits at minimum of tot */
668                                 temp = tot->xmin - cur->xmin;
669                                 
670                                 cur->xmin += temp;
671                                 cur->xmax += temp;
672                         }
673                         else if (cur->xmax > tot->xmax) {
674                                 /* - only offset by difference of cur-xmax and tot-xmax if that would not move 
675                                  *  cur-xmin to lie past tot-xmin
676                                  * - otherwise, simply shift to tot-xmin???
677                                  */
678                                 temp = cur->xmax - tot->xmax;
679                                 
680                                 if ((cur->xmin - temp) < tot->xmin) {
681                                         /* only offset by difference from cur-min and tot-min */
682                                         temp = cur->xmin - tot->xmin;
683                                         
684                                         cur->xmin -= temp;
685                                         cur->xmax -= temp;
686                                 }
687                                 else {
688                                         cur->xmin -= temp;
689                                         cur->xmax -= temp;
690                                 }
691                         }
692                 }
693                 
694                 /* height */
695                 if ((curheight > totheight) && !(v2d->keepzoom & (V2D_KEEPZOOM | V2D_LOCKZOOM_Y | V2D_LIMITZOOM))) {
696                         /* if zoom doesn't have to be maintained, just clamp edges */
697                         if (cur->ymin < tot->ymin) cur->ymin = tot->ymin;
698                         if (cur->ymax > tot->ymax) cur->ymax = tot->ymax;
699                 }
700                 else {
701                         /* This here occurs when:
702                          *  - height too big, but maintaining zoom (i.e. heights cannot be changed)
703                          *      - height is OK, but need to check if outside of boundaries
704                          * 
705                          * So, resolution is to just shift view by the gap between the extremities.
706                          * We favour moving the 'minimum' across, as that's origin for most things
707                          */
708                         if ((cur->ymin < tot->ymin) && (cur->ymax > tot->ymax)) {
709                                 /* outside boundaries on both sides, so take middle-point of tot, and place in balanced way */
710                                 temp = BLI_rctf_cent_y(tot);
711                                 diff = curheight * 0.5f;
712                                 
713                                 cur->ymin = temp - diff;
714                                 cur->ymax = temp + diff;
715                         }
716                         else if (cur->ymin < tot->ymin) {
717                                 /* there's still space remaining, so shift up */
718                                 temp = tot->ymin - cur->ymin;
719                                 
720                                 cur->ymin += temp;
721                                 cur->ymax += temp;
722                         }
723                         else if (cur->ymax > tot->ymax) {
724                                 /* there's still space remaining, so shift down */
725                                 temp = cur->ymax - tot->ymax;
726                                 
727                                 cur->ymin -= temp;
728                                 cur->ymax -= temp;
729                         }
730                 }
731         }
732         
733         /* Step 4: Make sure alignment restrictions are respected */
734         if (v2d->align) {
735                 /* If alignment flags are set (but keeptot is not), they must still be respected, as although
736                  * they don't specify any particular bounds to stay within, they do define ranges which are 
737                  * invalid.
738                  *
739                  * Here, we only check to make sure that on each axis, the 'cur' rect doesn't stray into these 
740                  * invalid zones, otherwise we offset.
741                  */
742                 
743                 /* handle width - posx and negx flags are mutually exclusive, so watch out */
744                 if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
745                         /* width is in negative-x half */
746                         if (v2d->cur.xmax > 0) {
747                                 v2d->cur.xmin -= v2d->cur.xmax;
748                                 v2d->cur.xmax = 0.0f;
749                         }
750                 }
751                 else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
752                         /* width is in positive-x half */
753                         if (v2d->cur.xmin < 0) {
754                                 v2d->cur.xmax -= v2d->cur.xmin;
755                                 v2d->cur.xmin = 0.0f;
756                         }
757                 }
758                 
759                 /* handle height - posx and negx flags are mutually exclusive, so watch out */
760                 if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
761                         /* height is in negative-y half */
762                         if (v2d->cur.ymax > 0) {
763                                 v2d->cur.ymin -= v2d->cur.ymax;
764                                 v2d->cur.ymax = 0.0f;
765                         }
766                 }
767                 else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
768                         /* height is in positive-y half */
769                         if (v2d->cur.ymin < 0) {
770                                 v2d->cur.ymax -= v2d->cur.ymin;
771                                 v2d->cur.ymin = 0.0f;
772                         }
773                 }
774         }
775         
776         /* set masks */
777         view2d_masks(v2d, mask_scrollers);
778 }
779
780 void UI_view2d_curRect_validate(View2D *v2d)
781 {
782         ui_view2d_curRect_validate_resize(v2d, 0, 1);
783 }
784
785 /* ------------------ */
786
787 /* Called by menus to activate it, or by view2d operators to make sure 'related' views stay in synchrony */
788 void UI_view2d_sync(bScreen *screen, ScrArea *area, View2D *v2dcur, int flag)
789 {
790         ScrArea *sa;
791         ARegion *ar;
792         
793         /* don't continue if no view syncing to be done */
794         if ((v2dcur->flag & (V2D_VIEWSYNC_SCREEN_TIME | V2D_VIEWSYNC_AREA_VERTICAL)) == 0)
795                 return;
796                 
797         /* check if doing within area syncing (i.e. channels/vertical) */
798         if ((v2dcur->flag & V2D_VIEWSYNC_AREA_VERTICAL) && (area)) {
799                 for (ar = area->regionbase.first; ar; ar = ar->next) {
800                         /* don't operate on self */
801                         if (v2dcur != &ar->v2d) {
802                                 /* only if view has vertical locks enabled */
803                                 if (ar->v2d.flag & V2D_VIEWSYNC_AREA_VERTICAL) {
804                                         if (flag == V2D_LOCK_COPY) {
805                                                 /* other views with locks on must copy active */
806                                                 ar->v2d.cur.ymin = v2dcur->cur.ymin;
807                                                 ar->v2d.cur.ymax = v2dcur->cur.ymax;
808                                         }
809                                         else { /* V2D_LOCK_SET */
810                                                    /* active must copy others */
811                                                 v2dcur->cur.ymin = ar->v2d.cur.ymin;
812                                                 v2dcur->cur.ymax = ar->v2d.cur.ymax;
813                                         }
814                                         
815                                         /* region possibly changed, so refresh */
816                                         ED_region_tag_redraw(ar);
817                                 }
818                         }
819                 }
820         }
821         
822         /* check if doing whole screen syncing (i.e. time/horizontal) */
823         if ((v2dcur->flag & V2D_VIEWSYNC_SCREEN_TIME) && (screen)) {
824                 for (sa = screen->areabase.first; sa; sa = sa->next) {
825                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
826                                 /* don't operate on self */
827                                 if (v2dcur != &ar->v2d) {
828                                         /* only if view has horizontal locks enabled */
829                                         if (ar->v2d.flag & V2D_VIEWSYNC_SCREEN_TIME) {
830                                                 if (flag == V2D_LOCK_COPY) {
831                                                         /* other views with locks on must copy active */
832                                                         ar->v2d.cur.xmin = v2dcur->cur.xmin;
833                                                         ar->v2d.cur.xmax = v2dcur->cur.xmax;
834                                                 }
835                                                 else { /* V2D_LOCK_SET */
836                                                            /* active must copy others */
837                                                         v2dcur->cur.xmin = ar->v2d.cur.xmin;
838                                                         v2dcur->cur.xmax = ar->v2d.cur.xmax;
839                                                 }
840                                                 
841                                                 /* region possibly changed, so refresh */
842                                                 ED_region_tag_redraw(ar);
843                                         }
844                                 }
845                         }
846                 }
847         }
848 }
849
850
851 /**
852  * Restore 'cur' rect to standard orientation (i.e. optimal maximum view of tot)
853  * This does not take into account if zooming the view on an axis will improve the view (if allowed)
854  */
855 void UI_view2d_curRect_reset(View2D *v2d)
856 {
857         float width, height;
858         
859         /* assume width and height of 'cur' rect by default, should be same size as mask */
860         width  = (float)(BLI_rcti_size_x(&v2d->mask) + 1);
861         height = (float)(BLI_rcti_size_y(&v2d->mask) + 1);
862         
863         /* handle width - posx and negx flags are mutually exclusive, so watch out */
864         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
865                 /* width is in negative-x half */
866                 v2d->cur.xmin = -width;
867                 v2d->cur.xmax = 0.0f;
868         }
869         else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
870                 /* width is in positive-x half */
871                 v2d->cur.xmin = 0.0f;
872                 v2d->cur.xmax = width;
873         }
874         else {
875                 /* width is centered around (x == 0) */
876                 const float dx = width / 2.0f;
877                 
878                 v2d->cur.xmin = -dx;
879                 v2d->cur.xmax = dx;
880         }
881         
882         /* handle height - posx and negx flags are mutually exclusive, so watch out */
883         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
884                 /* height is in negative-y half */
885                 v2d->cur.ymin = -height;
886                 v2d->cur.ymax = 0.0f;
887         }
888         else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
889                 /* height is in positive-y half */
890                 v2d->cur.ymin = 0.0f;
891                 v2d->cur.ymax = height;
892         }
893         else {
894                 /* height is centered around (y == 0) */
895                 const float dy = height / 2.0f;
896                 
897                 v2d->cur.ymin = -dy;
898                 v2d->cur.ymax = dy;
899         }
900 }
901
902 /* ------------------ */
903
904 /* Change the size of the maximum viewable area (i.e. 'tot' rect) */
905 void UI_view2d_totRect_set_resize(View2D *v2d, int width, int height, bool resize)
906 {
907 //      int scroll = view2d_scroll_mapped(v2d->scroll);
908         
909         /* don't do anything if either value is 0 */
910         width = abs(width);
911         height = abs(height);
912         
913         /* hrumf! */
914         /* XXX: there are work arounds for this in the panel and file browse code. */
915         /* round to int, because this is called with width + V2D_SCROLL_WIDTH */
916 //      if (scroll & V2D_SCROLL_HORIZONTAL)
917 //              width -= (int)V2D_SCROLL_WIDTH;
918 //      if (scroll & V2D_SCROLL_VERTICAL)
919 //              height -= (int)V2D_SCROLL_HEIGHT;
920         
921         if (ELEM(0, width, height)) {
922                 if (G.debug & G_DEBUG)
923                         printf("Error: View2D totRect set exiting: v2d=%p width=%d height=%d\n", (void *)v2d, width, height);  // XXX temp debug info
924                 return;
925         }
926         
927         /* handle width - posx and negx flags are mutually exclusive, so watch out */
928         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
929                 /* width is in negative-x half */
930                 v2d->tot.xmin = (float)-width;
931                 v2d->tot.xmax = 0.0f;
932         }
933         else if ((v2d->align & V2D_ALIGN_NO_NEG_X) && !(v2d->align & V2D_ALIGN_NO_POS_X)) {
934                 /* width is in positive-x half */
935                 v2d->tot.xmin = 0.0f;
936                 v2d->tot.xmax = (float)width;
937         }
938         else {
939                 /* width is centered around (x == 0) */
940                 const float dx = (float)width / 2.0f;
941                 
942                 v2d->tot.xmin = -dx;
943                 v2d->tot.xmax = dx;
944         }
945         
946         /* handle height - posx and negx flags are mutually exclusive, so watch out */
947         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
948                 /* height is in negative-y half */
949                 v2d->tot.ymin = (float)-height;
950                 v2d->tot.ymax = 0.0f;
951         }
952         else if ((v2d->align & V2D_ALIGN_NO_NEG_Y) && !(v2d->align & V2D_ALIGN_NO_POS_Y)) {
953                 /* height is in positive-y half */
954                 v2d->tot.ymin = 0.0f;
955                 v2d->tot.ymax = (float)height;
956         }
957         else {
958                 /* height is centered around (y == 0) */
959                 const float dy = (float)height / 2.0f;
960                 
961                 v2d->tot.ymin = -dy;
962                 v2d->tot.ymax = dy;
963         }
964         
965         /* make sure that 'cur' rect is in a valid state as a result of these changes */
966         ui_view2d_curRect_validate_resize(v2d, resize, 1);
967         
968 }
969
970 void UI_view2d_totRect_set(View2D *v2d, int width, int height)
971 {
972         int scroll = view2d_scroll_mapped(v2d->scroll);
973
974         UI_view2d_totRect_set_resize(v2d, width, height, 0);
975         
976         /* solve bad recursion... if scroller state changed, mask is different, so you get different rects */
977         if (scroll != view2d_scroll_mapped(v2d->scroll)) {
978                 UI_view2d_totRect_set_resize(v2d, width, height, 0);
979         }
980         
981 }
982
983 bool UI_view2d_tab_set(View2D *v2d, int tab)
984 {
985         float default_offset[2] = {0.0f, 0.0f};
986         float *offset, *new_offset;
987         bool changed = false;
988
989         /* if tab changed, change offset */
990         if (tab != v2d->tab_cur && v2d->tab_offset) {
991                 if (tab < v2d->tab_num)
992                         offset = &v2d->tab_offset[tab * 2];
993                 else
994                         offset = default_offset;
995
996                 v2d->cur.xmax += offset[0] - v2d->cur.xmin;
997                 v2d->cur.xmin = offset[0];
998
999                 v2d->cur.ymin += offset[1] - v2d->cur.ymax;
1000                 v2d->cur.ymax = offset[1];
1001
1002                 /* validation should happen in subsequent totRect_set */
1003
1004                 changed = true;
1005         }
1006
1007         /* resize array if needed */
1008         if (tab >= v2d->tab_num) {
1009                 new_offset = MEM_callocN(sizeof(float) * (tab + 1) * 2, "view2d tab offset");
1010
1011                 if (v2d->tab_offset) {
1012                         memcpy(new_offset, v2d->tab_offset, sizeof(float) * v2d->tab_num * 2);
1013                         MEM_freeN(v2d->tab_offset);
1014                 }
1015
1016                 v2d->tab_offset = new_offset;
1017                 v2d->tab_num = tab + 1;
1018         }
1019
1020         /* set current tab and offset */
1021         v2d->tab_cur = tab;
1022         v2d->tab_offset[2 * tab + 0] = v2d->cur.xmin;
1023         v2d->tab_offset[2 * tab + 1] = v2d->cur.ymax;
1024
1025         return changed;
1026 }
1027
1028 void UI_view2d_zoom_cache_reset(void)
1029 {
1030         /* While scaling we can accumulate fonts at many sizes (~20 or so).
1031          * Not an issue with embedded font, but can use over 500Mb with i18n ones! See [#38244]. */
1032
1033         /* note: only some views draw text, we could check for this case to avoid clearning cache */
1034         BLF_cache_clear();
1035 }
1036
1037 /* *********************************************************************** */
1038 /* View Matrix Setup */
1039
1040 /* mapping function to ensure 'cur' draws extended over the area where sliders are */
1041 static void view2d_map_cur_using_mask(View2D *v2d, rctf *curmasked)
1042 {
1043         *curmasked = v2d->cur;
1044         
1045         if (view2d_scroll_mapped(v2d->scroll)) {
1046                 float sizex = BLI_rcti_size_x(&v2d->mask);
1047                 float sizey = BLI_rcti_size_y(&v2d->mask);
1048                 
1049                 /* prevent tiny or narrow regions to get invalid coordinates - mask can get negative even... */
1050                 if (sizex > 0.0f && sizey > 0.0f) {
1051                         float dx = BLI_rctf_size_x(&v2d->cur) / (sizex + 1);
1052                         float dy = BLI_rctf_size_y(&v2d->cur) / (sizey + 1);
1053                         
1054                         if (v2d->mask.xmin != 0)
1055                                 curmasked->xmin -= dx * (float)v2d->mask.xmin;
1056                         if (v2d->mask.xmax + 1 != v2d->winx)
1057                                 curmasked->xmax += dx * (float)(v2d->winx - v2d->mask.xmax - 1);
1058                         
1059                         if (v2d->mask.ymin != 0)
1060                                 curmasked->ymin -= dy * (float)v2d->mask.ymin;
1061                         if (v2d->mask.ymax + 1 != v2d->winy)
1062                                 curmasked->ymax += dy * (float)(v2d->winy - v2d->mask.ymax - 1);
1063                 }
1064         }
1065 }
1066
1067 /* Set view matrices to use 'cur' rect as viewing frame for View2D drawing */
1068 void UI_view2d_view_ortho(View2D *v2d)
1069 {
1070         rctf curmasked;
1071         const int sizex = BLI_rcti_size_x(&v2d->mask);
1072         const int sizey = BLI_rcti_size_y(&v2d->mask);
1073         const float eps = 0.001f;
1074         float xofs = 0.0f, yofs = 0.0f;
1075         
1076         /* pixel offsets (-GLA_PIXEL_OFS) are needed to get 1:1 correspondence with pixels for smooth UI drawing,
1077          * but only applied where requested
1078          */
1079         /* XXX brecht: instead of zero at least use a tiny offset, otherwise
1080          * pixel rounding is effectively random due to float inaccuracy */
1081         if (sizex > 0)
1082                 xofs = eps * BLI_rctf_size_x(&v2d->cur) / sizex;
1083         if (sizey > 0)
1084                 yofs = eps * BLI_rctf_size_y(&v2d->cur) / sizey;
1085         
1086         /* apply mask-based adjustments to cur rect (due to scrollers), to eliminate scaling artifacts */
1087         view2d_map_cur_using_mask(v2d, &curmasked);
1088
1089         BLI_rctf_translate(&curmasked, -xofs, -yofs);
1090         
1091         /* XXX ton: this flag set by outliner, for icons */
1092         if (v2d->flag & V2D_PIXELOFS_X) {
1093                 curmasked.xmin = floorf(curmasked.xmin) - (eps + xofs);
1094                 curmasked.xmax = floorf(curmasked.xmax) - (eps + xofs);
1095         }
1096         if (v2d->flag & V2D_PIXELOFS_Y) {
1097                 curmasked.ymin = floorf(curmasked.ymin) - (eps + yofs);
1098                 curmasked.ymax = floorf(curmasked.ymax) - (eps + yofs);
1099         }
1100         
1101         /* set matrix on all appropriate axes */
1102         wmOrtho2(curmasked.xmin, curmasked.xmax, curmasked.ymin, curmasked.ymax);
1103 }
1104
1105 /**
1106  * Set view matrices to only use one axis of 'cur' only
1107  *
1108  * \param xaxis: if non-zero, only use cur x-axis, otherwise use cur-yaxis (mostly this will be used for x)
1109  */
1110 void UI_view2d_view_orthoSpecial(ARegion *ar, View2D *v2d, const bool xaxis)
1111 {
1112         rctf curmasked;
1113         float xofs, yofs;
1114         
1115         /* pixel offsets (-GLA_PIXEL_OFS) are needed to get 1:1 correspondence with pixels for smooth UI drawing,
1116          * but only applied where requested
1117          */
1118         /* XXX temp (ton) */
1119         xofs = 0.0f; // (v2d->flag & V2D_PIXELOFS_X) ? GLA_PIXEL_OFS : 0.0f;
1120         yofs = 0.0f; // (v2d->flag & V2D_PIXELOFS_Y) ? GLA_PIXEL_OFS : 0.0f;
1121         
1122         /* apply mask-based adjustments to cur rect (due to scrollers), to eliminate scaling artifacts */
1123         view2d_map_cur_using_mask(v2d, &curmasked);
1124         
1125         /* only set matrix with 'cur' coordinates on relevant axes */
1126         if (xaxis)
1127                 wmOrtho2(curmasked.xmin - xofs, curmasked.xmax - xofs, -yofs, ar->winy - yofs);
1128         else
1129                 wmOrtho2(-xofs, ar->winx - xofs, curmasked.ymin - yofs, curmasked.ymax - yofs);
1130
1131
1132
1133 /* Restore view matrices after drawing */
1134 void UI_view2d_view_restore(const bContext *C)
1135 {
1136         ARegion *ar = CTX_wm_region(C);
1137         int width  = BLI_rcti_size_x(&ar->winrct) + 1;
1138         int height = BLI_rcti_size_y(&ar->winrct) + 1;
1139         
1140         wmOrtho2(0.0f, (float)width, 0.0f, (float)height);
1141         gpuLoadIdentity();
1142         
1143         //      ED_region_pixelspace(CTX_wm_region(C));
1144 }
1145
1146 /* *********************************************************************** */
1147 /* Gridlines */
1148
1149 /* View2DGrid is typedef'd in UI_view2d.h */
1150 struct View2DGrid {
1151         float dx, dy;           /* stepsize (in pixels) between gridlines */
1152         float startx, starty;   /* initial coordinates to start drawing grid from */
1153         int powerx, powery;     /* step as power of 10 */
1154 };
1155
1156 /* --------------- */
1157
1158 /* try to write step as a power of 10 */
1159 static void step_to_grid(float *step, int *power, int unit)
1160 {
1161         const float loga = (float)log10(*step);
1162         float rem;
1163         
1164         *power = (int)(loga);
1165         
1166         rem = loga - (*power);
1167         rem = (float)pow(10.0, rem);
1168         
1169         if (loga < 0.0f) {
1170                 if (rem < 0.2f) rem = 0.2f;
1171                 else if (rem < 0.5f) rem = 0.5f;
1172                 else rem = 1.0f;
1173                 
1174                 *step = rem * (float)pow(10.0, (*power));
1175                 
1176                 /* for frames, we want 1.0 frame intervals only */
1177                 if (unit == V2D_UNIT_FRAMES) {
1178                         rem = 1.0f;
1179                         *step = 2.0f; /* use 2 since there are grid lines drawn in between, this way to get 1 line per frane */
1180                 }
1181                 
1182                 /* prevents printing 1.0 2.0 3.0 etc */
1183                 if (rem == 1.0f) (*power)++;
1184         }
1185         else {
1186                 if (rem < 2.0f) rem = 2.0f;
1187                 else if (rem < 5.0f) rem = 5.0f;
1188                 else rem = 10.0f;
1189                 
1190                 *step = rem * (float)pow(10.0, (*power));
1191                 
1192                 (*power)++;
1193                 /* prevents printing 1.0, 2.0, 3.0, etc. */
1194                 if (rem == 10.0f) (*power)++;
1195         }
1196 }
1197
1198 /**
1199  * Initialize settings necessary for drawing gridlines in a 2d-view
1200  *
1201  * - Currently, will return pointer to View2DGrid struct that needs to
1202  *   be freed with UI_view2d_grid_free()
1203  * - Is used for scrollbar drawing too (for units drawing)
1204  * - Units + clamping args will be checked, to make sure they are valid values that can be used
1205  *   so it is very possible that we won't return grid at all!
1206  *
1207  * - xunits,yunits      = V2D_UNIT_*  grid steps in seconds or frames
1208  * - xclamp,yclamp      = V2D_CLAMP_* only show whole-number intervals
1209  * - winx                       = width of region we're drawing to, note: not used but keeping for completeness.
1210  * - winy                       = height of region we're drawing into
1211  */
1212 View2DGrid *UI_view2d_grid_calc(
1213         Scene *scene, View2D *v2d,
1214         short xunits, short xclamp, short yunits, short yclamp, int UNUSED(winx), int winy)
1215 {
1216
1217         View2DGrid *grid;
1218         float space, seconddiv;
1219         
1220         /* check that there are at least some workable args */
1221         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) && ELEM(V2D_ARG_DUMMY, yunits, yclamp))
1222                 return NULL;
1223         
1224         /* grid here is allocated... */
1225         grid = MEM_callocN(sizeof(View2DGrid), "View2DGrid");
1226         
1227         /* rule: gridstep is minimal GRIDSTEP pixels */
1228         if (xunits == V2D_UNIT_SECONDS) {
1229                 seconddiv = (float)(0.01 * FPS);
1230         }
1231         else {
1232                 seconddiv = 1.0f;
1233         }
1234         
1235         /* calculate x-axis grid scale (only if both args are valid) */
1236         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) == 0) {
1237                 space = BLI_rctf_size_x(&v2d->cur);
1238
1239                 if (space != 0.0f) {
1240                         const float pixels = (float)BLI_rcti_size_x(&v2d->mask);
1241                         if (pixels != 0.0f) {
1242                                 grid->dx = (U.v2d_min_gridsize * UI_DPI_FAC * space) / (seconddiv * pixels);
1243                                 step_to_grid(&grid->dx, &grid->powerx, xunits);
1244                                 grid->dx *= seconddiv;
1245                         }
1246                 }
1247                 
1248                 if (xclamp == V2D_GRID_CLAMP) {
1249                         CLAMP_MIN(grid->dx, 0.1f);
1250                         CLAMP_MIN(grid->powerx, 0);
1251                         grid->powerx -= 2;
1252                 }
1253         }
1254         
1255         /* calculate y-axis grid scale (only if both args are valid) */
1256         if (ELEM(V2D_ARG_DUMMY, yunits, yclamp) == 0) {
1257                 space = BLI_rctf_size_y(&v2d->cur);
1258                 if (space != 0.0f) {
1259                         const float pixels = (float)winy;
1260                         if (pixels != 0.0f) {
1261                                 grid->dy = U.v2d_min_gridsize * UI_DPI_FAC * space / pixels;
1262                                 step_to_grid(&grid->dy, &grid->powery, yunits);
1263                         }
1264                 }
1265
1266                 if (yclamp == V2D_GRID_CLAMP) {
1267                         CLAMP_MIN(grid->dy, 1.0f);
1268                         CLAMP_MIN(grid->powery, 1);
1269                 }
1270         }
1271         
1272         /* calculate start position */
1273         if (ELEM(V2D_ARG_DUMMY, xunits, xclamp) == 0) {
1274                 grid->startx = seconddiv * (v2d->cur.xmin / seconddiv - (float)fmod(v2d->cur.xmin / seconddiv, grid->dx / seconddiv));
1275                 if (v2d->cur.xmin < 0.0f) grid->startx -= grid->dx;
1276         }
1277         else
1278                 grid->startx = v2d->cur.xmin;
1279                 
1280         if (ELEM(V2D_ARG_DUMMY, yunits, yclamp) == 0) {
1281                 grid->starty = (v2d->cur.ymin - (float)fmod(v2d->cur.ymin, grid->dy));
1282                 if (v2d->cur.ymin < 0.0f) grid->starty -= grid->dy;
1283         }
1284         else
1285                 grid->starty = v2d->cur.ymin;
1286         
1287         return grid;
1288 }
1289
1290 /* Draw gridlines in the given 2d-region */
1291 void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
1292 {
1293         float vec1[2], vec2[2];
1294         int a, step;
1295         int vertical_minor_step = (BLI_rcti_size_x(&v2d->mask) + 1) / (U.v2d_min_gridsize * UI_DPI_FAC),
1296                 horizontal_major_step = (BLI_rcti_size_y(&v2d->mask) + 1) / (U.v2d_min_gridsize * UI_DPI_FAC);
1297         unsigned char grid_line_color[3];
1298         
1299         /* check for grid first, as it may not exist */
1300         if (grid == NULL)
1301                 return;
1302
1303         /* Count the needed vertices for the gridlines */
1304         unsigned vertex_count = 0;
1305         if (flag & V2D_VERTICAL_LINES) {
1306                 /* vertical lines */
1307                 vertex_count += 2 * vertical_minor_step;                /* minor gridlines */
1308                 vertex_count += 2 * (vertical_minor_step + 2);  /* major gridlines */
1309         }
1310         if (flag & V2D_HORIZONTAL_LINES) {
1311                 /* horizontal lines */
1312                 vertex_count += 2 * (horizontal_major_step + 1);        /* major gridlines */
1313
1314                 /* fine lines */
1315                 if (flag & V2D_HORIZONTAL_FINELINES)
1316                         vertex_count += 2 * (horizontal_major_step + 1);
1317         }
1318         /* axes */
1319         if (flag & V2D_HORIZONTAL_AXIS)
1320                 vertex_count += 2;
1321         if (flag & V2D_VERTICAL_AXIS)
1322                 vertex_count += 2;
1323
1324         /* If there is nothing to render, exit early */
1325         if (vertex_count == 0)
1326                 return;
1327
1328         Gwn_VertFormat *format = immVertexFormat();
1329         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1330         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1331
1332         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1333         immBegin(GWN_PRIM_LINES, vertex_count);
1334
1335         /* vertical lines */
1336         if (flag & V2D_VERTICAL_LINES) {
1337                 /* initialize initial settings */
1338                 vec1[0] = vec2[0] = grid->startx;
1339                 vec1[1] = grid->starty;
1340                 vec2[1] = v2d->cur.ymax;
1341                 
1342                 /* minor gridlines */
1343                 step = vertical_minor_step;
1344                 if (step != 0) {
1345                         UI_GetThemeColor3ubv(TH_GRID, grid_line_color);
1346         
1347                         for (a = 0; a < step; a++) {
1348                                 immSkipAttrib(color);
1349                                 immVertex2fv(pos, vec1);
1350                                 immAttrib3ubv(color, grid_line_color);
1351                                 immVertex2fv(pos, vec2);
1352                                 
1353                                 vec2[0] = vec1[0] += grid->dx;
1354                         }
1355                 }
1356                 
1357                 /* major gridlines */
1358                 vec2[0] = vec1[0] -= 0.5f * grid->dx;
1359
1360                 UI_GetThemeColorShade3ubv(TH_GRID, 16, grid_line_color);
1361                 
1362                 step++;
1363                 for (a = 0; a <= step; a++) {
1364                         immSkipAttrib(color);
1365                         immVertex2fv(pos, vec1);
1366                         immAttrib3ubv(color, grid_line_color);
1367                         immVertex2fv(pos, vec2);
1368                         
1369                         vec2[0] = vec1[0] -= grid->dx;
1370                 }
1371         }
1372         
1373         /* horizontal lines */
1374         if (flag & V2D_HORIZONTAL_LINES) {
1375                 /* only major gridlines */
1376                 vec1[1] = vec2[1] = grid->starty;
1377                 vec1[0] = grid->startx;
1378                 vec2[0] = v2d->cur.xmax;
1379                 
1380                 step = horizontal_major_step;
1381         
1382                 UI_GetThemeColor3ubv(TH_GRID, grid_line_color);
1383
1384                 for (a = 0; a <= step; a++) {
1385                         immSkipAttrib(color);
1386                         immVertex2fv(pos, vec1);
1387                         immAttrib3ubv(color, grid_line_color);
1388                         immVertex2fv(pos, vec2);
1389                         
1390                         vec2[1] = vec1[1] += grid->dy;
1391                 }
1392                 
1393                 /* fine grid lines */
1394                 vec2[1] = vec1[1] -= 0.5f * grid->dy;
1395                 step++;
1396                 
1397                 if (flag & V2D_HORIZONTAL_FINELINES) {
1398                         UI_GetThemeColorShade3ubv(TH_GRID, 16, grid_line_color);
1399                         for (a = 0; a < step; a++) {
1400                                 immSkipAttrib(color);
1401                                 immVertex2fv(pos, vec1);
1402                                 immAttrib3ubv(color, grid_line_color);
1403                                 immVertex2fv(pos, vec2);
1404                                 
1405                                 vec2[1] = vec1[1] -= grid->dy;
1406                         }
1407                 }
1408         }
1409         
1410         /* Axes are drawn as darker lines */
1411         UI_GetThemeColorShade3ubv(TH_GRID, -50, grid_line_color);
1412         
1413         /* horizontal axis */
1414         if (flag & V2D_HORIZONTAL_AXIS) {
1415                 vec1[0] = v2d->cur.xmin;
1416                 vec2[0] = v2d->cur.xmax;
1417                 vec1[1] = vec2[1] = 0.0f;
1418                 
1419                 immSkipAttrib(color);
1420                 immVertex2fv(pos, vec1);
1421                 immAttrib3ubv(color, grid_line_color);
1422                 immVertex2fv(pos, vec2);
1423         }
1424         
1425         /* vertical axis */
1426         if (flag & V2D_VERTICAL_AXIS) {
1427                 vec1[1] = v2d->cur.ymin;
1428                 vec2[1] = v2d->cur.ymax;
1429                 vec1[0] = vec2[0] = 0.0f;
1430                 
1431                 immSkipAttrib(color);
1432                 immVertex2fv(pos, vec1);
1433                 immAttrib3ubv(color, grid_line_color);
1434                 immVertex2fv(pos, vec2);
1435         }
1436
1437         immEnd();
1438         immUnbindProgram();
1439 }
1440
1441 /* Draw a constant grid in given 2d-region */
1442 void UI_view2d_constant_grid_draw(View2D *v2d)
1443 {
1444         float start_x, start_y, step = 25.0f;
1445         int count_x, count_y;
1446         
1447         start_x = v2d->cur.xmin;
1448         if (start_x < 0.0)
1449                 start_x += -(float)fmod(v2d->cur.xmin, step);
1450         else
1451                 start_x += (step - (float)fmod(v2d->cur.xmin, step));
1452
1453         if (start_x > v2d->cur.xmax)
1454                 count_x = 0;
1455         else
1456                 count_x = (v2d->cur.xmax - start_x) / step + 1;
1457
1458         start_y = v2d->cur.ymin;
1459         if (start_y < 0.0)
1460                 start_y += -(float)fmod(v2d->cur.ymin, step);
1461         else
1462                 start_y += (step - (float)fabs(fmod(v2d->cur.ymin, step)));
1463
1464         if (start_y > v2d->cur.ymax)
1465                 count_y = 0;
1466         else
1467                 count_y = (v2d->cur.ymax - start_y) / step + 1;
1468         
1469         if (count_x > 0 || count_y > 0) {
1470                 Gwn_VertFormat *format = immVertexFormat();
1471                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1472                 unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
1473                 float theme_color[3];
1474
1475                 UI_GetThemeColorShade3fv(TH_BACK, -10, theme_color);
1476                 
1477                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1478                 immBegin(GWN_PRIM_LINES, count_x * 2 + count_y * 2 + 4);
1479                 
1480                 immAttrib3fv(color, theme_color);
1481                 for (int i = 0; i < count_x ; start_x += step, i++) {
1482                         immVertex2f(pos, start_x, v2d->cur.ymin);
1483                         immVertex2f(pos, start_x, v2d->cur.ymax);
1484                 }
1485
1486                 for (int i = 0; i < count_y; start_y += step, i++) {
1487                         immVertex2f(pos, v2d->cur.xmin, start_y);
1488                         immVertex2f(pos, v2d->cur.xmax, start_y);
1489                 }
1490         
1491                 /* X and Y axis */
1492                 UI_GetThemeColorShade3fv(TH_BACK, -18, theme_color);
1493                 
1494                 immAttrib3fv(color, theme_color);
1495                 immVertex2f(pos, 0.0f, v2d->cur.ymin);
1496                 immVertex2f(pos, 0.0f, v2d->cur.ymax);
1497                 immVertex2f(pos, v2d->cur.xmin, 0.0f);
1498                 immVertex2f(pos, v2d->cur.xmax, 0.0f);
1499         
1500                 immEnd();
1501                 immUnbindProgram();
1502         }
1503 }
1504
1505 /* Draw a multi-level grid in given 2d-region */
1506 void UI_view2d_multi_grid_draw(View2D *v2d, int colorid, float step, int level_size, int totlevels)
1507 {
1508         /* Exit if there is nothing to draw */
1509         if (totlevels == 0)
1510                 return;
1511
1512         int offset = -10;
1513         float lstep = step;
1514         unsigned char grid_line_color[3];
1515
1516         /* Make an estimate of at least how many vertices will be needed */
1517         unsigned vertex_count = 4;
1518         vertex_count += 2 * ((int)((v2d->cur.xmax - v2d->cur.xmin) / lstep) + 1);
1519         vertex_count += 2 * ((int)((v2d->cur.ymax - v2d->cur.ymin) / lstep) + 1);
1520
1521         Gwn_VertFormat *format = immVertexFormat();
1522         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1523         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1524
1525         glLineWidth(1.0f);
1526
1527         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1528         immBeginAtMost(GWN_PRIM_LINES, vertex_count);
1529
1530         for (int level = 0; level < totlevels; ++level) {
1531                 UI_GetThemeColorShade3ubv(colorid, offset, grid_line_color);
1532                 
1533                 int i = (int)(v2d->cur.xmin / lstep);
1534                 if (v2d->cur.xmin > 0.0f)
1535                         i++;
1536                 float start = i * lstep;
1537                 
1538                 for (; start < v2d->cur.xmax; start += lstep, ++i) {
1539                         if (i == 0 || (level < totlevels - 1 && i % level_size == 0))
1540                                 continue;
1541
1542                         immSkipAttrib(color);
1543                         immVertex2f(pos, start, v2d->cur.ymin);
1544                         immAttrib3ubv(color, grid_line_color);
1545                         immVertex2f(pos, start, v2d->cur.ymax);
1546                 }
1547                 
1548                 i = (int)(v2d->cur.ymin / lstep);
1549                 if (v2d->cur.ymin > 0.0f)
1550                         i++;
1551                 start = i * lstep;
1552                 
1553                 for (; start < v2d->cur.ymax; start += lstep, ++i) {
1554                         if (i == 0 || (level < totlevels - 1 && i % level_size == 0))
1555                                 continue;
1556
1557                         immSkipAttrib(color);
1558                         immVertex2f(pos, v2d->cur.xmin, start);
1559                         immAttrib3ubv(color, grid_line_color);
1560                         immVertex2f(pos, v2d->cur.xmax, start);
1561                 }
1562                 
1563                 lstep *= level_size;
1564                 offset -= 6;
1565         }
1566
1567         /* X and Y axis */
1568         UI_GetThemeColorShade3ubv(colorid, -18 + ((totlevels - 1) * -6) , grid_line_color);
1569
1570         immSkipAttrib(color);
1571         immVertex2f(pos, 0.0f, v2d->cur.ymin);
1572         immAttrib3ubv(color, grid_line_color);
1573         immVertex2f(pos, 0.0f, v2d->cur.ymax);
1574
1575         immSkipAttrib(color);
1576         immVertex2f(pos, v2d->cur.xmin, 0.0f);
1577         immAttrib3ubv(color, grid_line_color);
1578         immVertex2f(pos, v2d->cur.xmax, 0.0f);
1579
1580         immEnd();
1581         immUnbindProgram();
1582 }
1583
1584 /* the price we pay for not exposting structs :( */
1585 void UI_view2d_grid_size(View2DGrid *grid, float *r_dx, float *r_dy)
1586 {
1587         *r_dx = grid->dx;
1588         *r_dy = grid->dy;
1589 }
1590
1591 /* free temporary memory used for drawing grid */
1592 void UI_view2d_grid_free(View2DGrid *grid)
1593 {
1594         /* only free if there's a grid */
1595         if (grid) {
1596                 MEM_freeN(grid);
1597         }
1598 }
1599
1600 /* *********************************************************************** */
1601 /* Scrollers */
1602
1603 /**
1604  * View2DScrollers is typedef'd in UI_view2d.h
1605  *
1606  * \warning The start of this struct must not change, as view2d_ops.c uses this too.
1607  * For now, we don't need to have a separate (internal) header for structs like this...
1608  */
1609 struct View2DScrollers {
1610         /* focus bubbles */
1611         int vert_min, vert_max; /* vertical scrollbar */
1612         int hor_min, hor_max;   /* horizontal scrollbar */
1613         
1614         rcti hor, vert;         /* exact size of slider backdrop */
1615         int horfull, vertfull;  /* set if sliders are full, we don't draw them */
1616         
1617         /* scales */
1618         View2DGrid *grid;       /* grid for coordinate drawing */
1619         short xunits, xclamp;   /* units and clamping options for x-axis */
1620         short yunits, yclamp;   /* units and clamping options for y-axis */
1621 };
1622
1623 /* Calculate relevant scroller properties */
1624 View2DScrollers *UI_view2d_scrollers_calc(
1625         const bContext *C, View2D *v2d,
1626         short xunits, short xclamp, short yunits, short yclamp)
1627 {
1628         View2DScrollers *scrollers;
1629         rcti vert, hor;
1630         float fac1, fac2, totsize, scrollsize;
1631         int scroll = view2d_scroll_mapped(v2d->scroll);
1632         int smaller;
1633         
1634         /* scrollers is allocated here... */
1635         scrollers = MEM_callocN(sizeof(View2DScrollers), "View2DScrollers");
1636         
1637         vert = v2d->vert;
1638         hor = v2d->hor;
1639         
1640         /* slider rects need to be smaller than region */
1641         smaller = (int)(0.2f * U.widget_unit);
1642         hor.xmin += smaller;
1643         hor.xmax -= smaller;
1644         if (scroll & V2D_SCROLL_BOTTOM)
1645                 hor.ymin += smaller;
1646         else
1647                 hor.ymax -= smaller;
1648         
1649         if (scroll & V2D_SCROLL_LEFT)
1650                 vert.xmin += smaller;
1651         else
1652                 vert.xmax -= smaller;
1653         vert.ymin += smaller;
1654         vert.ymax -= smaller;
1655         
1656         CLAMP(vert.ymin, vert.ymin, vert.ymax - V2D_SCROLLER_HANDLE_SIZE);
1657         CLAMP(hor.xmin, hor.xmin, hor.xmax - V2D_SCROLLER_HANDLE_SIZE);
1658         
1659         /* store in scrollers, used for drawing */
1660         scrollers->vert = vert;
1661         scrollers->hor = hor;
1662         
1663         /* scroller 'buttons':
1664          *      - These should always remain within the visible region of the scrollbar
1665          *      - They represent the region of 'tot' that is visible in 'cur'
1666          */
1667         
1668         /* horizontal scrollers */
1669         if (scroll & V2D_SCROLL_HORIZONTAL) {
1670                 /* scroller 'button' extents */
1671                 totsize = BLI_rctf_size_x(&v2d->tot);
1672                 scrollsize = (float)BLI_rcti_size_x(&hor);
1673                 if (totsize == 0.0f) totsize = 1.0f;  /* avoid divide by zero */
1674
1675                 fac1 = (v2d->cur.xmin - v2d->tot.xmin) / totsize;
1676                 if (fac1 <= 0.0f)
1677                         scrollers->hor_min = hor.xmin;
1678                 else
1679                         scrollers->hor_min = (int)(hor.xmin + (fac1 * scrollsize));
1680                 
1681                 fac2 = (v2d->cur.xmax - v2d->tot.xmin) / totsize;
1682                 if (fac2 >= 1.0f)
1683                         scrollers->hor_max = hor.xmax;
1684                 else
1685                         scrollers->hor_max = (int)(hor.xmin + (fac2 * scrollsize));
1686                 
1687                 /* prevent inverted sliders */
1688                 if (scrollers->hor_min > scrollers->hor_max) 
1689                         scrollers->hor_min = scrollers->hor_max;
1690                 /* prevent sliders from being too small, and disappearing */
1691                 if ((scrollers->hor_max - scrollers->hor_min) < V2D_SCROLLER_HANDLE_SIZE) {
1692                         scrollers->hor_max = scrollers->hor_min + V2D_SCROLLER_HANDLE_SIZE;
1693
1694                         CLAMP(scrollers->hor_max, hor.xmin + V2D_SCROLLER_HANDLE_SIZE, hor.xmax);
1695                         CLAMP(scrollers->hor_min, hor.xmin, hor.xmax - V2D_SCROLLER_HANDLE_SIZE);
1696                 }
1697                 
1698         }
1699         
1700         /* vertical scrollers */
1701         if (scroll & V2D_SCROLL_VERTICAL) {
1702                 /* scroller 'button' extents */
1703                 totsize    =        BLI_rctf_size_y(&v2d->tot);
1704                 scrollsize = (float)BLI_rcti_size_y(&vert);
1705                 if (totsize == 0.0f) totsize = 1.0f;  /* avoid divide by zero */
1706
1707                 fac1 = (v2d->cur.ymin - v2d->tot.ymin) / totsize;
1708                 if (fac1 <= 0.0f)
1709                         scrollers->vert_min = vert.ymin;
1710                 else
1711                         scrollers->vert_min = (int)(vert.ymin + (fac1 * scrollsize));
1712                 
1713                 fac2 = (v2d->cur.ymax - v2d->tot.ymin) / totsize;
1714                 if (fac2 >= 1.0f)
1715                         scrollers->vert_max = vert.ymax;
1716                 else
1717                         scrollers->vert_max = (int)(vert.ymin + (fac2 * scrollsize));
1718                 
1719                 /* prevent inverted sliders */
1720                 if (scrollers->vert_min > scrollers->vert_max) 
1721                         scrollers->vert_min = scrollers->vert_max;
1722                 /* prevent sliders from being too small, and disappearing */
1723                 if ((scrollers->vert_max - scrollers->vert_min) < V2D_SCROLLER_HANDLE_SIZE) {
1724                         
1725                         scrollers->vert_max = scrollers->vert_min + V2D_SCROLLER_HANDLE_SIZE;
1726                         
1727                         CLAMP(scrollers->vert_max, vert.ymin + V2D_SCROLLER_HANDLE_SIZE, vert.ymax);
1728                         CLAMP(scrollers->vert_min, vert.ymin, vert.ymax - V2D_SCROLLER_HANDLE_SIZE);
1729                 }
1730
1731         }
1732         
1733         /* grid markings on scrollbars */
1734         if (scroll & (V2D_SCROLL_SCALE_HORIZONTAL | V2D_SCROLL_SCALE_VERTICAL)) {
1735                 /* store clamping */
1736                 scrollers->xclamp = xclamp;
1737                 scrollers->xunits = xunits;
1738                 scrollers->yclamp = yclamp;
1739                 scrollers->yunits = yunits;
1740                 
1741                 scrollers->grid = UI_view2d_grid_calc(CTX_data_scene(C), v2d,
1742                                                       xunits, xclamp, yunits, yclamp,
1743                                                       BLI_rcti_size_x(&hor), BLI_rcti_size_y(&vert));
1744         }
1745         
1746         /* return scrollers */
1747         return scrollers;
1748 }
1749
1750 /* Print scale marking along a time scrollbar */
1751 static void scroll_printstr(Scene *scene, float x, float y, float val, int power, short unit, char dir)
1752 {
1753         int len;
1754         char timecode_str[32];
1755         
1756         /* adjust the scale unit to work ok */
1757         if (dir == 'v') {
1758                 /* here we bump up the power by factor of 10, as 
1759                  * rotation values (hence 'degrees') are divided by 10 to 
1760                  * be able to show the curves at the same time
1761                  */
1762                 if (ELEM(unit, V2D_UNIT_DEGREES, V2D_UNIT_TIME)) {
1763                         power += 1;
1764                         val *= 10;
1765                 }
1766         }
1767         
1768         /* get string to print */
1769         if (unit == V2D_UNIT_SECONDS) {
1770                 /* not neces*/
1771                 BLI_timecode_string_from_time(timecode_str, sizeof(timecode_str), power, val, FPS, U.timecode_style);
1772         }
1773         else {
1774                 BLI_timecode_string_from_time_seconds(timecode_str, sizeof(timecode_str), power, val);
1775         }
1776         
1777         /* get length of string, and adjust printing location to fit it into the horizontal scrollbar */
1778         len = strlen(timecode_str);
1779         if (dir == 'h') {
1780                 /* seconds/timecode display has slightly longer strings... */
1781                 if (unit == V2D_UNIT_SECONDS)
1782                         x -= 3 * len;
1783                 else
1784                         x -= 4 * len;
1785         }
1786         
1787         /* Add degree sympbol to end of string for vertical scrollbar? */
1788         if ((dir == 'v') && (unit == V2D_UNIT_DEGREES)) {
1789                 timecode_str[len] = 186;
1790                 timecode_str[len + 1] = 0;
1791         }
1792         
1793         /* draw it */
1794         BLF_draw_default_ascii(x, y, 0.0f, timecode_str, sizeof(timecode_str));
1795 }
1796
1797 /* Draw scrollbars in the given 2d-region */
1798 void UI_view2d_scrollers_draw(const bContext *C, View2D *v2d, View2DScrollers *vs)
1799 {
1800         Scene *scene = CTX_data_scene(C);
1801         rcti vert, hor;
1802         int scroll = view2d_scroll_mapped(v2d->scroll);
1803         unsigned char scrollers_back_color[4];
1804
1805         /* Color for scrollbar backs */
1806         UI_GetThemeColor4ubv(TH_BACK, scrollers_back_color);
1807         
1808         /* make copies of rects for less typing */
1809         vert = vs->vert;
1810         hor = vs->hor;
1811         
1812         /* horizontal scrollbar */
1813         if (scroll & V2D_SCROLL_HORIZONTAL) {
1814                 bTheme *btheme = UI_GetTheme();
1815                 uiWidgetColors wcol = btheme->tui.wcol_scroll;
1816                 rcti slider;
1817                 int state;
1818                 
1819                 slider.xmin = vs->hor_min;
1820                 slider.xmax = vs->hor_max;
1821                 slider.ymin = hor.ymin;
1822                 slider.ymax = hor.ymax;
1823                 
1824                 state = (v2d->scroll_ui & V2D_SCROLL_H_ACTIVE) ? UI_SCROLL_PRESSED : 0;
1825                 
1826                 /* show zoom handles if:
1827                  *      - zooming on x-axis is allowed (no scroll otherwise)
1828                  *      - slider bubble is large enough (no overdraw confusion)
1829                  *      - scale is shown on the scroller 
1830                  *        (workaround to make sure that button windows don't show these, 
1831                  *              and only the time-grids with their zoomability can do so)
1832                  */
1833                 if ((v2d->keepzoom & V2D_LOCKZOOM_X) == 0 &&
1834                     (v2d->scroll & V2D_SCROLL_SCALE_HORIZONTAL) &&
1835                     (BLI_rcti_size_x(&slider) > V2D_SCROLLER_HANDLE_SIZE))
1836                 {
1837                         state |= UI_SCROLL_ARROWS;
1838                 }
1839                 
1840                 /* clean rect behind slider, but not with transparent background */
1841                 if (scrollers_back_color[3] == 255) {
1842                         Gwn_VertFormat *format = immVertexFormat();
1843                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
1844
1845                         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1846
1847                         immUniformColor3ubv(scrollers_back_color);
1848                         immRecti(pos, v2d->hor.xmin, v2d->hor.ymin, v2d->hor.xmax, v2d->hor.ymax);
1849
1850                         immUnbindProgram();
1851                 }
1852                 
1853                 UI_draw_widget_scroll(&wcol, &hor, &slider, state);
1854                 
1855                 /* scale indicators */
1856                 if ((scroll & V2D_SCROLL_SCALE_HORIZONTAL) && (vs->grid)) {
1857                         const int font_id = BLF_default();
1858                         View2DGrid *grid = vs->grid;
1859                         float fac, dfac, fac2, val;
1860                         
1861                         /* the numbers: convert grid->startx and -dx to scroll coordinates 
1862                          *      - fac is x-coordinate to draw to
1863                          *      - dfac is gap between scale markings
1864                          */
1865                         fac = (grid->startx - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
1866                         fac = (float)hor.xmin + fac * BLI_rcti_size_x(&hor);
1867                         
1868                         dfac = grid->dx / BLI_rctf_size_x(&v2d->cur);
1869                         dfac = dfac * BLI_rcti_size_x(&hor);
1870                         
1871                         /* set starting value, and text color */
1872                         UI_FontThemeColor(font_id, TH_TEXT);
1873                         val = grid->startx;
1874                         
1875                         /* if we're clamping to whole numbers only, make sure entries won't be repeated */
1876                         if (vs->xclamp == V2D_GRID_CLAMP) {
1877                                 while (grid->dx < 0.9999f) {
1878                                         grid->dx *= 2.0f;
1879                                         dfac *= 2.0f;
1880                                 }
1881                         }
1882                         if (vs->xunits == V2D_UNIT_FRAMES)
1883                                 grid->powerx = 1;
1884
1885                         /* draw numbers in the appropriate range */
1886                         if (dfac > 0.0f) {
1887                                 float h = 0.1f * UI_UNIT_Y + (float)(hor.ymin);
1888                                 
1889                                 for (; fac < hor.xmax - 0.5f * U.widget_unit; fac += dfac, val += grid->dx) {
1890                                         
1891                                         /* make prints look nicer for scrollers */
1892                                         if (fac < hor.xmin + 0.5f * U.widget_unit)
1893                                                 continue;
1894                                         
1895                                         switch (vs->xunits) {
1896                                                 case V2D_UNIT_FRAMES:       /* frames (as whole numbers)*/
1897                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_FRAMES, 'h');
1898                                                         break;
1899                                                         
1900                                                 case V2D_UNIT_FRAMESCALE:   /* frames (not always as whole numbers) */
1901                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_FRAMESCALE, 'h');
1902                                                         break;
1903                                                 
1904                                                 case V2D_UNIT_SECONDS:      /* seconds */
1905                                                         fac2 = val / (float)FPS;
1906                                                         scroll_printstr(scene, fac, h, fac2, grid->powerx, V2D_UNIT_SECONDS, 'h');
1907                                                         break;
1908                                                         
1909                                                 case V2D_UNIT_DEGREES:      /* Graph Editor for rotation Drivers */
1910                                                         /* HACK: although we're drawing horizontal, we make this draw as 'vertical', just to get degree signs */
1911                                                         scroll_printstr(scene, fac, h, val, grid->powerx, V2D_UNIT_DEGREES, 'v');
1912                                                         break;
1913                                         }
1914                                 }
1915                         }
1916                 }
1917         }
1918         
1919         /* vertical scrollbar */
1920         if (scroll & V2D_SCROLL_VERTICAL) {
1921                 bTheme *btheme = UI_GetTheme();
1922                 uiWidgetColors wcol = btheme->tui.wcol_scroll;
1923                 rcti slider;
1924                 int state;
1925                 
1926                 slider.xmin = vert.xmin;
1927                 slider.xmax = vert.xmax;
1928                 slider.ymin = vs->vert_min;
1929                 slider.ymax = vs->vert_max;
1930                 
1931                 state = (v2d->scroll_ui & V2D_SCROLL_V_ACTIVE) ? UI_SCROLL_PRESSED : 0;
1932                 
1933                 /* show zoom handles if:
1934                  *      - zooming on y-axis is allowed (no scroll otherwise)
1935                  *      - slider bubble is large enough (no overdraw confusion)
1936                  *      - scale is shown on the scroller 
1937                  *        (workaround to make sure that button windows don't show these, 
1938                  *              and only the time-grids with their zoomability can do so)
1939                  */
1940                 if ((v2d->keepzoom & V2D_LOCKZOOM_Y) == 0 &&
1941                     (v2d->scroll & V2D_SCROLL_SCALE_VERTICAL) &&
1942                     (BLI_rcti_size_y(&slider) > V2D_SCROLLER_HANDLE_SIZE))
1943                 {
1944                         state |= UI_SCROLL_ARROWS;
1945                 }
1946                 
1947                 /* clean rect behind slider, but not with transparent background */
1948                 if (scrollers_back_color[3] == 255) {
1949                         Gwn_VertFormat *format = immVertexFormat();
1950                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
1951
1952                         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1953
1954                         immUniformColor3ubv(scrollers_back_color);
1955                         immRecti(pos, v2d->vert.xmin, v2d->vert.ymin, v2d->vert.xmax, v2d->vert.ymax);
1956
1957                         immUnbindProgram();
1958                 }
1959                 
1960                 UI_draw_widget_scroll(&wcol, &vert, &slider, state);
1961                 
1962                 
1963                 /* scale indiators */
1964                 if ((scroll & V2D_SCROLL_SCALE_VERTICAL) && (vs->grid)) {
1965                         View2DGrid *grid = vs->grid;
1966                         float fac, dfac, val;
1967                         
1968                         /* the numbers: convert grid->starty and dy to scroll coordinates 
1969                          *      - fac is y-coordinate to draw to
1970                          *      - dfac is gap between scale markings
1971                          *      - these involve a correction for horizontal scrollbar
1972                          *        NOTE: it's assumed that that scrollbar is there if this is involved!
1973                          */
1974                         fac = (grid->starty - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
1975                         fac = vert.ymin + fac * BLI_rcti_size_y(&vert);
1976                         
1977                         dfac = grid->dy / BLI_rctf_size_y(&v2d->cur);
1978                         dfac = dfac     * BLI_rcti_size_y(&vert);
1979                         
1980                         /* set starting value, and text color */
1981                         const int font_id = BLF_default();
1982                         UI_FontThemeColor(font_id, TH_TEXT);
1983                         val = grid->starty;
1984                         
1985                         /* if vertical clamping (to whole numbers) is used (i.e. in Sequencer), apply correction */
1986                         if (vs->yclamp == V2D_GRID_CLAMP)
1987                                 fac += 0.5f * dfac;
1988                                 
1989                         /* draw vertical steps */
1990                         if (dfac > 0.0f) {
1991                                 BLF_rotation(font_id, M_PI_2);
1992                                 BLF_enable(font_id, BLF_ROTATION);
1993
1994                                 for (; fac < vert.ymax - 10; fac += dfac, val += grid->dy) {
1995                                         
1996                                         /* make prints look nicer for scrollers */
1997                                         if (fac < vert.ymin + 10)
1998                                                 continue;
1999                                         
2000                                         scroll_printstr(scene, (float)(vert.xmax) - 2.0f, fac, val, grid->powery, vs->yunits, 'v');
2001                                 }
2002                                 
2003                                 BLF_disable(font_id, BLF_ROTATION);
2004                         }
2005                 }
2006         }
2007         
2008 }
2009
2010 /* free temporary memory used for drawing scrollers */
2011 void UI_view2d_scrollers_free(View2DScrollers *scrollers)
2012 {
2013         /* need to free grid as well... */
2014         if (scrollers->grid) {
2015                 MEM_freeN(scrollers->grid);
2016         }
2017         MEM_freeN(scrollers);
2018 }
2019
2020 /* *********************************************************************** */
2021 /* List View Utilities */
2022
2023 /** Get the view-coordinates of the nominated cell
2024  *
2025  * \param columnwidth, rowheight: size of each 'cell'
2026  * \param startx, starty: coordinates (in 'tot' rect space) that the list starts from.
2027  * This should be (0,0) for most views. However, for those where the starting row was offsetted
2028  * (like for Animation Editor channel lists, to make the first entry more visible), these will be
2029  * the min-coordinates of the first item.
2030  * \param column, row: The 2d-coordinates
2031  * (in 2D-view / 'tot' rect space) the cell exists at
2032  * \param rect:  coordinates of the cell
2033  * (passed as single var instead of 4 separate, as it's more useful this way)
2034  */
2035 void UI_view2d_listview_cell_to_view(
2036         View2D *v2d, float columnwidth, float rowheight,
2037         float startx, float starty,
2038         int column, int row, rctf *rect)
2039 {
2040         /* sanity checks */
2041         if (ELEM(NULL, v2d, rect)) {
2042                 return;
2043         }
2044
2045         if ((columnwidth <= 0) && (rowheight <= 0)) {
2046                 rect->xmin = rect->xmax = 0.0f;
2047                 rect->ymin = rect->ymax = 0.0f;
2048                 return;
2049         }
2050         
2051         /* x-coordinates */
2052         rect->xmin = startx + (float)(columnwidth * column);
2053         rect->xmax = startx + (float)(columnwidth * (column + 1));
2054         
2055         if ((v2d->align & V2D_ALIGN_NO_POS_X) && !(v2d->align & V2D_ALIGN_NO_NEG_X)) {
2056                 /* simply negate the values for the coordinates if in negative half */
2057                 rect->xmin = -rect->xmin;
2058                 rect->xmax = -rect->xmax;
2059         }
2060         
2061         /* y-coordinates */
2062         rect->ymin = starty + (float)(rowheight * row);
2063         rect->ymax = starty + (float)(rowheight * (row + 1));
2064         
2065         if ((v2d->align & V2D_ALIGN_NO_POS_Y) && !(v2d->align & V2D_ALIGN_NO_NEG_Y)) {
2066                 /* simply negate the values for the coordinates if in negative half */
2067                 rect->ymin = -rect->ymin;
2068                 rect->ymax = -rect->ymax;
2069         }
2070 }
2071
2072 /**
2073  * Get the 'cell' (row, column) that the given 2D-view coordinates (i.e. in 'tot' rect space) lie in.
2074  *
2075  * \param columnwidth, rowheight: size of each 'cell'
2076  * \param startx, starty: coordinates (in 'tot' rect space) that the list starts from.
2077  * This should be (0,0) for most views. However, for those where the starting row was offsetted
2078  * (like for Animation Editor channel lists, to make the first entry more visible), these will be
2079  * the min-coordinates of the first item.
2080  * \param viewx, viewy: 2D-coordinates (in 2D-view / 'tot' rect space) to get the cell for
2081  * \param column, row: the 'coordinates' of the relevant 'cell'
2082  */
2083 void UI_view2d_listview_view_to_cell(
2084         View2D *v2d, float columnwidth, float rowheight, float startx, float starty,
2085         float viewx, float viewy, int *column, int *row)
2086 {
2087         /* adjust view coordinates to be all positive ints, corrected for the start offset */
2088         const int x = (int)(floorf(fabsf(viewx) + 0.5f) - startx);
2089         const int y = (int)(floorf(fabsf(viewy) + 0.5f) - starty);
2090         
2091         /* sizes must not be negative */
2092         if ((v2d == NULL) || ((columnwidth <= 0) && (rowheight <= 0))) {
2093                 if (column) *column = 0;
2094                 if (row) *row = 0;
2095                 
2096                 return;
2097         }
2098         
2099         /* get column */
2100         if ((column) && (columnwidth > 0))
2101                 *column = x / columnwidth;
2102         else if (column)
2103                 *column = 0;
2104         
2105         /* get row */
2106         if ((row) && (rowheight > 0))
2107                 *row = y / rowheight;
2108         else if (row)
2109                 *row = 0;
2110 }
2111
2112 /**
2113  * Get the 'extreme' (min/max) column and row indices which are visible within the 'cur' rect
2114  *
2115  * \param columnwidth, rowheight: Size of each 'cell'
2116  * \param startx, starty: Coordinates that the list starts from, which should be (0,0) for most views
2117  * \param column_min, column_max, row_min, row_max: The starting and ending column/row indices
2118  */
2119 void UI_view2d_listview_visible_cells(
2120         View2D *v2d, float columnwidth, float rowheight, float startx, float starty,
2121         int *column_min, int *column_max, int *row_min, int *row_max)
2122 {
2123         /* using 'cur' rect coordinates, call the cell-getting function to get the cells for this */
2124         if (v2d) {
2125                 /* min */
2126                 UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, 
2127                                                 v2d->cur.xmin, v2d->cur.ymin, column_min, row_min);
2128
2129                 /* max*/
2130                 UI_view2d_listview_view_to_cell(v2d, columnwidth, rowheight, startx, starty, 
2131                                                 v2d->cur.xmax, v2d->cur.ymax, column_max, row_max);
2132         }
2133 }
2134
2135 /* *********************************************************************** */
2136 /* Coordinate Conversions */
2137
2138 float UI_view2d_region_to_view_x(struct View2D *v2d, float x)
2139 {
2140         return (v2d->cur.xmin + (BLI_rctf_size_x(&v2d->cur) * (x - v2d->mask.xmin) / BLI_rcti_size_x(&v2d->mask)));
2141 }
2142 float UI_view2d_region_to_view_y(struct View2D *v2d, float y)
2143 {
2144         return (v2d->cur.ymin + (BLI_rctf_size_y(&v2d->cur) * (y - v2d->mask.ymin) / BLI_rcti_size_y(&v2d->mask)));
2145 }
2146
2147 /**
2148  * Convert from screen/region space to 2d-View space
2149  *
2150  * \param x, y: coordinates to convert
2151  * \param r_view_x, r_view_y: resultant coordinates
2152  */
2153 void UI_view2d_region_to_view(View2D *v2d, float x, float y, float *r_view_x, float *r_view_y)
2154 {
2155         *r_view_x = UI_view2d_region_to_view_x(v2d, x);
2156         *r_view_y = UI_view2d_region_to_view_y(v2d, y);
2157 }
2158
2159 void UI_view2d_region_to_view_rctf(View2D *v2d, const rctf *rect_src, rctf *rect_dst)
2160 {
2161         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2162         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2163
2164         rect_dst->xmin = (v2d->cur.xmin + (cur_size[0] * (rect_src->xmin - v2d->mask.xmin) / mask_size[0]));
2165         rect_dst->xmax = (v2d->cur.xmin + (cur_size[0] * (rect_src->xmax - v2d->mask.xmin) / mask_size[0]));
2166         rect_dst->ymin = (v2d->cur.ymin + (cur_size[1] * (rect_src->ymin - v2d->mask.ymin) / mask_size[1]));
2167         rect_dst->ymax = (v2d->cur.ymin + (cur_size[1] * (rect_src->ymax - v2d->mask.ymin) / mask_size[1]));
2168 }
2169
2170 float UI_view2d_view_to_region_x(View2D *v2d, float x)
2171 {
2172         return (v2d->mask.xmin + (((x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur)) * BLI_rcti_size_x(&v2d->mask)));
2173 }
2174 float UI_view2d_view_to_region_y(View2D *v2d, float y)
2175 {
2176         return (v2d->mask.ymin + (((y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur)) * BLI_rcti_size_y(&v2d->mask)));
2177 }
2178
2179 /**
2180  * Convert from 2d-View space to screen/region space
2181  * \note Coordinates are clamped to lie within bounds of region
2182  *
2183  * \param x, y: Coordinates to convert.
2184  * \param r_region_x, r_region_y: Resultant coordinates.
2185  */
2186 bool UI_view2d_view_to_region_clip(View2D *v2d, float x, float y, int *r_region_x, int *r_region_y)
2187 {
2188         /* express given coordinates as proportional values */
2189         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2190         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2191         
2192         /* check if values are within bounds */
2193         if ((x >= 0.0f) && (x <= 1.0f) && (y >= 0.0f) && (y <= 1.0f)) {
2194                 *r_region_x = (int)(v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask)));
2195                 *r_region_y = (int)(v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask)));
2196
2197                 return true;
2198         }
2199         else {
2200                 /* set initial value in case coordinate lies outside of bounds */
2201                 *r_region_x = *r_region_y = V2D_IS_CLIPPED;
2202
2203                 return false;
2204         }
2205 }
2206
2207 /**
2208  * Convert from 2d-view space to screen/region space
2209  *
2210  * \note Coordinates are NOT clamped to lie within bounds of region.
2211  *
2212  * \param x, y: Coordinates to convert.
2213  * \param r_region_x, r_region_y: Resultant coordinates.
2214  */
2215 void UI_view2d_view_to_region(View2D *v2d, float x, float y, int *r_region_x, int *r_region_y)
2216 {
2217         /* step 1: express given coordinates as proportional values */
2218         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2219         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2220
2221         /* step 2: convert proportional distances to screen coordinates  */
2222         x = v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask));
2223         y = v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask));
2224
2225         /* although we don't clamp to lie within region bounds, we must avoid exceeding size of ints */
2226         *r_region_x = clamp_float_to_int(x);
2227         *r_region_y = clamp_float_to_int(y);
2228 }
2229
2230 void UI_view2d_view_to_region_fl(View2D *v2d, float x, float y, float *r_region_x, float *r_region_y)
2231 {
2232         /* express given coordinates as proportional values */
2233         x = (x - v2d->cur.xmin) / BLI_rctf_size_x(&v2d->cur);
2234         y = (y - v2d->cur.ymin) / BLI_rctf_size_y(&v2d->cur);
2235
2236         /* convert proportional distances to screen coordinates */
2237         *r_region_x = v2d->mask.xmin + (x * BLI_rcti_size_x(&v2d->mask));
2238         *r_region_y = v2d->mask.ymin + (y * BLI_rcti_size_y(&v2d->mask));
2239 }
2240
2241 void UI_view2d_view_to_region_rcti(View2D *v2d, const rctf *rect_src, rcti *rect_dst)
2242 {
2243         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2244         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2245         rctf rect_tmp;
2246
2247         /* step 1: express given coordinates as proportional values */
2248         rect_tmp.xmin = (rect_src->xmin - v2d->cur.xmin) / cur_size[0];
2249         rect_tmp.xmax = (rect_src->xmax - v2d->cur.xmin) / cur_size[0];
2250         rect_tmp.ymin = (rect_src->ymin - v2d->cur.ymin) / cur_size[1];
2251         rect_tmp.ymax = (rect_src->ymax - v2d->cur.ymin) / cur_size[1];
2252
2253
2254         /* step 2: convert proportional distances to screen coordinates  */
2255         rect_tmp.xmin = v2d->mask.xmin + (rect_tmp.xmin * mask_size[0]);
2256         rect_tmp.xmax = v2d->mask.xmin + (rect_tmp.xmax * mask_size[0]);
2257         rect_tmp.ymin = v2d->mask.ymin + (rect_tmp.ymin * mask_size[1]);
2258         rect_tmp.ymax = v2d->mask.ymin + (rect_tmp.ymax * mask_size[1]);
2259
2260         clamp_rctf_to_rcti(rect_dst, &rect_tmp);
2261 }
2262
2263 void UI_view2d_view_to_region_m4(View2D *v2d, float matrix[4][4])
2264 {
2265         rctf mask;
2266         unit_m4(matrix);
2267         BLI_rctf_rcti_copy(&mask, &v2d->mask);
2268         BLI_rctf_transform_calc_m4_pivot_min(&v2d->cur, &mask, matrix);
2269 }
2270
2271 bool UI_view2d_view_to_region_rcti_clip(View2D *v2d, const rctf *rect_src, rcti *rect_dst)
2272 {
2273         const float cur_size[2]  = {BLI_rctf_size_x(&v2d->cur),  BLI_rctf_size_y(&v2d->cur)};
2274         const float mask_size[2] = {BLI_rcti_size_x(&v2d->mask), BLI_rcti_size_y(&v2d->mask)};
2275         rctf rect_tmp;
2276
2277         BLI_assert(rect_src->xmin <= rect_src->xmax && rect_src->ymin <= rect_src->ymax);
2278
2279         /* step 1: express given coordinates as proportional values */
2280         rect_tmp.xmin = (rect_src->xmin - v2d->cur.xmin) / cur_size[0];
2281         rect_tmp.xmax = (rect_src->xmax - v2d->cur.xmin) / cur_size[0];
2282         rect_tmp.ymin = (rect_src->ymin - v2d->cur.ymin) / cur_size[1];
2283         rect_tmp.ymax = (rect_src->ymax - v2d->cur.ymin) / cur_size[1];
2284
2285         if (((rect_tmp.xmax < 0.0f) || (rect_tmp.xmin > 1.0f) ||
2286              (rect_tmp.ymax < 0.0f) || (rect_tmp.ymin > 1.0f)) == 0)
2287         {
2288                 /* step 2: convert proportional distances to screen coordinates  */
2289                 rect_tmp.xmin = v2d->mask.xmin + (rect_tmp.xmin * mask_size[0]);
2290                 rect_tmp.xmax = v2d->mask.ymin + (rect_tmp.xmax * mask_size[0]);
2291                 rect_tmp.ymin = v2d->mask.ymin + (rect_tmp.ymin * mask_size[1]);
2292                 rect_tmp.ymax = v2d->mask.ymin + (rect_tmp.ymax * mask_size[1]);
2293
2294                 clamp_rctf_to_rcti(rect_dst, &rect_tmp);
2295
2296                 return true;
2297         }
2298         else {
2299                 rect_dst->xmin = rect_dst->xmax = rect_dst->ymin = rect_dst->ymax = V2D_IS_CLIPPED;
2300
2301                 return false;
2302         }
2303 }
2304
2305 /* *********************************************************************** */
2306 /* Utilities */
2307
2308 /* View2D data by default resides in region, so get from region stored in context */
2309 View2D *UI_view2d_fromcontext(const bContext *C)
2310 {
2311         ScrArea *area = CTX_wm_area(C);
2312         ARegion *region = CTX_wm_region(C);
2313
2314         if (area == NULL) return NULL;
2315         if (region == NULL) return NULL;
2316         return &(region->v2d);
2317 }
2318
2319 /* same as above, but it returns regionwindow. Utility for pulldowns or buttons */
2320 View2D *UI_view2d_fromcontext_rwin(const bContext *C)
2321 {
2322         ScrArea *sa = CTX_wm_area(C);
2323         ARegion *region = CTX_wm_region(C);
2324
2325         if (sa == NULL) return NULL;
2326         if (region == NULL) return NULL;
2327         if (region->regiontype != RGN_TYPE_WINDOW) {
2328                 ARegion *ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
2329                 return ar ? &(ar->v2d) : NULL;
2330         }
2331         return &(region->v2d);
2332 }
2333
2334
2335 /**
2336  * Calculate the scale per-axis of the drawing-area
2337  *
2338  * Is used to inverse correct drawing of icons, etc. that need to follow view
2339  * but not be affected by scale
2340  *
2341  * \param x, y: scale on each axis
2342  */
2343 void UI_view2d_scale_get(View2D *v2d, float *x, float *y) 
2344 {
2345         if (x) *x = BLI_rcti_size_x(&v2d->mask) / BLI_rctf_size_x(&v2d->cur);
2346         if (y) *y = BLI_rcti_size_y(&v2d->mask) / BLI_rctf_size_y(&v2d->cur);
2347 }
2348 /**
2349  * Same as ``UI_view2d_scale_get() - 1.0f / x, y``
2350  */
2351 void UI_view2d_scale_get_inverse(View2D *v2d, float *x, float *y)
2352 {
2353         if (x) *x = BLI_rctf_size_x(&v2d->cur) / BLI_rcti_size_x(&v2d->mask);
2354         if (y) *y = BLI_rctf_size_y(&v2d->cur) / BLI_rcti_size_y(&v2d->mask);
2355 }
2356
2357 /**
2358  * Simple functions for consistent center offset access.
2359  * Used by node editor to shift view center for each individual node tree.
2360  */
2361 void UI_view2d_center_get(struct View2D *v2d, float *x, float *y)
2362 {
2363         /* get center */
2364         if (x) *x = BLI_rctf_cent_x(&v2d->cur);
2365         if (y) *y = BLI_rctf_cent_y(&v2d->cur);
2366 }
2367 void UI_view2d_center_set(struct View2D *v2d, float x, float y)
2368 {
2369         BLI_rctf_recenter(&v2d->cur, x, y);
2370
2371         /* make sure that 'cur' rect is in a valid state as a result of these changes */
2372         UI_view2d_curRect_validate(v2d);
2373 }
2374
2375 /**
2376  * Simple pan function
2377  *  (0.0, 0.0) bottom left
2378  *  (0.5, 0.5) center
2379  *  (1.0, 1.0) top right.
2380  */
2381 void UI_view2d_offset(struct View2D *v2d, float xfac, float yfac)
2382 {
2383         if (xfac != -1.0f) {
2384                 const float xsize = BLI_rctf_size_x(&v2d->cur);
2385                 const float xmin = v2d->tot.xmin;
2386                 const float xmax = v2d->tot.xmax - xsize;
2387
2388                 v2d->cur.xmin = (xmin * (1.0f - xfac)) + (xmax * xfac);
2389                 v2d->cur.xmax = v2d->cur.xmin + xsize;
2390         }
2391
2392         if (yfac != -1.0f) {
2393                 const float ysize = BLI_rctf_size_y(&v2d->cur);
2394                 const float ymin = v2d->tot.ymin;
2395                 const float ymax = v2d->tot.ymax - ysize;
2396
2397                 v2d->cur.ymin = (ymin * (1.0f - yfac)) + (ymax * yfac);
2398                 v2d->cur.ymax = v2d->cur.ymin + ysize;
2399         }
2400
2401         UI_view2d_curRect_validate(v2d);
2402 }
2403
2404 /**
2405  * Check if mouse is within scrollers
2406  *
2407  * \param x, y: Mouse coordinates in screen (not region) space.
2408  *
2409  * \return appropriate code for match.
2410  * - 'h' = in horizontal scroller.
2411  * - 'v' = in vertical scroller.
2412  * - 0 = not in scroller.
2413  */
2414 short UI_view2d_mouse_in_scrollers(const bContext *C, View2D *v2d, int x, int y)
2415 {
2416         ARegion *ar = CTX_wm_region(C);
2417         int co[2];
2418         int scroll = view2d_scroll_mapped(v2d->scroll);
2419         
2420         /* clamp x,y to region-coordinates first */
2421         co[0] = x - ar->winrct.xmin;
2422         co[1] = y - ar->winrct.ymin;
2423         
2424         /* check if within scrollbars */
2425         if (scroll & V2D_SCROLL_HORIZONTAL) {
2426                 if (IN_2D_HORIZ_SCROLL(v2d, co)) return 'h';
2427         }
2428         if (scroll & V2D_SCROLL_VERTICAL) {
2429                 if (IN_2D_VERT_SCROLL(v2d, co)) return 'v';
2430         }
2431         
2432         /* not found */
2433         return 0;
2434 }
2435
2436 /* ******************* view2d text drawing cache ******************** */
2437
2438 typedef struct View2DString {
2439         struct View2DString *next;
2440         union {
2441                 unsigned char ub[4];
2442                 int pack;
2443         } col;
2444         rcti rect;
2445         int mval[2];
2446
2447         /* str is allocated past the end */
2448         char str[0];
2449 } View2DString;
2450
2451 /* assumes caches are used correctly, so for time being no local storage in v2d */
2452 static MemArena     *g_v2d_strings_arena = NULL;
2453 static View2DString *g_v2d_strings = NULL;
2454
2455 void UI_view2d_text_cache_add(
2456         View2D *v2d, float x, float y,
2457         const char *str, size_t str_len, const char col[4])
2458 {
2459         int mval[2];
2460         
2461         BLI_assert(str_len == strlen(str));
2462
2463         if (UI_view2d_view_to_region_clip(v2d, x, y, &mval[0], &mval[1])) {
2464                 int alloc_len = str_len + 1;
2465                 View2DString *v2s;
2466
2467                 if (g_v2d_strings_arena == NULL) {
2468                         g_v2d_strings_arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 14), __func__);
2469                 }
2470
2471                 v2s = BLI_memarena_alloc(g_v2d_strings_arena, sizeof(View2DString) + alloc_len);
2472
2473                 BLI_LINKS_PREPEND(g_v2d_strings, v2s);
2474
2475                 v2s->col.pack = *((const int *)col);
2476
2477                 memset(&v2s->rect, 0, sizeof(v2s->rect));
2478
2479                 v2s->mval[0] = mval[0];
2480                 v2s->mval[1] = mval[1];
2481
2482                 memcpy(v2s->str, str, alloc_len);
2483         }
2484 }
2485
2486 /* no clip (yet) */
2487 void UI_view2d_text_cache_add_rectf(
2488         View2D *v2d, const rctf *rect_view,
2489         const char *str, size_t str_len, const char col[4])
2490 {
2491         rcti rect;
2492
2493         BLI_assert(str_len == strlen(str));
2494
2495         if (UI_view2d_view_to_region_rcti_clip(v2d, rect_view, &rect)) {
2496                 int alloc_len = str_len + 1;
2497                 View2DString *v2s;
2498
2499                 if (g_v2d_strings_arena == NULL) {
2500                         g_v2d_strings_arena = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 14), __func__);
2501                 }
2502
2503                 v2s = BLI_memarena_alloc(g_v2d_strings_arena, sizeof(View2DString) + alloc_len);
2504
2505                 BLI_LINKS_PREPEND(g_v2d_strings, v2s);
2506
2507                 v2s->col.pack = *((const int *)col);
2508
2509                 v2s->rect = rect;
2510
2511                 v2s->mval[0] = v2s->rect.xmin;
2512                 v2s->mval[1] = v2s->rect.ymin;
2513
2514                 memcpy(v2s->str, str, alloc_len);
2515         }
2516 }
2517
2518
2519 void UI_view2d_text_cache_draw(ARegion *ar)
2520 {
2521         View2DString *v2s;
2522         int col_pack_prev = 0;
2523
2524         /* investigate using BLF_ascender() */
2525         const int font_id = BLF_default();
2526         const float default_height = g_v2d_strings ? BLF_height(font_id, "28", 3) : 0.0f;
2527
2528         wmOrtho2_region_pixelspace(ar);
2529
2530         for (v2s = g_v2d_strings; v2s; v2s = v2s->next) {
2531                 int xofs = 0, yofs;
2532
2533                 yofs = ceil(0.5f * (BLI_rcti_size_y(&v2s->rect) - default_height));
2534                 if (yofs < 1) yofs = 1;
2535
2536                 if (col_pack_prev != v2s->col.pack) {
2537                         BLF_color3ubv(font_id, v2s->col.ub);
2538                         col_pack_prev = v2s->col.pack;
2539                 }
2540
2541                 if (v2s->rect.xmin >= v2s->rect.xmax)
2542                         BLF_draw_default((float)(v2s->mval[0] + xofs), (float)(v2s->mval[1] + yofs), 0.0,
2543                                           v2s->str, BLF_DRAW_STR_DUMMY_MAX);
2544                 else {
2545                         BLF_enable(font_id, BLF_CLIPPING);
2546                         BLF_clipping(font_id, v2s->rect.xmin - 4, v2s->rect.ymin - 4, v2s->rect.xmax + 4, v2s->rect.ymax + 4);
2547                         BLF_draw_default(v2s->rect.xmin + xofs, v2s->rect.ymin + yofs, 0.0f,
2548                                          v2s->str, BLF_DRAW_STR_DUMMY_MAX);
2549                         BLF_disable(font_id, BLF_CLIPPING);
2550                 }
2551         }
2552         g_v2d_strings = NULL;
2553
2554         if (g_v2d_strings_arena) {
2555                 BLI_memarena_free(g_v2d_strings_arena);
2556                 g_v2d_strings_arena = NULL;
2557         }
2558 }
2559
2560
2561 /* ******************************************************** */
2562
2563