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