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