e1a541dc7deb24e1900131c14db23337b2dcee10
[blender.git] / source / blender / editors / interface / interface.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation 2002-2008, full recode.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <stddef.h>  /* offsetof() */
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_scene_types.h"
41 #include "DNA_screen_types.h"
42 #include "DNA_userdef_types.h"
43
44 #include "BLI_math.h"
45 #include "BLI_listbase.h"
46 #include "BLI_string.h"
47 #include "BLI_string_utf8.h"
48 #include "BLI_path_util.h"
49 #include "BLI_rect.h"
50
51 #include "BLI_dynstr.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_context.h"
55 #include "BKE_library.h"
56 #include "BKE_unit.h"
57 #include "BKE_screen.h"
58 #include "BKE_idprop.h"
59
60 #include "BIF_gl.h"
61
62 #include "BLF_api.h"
63 #include "BLF_translation.h"
64
65 #include "UI_interface.h"
66
67 #include "IMB_imbuf.h"
68
69 #include "WM_api.h"
70 #include "WM_types.h"
71 #include "wm_subwindow.h"
72
73 #include "RNA_access.h"
74
75 #include "BPY_extern.h"
76
77 #include "IMB_colormanagement.h"
78
79 #include "interface_intern.h"
80
81 #define PRECISION_FLOAT_MAX 6
82 #define PRECISION_FLOAT_MAX_POW 1000000 /* pow(10, PRECISION_FLOAT_MAX)  */
83
84 /* avoid unneeded calls to ui_get_but_val */
85 #define UI_BUT_VALUE_UNSET DBL_MAX
86 #define UI_GET_BUT_VALUE_INIT(_but, _value) if (_value == DBL_MAX) {  (_value) = ui_get_but_val(_but); } (void)0
87
88 /* 
89  * a full doc with API notes can be found in bf-blender/trunk/blender/doc/guides/interface_API.txt
90  * 
91  * uiBlahBlah()         external function
92  * ui_blah_blah()       internal function
93  */
94
95 static void ui_free_but(const bContext *C, uiBut *but);
96
97 /* ************* window matrix ************** */
98
99 void ui_block_to_window_fl(const ARegion *ar, uiBlock *block, float *x, float *y)
100 {
101         float gx, gy;
102         int sx, sy, getsizex, getsizey;
103
104         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
105         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
106         sx = ar->winrct.xmin;
107         sy = ar->winrct.ymin;
108
109         gx = *x;
110         gy = *y;
111
112         if (block->panel) {
113                 gx += block->panel->ofsx;
114                 gy += block->panel->ofsy;
115         }
116
117         *x = ((float)sx) + ((float)getsizex) * (0.5f + 0.5f * (gx * block->winmat[0][0] + gy * block->winmat[1][0] + block->winmat[3][0]));
118         *y = ((float)sy) + ((float)getsizey) * (0.5f + 0.5f * (gx * block->winmat[0][1] + gy * block->winmat[1][1] + block->winmat[3][1]));
119 }
120
121 void ui_block_to_window(const ARegion *ar, uiBlock *block, int *x, int *y)
122 {
123         float fx, fy;
124
125         fx = *x;
126         fy = *y;
127
128         ui_block_to_window_fl(ar, block, &fx, &fy);
129
130         *x = (int)(fx + 0.5f);
131         *y = (int)(fy + 0.5f);
132 }
133
134 void ui_block_to_window_rct(const ARegion *ar, uiBlock *block, const rctf *graph, rcti *winr)
135 {
136         rctf tmpr;
137
138         tmpr = *graph;
139         ui_block_to_window_fl(ar, block, &tmpr.xmin, &tmpr.ymin);
140         ui_block_to_window_fl(ar, block, &tmpr.xmax, &tmpr.ymax);
141
142         BLI_rcti_rctf_copy(winr, &tmpr);
143 }
144
145 void ui_window_to_block_fl(const ARegion *ar, uiBlock *block, float *x, float *y)   /* for mouse cursor */
146 {
147         float a, b, c, d, e, f, px, py;
148         int sx, sy, getsizex, getsizey;
149
150         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
151         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
152         sx = ar->winrct.xmin;
153         sy = ar->winrct.ymin;
154
155         a = 0.5f * ((float)getsizex) * block->winmat[0][0];
156         b = 0.5f * ((float)getsizex) * block->winmat[1][0];
157         c = 0.5f * ((float)getsizex) * (1.0f + block->winmat[3][0]);
158
159         d = 0.5f * ((float)getsizey) * block->winmat[0][1];
160         e = 0.5f * ((float)getsizey) * block->winmat[1][1];
161         f = 0.5f * ((float)getsizey) * (1.0f + block->winmat[3][1]);
162
163         px = *x - sx;
164         py = *y - sy;
165
166         *y =  (a * (py - f) + d * (c - px)) / (a * e - d * b);
167         *x = (px - b * (*y) - c) / a;
168
169         if (block->panel) {
170                 *x -= block->panel->ofsx;
171                 *y -= block->panel->ofsy;
172         }
173 }
174
175 void ui_window_to_block(const ARegion *ar, uiBlock *block, int *x, int *y)
176 {
177         float fx, fy;
178
179         fx = *x;
180         fy = *y;
181
182         ui_window_to_block_fl(ar, block, &fx, &fy);
183
184         *x = (int)(fx + 0.5f);
185         *y = (int)(fy + 0.5f);
186 }
187
188 void ui_window_to_region(const ARegion *ar, int *x, int *y)
189 {
190         *x -= ar->winrct.xmin;
191         *y -= ar->winrct.ymin;
192 }
193
194 /* ******************* block calc ************************* */
195
196 void ui_block_translate(uiBlock *block, int x, int y)
197 {
198         uiBut *but;
199
200         for (but = block->buttons.first; but; but = but->next) {
201                 BLI_rctf_translate(&but->rect, x, y);
202         }
203
204         BLI_rctf_translate(&block->rect, x, y);
205 }
206
207 static void ui_text_bounds_block(uiBlock *block, float offset)
208 {
209         uiStyle *style = UI_GetStyle();
210         uiBut *bt;
211         int i = 0, j, x1addval = offset, nextcol;
212         int lastcol = 0, col = 0;
213         
214         uiStyleFontSet(&style->widget);
215         
216         for (bt = block->buttons.first; bt; bt = bt->next) {
217                 if (bt->type != SEPR) {
218                         j = BLF_width(style->widget.uifont_id, bt->drawstr);
219
220                         if (j > i) i = j;
221                 }
222
223                 if (bt->next && bt->rect.xmin < bt->next->rect.xmin)
224                         lastcol++;
225         }
226
227         /* cope with multi collumns */
228         bt = block->buttons.first;
229         while (bt) {
230                 if (bt->next && bt->rect.xmin < bt->next->rect.xmin) {
231                         nextcol = 1;
232                         col++;
233                 }
234                 else nextcol = 0;
235                 
236                 bt->rect.xmin = x1addval;
237                 bt->rect.xmax = bt->rect.xmin + i + block->bounds;
238                 
239                 if (col == lastcol) {
240                         bt->rect.xmax = max_ff(bt->rect.xmax, offset + block->minbounds);
241                 }
242
243                 ui_check_but(bt);  /* clips text again */
244                 
245                 if (nextcol)
246                         x1addval += i + block->bounds;
247                 
248                 bt = bt->next;
249         }
250 }
251
252 void ui_bounds_block(uiBlock *block)
253 {
254         uiBut *bt;
255         int xof;
256         
257         if (block->buttons.first == NULL) {
258                 if (block->panel) {
259                         block->rect.xmin = 0.0; block->rect.xmax = block->panel->sizex;
260                         block->rect.ymin = 0.0; block->rect.ymax = block->panel->sizey;
261                 }
262         }
263         else {
264         
265                 BLI_rctf_init_minmax(&block->rect);
266
267                 for (bt = block->buttons.first; bt; bt = bt->next) {
268                         BLI_rctf_union(&block->rect, &bt->rect);
269                 }
270                 
271                 block->rect.xmin -= block->bounds;
272                 block->rect.ymin -= block->bounds;
273                 block->rect.xmax += block->bounds;
274                 block->rect.ymax += block->bounds;
275         }
276
277         block->rect.xmax = block->rect.xmin + max_ff(BLI_rctf_size_x(&block->rect), block->minbounds);
278
279         /* hardcoded exception... but that one is annoying with larger safety */ 
280         bt = block->buttons.first;
281         if (bt && strncmp(bt->str, "ERROR", 5) == 0) xof = 10;
282         else xof = 40;
283
284         block->safety.xmin = block->rect.xmin - xof;
285         block->safety.ymin = block->rect.ymin - xof;
286         block->safety.xmax = block->rect.xmax + xof;
287         block->safety.ymax = block->rect.ymax + xof;
288 }
289
290 static void ui_centered_bounds_block(const bContext *C, uiBlock *block)
291 {
292         wmWindow *window = CTX_wm_window(C);
293         int xmax, ymax;
294         int startx, starty;
295         int width, height;
296         
297         /* note: this is used for the splash where window bounds event has not been
298          * updated by ghost, get the window bounds from ghost directly */
299
300         xmax = WM_window_pixels_x(window);
301         ymax = WM_window_pixels_y(window);
302
303         ui_bounds_block(block);
304         
305         width  = BLI_rctf_size_x(&block->rect);
306         height = BLI_rctf_size_y(&block->rect);
307         
308         startx = (xmax * 0.5f) - (width * 0.5f);
309         starty = (ymax * 0.5f) - (height * 0.5f);
310         
311         ui_block_translate(block, startx - block->rect.xmin, starty - block->rect.ymin);
312         
313         /* now recompute bounds and safety */
314         ui_bounds_block(block);
315         
316 }
317 static void ui_popup_bounds_block(const bContext *C, uiBlock *block, eBlockBoundsCalc bounds_calc)
318 {
319         wmWindow *window = CTX_wm_window(C);
320         int startx, starty, endx, endy, width, height, oldwidth, oldheight;
321         int oldbounds, xmax, ymax;
322         const int margin = UI_SCREEN_MARGIN;
323
324         oldbounds = block->bounds;
325
326         /* compute mouse position with user defined offset */
327         ui_bounds_block(block);
328         
329         xmax = WM_window_pixels_x(window);
330         ymax = WM_window_pixels_y(window);
331
332         oldwidth  = BLI_rctf_size_x(&block->rect);
333         oldheight = BLI_rctf_size_y(&block->rect);
334
335         /* first we ensure wide enough text bounds */
336         if (bounds_calc == UI_BLOCK_BOUNDS_POPUP_MENU) {
337                 if (block->flag & UI_BLOCK_LOOP) {
338                         block->bounds = 2.5f * UI_UNIT_X;
339                         ui_text_bounds_block(block, block->rect.xmin);
340                 }
341         }
342
343         /* next we recompute bounds */
344         block->bounds = oldbounds;
345         ui_bounds_block(block);
346
347         /* and we adjust the position to fit within window */
348         width  = BLI_rctf_size_x(&block->rect);
349         height = BLI_rctf_size_y(&block->rect);
350
351         /* avoid divide by zero below, caused by calling with no UI, but better not crash */
352         oldwidth = oldwidth > 0 ? oldwidth : MAX2(1, width);
353         oldheight = oldheight > 0 ? oldheight : MAX2(1, height);
354
355         /* offset block based on mouse position, user offset is scaled
356          * along in case we resized the block in ui_text_bounds_block */
357         startx = window->eventstate->x + block->rect.xmin + (block->mx * width) / oldwidth;
358         starty = window->eventstate->y + block->rect.ymin + (block->my * height) / oldheight;
359
360         if (startx < margin)
361                 startx = margin;
362         if (starty < margin)
363                 starty = margin;
364
365         endx = startx + width;
366         endy = starty + height;
367
368         if (endx > xmax) {
369                 endx = xmax - margin;
370                 startx = endx - width;
371         }
372         if (endy > ymax - margin) {
373                 endy = ymax - margin;
374                 starty = endy - height;
375         }
376
377         ui_block_translate(block, startx - block->rect.xmin, starty - block->rect.ymin);
378
379         /* now recompute bounds and safety */
380         ui_bounds_block(block);
381 }
382
383 /* used for various cases */
384 void uiBoundsBlock(uiBlock *block, int addval)
385 {
386         if (block == NULL)
387                 return;
388         
389         block->bounds = addval;
390         block->bounds_type = UI_BLOCK_BOUNDS;
391 }
392
393 /* used for pulldowns */
394 void uiTextBoundsBlock(uiBlock *block, int addval)
395 {
396         block->bounds = addval;
397         block->bounds_type = UI_BLOCK_BOUNDS_TEXT;
398 }
399
400 /* used for block popups */
401 void uiPopupBoundsBlock(uiBlock *block, int addval, int mx, int my)
402 {
403         block->bounds = addval;
404         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_MOUSE;
405         block->mx = mx;
406         block->my = my;
407 }
408
409 /* used for menu popups */
410 void uiMenuPopupBoundsBlock(uiBlock *block, int addval, int mx, int my)
411 {
412         block->bounds = addval;
413         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_MENU;
414         block->mx = mx;
415         block->my = my;
416 }
417
418 /* used for centered popups, i.e. splash */
419 void uiCenteredBoundsBlock(uiBlock *block, int addval)
420 {
421         block->bounds = addval;
422         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_CENTER;
423 }
424
425 void uiExplicitBoundsBlock(uiBlock *block, int minx, int miny, int maxx, int maxy)
426 {
427         block->rect.xmin = minx;
428         block->rect.ymin = miny;
429         block->rect.xmax = maxx;
430         block->rect.ymax = maxy;
431         block->bounds_type = UI_BLOCK_BOUNDS_NONE;
432 }
433
434 /* ************** LINK LINE DRAWING  ************* */
435
436 /* link line drawing is not part of buttons or theme.. so we stick with it here */
437
438 static int ui_but_float_precision(uiBut *but, double value)
439 {
440         int prec;
441
442         /* first check if prec is 0 and fallback to a simple default */
443         if ((prec = (int)but->a2) == 0) {
444                 prec = (but->hardmax < 10.001f) ? 3 : 2;
445         }
446
447         /* check on the number of decimal places need to display
448          * the number, this is so 0.00001 is not displayed as 0.00,
449          * _but_, this is only for small values si 10.0001 will not get
450          * the same treatment */
451         if (value != 0.0 && (value = ABS(value)) < 0.1) {
452                 int value_i = (int)((value * PRECISION_FLOAT_MAX_POW) + 0.5);
453                 if (value_i != 0) {
454                         const int prec_span = 3; /* show: 0.01001, 5 would allow 0.0100001 for eg. */
455                         int test_prec;
456                         int prec_min = -1;
457                         int dec_flag = 0;
458                         int i = PRECISION_FLOAT_MAX;
459                         while (i && value_i) {
460                                 if (value_i % 10) {
461                                         dec_flag |= 1 << i;
462                                         prec_min = i;
463                                 }
464                                 value_i /= 10;
465                                 i--;
466                         }
467
468                         /* even though its a small value, if the second last digit is not 0, use it */
469                         test_prec = prec_min;
470
471                         dec_flag = (dec_flag >> (prec_min + 1)) & ((1 << prec_span) - 1);
472
473                         while (dec_flag) {
474                                 test_prec++;
475                                 dec_flag = dec_flag >> 1;
476                         }
477
478                         if (test_prec > prec) {
479                                 prec = test_prec;
480                         }
481                 }
482         }
483
484         CLAMP(prec, 1, PRECISION_FLOAT_MAX);
485
486         return prec;
487 }
488
489 static void ui_draw_linkline(uiLinkLine *line, int highlightActiveLines)
490 {
491         rcti rect;
492
493         if (line->from == NULL || line->to == NULL) return;
494         
495         rect.xmin = BLI_rctf_cent_x(&line->from->rect);
496         rect.ymin = BLI_rctf_cent_y(&line->from->rect);
497         rect.xmax = BLI_rctf_cent_x(&line->to->rect);
498         rect.ymax = BLI_rctf_cent_y(&line->to->rect);
499         
500         if (line->flag & UI_SELECT)
501                 glColor3ub(100, 100, 100);
502         else if (highlightActiveLines && ((line->from->flag & UI_ACTIVE) || (line->to->flag & UI_ACTIVE)))
503                 UI_ThemeColor(TH_TEXT_HI);
504         else 
505                 glColor3ub(0, 0, 0);
506
507         ui_draw_link_bezier(&rect);
508 }
509
510 static void ui_draw_links(uiBlock *block)
511 {
512         uiBut *but;
513         uiLinkLine *line;
514
515         /* Draw the inactive lines (lines with neither button being hovered over).
516          * As we go, remember if we see any active or selected lines. */
517         int foundselectline = FALSE;
518         int foundactiveline = FALSE;
519         for (but = block->buttons.first; but; but = but->next) {
520                 if (but->type == LINK && but->link) {
521                         for (line = but->link->lines.first; line; line = line->next) {
522                                 if (!(line->from->flag & UI_ACTIVE) && !(line->to->flag & UI_ACTIVE))
523                                         ui_draw_linkline(line, 0);
524                                 else
525                                         foundactiveline = TRUE;
526
527                                 if ((line->from->flag & UI_SELECT) || (line->to->flag & UI_SELECT))
528                                         foundselectline = TRUE;
529                         }
530                 }
531         }
532
533         /* Draw any active lines (lines with either button being hovered over).
534          * Do this last so they appear on top of inactive lines. */
535         if (foundactiveline) {
536                 for (but = block->buttons.first; but; but = but->next) {
537                         if (but->type == LINK && but->link) {
538                                 for (line = but->link->lines.first; line; line = line->next) {
539                                         if ((line->from->flag & UI_ACTIVE) || (line->to->flag & UI_ACTIVE))
540                                                 ui_draw_linkline(line, !foundselectline);
541                                 }
542                         }
543                 }
544         }
545 }
546
547 /* ************** BLOCK ENDING FUNCTION ************* */
548
549 /* NOTE: if but->poin is allocated memory for every defbut, things fail... */
550 static int ui_but_equals_old(uiBut *but, uiBut *oldbut)
551 {
552         /* various properties are being compared here, hopefully sufficient
553          * to catch all cases, but it is simple to add more checks later */
554         if (but->retval != oldbut->retval) return 0;
555         if (but->rnapoin.data != oldbut->rnapoin.data) return 0;
556         if (but->rnaprop != oldbut->rnaprop)
557                 if (but->rnaindex != oldbut->rnaindex) return 0;
558         if (but->func != oldbut->func) return 0;
559         if (but->funcN != oldbut->funcN) return 0;
560         if (oldbut->func_arg1 != oldbut && but->func_arg1 != oldbut->func_arg1) return 0;
561         if (oldbut->func_arg2 != oldbut && but->func_arg2 != oldbut->func_arg2) return 0;
562         if (!but->funcN && ((but->poin != oldbut->poin && (uiBut *)oldbut->poin != oldbut) || but->pointype != oldbut->pointype)) return 0;
563         if (but->optype != oldbut->optype) return 0;
564
565         return 1;
566 }
567
568 /* oldbut is being inserted in new block, so we use the lines from new button, and replace button pointers */
569 static void ui_but_update_linklines(uiBlock *block, uiBut *oldbut, uiBut *newbut)
570 {
571         uiLinkLine *line;
572         uiBut *but;
573         
574         /* if active button is LINK */
575         if (newbut->type == LINK && newbut->link) {
576                 
577                 SWAP(uiLink *, oldbut->link, newbut->link);
578                 
579                 for (line = oldbut->link->lines.first; line; line = line->next) {
580                         if (line->to == newbut)
581                                 line->to = oldbut;
582                         if (line->from == newbut)
583                                 line->from = oldbut;
584                 }
585         }
586         
587         /* check all other button links */
588         for (but = block->buttons.first; but; but = but->next) {
589                 if (but != newbut && but->type == LINK && but->link) {
590                         for (line = but->link->lines.first; line; line = line->next) {
591                                 if (line->to == newbut)
592                                         line->to = oldbut;
593                                 if (line->from == newbut)
594                                         line->from = oldbut;
595                         }
596                 }
597         }
598 }
599
600 static int ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBut **butpp)
601 {
602         uiBlock *oldblock;
603         uiBut *oldbut, *but = *butpp;
604         int found = 0;
605
606         oldblock = block->oldblock;
607         if (!oldblock)
608                 return found;
609
610         for (oldbut = oldblock->buttons.first; oldbut; oldbut = oldbut->next) {
611                 if (ui_but_equals_old(oldbut, but)) {
612                         if (oldbut->active) {
613 #if 0
614 //                              but->flag = oldbut->flag;
615 #else
616                                 /* exception! redalert flag can't be update from old button. 
617                                  * perhaps it should only copy specific flags rather than all. */
618 //                              but->flag = (oldbut->flag & ~UI_BUT_REDALERT) | (but->flag & UI_BUT_REDALERT);
619 #endif
620 //                              but->active = oldbut->active;
621 //                              but->pos = oldbut->pos;
622 //                              but->ofs = oldbut->ofs;
623 //                              but->editstr = oldbut->editstr;
624 //                              but->editval = oldbut->editval;
625 //                              but->editvec = oldbut->editvec;
626 //                              but->editcoba = oldbut->editcoba;
627 //                              but->editcumap = oldbut->editcumap;
628 //                              but->selsta = oldbut->selsta;
629 //                              but->selend = oldbut->selend;
630 //                              but->softmin = oldbut->softmin;
631 //                              but->softmax = oldbut->softmax;
632 //                              but->linkto[0] = oldbut->linkto[0];
633 //                              but->linkto[1] = oldbut->linkto[1];
634                                 found = 1;
635 //                              oldbut->active = NULL;
636                         
637                                 /* move button over from oldblock to new block */
638                                 BLI_remlink(&oldblock->buttons, oldbut);
639                                 BLI_insertlinkafter(&block->buttons, but, oldbut);
640                                 oldbut->block = block;
641                                 *butpp = oldbut;
642                                 
643                                 /* still stuff needs to be copied */
644                                 oldbut->rect = but->rect;
645                                 oldbut->context = but->context; /* set by Layout */
646                                 
647                                 /* typically the same pointers, but not on undo/redo */
648                                 /* XXX some menu buttons store button itself in but->poin. Ugly */
649                                 if (oldbut->poin != (char *)oldbut) {
650                                         SWAP(char *, oldbut->poin, but->poin);
651                                         SWAP(void *, oldbut->func_argN, but->func_argN);
652                                 }
653                                 
654                                 /* copy hardmin for list rows to prevent 'sticking' highlight to mouse position
655                                  * when scrolling without moving mouse (see [#28432]) */
656                                 if (ELEM(oldbut->type, ROW, LISTROW))
657                                         oldbut->hardmax = but->hardmax;
658                                 
659                                 ui_but_update_linklines(block, oldbut, but);
660                                 
661                                 BLI_remlink(&block->buttons, but);
662                                 ui_free_but(C, but);
663                                 
664                                 /* note: if layout hasn't been applied yet, it uses old button pointers... */
665                         }
666                         else {
667                                 /* ensures one button can get activated, and in case the buttons
668                                  * draw are the same this gives O(1) lookup for each button */
669                                 BLI_remlink(&oldblock->buttons, oldbut);
670                                 ui_free_but(C, oldbut);
671                         }
672                         
673                         break;
674                 }
675         }
676         
677         return found;
678 }
679
680 /* needed for temporarily rename buttons, such as in outliner or file-select,
681  * they should keep calling uiDefButs to keep them alive */
682 /* returns 0 when button removed */
683 int uiButActiveOnly(const bContext *C, uiBlock *block, uiBut *but)
684 {
685         uiBlock *oldblock;
686         uiBut *oldbut;
687         int activate = FALSE, found = FALSE, isactive = FALSE;
688         
689         oldblock = block->oldblock;
690         if (!oldblock)
691                 activate = TRUE;
692         else {
693                 for (oldbut = oldblock->buttons.first; oldbut; oldbut = oldbut->next) {
694                         if (ui_but_equals_old(oldbut, but)) {
695                                 found = TRUE;
696                                 
697                                 if (oldbut->active)
698                                         isactive = TRUE;
699                                 
700                                 break;
701                         }
702                 }
703         }
704         if ((activate == TRUE) || (found == FALSE)) {
705                 ui_button_activate_do((bContext *)C, CTX_wm_region(C), but);
706         }
707         else if ((found == TRUE) && (isactive == FALSE)) {
708                 BLI_remlink(&block->buttons, but);
709                 ui_free_but(C, but);
710                 return 0;
711         }
712         
713         return 1;
714 }
715
716 /* simulate button click */
717 void uiButExecute(const bContext *C, uiBut *but)
718 {
719         ui_button_execute_do((bContext *)C, CTX_wm_region(C), but);
720 }
721
722 /* use to check if we need to disable undo, but don't make any changes
723  * returns FALSE if undo needs to be disabled. */
724 static int ui_but_is_rna_undo(uiBut *but)
725 {
726         if (but->rnapoin.id.data) {
727                 /* avoid undo push for buttons who's ID are screen or wm level
728                  * we could disable undo for buttons with no ID too but may have
729                  * unforeseen consequences, so best check for ID's we _know_ are not
730                  * handled by undo - campbell */
731                 ID *id = but->rnapoin.id.data;
732                 if (ID_CHECK_UNDO(id) == FALSE) {
733                         return FALSE;
734                 }
735                 else {
736                         return TRUE;
737                 }
738         }
739         else if (but->rnapoin.type && !RNA_struct_undo_check(but->rnapoin.type)) {
740                 return FALSE;
741         }
742
743         return TRUE;
744 }
745
746 /* assigns automatic keybindings to menu items for fast access
747  * (underline key in menu) */
748 static void ui_menu_block_set_keyaccels(uiBlock *block)
749 {
750         uiBut *but;
751
752         unsigned int menu_key_mask = 0;
753         unsigned char menu_key;
754         const char *str_pt;
755         int pass;
756         int tot_missing = 0;
757
758         /* only do it before bounding */
759         if (block->rect.xmin != block->rect.xmax)
760                 return;
761
762         for (pass = 0; pass < 2; pass++) {
763                 /* 2 Passes, on for first letter only, second for any letter if first fails
764                  * fun first pass on all buttons so first word chars always get first priority */
765
766                 for (but = block->buttons.first; but; but = but->next) {
767                         if (!ELEM5(but->type, BUT, BUTM, MENU, BLOCK, PULLDOWN) || (but->flag & UI_HIDDEN)) {
768                                 /* pass */
769                         }
770                         else if (but->menu_key == '\0') {
771                                 if (but->str) {
772                                         for (str_pt = but->str; *str_pt; ) {
773                                                 menu_key = tolower(*str_pt);
774                                                 if ((menu_key >= 'a' && menu_key <= 'z') && !(menu_key_mask & 1 << (menu_key - 'a'))) {
775                                                         menu_key_mask |= 1 << (menu_key - 'a');
776                                                         break;
777                                                 }
778
779                                                 if (pass == 0) {
780                                                         /* Skip to next delimiter on first pass (be picky) */
781                                                         while (isalpha(*str_pt))
782                                                                 str_pt++;
783
784                                                         if (*str_pt)
785                                                                 str_pt++;
786                                                 }
787                                                 else {
788                                                         /* just step over every char second pass and find first usable key */
789                                                         str_pt++;
790                                                 }
791                                         }
792
793                                         if (*str_pt) {
794                                                 but->menu_key = menu_key;
795                                         }
796                                         else {
797                                                 /* run second pass */
798                                                 tot_missing++;
799                                         }
800
801                                         /* if all keys have been used just exit, unlikely */
802                                         if (menu_key_mask == (1 << 26) - 1) {
803                                                 return;
804                                         }
805                                 }
806                         }
807                 }
808
809                 /* check if second pass is needed */
810                 if (!tot_missing) {
811                         break;
812                 }
813         }
814 }
815
816 /* XXX, this code will shorten any allocated string to 'UI_MAX_NAME_STR'
817  * since this is really long its unlikely to be an issue,
818  * but this could be supported */
819 void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const short do_strip)
820 {
821
822         if (do_strip) {
823                 char *cpoin = strchr(but->str, '|');
824                 if (cpoin) {
825                         *cpoin = '\0';
826                 }
827         }
828
829         /* without this, just allow stripping of the shortcut */
830         if (shortcut_str) {
831                 char *butstr_orig;
832
833                 if (but->str != but->strdata) {
834                         butstr_orig = but->str; /* free after using as source buffer */
835                 }
836                 else {
837                         butstr_orig = BLI_strdup(but->str);
838                 }
839                 BLI_snprintf(but->strdata,
840                              sizeof(but->strdata),
841                              "%s|%s",
842                              butstr_orig, shortcut_str);
843                 MEM_freeN(butstr_orig);
844                 but->str = but->strdata;
845                 ui_check_but(but);
846         }
847 }
848
849 static void ui_menu_block_set_keymaps(const bContext *C, uiBlock *block)
850 {
851         uiBut *but;
852         char buf[128];
853
854         /* for menu's */
855         MenuType *mt;
856         IDProperty *prop_menu = NULL;
857         IDProperty *prop_menu_name = NULL;
858
859         /* only do it before bounding */
860         if (block->rect.xmin != block->rect.xmax)
861                 return;
862
863         for (but = block->buttons.first; but; but = but->next) {
864                 if (but->optype) {
865                         IDProperty *prop = (but->opptr) ? but->opptr->data : NULL;
866
867                         if (WM_key_event_operator_string(C, but->optype->idname, but->opcontext, prop, TRUE,
868                                                          buf, sizeof(buf)))
869                         {
870                                 ui_but_add_shortcut(but, buf, FALSE);
871                         }
872                 }
873                 else if ((mt = uiButGetMenuType(but))) {
874                         /* only allocate menu property once */
875                         if (prop_menu == NULL) {
876                                 /* annoying, create a property */
877                                 IDPropertyTemplate val = {0};
878                                 prop_menu = IDP_New(IDP_GROUP, &val, __func__); /* dummy, name is unimportant  */
879                                 IDP_AddToGroup(prop_menu, (prop_menu_name = IDP_NewString("", "name", sizeof(mt->idname))));
880                         }
881
882                         IDP_AssignString(prop_menu_name, mt->idname, sizeof(mt->idname));
883
884                         if (WM_key_event_operator_string(C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, FALSE,
885                                                          buf, sizeof(buf)))
886                         {
887                                 ui_but_add_shortcut(but, buf, FALSE);
888                         }
889                 }
890         }
891
892         if (prop_menu) {
893                 IDP_FreeProperty(prop_menu);
894                 MEM_freeN(prop_menu);
895         }
896
897 #undef UI_MENU_KEY_STR_CAT
898
899 }
900
901 void uiEndBlock(const bContext *C, uiBlock *block)
902 {
903         uiBut *but;
904         Scene *scene = CTX_data_scene(C);
905
906         /* inherit flags from 'old' buttons that was drawn here previous, based
907          * on matching buttons, we need this to make button event handling non
908          * blocking, while still allowing buttons to be remade each redraw as it
909          * is expected by blender code */
910         for (but = block->buttons.first; but; but = but->next) {
911                 if (ui_but_update_from_old_block(C, block, &but))
912                         ui_check_but(but);
913                 
914                 /* temp? Proper check for graying out */
915                 if (but->optype) {
916                         wmOperatorType *ot = but->optype;
917
918                         if (but->context)
919                                 CTX_store_set((bContext *)C, but->context);
920
921                         if (ot == NULL || WM_operator_poll_context((bContext *)C, ot, but->opcontext) == 0) {
922                                 but->flag |= UI_BUT_DISABLED;
923                                 but->lock = TRUE;
924                         }
925
926                         if (but->context)
927                                 CTX_store_set((bContext *)C, NULL);
928                 }
929
930                 ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f);
931         }
932
933         if (block->oldblock) {
934                 block->auto_open = block->oldblock->auto_open;
935                 block->auto_open_last = block->oldblock->auto_open_last;
936                 block->tooltipdisabled = block->oldblock->tooltipdisabled;
937                 copy_v3_v3(ui_block_hsv_get(block),
938                            ui_block_hsv_get(block->oldblock));
939
940                 block->oldblock = NULL;
941         }
942
943         /* handle pending stuff */
944         if (block->layouts.first) {
945                 uiBlockLayoutResolve(block, NULL, NULL);
946         }
947         ui_block_do_align(block);
948         if ((block->flag & UI_BLOCK_LOOP) && (block->flag & UI_BLOCK_NUMSELECT)) {
949                 ui_menu_block_set_keyaccels(block); /* could use a different flag to check */
950         }
951
952         if (block->flag & UI_BLOCK_LOOP) {
953                 ui_menu_block_set_keymaps(C, block);
954         }
955         
956         /* after keymaps! */
957         switch (block->bounds_type) {
958                 case UI_BLOCK_BOUNDS_NONE:
959                         break;
960                 case UI_BLOCK_BOUNDS:
961                         ui_bounds_block(block);
962                         break;
963                 case UI_BLOCK_BOUNDS_TEXT:
964                         ui_text_bounds_block(block, 0.0f);
965                         break;
966                 case UI_BLOCK_BOUNDS_POPUP_CENTER:
967                         ui_centered_bounds_block(C, block);
968                         break;
969
970                         /* fallback */
971                 case UI_BLOCK_BOUNDS_POPUP_MOUSE:
972                 case UI_BLOCK_BOUNDS_POPUP_MENU:
973                         ui_popup_bounds_block(C, block, block->bounds_type);
974                         break;
975         }
976
977         if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
978                 uiBoundsBlock(block, 0);
979         }
980         if (block->flag & UI_BUT_ALIGN) {
981                 uiBlockEndAlign(block);
982         }
983
984         block->endblock = 1;
985 }
986
987 /* ************** BLOCK DRAWING FUNCTION ************* */
988
989 void ui_fontscale(short *points, float aspect)
990 {
991         if (aspect < 0.9f || aspect > 1.1f) {
992                 float pointsf = *points;
993                 
994                 /* for some reason scaling fonts goes too fast compared to widget size */
995                 /* XXX not true anymore? (ton) */
996                 //aspect = sqrt(aspect);
997                 pointsf /= aspect;
998                 
999                 if (aspect > 1.0f)
1000                         *points = ceilf(pointsf);
1001                 else
1002                         *points = floorf(pointsf);
1003         }
1004 }
1005
1006 /* project button or block (but==NULL) to pixels in regionspace */
1007 static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
1008 {
1009         rctf rectf = (but) ? but->rect : block->rect;
1010         
1011         ui_block_to_window_fl(ar, block, &rectf.xmin, &rectf.ymin);
1012         ui_block_to_window_fl(ar, block, &rectf.xmax, &rectf.ymax);
1013         
1014         rectf.xmin -= ar->winrct.xmin;
1015         rectf.ymin -= ar->winrct.ymin;
1016         rectf.xmax -= ar->winrct.xmin;
1017         rectf.ymax -= ar->winrct.ymin;
1018
1019         rect->xmin = floorf(rectf.xmin);
1020         rect->ymin = floorf(rectf.ymin);
1021         rect->xmax = floorf(rectf.xmax);
1022         rect->ymax = floorf(rectf.ymax);
1023 }
1024
1025 /* uses local copy of style, to scale things down, and allow widgets to change stuff */
1026 void uiDrawBlock(const bContext *C, uiBlock *block)
1027 {
1028         uiStyle style = *UI_GetStyleDraw();  /* XXX pass on as arg */
1029         ARegion *ar;
1030         uiBut *but;
1031         rcti rect;
1032         int multisample_enabled;
1033         
1034         /* get menu region or area region */
1035         ar = CTX_wm_menu(C);
1036         if (!ar)
1037                 ar = CTX_wm_region(C);
1038
1039         if (!block->endblock)
1040                 uiEndBlock(C, block);
1041
1042         /* disable AA, makes widgets too blurry */
1043         multisample_enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
1044         if (multisample_enabled)
1045                 glDisable(GL_MULTISAMPLE_ARB);
1046
1047         /* we set this only once */
1048         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1049         
1050         /* scale fonts */
1051         ui_fontscale(&style.paneltitle.points, block->aspect);
1052         ui_fontscale(&style.grouplabel.points, block->aspect);
1053         ui_fontscale(&style.widgetlabel.points, block->aspect);
1054         ui_fontscale(&style.widget.points, block->aspect);
1055         
1056         /* scale block min/max to rect */
1057         ui_but_to_pixelrect(&rect, ar, block, NULL);
1058         
1059         /* pixel space for AA widgets */
1060         glMatrixMode(GL_PROJECTION);
1061         glPushMatrix();
1062         glMatrixMode(GL_MODELVIEW);
1063         glPushMatrix();
1064         glLoadIdentity();
1065         
1066         wmOrtho2(-0.01f, ar->winx - 0.01f, -0.01f, ar->winy - 0.01f);
1067         
1068         /* back */
1069         if (block->flag & UI_BLOCK_LOOP)
1070                 ui_draw_menu_back(&style, block, &rect);
1071         else if (block->panel)
1072                 ui_draw_aligned_panel(&style, block, &rect);
1073
1074         /* widgets */
1075         for (but = block->buttons.first; but; but = but->next) {
1076                 if (!(but->flag & (UI_HIDDEN | UI_SCROLLED))) {
1077                         ui_but_to_pixelrect(&rect, ar, block, but);
1078                 
1079                         /* XXX: figure out why invalid coordinates happen when closing render window */
1080                         /* and material preview is redrawn in main window (temp fix for bug #23848) */
1081                         if (rect.xmin < rect.xmax && rect.ymin < rect.ymax)
1082                                 ui_draw_but(C, ar, &style, but, &rect);
1083                 }
1084         }
1085         
1086         /* restore matrix */
1087         glMatrixMode(GL_PROJECTION);
1088         glPopMatrix();
1089         glMatrixMode(GL_MODELVIEW);
1090         glPopMatrix();
1091
1092         if (multisample_enabled)
1093                 glEnable(GL_MULTISAMPLE_ARB);
1094         
1095         ui_draw_links(block);
1096 }
1097
1098 /* ************* EVENTS ************* */
1099
1100 int ui_is_but_push_ex(uiBut *but, double *value)
1101 {
1102         int is_push = false;  /* (0 == UNSELECT), (1 == SELECT), (-1 == DO-NOHING) */
1103
1104         if (but->bit) {
1105                 const bool state = ELEM3(but->type, TOGN, ICONTOGN, OPTIONN) ? false : true;
1106                 int lvalue;
1107                 UI_GET_BUT_VALUE_INIT(but, *value);
1108                 lvalue = (int)*value;
1109                 if (UI_BITBUT_TEST(lvalue, (but->bitnr))) {
1110                         is_push = state;
1111                 }
1112                 else {
1113                         is_push = !state;
1114                 }
1115         }
1116         else {
1117                 switch (but->type) {
1118                         case BUT:
1119                         case HOTKEYEVT:
1120                         case KEYEVT:
1121                         case COLOR:
1122                                 is_push = -1;
1123                                 break;
1124                         case TOGBUT:
1125                         case TOG:
1126                         case TOGR:
1127                         case TOG3:
1128                         case BUT_TOGDUAL:
1129                         case ICONTOG:
1130                         case OPTION:
1131                                 UI_GET_BUT_VALUE_INIT(but, *value);
1132                                 if (*value != (double)but->hardmin) is_push = true;
1133                                 break;
1134                         case ICONTOGN:
1135                         case TOGN:
1136                         case OPTIONN:
1137                                 UI_GET_BUT_VALUE_INIT(but, *value);
1138                                 if (*value == 0.0) is_push = true;
1139                                 break;
1140                         case ROW:
1141                         case LISTROW:
1142                                 UI_GET_BUT_VALUE_INIT(but, *value);
1143                                 /* support for rna enum buts */
1144                                 if (but->rnaprop && (RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG)) {
1145                                         if ((int)*value & (int)but->hardmax) is_push = true;
1146                                 }
1147                                 else {
1148                                         if (*value == (double)but->hardmax) is_push = true;
1149                                 }
1150                                 break;
1151                         default:
1152                                 is_push = -1;
1153                                 break;
1154                 }
1155         }
1156
1157         return is_push;
1158 }
1159 int ui_is_but_push(uiBut *but)
1160 {
1161         double value = UI_BUT_VALUE_UNSET;
1162         return ui_is_but_push_ex(but, &value);
1163 }
1164
1165 static void ui_check_but_select(uiBut *but, double *value)
1166 {
1167         switch (ui_is_but_push_ex(but, value)) {
1168                 case true:
1169                         but->flag |= UI_SELECT;
1170                         break;
1171                 case false:
1172                         but->flag &= ~UI_SELECT;
1173                         break;
1174         }
1175 }
1176
1177 static uiBut *ui_find_inlink(uiBlock *block, void *poin)
1178 {
1179         uiBut *but;
1180         
1181         but = block->buttons.first;
1182         while (but) {
1183                 if (but->type == INLINK) {
1184                         if (but->poin == poin) return but;
1185                 }
1186                 but = but->next;
1187         }
1188         return NULL;
1189 }
1190
1191 static void ui_add_link_line(ListBase *listb, uiBut *but, uiBut *bt)
1192 {
1193         uiLinkLine *line;
1194         
1195         line = MEM_callocN(sizeof(uiLinkLine), "linkline");
1196         BLI_addtail(listb, line);
1197         line->from = but;
1198         line->to = bt;
1199 }
1200
1201 uiBut *uiFindInlink(uiBlock *block, void *poin)
1202 {
1203         return ui_find_inlink(block, poin);
1204 }
1205
1206 void uiComposeLinks(uiBlock *block)
1207 {
1208         uiBut *but, *bt;
1209         uiLink *link;
1210         void ***ppoin;
1211         int a;
1212         
1213         but = block->buttons.first;
1214         while (but) {
1215                 if (but->type == LINK) {
1216                         link = but->link;
1217                         
1218                         /* for all pointers in the array */
1219                         if (link) {
1220                                 if (link->ppoin) {
1221                                         ppoin = link->ppoin;
1222                                         for (a = 0; a < *(link->totlink); a++) {
1223                                                 bt = ui_find_inlink(block, (*ppoin)[a]);
1224                                                 if (bt) {
1225                                                         ui_add_link_line(&link->lines, but, bt);
1226                                                 }
1227                                         }
1228                                 }
1229                                 else if (link->poin) {
1230                                         bt = ui_find_inlink(block, *(link->poin) );
1231                                         if (bt) {
1232                                                 ui_add_link_line(&link->lines, but, bt);
1233                                         }
1234                                 }
1235                         }
1236                 }
1237                 but = but->next;
1238         }
1239 }
1240
1241
1242 /* ************************************************ */
1243
1244 void uiBlockSetButLock(uiBlock *block, int val, const char *lockstr)
1245 {
1246         if (val) {
1247                 block->lock = val ? TRUE : FALSE;
1248                 block->lockstr = lockstr;
1249         }
1250 }
1251
1252 void uiBlockClearButLock(uiBlock *block)
1253 {
1254         block->lock = FALSE;
1255         block->lockstr = NULL;
1256 }
1257
1258 /* *************************************************************** */
1259
1260 void ui_delete_linkline(uiLinkLine *line, uiBut *but)
1261 {
1262         uiLink *link;
1263         int a, b;
1264         
1265         BLI_remlink(&but->link->lines, line);
1266
1267         link = line->from->link;
1268
1269         /* are there more pointers allowed? */
1270         if (link->ppoin) {
1271                 
1272                 if (*(link->totlink) == 1) {
1273                         *(link->totlink) = 0;
1274                         MEM_freeN(*(link->ppoin));
1275                         *(link->ppoin) = NULL;
1276                 }
1277                 else {
1278                         b = 0;
1279                         for (a = 0; a < (*(link->totlink)); a++) {
1280                                 if ((*(link->ppoin))[a] != line->to->poin) {
1281                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1282                                         b++;
1283                                 }
1284                         }
1285                         (*(link->totlink))--;
1286                 }
1287         }
1288         else {
1289                 *(link->poin) = NULL;
1290         }
1291
1292         MEM_freeN(line);
1293         //REDRAW
1294 }
1295
1296 /* *********************** data get/set ***********************
1297  * this either works with the pointed to data, or can work with
1298  * an edit override pointer while dragging for example */
1299
1300 /* for buttons pointing to color for example */
1301 void ui_get_but_vectorf(uiBut *but, float vec[3])
1302 {
1303         PropertyRNA *prop;
1304         int a;
1305
1306         if (but->editvec) {
1307                 copy_v3_v3(vec, but->editvec);
1308         }
1309
1310         if (but->rnaprop) {
1311                 prop = but->rnaprop;
1312
1313                 zero_v3(vec);
1314
1315                 if (RNA_property_type(prop) == PROP_FLOAT) {
1316                         int tot = RNA_property_array_length(&but->rnapoin, prop);
1317                         BLI_assert(tot > 0);
1318                         if (tot == 3) {
1319                                 RNA_property_float_get_array(&but->rnapoin, prop, vec);
1320                         }
1321                         else {
1322                                 tot = min_ii(tot, 3);
1323                                 for (a = 0; a < tot; a++) {
1324                                         vec[a] = RNA_property_float_get_index(&but->rnapoin, prop, a);
1325                                 }
1326                         }
1327                 }
1328         }
1329         else if (but->pointype == UI_BUT_POIN_CHAR) {
1330                 char *cp = (char *)but->poin;
1331
1332                 vec[0] = ((float)cp[0]) / 255.0f;
1333                 vec[1] = ((float)cp[1]) / 255.0f;
1334                 vec[2] = ((float)cp[2]) / 255.0f;
1335         }
1336         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1337                 float *fp = (float *)but->poin;
1338                 copy_v3_v3(vec, fp);
1339         }
1340         else {
1341                 if (but->editvec == NULL) {
1342                         fprintf(stderr, "%s: can't get color, should never happen\n", __func__);
1343                         zero_v3(vec);
1344                 }
1345         }
1346
1347         if (but->type == BUT_NORMAL) {
1348                 normalize_v3(vec);
1349         }
1350 }
1351
1352 /* for buttons pointing to color for example */
1353 void ui_set_but_vectorf(uiBut *but, const float vec[3])
1354 {
1355         PropertyRNA *prop;
1356
1357         if (but->editvec) {
1358                 copy_v3_v3(but->editvec, vec);
1359         }
1360
1361         if (but->rnaprop) {
1362                 prop = but->rnaprop;
1363
1364                 if (RNA_property_type(prop) == PROP_FLOAT) {
1365                         int tot;
1366                         int a;
1367
1368                         tot = RNA_property_array_length(&but->rnapoin, prop);
1369                         BLI_assert(tot > 0);
1370                         if (tot == 3) {
1371                                 RNA_property_float_set_array(&but->rnapoin, prop, vec);
1372                         }
1373                         else {
1374                                 tot = min_ii(tot, 3);
1375                                 for (a = 0; a < tot; a++) {
1376                                         RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
1377                                 }
1378                         }
1379                 }
1380         }
1381         else if (but->pointype == UI_BUT_POIN_CHAR) {
1382                 char *cp = (char *)but->poin;
1383                 cp[0] = (char)(0.5f + vec[0] * 255.0f);
1384                 cp[1] = (char)(0.5f + vec[1] * 255.0f);
1385                 cp[2] = (char)(0.5f + vec[2] * 255.0f);
1386         }
1387         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1388                 float *fp = (float *)but->poin;
1389                 copy_v3_v3(fp, vec);
1390         }
1391 }
1392
1393 int ui_is_but_float(uiBut *but)
1394 {
1395         if (but->pointype == UI_BUT_POIN_FLOAT && but->poin)
1396                 return 1;
1397         
1398         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_FLOAT)
1399                 return 1;
1400         
1401         return 0;
1402 }
1403
1404 int ui_is_but_bool(uiBut *but)
1405 {
1406         if (ELEM5(but->type, TOG, TOGN, TOGR, ICONTOG, ICONTOGN))
1407                 return 1;
1408
1409         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_BOOLEAN)
1410                 return 1;
1411
1412         return 0;
1413 }
1414
1415
1416 int ui_is_but_unit(uiBut *but)
1417 {
1418         UnitSettings *unit = but->block->unit;
1419         const int unit_type = uiButGetUnitType(but);
1420
1421         if (unit_type == PROP_UNIT_NONE)
1422                 return 0;
1423
1424 #if 1 /* removed so angle buttons get correct snapping */
1425         if (unit->system_rotation == USER_UNIT_ROT_RADIANS && unit_type == PROP_UNIT_ROTATION)
1426                 return 0;
1427 #endif
1428         
1429         /* for now disable time unit conversion */
1430         if (unit_type == PROP_UNIT_TIME)
1431                 return 0;
1432
1433         if (unit->system == USER_UNIT_NONE) {
1434                 if (unit_type != PROP_UNIT_ROTATION) {
1435                         return 0;
1436                 }
1437         }
1438
1439         return 1;
1440 }
1441
1442 int ui_is_but_rna_valid(uiBut *but)
1443 {
1444         if (but->rnaprop == NULL || RNA_struct_contains_property(&but->rnapoin, but->rnaprop)) {
1445                 return TRUE;
1446         }
1447         else {
1448                 printf("property removed %s: %p\n", but->drawstr, but->rnaprop);
1449                 return FALSE;
1450         }
1451 }
1452
1453 double ui_get_but_val(uiBut *but)
1454 {
1455         PropertyRNA *prop;
1456         double value = 0.0;
1457
1458         if (but->editval) { return *(but->editval); }
1459         if (but->poin == NULL && but->rnapoin.data == NULL) return 0.0;
1460
1461         if (but->rnaprop) {
1462                 prop = but->rnaprop;
1463
1464                 BLI_assert(but->rnaindex != -1);
1465
1466                 switch (RNA_property_type(prop)) {
1467                         case PROP_BOOLEAN:
1468                                 if (RNA_property_array_check(prop))
1469                                         value = RNA_property_boolean_get_index(&but->rnapoin, prop, but->rnaindex);
1470                                 else
1471                                         value = RNA_property_boolean_get(&but->rnapoin, prop);
1472                                 break;
1473                         case PROP_INT:
1474                                 if (RNA_property_array_check(prop))
1475                                         value = RNA_property_int_get_index(&but->rnapoin, prop, but->rnaindex);
1476                                 else
1477                                         value = RNA_property_int_get(&but->rnapoin, prop);
1478                                 break;
1479                         case PROP_FLOAT:
1480                                 if (RNA_property_array_check(prop))
1481                                         value = RNA_property_float_get_index(&but->rnapoin, prop, but->rnaindex);
1482                                 else
1483                                         value = RNA_property_float_get(&but->rnapoin, prop);
1484                                 break;
1485                         case PROP_ENUM:
1486                                 value = RNA_property_enum_get(&but->rnapoin, prop);
1487                                 break;
1488                         default:
1489                                 value = 0.0;
1490                                 break;
1491                 }
1492         }
1493         else if (but->type == HSVSLI) {
1494                 float *fp, hsv[3];
1495                 
1496                 fp = (but->editvec) ? but->editvec : (float *)but->poin;
1497                 rgb_to_hsv_v(fp, hsv);
1498
1499                 switch (but->str[0]) {
1500                         case 'H': value = hsv[0]; break;
1501                         case 'S': value = hsv[1]; break;
1502                         case 'V': value = hsv[2]; break;
1503                 }
1504         }
1505         else if (but->pointype == UI_BUT_POIN_CHAR) {
1506                 value = *(char *)but->poin;
1507         }
1508         else if (but->pointype == UI_BUT_POIN_SHORT) {
1509                 value = *(short *)but->poin;
1510         }
1511         else if (but->pointype == UI_BUT_POIN_INT) {
1512                 value = *(int *)but->poin;
1513         }
1514         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1515                 value = *(float *)but->poin;
1516         }
1517
1518         return value;
1519 }
1520
1521 void ui_set_but_val(uiBut *but, double value)
1522 {
1523         PropertyRNA *prop;
1524
1525         /* value is a hsv value: convert to rgb */
1526         if (but->rnaprop) {
1527                 prop = but->rnaprop;
1528
1529                 if (RNA_property_editable(&but->rnapoin, prop)) {
1530                         switch (RNA_property_type(prop)) {
1531                                 case PROP_BOOLEAN:
1532                                         if (RNA_property_array_length(&but->rnapoin, prop))
1533                                                 RNA_property_boolean_set_index(&but->rnapoin, prop, but->rnaindex, value);
1534                                         else
1535                                                 RNA_property_boolean_set(&but->rnapoin, prop, value);
1536                                         break;
1537                                 case PROP_INT:
1538                                         if (RNA_property_array_length(&but->rnapoin, prop))
1539                                                 RNA_property_int_set_index(&but->rnapoin, prop, but->rnaindex, (int)value);
1540                                         else
1541                                                 RNA_property_int_set(&but->rnapoin, prop, (int)value);
1542                                         break;
1543                                 case PROP_FLOAT:
1544                                         if (RNA_property_array_length(&but->rnapoin, prop))
1545                                                 RNA_property_float_set_index(&but->rnapoin, prop, but->rnaindex, value);
1546                                         else
1547                                                 RNA_property_float_set(&but->rnapoin, prop, value);
1548                                         break;
1549                                 case PROP_ENUM:
1550                                         if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1551                                                 int ivalue = (int)value;
1552                                                 ivalue ^= RNA_property_enum_get(&but->rnapoin, prop); /* toggle for enum/flag buttons */
1553                                                 RNA_property_enum_set(&but->rnapoin, prop, ivalue);
1554                                         }
1555                                         else {
1556                                                 RNA_property_enum_set(&but->rnapoin, prop, value);
1557                                         }
1558                                         break;
1559                                 default:
1560                                         break;
1561                         }
1562                 }
1563
1564                 /* we can't be sure what RNA set functions actually do,
1565                  * so leave this unset */
1566                 value = UI_BUT_VALUE_UNSET;
1567         }
1568         else if (but->pointype == 0) {
1569                 /* pass */
1570         }
1571         else if (but->type == HSVSLI) {
1572                 float *fp, hsv[3];
1573                 
1574                 fp = (but->editvec) ? but->editvec : (float *)but->poin;
1575                 rgb_to_hsv_v(fp, hsv);
1576                 
1577                 switch (but->str[0]) {
1578                         case 'H': hsv[0] = value; break;
1579                         case 'S': hsv[1] = value; break;
1580                         case 'V': hsv[2] = value; break;
1581                 }
1582                 
1583                 hsv_to_rgb_v(hsv, fp);
1584                 
1585         }
1586         else {
1587                 /* first do rounding */
1588                 if (but->pointype == UI_BUT_POIN_CHAR) {
1589                         value = (char)floor(value + 0.5);
1590                 }
1591                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1592                         /* gcc 3.2.1 seems to have problems
1593                          * casting a double like 32772.0 to
1594                          * a short so we cast to an int, then
1595                          * to a short.
1596                          *
1597                          * Update: even in gcc.4.6 using intermediate int cast gives -32764,
1598                          * where as a direct cast from double to short gives -32768,
1599                          * if this difference isn't important we could remove this hack,
1600                          * since we dont support gcc3 anymore - Campbell */
1601                         int gcckludge;
1602                         gcckludge = (int) floor(value + 0.5);
1603                         value = (short)gcckludge;
1604                 }
1605                 else if (but->pointype == UI_BUT_POIN_INT)
1606                         value = (int)floor(value + 0.5);
1607                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1608                         float fval = (float)value;
1609                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1610                         value = fval;
1611                 }
1612                 
1613                 /* then set value with possible edit override */
1614                 if (but->editval)
1615                         value = *but->editval = value;
1616                 else if (but->pointype == UI_BUT_POIN_CHAR)
1617                         value = *((char *)but->poin) = (char)value;
1618                 else if (but->pointype == UI_BUT_POIN_SHORT)
1619                         value = *((short *)but->poin) = (short)value;
1620                 else if (but->pointype == UI_BUT_POIN_INT)
1621                         value = *((int *)but->poin) = (int)value;
1622                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1623                         value = *((float *)but->poin) = (float)value;
1624         }
1625
1626         ui_check_but_select(but, &value);
1627 }
1628
1629 int ui_get_but_string_max_length(uiBut *but)
1630 {
1631         if (ELEM3(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK))
1632                 return but->hardmax;
1633         else if (but->type == IDPOIN)
1634                 return MAX_ID_NAME - 2;
1635         else
1636                 return UI_MAX_DRAW_STR;
1637 }
1638
1639 static double ui_get_but_scale_unit(uiBut *but, double value)
1640 {
1641         UnitSettings *unit = but->block->unit;
1642         int unit_type = uiButGetUnitType(but);
1643
1644         if (unit_type == PROP_UNIT_LENGTH) {
1645                 return value * (double)unit->scale_length;
1646         }
1647         else if (unit_type == PROP_UNIT_AREA) {
1648                 return value * pow(unit->scale_length, 2);
1649         }
1650         else if (unit_type == PROP_UNIT_VOLUME) {
1651                 return value * pow(unit->scale_length, 3);
1652         }
1653         else if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1654                 Scene *scene = CTX_data_scene(but->block->evil_C);
1655                 return FRA2TIME(value);
1656         }
1657         else {
1658                 return value;
1659         }
1660 }
1661
1662 /* str will be overwritten */
1663 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1664 {
1665         if (ui_is_but_unit(but)) {
1666                 UnitSettings *unit = but->block->unit;
1667                 int unit_type = uiButGetUnitType(but);
1668                 char *orig_str;
1669                 
1670                 orig_str = MEM_callocN(sizeof(char) * maxlen + 1, "textedit sub str");
1671                 memcpy(orig_str, str, maxlen);
1672                 
1673                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1674                 
1675                 MEM_freeN(orig_str);
1676         }
1677 }
1678
1679 /**
1680  * \param float_precision  Override the button precision.
1681  */
1682 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, int pad, int float_precision)
1683 {
1684         UnitSettings *unit = but->block->unit;
1685         int do_split = unit->flag & USER_UNIT_OPT_SPLIT;
1686         int unit_type = uiButGetUnitType(but);
1687         int precision;
1688
1689         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
1690
1691         /* Use precision override? */
1692         if (float_precision == -1) {
1693                 /* Sanity checks */
1694                 precision = (int)but->a2;
1695                 if      (precision > PRECISION_FLOAT_MAX) precision = PRECISION_FLOAT_MAX;
1696                 else if (precision == 0)                  precision = 2;
1697         }
1698         else {
1699                 precision = float_precision;
1700         }
1701
1702         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
1703                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
1704 }
1705
1706 static float ui_get_but_step_unit(uiBut *but, float step_default)
1707 {
1708         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
1709         float step;
1710
1711         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1712
1713         if (step > 0.0f) { /* -1 is an error value */
1714                 return (float)((double)step / ui_get_but_scale_unit(but, 1.0)) * 100.0f;
1715         }
1716         else {
1717                 return step_default;
1718         }
1719 }
1720
1721 /**
1722  * \param float_precision  For number buttons the precission to use or -1 to fallback to the button default.
1723  */
1724 void ui_get_but_string_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision)
1725 {
1726         if (but->rnaprop && ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1727                 PropertyType type;
1728                 const char *buf = NULL;
1729                 int buf_len;
1730
1731                 type = RNA_property_type(but->rnaprop);
1732
1733                 if (type == PROP_STRING) {
1734                         /* RNA string */
1735                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
1736                 }
1737                 else if (type == PROP_ENUM) {
1738                         /* RNA enum */
1739                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
1740                         if (RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &buf)) {
1741                                 BLI_strncpy(str, buf, maxlen);
1742                                 buf = str;
1743                         }
1744                 }
1745                 else if (type == PROP_POINTER) {
1746                         /* RNA pointer */
1747                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1748                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
1749                 }
1750                 else {
1751                         BLI_assert(0);
1752                 }
1753
1754                 if (!buf) {
1755                         str[0] = '\0';
1756                 }
1757                 else if (buf && buf != str) {
1758                         /* string was too long, we have to truncate */
1759                         memcpy(str, buf, MIN2(maxlen, (size_t)buf_len + 1));
1760                         MEM_freeN((void *)buf);
1761                 }
1762         }
1763         else if (but->type == IDPOIN) {
1764                 /* ID pointer */
1765                 if (but->idpoin_idpp) { /* Can be NULL for ID properties by python */
1766                         ID *id = *(but->idpoin_idpp);
1767                         if (id) {
1768                                 BLI_strncpy(str, id->name + 2, maxlen);
1769                                 return;
1770                         }
1771                 }
1772                 str[0] = '\0';
1773                 return;
1774         }
1775         else if (but->type == TEX) {
1776                 /* string */
1777                 BLI_strncpy(str, but->poin, maxlen);
1778                 return;
1779         }
1780         else if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1781                 /* string */
1782                 BLI_strncpy(str, but->poin, maxlen);
1783                 return;
1784         }
1785         else if (ui_but_anim_expression_get(but, str, maxlen)) {
1786                 /* driver expression */
1787         }
1788         else {
1789                 /* number editing */
1790                 double value;
1791
1792                 value = ui_get_but_val(but);
1793
1794                 if (ui_is_but_float(but)) {
1795                         if (ui_is_but_unit(but)) {
1796                                 ui_get_but_string_unit(but, str, maxlen, value, 0, float_precision);
1797                         }
1798                         else {
1799                                 const int prec = (float_precision == -1) ? ui_but_float_precision(but, value) : float_precision;
1800                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
1801                         }
1802                 }
1803                 else
1804                         BLI_snprintf(str, maxlen, "%d", (int)value);
1805         }
1806 }
1807 void ui_get_but_string(uiBut *but, char *str, const size_t maxlen)
1808 {
1809         ui_get_but_string_ex(but, str, maxlen, -1);
1810 }
1811
1812 #ifdef WITH_PYTHON
1813
1814 static int ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
1815 {
1816         char str_unit_convert[256];
1817         const int unit_type = uiButGetUnitType(but);
1818
1819         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
1820
1821         /* ugly, use the draw string to get the value,
1822          * this could cause problems if it includes some text which resolves to a unit */
1823         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
1824                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1825
1826         return (BPY_button_exec(C, str_unit_convert, value, TRUE) != -1);
1827 }
1828
1829 #endif /* WITH_PYTHON */
1830
1831
1832 int ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
1833 {
1834         int ok = FALSE;
1835
1836 #ifdef WITH_PYTHON
1837
1838         if (str[0] != '\0') {
1839                 bool is_unit_but = (ui_is_but_float(but) && ui_is_but_unit(but));
1840                 /* only enable verbose if we won't run again with units */
1841                 if (BPY_button_exec(C, str, value, is_unit_but == false) != -1) {
1842                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
1843                         if (is_unit_but) {
1844                                 char str_new[128];
1845
1846                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
1847                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
1848                         }
1849                         else {
1850                                 ok = TRUE; /* parse normal string via py (no unit conversion needed) */
1851                         }
1852                 }
1853                 else if (is_unit_but) {
1854                         /* parse failed, this is a unit but so run replacements and parse again */
1855                         ok = ui_set_but_string_eval_num_unit(C, but, str, value);
1856                 }
1857         }
1858
1859 #else /* WITH_PYTHON */
1860
1861         *value = atof(str);
1862         ok = TRUE;
1863
1864         (void)C;
1865         (void)but;
1866
1867 #endif /* WITH_PYTHON */
1868
1869         return ok;
1870 }
1871
1872
1873 int ui_set_but_string(bContext *C, uiBut *but, const char *str)
1874 {
1875         if (but->rnaprop && ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1876                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
1877                         PropertyType type;
1878
1879                         type = RNA_property_type(but->rnaprop);
1880
1881                         if (type == PROP_STRING) {
1882                                 /* RNA string */
1883                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
1884                                 return 1;
1885                         }
1886                         else if (type == PROP_POINTER) {
1887                                 /* RNA pointer */
1888                                 PointerRNA ptr, rptr;
1889                                 PropertyRNA *prop;
1890
1891                                 if (str == NULL || str[0] == '\0') {
1892                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
1893                                         return 1;
1894                                 }
1895                                 else {
1896                                         ptr = but->rnasearchpoin;
1897                                         prop = but->rnasearchprop;
1898                                         
1899                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
1900                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
1901
1902                                         return 1;
1903                                 }
1904
1905                                 return 0;
1906                         }
1907                         else if (type == PROP_ENUM) {
1908                                 int value;
1909                                 if (RNA_property_enum_value(but->block->evil_C, &but->rnapoin, but->rnaprop, str, &value)) {
1910                                         RNA_property_enum_set(&but->rnapoin, but->rnaprop, value);
1911                                         return 1;
1912                                 }
1913                                 return 0;
1914                         }
1915                         else {
1916                                 BLI_assert(0);
1917                         }
1918                 }
1919         }
1920         else if (but->type == IDPOIN) {
1921                 /* ID pointer */
1922                 but->idpoin_func(C, str, but->idpoin_idpp);
1923                 return 1;
1924         }
1925         else if (but->type == TEX) {
1926                 /* string */
1927                 if (ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
1928                 else BLI_strncpy(but->poin, str, but->hardmax);
1929
1930                 return 1;
1931         }
1932         else if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
1933                 /* string */
1934                 BLI_strncpy(but->poin, str, but->hardmax);
1935                 return 1;
1936         }
1937         else if (ui_but_anim_expression_set(but, str)) {
1938                 /* driver expression */
1939                 return 1;
1940         }
1941         else if (str[0] == '#') {
1942                 /* shortcut to create new driver expression (versus immediate Py-execution) */
1943                 return ui_but_anim_expression_create(but, str + 1);
1944         }
1945         else {
1946                 /* number editing */
1947                 double value;
1948
1949                 if (ui_set_but_string_eval_num(C, but, str, &value) == FALSE) {
1950                         return 0;
1951                 }
1952
1953                 if (!ui_is_but_float(but)) value = (int)floor(value + 0.5);
1954                 if (but->type == NUMABS) value = fabs(value);
1955
1956                 /* not that we use hard limits here */
1957                 if (value < (double)but->hardmin) value = but->hardmin;
1958                 if (value > (double)but->hardmax) value = but->hardmax;
1959
1960                 ui_set_but_val(but, value);
1961                 return 1;
1962         }
1963
1964         return 0;
1965 }
1966
1967 void ui_set_but_default(bContext *C, short all)
1968 {
1969         PointerRNA ptr;
1970
1971         WM_operator_properties_create(&ptr, "UI_OT_reset_default_button");
1972         RNA_boolean_set(&ptr, "all", all);
1973         WM_operator_name_call(C, "UI_OT_reset_default_button", WM_OP_EXEC_DEFAULT, &ptr);
1974         WM_operator_properties_free(&ptr);
1975 }
1976
1977 static double soft_range_round_up(double value, double max)
1978 {
1979         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
1980          * checking for 0.0 prevents floating point exceptions */
1981         double newmax = (value != 0.0) ? pow(10.0, ceil(log(value) / M_LN10)) : 0.0;
1982
1983         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
1984                 return newmax * 0.2;
1985         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
1986                 return newmax * 0.5;
1987         else
1988                 return newmax;
1989 }
1990
1991 static double soft_range_round_down(double value, double max)
1992 {
1993         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
1994          * checking for 0.0 prevents floating point exceptions */
1995         double newmax = (value != 0.0) ? pow(10.0, floor(log(value) / M_LN10)) : 0.0;
1996
1997         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
1998                 return newmax * 5.0;
1999         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
2000                 return newmax * 2.0;
2001         else
2002                 return newmax;
2003 }
2004
2005 /* note: this could be split up into functions which handle arrays and not */
2006 static void ui_set_but_soft_range(uiBut *but)
2007 {
2008         /* ideally we would not limit this but practically, its more then
2009          * enough worst case is very long vectors wont use a smart soft-range
2010          * which isn't so bad. */
2011
2012         if (but->rnaprop) {
2013                 const PropertyType type = RNA_property_type(but->rnaprop);
2014                 double softmin, softmax /*, step, precision*/;
2015                 double value_min;
2016                 double value_max;
2017
2018                 /* clamp button range to something reasonable in case
2019                  * we get -inf/inf from RNA properties */
2020                 if (type == PROP_INT) {
2021                         const bool is_array = RNA_property_array_check(but->rnaprop);
2022                         int imin, imax, istep;
2023
2024                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
2025                         softmin = (imin == INT_MIN) ? -1e4 : imin;
2026                         softmax = (imin == INT_MAX) ? 1e4 : imax;
2027                         /*step = istep;*/ /*UNUSED*/
2028                         /*precision = 1;*/ /*UNUSED*/
2029
2030                         if (is_array) {
2031                                 int value_range[2];
2032                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2033                                 value_min = (double)value_range[0];
2034                                 value_max = (double)value_range[1];
2035                         }
2036                         else {
2037                                 value_min = value_max = (double)RNA_property_int_get(&but->rnapoin, but->rnaprop);
2038                         }
2039                 }
2040                 else if (type == PROP_FLOAT) {
2041                         const bool is_array = RNA_property_array_check(but->rnaprop);
2042                         float fmin, fmax, fstep, fprecision;
2043
2044                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
2045                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
2046                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
2047                         /*step = fstep;*/ /*UNUSED*/
2048                         /*precision = fprecision;*/ /*UNUSED*/
2049
2050                         if (is_array) {
2051                                 float value_range[2];
2052                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2053                                 value_min = (double)value_range[0];
2054                                 value_max = (double)value_range[1];
2055                         }
2056                         else {
2057                                 value_min = value_max = (double)RNA_property_float_get(&but->rnapoin, but->rnaprop);
2058                         }
2059                 }
2060                 else {
2061                         return;
2062                 }
2063
2064                 /* if the value goes out of the soft/max range, adapt the range */
2065                 if (value_min + 1e-10 < softmin) {
2066                         if (value_min < 0.0)
2067                                 softmin = -soft_range_round_up(-value_min, -softmin);
2068                         else
2069                                 softmin = soft_range_round_down(value_min, softmin);
2070
2071                         if (softmin < (double)but->hardmin)
2072                                 softmin = (double)but->hardmin;
2073                 }
2074                 if (value_max - 1e-10 > softmax) {
2075                         if (value_max < 0.0)
2076                                 softmax = -soft_range_round_down(-value_max, -softmax);
2077                         else
2078                                 softmax = soft_range_round_up(value_max, softmax);
2079
2080                         if (softmax > (double)but->hardmax)
2081                                 softmax = but->hardmax;
2082                 }
2083
2084                 but->softmin = softmin;
2085                 but->softmax = softmax;
2086         }
2087 }
2088
2089 /* ******************* Free ********************/
2090
2091 static void ui_free_link(uiLink *link)
2092 {
2093         if (link) {
2094                 BLI_freelistN(&link->lines);
2095                 MEM_freeN(link);
2096         }
2097 }
2098
2099 /* can be called with C==NULL */
2100 static void ui_free_but(const bContext *C, uiBut *but)
2101 {
2102         if (but->opptr) {
2103                 WM_operator_properties_free(but->opptr);
2104                 MEM_freeN(but->opptr);
2105         }
2106
2107         if (but->func_argN) {
2108                 MEM_freeN(but->func_argN);
2109         }
2110
2111         if (but->active) {
2112                 /* XXX solve later, buttons should be free-able without context ideally,
2113                  * however they may have open tooltips or popup windows, which need to
2114                  * be closed using a context pointer */
2115                 if (C) {
2116                         ui_button_active_free(C, but);
2117                 }
2118                 else {
2119                         if (but->active) {
2120                                 MEM_freeN(but->active);
2121                         }
2122                 }
2123         }
2124         if (but->str && but->str != but->strdata) {
2125                 MEM_freeN(but->str);
2126         }
2127         ui_free_link(but->link);
2128
2129         if ((but->type == BUT_IMAGE) && but->poin) {
2130                 IMB_freeImBuf((struct ImBuf *)but->poin);
2131         }
2132
2133         MEM_freeN(but);
2134 }
2135
2136 /* can be called with C==NULL */
2137 void uiFreeBlock(const bContext *C, uiBlock *block)
2138 {
2139         uiBut *but;
2140
2141         while ( (but = block->buttons.first) ) {
2142                 BLI_remlink(&block->buttons, but);
2143                 ui_free_but(C, but);
2144         }
2145
2146         if (block->unit) {
2147                 MEM_freeN(block->unit);
2148         }
2149
2150         if (block->func_argN) {
2151                 MEM_freeN(block->func_argN);
2152         }
2153
2154         CTX_store_free_list(&block->contexts);
2155
2156         BLI_freelistN(&block->saferct);
2157         
2158         MEM_freeN(block);
2159 }
2160
2161 /* can be called with C==NULL */
2162 void uiFreeBlocks(const bContext *C, ListBase *lb)
2163 {
2164         uiBlock *block;
2165         
2166         while ( (block = lb->first) ) {
2167                 BLI_remlink(lb, block);
2168                 uiFreeBlock(C, block);
2169         }
2170 }
2171
2172 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2173 {
2174         uiBlock *block, *nextblock;
2175
2176         for (block = lb->first; block; block = nextblock) {
2177                 nextblock = block->next;
2178         
2179                 if (!block->handle) {
2180                         if (!block->active) {
2181                                 BLI_remlink(lb, block);
2182                                 uiFreeBlock(C, block);
2183                         }
2184                         else
2185                                 block->active = 0;
2186                 }
2187         }
2188 }
2189
2190 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2191 {
2192         ListBase *lb = &region->uiblocks;
2193         uiBlock *oldblock = NULL;
2194
2195         /* each listbase only has one block with this name, free block
2196          * if is already there so it can be rebuilt from scratch */
2197         if (lb) {
2198                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2199
2200                 if (oldblock) {
2201                         oldblock->active = 0;
2202                         oldblock->panel = NULL;
2203                 }
2204
2205                 /* at the beginning of the list! for dynamical menus/blocks */
2206                 BLI_addhead(lb, block);
2207         }
2208
2209         block->oldblock = oldblock;
2210 }
2211
2212 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2213 {
2214         uiBlock *block;
2215         wmWindow *window;
2216         Scene *scn;
2217         int getsizex, getsizey;
2218
2219         window = CTX_wm_window(C);
2220         scn = CTX_data_scene(C);
2221
2222         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2223         block->active = 1;
2224         block->dt = dt;
2225         block->evil_C = (void *)C;  /* XXX */
2226
2227         if (scn) {
2228                 block->color_profile = TRUE;
2229
2230                 /* store display device name, don't lookup for transformations yet
2231                  * block could be used for non-color displays where looking up for transformation
2232                  * would slow down redraw, so only lookup for actual transform when it's indeed
2233                  * needed
2234                  */
2235                 block->display_device = scn->display_settings.display_device;
2236
2237                 /* copy to avoid crash when scene gets deleted with ui still open */
2238                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2239                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2240         }
2241
2242         BLI_strncpy(block->name, name, sizeof(block->name));
2243
2244         if (region)
2245                 uiBlockSetRegion(block, region);
2246
2247         /* window matrix and aspect */
2248         if (region && region->swinid) {
2249                 wm_subwindow_getmatrix(window, region->swinid, block->winmat);
2250                 wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
2251
2252                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2253         }
2254         else {
2255                 /* no subwindow created yet, for menus for example, so we
2256                  * use the main window instead, since buttons are created
2257                  * there anyway */
2258                 wm_subwindow_getmatrix(window, window->screen->mainwin, block->winmat);
2259                 wm_subwindow_getsize(window, window->screen->mainwin, &getsizex, &getsizey);
2260
2261                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2262                 block->auto_open = TRUE;
2263                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2264         }
2265
2266         return block;
2267 }
2268
2269 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2270 {
2271         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2272 }
2273
2274 void uiBlockSetEmboss(uiBlock *block, char dt)
2275 {
2276         block->dt = dt;
2277 }
2278
2279 void ui_check_but(uiBut *but)
2280 {
2281         /* if something changed in the button */
2282         double value = UI_BUT_VALUE_UNSET;
2283 //      float okwidth; // UNUSED
2284         
2285         ui_check_but_select(but, &value);
2286         
2287         /* only update soft range while not editing */
2288         if (but->rnaprop && !(but->editval || but->editstr || but->editvec)) {
2289                 ui_set_but_soft_range(but);
2290         }
2291
2292         /* test for min and max, icon sliders, etc */
2293         switch (but->type) {
2294                 case NUM:
2295                 case SLI:
2296                 case SCROLL:
2297                 case NUMSLI:
2298                 case HSVSLI:
2299                         UI_GET_BUT_VALUE_INIT(but, value);
2300                         if (value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2301                         else if (value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2302                         break;
2303                         
2304                 case NUMABS:
2305                 {
2306                         double value_abs;
2307                         UI_GET_BUT_VALUE_INIT(but, value);
2308                         value_abs = fabs(value);
2309                         if (value_abs < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2310                         else if (value_abs > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2311                         break;
2312                 }
2313                 case ICONTOG: 
2314                 case ICONTOGN:
2315                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2316                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2317                                 else but->iconadd = 0;
2318                         }
2319                         break;
2320                         
2321                 case ICONROW:
2322                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2323                                 UI_GET_BUT_VALUE_INIT(but, value);
2324                                 but->iconadd = (int)value - (int)(but->hardmin);
2325                         }
2326                         break;
2327                         
2328                 case ICONTEXTROW:
2329                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2330                                 UI_GET_BUT_VALUE_INIT(but, value);
2331                                 but->iconadd = (int)value - (int)(but->hardmin);
2332                         }
2333                         break;
2334
2335                         /* quiet warnings for unhandled types */
2336                 default:
2337                         break;
2338         }
2339         
2340         
2341         /* safety is 4 to enable small number buttons (like 'users') */
2342         // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2343         
2344         /* name: */
2345         switch (but->type) {
2346         
2347                 case MENU:
2348                 case ICONTEXTROW:
2349                 
2350                         if (BLI_rctf_size_x(&but->rect) > 24.0f) {
2351                                 UI_GET_BUT_VALUE_INIT(but, value);
2352                                 ui_set_name_menu(but, (int)value);
2353                         }
2354                         break;
2355         
2356                 case NUM:
2357                 case NUMSLI:
2358                 case HSVSLI:
2359                 case NUMABS:
2360
2361                         UI_GET_BUT_VALUE_INIT(but, value);
2362
2363                         if (ui_is_but_float(but)) {
2364                                 if (value == (double) FLT_MAX) {
2365                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%sinf", but->str);
2366                                 }
2367                                 else if (value == (double) -FLT_MAX) {
2368                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s-inf", but->str);
2369                                 }
2370                                 /* support length type buttons */
2371                                 else if (ui_is_but_unit(but)) {
2372                                         char new_str[sizeof(but->drawstr)];
2373                                         ui_get_but_string_unit(but, new_str, sizeof(new_str), value, TRUE, -1);
2374                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, new_str);
2375                                 }
2376                                 else {
2377                                         const int prec = ui_but_float_precision(but, value);
2378                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2379                                 }
2380                         }
2381                         else {
2382                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%d", but->str, (int)value);
2383                         }
2384                         
2385                         if (but->rnaprop) {
2386                                 PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2387                         
2388                                 if (pstype == PROP_PERCENTAGE)
2389                                         strcat(but->drawstr, "%");
2390                         }
2391                         break;
2392
2393                 case LABEL:
2394                         if (ui_is_but_float(but)) {
2395                                 int prec;
2396                                 UI_GET_BUT_VALUE_INIT(but, value);
2397                                 prec = ui_but_float_precision(but, value);
2398                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2399                         }
2400                         else {
2401                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2402                         }
2403                 
2404                         break;
2405
2406                 case IDPOIN:
2407                 case TEX:
2408                 case SEARCH_MENU:
2409                 case SEARCH_MENU_UNLINK:
2410                         if (!but->editstr) {
2411                                 char str[UI_MAX_DRAW_STR];
2412
2413                                 ui_get_but_string(but, str, UI_MAX_DRAW_STR - strlen(but->str));
2414
2415                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2416                         }
2417                         break;
2418         
2419                 case KEYEVT:
2420                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2421                         if (but->flag & UI_SELECT) {
2422                                 strcat(but->drawstr, "Press a key");
2423                         }
2424                         else {
2425                                 UI_GET_BUT_VALUE_INIT(but, value);
2426                                 strcat(but->drawstr, WM_key_event_string((short)value));
2427                         }
2428                         break;
2429                 
2430                 case HOTKEYEVT:
2431                         if (but->flag & UI_SELECT) {
2432                                 but->drawstr[0] = '\0';
2433
2434                                 if (but->modifier_key) {
2435                                         char *str = but->drawstr;
2436
2437                                         if (but->modifier_key & KM_SHIFT)
2438                                                 str = strcat(str, "Shift ");
2439                                         if (but->modifier_key & KM_CTRL)
2440                                                 str = strcat(str, "Ctrl ");
2441                                         if (but->modifier_key & KM_ALT)
2442                                                 str = strcat(str, "Alt ");
2443                                         if (but->modifier_key & KM_OSKEY)
2444                                                 str = strcat(str, "Cmd ");
2445
2446                                         (void)str; /* UNUSED */
2447                                 }
2448                                 else
2449                                         strcat(but->drawstr, "Press a key  ");
2450                         }
2451                         else
2452                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2453
2454                         break;
2455
2456                 case BUT_TOGDUAL:
2457                         /* trying to get the dual-icon to left of text... not very nice */
2458                         if (but->str[0]) {
2459                                 BLI_strncpy(but->drawstr, "  ", UI_MAX_DRAW_STR);
2460                                 BLI_strncpy(but->drawstr + 2, but->str, UI_MAX_DRAW_STR - 2);
2461                         }
2462                         break;
2463                 
2464                 case HSVCUBE:
2465                 case HSVCIRCLE:
2466                         break;
2467                 default:
2468                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2469                 
2470         }
2471
2472         /* if we are doing text editing, this will override the drawstr */
2473         if (but->editstr)
2474                 BLI_strncpy(but->drawstr, but->editstr, UI_MAX_DRAW_STR);
2475         
2476         /* text clipping moved to widget drawing code itself */
2477 }
2478
2479
2480 void uiBlockBeginAlign(uiBlock *block)
2481 {
2482         /* if other align was active, end it */
2483         if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2484
2485         block->flag |= UI_BUT_ALIGN_DOWN;
2486         block->alignnr++;
2487
2488         /* buttons declared after this call will get this align nr */ // XXX flag?
2489 }
2490
2491 static int buts_are_horiz(uiBut *but1, uiBut *but2)
2492 {
2493         float dx, dy;
2494         
2495         dx = fabs(but1->rect.xmax - but2->rect.xmin);
2496         dy = fabs(but1->rect.ymin - but2->rect.ymax);
2497         
2498         if (dx > dy) return 0;
2499         return 1;
2500 }
2501
2502 void uiBlockEndAlign(uiBlock *block)
2503 {
2504         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
2505 }
2506
2507 int ui_but_can_align(uiBut *but)
2508 {
2509         return !ELEM4(but->type, LABEL, OPTION, OPTIONN, SEPR);
2510 }
2511
2512 static void ui_block_do_align_but(uiBut *first, short nr)
2513 {
2514         uiBut *prev, *but = NULL, *next;
2515         int flag = 0, cols = 0, rows = 0;
2516         
2517         /* auto align */
2518
2519         for (but = first; but && but->alignnr == nr; but = but->next) {
2520                 if (but->next && but->next->alignnr == nr) {
2521                         if (buts_are_horiz(but, but->next)) cols++;
2522                         else rows++;
2523                 }
2524         }
2525
2526         /* rows == 0: 1 row, cols == 0: 1 column */
2527         
2528         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2529         for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
2530                 next = but->next;
2531                 if (next && next->alignnr != nr)
2532                         next = NULL;
2533
2534                 /* clear old flag */
2535                 but->flag &= ~UI_BUT_ALIGN;
2536                         
2537                 if (flag == 0) {  /* first case */
2538                         if (next) {
2539                                 if (buts_are_horiz(but, next)) {
2540                                         if (rows == 0)
2541                                                 flag = UI_BUT_ALIGN_RIGHT;
2542                                         else 
2543                                                 flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT;
2544                                 }
2545                                 else {
2546                                         flag = UI_BUT_ALIGN_DOWN;
2547                                 }
2548                         }
2549                 }
2550                 else if (next == NULL) {  /* last case */
2551                         if (prev) {
2552                                 if (buts_are_horiz(prev, but)) {
2553                                         if (rows == 0)
2554                                                 flag = UI_BUT_ALIGN_LEFT;
2555                                         else
2556                                                 flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT;
2557                                 }
2558                                 else flag = UI_BUT_ALIGN_TOP;
2559                         }
2560                 }
2561                 else if (buts_are_horiz(but, next)) {
2562                         /* check if this is already second row */
2563                         if (prev && buts_are_horiz(prev, but) == 0) {
2564                                 flag &= ~UI_BUT_ALIGN_LEFT;
2565                                 flag |= UI_BUT_ALIGN_TOP;
2566                                 /* exception case: bottom row */
2567                                 if (rows > 0) {
2568                                         uiBut *bt = but;
2569                                         while (bt && bt->alignnr == nr) {
2570                                                 if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) {
2571                                                         break;
2572                                                 }
2573                                                 bt = bt->next;
2574                                         }
2575                                         if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
2576                                 }
2577                         }
2578                         else flag |= UI_BUT_ALIGN_LEFT;
2579                 }
2580                 else {
2581                         if (cols == 0) {
2582                                 flag |= UI_BUT_ALIGN_TOP;
2583                         }
2584                         else {  /* next button switches to new row */
2585                                 
2586                                 if (prev && buts_are_horiz(prev, but))
2587                                         flag |= UI_BUT_ALIGN_LEFT;
2588                                 else {
2589                                         flag &= ~UI_BUT_ALIGN_LEFT;
2590                                         flag |= UI_BUT_ALIGN_TOP;
2591                                 }
2592                                 
2593                                 if ((flag & UI_BUT_ALIGN_TOP) == 0) {  /* stil top row */
2594                                         if (prev) {
2595                                                 if (next && buts_are_horiz(but, next))
2596                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT;
2597                                                 else {
2598                                                         /* last button in top row */
2599                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT;
2600                                                 }
2601                                         }
2602                                         else 
2603                                                 flag |= UI_BUT_ALIGN_DOWN;
2604                                 }
2605                                 else 
2606                                         flag |= UI_BUT_ALIGN_TOP;
2607                         }
2608                 }
2609                 
2610                 but->flag |= flag;
2611                 
2612                 /* merge coordinates */
2613                 if (prev) {
2614                         /* simple cases */
2615                         if (rows == 0) {
2616                                 but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2617                                 prev->rect.xmax = but->rect.xmin;
2618                         }
2619                         else if (cols == 0) {
2620                                 but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2621                                 prev->rect.ymin = but->rect.ymax;
2622                         }
2623                         else {
2624                                 if (buts_are_horiz(prev, but)) {
2625                                         but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2626                                         prev->rect.xmax = but->rect.xmin;
2627                                         /* copy height too */
2628                                         but->rect.ymax = prev->rect.ymax;
2629                                 }
2630                                 else if (prev->prev && buts_are_horiz(prev->prev, prev) == 0) {
2631                                         /* the previous button is a single one in its row */
2632                                         but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2633                                         prev->rect.ymin = but->rect.ymax;
2634                                         
2635                                         but->rect.xmin = prev->rect.xmin;
2636                                         if (next && buts_are_horiz(but, next) == 0)
2637                                                 but->rect.xmax = prev->rect.xmax;
2638                                 }
2639                                 else {
2640                                         /* the previous button is not a single one in its row */
2641                                         but->rect.ymax = prev->rect.ymin;
2642                                 }
2643                         }
2644                 }
2645         }
2646 }
2647
2648 void ui_block_do_align(uiBlock *block)
2649 {
2650         uiBut *but;
2651         short nr;
2652
2653         /* align buttons with same align nr */
2654         for (but = block->buttons.first; but; ) {
2655                 if (but->alignnr) {
2656                         nr = but->alignnr;
2657                         ui_block_do_align_but(but, nr);
2658
2659                         /* skip with same number */
2660                         for (; but && but->alignnr == nr; but = but->next) {
2661                                 /* pass */
2662                         }
2663
2664                         if (!but) {
2665                                 break;
2666                         }
2667                 }
2668                 else {
2669                         but = but->next;
2670                 }
2671         }
2672 }
2673
2674 struct ColorManagedDisplay *ui_block_display_get(uiBlock *block)
2675 {
2676         return IMB_colormanagement_display_get_named(block->display_device);
2677 }
2678
2679 void ui_block_to_display_space_v3(uiBlock *block, float pixel[3])
2680 {
2681         struct ColorManagedDisplay *display = ui_block_display_get(block);
2682
2683         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
2684 }
2685
2686 void ui_block_to_scene_linear_v3(uiBlock *block, float pixel[3])
2687 {
2688         struct ColorManagedDisplay *display = ui_block_display_get(block);
2689
2690         IMB_colormanagement_display_to_scene_linear_v3(pixel, display);
2691 }
2692
2693 /**
2694  * \brief ui_def_but is the function that draws many button types
2695  *
2696  * \param x,y The lower left hand corner of the button (X axis)
2697  * \param width,height The size of the button.
2698  *
2699  * for float buttons:
2700  * - \a a1 Click Step (how much to change the value each click)
2701  * - \a a2 Number of decimal point values to display. 0 defaults to 3 (0.000)
2702  *      1,2,3, and a maximum of 4, all greater values will be clamped to 4.
2703  */
2704 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
2705                          int x, int y, short width, short height,
2706                          void *poin, float min, float max, float a1, float a2, const char *tip)
2707 {
2708         uiBut *but;
2709         int slen;
2710
2711         BLI_assert(width >= 0);
2712         BLI_assert(height >= 0);
2713         
2714         /* we could do some more error checks here */
2715         if ((type & BUTTYPE) == LABEL) {
2716                 if ((poin != NULL || min != 0.0f || max != 0.0f || (a1 == 0.0f && a2 != 0.0f) || (a1 != 0.0f && a1 != 1.0f)))
2717                         printf("blah\n");
2718                 BLI_assert((poin != NULL || min != 0.0f || max != 0.0f || (a1 == 0.0f && a2 != 0.0f) || (a1 != 0.0f && a1 != 1.0f)) == FALSE);
2719         }
2720
2721         if (type & UI_BUT_POIN_TYPES) {  /* a pointer is required */
2722                 if (poin == NULL) {
2723                         BLI_assert(0);
2724                         return NULL;
2725                 }
2726         }
2727
2728         but = MEM_callocN(sizeof(uiBut), "uiBut");
2729
2730         but->type = type & BUTTYPE;
2731         but->pointype = type & UI_BUT_POIN_TYPES;
2732         but->bit = type & UI_BUT_POIN_BIT;
2733         but->bitnr = type & 31;
2734         but->icon = ICON_NONE;
2735         but->iconadd = 0;
2736
2737         but->retval = retval;
2738
2739         slen = strlen(str);
2740         if (slen >= UI_MAX_NAME_STR - 1) {
2741                 but->str = MEM_mallocN(slen + 2, "ui_def_but str"); /* why +2 ? */
2742         }
2743         else {
2744                 but->str = but->strdata;
2745         }
2746         memcpy(but->str, str, slen + 1);
2747
2748         but->rect.xmin = x;
2749         but->rect.ymin = y;
2750         but->rect.xmax = but->rect.xmin + width;
2751         but->rect.ymax = but->rect.ymin + height;
2752
2753         but->poin = poin;
2754         but->hardmin = but->softmin = min;
2755         but->hardmax = but->softmax = max;
2756         but->a1 = a1;
2757         but->a2 = a2;
2758         but->tip = tip;
2759
2760         but->lock = block->lock;
2761         but->lockstr = block->lockstr;
2762         but->dt = block->dt;
2763
2764         but->aspect = 1.0f;  /* XXX block->aspect; */
2765         but->block = block;  /* pointer back, used for frontbuffer status, and picker */
2766
2767         if ((block->flag & UI_BUT_ALIGN) && ui_but_can_align(but))
2768                 but->alignnr = block->alignnr;
2769
2770         but->func = block->func;
2771         but->func_arg1 = block->func_arg1;
2772         but->func_arg2 = block->func_arg2;
2773
2774         but->funcN = block->funcN;
2775         if (block->func_argN)
2776                 but->func_argN = MEM_dupallocN(block->func_argN);
2777         
2778         but->pos = -1;   /* cursor invisible */
2779
2780         if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {    /* add a space to name */
2781                 /* slen remains unchanged from previous assignment, ensure this stays true */
2782                 if (slen > 0 && slen < UI_MAX_NAME_STR - 2) {
2783                         if (but->str[slen - 1] != ' ') {
2784                                 but->str[slen] = ' ';
2785                                 but->str[slen + 1] = 0;
2786                         }
2787                 }
2788         }
2789
2790         if ((block->flag & UI_BLOCK_LOOP) ||
2791             ELEM9(but->type, MENU, TEX, LABEL, IDPOIN, BLOCK, BUTM, SEARCH_MENU, PROGRESSBAR, SEARCH_MENU_UNLINK))
2792         {
2793                 but->flag |= (UI_TEXT_LEFT | UI_ICON_LEFT);
2794         }
2795         else if (but->type == BUT_TOGDUAL) {
2796                 but->flag |= UI_ICON_LEFT;
2797         }
2798
2799         but->flag |= (block->flag & UI_BUT_ALIGN);
2800
2801         if (but->lock == TRUE) {
2802                 if (but->lockstr) {
2803                         but->flag |= UI_BUT_DISABLED;
2804                 }
2805         }
2806
2807         /* keep track of UI_interface.h */
2808         if      (ELEM9(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM, SCROLL, SEPR /* , FTPREVIEW */)) {}
2809         else if (but->type >= SEARCH_MENU) {}
2810         else but->flag |= UI_BUT_UNDO;
2811
2812         BLI_addtail(&block->buttons, but);
2813         
2814         if (block->curlayout)
2815                 ui_layout_add_but(block->curlayout, but);
2816
2817 #ifdef WITH_PYTHON
2818         /* if the 'UI_OT_editsource' is running, extract the source info from the button  */
2819         if (UI_editsource_enable_check()) {
2820                 UI_editsource_active_but_test(but);
2821         }
2822 #endif
2823
2824         return but;
2825 }
2826
2827 static void ui_def_but_rna__disable(uiBut *but)
2828 {
2829         but->flag |= UI_BUT_DISABLED;
2830         but->lock = true;
2831         but->lockstr = "";
2832 }
2833
2834 /**
2835  * ui_def_but_rna_propname and ui_def_but_rna
2836  * both take the same args except for propname vs prop, this is done so we can
2837  * avoid an extra lookup on 'prop' when its already available.
2838  *
2839  * When this kind of change won't disrupt branches, best look into making more
2840  * of our UI functions take prop rather then propname.
2841  */
2842 static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str,
2843                              int x, int y, short width, short height,
2844                              PointerRNA *ptr, PropertyRNA *prop, int index,
2845                              float min, float max, float a1, float a2,  const char *tip)
2846 {
2847         const PropertyType proptype = RNA_property_type(prop);
2848         uiBut *but;
2849         int freestr = 0, icon = 0;
2850
2851         if (ELEM3(type, COLOR, HSVCIRCLE, HSVCUBE)) {
2852                 BLI_assert(index == -1);
2853         }
2854
2855         /* use rna values if parameters are not specified */
2856         if (!str) {
2857                 if (type == MENU && proptype == PROP_ENUM) {
2858                         EnumPropertyItem *item;
2859                         DynStr *dynstr;
2860                         int i, totitem, value, free;
2861
2862                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2863                         value = RNA_property_enum_get(ptr, prop);
2864
2865                         dynstr = BLI_dynstr_new();
2866                         BLI_dynstr_appendf(dynstr, "%s%%t", RNA_property_ui_name(prop));
2867                         for (i = 0; i < totitem; i++) {
2868                                 if (!item[i].identifier[0]) {
2869                                         if (item[i].name)
2870                                                 BLI_dynstr_appendf(dynstr, "|%s%%l", item[i].name);
2871                                         else
2872                                                 BLI_dynstr_append(dynstr, "|%l");
2873                                 }
2874                                 else if (item[i].icon)
2875                                         BLI_dynstr_appendf(dynstr, "|%s %%i%d %%x%d", item[i].name, item[i].icon, item[i].value);
2876                                 else
2877                                         BLI_dynstr_appendf(dynstr, "|%s %%x%d", item[i].name, item[i].value);
2878
2879                                 if (value == item[i].value)
2880                                         icon = item[i].icon;
2881                         }
2882                         str = BLI_dynstr_get_cstring(dynstr);
2883                         BLI_dynstr_free(dynstr);
2884
2885                         if (free) {
2886                                 MEM_freeN(item);
2887                         }
2888
2889                         freestr = 1;
2890                 }
2891                 else if (ELEM(type, ROW, LISTROW) && proptype == PROP_ENUM) {
2892                         EnumPropertyItem *item;
2893                         int i, totitem, free;
2894
2895                         /* get untranslated, then translate the single string we need */
2896                         RNA_property_enum_items(block->evil_C, ptr, prop, &item, &totitem, &free);
2897                         for (i = 0; i < totitem; i++) {
2898                                 if (item[i].identifier[0] && item[i].value == (int)max) {
2899                                         str = CTX_IFACE_(RNA_property_translation_context(prop), item[i].name);
2900                                         icon = item[i].icon;
2901                                         break;
2902                                 }
2903                         }
2904
2905                         if (!str) {
2906                                 str = RNA_property_ui_name(prop);
2907                         }
2908                         if (free) {
2909                                 MEM_freeN(item);
2910                         }
2911                 }
2912                 else {
2913                         str = RNA_property_ui_name(prop);
2914                         icon = RNA_property_ui_icon(prop);
2915                 }
2916         }
2917
2918         if (!tip && proptype != PROP_ENUM)
2919                 tip = RNA_property_ui_description(prop);
2920
2921         if (min == max || a1 == -1 || a2 == -1) {
2922                 if (proptype == PROP_INT) {
2923                         int hardmin, hardmax, softmin, softmax, step;
2924
2925                         RNA_property_int_range(ptr, prop, &hardmin, &hardmax);
2926                         RNA_property_int_ui_range(ptr, prop, &softmin, &softmax, &step);
2927
2928                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2929                                 min = hardmin;
2930                                 max = hardmax;
2931                         }
2932                         if (a1 == -1)
2933                                 a1 = step;
2934                         if (a2 == -1)
2935                                 a2 = 0;
2936                 }
2937                 else if (proptype == PROP_FLOAT) {
2938                         float hardmin, hardmax, softmin, softmax, step, precision;
2939
2940                         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2941                         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2942
2943                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2944                                 min = hardmin;
2945                                 max = hardmax;
2946                         }
2947                         if (a1 == -1)
2948                                 a1 = step;
2949                         if (a2 == -1)
2950                                 a2 = precision;
2951                 }
2952                 else if (proptype == PROP_STRING) {
2953                         min = 0;
2954                         max = RNA_property_string_maxlength(prop);
2955                         if (max == 0) /* interface code should ideally support unlimited length */
2956                                 max = UI_MAX_DRAW_STR;
2957                 }
2958         }
2959
2960         /* now create button */
2961         but = ui_def_but(block, type, retval, str, x, y, width, height, NULL, min, max, a1, a2, tip);
2962
2963         but->rnapoin = *ptr;
2964         but->rnaprop = prop;
2965
2966         if (RNA_property_array_length(&but->rnapoin, but->rnaprop))
2967                 but->rnaindex = index;
2968         else
2969                 but->rnaindex = 0;
2970
2971         if (icon) {
2972                 but->icon = (BIFIconID)icon;
2973                 but->flag |= UI_HAS_ICON;
2974                 but->flag |= UI_ICON_LEFT;
2975         }
2976         
2977         if (!RNA_property_editable(&but->rnapoin, prop)) {
2978                 ui_def_but_rna__disable(but);
2979         }
2980
2981         if (but->flag & UI_BUT_UNDO && (ui_but_is_rna_undo(but) == FALSE)) {
2982                 but->flag &= ~UI_BUT_UNDO;
2983         }
2984
2985         /* If this button uses units, calculate the step from this */
2986         if ((proptype == PROP_FLOAT) && ui_is_but_unit(but)) {
2987                 but->a1 = ui_get_but_step_unit(but, but->a1);
2988         }
2989
2990         if (freestr) {
2991                 MEM_freeN((void *)str);
2992         }
2993
2994         return but;
2995 }
2996
2997 static uiBut *ui_def_but_rna_propname(uiBlock *block, int type, int retval, const char *str, int x, int y, short width, short height, PointerRNA *ptr, const char *propname, int index, float min, float max, float a1, float a2,  const char *tip)
2998 {
2999         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
3000         uiBut *but;
3001
3002         if (prop) {
3003                 but = ui_def_but_rna(block, type, retval, str, x, y, width, height, ptr, prop, index, min, max, a1, a2,  tip);
3004         }
3005         else {
3006                 but = ui_def_but(block, type, retval, propname, x, y, width, height, NULL, min, max, a1, a2, tip);
3007
3008                 ui_def_but_rna__disable(but);
3009         }
3010
3011         return but;
3012 }
3013
3014 static uiBut *ui_def_but_operator_ptr(uiBlock *block, int type, wmOperatorType *ot, int opcontext, const char *str, int x, int y, short width, short height, const char *tip)
3015 {
3016         uiBut *but;
3017
3018         if (!str) {
3019                 if (ot && ot->srna)
3020                         str = RNA_struct_ui_name(ot->srna);
3021                 else
3022                         str = "";
3023         }
3024
3025         if ((!tip || tip[0] == '\0') && ot && ot->srna) {
3026                 tip = RNA_struct_ui_description(ot->srna);
3027         }
3028
3029         but = ui_def_but(block, type, -1, str, x, y, width, height, NULL, 0, 0, 0, 0, tip);
3030         but->optype = ot;
3031         but->opcontext = opcontext;
3032         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
3033
3034         if (!ot) {
3035                 but->flag |= UI_BUT_DISABLED;
3036                 but->lock = TRUE;
3037                 but->lockstr = "";
3038         }
3039
3040         return but;
3041 }
3042
3043 #if 0 /* UNUSED */
3044 static uiBut *UNUSED_FUNCTION(ui_def_but_operator) (uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x, int y, short width, short height, const char *tip)
3045 {
3046         wmOperatorType *ot = WM_operatortype_find(opname, 0);
3047         if (str == NULL && ot == NULL) str = opname;
3048         return ui_def_but_operator_ptr(block, type, ot, opcontext, str, x, y, width, height, tip);
3049 }
3050 #endif
3051
3052 static uiBut *ui_def_but_operator_text(uiBlock *block, int type, const char *opname, int opcontext, const char *str, int x, int y, short width, short height, void *poin, float min, float max, float a1, float a2, const char *tip)
3053 {
3054         uiBut *but;
3055         wmOperatorType *ot;
3056         
3057         ot = WM_operatortype_find(opname, 0);
3058
3059         if (!str) {
3060                 if (ot) str = ot->name;
3061                 else str = opname;
3062         }
3063         
3064         if ((!tip || tip[0] == '\0') && ot && ot->description) {
3065                 tip = ot->description;
3066         }
3067
3068         but = ui_def_but(block, type, -1, str, x, y, width, height, poin, min, max, a1, a2, tip);
3069         but->optype = ot;
3070         but->opcontext = opcontext;
3071         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
3072
3073         if (!ot) {
307