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