Display enum descriptions in tooltips for operators using a "type" or "mode"
[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 = maxf(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 + maxf(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 = MIN2(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 = MIN2(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         else if (but->type == HSVSLI) {
1533                 float *fp, hsv[3];
1534                 
1535                 fp = (but->editvec) ? but->editvec : (float *)but->poin;
1536                 rgb_to_hsv_v(fp, hsv);
1537                 
1538                 switch (but->str[0]) {
1539                         case 'H': hsv[0] = value; break;
1540                         case 'S': hsv[1] = value; break;
1541                         case 'V': hsv[2] = value; break;
1542                 }
1543                 
1544                 hsv_to_rgb_v(hsv, fp);
1545                 
1546         }
1547         else {
1548                 /* first do rounding */
1549                 if (but->pointype == UI_BUT_POIN_CHAR) {
1550                         value = (char)floor(value + 0.5);
1551                 }
1552                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1553                         /* gcc 3.2.1 seems to have problems
1554                          * casting a double like 32772.0 to
1555                          * a short so we cast to an int, then
1556                          * to a short.
1557                          *
1558                          * Update: even in gcc.4.6 using intermediate int cast gives -32764,
1559                          * where as a direct cast from double to short gives -32768,
1560                          * if this difference isn't important we could remove this hack,
1561                          * since we dont support gcc3 anymore - Campbell */
1562                         int gcckludge;
1563                         gcckludge = (int) floor(value + 0.5);
1564                         value = (short)gcckludge;
1565                 }
1566                 else if (but->pointype == UI_BUT_POIN_INT)
1567                         value = (int)floor(value + 0.5);
1568                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1569                         float fval = (float)value;
1570                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1571                         value = fval;
1572                 }
1573                 
1574                 /* then set value with possible edit override */
1575                 if (but->editval)
1576                         value = *but->editval = value;
1577                 else if (but->pointype == UI_BUT_POIN_CHAR)
1578                         value = *((char *)but->poin) = (char)value;
1579                 else if (but->pointype == UI_BUT_POIN_SHORT)
1580                         value = *((short *)but->poin) = (short)value;
1581                 else if (but->pointype == UI_BUT_POIN_INT)
1582                         value = *((int *)but->poin) = (int)value;
1583                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1584                         value = *((float *)but->poin) = (float)value;
1585         }
1586
1587         /* update select flag */
1588         ui_is_but_sel(but, &value);
1589 }
1590
1591 int ui_get_but_string_max_length(uiBut *but)
1592 {
1593         if (ELEM(but->type, TEX, SEARCH_MENU))
1594                 return but->hardmax;
1595         else if (but->type == IDPOIN)
1596                 return MAX_ID_NAME - 2;
1597         else
1598                 return UI_MAX_DRAW_STR;
1599 }
1600
1601 static double ui_get_but_scale_unit(uiBut *but, double value)
1602 {
1603         UnitSettings *unit = but->block->unit;
1604         int unit_type = uiButGetUnitType(but);
1605
1606         if (unit_type == PROP_UNIT_LENGTH) {
1607                 return value * (double)unit->scale_length;
1608         }
1609         else if (unit_type == PROP_UNIT_AREA) {
1610                 return value * pow(unit->scale_length, 2);
1611         }
1612         else if (unit_type == PROP_UNIT_VOLUME) {
1613                 return value * pow(unit->scale_length, 3);
1614         }
1615         else if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1616                 Scene *scene = CTX_data_scene(but->block->evil_C);
1617                 return FRA2TIME(value);
1618         }
1619         else {
1620                 return value;
1621         }
1622 }
1623
1624 /* str will be overwritten */
1625 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1626 {
1627         if (ui_is_but_unit(but)) {
1628                 UnitSettings *unit = but->block->unit;
1629                 int unit_type = uiButGetUnitType(but);
1630                 char *orig_str;
1631                 
1632                 orig_str = MEM_callocN(sizeof(char) * maxlen + 1, "textedit sub str");
1633                 memcpy(orig_str, str, maxlen);
1634                 
1635                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1636                 
1637                 MEM_freeN(orig_str);
1638         }
1639 }
1640
1641 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, int pad)
1642 {
1643         UnitSettings *unit = but->block->unit;
1644         int do_split = unit->flag & USER_UNIT_OPT_SPLIT;
1645         int unit_type = uiButGetUnitType(but);
1646         int precision = but->a2;
1647
1648         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
1649
1650         /* Sanity checks */
1651         if (precision > PRECISION_FLOAT_MAX) precision = PRECISION_FLOAT_MAX;
1652         else if (precision == 0) precision = 2;
1653
1654         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
1655                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
1656 }
1657
1658 static float ui_get_but_step_unit(uiBut *but, float step_default)
1659 {
1660         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
1661         float step;
1662
1663         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1664
1665         if (step > 0.0f) { /* -1 is an error value */
1666                 return (float)((double)step / ui_get_but_scale_unit(but, 1.0)) * 100.0f;
1667         }
1668         else {
1669                 return step_default;
1670         }
1671 }
1672
1673
1674 void ui_get_but_string(uiBut *but, char *str, size_t maxlen)
1675 {
1676         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1677                 PropertyType type;
1678                 char *buf = NULL;
1679                 int buf_len;
1680
1681                 type = RNA_property_type(but->rnaprop);
1682
1683                 if (type == PROP_STRING) {
1684                         /* RNA string */
1685                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
1686                 }
1687                 else if (type == PROP_POINTER) {
1688                         /* RNA pointer */
1689                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1690                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
1691                 }
1692
1693                 if (!buf) {
1694                         str[0] = '\0';
1695                 }
1696                 else if (buf && buf != str) {
1697                         /* string was too long, we have to truncate */
1698                         memcpy(str, buf, MIN2(maxlen, buf_len + 1));
1699                         MEM_freeN(buf);
1700                 }
1701         }
1702         else if (but->type == IDPOIN) {
1703                 /* ID pointer */
1704                 if (but->idpoin_idpp) { /* Can be NULL for ID properties by python */
1705                         ID *id = *(but->idpoin_idpp);
1706                         if (id) {
1707                                 BLI_strncpy(str, id->name + 2, maxlen);
1708                                 return;
1709                         }
1710                 }
1711                 str[0] = '\0';
1712                 return;
1713         }
1714         else if (but->type == TEX) {
1715                 /* string */
1716                 BLI_strncpy(str, but->poin, maxlen);
1717                 return;
1718         }
1719         else if (but->type == SEARCH_MENU) {
1720                 /* string */
1721                 BLI_strncpy(str, but->poin, maxlen);
1722                 return;
1723         }
1724         else if (ui_but_anim_expression_get(but, str, maxlen))
1725                 ;  /* driver expression */
1726         else {
1727                 /* number editing */
1728                 double value;
1729
1730                 value = ui_get_but_val(but);
1731
1732                 if (ui_is_but_float(but)) {
1733                         if (ui_is_but_unit(but)) {
1734                                 ui_get_but_string_unit(but, str, maxlen, value, 0);
1735                         }
1736                         else {
1737                                 const int prec = ui_but_float_precision(but, value);
1738                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
1739                         }
1740                 }
1741                 else
1742                         BLI_snprintf(str, maxlen, "%d", (int)value);
1743         }
1744 }
1745
1746 #ifdef WITH_PYTHON
1747
1748 static int ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
1749 {
1750         char str_unit_convert[256];
1751         const int unit_type = uiButGetUnitType(but);
1752
1753         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
1754
1755         /* ugly, use the draw string to get the value,
1756          * this could cause problems if it includes some text which resolves to a unit */
1757         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
1758                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1759
1760         return (BPY_button_exec(C, str_unit_convert, value, TRUE) != -1);
1761 }
1762
1763 #endif /* WITH_PYTHON */
1764
1765
1766 int ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
1767 {
1768         int ok = FALSE;
1769
1770 #ifdef WITH_PYTHON
1771
1772         if (str[0] != '\0') {
1773                 int is_unit_but = ui_is_but_unit(but);
1774                 /* only enable verbose if we won't run again with units */
1775                 if (BPY_button_exec(C, str, value, is_unit_but == FALSE) != -1) {
1776                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
1777                         if (is_unit_but) {
1778                                 char str_new[128];
1779
1780                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
1781                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
1782                         }
1783                         else {
1784                                 ok = TRUE; /* parse normal string via py (no unit conversion needed) */
1785                         }
1786                 }
1787                 else if (is_unit_but) {
1788                         /* parse failed, this is a unit but so run replacements and parse again */
1789                         ok = ui_set_but_string_eval_num_unit(C, but, str, value);
1790                 }
1791         }
1792
1793 #else /* WITH_PYTHON */
1794
1795         *value = atof(str);
1796         ok = TRUE;
1797
1798         (void)C;
1799         (void)but;
1800
1801 #endif /* WITH_PYTHON */
1802
1803         return ok;
1804 }
1805
1806
1807 int ui_set_but_string(bContext *C, uiBut *but, const char *str)
1808 {
1809         if (but->rnaprop && ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1810                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
1811                         PropertyType type;
1812
1813                         type = RNA_property_type(but->rnaprop);
1814
1815                         if (type == PROP_STRING) {
1816                                 /* RNA string */
1817                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
1818                                 return 1;
1819                         }
1820                         else if (type == PROP_POINTER) {
1821                                 /* RNA pointer */
1822                                 PointerRNA ptr, rptr;
1823                                 PropertyRNA *prop;
1824
1825                                 if (str == NULL || str[0] == '\0') {
1826                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
1827                                         return 1;
1828                                 }
1829                                 else {
1830                                         ptr = but->rnasearchpoin;
1831                                         prop = but->rnasearchprop;
1832                                         
1833                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
1834                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
1835
1836                                         return 1;
1837                                 }
1838
1839                                 return 0;
1840                         }
1841                 }
1842         }
1843         else if (but->type == IDPOIN) {
1844                 /* ID pointer */
1845                 but->idpoin_func(C, str, but->idpoin_idpp);
1846                 return 1;
1847         }
1848         else if (but->type == TEX) {
1849                 /* string */
1850                 if (ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
1851                 else BLI_strncpy(but->poin, str, but->hardmax);
1852
1853                 return 1;
1854         }
1855         else if (but->type == SEARCH_MENU) {
1856                 /* string */
1857                 BLI_strncpy(but->poin, str, but->hardmax);
1858                 return 1;
1859         }
1860         else if (ui_but_anim_expression_set(but, str)) {
1861                 /* driver expression */
1862                 return 1;
1863         }
1864         else if (str[0] == '#') {
1865                 /* shortcut to create new driver expression (versus immediate Py-execution) */
1866                 return ui_but_anim_expression_create(but, str + 1);
1867         }
1868         else {
1869                 /* number editing */
1870                 double value;
1871
1872                 if (ui_set_but_string_eval_num(C, but, str, &value) == FALSE) {
1873                         return 0;
1874                 }
1875
1876                 if (!ui_is_but_float(but)) value = (int)floor(value + 0.5);
1877                 if (but->type == NUMABS) value = fabs(value);
1878
1879                 /* not that we use hard limits here */
1880                 if (value < (double)but->hardmin) value = but->hardmin;
1881                 if (value > (double)but->hardmax) value = but->hardmax;
1882
1883                 ui_set_but_val(but, value);
1884                 return 1;
1885         }
1886
1887         return 0;
1888 }
1889
1890 void ui_set_but_default(bContext *C, short all)
1891 {
1892         PointerRNA ptr;
1893
1894         WM_operator_properties_create(&ptr, "UI_OT_reset_default_button");
1895         RNA_boolean_set(&ptr, "all", all);
1896         WM_operator_name_call(C, "UI_OT_reset_default_button", WM_OP_EXEC_DEFAULT, &ptr);
1897         WM_operator_properties_free(&ptr);
1898 }
1899
1900 static double soft_range_round_up(double value, double max)
1901 {
1902         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1903         double newmax = pow(10.0, ceil(log(value) / M_LN10));
1904
1905         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
1906                 return newmax * 0.2;
1907         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
1908                 return newmax * 0.5;
1909         else
1910                 return newmax;
1911 }
1912
1913 static double soft_range_round_down(double value, double max)
1914 {
1915         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, .. */
1916         double newmax = pow(10.0, floor(log(value) / M_LN10));
1917
1918         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
1919                 return newmax * 5.0;
1920         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
1921                 return newmax * 2.0;
1922         else
1923                 return newmax;
1924 }
1925
1926 void ui_set_but_soft_range(uiBut *but, double value)
1927 {
1928         /* ideally we would not limit this but practically, its more then
1929          * enough worst case is very long vectors wont use a smart soft-range
1930          * which isn't so bad. */
1931
1932         if (but->rnaprop) {
1933                 const PropertyType type = RNA_property_type(but->rnaprop);
1934                 double softmin, softmax /*, step, precision*/;
1935                 double value_min = value;
1936                 double value_max = value;
1937
1938                 /* clamp button range to something reasonable in case
1939                  * we get -inf/inf from RNA properties */
1940                 if (type == PROP_INT) {
1941                         int imin, imax, istep;
1942                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1943
1944                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
1945                         softmin = (imin == INT_MIN) ? -1e4 : imin;
1946                         softmax = (imin == INT_MAX) ? 1e4 : imax;
1947                         /*step= istep;*/ /*UNUSED*/
1948                         /*precision= 1;*/ /*UNUSED*/
1949
1950                         if (array_len >= 2) {
1951                                 int value_range[2];
1952                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1953                                 value_min = (double)value_range[0];
1954                                 value_max = (double)value_range[1];
1955                         }
1956                 }
1957                 else if (type == PROP_FLOAT) {
1958                         float fmin, fmax, fstep, fprecision;
1959                         const int array_len = RNA_property_array_length(&but->rnapoin, but->rnaprop);
1960
1961                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
1962                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
1963                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
1964                         /*step= fstep;*/ /*UNUSED*/
1965                         /*precision= fprecision;*/ /*UNUSED*/
1966
1967                         if (array_len >= 2) {
1968                                 float value_range[2];
1969                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
1970                                 value_min = (double)value_range[0];
1971                                 value_max = (double)value_range[1];
1972                         }
1973                 }
1974                 else
1975                         return;
1976
1977                 /* if the value goes out of the soft/max range, adapt the range */
1978                 if (value_min + 1e-10 < softmin) {
1979                         if (value_min < 0.0)
1980                                 softmin = -soft_range_round_up(-value_min, -softmin);
1981                         else
1982                                 softmin = soft_range_round_down(value_min, softmin);
1983
1984                         if (softmin < (double)but->hardmin)
1985                                 softmin = (double)but->hardmin;
1986                 }
1987                 if (value_max - 1e-10 > softmax) {
1988                         if (value_max < 0.0)
1989                                 softmax = -soft_range_round_down(-value_max, -softmax);
1990                         else
1991                                 softmax = soft_range_round_up(value_max, softmax);
1992
1993                         if (softmax > (double)but->hardmax)
1994                                 softmax = but->hardmax;
1995                 }
1996
1997                 but->softmin = softmin;
1998                 but->softmax = softmax;
1999         }
2000 }
2001
2002 /* ******************* Free ********************/
2003
2004 static void ui_free_link(uiLink *link)
2005 {
2006         if (link) {     
2007                 BLI_freelistN(&link->lines);
2008                 MEM_freeN(link);
2009         }
2010 }
2011
2012 /* can be called with C==NULL */
2013 static void ui_free_but(const bContext *C, uiBut *but)
2014 {
2015         if (but->opptr) {
2016                 WM_operator_properties_free(but->opptr);
2017                 MEM_freeN(but->opptr);
2018         }
2019
2020         if (but->func_argN) {
2021                 MEM_freeN(but->func_argN);
2022         }
2023
2024         if (but->active) {
2025                 /* XXX solve later, buttons should be free-able without context ideally,
2026                  * however they may have open tooltips or popup windows, which need to
2027                  * be closed using a context pointer */
2028                 if (C) {
2029                         ui_button_active_free(C, but);
2030                 }
2031                 else {
2032                         if (but->active) {
2033                                 MEM_freeN(but->active);
2034                         }
2035                 }
2036         }
2037         if (but->str && but->str != but->strdata) {
2038                 MEM_freeN(but->str);
2039         }
2040         ui_free_link(but->link);
2041
2042         if ((but->type == BUT_IMAGE) && but->poin) {
2043                 IMB_freeImBuf((struct ImBuf *)but->poin);
2044         }
2045
2046         MEM_freeN(but);
2047 }
2048
2049 /* can be called with C==NULL */
2050 void uiFreeBlock(const bContext *C, uiBlock *block)
2051 {
2052         uiBut *but;
2053
2054         while ( (but = block->buttons.first) ) {
2055                 BLI_remlink(&block->buttons, but);      
2056                 ui_free_but(C, but);
2057         }
2058
2059         if (block->unit) {
2060                 MEM_freeN(block->unit);
2061         }
2062
2063         if (block->func_argN) {
2064                 MEM_freeN(block->func_argN);
2065         }
2066
2067         CTX_store_free_list(&block->contexts);
2068
2069         BLI_freelistN(&block->saferct);
2070         
2071         MEM_freeN(block);
2072 }
2073
2074 /* can be called with C==NULL */
2075 void uiFreeBlocks(const bContext *C, ListBase *lb)
2076 {
2077         uiBlock *block;
2078         
2079         while ( (block = lb->first) ) {
2080                 BLI_remlink(lb, block);
2081                 uiFreeBlock(C, block);
2082         }
2083 }
2084
2085 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2086 {
2087         uiBlock *block, *nextblock;
2088
2089         for (block = lb->first; block; block = nextblock) {
2090                 nextblock = block->next;
2091         
2092                 if (!block->handle) {
2093                         if (!block->active) {
2094                                 BLI_remlink(lb, block);
2095                                 uiFreeBlock(C, block);
2096                         }
2097                         else
2098                                 block->active = 0;
2099                 }
2100         }
2101 }
2102
2103 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2104 {
2105         ListBase *lb = &region->uiblocks;
2106         uiBlock *oldblock = NULL;
2107
2108         /* each listbase only has one block with this name, free block
2109          * if is already there so it can be rebuilt from scratch */
2110         if (lb) {
2111                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2112
2113                 if (oldblock) {
2114                         oldblock->active = 0;
2115                         oldblock->panel = NULL;
2116                 }
2117
2118                 /* at the beginning of the list! for dynamical menus/blocks */
2119                 BLI_addhead(lb, block);
2120         }
2121
2122         block->oldblock = oldblock;
2123 }
2124
2125 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2126 {
2127         uiBlock *block;
2128         wmWindow *window;
2129         Scene *scn;
2130         int getsizex, getsizey;
2131
2132         window = CTX_wm_window(C);
2133         scn = CTX_data_scene(C);
2134
2135         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2136         block->active = 1;
2137         block->dt = dt;
2138         block->evil_C = (void *)C;  /* XXX */
2139
2140         if (scn) {
2141                 block->color_profile = TRUE;
2142
2143                 /* store display device name, don't lookup for transformations yet
2144                  * block could be used for non-color displays where looking up for transformation
2145                  * would slow down redraw, so only lookup for actual transform when it's indeed
2146                  * needed
2147                  */
2148                 block->display_device = scn->display_settings.display_device;
2149
2150                 /* copy to avoid crash when scene gets deleted with ui still open */
2151                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2152                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2153         }
2154
2155         BLI_strncpy(block->name, name, sizeof(block->name));
2156
2157         if (region)
2158                 uiBlockSetRegion(block, region);
2159
2160         /* window matrix and aspect */
2161         if (region && region->swinid) {
2162                 wm_subwindow_getmatrix(window, region->swinid, block->winmat);
2163                 wm_subwindow_getsize(window, region->swinid, &getsizex, &getsizey);
2164
2165                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2166         }
2167         else {
2168                 /* no subwindow created yet, for menus for example, so we
2169                  * use the main window instead, since buttons are created
2170                  * there anyway */
2171                 wm_subwindow_getmatrix(window, window->screen->mainwin, block->winmat);
2172                 wm_subwindow_getsize(window, window->screen->mainwin, &getsizex, &getsizey);
2173
2174                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2175                 block->auto_open = TRUE;
2176                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2177         }
2178
2179         return block;
2180 }
2181
2182 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2183 {
2184         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2185 }
2186
2187 void uiBlockSetEmboss(uiBlock *block, char dt)
2188 {
2189         block->dt = dt;
2190 }
2191
2192 void ui_check_but(uiBut *but)
2193 {
2194         /* if something changed in the button */
2195         double value = UI_BUT_VALUE_UNSET;
2196 //      float okwidth; // UNUSED
2197         
2198         ui_is_but_sel(but, &value);
2199         
2200         /* only update soft range while not editing */
2201         if (but->rnaprop && !(but->editval || but->editstr || but->editvec)) {
2202                 UI_GET_BUT_VALUE_INIT(but, value);
2203                 ui_set_but_soft_range(but, value);
2204         }
2205
2206         /* test for min and max, icon sliders, etc */
2207         switch (but->type) {
2208                 case NUM:
2209                 case SLI:
2210                 case SCROLL:
2211                 case NUMSLI:
2212                 case HSVSLI:
2213                         UI_GET_BUT_VALUE_INIT(but, value);
2214                         if (value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2215                         else if (value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2216                         break;
2217                         
2218                 case NUMABS:
2219                 {
2220                         double value_abs;
2221                         UI_GET_BUT_VALUE_INIT(but, value);
2222                         value_abs = fabs(value);
2223                         if (value_abs < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2224                         else if (value_abs > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2225                         break;
2226                 }
2227                 case ICONTOG: 
2228                 case ICONTOGN:
2229                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2230                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2231                                 else but->iconadd = 0;
2232                         }
2233                         break;
2234                         
2235                 case ICONROW:
2236                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2237                                 UI_GET_BUT_VALUE_INIT(but, value);
2238                                 but->iconadd = (int)value - (int)(but->hardmin);
2239                         }
2240                         break;
2241                         
2242                 case ICONTEXTROW:
2243                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2244                                 UI_GET_BUT_VALUE_INIT(but, value);
2245                                 but->iconadd = (int)value - (int)(but->hardmin);
2246                         }
2247                         break;
2248
2249                         /* quiet warnings for unhandled types */
2250                 default:
2251                         break;
2252         }
2253         
2254         
2255         /* safety is 4 to enable small number buttons (like 'users') */
2256         // okwidth= -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2257         
2258         /* name: */
2259         switch (but->type) {
2260         
2261                 case MENU:
2262                 case ICONTEXTROW:
2263                 
2264                         if (BLI_rctf_size_x(&but->rect) > 24.0f) {
2265                                 UI_GET_BUT_VALUE_INIT(but, value);
2266                                 ui_set_name_menu(but, (int)value);
2267                         }
2268                         break;
2269         
2270                 case NUM:
2271                 case NUMSLI:
2272                 case HSVSLI:
2273                 case NUMABS:
2274
2275                         UI_GET_BUT_VALUE_INIT(but, value);
2276
2277                         if (ui_is_but_float(but)) {
2278                                 if (value == (double) FLT_MAX) {
2279                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%sinf", but->str);
2280                                 }
2281                                 else if (value == (double) -FLT_MAX) {
2282                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s-inf", but->str);
2283                                 }
2284                                 /* support length type buttons */
2285                                 else if (ui_is_but_unit(but)) {
2286                                         char new_str[sizeof(but->drawstr)];
2287                                         ui_get_but_string_unit(but, new_str, sizeof(new_str), value, TRUE);
2288                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, new_str);
2289                                 }
2290                                 else {
2291                                         const int prec = ui_but_float_precision(but, value);
2292                                         BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2293                                 }
2294                         }
2295                         else {
2296                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%d", but->str, (int)value);
2297                         }
2298                         
2299                         if (but->rnaprop) {
2300                                 PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2301                         
2302                                 if (pstype == PROP_PERCENTAGE)
2303                                         strcat(but->drawstr, "%");
2304                         }
2305                         break;
2306
2307                 case LABEL:
2308                         if (ui_is_but_float(but)) {
2309                                 int prec;
2310                                 UI_GET_BUT_VALUE_INIT(but, value);
2311                                 prec = ui_but_float_precision(but, value);
2312                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2313                         }
2314                         else {
2315                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2316                         }
2317                 
2318                         break;
2319
2320                 case IDPOIN:
2321                 case TEX:
2322                 case SEARCH_MENU:
2323                         if (!but->editstr) {
2324                                 char str[UI_MAX_DRAW_STR];
2325
2326                                 ui_get_but_string(but, str, UI_MAX_DRAW_STR - strlen(but->str));
2327
2328                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2329                         }
2330                         break;
2331         
2332                 case KEYEVT:
2333                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2334                         if (but->flag & UI_SELECT) {
2335                                 strcat(but->drawstr, "Press a key");
2336                         }
2337                         else {
2338                                 UI_GET_BUT_VALUE_INIT(but, value);
2339                                 strcat(but->drawstr, WM_key_event_string((short)value));
2340                         }
2341                         break;
2342                 
2343                 case HOTKEYEVT:
2344                         if (but->flag & UI_SELECT) {
2345                                 but->drawstr[0] = '\0';
2346
2347                                 if (but->modifier_key) {
2348                                         char *str = but->drawstr;
2349
2350                                         if (but->modifier_key & KM_SHIFT)
2351                                                 str = strcat(str, "Shift ");
2352                                         if (but->modifier_key & KM_CTRL)
2353                                                 str = strcat(str, "Ctrl ");
2354                                         if (but->modifier_key & KM_ALT)
2355                                                 str = strcat(str, "Alt ");
2356                                         if (but->modifier_key & KM_OSKEY)
2357                                                 str = strcat(str, "Cmd ");
2358
2359                                         (void)str; /* UNUSED */
2360                                 }
2361                                 else
2362                                         strcat(but->drawstr, "Press a key  ");
2363                         }
2364                         else
2365                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2366
2367                         break;
2368
2369                 case BUT_TOGDUAL:
2370                         /* trying to get the dual-icon to left of text... not very nice */
2371                         if (but->str[0]) {
2372                                 BLI_strncpy(but->drawstr, "  ", UI_MAX_DRAW_STR);
2373                                 BLI_strncpy(but->drawstr + 2, but->str, UI_MAX_DRAW_STR - 2);
2374                         }
2375                         break;
2376                 
2377                 case HSVCUBE:
2378                 case HSVCIRCLE:
2379                         break;
2380                 default:
2381                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2382                 
2383         }
2384
2385         /* if we are doing text editing, this will override the drawstr */
2386         if (but->editstr)
2387                 BLI_strncpy(but->drawstr, but->editstr, UI_MAX_DRAW_STR);
2388         
2389         /* text clipping moved to widget drawing code itself */
2390 }
2391
2392
2393 void uiBlockBeginAlign(uiBlock *block)
2394 {
2395         /* if other align was active, end it */
2396         if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2397
2398         block->flag |= UI_BUT_ALIGN_DOWN;       
2399         block->alignnr++;
2400
2401         /* buttons declared after this call will get this align nr */ // XXX flag?
2402 }
2403
2404 static int buts_are_horiz(uiBut *but1, uiBut *but2)
2405 {
2406         float dx, dy;
2407         
2408         dx = fabs(but1->rect.xmax - but2->rect.xmin);
2409         dy = fabs(but1->rect.ymin - but2->rect.ymax);
2410         
2411         if (dx > dy) return 0;
2412         return 1;
2413 }
2414
2415 void uiBlockEndAlign(uiBlock *block)
2416 {
2417         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
2418 }
2419
2420 int ui_but_can_align(uiBut *but)
2421 {
2422         return !ELEM3(but->type, LABEL, OPTION, OPTIONN);
2423 }
2424
2425 static void ui_block_do_align_but(uiBut *first, short nr)
2426 {
2427         uiBut *prev, *but = NULL, *next;
2428         int flag = 0, cols = 0, rows = 0;
2429         
2430         /* auto align */
2431
2432         for (but = first; but && but->alignnr == nr; but = but->next) {
2433                 if (but->next && but->next->alignnr == nr) {
2434                         if (buts_are_horiz(but, but->next)) cols++;
2435                         else rows++;
2436                 }
2437         }
2438
2439         /* rows==0: 1 row, cols==0: 1 column */
2440         
2441         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2442         for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
2443                 next = but->next;
2444                 if (next && next->alignnr != nr)
2445                         next = NULL;
2446
2447                 /* clear old flag */
2448                 but->flag &= ~UI_BUT_ALIGN;
2449                         
2450                 if (flag == 0) {  /* first case */
2451                         if (next) {
2452                                 if (buts_are_horiz(but, next)) {
2453                                         if (rows == 0)
2454                                                 flag = UI_BUT_ALIGN_RIGHT;
2455                                         else 
2456                                                 flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT;
2457                                 }
2458                                 else {
2459                                         flag = UI_BUT_ALIGN_DOWN;
2460                                 }
2461                         }
2462                 }
2463                 else if (next == NULL) {  /* last case */
2464                         if (prev) {
2465                                 if (buts_are_horiz(prev, but)) {
2466                                         if (rows == 0)
2467                                                 flag = UI_BUT_ALIGN_LEFT;
2468                                         else
2469                                                 flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT;
2470                                 }
2471                                 else flag = UI_BUT_ALIGN_TOP;
2472                         }
2473                 }
2474                 else if (buts_are_horiz(but, next)) {
2475                         /* check if this is already second row */
2476                         if (prev && buts_are_horiz(prev, but) == 0) {
2477                                 flag &= ~UI_BUT_ALIGN_LEFT;
2478                                 flag |= UI_BUT_ALIGN_TOP;
2479                                 /* exception case: bottom row */
2480                                 if (rows > 0) {
2481                                         uiBut *bt = but;
2482                                         while (bt && bt->alignnr == nr) {
2483                                                 if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) break;
2484                                                 bt = bt->next;
2485                                         }
2486                                         if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
2487                                 }
2488                         }
2489                         else flag |= UI_BUT_ALIGN_LEFT;
2490                 }
2491                 else {
2492                         if (cols == 0) {
2493                                 flag |= UI_BUT_ALIGN_TOP;
2494                         }
2495                         else {  /* next button switches to new row */
2496                                 
2497                                 if (prev && buts_are_horiz(prev, but))
2498                                         flag |= UI_BUT_ALIGN_LEFT;
2499                                 else {
2500                                         flag &= ~UI_BUT_ALIGN_LEFT;
2501                                         flag |= UI_BUT_ALIGN_TOP;
2502                                 }
2503                                 
2504                                 if ((flag & UI_BUT_ALIGN_TOP) == 0) {  /* stil top row */
2505                                         if (prev) {
2506                                                 if (next && buts_are_horiz(but, next))
2507                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT;
2508                                                 else {
2509                                                         /* last button in top row */
2510                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT;
2511                                                 }
2512                                         }
2513                                         else 
2514                                                 flag |= UI_BUT_ALIGN_DOWN;
2515                                 }
2516                                 else 
2517                                         flag |= UI_BUT_ALIGN_TOP;
2518                         }
2519                 }
2520                 
2521                 but->flag |= flag;
2522                 
2523                 /* merge coordinates */
2524                 if (prev) {
2525                         /* simple cases */
2526                         if (rows == 0) {
2527                                 but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2528                                 prev->rect.xmax = but->rect.xmin;
2529                         }
2530                         else if (cols == 0) {
2531                                 but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2532                                 prev->rect.ymin = but->rect.ymax;
2533                         }
2534                         else {
2535                                 if (buts_are_horiz(prev, but)) {
2536                                         but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2537                                         prev->rect.xmax = but->rect.xmin;
2538                                         /* copy height too */
2539                                         but->rect.ymax = prev->rect.ymax;
2540                                 }
2541                                 else if (prev->prev && buts_are_horiz(prev->prev, prev) == 0) {
2542                                         /* the previous button is a single one in its row */
2543                                         but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2544                                         prev->rect.ymin = but->rect.ymax;
2545                                         
2546                                         but->rect.xmin = prev->rect.xmin;
2547                                         if (next && buts_are_horiz(but, next) == 0)
2548                                                 but->rect.xmax = prev->rect.xmax;
2549                                 }
2550                                 else {
2551                                         /* the previous button is not a single one in its row */
2552                                         but->rect.ymax = prev->rect.ymin;
2553                                 }
2554                         }
2555                 }
2556         }
2557 }
2558
2559 void ui_block_do_align(uiBlock *block)
2560 {
2561         uiBut *but;
2562         short nr;
2563
2564         /* align buttons with same align nr */
2565         for (but = block->buttons.first; but; ) {
2566                 if (but->alignnr) {
2567                         nr = but->alignnr;
2568                         ui_block_do_align_but(but, nr);
2569
2570                         /* skip with same number */
2571                         for (; but && but->alignnr == nr; but = but->next) {
2572                                 /* pass */
2573                         }
2574
2575                         if (!but) {
2576                                 break;
2577                         }
2578                 }
2579                 else {
2580                         but = but->next;
2581                 }
2582         }
2583 }
2584
2585 struct ColorManagedDisplay *ui_block_display_get(uiBlock *block)
2586 {
2587         return IMB_colormanagement_display_get_named(block->display_device);
2588 }
2589
2590 void ui_block_to_display_space_v3(uiBlock *block, float pixel[3])
2591 {
2592         struct ColorManagedDisplay *display = ui_block_display_get(block);
2593
2594         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
2595 }
2596
2597 void ui_block_to_scene_linear_v3(uiBlock *block, float pixel[3])
2598 {
2599         struct ColorManagedDisplay *display = ui_block_display_get(block);
2600
2601         IMB_colormanagement_display_to_scene_linear_v3(pixel, display);
2602 }
2603
2604 /**
2605  * \brief ui_def_but is the function that draws many button types
2606  *
2607  * \param x,y The lower left hand corner of the button (X axis)
2608  * \param width,height The size of the button.
2609  *
2610  * for float buttons:
2611  * - \a a1 Click Step (how much to change the value each click)
2612  * - \a a2 Number of decimal point values to display. 0 defaults to 3 (0.000)
2613  *      1,2,3, and a maximum of 4, all greater values will be clamped to 4.
2614  */
2615 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
2616                          int x, int y, short width, short height,
2617                          void *poin, float min, float max, float a1, float a2, const char *tip)
2618 {
2619         uiBut *but;
2620         int slen;
2621
2622         BLI_assert(width >= 0);
2623         BLI_assert(height >= 0);
2624
2625         /* we could do some more error checks here */
2626         if ((type & BUTTYPE) == LABEL) {
2627                 BLI_assert((poin != NULL || min != 0.0f || max != 0.0f || (a1 == 0.0f && a2 != 0.0f) || (a1 != 0.0f && a1 != 1.0f)) == FALSE);
2628         }
2629
2630         if (type & UI_BUT_POIN_TYPES) {  /* a pointer is required */
2631                 if (poin == NULL) {
2632                         BLI_assert(0);
2633                         return NULL;
2634                 }
2635         }
2636
2637         but = MEM_callocN(sizeof(uiBut), "uiBut");
2638
2639         but->type = type & BUTTYPE;
2640         but->pointype = type & UI_BUT_POIN_TYPES;
2641         but->bit = type & UI_BUT_POIN_BIT;
2642         but->bitnr = type & 31;
2643         but->icon = ICON_NONE;
2644         but->iconadd = 0;
2645
2646         but->retval = retval;
2647
2648         slen = strlen(str);
2649         if (slen >= UI_MAX_NAME_STR - 1) {
2650                 but->str = MEM_mallocN(slen + 2, "ui_def_but str"); /* why +2 ? */
2651         }
2652         else {
2653                 but->str = but->strdata;
2654         }
2655         memcpy(but->str, str, slen + 1);
2656
2657         but->rect.xmin = x;
2658         but->rect.ymin = y;
2659         but->rect.xmax = but->rect.xmin + width;
2660         but->rect.ymax = but->rect.ymin + height;
2661
2662         but->poin = poin;
2663         but->hardmin = but->softmin = min;
2664         but->hardmax = but->softmax = max;
2665         but->a1 = a1;
2666         but->a2 = a2;
2667         but->tip = tip;
2668
2669         but->lock = block->lock;
2670         but->lockstr = block->lockstr;
2671         but->dt = block->dt;
2672
2673         but->aspect = 1.0f;  /* XXX block->aspect; */
2674         but->block = block;  /* pointer back, used for frontbuffer status, and picker */
2675
2676         if ((block->flag & UI_BUT_ALIGN) && ui_but_can_align(but))
2677                 but->alignnr = block->alignnr;
2678
2679         but->func = block->func;
2680         but->func_arg1 = block->func_arg1;
2681         but->func_arg2 = block->func_arg2;
2682
2683         but->funcN = block->funcN;
2684         if (block->func_argN)
2685                 but->func_argN = MEM_dupallocN(block->func_argN);
2686         
2687         but->pos = -1;   /* cursor invisible */
2688
2689         if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {    /* add a space to name */
2690                 /* slen remains unchanged from previous assignment, ensure this stays true */
2691                 if (slen > 0 && slen < UI_MAX_NAME_STR - 2) {
2692                         if (but->str[slen - 1] != ' ') {
2693                                 but->str[slen] = ' ';
2694                                 but->str[slen + 1] = 0;
2695                         }
2696                 }
2697         }
2698
2699         if ((block->flag & UI_BLOCK_LOOP) ||
2700             ELEM8(but->type, MENU, TEX, LABEL, IDPOIN, BLOCK, BUTM, SEARCH_MENU, PROGRESSBAR))
2701         {
2702                 but->flag |= (UI_TEXT_LEFT | UI_ICON_LEFT);
2703         }
2704         else if (but->type == BUT_TOGDUAL) {
2705                 but->flag |= UI_ICON_LEFT;
2706         }
2707
2708         but->flag |= (block->flag & UI_BUT_ALIGN);
2709
2710         if (but->lock == TRUE) {
2711                 if (but->lockstr) {
2712                         but->flag |= UI_BUT_DISABLED;
2713                 }
2714         }
2715
2716         /* keep track of UI_interface.h */
2717         if (ELEM7(but->type, BLOCK, BUT, LABEL, PULLDOWN, ROUNDBOX, LISTBOX, BUTM)) ;
2718         else if (ELEM(but->type, SCROLL, SEPR /* , FTPREVIEW */ )) ;
2719         else if (but->type >= SEARCH_MENU) ;
2720         else but->flag |= UI_BUT_UNDO;
2721
2722         BLI_addtail(&block->buttons, but);
2723         
2724         if (block->curlayout)
2725                 ui_layout_add_but(block->curlayout, but);
2726
2727 #ifdef WITH_PYTHON
2728         /* if the 'UI_OT_editsource' is running, extract the source info from the button  */
2729         if (UI_editsource_enable_check()) {
2730                 UI_editsource_active_but_test(but);
2731         }
2732 #endif
2733
2734         return but;
2735 }
2736
2737 /* ui_def_but_rna_propname and ui_def_but_rna
2738  * both take the same args except for propname vs prop, this is done so we can
2739  * avoid an extra lookup on 'prop' when its already available.
2740  *
2741  * When this kind of change won't disrupt branches, best look into making more
2742  * of our UI functions take prop rather then propname.
2743  */
2744
2745 #define UI_DEF_BUT_RNA_DISABLE(but)  { \
2746                 but->flag |= UI_BUT_DISABLED;  \
2747                 but->lock = TRUE;              \
2748                 but->lockstr = "";             \
2749         } (void)0
2750
2751
2752 static uiBut *ui_def_but_rna(uiBlock *block, int type, int retval, const char *str,
2753                                                          int x, int y, short width, short height,
2754                              PointerRNA *ptr, PropertyRNA *prop, int index,
2755                              float min, float max, float a1, float a2,  const char *tip)
2756 {
2757         const PropertyType proptype = RNA_property_type(prop);
2758         uiBut *but;
2759         int freestr = 0, icon = 0;
2760
2761         /* use rna values if parameters are not specified */
2762         if (!str) {
2763                 if (type == MENU && proptype == PROP_ENUM) {
2764                         EnumPropertyItem *item;
2765                         DynStr *dynstr;
2766                         int i, totitem, value, free;
2767
2768                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2769                         value = RNA_property_enum_get(ptr, prop);
2770
2771                         dynstr = BLI_dynstr_new();
2772                         BLI_dynstr_appendf(dynstr, "%s%%t", RNA_property_ui_name(prop));
2773                         for (i = 0; i < totitem; i++) {
2774                                 if (!item[i].identifier[0]) {
2775                                         if (item[i].name)
2776                                                 BLI_dynstr_appendf(dynstr, "|%s%%l", item[i].name);
2777                                         else
2778                                                 BLI_dynstr_append(dynstr, "|%l");
2779                                 }
2780                                 else if (item[i].icon)
2781                                         BLI_dynstr_appendf(dynstr, "|%s %%i%d %%x%d", item[i].name, item[i].icon, item[i].value);
2782                                 else
2783                                         BLI_dynstr_appendf(dynstr, "|%s %%x%d", item[i].name, item[i].value);
2784
2785                                 if (value == item[i].value)
2786                                         icon = item[i].icon;
2787                         }
2788                         str = BLI_dynstr_get_cstring(dynstr);
2789                         BLI_dynstr_free(dynstr);
2790
2791                         if (free) {
2792                                 MEM_freeN(item);
2793                         }
2794
2795                         freestr = 1;
2796                 }
2797                 else if (ELEM(type, ROW, LISTROW) && proptype == PROP_ENUM) {
2798                         EnumPropertyItem *item;
2799                         int i, totitem, free;
2800
2801                         RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);
2802                         for (i = 0; i < totitem; i++) {
2803                                 if (item[i].identifier[0] && item[i].value == (int)max) {
2804                                         str = item[i].name;
2805                                         icon = item[i].icon;
2806                                 }
2807                         }
2808
2809                         if (!str) {
2810                                 str = RNA_property_ui_name(prop);
2811                         }
2812                         if (free) {
2813                                 MEM_freeN(item);
2814                         }
2815                 }
2816                 else {
2817                         str = RNA_property_ui_name(prop);
2818                         icon = RNA_property_ui_icon(prop);
2819                 }
2820         }
2821
2822         if (!tip && proptype != PROP_ENUM)
2823                 tip = RNA_property_ui_description(prop);
2824
2825         if (min == max || a1 == -1 || a2 == -1) {
2826                 if (proptype == PROP_INT) {
2827                         int hardmin, hardmax, softmin, softmax, step;
2828
2829                         RNA_property_int_range(ptr, prop, &hardmin, &hardmax);
2830                         RNA_property_int_ui_range(ptr, prop, &softmin, &softmax, &step);
2831
2832                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2833                                 min = hardmin;
2834                                 max = hardmax;
2835                         }
2836                         if (a1 == -1)
2837                                 a1 = step;
2838                         if (a2 == -1)
2839                                 a2 = 0;
2840                 }
2841                 else if (proptype == PROP_FLOAT) {
2842                         float hardmin, hardmax, softmin, softmax, step, precision;
2843
2844                         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2845                         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2846
2847                         if (!ELEM(type, ROW, LISTROW) && min == max) {
2848                                 min = hardmin;
2849                                 max = hardmax;
2850                         }
2851                         if (a1 == -1)
2852                                 a1 = step;
2853                         if (a2 == -1)
2854                                 a2 = precision;
2855                 }
2856                 else if (proptype == PROP_STRING) {
2857                         min = 0;
2858                         max = RNA_property_string_maxlength(prop);
2859                         if (max == 0) /* interface code should ideally support unlimited length */
2860                                 max = UI_MAX_DRAW_STR;
2861                 }
2862         }
2863
2864         /* now create button */
2865         but = ui_def_but(block, type, retval, str, x, y, width, height, NULL, min, max, a1, a2, tip);
2866
2867         but->rnapoin = *ptr;
2868         but->rnaprop = prop;
2869
2870         if (RNA_property_array_length(&but->rnapoin, but->rnaprop))
2871                 but->rnaindex = index;
2872         else
2873                 but->rnaindex = 0;
2874
2875         if (icon) {
2876                 but->icon = (BIFIconID)icon;
2877                 but->flag |= UI_HAS_ICON;
2878                 but->flag |= UI_ICON_LEFT;
2879         }
2880         
2881         if (!RNA_property_editable(&but->rnapoin, prop)) {
2882                 UI_DEF_BUT_RNA_DISABLE(but);
2883         }
2884
2885         if (but->flag & UI_BUT_UNDO && (ui_but_is_rna_undo(but) == FALSE)) {
2886                 but->flag &= ~UI_BUT_UNDO;
2887         }
2888
2889         /* If this button uses units, calculate the step from this */
2890         if ((proptype == PROP_FLOAT) && ui_is_but_unit(but)) {
2891                 but->a1 = ui_get_but_step_unit(but, but->a1);
2892         }
2893
2894         if (freestr) {
2895                 MEM_freeN((void *)str);
2896         }
2897
2898         return but;
2899 }
2900
2901 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)
2902 {
2903         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2904         uiBut *but;
2905
2906         if (prop) {
2907                 but = ui_def_but_rna(block, type, retval, str, x, y, width, height, ptr, prop, index, min, max, a1, a2,  tip);
2908         }
2909         else {
2910                 but = ui_def_but(block, type, retval, propname, x, y, width, height, NULL, min, max, a1, a2, tip);
2911
2912                 UI_DEF_BUT_RNA_DISABLE(but);
2913         }
2914
2915         return but;
2916 }
2917
2918 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)
2919 {
2920         uiBut *but;
2921
2922         if (!str) {
2923                 if (ot && ot->srna)
2924                         str = RNA_struct_ui_name(ot->srna);
2925                 else
2926                         str = "";
2927         }
2928
2929         if ((!tip || tip[0] == '\0') && ot && ot->srna) {
2930                 tip = RNA_struct_ui_description(ot->srna);
2931         }
2932
2933         but = ui_def_but(block, type, -1, str, x, y, width, height, NULL, 0, 0, 0, 0, tip);
2934         but->optype = ot;
2935         but->opcontext = opcontext;
2936         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2937
2938         if (!ot) {
2939                 but->flag |= UI_BUT_DISABLED;
2940                 but->lock = TRUE;
2941                 but->lockstr = "";
2942         }
2943
2944         return but;
2945 }
2946
2947 #if 0 /* UNUSED */
2948 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)
2949 {
2950         wmOperatorType *ot = WM_operatortype_find(opname, 0);
2951         if (str == NULL && ot == NULL) str = opname;
2952         return ui_def_but_operator_ptr(block, type, ot, opcontext, str, x, y, width, height, tip);
2953 }
2954 #endif
2955
2956 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)
2957 {
2958         uiBut *but;
2959         wmOperatorType *ot;
2960         
2961         ot = WM_operatortype_find(opname, 0);
2962
2963         if (!str) {
2964                 if (ot) str = ot->name;
2965                 else str = opname;
2966         }
2967         
2968         if ((!tip || tip[0] == '\0') && ot && ot->description) {
2969                 tip = ot->description;
2970         }
2971
2972         but = ui_def_but(block, type, -1, str, x, y, width, height, poin, min, max, a1, a2, tip);
2973         but->optype = ot;
2974         but->opcontext = opcontext;
2975         but->flag &= ~UI_BUT_UNDO; /* no need for ui_but_is_undo(), we never need undo here */
2976
2977         if (!ot) {
2978                 but->flag |= UI_BUT_DISABLED;
2979                 but->lock = TRUE;
2980                 but->lockstr = "";
2981         }
2982
2983         return but;
2984 }
2985
2986 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)
2987 {
2988         uiBut *but = ui_def_but(block, type, retval, str, x, y, width, height, poin, min, max, a1, a2, tip);
2989
2990         ui_check_but(but);
2991         
2992         return but;
2993 }
2994
2995 /* if _x_ is a power of two (only one bit) return the power,
2996  * otherwise return -1.
2997  * (1<<findBitIndex(x))==x for powers of two.
2998  */
2999 static int findBitIndex(unsigned int x)
3000 {
3001         if (!x || !is_power_of_2_i(x)) { /* is_power_of_2_i(x) strips lowest bit */
3002                 return -1;
3003         }
3004         else {
3005                 int idx = 0;
3006
3007                 if (x & 0xFFFF0000) idx += 16, x >>= 16;
3008                 if (x & 0xFF00) idx += 8, x >>= 8;
3009                 if (x & 0xF0) idx += 4, x >>= 4;
3010                 if (x & 0xC) idx += 2, x >>= 2;
3011                 if (x & 0x2) idx += 1;
3012
3013                 return idx;
3014         }
3015 }
3016
3017 /* autocomplete helper functions */
3018 struct AutoComplete {
3019         size_t maxlen;
3020         char *truncate;
3021         const char *startname;
3022 };
3023
3024 AutoComplete *autocomplete_begin(const char *startname, size_t maxlen)
3025 {
3026         AutoComplete *autocpl;
3027         
3028         autocpl = MEM_callocN(sizeof(AutoComplete), "AutoComplete");
3029         autocpl->maxlen = maxlen;
3030         autocpl->truncate = MEM_callocN(sizeof(char) * maxlen, "AutoCompleteTruncate");
3031         autocpl->startname = startname;
3032
3033         return autocpl;
3034 }
3035
3036 void autocomplete_do_name(AutoComplete *autocpl, const char *name)
3037 {
3038         char *truncate = autocpl->truncate;
3039         const char *startname = autocpl->startname;
3040         int a;
3041
3042         for (a = 0; a < autocpl->maxlen - 1; a++) {
3043                 if (startname[a] == 0 || startname[a] != name[a])
3044                         break;
3045         }
3046         /* found a match */
3047         if (startname[a] == 0) {
3048                 /* first match */
3049                 if (truncate[0] == 0)
3050                         BLI_strncpy(truncate, name, autocpl->maxlen);
3051                 else {
3052                         /* remove from truncate what is not in bone->name */
3053                         for (a = 0; a < autocpl->maxlen - 1; a++) {
3054                                 if (name[a] == 0) {
3055                                         truncate[a] = 0;
3056                                         break;
3057                                 }
3058                                 else if (truncate[a] != name[a])
3059                                         truncate[a] = 0;
3060                         }
3061                 }
3062         }
3063 }
3064
3065 void autocomplete_end(AutoComplete *autocpl, char *autoname)
3066 {       
3067         if (autocpl->truncate[0])
3068                 BLI_strncpy(autoname, autocpl->truncate, autocpl->maxlen);
3069         else {
3070                 if (autoname != autocpl->startname) /* don't copy a string over its self */
3071                         BLI_strncpy(autoname, autocpl->startname, autocpl->maxlen);
3072         }
3073         MEM_freeN(autocpl->truncate);
3074         MEM_freeN(autocpl);
3075 }
3076
3077 /* autocomplete callback for ID buttons */
3078 static void autocomplete_id(bContext *C, char *str, void *arg_v)
3079 {
3080         int blocktype = (intptr_t)arg_v;
3081         ListBase *listb = which_libbase(CTX_data_main(C), blocktype);
3082         
3083         if (listb == NULL) return;
3084         
3085         /* search if str matches the beginning of an ID struct */
3086         if (str[0]) {
3087                 AutoComplete *autocpl = autocomplete_begin(str, MAX_ID_NAME - 2);
3088                 ID *id;
3089                 
3090                 for (id = listb->first; id; id = id->next)
3091                         autocomplete_do_name(autocpl, id->name + 2);