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