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