ce82e0645314a95849e69e20f95eb4b31febe5ad
[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 #include "wm_window.h"
73
74 #include "RNA_access.h"
75
76 #include "BPY_extern.h"
77
78 #include "IMB_colormanagement.h"
79
80 #include "interface_intern.h"
81
82 #define PRECISION_FLOAT_MAX 6
83 #define PRECISION_FLOAT_MAX_POW 1000000 /* pow(10, PRECISION_FLOAT_MAX)  */
84
85 /* avoid unneeded calls to ui_get_but_val */
86 #define UI_BUT_VALUE_UNSET DBL_MAX
87 #define UI_GET_BUT_VALUE_INIT(_but, _value) if (_value == DBL_MAX) {  (_value) = ui_get_but_val(_but); } (void)0
88
89 /* 
90  * a full doc with API notes can be found in bf-blender/trunk/blender/doc/guides/interface_API.txt
91  * 
92  * uiBlahBlah()         external function
93  * ui_blah_blah()       internal function
94  */
95
96 static void ui_free_but(const bContext *C, uiBut *but);
97
98 /* ************* window matrix ************** */
99
100 void ui_block_to_window_fl(const ARegion *ar, uiBlock *block, float *x, float *y)
101 {
102         float gx, gy;
103         int sx, sy, getsizex, getsizey;
104
105         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
106         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
107         sx = ar->winrct.xmin;
108         sy = ar->winrct.ymin;
109
110         gx = *x;
111         gy = *y;
112
113         if (block->panel) {
114                 gx += block->panel->ofsx;
115                 gy += block->panel->ofsy;
116         }
117
118         *x = ((float)sx) + ((float)getsizex) * (0.5f + 0.5f * (gx * block->winmat[0][0] + gy * block->winmat[1][0] + block->winmat[3][0]));
119         *y = ((float)sy) + ((float)getsizey) * (0.5f + 0.5f * (gx * block->winmat[0][1] + gy * block->winmat[1][1] + block->winmat[3][1]));
120 }
121
122 void ui_block_to_window(const ARegion *ar, uiBlock *block, int *x, int *y)
123 {
124         float fx, fy;
125
126         fx = *x;
127         fy = *y;
128
129         ui_block_to_window_fl(ar, block, &fx, &fy);
130
131         *x = (int)(fx + 0.5f);
132         *y = (int)(fy + 0.5f);
133 }
134
135 void ui_block_to_window_rct(const ARegion *ar, uiBlock *block, const rctf *graph, rcti *winr)
136 {
137         rctf tmpr;
138
139         tmpr = *graph;
140         ui_block_to_window_fl(ar, block, &tmpr.xmin, &tmpr.ymin);
141         ui_block_to_window_fl(ar, block, &tmpr.xmax, &tmpr.ymax);
142
143         BLI_rcti_rctf_copy(winr, &tmpr);
144 }
145
146 void ui_window_to_block_fl(const ARegion *ar, uiBlock *block, float *x, float *y)   /* for mouse cursor */
147 {
148         float a, b, c, d, e, f, px, py;
149         int sx, sy, getsizex, getsizey;
150
151         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
152         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
153         sx = ar->winrct.xmin;
154         sy = ar->winrct.ymin;
155
156         a = 0.5f * ((float)getsizex) * block->winmat[0][0];
157         b = 0.5f * ((float)getsizex) * block->winmat[1][0];
158         c = 0.5f * ((float)getsizex) * (1.0f + block->winmat[3][0]);
159
160         d = 0.5f * ((float)getsizey) * block->winmat[0][1];
161         e = 0.5f * ((float)getsizey) * block->winmat[1][1];
162         f = 0.5f * ((float)getsizey) * (1.0f + block->winmat[3][1]);
163
164         px = *x - sx;
165         py = *y - sy;
166
167         *y =  (a * (py - f) + d * (c - px)) / (a * e - d * b);
168         *x = (px - b * (*y) - c) / a;
169
170         if (block->panel) {
171                 *x -= block->panel->ofsx;
172                 *y -= block->panel->ofsy;
173         }
174 }
175
176 void ui_window_to_block(const ARegion *ar, uiBlock *block, int *x, int *y)
177 {
178         float fx, fy;
179
180         fx = *x;
181         fy = *y;
182
183         ui_window_to_block_fl(ar, block, &fx, &fy);
184
185         *x = (int)(fx + 0.5f);
186         *y = (int)(fy + 0.5f);
187 }
188
189 void ui_window_to_region(const ARegion *ar, int *x, int *y)
190 {
191         *x -= ar->winrct.xmin;
192         *y -= ar->winrct.ymin;
193 }
194
195 /* ******************* block calc ************************* */
196
197 void ui_block_translate(uiBlock *block, int x, int y)
198 {
199         uiBut *but;
200
201         for (but = block->buttons.first; but; but = but->next) {
202                 BLI_rctf_translate(&but->rect, x, y);
203         }
204
205         BLI_rctf_translate(&block->rect, x, y);
206 }
207
208 static void ui_text_bounds_block(uiBlock *block, float offset)
209 {
210         uiStyle *style = UI_GetStyle();
211         uiBut *bt;
212         int i = 0, j, x1addval = offset, nextcol;
213         int lastcol = 0, col = 0;
214         
215         uiStyleFontSet(&style->widget);
216         
217         for (bt = block->buttons.first; bt; bt = bt->next) {
218                 if (bt->type != SEPR) {
219                         j = BLF_width(style->widget.uifont_id, bt->drawstr);
220
221                         if (j > i) i = j;
222                 }
223
224                 if (bt->next && bt->rect.xmin < bt->next->rect.xmin)
225                         lastcol++;
226         }
227
228         /* cope with multi collumns */
229         bt = block->buttons.first;
230         while (bt) {
231                 if (bt->next && bt->rect.xmin < bt->next->rect.xmin) {
232                         nextcol = 1;
233                         col++;
234                 }
235                 else nextcol = 0;
236                 
237                 bt->rect.xmin = x1addval;
238                 bt->rect.xmax = bt->rect.xmin + i + block->bounds;
239                 
240                 if (col == lastcol) {
241                         bt->rect.xmax = max_ff(bt->rect.xmax, offset + block->minbounds);
242                 }
243
244                 ui_check_but(bt);  /* clips text again */
245                 
246                 if (nextcol)
247                         x1addval += i + block->bounds;
248                 
249                 bt = bt->next;
250         }
251 }
252
253 void ui_bounds_block(uiBlock *block)
254 {
255         uiBut *bt;
256         int xof;
257         
258         if (block->buttons.first == NULL) {
259                 if (block->panel) {
260                         block->rect.xmin = 0.0; block->rect.xmax = block->panel->sizex;
261                         block->rect.ymin = 0.0; block->rect.ymax = block->panel->sizey;
262                 }
263         }
264         else {
265         
266                 BLI_rctf_init_minmax(&block->rect);
267
268                 for (bt = block->buttons.first; bt; bt = bt->next) {
269                         BLI_rctf_union(&block->rect, &bt->rect);
270                 }
271                 
272                 block->rect.xmin -= block->bounds;
273                 block->rect.ymin -= block->bounds;
274                 block->rect.xmax += block->bounds;
275                 block->rect.ymax += block->bounds;
276         }
277
278         block->rect.xmax = block->rect.xmin + max_ff(BLI_rctf_size_x(&block->rect), block->minbounds);
279
280         /* hardcoded exception... but that one is annoying with larger safety */ 
281         bt = block->buttons.first;
282         if (bt && strncmp(bt->str, "ERROR", 5) == 0) xof = 10;
283         else xof = 40;
284
285         block->safety.xmin = block->rect.xmin - xof;
286         block->safety.ymin = block->rect.ymin - xof;
287         block->safety.xmax = block->rect.xmax + xof;
288         block->safety.ymax = block->rect.ymax + xof;
289 }
290
291 static void ui_centered_bounds_block(const bContext *C, uiBlock *block)
292 {
293         wmWindow *window = CTX_wm_window(C);
294         int xmax, ymax;
295         int startx, starty;
296         int width, height;
297         
298         /* note: this is used for the splash where window bounds event has not been
299          * updated by ghost, get the window bounds from ghost directly */
300
301         // wm_window_get_size(window, &xmax, &ymax);
302         wm_window_get_size_ghost(window, &xmax, &ymax);
303         
304         ui_bounds_block(block);
305         
306         width  = BLI_rctf_size_x(&block->rect);
307         height = BLI_rctf_size_y(&block->rect);
308         
309         startx = (xmax * 0.5f) - (width * 0.5f);
310         starty = (ymax * 0.5f) - (height * 0.5f);
311         
312         ui_block_translate(block, startx - block->rect.xmin, starty - block->rect.ymin);
313         
314         /* now recompute bounds and safety */
315         ui_bounds_block(block);
316         
317 }
318 static void ui_popup_bounds_block(const bContext *C, uiBlock *block, eBlockBoundsCalc bounds_calc)
319 {
320         wmWindow *window = CTX_wm_window(C);
321         int startx, starty, endx, endy, width, height, oldwidth, oldheight;
322         int oldbounds, xmax, ymax;
323
324         oldbounds = block->bounds;
325
326         /* compute mouse position with user defined offset */
327         ui_bounds_block(block);
328         
329         wm_window_get_size(window, &xmax, &ymax);
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 = 50;
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                 aspect = sqrt(aspect);
987                 pointsf /= aspect;
988                 
989                 if (aspect > 1.0f)
990                         *points = ceilf(pointsf);
991                 else
992                         *points = floorf(pointsf);
993         }
994 }
995
996 /* project button or block (but==NULL) to pixels in regionspace */
997 static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
998 {
999         rctf rectf = (but)? but->rect: block->rect;
1000         
1001         ui_block_to_window_fl(ar, block, &rectf.xmin, &rectf.ymin);
1002         ui_block_to_window_fl(ar, block, &rectf.xmax, &rectf.ymax);
1003
1004         rectf.xmin -= ar->winrct.xmin;
1005         rectf.ymin -= ar->winrct.ymin;
1006         rectf.xmax -= ar->winrct.xmin;
1007         rectf.ymax -= ar->winrct.ymin;
1008
1009         rect->xmin = floorf(rectf.xmin);
1010         rect->ymin = floorf(rectf.ymin);
1011         rect->xmax = floorf(rectf.xmax);
1012         rect->ymax = floorf(rectf.ymax);
1013 }
1014
1015 /* uses local copy of style, to scale things down, and allow widgets to change stuff */
1016 void uiDrawBlock(const bContext *C, uiBlock *block)
1017 {
1018         uiStyle style = *UI_GetStyle();  /* XXX pass on as arg */
1019         ARegion *ar;
1020         uiBut *but;
1021         rcti rect;
1022         int multisample_enabled;
1023         
1024         /* get menu region or area region */
1025         ar = CTX_wm_menu(C);
1026         if (!ar)
1027                 ar = CTX_wm_region(C);
1028
1029         if (!block->endblock)
1030                 uiEndBlock(C, block);
1031
1032         /* disable AA, makes widgets too blurry */
1033         multisample_enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
1034         if (multisample_enabled)
1035                 glDisable(GL_MULTISAMPLE_ARB);
1036
1037         /* we set this only once */
1038         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1039         
1040         /* scale fonts */
1041         ui_fontscale(&style.paneltitle.points, block->aspect);
1042         ui_fontscale(&style.grouplabel.points, block->aspect);
1043         ui_fontscale(&style.widgetlabel.points, block->aspect);
1044         ui_fontscale(&style.widget.points, block->aspect);
1045         
1046         /* scale block min/max to rect */
1047         ui_but_to_pixelrect(&rect, ar, block, NULL);
1048         
1049         /* pixel space for AA widgets */
1050         glMatrixMode(GL_PROJECTION);
1051         glPushMatrix();
1052         glMatrixMode(GL_MODELVIEW);
1053         glPushMatrix();
1054         glLoadIdentity();
1055         
1056         wmOrtho2(-0.01f, ar->winx - 0.01f, -0.01f, ar->winy - 0.01f);
1057         
1058         /* back */
1059         if (block->flag & UI_BLOCK_LOOP)
1060                 ui_draw_menu_back(&style, block, &rect);
1061         else if (block->panel)
1062                 ui_draw_aligned_panel(&style, block, &rect);
1063
1064         /* widgets */
1065         for (but = block->buttons.first; but; but = but->next) {
1066                 if (!(but->flag & (UI_HIDDEN | UI_SCROLLED))) {
1067                         ui_but_to_pixelrect(&rect, ar, block, but);
1068                 
1069                         /* XXX: figure out why invalid coordinates happen when closing render window */
1070                         /* and material preview is redrawn in main window (temp fix for bug #23848) */
1071                         if (rect.xmin < rect.xmax && rect.ymin < rect.ymax)
1072                                 ui_draw_but(C, ar, &style, but, &rect);
1073                 }
1074         }
1075         
1076         /* restore matrix */
1077         glMatrixMode(GL_PROJECTION);
1078         glPopMatrix();
1079         glMatrixMode(GL_MODELVIEW);
1080         glPopMatrix();
1081
1082         if (multisample_enabled)
1083                 glEnable(GL_MULTISAMPLE_ARB);
1084         
1085         ui_draw_links(block);
1086 }
1087
1088 /* ************* EVENTS ************* */
1089
1090 static void ui_is_but_sel(uiBut *but, double *value)
1091 {
1092         short is_push = 0;  /* (0 == UNSELECT), (1 == SELECT), (2 == DO-NOHING) */
1093         short is_true = TRUE;
1094
1095         if (ELEM3(but->type, TOGN, ICONTOGN, OPTIONN)) {
1096                 is_true = FALSE;
1097         }
1098
1099         if (but->bit) {
1100                 int lvalue;
1101                 UI_GET_BUT_VALUE_INIT(but, *value);
1102                 lvalue = (int)*value;
1103                 if (UI_BITBUT_TEST(lvalue, (but->bitnr))) {
1104                         is_push = is_true;
1105                 }
1106                 else {
1107                         is_push = !is_true;
1108                 }
1109         }
1110         else {
1111                 switch (but->type) {
1112                         case BUT:
1113                                 is_push = 2;
1114                                 break;
1115                         case HOTKEYEVT:
1116                         case KEYEVT:
1117                                 is_push = 2;
1118                                 break;
1119                         case TOGBUT:
1120                         case TOG:
1121                         case TOGR:
1122                         case TOG3:
1123                         case BUT_TOGDUAL:
1124                         case ICONTOG:
1125                         case OPTION:
1126                                 UI_GET_BUT_VALUE_INIT(but, *value);
1127                                 if (*value != (double)but->hardmin) is_push = 1;
1128                                 break;
1129                         case ICONTOGN:
1130                         case TOGN:
1131                         case OPTIONN:
1132                                 UI_GET_BUT_VALUE_INIT(but, *value);
1133                                 if (*value == 0.0) is_push = 1;
1134                                 break;
1135                         case ROW:
1136                         case LISTROW:
1137                                 UI_GET_BUT_VALUE_INIT(but, *value);
1138                                 /* support for rna enum buts */
1139                                 if (but->rnaprop && (RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG)) {
1140                                         if ((int)*value & (int)but->hardmax) is_push = 1;
1141                                 }
1142                                 else {
1143                                         if (*value == (double)but->hardmax) is_push = 1;
1144                                 }
1145                                 break;
1146                         case COLOR:
1147                                 is_push = 2;
1148                                 break;
1149                         default:
1150                                 is_push = 2;
1151                                 break;
1152                 }
1153         }
1154         
1155         if (is_push == 2) {
1156                 /* pass */
1157         }
1158         else if (is_push == 1) {
1159                 but->flag |= UI_SELECT;
1160         }
1161         else {
1162                 but->flag &= ~UI_SELECT;
1163         }
1164 }
1165
1166 static uiBut *ui_find_inlink(uiBlock *block, void *poin)
1167 {
1168         uiBut *but;
1169         
1170         but = block->buttons.first;
1171         while (but) {
1172                 if (but->type == INLINK) {
1173                         if (but->poin == poin) return but;
1174                 }
1175                 but = but->next;
1176         }
1177         return NULL;
1178 }
1179
1180 static void ui_add_link_line(ListBase *listb, uiBut *but, uiBut *bt)
1181 {
1182         uiLinkLine *line;
1183         
1184         line = MEM_callocN(sizeof(uiLinkLine), "linkline");
1185         BLI_addtail(listb, line);
1186         line->from = but;
1187         line->to = bt;
1188 }
1189
1190 uiBut *uiFindInlink(uiBlock *block, void *poin)
1191 {
1192         return ui_find_inlink(block, poin);
1193 }
1194
1195 void uiComposeLinks(uiBlock *block)
1196 {
1197         uiBut *but, *bt;
1198         uiLink *link;
1199         void ***ppoin;
1200         int a;
1201         
1202         but = block->buttons.first;
1203         while (but) {
1204                 if (but->type == LINK) {
1205                         link = but->link;
1206                         
1207                         /* for all pointers in the array */
1208                         if (link) {
1209                                 if (link->ppoin) {
1210                                         ppoin = link->ppoin;
1211                                         for (a = 0; a < *(link->totlink); a++) {
1212                                                 bt = ui_find_inlink(block, (*ppoin)[a]);
1213                                                 if (bt) {
1214                                                         ui_add_link_line(&link->lines, but, bt);
1215                                                 }
1216                                         }
1217                                 }
1218                                 else if (link->poin) {
1219                                         bt = ui_find_inlink(block, *(link->poin) );
1220                                         if (bt) {
1221                                                 ui_add_link_line(&link->lines, but, bt);
1222                                         }
1223                                 }
1224                         }
1225                 }
1226                 but = but->next;
1227         }
1228 }
1229
1230
1231 /* ************************************************ */
1232
1233 void uiBlockSetButLock(uiBlock *block, int val, const char *lockstr)
1234 {
1235         if (val) {
1236                 block->lock = val ? TRUE : FALSE;
1237                 block->lockstr = lockstr;
1238         }
1239 }
1240
1241 void uiBlockClearButLock(uiBlock *block)
1242 {
1243         block->lock = FALSE;
1244         block->lockstr = NULL;
1245 }
1246
1247 /* *************************************************************** */
1248
1249 void ui_delete_linkline(uiLinkLine *line, uiBut *but)
1250 {
1251         uiLink *link;
1252         int a, b;
1253         
1254         BLI_remlink(&but->link->lines, line);
1255
1256         link = line->from->link;
1257
1258         /* are there more pointers allowed? */
1259         if (link->ppoin) {
1260                 
1261                 if (*(link->totlink) == 1) {
1262                         *(link->totlink) = 0;
1263                         MEM_freeN(*(link->ppoin));
1264                         *(link->ppoin) = NULL;
1265                 }
1266                 else {
1267                         b = 0;
1268                         for (a = 0; a < (*(link->totlink)); a++) {
1269                                 if ((*(link->ppoin))[a] != line->to->poin) {
1270                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1271                                         b++;
1272                                 }
1273                         }
1274                         (*(link->totlink))--;
1275                 }
1276         }
1277         else {
1278                 *(link->poin) = NULL;
1279         }
1280
1281         MEM_freeN(line);
1282         //REDRAW
1283 }
1284
1285 /* *********************** data get/set ***********************
1286  * this either works with the pointed to data, or can work with
1287  * an edit override pointer while dragging for example */
1288
1289 /* for buttons pointing to color for example */
1290 void ui_get_but_vectorf(uiBut *but, float vec[3])
1291 {
1292         PropertyRNA *prop;
1293         int a, tot;
1294
1295         if (but->editvec) {
1296                 copy_v3_v3(vec, but->editvec);
1297         }
1298
1299         if (but->rnaprop) {
1300                 prop = but->rnaprop;
1301
1302                 vec[0] = vec[1] = vec[2] = 0.0f;
1303
1304                 if (RNA_property_type(prop) == PROP_FLOAT) {
1305                         tot = RNA_property_array_length(&but->rnapoin, prop);
1306                         tot = min_ii(tot, 3);
1307
1308                         for (a = 0; a < tot; a++)
1309                                 vec[a] = RNA_property_float_get_index(&but->rnapoin, prop, a);
1310                 }
1311         }
1312         else if (but->pointype == UI_BUT_POIN_CHAR) {
1313                 char *cp = (char *)but->poin;
1314                 vec[0] = ((float)cp[0]) / 255.0f;
1315                 vec[1] = ((float)cp[1]) / 255.0f;
1316                 vec[2] = ((float)cp[2]) / 255.0f;
1317         }
1318         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1319                 float *fp = (float *)but->poin;
1320                 copy_v3_v3(vec, fp);
1321         }
1322         else {
1323                 if (but->editvec == NULL) {
1324                         fprintf(stderr, "ui_get_but_vectorf: can't get color, should never happen\n");
1325                         vec[0] = vec[1] = vec[2] = 0.0f;
1326                 }
1327         }
1328
1329         if (but->type == BUT_NORMAL) {
1330                 normalize_v3(vec);
1331         }
1332 }
1333
1334 /* for buttons pointing to color for example */
1335 void ui_set_but_vectorf(uiBut *but, const float vec[3])
1336 {
1337         PropertyRNA *prop;
1338
1339         if (but->editvec) {
1340                 copy_v3_v3(but->editvec, vec);
1341         }
1342
1343         if (but->rnaprop) {
1344                 prop = but->rnaprop;
1345
1346                 if (RNA_property_type(prop) == PROP_FLOAT) {
1347                         int tot;
1348                         int a;
1349
1350                         tot = RNA_property_array_length(&but->rnapoin, prop);
1351                         tot = min_ii(tot, 3);
1352
1353                         for (a = 0; a < tot; a++) {
1354                                 RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
1355                         }
1356                 }
1357         }
1358         else if (but->pointype == UI_BUT_POIN_CHAR) {
1359                 char *cp = (char *)but->poin;
1360                 cp[0] = (char)(0.5f + vec[0] * 255.0f);
1361                 cp[1] = (char)(0.5f + vec[1] * 255.0f);
1362                 cp[2] = (char)(0.5f + vec[2] * 255.0f);
1363         }
1364         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1365                 float *fp = (float *)but->poin;
1366                 copy_v3_v3(fp, vec);
1367         }
1368 }
1369
1370 int ui_is_but_float(uiBut *but)
1371 {
1372         if (but->pointype == UI_BUT_POIN_FLOAT && but->poin)
1373                 return 1;
1374         
1375         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_FLOAT)
1376                 return 1;
1377         
1378         return 0;
1379 }
1380
1381 int ui_is_but_unit(uiBut *but)
1382 {
1383         UnitSettings *unit = but->block->unit;
1384         const int unit_type = uiButGetUnitType(but);
1385
1386         if (unit_type == PROP_UNIT_NONE)
1387                 return 0;
1388
1389 #if 1 /* removed so angle buttons get correct snapping */
1390         if (unit->system_rotation == USER_UNIT_ROT_RADIANS && unit_type == PROP_UNIT_ROTATION)
1391                 return 0;
1392 #endif
1393         
1394         /* for now disable time unit conversion */
1395         if (unit_type == PROP_UNIT_TIME)
1396                 return 0;
1397
1398         if (unit->system == USER_UNIT_NONE) {
1399                 if (unit_type != PROP_UNIT_ROTATION) {
1400                         return 0;
1401                 }
1402         }
1403
1404         return 1;
1405 }
1406
1407 int ui_is_but_rna_valid(uiBut *but)
1408 {
1409         if (but->rnaprop == NULL || RNA_struct_contains_property(&but->rnapoin, but->rnaprop)) {
1410                 return TRUE;
1411         }
1412         else {
1413                 printf("property removed %s: %p\n", but->drawstr, but->rnaprop);
1414                 return FALSE;
1415         }
1416 }
1417
1418 double ui_get_but_val(uiBut *but)
1419 {
1420         PropertyRNA *prop;
1421         double value = 0.0;
1422
1423         if (but->editval) { return *(but->editval); }
1424         if (but->poin == NULL && but->rnapoin.data == NULL) return 0.0;
1425
1426         if (but->rnaprop) {
1427                 prop = but->rnaprop;
1428
1429                 switch (RNA_property_type(prop)) {
1430                         case PROP_BOOLEAN:
1431                                 if (RNA_property_array_check(prop))
1432                                         value = RNA_property_boolean_get_index(&but->rnapoin, prop, but->rnaindex);
1433                                 else
1434                                         value = RNA_property_boolean_get(&but->rnapoin, prop);
1435                                 break;
1436                         case PROP_INT:
1437                                 if (RNA_property_array_check(prop))
1438                                         value = RNA_property_int_get_index(&but->rnapoin, prop, but->rnaindex);
1439                                 else
1440                                         value = RNA_property_int_get(&but->rnapoin, prop);
1441                                 break;
1442                         case PROP_FLOAT:
1443                                 if (RNA_property_array_check(prop))
1444                                         value = RNA_property_float_get_index(&but->rnapoin, prop, but->rnaindex);
1445                                 else
1446                                         value = RNA_property_float_get(&but->rnapoin, prop);
1447                                 break;
1448                         case PROP_ENUM:
1449                                 value = RNA_property_enum_get(&but->rnapoin, prop);
1450                                 break;
1451                         default:
1452                                 value = 0.0;
1453                                 break;
1454                 }
1455         }
1456         else if (but->type == HSVSLI) {
1457                 float *fp, hsv[3];
1458                 
1459                 fp = (but->editvec) ? but->editvec : (float *)but->poin;
1460                 rgb_to_hsv_v(fp, hsv);
1461
1462                 switch (but->str[0]) {
1463                         case 'H': value = hsv[0]; break;
1464                         case 'S': value = hsv[1]; break;
1465                         case 'V': value = hsv[2]; break;
1466                 }
1467         }
1468         else if (but->pointype == UI_BUT_POIN_CHAR) {
1469                 value = *(char *)but->poin;
1470         }
1471         else if (but->pointype == UI_BUT_POIN_SHORT) {
1472                 value = *(short *)but->poin;
1473         }
1474         else if (but->pointype == UI_BUT_POIN_INT) {
1475                 value = *(int *)but->poin;
1476         }
1477         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1478                 value = *(float *)but->poin;
1479         }
1480
1481         return value;
1482 }
1483
1484 void ui_set_but_val(uiBut *but, double value)
1485 {
1486         PropertyRNA *prop;
1487
1488         /* value is a hsv value: convert to rgb */
1489         if (but->rnaprop) {
1490                 prop = but->rnaprop;
1491
1492                 if (RNA_property_editable(&but->rnapoin, prop)) {
1493                         switch (RNA_property_type(prop)) {
1494                                 case PROP_BOOLEAN:
1495                                         if (RNA_property_array_length(&but->rnapoin, prop))
1496                                                 RNA_property_boolean_set_index(&but->rnapoin, prop, but->rnaindex, value);
1497                                         else
1498                                                 RNA_property_boolean_set(&but->rnapoin, prop, value);
1499                                         break;
1500                                 case PROP_INT:
1501                                         if (RNA_property_array_length(&but->rnapoin, prop))
1502                                                 RNA_property_int_set_index(&but->rnapoin, prop, but->rnaindex, (int)value);
1503                                         else
1504                                                 RNA_property_int_set(&but->rnapoin, prop, (int)value);
1505                                         break;
1506                                 case PROP_FLOAT:
1507                                         if (RNA_property_array_length(&but->rnapoin, prop))
1508                                                 RNA_property_float_set_index(&but->rnapoin, prop, but->rnaindex, value);
1509                                         else
1510                                                 RNA_property_float_set(&but->rnapoin, prop, value);
1511                                         break;
1512                                 case PROP_ENUM:
1513                                         if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1514                                                 int ivalue = (int)value;
1515                                                 ivalue ^= RNA_property_enum_get(&but->rnapoin, prop); /* toggle for enum/flag buttons */
1516                                                 RNA_property_enum_set(&but->rnapoin, prop, ivalue);
1517                                         }
1518                                         else {
1519                                                 RNA_property_enum_set(&but->rnapoin, prop, value);
1520                                         }
1521                                         break;
1522                                 default:
1523                                         break;
1524                         }
1525                 }
1526
1527                 /* we can't be sure what RNA set functions actually do,
1528                  * so leave this unset */
1529                 value = UI_BUT_VALUE_UNSET;
1530         }
1531         else if (but->pointype == 0) {
1532                 /* pass */
1533         }
1534         else if (but->type == HSVSLI) {
1535                 float *fp, hsv[3];
1536                 
1537                 fp = (but->editvec) ? but->editvec : (float *)but->poin;
1538                 rgb_to_hsv_v(fp, hsv);
1539                 
1540                 switch (but->str[0]) {
1541                         case 'H': hsv[0] = value; break;
1542                         case 'S': hsv[1] = value; break;
1543                         case 'V': hsv[2] = value; break;
1544                 }
1545                 
1546                 hsv_to_rgb_v(hsv, fp);
1547                 
1548         }
1549         else {
1550                 /* first do rounding */
1551                 if (but->pointype == UI_BUT_POIN_CHAR) {
1552                         value = (char)floor(value + 0.5);
1553                 }
1554                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1555                         /* gcc 3.2.1 seems to have problems
1556                          * casting a double like 32772.0 to
1557                          * a short so we cast to an int, then
1558                          * to a short.
1559                          *
1560                          * Update: even in gcc.4.6 using intermediate int cast gives -32764,
1561                          * where as a direct cast from double to short gives -32768,
1562                          * if this difference isn't important we could remove this hack,
1563                          * since we dont support gcc3 anymore - Campbell */
1564                         int gcckludge;
1565                         gcckludge = (int) floor(value + 0.5);
1566                         value = (short)gcckludge;
1567                 }
1568                 else if (but->pointype == UI_BUT_POIN_INT)
1569                         value = (int)floor(value + 0.5);
1570                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1571                         float fval = (float)value;
1572                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1573                         value = fval;
1574                 }
1575                 
1576                 /* then set value with possible edit override */
1577                 if (but->editval)
1578                         value = *but->editval = value;
1579                 else if (but->pointype == UI_BUT_POIN_CHAR)
1580                         value = *((char *)but->poin) = (char)value;
1581                 else if (but->pointype == UI_BUT_POIN_SHORT)
1582                         value = *((short *)but->poin) = (short)value;
1583                 else if (but->pointype == UI_BUT_POIN_INT)
1584                         value = *((int *)but->poin) = (int)value;
1585                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1586                         value = *((float *)but->poin) = (float)value;
1587         }
1588
1589         /* update select flag */
1590         ui_is_but_sel(but, &value);
1591 }
1592
1593 int ui_get_but_string_max_length(uiBut *but)
1594 {
1595         if (ELEM(but->type, TEX, SEARCH_MENU))
1596                 return but->hardmax;
1597         else if (but->type == IDPOIN)
1598                 return MAX_ID_NAME - 2;
1599         else
1600                 return UI_MAX_DRAW_STR;
1601 }
1602
1603 static double ui_get_but_scale_unit(uiBut *but, double value)
1604 {
1605         UnitSettings *unit = but->block->unit;
1606         int unit_type = uiButGetUnitType(but);
1607
1608         if (unit_type == PROP_UNIT_LENGTH) {
1609                 return value * (double)unit->scale_length;
1610         }
1611         else if (unit_type == PROP_UNIT_AREA) {
1612                 return value * pow(unit->scale_length, 2);
1613         }
1614         else if (unit_type == PROP_UNIT_VOLUME) {
1615                 return value * pow(unit->scale_length, 3);
1616         }
1617         else if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1618                 Scene *scene = CTX_data_scene(but->block->evil_C);
1619                 return FRA2TIME(value);
1620         }
1621         else {
1622                 return value;
1623         }
1624 }
1625
1626 /* str will be overwritten */
1627 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1628 {
1629         if (ui_is_but_unit(but)) {
1630                 UnitSettings *unit = but->block->unit;
1631                 int unit_type = uiButGetUnitType(but);
1632                 char *orig_str;
1633                 
1634                 orig_str = MEM_callocN(sizeof(char) * maxlen + 1, "textedit sub str");
1635                 memcpy(orig_str, str, maxlen);
1636                 
1637                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1638                 
1639                 MEM_freeN(orig_str);
1640         }
1641 }
1642
1643 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, int pad)
1644 {
1645         UnitSettings *unit = but->block->unit;
1646         int do_split = unit->flag & USER_UNIT_OPT_SPLIT;
1647         int unit_type = uiButGetUnitType(but);
1648         int precision = but->a2;
1649
1650         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
1651
1652         /* Sanity checks */
1653         if (precision > PRECISION_FLOAT_MAX) precision = PRECISION_FLOAT_MAX;
1654         else if (precision == 0) precision = 2;
1655
1656         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
1657                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
1658 }
1659
1660 static float ui_get_but_step_unit(uiBut *but, float step_default)
1661 {
1662         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
1663         float step;
1664
1665         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1666
1667         if (step > 0.0f) { /* -1 is an error value */
1668                 return (float)((double)step / ui_get_but_scale_unit(but, 1.0)) * 100.0f;
1669         }
1670         else {
1671                 return step_default;
1672         }
1673 }
1674
1675
1676 void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
1677 {
1678         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1679                 PropertyType type;
1680                 const char *buf = NULL;
1681                 int buf_len;
1682
1683                 type = RNA_property_type(but->rnaprop);
1684
1685                 if (type == PROP_STRING) {
1686                         /* RNA string */
1687                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
1688                 }
1689                 else if (type == PROP_ENUM) {
1690                         /* RNA enum */
1691                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
1692                         if (RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &buf)) {
1693                                 BLI_strncpy(str, buf, maxlen);
1694                                 buf = str;
1695                         }
1696                 }
1697                 else if (type == PROP_POINTER) {
1698                         /* RNA pointer */
1699                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1700                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
1701                 }
1702                 else {
1703                         BLI_assert(0);
1704                 }
1705
1706                 if (!buf) {
1707                         str[0] = '\0';
1708                 }
1709                 else if (buf && buf != str) {
1710                         /* string was too long, we have to truncate */
1711                         memcpy(str, buf, MIN2(maxlen, (size_t)buf_len + 1));
1712                         MEM_freeN((void *)buf);
1713                 }
1714         }
1715         else if (but->type == IDPOIN) {
1716                 /* ID pointer */
1717                 if (but->idpoin_idpp) { /* Can be NULL for ID properties by python */
1718                         ID *id = *(but->idpoin_idpp);
1719                         if (id) {
1720                                 BLI_strncpy(str, id->name + 2, maxlen);
1721                                 return;
1722                         }
1723                 }
1724                 str[0] = '\0';
1725                 return;
1726         }
1727         else if (but->type == TEX) {
1728                 /* string */
1729                 BLI_strncpy(str, but->poin, maxlen);
1730                 return;
1731         }
1732         else if (but->type == SEARCH_MENU) {
1733                 /* string */
1734                 BLI_strncpy(str, but->poin, maxlen);
1735                 return;
1736         }
1737         else if (ui_but_anim_expression_get(but, str, maxlen)) {
1738                 /* driver expression */
1739         }
1740         else {
1741                 /* number editing */
1742                 double value;
1743
1744                 value = ui_get_but_val(but);
1745
1746                 if (ui_is_but_float(but)) {
1747                         if (ui_is_but_unit(but)) {
1748                                 ui_get_but_string_unit(but, str, maxlen, value, 0);
1749                         }
1750                         else {
1751                                 const int prec = ui_but_float_precision(but, value);
1752                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
1753                         }
1754                 }
1755                 else
1756                         BLI_snprintf(str, maxlen, "%d", (int)value);
1757         }
1758 }
1759
1760 #ifdef WITH_PYTHON
1761
1762 static int ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
1763 {
1764         char str_unit_convert[256];
1765         const int unit_type = uiButGetUnitType(but);
1766
1767         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
1768
1769         /* ugly, use the draw string to get the value,
1770          * this could cause problems if it includes some text which resolves to a unit */
1771         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
1772                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1773
1774         return (BPY_button_exec(C, str_unit_convert, value, TRUE) != -1);
1775 }
1776
1777 #endif /* WITH_PYTHON */
1778
1779
1780 int ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
1781 {
1782         int ok = FALSE;
1783
1784 #ifdef WITH_PYTHON
1785
1786         if (str[0] != '\0') {
1787                 int is_unit_but = ui_is_but_unit(but);
1788                 /* only enable verbose if we won't run again with units */
1789                 if (BPY_button_exec(C, str, value, is_unit_but == FALSE) != -1) {
1790                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
1791                         if (is_unit_but) {
1792                                 char str_new[128];
1793
1794                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
1795                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
1796                         }
1797                         else {
1798                                 ok = TRUE; /* parse normal string via py (no unit conversion needed) */
1799                         }
1800                 }
1801                 else if (is_unit_but) {
1802                         /* parse failed, this is a unit but so run replacements and parse again */
1803                         ok = ui_set_but_string_eval_num_unit(C, but, str, value);
1804                 }
1805         }
1806
1807 #else /* WITH_PYTHON */
1808
1809         *value = atof(str);
1810         ok = TRUE;
1811
1812         (void)C;
1813         (void)but;
1814
1815 #endif /* WITH_PYTHON */
1816
1817         return ok;
1818 }
1819
1820
1821 int ui_set_but_string(bContext *C, uiBut *but, const char *str)
1822 {
1823         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1824                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
1825                         PropertyType type;
1826
1827                         type = RNA_property_type(but->rnaprop);
1828
1829                         if (type == PROP_STRING) {
1830                                 /* RNA string */
1831                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
1832                                 return 1;
1833                         }
1834                         else if (type == PROP_POINTER) {
1835                                 /* RNA pointer */
1836                                 PointerRNA ptr, rptr;
1837                                 PropertyRNA *prop;
1838
1839                                 if (str == NULL || str[0] == '\0') {
1840                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
1841                                         return 1;
1842                                 }
1843                                 else {
1844                                         ptr = but->rnasearchpoin;
1845                                         prop = but->rnasearchprop;
1846                                         
1847                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
1848                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
1849
1850                                         return 1;
1851                                 }
1852
1853                                 return 0;
1854                         }
1855                         else if (type == PROP_ENUM) {
1856                                 int value;
1857                                 if (RNA_property_enum_value(but->block->evil_C, &but->rnapoin, but->rnaprop, str, &value)) {
1858                                         RNA_property_enum_set(&but->rnapoin, but->rnaprop, value);
1859                                         return 1;
1860                                 }
1861                                 return 0;
1862                         }
1863                         else {
1864                                 BLI_assert(0);
1865                         }
1866                 }
1867         }
1868         else if (but->type == IDPOIN) {
1869                 /* ID pointer */
1870                 but->idpoin_func(C, str, but->idpoin_idpp);
1871                 return 1;
1872         }
1873         else if (but->type == TEX) {
1874                 /* string */
1875                 if (ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
1876                 else BLI_strncpy(but->poin, str, but->hardmax);
1877
1878                 return 1;
1879         }
1880         else if (but->type == SEARCH_MENU) {
1881                 /* string */
1882                 BLI_strncpy(but->poin, str, but->hardmax);
1883                 return 1;
1884         }
1885         else if (ui_but_anim_expression_set(but, str)) {
1886                 /* driver expression */
1887                 return 1;
1888         }
1889         else if (str[0] == '#') {
1890                 /* shortcut to create new driver expression (versus immediate Py-execution) */
1891                 return ui_but_anim_expression_create(but, str + 1);
1892         }
1893         else {
1894                 /* number editing */
1895                 double value;
1896
1897                 if (ui_set_but_string_eval_num(C, but, str, &value) == FALSE) {
1898                         return 0;
1899                 }
1900
1901                 if (!ui_is_but_float(but)) value = (int)floor(value + 0.5);
1902                 if (but->type == NUMABS) value = fabs(value);
1903
1904                 /* not that we use hard limits here */
1905                 if (value < (double)but->hardmin) value = but->hardmin;
1906                 if (value > (double)but->hardmax) value = but->hardmax;
1907
1908                 ui_set_but_val(but, value);
1909                 return 1;
1910         }
1911
1912         return 0;
1913 }
1914
1915 void ui_set_but_default(bContext *C, short all)
1916 {
1917         PointerRNA ptr;
1918
1919         WM_operator_properties_create(&ptr, "UI_OT_reset_default_button");
1920         RNA_boolean_set(&ptr, "all", all);
1921         WM_operator_name_call(C, "UI_OT_reset_default_button", WM_OP_EXEC_DEFAULT, &ptr);
1922         WM_operator_properties_free(&ptr);
1923 }
1924
1925 static double soft_range_round_up(double value, double max)
1926 {
1927         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
1928          * checking for 0.0 prevents floating point exceptions */
1929         double newmax = (value != 0.0) ? pow(10.0, ceil(log(value) / M_LN10)) : 0.0;
1930
1931         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
1932                 return newmax * 0.2;
1933         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
1934                 return newmax * 0.5;
1935         else
1936                 return newmax;
1937 }
1938
1939 static double soft_range_round_down(double value, double max)
1940 {
1941         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
1942          * checking for 0.0 prevents floating point exceptions */
1943         double newmax = (value != 0.0) ? pow(10.0, floor(log(value) / M_LN10)) : 0.0;
1944
1945         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
1946                 return newmax * 5.0;
1947         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
1948                 return newmax * 2.0;
1949         else
1950                 return newmax;
1951 }
1952
1953 void ui_set_but_soft_range(uiBut *but, double value)
1954 {
1955         /* ideally we would not limit this but practically, its more then
1956          * enough worst case is very long vectors wont use a smart soft-range
1957          * which isn't so bad. */
1958
1959         if (but->rnaprop) {
1960                 const PropertyType type = RNA_property_type(but->rnaprop);
1961                 double softmin, softmax /*, step, precision*/;
1962                 double value_min = value;
1963                 double value_max = value;
1964
1965                 /* clamp button range to something reasonable in case
1966                  * we get -inf/inf from RNA properties */
1967                 if (type == PROP_INT) {
1968                         int imin, imax, istep;
1969                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1970
1971                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
1972                         softmin = (imin == INT_MIN) ? -1e4 : imin;
1973                         softmax = (imin == INT_MAX) ? 1e4 : imax;
1974                         /*step = istep;*/ /*UNUSED*/
1975                         /*precision = 1;*/ /*UNUSED*/
1976
1977                         if (array_len >= 2) {
1978                                 int value_range[2];
1979                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1980                                 value_min = (double)value_range[0];
1981                                 value_max = (double)value_range[1];
1982                         }
1983                 }
1984                 else if (type == PROP_FLOAT) {
1985                         float fmin, fmax, fstep, fprecision;
1986                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1987
1988                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
1989                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
1990                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
1991                         /*step = fstep;*/ /*UNUSED*/
1992                         /*precision = fprecision;*/ /*UNUSED*/
1993
1994                         if (array_len >= 2) {
1995                                 float value_range[2];
1996                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1997                                 value_min = (double)value_range[0];
1998                                 value_max = (double)value_range[1];
1999                         }
2000                 }
2001                 else
2002                         return;
2003
2004                 /* if the value goes out of the soft/max range, adapt the range */
2005                 if (value_min + 1e-10 < softmin) {
2006                         if (value_min < 0.0)
2007                                 softmin = -soft_range_round_up(-value_min, -softmin);
2008                         else
2009                                 softmin = soft_range_round_down(value_min, softmin);
2010
2011                         if (softmin < (double)but->hardmin)
2012                                 softmin = (double)but->hardmin;
2013                 }
2014                 if (value_max - 1e-10 > softmax) {
2015                         if (value_max < 0.0)
2016                                 softmax = -soft_range_round_down(-value_max, -softmax);
2017                         else
2018                                 softmax = soft_range_round_up(value_max, softmax);
2019
2020                         if (softmax > (double)but->hardmax)
2021                                 softmax = but->hardmax;
2022                 }
2023
2024                 but->softmin = softmin;
2025                 but->softmax = softmax;
2026         }
2027 }
2028
2029 /* ******************* Free ********************/
2030
2031 static void ui_free_link(uiLink *link)
2032 {
2033         if (link) {
2034                 BLI_freelistN(&link->lines);
2035                 MEM_freeN(link);
2036         }
2037 }
2038
2039 /* can be called with C==NULL */
2040 static void ui_free_but(const bContext *C, uiBut *but)
2041 {
2042         if (but->opptr) {
2043                 WM_operator_properties_free(but->opptr);
2044                 MEM_freeN(but->opptr);
2045         }
2046
2047         if (but->func_argN) {
2048                 MEM_freeN(but->func_argN);
2049         }
2050
2051         if (but->active) {
2052                 /* XXX solve later, buttons should be free-able without context ideally,
2053                  * however they may have open tooltips or popup windows, which need to
2054                  * be closed using a context pointer */
2055                 if (C) {
2056                         ui_button_active_free(C, but);
2057                 }
2058                 else {
2059                         if (but->active) {
2060                                 MEM_freeN(but->active);
2061                         }
2062                 }
2063         }
2064         if (but->str && but->str != but->strdata) {
2065                 MEM_freeN(but->str);
2066         }
2067         ui_free_link(but->link);
2068
2069         if ((but->type == BUT_IMAGE) && but->poin) {
2070                 IMB_freeImBuf((struct ImBuf *)but->poin);
2071         }
2072
2073         MEM_freeN(but);
2074 }
2075
2076 /* can be called with C==NULL */
2077 void uiFreeBlock(const bContext *C, uiBlock *block)
2078 {
2079         uiBut *but;
2080
2081         while ( (but = block->buttons.first) ) {
2082                 BLI_remlink(&block->buttons, but);
2083                 ui_free_but(C, but);
2084         }
2085
2086         if (block->unit) {
2087                 MEM_freeN(block->unit);
2088         }
2089
2090         if (block->func_argN) {
2091                 MEM_freeN(block->func_argN);
2092         }
2093
2094         CTX_store_free_list(&block->contexts);
2095
2096         BLI_freelistN(&block->saferct);
2097         
2098         MEM_freeN(block);
2099 }
2100
2101 /* can be called with C==NULL */
2102 void uiFreeBlocks(const bContext *C, ListBase *lb)
2103 {
2104         uiBlock *block;
2105         
2106         while ( (block = lb->first) ) {
2107                 BLI_remlink(lb, block);
2108                 uiFreeBlock(C, block);
2109         }
2110 }
2111
2112 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2113 {
2114         uiBlock *block, *nextblock;
2115
2116         for (block = lb->first; block; block = nextblock) {
2117                 nextblock = block->next;
2118         
2119                 if (!block->handle) {
2120                         if (!block->active) {
2121                                 BLI_remlink(lb, block);
2122                                 uiFreeBlock(C, block);
2123                         }
2124                         else
2125                                 block->active = 0;
2126                 }
2127         }
2128 }
2129
2130 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2131 {
2132         ListBase *lb = &region->uiblocks;
2133         uiBlock *oldblock = NULL;
2134
2135         /* each listbase only has one block with this name, free block
2136          * if is already there so it can be rebuilt from scratch */
2137         if (lb) {
2138                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2139
2140                 if (oldblock) {
2141                         oldblock->active = 0;
2142                         oldblock->panel = NULL;
2143                 }
2144
2145                 /* at the beginning of the list! for dynamical menus/blocks */
2146                 BLI_addhead(lb, block);
2147         }
2148
2149         block->oldblock = oldblock;
2150 }
2151
2152 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2153 {
2154         uiBlock *block;
2155         wmWindow *window;
2156         Scene *scn;
2157         int getsizex, getsizey;
2158
2159         window = CTX_wm_window(C);
2160         scn = CTX_data_scene(C);
2161
2162         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2163         block->active = 1;
2164         block->dt = dt;
2165         block->evil_C = (void *)C;  /* XXX */
2166
2167         if (scn) {
2168                 block->color_profile = TRUE;
2169
2170                 /* store display device name, don't lookup for transformations yet
2171                  * block could be used for non-color displays where looking up for transformation
2172                  * would slow down redraw, so only lookup for actual transform when it's indeed
2173                  * needed
2174                  */
2175                 block->display_device = scn->display_settings.display_device;
2176
2177                 /* copy to avoid crash when scene gets deleted with ui still open */
2178                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2179                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2180         }
2181
2182         BLI_strncpy(block->name, name, sizeof(block->name));
2183
2184         if (region)
2185                 uiBlockSetRegion(block, region);
2186
2187         /* window matrix and aspect */
2188         if (region && region->swinid) {
2189                 wm_subwindow_getmatrix(window, region->swinid, block->winmat);
2190                 wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
2191
2192                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2193         }
2194         else {
2195                 /* no subwindow created yet, for menus for example, so we
2196                  * use the main window instead, since buttons are created
2197                  * there anyway */
2198                 wm_subwindow_getmatrix(window, window->screen->mainwin, block->winmat);
2199                 wm_subwindow_getsize(window, window->screen->mainwin, &getsizex, &getsizey);
2200
2201                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2202                 block->auto_open = TRUE;
2203                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2204         }
2205
2206         return block;
2207 }
2208
2209 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2210 {
2211         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2212 }
2213
2214 void uiBlockSetEmboss(uiBlock *block, char dt)
2215 {
2216         block->dt = dt;
2217 }
2218
2219 void ui_check_but(uiBut *but)
2220 {
2221         /* if something changed in the button */
2222         double value = UI_BUT_VALUE_UNSET;
2223 //      float okwidth; // UNUSED
2224         
2225         ui_is_but_sel(but, &value);
2226         
2227         /* only update soft range while not editing */
2228         if (but->rnaprop && !(but->editval || but->editstr || but->editvec)) {
2229                 UI_GET_BUT_VALUE_INIT(but, value);
2230                 ui_set_but_soft_range(but, value);
2231         }
2232
2233         /* test for min and max, icon sliders, etc */
2234         switch (but->type) {
2235                 case NUM:
2236                 case SLI:
2237                 case SCROLL:
2238                 case NUMSLI:
2239                 case HSVSLI:
2240                         UI_GET_BUT_VALUE_INIT(but, value);
2241                         if (value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2242                         else if (value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2243                         break;
2244                         
2245                 case NUMABS:
2246                 {
2247                         double value_abs;
2248                         UI_GET_BUT_VALUE_INIT(but, value);
2249                         value_abs = fabs(value);
2250                         if (value_abs < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2251                         else if (value_abs > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2252                         break;
2253                 }
2254                 case ICONTOG: 
2255                 case ICONTOGN:
2256                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2257                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2258                                 else but->iconadd = 0;
2259                         }
2260                         break;
2261                         
2262                 case ICONROW:
2263                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2264                                 UI_GET_BUT_VALUE_INIT(but, value);
2265                                 but->iconadd = (int)value - (int)(but->hardmin);
2266                         }
2267                         break;
2268                         
2269                 case ICONTEXTROW:
2270                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2271                                 UI_GET_BUT_VALUE_INIT(but, value);
2272                                 but->iconadd = (int)value - (int)(but->hardmin);
2273                         }
2274                         break;
2275
2276                         /* quiet warnings for unhandled types */
2277                 default:
2278                         break;
2279         }
2280         
2281         
2282         /* safety is 4 to enable small number buttons (like 'users') */
2283         // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2284         
2285         /* name: */
2286         switch (but->type) {
2287         
2288                 case MENU:
2289                 case ICONTEXTROW:
2290                 
2291                         if (BLI_rctf_size_x(&but->rect) > 24.0f) {
2292                                 UI_GET_BUT_VALUE_INIT(but, value);
2293                                 ui_set_name_menu(but, (int)value);
2294                         }
2295                         break;
2296         
2297                 case NUM:
2298                 case NUMSLI:
2299                 case HSVSLI:
2300                 case NUMABS:
2301
2302                         UI_GET_BUT_VALUE_INIT(but, value);
2303
2304                         if (ui_is_but_float(but)) {
2305                                 if (value == (double) FLT_MAX) {
2306                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%sinf", but->str);
2307                                 }
2308                                 else if (value == (double) -FLT_MAX) {
2309                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s-inf", but->str);
2310                                 }
2311                                 /* support length type buttons */
2312                                 else if (ui_is_but_unit(but)) {
2313                                         char new_str[sizeof(but->drawstr)];
2314                                         ui_get_but_string_unit(but, new_str, sizeof(new_str), value, TRUE);
2315                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, new_str);
2316                                 }
2317                                 else {
2318                                         const int prec = ui_but_float_precision(but, value);
2319                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2320                                 }
2321                         }
2322                         else {
2323                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%d", but->str, (int)value);
2324                         }
2325                         
2326                         if (but->rnaprop) {
2327                                 PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2328                         
2329                                 if (pstype == PROP_PERCENTAGE)
2330                                         strcat(but->drawstr, "%");
2331                         }
2332                         break;
2333
2334                 case LABEL:
2335                         if (ui_is_but_float(but)) {
2336                                 int prec;
2337                                 UI_GET_BUT_VALUE_INIT(but, value);
2338                                 prec = ui_but_float_precision(but, value);
2339                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2340                         }
2341                         else {
2342                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2343                         }
2344                 
2345                         break;
2346
2347                 case IDPOIN:
2348                 case TEX:
2349                 case SEARCH_MENU:
2350                         if (!but->editstr) {
2351                                 char str[UI_MAX_DRAW_STR];
2352
2353                                 ui_get_but_string(but, str, UI_MAX_DRAW_STR - strlen(but->str));
2354
2355                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2356                         }
2357                         break;
2358         
2359                 case KEYEVT:
2360                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2361                         if (but->flag & UI_SELECT) {
2362                                 strcat(but->drawstr, "Press a key");
2363                         }
2364                         else {
2365                                 UI_GET_BUT_VALUE_INIT(but, value);
2366                                 strcat(but->drawstr, WM_key_event_string((short)value));
2367                         }
2368                         break;
2369                 
2370                 case HOTKEYEVT:
2371                         if (but->flag & UI_SELECT) {
2372                                 but->drawstr[0] = '\0';
2373
2374                                 if (but->modifier_key) {
2375                                         char *str = but->drawstr;
2376
2377                                         if (but->modifier_key & KM_SHIFT)
2378                                                 str = strcat(str, "Shift ");
2379                                         if (but->modifier_key & KM_CTRL)
2380                                                 str = strcat(str, "Ctrl ");
2381                                         if (but->modifier_key & KM_ALT)
2382                                                 str = strcat(str, "Alt ");
2383                                         if (but->modifier_key & KM_OSKEY)
2384                                                 str = strcat(str, "Cmd ");
2385
2386                                         (void)str; /* UNUSED */
2387                                 }
2388                                 else
2389                                         strcat(but->drawstr, "Press a key  ");
2390                         }
2391                         else
2392                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2393
2394                         break;
2395
2396                 case BUT_TOGDUAL:
2397                         /* trying to get the dual-icon to left of text... not very nice */
2398                         if (but->str[0]) {
2399                                 BLI_strncpy(but->drawstr, "  ", UI_MAX_DRAW_STR);
2400                                 BLI_strncpy(but->drawstr + 2, but->str, UI_MAX_DRAW_STR - 2);
2401                         }
2402                         break;
2403                 
2404                 case HSVCUBE:
2405                 case HSVCIRCLE:
2406                         break;
2407                 default:
2408                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2409                 
2410         }
2411
2412         /* if we are doing text editing, this will override the drawstr */
2413         if (but->editstr)
2414                 BLI_strncpy(but->drawstr, but->editstr, UI_MAX_DRAW_STR);
2415         
2416         /* text clipping moved to widget drawing code itself */
2417 }
2418
2419
2420 void uiBlockBeginAlign(uiBlock *block)
2421 {
2422         /* if other align was active, end it */
2423         if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2424
2425         block->flag |= UI_BUT_ALIGN_DOWN;
2426         block->alignnr++;
2427
2428         /* buttons declared after this call will get this align nr */ // XXX flag?
2429 }
2430
2431 static int buts_are_horiz(uiBut *but1, uiBut *but2)
2432 {
2433         float dx, dy;
2434         
2435         dx = fabs(but1->rect.xmax - but2->rect.xmin);
2436         dy = fabs(but1->rect.ymin - but2->rect.ymax);
2437         
2438         if (dx > dy) return 0;
2439         return 1;
2440 }
2441
2442 void uiBlockEndAlign(uiBlock *block)
2443 {
2444         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
2445 }
2446
2447 int ui_but_can_align(uiBut *but)
2448 {
2449         return !ELEM4(but->type, LABEL, OPTION, OPTIONN, SEPR);
2450 }
2451
2452 static void ui_block_do_align_but(uiBut *first, short nr)
2453 {
2454         uiBut *prev, *but = NULL, *next;
2455         int flag = 0, cols = 0, rows = 0;
2456         
2457         /* auto align */
2458
2459         for (but = first; but && but->alignnr == nr; but = but->next) {
2460                 if (but->next && but->next->alignnr == nr) {
2461                         if (buts_are_horiz(but, but->next)) cols++;
2462                         else rows++;
2463                 }
2464         }
2465
2466         /* rows == 0: 1 row, cols == 0: 1 column */
2467         
2468         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2469         for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
2470                 next = but->next;
2471                 if (next && next->alignnr != nr)
2472                         next = NULL;
2473
2474                 /* clear old flag */
2475                 but->flag &= ~UI_BUT_ALIGN;
2476                         
2477                 if (flag == 0) {  /* first case */
2478                         if (next) {
2479                                 if (buts_are_horiz(but, next)) {
2480                                         if (rows == 0)
2481                                                 flag = UI_BUT_ALIGN_RIGHT;
2482                                         else 
2483                                                 flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT;
2484                                 }
2485                                 else {
2486                                         flag = UI_BUT_ALIGN_DOWN;
2487                                 }
2488                         }
2489                 }
2490                 else if (next == NULL) {  /* last case */
2491                         if (prev) {
2492                                 if (buts_are_horiz(prev, but)) {
2493                                         if (rows == 0)
2494                                                 flag = UI_BUT_ALIGN_LEFT;
2495                                         else
2496                                                 flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT;
2497                                 }
2498                                 else flag = UI_BUT_ALIGN_TOP;
2499                         }
2500                 }
2501                 else if (buts_are_horiz(but, next)) {
2502                         /* check if this is already second row */
2503                         if (prev && buts_are_horiz(prev, but) == 0) {
2504                                 flag &= ~UI_BUT_ALIGN_LEFT;
2505                                 flag |= UI_BUT_ALIGN_TOP;
2506                                 /* exception case: bottom row */
2507                                 if (rows > 0) {
2508                                         uiBut *bt = but;
2509                                         while (bt && bt->alignnr == nr) {
2510                                                 if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) {
2511                                                         break;
2512                                                 }
2513                                                 bt = bt->next;
2514                                         }
2515                                         if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
2516                                 }
2517                         }
2518                         else flag |= UI_BUT_ALIGN_LEFT;
2519                 }
2520                 else {
2521                         if (cols == 0) {
2522                                 flag |= UI_BUT_ALIGN_TOP;
2523                         }
2524                         else {  /* next button switches to new row */
2525                                 
2526                                 if (prev && buts_are_horiz(prev, but))
2527                                         flag |= UI_BUT_ALIGN_LEFT;
2528                                 else {
2529                                         flag &= ~UI_BUT_ALIGN_LEFT;
2530                                         flag |= UI_BUT_ALIGN_TOP;
2531                                 }
2532                                 
2533                                 if ((flag & UI_BUT_ALIGN_TOP) == 0) {  /* stil top row */
2534                                         if (prev) {
2535                                                 if (next && buts_are_horiz(but, next))
2536                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT;
2537                                                 else {
2538                                                         /* last button in top row */
2539                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT;
2540                                                 }
2541                                         }
2542                                         else 
2543                                                 flag |= UI_BUT_ALIGN_DOWN;
2544                                 }
2545                                 else 
2546                                         flag |= UI_BUT_ALIGN_TOP;
2547                         }
2548                 }
2549                 
2550                 but->flag |= flag;
2551                 
2552                 /* merge coordinates */
2553                 if (prev) {
2554                         /* simple cases */
2555                         if (rows == 0) {
2556                                 but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2557                                 prev->rect.xmax = but->rect.xmin;
2558                         }
2559                         else if (cols == 0) {
2560                                 but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2561                                 prev->rect.ymin = but->rect.ymax;
2562                         }
2563                         else {
2564                                 if (buts_are_horiz(prev, but)) {
2565                                         but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2566                                         prev->rect.xmax = but->rect.xmin;
2567                                         /* copy height too */
2568                                         but->rect.ymax = prev->rect.ymax;
2569                                 }
2570                                 else if (prev->prev && buts_are_horiz(prev->prev, prev) == 0) {
2571                                         /* the previous button is a single one in its row */
2572                                         but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2573                                         prev->rect.ymin = but->rect.ymax;
2574                                         
2575                                         but->rect.xmin = prev->rect.xmin;
2576                                         if (next && buts_are_horiz(but, next) == 0)
2577                                                 but->rect.xmax = prev->rect.xmax;
2578                                 }
2579                                 else {
2580                                         /* the previous button is not a single one in its row */
2581                                         but->rect.ymax = prev->rect.ymin;
2582                                 }
2583                         }
2584                 }
2585         }
2586 }
2587
2588 void ui_block_do_align(uiBlock *block)
2589 {
2590         uiBut *but;
2591         short nr;
2592
2593         /* align buttons with same align nr */
2594         for (but = block->buttons.first; but; ) {
2595                 if (but->alignnr) {
2596                         nr = but->alignnr;
2597                         ui_block_do_align_but(but, nr);
2598
2599                         /* skip with same number */
2600                         for (; but && but->alignnr == nr; but = but->next) {
2601                                 /* pass */
2602                         }
2603
2604                         if (!but) {
2605                                 break;
2606                         }
2607                 }
2608                 else {
2609                         but = but->next;
2610                 }
2611         }
2612 }
2613
2614 struct ColorManagedDisplay *ui_block_display_get(uiBlock *block)
2615 {
2616         return IMB_colormanagement_display_get_named(block->display_device);
2617 }
2618
2619 void ui_block_to_display_space_v3(uiBlock *block, float pixel[3])
2620 {
2621         struct ColorManagedDisplay *display = ui_block_display_get(block);
2622
2623         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
2624 }
2625
2626 void ui_block_to_scene_linear_v3(uiBlock *block, float pixel[3])
2627 {
2628         struct ColorManagedDisplay *display = ui_block_display_get(block);
2629
2630         IMB_colormanagement_display_to_scene_linear_v3(pixel, display);
2631 }
2632
2633 /**
2634  * \brief ui_def_but is the function that draws many button types
2635  *
2636  * \param x,y The lower left hand corner of the button (X axis)
2637  * \param width,height The size of the button.
2638  *
2639  * for float buttons:
2640  * - \a a1 Click Step (how much to change the value each click)
2641  * - \a a2 Number of decimal point values to display. 0 defaults to 3 (0.000)
2642  *      1,2,3, and a maximum of 4, all greater values will be clamped to 4.
2643  */
2644 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
2645                          int x, int y, short width, short height,
2646                          void *poin, float min, float max, float a1, float a2, const char *tip)
2647 {
2648         uiBut *but;
2649         int slen;
2650
2651         BLI_assert(width >= 0);
2652         BLI_assert(height >= 0);
2653
2654         /* we could do some more error checks here */
2655         if ((type & BUTTYPE) == LABEL) {
2656                 BLI_assert((poin != NULL || min != 0.0f || max != 0.0f || (a1 == 0.0f && a2 != 0.0f) || (a1 != 0.0f && a1 != 1.0f)) == FALSE);
2657         }
2658
2659         if (type & UI_BUT_POIN_TYPES) {  /* a pointer is required */
2660                 if (poin == NULL) {
2661                         BLI_assert(0);
2662                         return NULL;
2663                 }
2664         }
2665
2666         but = MEM_callocN(sizeof(uiBut), "uiBut");
2667
2668         but->type = type & BUTTYPE;
2669         but->pointype = type & UI_BUT_POIN_TYPES;
2670         but->bit = type & UI_BUT_POIN_BIT;
2671         but->bitnr = type & 31;
2672         but->icon = ICON_NONE;
2673         but->iconadd = 0;
2674
2675         but->retval = retval;
2676
2677         slen = strlen(str);
2678         if (slen >= UI_MAX_NAME_STR - 1) {
2679                 but->str = MEM_mallocN(slen + 2, "ui_def_but str"); /* why +2 ? */
2680         }
2681         else {
2682                 but->str = but->strdata;
2683         }
2684         memcpy(but->str, str, slen + 1);
2685
2686         but->rect.xmin = x;
2687         but->rect.ymin = y;
2688         but->rect.xmax = but->rect.xmin + width;
2689         but->rect.ymax = but->rect.ymin + height;
2690
2691         but->poin = poin;
2692         but->hardmin = but->softmin = min;
2693         but->hardmax = but->softmax = max;
2694         but->a1 = a1;
2695         but->a2 = a2;
2696         but->tip = tip;
2697
2698         but->lock = block->lock;
2699         but->lockstr = block->lockstr;
2700         but->dt = block->dt;
2701
2702         but->aspect = 1.0f;  /* XXX block->aspect; */
2703         but->block = block;  /* pointer back, used for frontbuffer status, and picker */
2704
2705         if ((block->flag & UI_BUT_ALIGN) && ui_but_can_align(but))
2706                 but->alignnr = block->alignnr;
2707
2708         but->func = block->func;
2709         but->func_arg1 = block->func_arg1;
2710         but->func_arg2 = block->func_arg2;
2711
2712         but->funcN = block->funcN;
2713         if (block->func_argN)
2714                 but->func_argN = MEM_dupallocN(block->func_argN);
2715         
2716         but->pos = -1;   /* cursor invisible */
2717
2718         if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {    /* add a space to name */
2719                 /* slen remains unchanged from previous assignment, ensure this stays true */
2720                 if (slen > 0 && slen < UI_MAX_NAME_STR - 2) {
2721                         if (but->str[slen - 1] != ' ') {
2722                                 but->str[slen] = ' ';
2723                                 but->str[slen + 1] = 0;
2724                         }
2725                 }
2726         }
2727
2728         if ((block->flag & UI_BLOCK_LOOP) ||
2729             ELEM8(but->type, MENU, TEX, LABEL, IDPOIN, BLOCK, BUTM, SEARCH_MENU, PROGRESSBAR))
2730         {
2731                 but->flag |= (UI_TEXT_LEFT | UI_ICON_LEFT);
2732         }
2733         else if (but->type == BUT_TOGDUAL) {
2734                 but->flag |= UI_ICON_LEFT;
2735         }
2736
2737         but->flag |= (block->flag & UI_BUT_ALIGN);
2738
2739         if (but->lock == TRUE) {
2740                 if (but->lockstr) {
2741                         but->flag |= UI_BUT_DISABLED;
2742                 }
2743         }
2744
2745         /* keep track of UI_interface.h */
2746         if      (ELEM9(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM, SCROLL, SEPR /* , FTPREVIEW */)) {}
2747         else if (but->type >= SEARCH_MENU) {}
2748         else but->flag |= UI_BUT_UNDO;
2749
2750         BLI_addtail(&block->buttons, but);
2751         
2752         if (block->curlayout)
2753                 ui_layout_add_but(block->curlayout, but);
2754
2755 #ifdef WITH_PYTHON
2756         /* if the 'UI_OT_editsource' is running, extract the source info from the button  */
2757         if (UI_editsource_enable_check()) {
2758                 UI_editsource_active_but_test(but);
2759         }
2760 #endif
2761
2762         return but;
2763 }
2764
2765 /* ui_def_but_rna_propname and ui_def_but_rna
2766  * both take the same args except for propname vs prop, this is done so we can
2767  * avoid an extra lookup on 'prop' when its already available.
2768  *
2769  * When this kind of change won't disrupt branches, best look into making more
2770  * of our UI functions take prop rather then propname.
2771  */
2772
2773 #define UI_DEF_BUT_RNA_DISABLE(but)  { \
2774                 but->flag |= UI_BUT_DISABLED;  \
2775                 but->lock = TRUE;              \
2776                 but->lockstr = "";             \
2777         } (void)0
2778
2779
2780 static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str,
2781                              int x, int y, short width, short height,
2782                              PointerRNA *ptr, PropertyRNA *prop, int index,
2783                              float min, float max, float a1, float a2,  const char *tip)
2784 {
2785         const PropertyType proptype = RNA_property_type(prop);
2786         uiBut *but;
2787         int freestr = 0, icon = 0;
2788
2789         /* use rna values if parameters are not specified */
2790         if (!str) {
2791                 if (type == MENU && proptype == PROP_ENUM) {
2792                         EnumPropertyItem *item;
2793                         DynStr *dynstr;
2794                         int i, totitem, value, free;
2795
2796                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2797                         value = RNA_property_enum_get(ptr, prop);
2798
2799                         dynstr = BLI_dynstr_new();
2800                         BLI_dynstr_appendf(dynstr, "%s%%t", RNA_property_ui_name(prop));
2801                         for (i = 0; i < totitem; i++) {
2802                                 if (!item[i].identifier[0]) {
2803                                         if (item[i].name)
2804                                                 BLI_dynstr_appendf(dynstr, "|%s%%l", item[i].name);
2805                                         else
2806                                                 BLI_dynstr_append(dynstr, "|%l");
2807                                 }
2808                                 else if (item[i].icon)
2809                                         BLI_dynstr_appendf(dynstr, "|%s %%i%d %%x%d", item[i].name, item[i].icon, item[i].value);
2810                                 else
2811                                         BLI_dynstr_appendf(dynstr, "|%s %%x%d", item[i].name, item[i].value);
2812
2813                                 if (value == item[i].value)
2814                                         icon = item[i].icon;
2815                         }
2816                         str = BLI_dynstr_get_cstring(dynstr);
2817                         BLI_dynstr_free(dynstr);
2818
2819                         if (free) {
2820                                 MEM_freeN(item);
2821                         }
2822
2823                         freestr = 1;
2824                 }
2825                 else if (ELEM(type, ROW, LISTROW) && proptype == PROP_ENUM) {
2826                         EnumPropertyItem *item;
2827                         int i, totitem, free;
2828
2829                         /* TODO, translate after getting the item, saves many lookups */
2830                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2831                         for (i = 0; i < totitem; i++) {
2832                                 if (item[i].identifier[0] && item[i].value == (int)max) {
2833                                         str = item[i].name;
2834                                         icon = item[i].icon;
2835                                 }
2836                         }
2837
2838                         if (!str) {
2839                                 str = RNA_property_ui_name(prop);
2840                         }
2841                         if (free) {
2842                                 MEM_freeN(item);
2843                         }
2844                 }
2845                 else {
2846                         str = RNA_property_ui_name(prop);
2847                         icon = RNA_property_ui_icon(prop);
2848                 }
2849         }
2850
2851         if (!tip && proptype != PROP_ENUM)
2852                 tip = RNA_property_ui_description(prop);
2853
2854         if (min == max || a1 == -1 || a2 == -1) {
2855                 if (proptype == PROP_INT) {
2856                         int hardmin, hardmax, softmin, softmax, step;
2857
2858                         RNA_property_int_range(ptr, prop, &hardmin, &hardmax);
2859                         RNA_property_int_ui_range(ptr, prop, &softmin, &softmax, &step);
2860
2861                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2862                                 min = hardmin;
2863                                 max = hardmax;
2864                         }
2865                         if (a1 == -1)
2866                                 a1 = step;
2867                         if (a2 == -1)
2868                                 a2 = 0;
2869                 }
2870                 else if (proptype == PROP_FLOAT) {
2871                         float hardmin, hardmax, softmin, softmax, step, precision;
2872
2873                         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2874                         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2875
2876                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2877                                 min = hardmin;
2878                                 max = hardmax;
2879                         }
2880                         if (a1 == -1)
2881                                 a1 = step;
2882                         if (a2 == -1)
2883                                 a2 = precision;
2884                 }
2885                 else if (proptype == PROP_STRING) {
2886                         min = 0;
2887                         max = RNA_property_string_maxlength(prop);
2888                         if (max == 0) /* interface code should ideally support unlimited length */
2889                                 max = UI_MAX_DRAW_STR;
2890                 }
2891         }
2892
2893         /* now create button */
2894         but = ui_def_but(block, type, retval, str, x, y, width, height, NULL, min, max, a1, a2, tip);
2895
2896         but->rnapoin = *ptr;
2897         but->rnaprop = prop;
2898
2899         if (RNA_property_array_length(&but->rnapoin, but->rnaprop))
2900                 but->rnaindex = index;
2901         else
2902                 but->rnaindex = 0;
2903
2904         if (icon) {
2905                 but->icon = (BIFIconID)icon;
2906                 but->flag |= UI_HAS_ICON;
2907                 but->flag |= UI_ICON_LEFT;
2908         }
2909         
2910         if (!RNA_property_editable(&but->rnapoin, prop)) {
2911                 UI_DEF_BUT_RNA_DISABLE(but);
2912         }
2913
2914         if (but->flag & UI_BUT_UNDO && (ui_but_is_rna_undo(but) == FALSE)) {
2915                 but->flag &= ~UI_BUT_UNDO;
2916         }
2917
2918         /* If this button uses units, calculate the step from this */
2919         if ((proptype == PROP_FLOAT) && ui_is_but_unit(but)) {
2920                 but->a1 = ui_get_but_step_unit(but, but->a1);
2921         }
2922
2923         if (freestr) {
2924                 MEM_freeN((void *)str);
2925         }
2926
2927         return but;
2928 }
2929
2930 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)
2931 {
2932         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2933         uiBut *but;
2934
2935         if (prop) {
2936                 but = ui_def_but_rna(block, type, retval, str, x, y, width, height, ptr, prop, index, min, max, a1, a2,  tip);
2937         }
2938         else {
2939                 but = ui_def_but(block, type, retval, propname, x, y, width, height, NULL, min, max, a1, a2, tip);
2940
2941                 UI_DEF_BUT_RNA_DISABLE(but);
2942         }
2943
2944         return but;
2945 }
2946
2947 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)
2948 {
2949         uiBut *but;
2950
2951         if (!str) {
2952                 if (ot && ot->srna)
2953                         str = RNA_struct_ui_name(ot->srna);
2954                 else
2955                         str = "";
2956         }
2957
2958         if ((!tip || tip[0] == '\0') && ot && ot->srna) {
2959                 tip = RNA_struct_ui_description(ot->srna);
2960         }
2961
2962         but = ui_def_but(block, type, -1, str, x, y, width, height, NULL, 0, 0, 0, 0, tip);
2963         but->optype = ot;
2964         but->opcontext = opcontext;
2965         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2966
2967         if (!ot) {
2968                 but->flag |= UI_BUT_DISABLED;
2969                 but->lock = TRUE;
2970                 but->lockstr = "";
2971         }
2972
2973         return but;
2974 }
2975
2976 #if 0 /* UNUSED */
2977 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)
2978 {
2979         wmOperatorType *ot = WM_operatortype_find(opname, 0);
2980         if (str == NULL && ot == NULL) str = opname;
2981         return ui_def_but_operator_ptr(block, type, ot, opcontext, str, x, y, width, height, tip);
2982 }
2983 #endif
2984
2985 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)
2986 {
2987         uiBut *but;
2988         wmOperatorType *ot;
2989         
2990         ot = WM_operatortype_find(opname, 0);
2991
2992         if (!str) {
2993                 if (ot) str = ot->name;
2994                 else str = opname;
2995         }
2996         
2997         if ((!tip || tip[0] == '\0') && ot && ot->description) {
2998                 tip = ot->description;
2999         }
3000
3001         but = ui_def_but(block, type, -1, str, x, y, width, height, poin, min, max, a1, a2, tip);
3002         but->optype = ot;
3003         but->opcontext = opcontext;
3004         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
3005
3006         if (!ot) {
3007                 but->flag |= UI_BUT_DISABLED;
3008                 but->lock = TRUE;
3009                 but->lockstr = "";
3010         }
3011
3012         return but;
3013 }
3014
3015 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)
3016 {
3017         uiBut *but = ui_def_but(block, type, retval, str, x, y, width, height, poin, min, max, a1, a2, tip);
3018
3019         ui_check_but(but);
3020         
3021         return but;
3022 }
3023
3024 /* if _x_ is a power of two (only one bit) return the power,
3025  * otherwise return -1.
3026  * (1<<findBitIndex(x))==x for powers of two.
3027  */
3028 static int findBitIndex(unsigned int x)
3029 {
3030         if (!x || !is_power_of_2_i(x)) { /* is_power_of_2_i(x) strips lowest bit */
3031                 return -1;
3032         }
3033         else {
3034                 int idx = 0;
3035
3036                 if (x & 0xFFFF0000) idx += 16, x >>= 16;
3037                 if (x & 0xFF00) idx += 8, x >>= 8;
3038                 if (x & 0xF0) idx += 4, x >>= 4;
3039                 if (x & 0xC) idx += 2, x >>= 2;
3040                 if (x & 0x2) idx += 1;
3041
3042                 return idx;
3043         }
3044 }
3045
3046 /* autocomplete helper functions */
3047 struct AutoComplete {
3048         size_t maxlen;
3049         char *truncate;
3050         const char *startname;
3051 };
3052
3053 AutoComplete *autocomplete_begin(const char *startname, size_t maxlen)
3054 {
3055         AutoComplete *autocpl;
3056         
3057         autocpl = MEM_callocN(sizeof(AutoComplete), "AutoComplete");
3058         autocpl->maxlen = maxlen;
3059         autocpl->truncate = MEM_callocN(sizeof(char) * maxlen, "AutoCompleteTruncate");
3060         autocpl->startname = startname;
3061
3062         return autocpl;
3063 }
3064
3065 void autocomplete_do_name(AutoComplete *autocpl, const char *name)
3066 {
3067         char *truncate = autocpl->truncate;
3068         const char *startname = autocpl->startname;
3069         int a;
3070
3071         for (a = 0; a < autocpl->maxlen - 1; a++) {
3072                 if (startname[a] == 0 || startname[a] != name[a])
3073                         break;
3074         }
3075         /* found a match */
3076         if (startname[a] == 0) {
3077                 /* first match */
3078                 if (truncate[0] == 0)
3079                         BLI_strncpy(truncate, name, autocpl->maxlen);
3080                 else {
3081                         /* remove from truncate what is not in bone->name */
<