Add red alert in UI controls for datablock pointer properties
[blender.git] / source / blender / editors / interface / interface_regions.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) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_regions.c
27  *  \ingroup edinterface
28  */
29
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_userdef_types.h"
38
39 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_ghash.h"
43
44 #include "PIL_time.h"
45
46 #include "BKE_context.h"
47 #include "BKE_screen.h"
48 #include "BKE_report.h"
49 #include "BKE_global.h"
50
51 #include "WM_api.h"
52 #include "WM_types.h"
53 #include "wm_draw.h"
54 #include "wm_subwindow.h"
55
56 #include "RNA_access.h"
57
58 #include "BIF_gl.h"
59
60 #include "UI_interface.h"
61 #include "UI_interface_icons.h"
62 #include "UI_view2d.h"
63
64 #include "BLF_api.h"
65 #include "BLT_translation.h"
66
67 #include "ED_screen.h"
68
69 #include "IMB_colormanagement.h"
70
71 #include "interface_intern.h"
72
73 #define MENU_PADDING            (int)(0.2f * UI_UNIT_Y)
74 #define MENU_BORDER                     (int)(0.3f * U.widget_unit)
75
76
77 bool ui_but_menu_step_poll(const uiBut *but)
78 {
79         BLI_assert(but->type == UI_BTYPE_MENU);
80
81         /* currently only RNA buttons */
82         return ((but->menu_step_func != NULL) ||
83                 (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM));
84 }
85
86 int ui_but_menu_step(uiBut *but, int direction)
87 {
88         if (ui_but_menu_step_poll(but)) {
89                 if (but->menu_step_func) {
90                         return but->menu_step_func(but->block->evil_C, direction, but->poin);
91                 }
92                 else {
93                         const int curval = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
94                         return RNA_property_enum_step(but->block->evil_C, &but->rnapoin, but->rnaprop, curval, direction);
95                 }
96         }
97
98         printf("%s: cannot cycle button '%s'\n", __func__, but->str);
99         return 0;
100 }
101
102 /******************** Creating Temporary regions ******************/
103
104 static ARegion *ui_region_temp_add(bScreen *sc)
105 {
106         ARegion *ar;
107
108         ar = MEM_callocN(sizeof(ARegion), "area region");
109         BLI_addtail(&sc->regionbase, ar);
110
111         ar->regiontype = RGN_TYPE_TEMPORARY;
112         ar->alignment = RGN_ALIGN_FLOAT;
113
114         return ar;
115 }
116
117 static void ui_region_temp_remove(bContext *C, bScreen *sc, ARegion *ar)
118 {
119         wmWindow *win = CTX_wm_window(C);
120         if (win)
121                 wm_draw_region_clear(win, ar);
122
123         ED_region_exit(C, ar);
124         BKE_area_region_free(NULL, ar);     /* NULL: no spacetype */
125         BLI_freelinkN(&sc->regionbase, ar);
126 }
127
128 /************************* Creating Tooltips **********************/
129
130 #define UI_TIP_PAD_FAC      1.3f
131 #define UI_TIP_PADDING      (int)(UI_TIP_PAD_FAC * UI_UNIT_Y)
132 #define UI_TIP_MAXWIDTH     600
133
134 #define MAX_TOOLTIP_LINES 8
135 typedef struct uiTooltipData {
136         rcti bbox;
137         uiFontStyle fstyle;
138         char lines[MAX_TOOLTIP_LINES][2048];
139         char header[2048], active_info[2048];
140         struct {
141                 enum {
142                         UI_TIP_STYLE_NORMAL = 0,
143                         UI_TIP_STYLE_HEADER,
144                         UI_TIP_STYLE_MONO,
145                 } style : 3;
146                 enum {
147                         UI_TIP_LC_MAIN = 0,     /* primary text */
148                         UI_TIP_LC_VALUE,        /* the value of buttons (also shortcuts) */
149                         UI_TIP_LC_ACTIVE,       /* titles of active enum values */
150                         UI_TIP_LC_NORMAL,       /* regular text */
151                         UI_TIP_LC_PYTHON,       /* Python snippet */
152                         UI_TIP_LC_ALERT,        /* description of why operator can't run */
153                 } color_id : 4;
154                 int is_pad : 1;
155         } format[MAX_TOOLTIP_LINES];
156
157         struct {
158                 unsigned int x_pos;     /* x cursor position at the end of the last line */
159                 unsigned int lines;     /* number of lines, 1 or more with word-wrap */
160         } line_geom[MAX_TOOLTIP_LINES];
161
162         int wrap_width;
163
164         int totline;
165         int toth, lineh;
166 } uiTooltipData;
167
168 #define UI_TIP_LC_MAX 6
169
170 BLI_STATIC_ASSERT(UI_TIP_LC_MAX == UI_TIP_LC_ALERT + 1, "invalid lc-max");
171 BLI_STATIC_ASSERT(sizeof(((uiTooltipData *)NULL)->format[0]) <= sizeof(int), "oversize");
172
173 static void rgb_tint(
174         float col[3],
175         float h, float h_strength,
176         float v, float v_strength)
177 {
178         float col_hsv_from[3];
179         float col_hsv_to[3];
180
181         rgb_to_hsv_v(col, col_hsv_from);
182
183         col_hsv_to[0] = h;
184         col_hsv_to[1] = h_strength;
185         col_hsv_to[2] = (col_hsv_from[2] * (1.0f - v_strength)) + (v * v_strength);
186
187         hsv_to_rgb_v(col_hsv_to, col);
188 }
189
190 static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
191 {
192         const float pad_px = UI_TIP_PADDING;
193         uiTooltipData *data = ar->regiondata;
194         uiWidgetColors *theme = ui_tooltip_get_theme();
195         rcti bbox = data->bbox;
196         float tip_colors[UI_TIP_LC_MAX][3];
197
198         float *main_color    = tip_colors[UI_TIP_LC_MAIN]; /* the color from the theme */
199         float *value_color   = tip_colors[UI_TIP_LC_VALUE];
200         float *active_color  = tip_colors[UI_TIP_LC_ACTIVE];
201         float *normal_color  = tip_colors[UI_TIP_LC_NORMAL];
202         float *python_color  = tip_colors[UI_TIP_LC_PYTHON];
203         float *alert_color   = tip_colors[UI_TIP_LC_ALERT];
204
205         float background_color[3];
206         float tone_bg;
207         int i, multisample_enabled;
208
209         /* disable AA, makes widgets too blurry */
210         multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
211         if (multisample_enabled)
212                 glDisable(GL_MULTISAMPLE);
213
214         wmOrtho2_region_pixelspace(ar);
215
216         /* draw background */
217         ui_draw_tooltip_background(UI_style_get(), NULL, &bbox);
218
219         /* set background_color */
220         rgb_uchar_to_float(background_color, (const unsigned char *)theme->inner);
221
222         /* calculate normal_color */
223         rgb_uchar_to_float(main_color, (const unsigned char *)theme->text);
224         copy_v3_v3(active_color, main_color);
225         copy_v3_v3(normal_color, main_color);
226         copy_v3_v3(python_color, main_color);
227         copy_v3_v3(alert_color, main_color);
228         copy_v3_v3(value_color, main_color);
229
230         /* find the brightness difference between background and text colors */
231         
232         tone_bg = rgb_to_grayscale(background_color);
233         /* tone_fg = rgb_to_grayscale(main_color); */
234
235         /* mix the colors */
236         rgb_tint(value_color,  0.0f, 0.0f, tone_bg, 0.2f);  /* light gray */
237         rgb_tint(active_color, 0.6f, 0.2f, tone_bg, 0.2f);  /* light blue */
238         rgb_tint(normal_color, 0.0f, 0.0f, tone_bg, 0.4f);  /* gray       */
239         rgb_tint(python_color, 0.0f, 0.0f, tone_bg, 0.5f);  /* dark gray  */
240         rgb_tint(alert_color,  0.0f, 0.8f, tone_bg, 0.1f);  /* red        */
241
242         /* draw text */
243         BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
244         BLF_wordwrap(blf_mono_font, data->wrap_width);
245
246         bbox.xmin += 0.5f * pad_px;  /* add padding to the text */
247         bbox.ymax -= 0.25f * pad_px;
248
249         for (i = 0; i < data->totline; i++) {
250                 bbox.ymin = bbox.ymax - (data->lineh * data->line_geom[i].lines);
251                 if (data->format[i].style == UI_TIP_STYLE_HEADER) {
252                         /* draw header and active data (is done here to be able to change color) */
253                         uiFontStyle fstyle_header = data->fstyle;
254                         float xofs, yofs;
255
256                         /* override text-style */
257                         fstyle_header.shadow = 1;
258                         fstyle_header.shadowcolor = rgb_to_grayscale(tip_colors[UI_TIP_LC_MAIN]);
259                         fstyle_header.shadx = fstyle_header.shady = 0;
260                         fstyle_header.shadowalpha = 1.0f;
261                         fstyle_header.word_wrap = true;
262
263                         UI_fontstyle_set(&fstyle_header);
264                         glColor3fv(tip_colors[UI_TIP_LC_MAIN]);
265                         UI_fontstyle_draw(&fstyle_header, &bbox, data->header);
266
267                         /* offset to the end of the last line */
268                         xofs = data->line_geom[i].x_pos;
269                         yofs = data->lineh * (data->line_geom[i].lines - 1);
270                         bbox.xmin += xofs;
271                         bbox.ymax -= yofs;
272
273                         glColor3fv(tip_colors[UI_TIP_LC_ACTIVE]);
274                         fstyle_header.shadow = 0;
275                         UI_fontstyle_draw(&fstyle_header, &bbox, data->active_info);
276
277                         /* undo offset */
278                         bbox.xmin -= xofs;
279                         bbox.ymax += yofs;
280                 }
281                 else if (data->format[i].style == UI_TIP_STYLE_MONO) {
282                         uiFontStyle fstyle_mono = data->fstyle;
283                         fstyle_mono.uifont_id = blf_mono_font;
284                         fstyle_mono.word_wrap = true;
285
286                         UI_fontstyle_set(&fstyle_mono);
287                         /* XXX, needed because we dont have mono in 'U.uifonts' */
288                         BLF_size(fstyle_mono.uifont_id, fstyle_mono.points * U.pixelsize, U.dpi);
289                         glColor3fv(tip_colors[data->format[i].color_id]);
290                         UI_fontstyle_draw(&fstyle_mono, &bbox, data->lines[i]);
291                 }
292                 else {
293                         uiFontStyle fstyle_normal = data->fstyle;
294                         BLI_assert(data->format[i].style == UI_TIP_STYLE_NORMAL);
295                         fstyle_normal.word_wrap = true;
296
297                         /* draw remaining data */
298                         UI_fontstyle_set(&fstyle_normal);
299                         glColor3fv(tip_colors[data->format[i].color_id]);
300                         UI_fontstyle_draw(&fstyle_normal, &bbox, data->lines[i]);
301                 }
302
303                 bbox.ymax -= data->lineh * data->line_geom[i].lines;
304
305                 if ((i + 1 != data->totline) && data->format[i + 1].is_pad) {
306                         bbox.ymax -= data->lineh * (UI_TIP_PAD_FAC - 1);
307                 }
308         }
309
310         BLF_disable(data->fstyle.uifont_id, BLF_WORD_WRAP);
311         BLF_disable(blf_mono_font, BLF_WORD_WRAP);
312
313         if (multisample_enabled)
314                 glEnable(GL_MULTISAMPLE);
315 }
316
317 static void ui_tooltip_region_free_cb(ARegion *ar)
318 {
319         uiTooltipData *data;
320
321         data = ar->regiondata;
322         MEM_freeN(data);
323         ar->regiondata = NULL;
324 }
325
326 static uiTooltipData *ui_tooltip_data_from_button(bContext *C, uiBut *but)
327 {
328         uiStringInfo but_tip = {BUT_GET_TIP, NULL};
329         uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
330         uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
331         uiStringInfo op_keymap = {BUT_GET_OP_KEYMAP, NULL};
332         uiStringInfo prop_keymap = {BUT_GET_PROP_KEYMAP, NULL};
333         uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
334         uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
335
336         char buf[512];
337
338         /* create tooltip data */
339         uiTooltipData *data = MEM_callocN(sizeof(uiTooltipData), "uiTooltipData");
340
341         UI_but_string_info_get(C, but, &but_tip, &enum_label, &enum_tip, &op_keymap, &prop_keymap, &rna_struct, &rna_prop, NULL);
342
343         /* Tip */
344         if (but_tip.strinfo) {
345                 BLI_strncpy(data->header, but_tip.strinfo, sizeof(data->lines[0]));
346                 if (enum_label.strinfo) {
347                         BLI_snprintf(data->header, sizeof(data->header), "%s:  ", but_tip.strinfo);
348                         BLI_strncpy(data->active_info, enum_label.strinfo, sizeof(data->lines[0]));
349                 }
350                 data->format[data->totline].style = UI_TIP_STYLE_HEADER;
351                 data->totline++;
352
353                 /* special case enum rna buttons */
354                 if ((but->type & UI_BTYPE_ROW) && but->rnaprop && RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG) {
355                         BLI_strncpy(data->lines[data->totline], IFACE_("(Shift-Click/Drag to select multiple)"),
356                                     sizeof(data->lines[0]));
357
358                         data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
359                         data->totline++;
360                 }
361
362         }
363         /* Enum item label & tip */
364         if (enum_tip.strinfo) {
365                 BLI_strncpy(data->lines[data->totline], enum_tip.strinfo, sizeof(data->lines[0]));
366                 data->format[data->totline].is_pad = true;
367                 data->format[data->totline].color_id = UI_TIP_LC_VALUE;
368                 data->totline++;
369         }
370
371         /* Op shortcut */
372         if (op_keymap.strinfo) {
373                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), op_keymap.strinfo);
374                 data->format[data->totline].is_pad = true;
375                 data->format[data->totline].color_id = UI_TIP_LC_VALUE;
376                 data->totline++;
377         }
378         
379         /* Property context-toggle shortcut */
380         if (prop_keymap.strinfo) {
381                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), prop_keymap.strinfo);
382                 data->format[data->totline].is_pad = true;
383                 data->format[data->totline].color_id = UI_TIP_LC_VALUE;
384                 data->totline++;
385         }
386
387         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
388                 /* better not show the value of a password */
389                 if ((but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) == 0) {
390                         /* full string */
391                         ui_but_string_get(but, buf, sizeof(buf));
392                         if (buf[0]) {
393                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Value: %s"), buf);
394                                 data->format[data->totline].is_pad = true;
395                                 data->format[data->totline].color_id = UI_TIP_LC_VALUE;
396                                 data->totline++;
397                         }
398                 }
399         }
400
401         if (but->rnaprop) {
402                 int unit_type = UI_but_unit_type_get(but);
403                 
404                 if (unit_type == PROP_UNIT_ROTATION) {
405                         if (RNA_property_type(but->rnaprop) == PROP_FLOAT) {
406                                 float value = RNA_property_array_check(but->rnaprop) ?
407                                                   RNA_property_float_get_index(&but->rnapoin, but->rnaprop, but->rnaindex) :
408                                                   RNA_property_float_get(&but->rnapoin, but->rnaprop);
409                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Radians: %f"), value);
410                                 data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
411                                 data->totline++;
412                         }
413                 }
414                 
415                 if (but->flag & UI_BUT_DRIVEN) {
416                         if (ui_but_anim_expression_get(but, buf, sizeof(buf))) {
417                                 /* expression */
418                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Expression: %s"), buf);
419                                 data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
420                                 data->totline++;
421                         }
422                 }
423
424                 if (but->rnapoin.id.data) {
425                         ID *id = but->rnapoin.id.data;
426                         if (ID_IS_LINKED_DATABLOCK(id)) {
427                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Library: %s"), id->lib->name);
428                                 data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
429                                 data->totline++;
430                         }
431                 }
432         }
433         else if (but->optype) {
434                 PointerRNA *opptr;
435                 char *str;
436                 opptr = UI_but_operator_ptr_get(but); /* allocated when needed, the button owns it */
437
438                 /* so the context is passed to itemf functions (some py itemf functions use it) */
439                 WM_operator_properties_sanitize(opptr, false);
440
441                 str = WM_operator_pystring_ex(C, NULL, false, false, but->optype, opptr);
442
443                 /* avoid overly verbose tips (eg, arrays of 20 layers), exact limit is arbitrary */
444                 WM_operator_pystring_abbreviate(str, 32);
445
446                 /* operator info */
447                 if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
448                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s"), str);
449                         data->format[data->totline].style = UI_TIP_STYLE_MONO;
450                         data->format[data->totline].is_pad = true;
451                         data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
452                         data->totline++;
453                 }
454
455                 MEM_freeN(str);
456         }
457
458         /* button is disabled, we may be able to tell user why */
459         if (but->flag & UI_BUT_DISABLED) {
460                 const char *disabled_msg = NULL;
461
462                 /* if operator poll check failed, it can give pretty precise info why */
463                 if (but->optype) {
464                         CTX_wm_operator_poll_msg_set(C, NULL);
465                         WM_operator_poll_context(C, but->optype, but->opcontext);
466                         disabled_msg = CTX_wm_operator_poll_msg_get(C);
467                 }
468                 /* alternatively, buttons can store some reasoning too */
469                 else if (but->disabled_info) {
470                         disabled_msg = TIP_(but->disabled_info);
471                 }
472
473                 if (disabled_msg && disabled_msg[0]) {
474                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Disabled: %s"), disabled_msg);
475                         data->format[data->totline].color_id = UI_TIP_LC_ALERT;
476                         data->totline++;
477                 }
478         }
479
480         if ((U.flag & USER_TOOLTIPS_PYTHON) == 0 && !but->optype && rna_struct.strinfo) {
481                 if (rna_prop.strinfo) {
482                         /* Struct and prop */
483                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
484                                      TIP_("Python: %s.%s"),
485                                      rna_struct.strinfo, rna_prop.strinfo);
486                 }
487                 else {
488                         /* Only struct (e.g. menus) */
489                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
490                                      TIP_("Python: %s"), rna_struct.strinfo);
491                 }
492                 data->format[data->totline].style = UI_TIP_STYLE_MONO;
493                 data->format[data->totline].is_pad = true;
494                 data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
495                 data->totline++;
496
497                 if (but->rnapoin.id.data) {
498                         /* this could get its own 'BUT_GET_...' type */
499
500                         /* never fails */
501                         char *id_path;
502
503                         if (but->rnaprop) {
504                                 id_path = RNA_path_full_property_py_ex(&but->rnapoin, but->rnaprop, but->rnaindex, true);
505                         }
506                         else {
507                                 id_path = RNA_path_full_struct_py(&but->rnapoin);
508                         }
509
510                         BLI_strncat_utf8(data->lines[data->totline], id_path, sizeof(data->lines[0]));
511                         MEM_freeN(id_path);
512
513                         data->format[data->totline].style = UI_TIP_STYLE_MONO;
514                         data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
515                         data->totline++;
516                 }
517         }
518
519         /* Free strinfo's... */
520         if (but_tip.strinfo)
521                 MEM_freeN(but_tip.strinfo);
522         if (enum_label.strinfo)
523                 MEM_freeN(enum_label.strinfo);
524         if (enum_tip.strinfo)
525                 MEM_freeN(enum_tip.strinfo);
526         if (op_keymap.strinfo)
527                 MEM_freeN(op_keymap.strinfo);
528         if (prop_keymap.strinfo)
529                 MEM_freeN(prop_keymap.strinfo);
530         if (rna_struct.strinfo)
531                 MEM_freeN(rna_struct.strinfo);
532         if (rna_prop.strinfo)
533                 MEM_freeN(rna_prop.strinfo);
534
535         BLI_assert(data->totline < MAX_TOOLTIP_LINES);
536         
537         if (data->totline == 0) {
538                 MEM_freeN(data);
539                 return NULL;
540         }
541         else {
542                 return data;
543         }
544 }
545
546 ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
547 {
548         const float pad_px = UI_TIP_PADDING;
549         wmWindow *win = CTX_wm_window(C);
550         const int winx = WM_window_pixels_x(win);
551         uiStyle *style = UI_style_get();
552         static ARegionType type;
553         ARegion *ar;
554 /*      IDProperty *prop;*/
555         /* aspect values that shrink text are likely unreadable */
556         const float aspect = min_ff(1.0f, but->block->aspect);
557         int fonth, fontw;
558         int ofsx, ofsy, h, i;
559         rctf rect_fl;
560         rcti rect_i;
561         int font_flag = 0;
562
563         if (but->drawflag & UI_BUT_NO_TOOLTIP) {
564                 return NULL;
565         }
566
567         uiTooltipData *data = ui_tooltip_data_from_button(C, but);
568         if (data == NULL) {
569                 return NULL;
570         }
571
572         /* create area region */
573         ar = ui_region_temp_add(CTX_wm_screen(C));
574
575         memset(&type, 0, sizeof(ARegionType));
576         type.draw = ui_tooltip_region_draw_cb;
577         type.free = ui_tooltip_region_free_cb;
578         type.regionid = RGN_TYPE_TEMPORARY;
579         ar->type = &type;
580         
581         /* set font, get bb */
582         data->fstyle = style->widget; /* copy struct */
583         ui_fontscale(&data->fstyle.points, aspect);
584
585         UI_fontstyle_set(&data->fstyle);
586
587         data->wrap_width = min_ii(UI_TIP_MAXWIDTH * U.pixelsize / aspect, winx - (UI_TIP_PADDING * 2));
588
589         font_flag |= BLF_WORD_WRAP;
590         if (data->fstyle.kerning == 1) {
591                 font_flag |= BLF_KERNING_DEFAULT;
592         }
593         BLF_enable(data->fstyle.uifont_id, font_flag);
594         BLF_enable(blf_mono_font, font_flag);
595         BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
596         BLF_wordwrap(blf_mono_font, data->wrap_width);
597
598         /* these defines tweaked depending on font */
599 #define TIP_BORDER_X (16.0f / aspect)
600 #define TIP_BORDER_Y (6.0f / aspect)
601
602         h = BLF_height_max(data->fstyle.uifont_id);
603
604         for (i = 0, fontw = 0, fonth = 0; i < data->totline; i++) {
605                 struct ResultBLF info;
606                 int w, x_pos = 0;
607
608                 if (data->format[i].style == UI_TIP_STYLE_HEADER) {
609                         w = BLF_width_ex(data->fstyle.uifont_id, data->header, sizeof(data->header), &info);
610                         /* check for enum label */
611                         if (data->active_info[0]) {
612                                 x_pos = info.width;
613                                 w = max_ii(w, x_pos + BLF_width(data->fstyle.uifont_id, data->active_info, sizeof(data->active_info)));
614                         }
615                 }
616                 else if (data->format[i].style == UI_TIP_STYLE_MONO) {
617                         BLF_size(blf_mono_font, data->fstyle.points * U.pixelsize, U.dpi);
618
619                         w = BLF_width_ex(blf_mono_font, data->lines[i], sizeof(data->lines[i]), &info);
620                 }
621                 else {
622                         BLI_assert(data->format[i].style == UI_TIP_STYLE_NORMAL);
623
624                         w = BLF_width_ex(data->fstyle.uifont_id, data->lines[i], sizeof(data->lines[i]), &info);
625                 }
626
627                 fontw = max_ii(fontw, w);
628
629                 fonth += h * info.lines;
630                 if ((i + 1 != data->totline) && data->format[i + 1].is_pad) {
631                         fonth += h * (UI_TIP_PAD_FAC - 1);
632                 }
633
634                 data->line_geom[i].lines = info.lines;
635                 data->line_geom[i].x_pos = x_pos;
636         }
637
638         //fontw *= aspect;
639
640         BLF_disable(data->fstyle.uifont_id, font_flag);
641         BLF_disable(blf_mono_font, font_flag);
642
643         ar->regiondata = data;
644
645         data->toth = fonth;
646         data->lineh = h;
647
648         /* compute position */
649         ofsx = 0; //(but->block->panel) ? but->block->panel->ofsx : 0;
650         ofsy = 0; //(but->block->panel) ? but->block->panel->ofsy : 0;
651
652         rect_fl.xmin = BLI_rctf_cent_x(&but->rect) + ofsx - TIP_BORDER_X;
653         rect_fl.xmax = rect_fl.xmin + fontw + pad_px;
654         rect_fl.ymax = but->rect.ymin + ofsy - TIP_BORDER_Y;
655         rect_fl.ymin = rect_fl.ymax - fonth  - TIP_BORDER_Y;
656         
657         /* since the text has beens caled already, the size of tooltips is defined now */
658         /* here we try to figure out the right location */
659         if (butregion) {
660                 float mx, my;
661                 float ofsx_fl = rect_fl.xmin, ofsy_fl = rect_fl.ymax;
662                 ui_block_to_window_fl(butregion, but->block, &ofsx_fl, &ofsy_fl);
663
664 #if 1
665                 /* use X mouse location */
666                 mx = (win->eventstate->x + (TIP_BORDER_X * 2)) - BLI_rctf_cent_x(&but->rect);
667 #else
668                 mx = ofsx_fl - rect_fl.xmin;
669 #endif
670                 my = ofsy_fl - rect_fl.ymax;
671
672                 BLI_rctf_translate(&rect_fl, mx, my);
673         }
674         BLI_rcti_rctf_copy(&rect_i, &rect_fl);
675
676 #undef TIP_BORDER_X
677 #undef TIP_BORDER_Y
678
679         /* clip with window boundaries */
680         if (rect_i.xmax > winx) {
681                 /* super size */
682                 if (rect_i.xmax > winx + rect_i.xmin) {
683                         rect_i.xmax = winx;
684                         rect_i.xmin = 0;
685                 }
686                 else {
687                         rect_i.xmin -= rect_i.xmax - winx;
688                         rect_i.xmax = winx;
689                 }
690         }
691         /* ensure at least 5 px above screen bounds
692          * 25 is just a guess to be above the menu item */
693         if (rect_i.ymin < 5) {
694                 rect_i.ymax += (-rect_i.ymin) + 30;
695                 rect_i.ymin = 30;
696         }
697
698         /* add padding */
699         BLI_rcti_resize(&rect_i,
700                         BLI_rcti_size_x(&rect_i) + pad_px,
701                         BLI_rcti_size_y(&rect_i) + pad_px);
702
703         /* widget rect, in region coords */
704         {
705                 const int margin = UI_POPUP_MARGIN;
706                 
707                 data->bbox.xmin = margin;
708                 data->bbox.xmax = BLI_rcti_size_x(&rect_i) - margin;
709                 data->bbox.ymin = margin;
710                 data->bbox.ymax = BLI_rcti_size_y(&rect_i);
711                 
712                 /* region bigger for shadow */
713                 ar->winrct.xmin = rect_i.xmin - margin;
714                 ar->winrct.xmax = rect_i.xmax + margin;
715                 ar->winrct.ymin = rect_i.ymin - margin;
716                 ar->winrct.ymax = rect_i.ymax + margin;
717         }
718
719         /* adds subwindow */
720         ED_region_init(C, ar);
721         
722         /* notify change and redraw */
723         ED_region_tag_redraw(ar);
724
725         return ar;
726 }
727
728 void ui_tooltip_free(bContext *C, ARegion *ar)
729 {
730         ui_region_temp_remove(C, CTX_wm_screen(C), ar);
731 }
732
733
734 /************************* Creating Search Box **********************/
735
736 struct uiSearchItems {
737         int maxitem, totitem, maxstrlen;
738         
739         int offset, offset_i; /* offset for inserting in array */
740         int more;  /* flag indicating there are more items */
741         
742         char **names;
743         void **pointers;
744         int *icons;
745
746         AutoComplete *autocpl;
747         void *active;
748 };
749
750 typedef struct uiSearchboxData {
751         rcti bbox;
752         uiFontStyle fstyle;
753         uiSearchItems items;
754         int active;     /* index in items array */
755         bool noback;    /* when menu opened with enough space for this */
756         bool preview;   /* draw thumbnail previews, rather than list */
757         bool use_sep;   /* use the UI_SEP_CHAR char for splitting shortcuts (good for operators, bad for data) */
758         int prv_rows, prv_cols;
759 } uiSearchboxData;
760
761 #define SEARCH_ITEMS    10
762
763 /* exported for use by search callbacks */
764 /* returns zero if nothing to add */
765 bool UI_search_item_add(uiSearchItems *items, const char *name, void *poin, int iconid)
766 {
767         /* hijack for autocomplete */
768         if (items->autocpl) {
769                 UI_autocomplete_update_name(items->autocpl, name);
770                 return true;
771         }
772         
773         /* hijack for finding active item */
774         if (items->active) {
775                 if (poin == items->active)
776                         items->offset_i = items->totitem;
777                 items->totitem++;
778                 return true;
779         }
780         
781         if (items->totitem >= items->maxitem) {
782                 items->more = 1;
783                 return false;
784         }
785         
786         /* skip first items in list */
787         if (items->offset_i > 0) {
788                 items->offset_i--;
789                 return true;
790         }
791         
792         if (items->names)
793                 BLI_strncpy(items->names[items->totitem], name, items->maxstrlen);
794         if (items->pointers)
795                 items->pointers[items->totitem] = poin;
796         if (items->icons)
797                 items->icons[items->totitem] = iconid;
798         
799         items->totitem++;
800         
801         return true;
802 }
803
804 int UI_searchbox_size_y(void)
805 {
806         return SEARCH_ITEMS * UI_UNIT_Y + 2 * UI_POPUP_MENU_TOP;
807 }
808
809 int UI_searchbox_size_x(void)
810 {
811         return 12 * UI_UNIT_X;
812 }
813
814 int UI_search_items_find_index(uiSearchItems *items, const char *name, const size_t offset)
815 {
816         int i;
817         for (i = 0; i < items->totitem; i++) {
818                 if (STREQ(name, items->names[i] + offset)) {
819                         return i;
820                 }
821         }
822         return -1;
823 }
824
825 /* ar is the search box itself */
826 static void ui_searchbox_select(bContext *C, ARegion *ar, uiBut *but, int step)
827 {
828         uiSearchboxData *data = ar->regiondata;
829         
830         /* apply step */
831         data->active += step;
832         
833         if (data->items.totitem == 0) {
834                 data->active = -1;
835         }
836         else if (data->active >= data->items.totitem) {
837                 if (data->items.more) {
838                         data->items.offset++;
839                         data->active = data->items.totitem - 1;
840                         ui_searchbox_update(C, ar, but, false);
841                 }
842                 else {
843                         data->active = data->items.totitem - 1;
844                 }
845         }
846         else if (data->active < 0) {
847                 if (data->items.offset) {
848                         data->items.offset--;
849                         data->active = 0;
850                         ui_searchbox_update(C, ar, but, false);
851                 }
852                 else {
853                         /* only let users step into an 'unset' state for unlink buttons */
854                         data->active = (but->flag & UI_BUT_VALUE_CLEAR) ? -1 : 0;
855                 }
856         }
857         
858         ED_region_tag_redraw(ar);
859 }
860
861 static void ui_searchbox_butrect(rcti *r_rect, uiSearchboxData *data, int itemnr)
862 {
863         /* thumbnail preview */
864         if (data->preview) {
865                 int butw = (BLI_rcti_size_x(&data->bbox) - 2 * MENU_BORDER) / data->prv_cols;
866                 int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_BORDER) / data->prv_rows;
867                 int row, col;
868                 
869                 *r_rect = data->bbox;
870                 
871                 col = itemnr % data->prv_cols;
872                 row = itemnr / data->prv_cols;
873                 
874                 r_rect->xmin += MENU_BORDER + (col * butw);
875                 r_rect->xmax = r_rect->xmin + butw;
876                 
877                 r_rect->ymax -= MENU_BORDER + (row * buth);
878                 r_rect->ymin = r_rect->ymax - buth;
879         }
880         /* list view */
881         else {
882                 int buth = (BLI_rcti_size_y(&data->bbox) - 2 * UI_POPUP_MENU_TOP) / SEARCH_ITEMS;
883                 
884                 *r_rect = data->bbox;
885                 r_rect->xmin = data->bbox.xmin + 3.0f;
886                 r_rect->xmax = data->bbox.xmax - 3.0f;
887                 
888                 r_rect->ymax = data->bbox.ymax - UI_POPUP_MENU_TOP - itemnr * buth;
889                 r_rect->ymin = r_rect->ymax - buth;
890         }
891         
892 }
893
894 int ui_searchbox_find_index(ARegion *ar, const char *name)
895 {
896         uiSearchboxData *data = ar->regiondata;
897         return UI_search_items_find_index(&data->items, name, 0);
898 }
899
900 /* x and y in screencoords */
901 bool ui_searchbox_inside(ARegion *ar, int x, int y)
902 {
903         uiSearchboxData *data = ar->regiondata;
904         
905         return BLI_rcti_isect_pt(&data->bbox, x - ar->winrct.xmin, y - ar->winrct.ymin);
906 }
907
908 /* string validated to be of correct length (but->hardmax) */
909 bool ui_searchbox_apply(uiBut *but, ARegion *ar)
910 {
911         uiSearchboxData *data = ar->regiondata;
912
913         but->func_arg2 = NULL;
914         
915         if (data->active != -1) {
916                 const char *name = data->items.names[data->active];
917                 const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
918
919                 BLI_strncpy(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen);
920                 
921                 but->func_arg2 = data->items.pointers[data->active];
922
923                 return true;
924         }
925         else if (but->flag & UI_BUT_VALUE_CLEAR) {
926                 /* It is valid for _VALUE_CLEAR flavor to have no active element (it's a valid way to unlink). */
927                 but->editstr[0] = '\0';
928
929                 return true;
930         }
931         else {
932                 return false;
933         }
934 }
935
936 void ui_searchbox_event(bContext *C, ARegion *ar, uiBut *but, const wmEvent *event)
937 {
938         uiSearchboxData *data = ar->regiondata;
939         int type = event->type, val = event->val;
940         
941         if (type == MOUSEPAN)
942                 ui_pan_to_scroll(event, &type, &val);
943         
944         switch (type) {
945                 case WHEELUPMOUSE:
946                 case UPARROWKEY:
947                         ui_searchbox_select(C, ar, but, -1);
948                         break;
949                 case WHEELDOWNMOUSE:
950                 case DOWNARROWKEY:
951                         ui_searchbox_select(C, ar, but, 1);
952                         break;
953                 case MOUSEMOVE:
954                         if (BLI_rcti_isect_pt(&ar->winrct, event->x, event->y)) {
955                                 rcti rect;
956                                 int a;
957                                 
958                                 for (a = 0; a < data->items.totitem; a++) {
959                                         ui_searchbox_butrect(&rect, data, a);
960                                         if (BLI_rcti_isect_pt(&rect, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin)) {
961                                                 if (data->active != a) {
962                                                         data->active = a;
963                                                         ui_searchbox_select(C, ar, but, 0);
964                                                         break;
965                                                 }
966                                         }
967                                 }
968                         }
969                         break;
970         }
971 }
972
973 /* ar is the search box itself */
974 void ui_searchbox_update(bContext *C, ARegion *ar, uiBut *but, const bool reset)
975 {
976         uiSearchboxData *data = ar->regiondata;
977         
978         /* reset vars */
979         data->items.totitem = 0;
980         data->items.more = 0;
981         if (reset == false) {
982                 data->items.offset_i = data->items.offset;
983         }
984         else {
985                 data->items.offset_i = data->items.offset = 0;
986                 data->active = -1;
987                 
988                 /* handle active */
989                 if (but->search_func && but->func_arg2) {
990                         data->items.active = but->func_arg2;
991                         but->search_func(C, but->search_arg, but->editstr, &data->items);
992                         data->items.active = NULL;
993                         
994                         /* found active item, calculate real offset by centering it */
995                         if (data->items.totitem) {
996                                 /* first case, begin of list */
997                                 if (data->items.offset_i < data->items.maxitem) {
998                                         data->active = data->items.offset_i;
999                                         data->items.offset_i = 0;
1000                                 }
1001                                 else {
1002                                         /* second case, end of list */
1003                                         if (data->items.totitem - data->items.offset_i <= data->items.maxitem) {
1004                                                 data->active = data->items.offset_i - data->items.totitem + data->items.maxitem;
1005                                                 data->items.offset_i = data->items.totitem - data->items.maxitem;
1006                                         }
1007                                         else {
1008                                                 /* center active item */
1009                                                 data->items.offset_i -= data->items.maxitem / 2;
1010                                                 data->active = data->items.maxitem / 2;
1011                                         }
1012                                 }
1013                         }
1014                         data->items.offset = data->items.offset_i;
1015                         data->items.totitem = 0;
1016                 }
1017         }
1018         
1019         /* callback */
1020         if (but->search_func)
1021                 but->search_func(C, but->search_arg, but->editstr, &data->items);
1022         
1023         /* handle case where editstr is equal to one of items */
1024         if (reset && data->active == -1) {
1025                 int a;
1026                 
1027                 for (a = 0; a < data->items.totitem; a++) {
1028                         const char *name = data->items.names[a];
1029                         const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
1030                         if (STREQLEN(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen)) {
1031                                 data->active = a;
1032                                 break;
1033                         }
1034                 }
1035                 if (data->items.totitem == 1 && but->editstr[0])
1036                         data->active = 0;
1037         }
1038
1039         /* validate selected item */
1040         ui_searchbox_select(C, ar, but, 0);
1041         
1042         ED_region_tag_redraw(ar);
1043 }
1044
1045 int ui_searchbox_autocomplete(bContext *C, ARegion *ar, uiBut *but, char *str)
1046 {
1047         uiSearchboxData *data = ar->regiondata;
1048         int match = AUTOCOMPLETE_NO_MATCH;
1049
1050         if (str[0]) {
1051                 data->items.autocpl = UI_autocomplete_begin(str, ui_but_string_get_max_length(but));
1052
1053                 but->search_func(C, but->search_arg, but->editstr, &data->items);
1054
1055                 match = UI_autocomplete_end(data->items.autocpl, str);
1056                 data->items.autocpl = NULL;
1057         }
1058
1059         return match;
1060 }
1061
1062 static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
1063 {
1064         uiSearchboxData *data = ar->regiondata;
1065         
1066         /* pixel space */
1067         wmOrtho2_region_pixelspace(ar);
1068
1069         if (data->noback == false)
1070                 ui_draw_search_back(NULL, NULL, &data->bbox);  /* style not used yet */
1071         
1072         /* draw text */
1073         if (data->items.totitem) {
1074                 rcti rect;
1075                 int a;
1076                 
1077                 if (data->preview) {
1078                         /* draw items */
1079                         for (a = 0; a < data->items.totitem; a++) {
1080                                 ui_searchbox_butrect(&rect, data, a);
1081                                 
1082                                 /* widget itself */
1083                                 ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
1084                                                      (a == data->active) ? UI_ACTIVE : 0);
1085                         }
1086                         
1087                         /* indicate more */
1088                         if (data->items.more) {
1089                                 ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
1090                                 glEnable(GL_BLEND);
1091                                 UI_icon_draw(rect.xmax - 18, rect.ymin - 7, ICON_TRIA_DOWN);
1092                                 glDisable(GL_BLEND);
1093                         }
1094                         if (data->items.offset) {
1095                                 ui_searchbox_butrect(&rect, data, 0);
1096                                 glEnable(GL_BLEND);
1097                                 UI_icon_draw(rect.xmin, rect.ymax - 9, ICON_TRIA_UP);
1098                                 glDisable(GL_BLEND);
1099                         }
1100                         
1101                 }
1102                 else {
1103                         /* draw items */
1104                         for (a = 0; a < data->items.totitem; a++) {
1105                                 ui_searchbox_butrect(&rect, data, a);
1106                                 
1107                                 /* widget itself */
1108                                 ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
1109                                                   (a == data->active) ? UI_ACTIVE : 0, data->use_sep);
1110                                 
1111                         }
1112                         /* indicate more */
1113                         if (data->items.more) {
1114                                 ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
1115                                 glEnable(GL_BLEND);
1116                                 UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
1117                                 glDisable(GL_BLEND);
1118                         }
1119                         if (data->items.offset) {
1120                                 ui_searchbox_butrect(&rect, data, 0);
1121                                 glEnable(GL_BLEND);
1122                                 UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
1123                                 glDisable(GL_BLEND);
1124                         }
1125                 }
1126         }
1127 }
1128
1129 static void ui_searchbox_region_free_cb(ARegion *ar)
1130 {
1131         uiSearchboxData *data = ar->regiondata;
1132         int a;
1133
1134         /* free search data */
1135         for (a = 0; a < data->items.maxitem; a++) {
1136                 MEM_freeN(data->items.names[a]);
1137         }
1138         MEM_freeN(data->items.names);
1139         MEM_freeN(data->items.pointers);
1140         MEM_freeN(data->items.icons);
1141         
1142         MEM_freeN(data);
1143         ar->regiondata = NULL;
1144 }
1145
1146 ARegion *ui_searchbox_create_generic(bContext *C, ARegion *butregion, uiBut *but)
1147 {
1148         wmWindow *win = CTX_wm_window(C);
1149         uiStyle *style = UI_style_get();
1150         static ARegionType type;
1151         ARegion *ar;
1152         uiSearchboxData *data;
1153         float aspect = but->block->aspect;
1154         rctf rect_fl;
1155         rcti rect_i;
1156         const int margin = UI_POPUP_MARGIN;
1157         int winx /*, winy */, ofsx, ofsy;
1158         int i;
1159         
1160         /* create area region */
1161         ar = ui_region_temp_add(CTX_wm_screen(C));
1162         
1163         memset(&type, 0, sizeof(ARegionType));
1164         type.draw = ui_searchbox_region_draw_cb;
1165         type.free = ui_searchbox_region_free_cb;
1166         type.regionid = RGN_TYPE_TEMPORARY;
1167         ar->type = &type;
1168         
1169         /* create searchbox data */
1170         data = MEM_callocN(sizeof(uiSearchboxData), "uiSearchboxData");
1171
1172         /* set font, get bb */
1173         data->fstyle = style->widget; /* copy struct */
1174         data->fstyle.align = UI_STYLE_TEXT_CENTER;
1175         ui_fontscale(&data->fstyle.points, aspect);
1176         UI_fontstyle_set(&data->fstyle);
1177         
1178         ar->regiondata = data;
1179         
1180         /* special case, hardcoded feature, not draw backdrop when called from menus,
1181          * assume for design that popup already added it */
1182         if (but->block->flag & UI_BLOCK_SEARCH_MENU)
1183                 data->noback = true;
1184         
1185         if (but->a1 > 0 && but->a2 > 0) {
1186                 data->preview = true;
1187                 data->prv_rows = but->a1;
1188                 data->prv_cols = but->a2;
1189         }
1190
1191         /* only show key shortcuts when needed (not rna buttons) [#36699] */
1192         if (but->rnaprop == NULL) {
1193                 data->use_sep = true;
1194         }
1195         
1196         /* compute position */
1197         if (but->block->flag & UI_BLOCK_SEARCH_MENU) {
1198                 const int search_but_h = BLI_rctf_size_y(&but->rect) + 10;
1199                 /* this case is search menu inside other menu */
1200                 /* we copy region size */
1201
1202                 ar->winrct = butregion->winrct;
1203                 
1204                 /* widget rect, in region coords */
1205                 data->bbox.xmin = margin;
1206                 data->bbox.xmax = BLI_rcti_size_x(&ar->winrct) - margin;
1207                 data->bbox.ymin = margin;
1208                 data->bbox.ymax = BLI_rcti_size_y(&ar->winrct) - margin;
1209                 
1210                 /* check if button is lower half */
1211                 if (but->rect.ymax < BLI_rctf_cent_y(&but->block->rect)) {
1212                         data->bbox.ymin += search_but_h;
1213                 }
1214                 else {
1215                         data->bbox.ymax -= search_but_h;
1216                 }
1217         }
1218         else {
1219                 const int searchbox_width = UI_searchbox_size_x();
1220
1221                 rect_fl.xmin = but->rect.xmin - 5;   /* align text with button */
1222                 rect_fl.xmax = but->rect.xmax + 5;   /* symmetrical */
1223                 rect_fl.ymax = but->rect.ymin;
1224                 rect_fl.ymin = rect_fl.ymax - UI_searchbox_size_y();
1225
1226                 ofsx = (but->block->panel) ? but->block->panel->ofsx : 0;
1227                 ofsy = (but->block->panel) ? but->block->panel->ofsy : 0;
1228
1229                 BLI_rctf_translate(&rect_fl, ofsx, ofsy);
1230         
1231                 /* minimal width */
1232                 if (BLI_rctf_size_x(&rect_fl) < searchbox_width) {
1233                         rect_fl.xmax = rect_fl.xmin + searchbox_width;
1234                 }
1235                 
1236                 /* copy to int, gets projected if possible too */
1237                 BLI_rcti_rctf_copy(&rect_i, &rect_fl);
1238                 
1239                 if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
1240                         UI_view2d_view_to_region_rcti(&butregion->v2d, &rect_fl, &rect_i);
1241                 }
1242
1243                 BLI_rcti_translate(&rect_i, butregion->winrct.xmin, butregion->winrct.ymin);
1244
1245                 winx = WM_window_pixels_x(win);
1246                 // winy = WM_window_pixels_y(win);  /* UNUSED */
1247                 //wm_window_get_size(win, &winx, &winy);
1248                 
1249                 if (rect_i.xmax > winx) {
1250                         /* super size */
1251                         if (rect_i.xmax > winx + rect_i.xmin) {
1252                                 rect_i.xmax = winx;
1253                                 rect_i.xmin = 0;
1254                         }
1255                         else {
1256                                 rect_i.xmin -= rect_i.xmax - winx;
1257                                 rect_i.xmax = winx;
1258                         }
1259                 }
1260
1261                 if (rect_i.ymin < 0) {
1262                         int newy1 = but->rect.ymax + ofsy;
1263
1264                         if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax)
1265                                 newy1 = UI_view2d_view_to_region_y(&butregion->v2d, newy1);
1266
1267                         newy1 += butregion->winrct.ymin;
1268
1269                         rect_i.ymax = BLI_rcti_size_y(&rect_i) + newy1;
1270                         rect_i.ymin = newy1;
1271                 }
1272
1273                 /* widget rect, in region coords */
1274                 data->bbox.xmin = margin;
1275                 data->bbox.xmax = BLI_rcti_size_x(&rect_i) + margin;
1276                 data->bbox.ymin = margin;
1277                 data->bbox.ymax = BLI_rcti_size_y(&rect_i) + margin;
1278                 
1279                 /* region bigger for shadow */
1280                 ar->winrct.xmin = rect_i.xmin - margin;
1281                 ar->winrct.xmax = rect_i.xmax + margin;
1282                 ar->winrct.ymin = rect_i.ymin - margin;
1283                 ar->winrct.ymax = rect_i.ymax;
1284         }
1285         
1286         /* adds subwindow */
1287         ED_region_init(C, ar);
1288         
1289         /* notify change and redraw */
1290         ED_region_tag_redraw(ar);
1291         
1292         /* prepare search data */
1293         if (data->preview) {
1294                 data->items.maxitem = data->prv_rows * data->prv_cols;
1295         }
1296         else {
1297                 data->items.maxitem = SEARCH_ITEMS;
1298         }
1299         data->items.maxstrlen = but->hardmax;
1300         data->items.totitem = 0;
1301         data->items.names = MEM_callocN(data->items.maxitem * sizeof(void *), "search names");
1302         data->items.pointers = MEM_callocN(data->items.maxitem * sizeof(void *), "search pointers");
1303         data->items.icons = MEM_callocN(data->items.maxitem * sizeof(int), "search icons");
1304         for (i = 0; i < data->items.maxitem; i++)
1305                 data->items.names[i] = MEM_callocN(but->hardmax + 1, "search pointers");
1306         
1307         return ar;
1308 }
1309
1310 /**
1311  * Similar to Python's `str.title` except...
1312  *
1313  * - we know words are upper case and ascii only.
1314  * - '_' are replaces by spaces.
1315  */
1316 static void str_tolower_titlecaps_ascii(char *str, const size_t len)
1317 {
1318         size_t i;
1319         bool prev_delim = true;
1320
1321         for (i = 0; (i < len) && str[i]; i++) {
1322                 if (str[i] >= 'A' && str[i] <= 'Z') {
1323                         if (prev_delim == false) {
1324                                 str[i] += 'a' - 'A';
1325                         }
1326                 }
1327                 else if (str[i] == '_') {
1328                         str[i] = ' ';
1329                 }
1330
1331                 prev_delim = ELEM(str[i], ' ') || (str[i] >= '0' && str[i] <= '9');
1332         }
1333
1334 }
1335
1336 static void ui_searchbox_region_draw_cb__operator(const bContext *UNUSED(C), ARegion *ar)
1337 {
1338         uiSearchboxData *data = ar->regiondata;
1339
1340         /* pixel space */
1341         wmOrtho2_region_pixelspace(ar);
1342
1343         if (data->noback == false)
1344                 ui_draw_search_back(NULL, NULL, &data->bbox);  /* style not used yet */
1345
1346         /* draw text */
1347         if (data->items.totitem) {
1348                 rcti rect;
1349                 int a;
1350
1351                 /* draw items */
1352                 for (a = 0; a < data->items.totitem; a++) {
1353                         rcti rect_pre, rect_post;
1354                         ui_searchbox_butrect(&rect, data, a);
1355
1356                         rect_pre  = rect;
1357                         rect_post = rect;
1358
1359                         rect_pre.xmax = rect_post.xmin = rect.xmin + ((rect.xmax - rect.xmin) / 4);
1360
1361                         /* widget itself */
1362                         /* NOTE: i18n messages extracting tool does the same, please keep it in sync. */
1363                         {
1364                                 wmOperatorType *ot = data->items.pointers[a];
1365
1366                                 int state = (a == data->active) ? UI_ACTIVE : 0;
1367                                 char  text_pre[128];
1368                                 char *text_pre_p = strstr(ot->idname, "_OT_");
1369                                 if (text_pre_p == NULL) {
1370                                         text_pre[0] = '\0';
1371                                 }
1372                                 else {
1373                                         int text_pre_len;
1374                                         text_pre_p += 1;
1375                                         text_pre_len = BLI_strncpy_rlen(
1376                                                 text_pre, ot->idname, min_ii(sizeof(text_pre), text_pre_p - ot->idname));
1377                                         text_pre[text_pre_len] = ':';
1378                                         text_pre[text_pre_len + 1] = '\0';
1379                                         str_tolower_titlecaps_ascii(text_pre, sizeof(text_pre));
1380                                 }
1381
1382                                 rect_pre.xmax += 4;  /* sneaky, avoid showing ugly margin */
1383                                 ui_draw_menu_item(&data->fstyle, &rect_pre, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, text_pre),
1384                                                   data->items.icons[a], state, false);
1385                                 ui_draw_menu_item(&data->fstyle, &rect_post, data->items.names[a], 0, state, data->use_sep);
1386                         }
1387
1388                 }
1389                 /* indicate more */
1390                 if (data->items.more) {
1391                         ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
1392                         glEnable(GL_BLEND);
1393                         UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
1394                         glDisable(GL_BLEND);
1395                 }
1396                 if (data->items.offset) {
1397                         ui_searchbox_butrect(&rect, data, 0);
1398                         glEnable(GL_BLEND);
1399                         UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
1400                         glDisable(GL_BLEND);
1401                 }
1402         }
1403 }
1404
1405 ARegion *ui_searchbox_create_operator(bContext *C, ARegion *butregion, uiBut *but)
1406 {
1407         ARegion *ar;
1408
1409         ar = ui_searchbox_create_generic(C, butregion, but);
1410
1411         ar->type->draw = ui_searchbox_region_draw_cb__operator;
1412
1413         return ar;
1414 }
1415
1416 void ui_searchbox_free(bContext *C, ARegion *ar)
1417 {
1418         ui_region_temp_remove(C, CTX_wm_screen(C), ar);
1419 }
1420
1421 /* sets red alert if button holds a string it can't find */
1422 /* XXX weak: search_func adds all partial matches... */
1423 void ui_but_search_refresh(uiBut *but, const bool is_template_ID)
1424 {
1425         uiSearchItems *items;
1426         int x1;
1427
1428         /* possibly very large lists (such as ID datablocks),
1429          * only validate string and pointer RNA buts */
1430         if (but->rnaprop && !ELEM(RNA_property_type(but->rnaprop), PROP_STRING, PROP_POINTER)) {
1431                 return;
1432         }
1433
1434         items = MEM_callocN(sizeof(uiSearchItems), "search items");
1435
1436         /* setup search struct */
1437         items->maxitem = 10;
1438         items->maxstrlen = 256;
1439         items->names = MEM_callocN(items->maxitem * sizeof(void *), "search names");
1440         for (x1 = 0; x1 < items->maxitem; x1++)
1441                 items->names[x1] = MEM_callocN(but->hardmax + 1, "search names");
1442         
1443         but->search_func(but->block->evil_C, but->search_arg, but->drawstr, items);
1444         
1445         /* only redalert when we are sure of it, this can miss cases when >10 matches */
1446         if (items->totitem == 0) {
1447                 UI_but_flag_enable(but, UI_BUT_REDALERT);
1448         }
1449         else if (items->more == 0) {
1450                 const size_t offset = is_template_ID ? 3 : 0;
1451                 if (UI_search_items_find_index(items, but->drawstr, offset) == -1) {
1452                         UI_but_flag_enable(but, UI_BUT_REDALERT);
1453                 }
1454         }
1455         
1456         for (x1 = 0; x1 < items->maxitem; x1++) {
1457                 MEM_freeN(items->names[x1]);
1458         }
1459         MEM_freeN(items->names);
1460         MEM_freeN(items);
1461 }
1462
1463
1464 /************************* Creating Menu Blocks **********************/
1465
1466 /* position block relative to but, result is in window space */
1467 static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but, uiBlock *block)
1468 {
1469         uiBut *bt;
1470         uiSafetyRct *saferct;
1471         rctf butrct;
1472         /*float aspect;*/ /*UNUSED*/
1473         int xsize, ysize, xof = 0, yof = 0, center;
1474         short dir1 = 0, dir2 = 0;
1475         
1476         /* transform to window coordinates, using the source button region/block */
1477         ui_block_to_window_rctf(butregion, but->block, &butrct, &but->rect);
1478
1479         /* widget_roundbox_set has this correction too, keep in sync */
1480         if (but->type != UI_BTYPE_PULLDOWN) {
1481                 if (but->drawflag & UI_BUT_ALIGN_TOP)
1482                         butrct.ymax += U.pixelsize;
1483                 if (but->drawflag & UI_BUT_ALIGN_LEFT)
1484                         butrct.xmin -= U.pixelsize;
1485         }
1486         
1487         /* calc block rect */
1488         if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
1489                 if (block->buttons.first) {
1490                         BLI_rctf_init_minmax(&block->rect);
1491
1492                         for (bt = block->buttons.first; bt; bt = bt->next) {
1493                                 BLI_rctf_union(&block->rect, &bt->rect);
1494                         }
1495                 }
1496                 else {
1497                         /* we're nice and allow empty blocks too */
1498                         block->rect.xmin = block->rect.ymin = 0;
1499                         block->rect.xmax = block->rect.ymax = 20;
1500                 }
1501         }
1502                 
1503         /* aspect = (float)(BLI_rcti_size_x(&block->rect) + 4);*/ /*UNUSED*/
1504         ui_block_to_window_rctf(butregion, but->block, &block->rect, &block->rect);
1505
1506         //block->rect.xmin -= 2.0; block->rect.ymin -= 2.0;
1507         //block->rect.xmax += 2.0; block->rect.ymax += 2.0;
1508         
1509         xsize = BLI_rctf_size_x(&block->rect) + 0.2f * UI_UNIT_X;  /* 4 for shadow */
1510         ysize = BLI_rctf_size_y(&block->rect) + 0.2f * UI_UNIT_Y;
1511         /* aspect /= (float)xsize;*/ /*UNUSED*/
1512
1513         {
1514                 bool left = 0, right = 0, top = 0, down = 0;
1515                 int winx, winy;
1516                 // int offscreen;
1517
1518                 winx = WM_window_pixels_x(window);
1519                 winy = WM_window_pixels_y(window);
1520                 // wm_window_get_size(window, &winx, &winy);
1521
1522                 if (block->direction & UI_DIR_CENTER_Y) {
1523                         center = ysize / 2;
1524                 }
1525                 else {
1526                         center = 0;
1527                 }
1528                 
1529                 /* check if there's space at all */
1530                 if (butrct.xmin - xsize > 0.0f) left = 1;
1531                 if (butrct.xmax + xsize < winx) right = 1;
1532                 if (butrct.ymin - ysize + center > 0.0f) down = 1;
1533                 if (butrct.ymax + ysize - center < winy) top = 1;
1534
1535                 if (top == 0 && down == 0) {
1536                         if (butrct.ymin - ysize < winy - butrct.ymax - ysize)
1537                                 top = 1;
1538                         else
1539                                 down = 1;
1540                 }
1541                 
1542                 dir1 = (block->direction & UI_DIR_ALL);
1543
1544                 /* secundary directions */
1545                 if (dir1 & (UI_DIR_UP | UI_DIR_DOWN)) {
1546                         if      (dir1 & UI_DIR_LEFT)  dir2 = UI_DIR_LEFT;
1547                         else if (dir1 & UI_DIR_RIGHT) dir2 = UI_DIR_RIGHT;
1548                         dir1 &= (UI_DIR_UP | UI_DIR_DOWN);
1549                 }
1550
1551                 if ((dir2 == 0) && (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT)) dir2 = UI_DIR_DOWN;
1552                 if ((dir2 == 0) && (dir1 == UI_DIR_UP   || dir1 == UI_DIR_DOWN))  dir2 = UI_DIR_LEFT;
1553                 
1554                 /* no space at all? don't change */
1555                 if (left || right) {
1556                         if (dir1 == UI_DIR_LEFT  && left == 0)  dir1 = UI_DIR_RIGHT;
1557                         if (dir1 == UI_DIR_RIGHT && right == 0) dir1 = UI_DIR_LEFT;
1558                         /* this is aligning, not append! */
1559                         if (dir2 == UI_DIR_LEFT  && right == 0) dir2 = UI_DIR_RIGHT;
1560                         if (dir2 == UI_DIR_RIGHT && left == 0)  dir2 = UI_DIR_LEFT;
1561                 }
1562                 if (down || top) {
1563                         if (dir1 == UI_DIR_UP   && top == 0)  dir1 = UI_DIR_DOWN;
1564                         if (dir1 == UI_DIR_DOWN && down == 0) dir1 = UI_DIR_UP;
1565                         BLI_assert(dir2 != UI_DIR_UP);
1566 //                      if (dir2 == UI_DIR_UP   && top == 0)  dir2 = UI_DIR_DOWN;
1567                         if (dir2 == UI_DIR_DOWN && down == 0) dir2 = UI_DIR_UP;
1568                 }
1569
1570                 if (dir1 == UI_DIR_LEFT) {
1571                         xof = butrct.xmin - block->rect.xmax;
1572                         if (dir2 == UI_DIR_UP) yof = butrct.ymin - block->rect.ymin - center - MENU_PADDING;
1573                         else                   yof = butrct.ymax - block->rect.ymax + center + MENU_PADDING;
1574                 }
1575                 else if (dir1 == UI_DIR_RIGHT) {
1576                         xof = butrct.xmax - block->rect.xmin;
1577                         if (dir2 == UI_DIR_UP) yof = butrct.ymin - block->rect.ymin - center - MENU_PADDING;
1578                         else                   yof = butrct.ymax - block->rect.ymax + center + MENU_PADDING;
1579                 }
1580                 else if (dir1 == UI_DIR_UP) {
1581                         yof = butrct.ymax - block->rect.ymin;
1582                         if (dir2 == UI_DIR_RIGHT) xof = butrct.xmax - block->rect.xmax;
1583                         else                      xof = butrct.xmin - block->rect.xmin;
1584                         /* changed direction? */
1585                         if ((dir1 & block->direction) == 0) {
1586                                 UI_block_order_flip(block);
1587                         }
1588                 }
1589                 else if (dir1 == UI_DIR_DOWN) {
1590                         yof = butrct.ymin - block->rect.ymax;
1591                         if (dir2 == UI_DIR_RIGHT) xof = butrct.xmax - block->rect.xmax;
1592                         else                      xof = butrct.xmin - block->rect.xmin;
1593                         /* changed direction? */
1594                         if ((dir1 & block->direction) == 0) {
1595                                 UI_block_order_flip(block);
1596                         }
1597                 }
1598
1599                 /* and now we handle the exception; no space below or to top */
1600                 if (top == 0 && down == 0) {
1601                         if (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT) {
1602                                 /* align with bottom of screen */
1603                                 // yof = ysize; (not with menu scrolls)
1604                         }
1605                 }
1606
1607 #if 0 /* seems redundant and causes issues with blocks inside big regions */
1608                 /* or no space left or right */
1609                 if (left == 0 && right == 0) {
1610                         if (dir1 == UI_DIR_UP || dir1 == UI_DIR_DOWN) {
1611                                 /* align with left size of screen */
1612                                 xof = -block->rect.xmin + 5;
1613                         }
1614                 }
1615 #endif
1616
1617 #if 0
1618                 /* clamp to window bounds, could be made into an option if its ever annoying */
1619                 if (     (offscreen = (block->rect.ymin + yof)) < 0) yof -= offscreen;   /* bottom */
1620                 else if ((offscreen = (block->rect.ymax + yof) - winy) > 0) yof -= offscreen;  /* top */
1621                 if (     (offscreen = (block->rect.xmin + xof)) < 0) xof -= offscreen;   /* left */
1622                 else if ((offscreen = (block->rect.xmax + xof) - winx) > 0) xof -= offscreen;  /* right */
1623 #endif
1624         }
1625         
1626         /* apply offset, buttons in window coords */
1627         
1628         for (bt = block->buttons.first; bt; bt = bt->next) {
1629                 ui_block_to_window_rctf(butregion, but->block, &bt->rect, &bt->rect);
1630
1631                 BLI_rctf_translate(&bt->rect, xof, yof);
1632
1633                 /* ui_but_update recalculates drawstring size in pixels */
1634                 ui_but_update(bt);
1635         }
1636         
1637         BLI_rctf_translate(&block->rect, xof, yof);
1638
1639         /* safety calculus */
1640         {
1641                 const float midx = BLI_rctf_cent_x(&butrct);
1642                 const float midy = BLI_rctf_cent_y(&butrct);
1643                 
1644                 /* when you are outside parent button, safety there should be smaller */
1645                 
1646                 /* parent button to left */
1647                 if (midx < block->rect.xmin) block->safety.xmin = block->rect.xmin - 3;
1648                 else block->safety.xmin = block->rect.xmin - 40;
1649                 /* parent button to right */
1650                 if (midx > block->rect.xmax) block->safety.xmax = block->rect.xmax + 3;
1651                 else block->safety.xmax = block->rect.xmax + 40;
1652
1653                 /* parent button on bottom */
1654                 if (midy < block->rect.ymin) block->safety.ymin = block->rect.ymin - 3;
1655                 else block->safety.ymin = block->rect.ymin - 40;
1656                 /* parent button on top */
1657                 if (midy > block->rect.ymax) block->safety.ymax = block->rect.ymax + 3;
1658                 else block->safety.ymax = block->rect.ymax + 40;
1659
1660                 /* exception for switched pulldowns... */
1661                 if (dir1 && (dir1 & block->direction) == 0) {
1662                         if (dir2 == UI_DIR_RIGHT) block->safety.xmax = block->rect.xmax + 3;
1663                         if (dir2 == UI_DIR_LEFT)  block->safety.xmin = block->rect.xmin - 3;
1664                 }
1665                 block->direction = dir1;
1666         }
1667
1668         /* keep a list of these, needed for pulldown menus */
1669         saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1670         saferct->parent = butrct;
1671         saferct->safety = block->safety;
1672         BLI_freelistN(&block->saferct);
1673         BLI_duplicatelist(&block->saferct, &but->block->saferct);
1674         BLI_addhead(&block->saferct, saferct);
1675 }
1676
1677 static void ui_block_region_draw(const bContext *C, ARegion *ar)
1678 {
1679         uiBlock *block;
1680
1681         if (ar->do_draw & RGN_DRAW_REFRESH_UI) {
1682                 uiBlock *block_next;
1683                 ar->do_draw &= ~RGN_DRAW_REFRESH_UI;
1684                 for (block = ar->uiblocks.first; block; block = block_next) {
1685                         block_next = block->next;
1686                         if (block->handle->can_refresh) {
1687                                 ui_popup_block_refresh((bContext *)C, block->handle, NULL, NULL);
1688                         }
1689                 }
1690         }
1691
1692         for (block = ar->uiblocks.first; block; block = block->next)
1693                 UI_block_draw(C, block);
1694 }
1695
1696 /**
1697  * Use to refresh centered popups on screen resizing (for splash).
1698  */
1699 static void ui_block_region_popup_window_listener(
1700         bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, wmNotifier *wmn)
1701 {
1702         switch (wmn->category) {
1703                 case NC_WINDOW:
1704                 {
1705                         switch (wmn->action) {
1706                                 case NA_EDITED:
1707                                 {
1708                                         /* window resize */
1709                                         ED_region_tag_refresh_ui(ar);
1710                                         break;
1711                                 }
1712                         }
1713                         break;
1714                 }
1715         }
1716 }
1717
1718 static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
1719 {
1720         uiBut *bt;
1721         float xofs = 0.0f;
1722         int width = UI_SCREEN_MARGIN;
1723         int winx, winy;
1724
1725         if (block->flag & UI_BLOCK_NO_WIN_CLIP) {
1726                 return;
1727         }
1728
1729         winx = WM_window_pixels_x(window);
1730         winy = WM_window_pixels_y(window);
1731         
1732         /* shift menus to right if outside of view */
1733         if (block->rect.xmin < width) {
1734                 xofs = (width - block->rect.xmin);
1735                 block->rect.xmin += xofs;
1736                 block->rect.xmax += xofs;
1737         }
1738         /* or shift to left if outside of view */
1739         if (block->rect.xmax > winx - width) {
1740                 xofs = winx - width - block->rect.xmax;
1741                 block->rect.xmin += xofs;
1742                 block->rect.xmax += xofs;
1743         }
1744         
1745         if (block->rect.ymin < width)
1746                 block->rect.ymin = width;
1747         if (block->rect.ymax > winy - UI_POPUP_MENU_TOP)
1748                 block->rect.ymax = winy - UI_POPUP_MENU_TOP;
1749         
1750         /* ensure menu items draw inside left/right boundary */
1751         for (bt = block->buttons.first; bt; bt = bt->next) {
1752                 bt->rect.xmin += xofs;
1753                 bt->rect.xmax += xofs;
1754         }
1755
1756 }
1757
1758 void ui_popup_block_scrolltest(uiBlock *block)
1759 {
1760         uiBut *bt;
1761         
1762         block->flag &= ~(UI_BLOCK_CLIPBOTTOM | UI_BLOCK_CLIPTOP);
1763         
1764         for (bt = block->buttons.first; bt; bt = bt->next)
1765                 bt->flag &= ~UI_SCROLLED;
1766         
1767         if (block->buttons.first == block->buttons.last)
1768                 return;
1769         
1770         /* mark buttons that are outside boundary */
1771         for (bt = block->buttons.first; bt; bt = bt->next) {
1772                 if (bt->rect.ymin < block->rect.ymin) {
1773                         bt->flag |= UI_SCROLLED;
1774                         block->flag |= UI_BLOCK_CLIPBOTTOM;
1775                 }
1776                 if (bt->rect.ymax > block->rect.ymax) {
1777                         bt->flag |= UI_SCROLLED;
1778                         block->flag |= UI_BLOCK_CLIPTOP;
1779                 }
1780         }
1781
1782         /* mark buttons overlapping arrows, if we have them */
1783         for (bt = block->buttons.first; bt; bt = bt->next) {
1784                 if (block->flag & UI_BLOCK_CLIPBOTTOM) {
1785                         if (bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
1786                                 bt->flag |= UI_SCROLLED;
1787                 }
1788                 if (block->flag & UI_BLOCK_CLIPTOP) {
1789                         if (bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
1790                                 bt->flag |= UI_SCROLLED;
1791                 }
1792         }
1793 }
1794
1795 static void ui_popup_block_remove(bContext *C, uiPopupBlockHandle *handle)
1796 {
1797         wmWindow *win = CTX_wm_window(C);
1798         bScreen *sc = CTX_wm_screen(C);
1799
1800         ui_region_temp_remove(C, sc, handle->region);
1801
1802         /* reset to region cursor (only if there's not another menu open) */
1803         if (BLI_listbase_is_empty(&sc->regionbase)) {
1804                 ED_region_cursor_set(win, CTX_wm_area(C), CTX_wm_region(C));
1805                 /* in case cursor needs to be changed again */
1806                 WM_event_add_mousemove(C);
1807         }
1808
1809         if (handle->scrolltimer)
1810                 WM_event_remove_timer(CTX_wm_manager(C), win, handle->scrolltimer);
1811 }
1812
1813 /**
1814  * Called for creating new popups and refreshing existing ones.
1815  */
1816 uiBlock *ui_popup_block_refresh(
1817         bContext *C, uiPopupBlockHandle *handle,
1818         ARegion *butregion, uiBut *but)
1819 {
1820         BLI_assert(handle->can_refresh == true);
1821
1822         const int margin = UI_POPUP_MARGIN;
1823         wmWindow *window = CTX_wm_window(C);
1824         ARegion *ar = handle->region;
1825
1826         uiBlockCreateFunc create_func = handle->popup_create_vars.create_func;
1827         uiBlockHandleCreateFunc handle_create_func = handle->popup_create_vars.handle_create_func;
1828         void *arg = handle->popup_create_vars.arg;
1829
1830         uiBlock *block_old = ar->uiblocks.first;
1831         uiBlock *block;
1832
1833 #ifdef DEBUG
1834         wmEvent *event_back = window->eventstate;
1835 #endif
1836
1837         /* create ui block */
1838         if (create_func)
1839                 block = create_func(C, ar, arg);
1840         else
1841                 block = handle_create_func(C, handle, arg);
1842         
1843         /* callbacks _must_ leave this for us, otherwise we can't call UI_block_update_from_old */
1844         BLI_assert(!block->endblock);
1845
1846         /* ensure we don't use mouse coords here! */
1847 #ifdef DEBUG
1848         window->eventstate = NULL;
1849 #endif
1850
1851         if (block->handle) {
1852                 memcpy(block->handle, handle, sizeof(uiPopupBlockHandle));
1853                 MEM_freeN(handle);
1854                 handle = block->handle;
1855         }
1856         else
1857                 block->handle = handle;
1858
1859         ar->regiondata = handle;
1860
1861         /* set UI_BLOCK_NUMSELECT before UI_block_end() so we get alphanumeric keys assigned */
1862         if (but == NULL) {
1863                 block->flag |= UI_BLOCK_POPUP;
1864         }
1865
1866         block->flag |= UI_BLOCK_LOOP;
1867
1868         /* defer this until blocks are translated (below) */
1869         block->oldblock = NULL;
1870
1871         if (!block->endblock)
1872                 UI_block_end_ex(C, block, handle->popup_create_vars.event_xy);
1873
1874         /* if this is being created from a button */
1875         if (but) {
1876                 block->aspect = but->block->aspect;
1877                 ui_block_position(window, butregion, but, block);
1878                 handle->direction = block->direction;
1879         }
1880         else {
1881                 uiSafetyRct *saferct;
1882                 /* keep a list of these, needed for pulldown menus */
1883                 saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1884                 saferct->safety = block->safety;
1885                 BLI_addhead(&block->saferct, saferct);
1886         }
1887
1888         if (block->flag & UI_BLOCK_RADIAL) {
1889                 int win_width = UI_SCREEN_MARGIN;
1890                 int winx, winy;
1891
1892                 int x_offset = 0, y_offset = 0;
1893
1894                 winx = WM_window_pixels_x(window);
1895                 winy = WM_window_pixels_y(window);
1896
1897                 copy_v2_v2(block->pie_data.pie_center_init, block->pie_data.pie_center_spawned);
1898
1899                 /* only try translation if area is large enough */
1900                 if (BLI_rctf_size_x(&block->rect) < winx - (2.0f * win_width)) {
1901                         if (block->rect.xmin < win_width )   x_offset += win_width - block->rect.xmin;
1902                         if (block->rect.xmax > winx - win_width) x_offset += winx - win_width - block->rect.xmax;
1903                 }
1904
1905                 if (BLI_rctf_size_y(&block->rect) < winy - (2.0f * win_width)) {
1906                         if (block->rect.ymin < win_width )   y_offset += win_width - block->rect.ymin;
1907                         if (block->rect.ymax > winy - win_width) y_offset += winy - win_width - block->rect.ymax;
1908                 }
1909                 /* if we are offsetting set up initial data for timeout functionality */
1910
1911                 if ((x_offset != 0) || (y_offset != 0)) {
1912                         block->pie_data.pie_center_spawned[0] += x_offset;
1913                         block->pie_data.pie_center_spawned[1] += y_offset;
1914
1915                         ui_block_translate(block, x_offset, y_offset);
1916
1917                         if (U.pie_initial_timeout > 0)
1918                                 block->pie_data.flags |= UI_PIE_INITIAL_DIRECTION;
1919                 }
1920
1921                 ar->winrct.xmin = 0;
1922                 ar->winrct.xmax = winx;
1923                 ar->winrct.ymin = 0;
1924                 ar->winrct.ymax = winy;
1925
1926                 ui_block_calc_pie_segment(block, block->pie_data.pie_center_init);
1927
1928                 /* lastly set the buttons at the center of the pie menu, ready for animation */
1929                 if (U.pie_animation_timeout > 0) {
1930                         for (uiBut *but_iter = block->buttons.first; but_iter; but_iter = but_iter->next) {
1931                                 if (but_iter->pie_dir != UI_RADIAL_NONE) {
1932                                         BLI_rctf_recenter(&but_iter->rect, UNPACK2(block->pie_data.pie_center_spawned));
1933                                 }
1934                         }
1935                 }
1936         }
1937         else {
1938                 /* clip block with window boundary */
1939                 ui_popup_block_clip(window, block);
1940                 /* the block and buttons were positioned in window space as in 2.4x, now
1941                  * these menu blocks are regions so we bring it back to region space.
1942                  * additionally we add some padding for the menu shadow or rounded menus */
1943                 ar->winrct.xmin = block->rect.xmin - margin;
1944                 ar->winrct.xmax = block->rect.xmax + margin;
1945                 ar->winrct.ymin = block->rect.ymin - margin;
1946                 ar->winrct.ymax = block->rect.ymax + UI_POPUP_MENU_TOP;
1947
1948                 ui_block_translate(block, -ar->winrct.xmin, -ar->winrct.ymin);
1949         }
1950
1951         if (block_old) {
1952                 block->oldblock = block_old;
1953                 UI_block_update_from_old(C, block);
1954                 UI_blocklist_free_inactive(C, &ar->uiblocks);
1955         }
1956
1957         /* checks which buttons are visible, sets flags to prevent draw (do after region init) */
1958         ui_popup_block_scrolltest(block);
1959         
1960         /* adds subwindow */
1961         ED_region_init(C, ar);
1962
1963         /* get winmat now that we actually have the subwindow */
1964         wmSubWindowSet(window, ar->swinid);
1965         
1966         wm_subwindow_matrix_get(window, ar->swinid, block->winmat);
1967         
1968         /* notify change and redraw */
1969         ED_region_tag_redraw(ar);
1970
1971         ED_region_update_rect(C, ar);
1972
1973 #ifdef DEBUG
1974         window->eventstate = event_back;
1975 #endif
1976
1977         return block;
1978 }
1979
1980 uiPopupBlockHandle *ui_popup_block_create(
1981         bContext *C, ARegion *butregion, uiBut *but,
1982         uiBlockCreateFunc create_func, uiBlockHandleCreateFunc handle_create_func,
1983         void *arg)
1984 {
1985         wmWindow *window = CTX_wm_window(C);
1986         uiBut *activebut = UI_context_active_but_get(C);
1987         static ARegionType type;
1988         ARegion *ar;
1989         uiBlock *block;
1990         uiPopupBlockHandle *handle;
1991
1992         /* disable tooltips from buttons below */
1993         if (activebut) {
1994                 UI_but_tooltip_timer_remove(C, activebut);
1995         }
1996         /* standard cursor by default */
1997         WM_cursor_set(window, CURSOR_STD);
1998
1999         /* create handle */
2000         handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
2001
2002         /* store context for operator */
2003         handle->ctx_area = CTX_wm_area(C);
2004         handle->ctx_region = CTX_wm_region(C);
2005
2006         /* store vars to refresh popup (RGN_DRAW_REFRESH_UI) */
2007         handle->popup_create_vars.create_func = create_func;
2008         handle->popup_create_vars.handle_create_func = handle_create_func;
2009         handle->popup_create_vars.arg = arg;
2010         handle->popup_create_vars.butregion = but ? butregion : NULL;
2011         copy_v2_v2_int(handle->popup_create_vars.event_xy, &window->eventstate->x);
2012         /* caller may free vars used to create this popup, in that case this variable should be disabled. */
2013         handle->can_refresh = true;
2014
2015         /* create area region */
2016         ar = ui_region_temp_add(CTX_wm_screen(C));
2017         handle->region = ar;
2018
2019         memset(&type, 0, sizeof(ARegionType));
2020         type.draw = ui_block_region_draw;
2021         type.regionid = RGN_TYPE_TEMPORARY;
2022         ar->type = &type;
2023
2024         UI_region_handlers_add(&ar->handlers);
2025
2026         block = ui_popup_block_refresh(C, handle, butregion, but);
2027         handle = block->handle;
2028
2029         /* keep centered on window resizing */
2030         if ((block->bounds_type == UI_BLOCK_BOUNDS_POPUP_CENTER) && handle->can_refresh) {
2031                 type.listener = ui_block_region_popup_window_listener;
2032         }
2033
2034         return handle;
2035 }
2036
2037 void ui_popup_block_free(bContext *C, uiPopupBlockHandle *handle)
2038 {
2039         ui_popup_block_remove(C, handle);
2040         
2041         MEM_freeN(handle);
2042 }
2043
2044 /***************************** Menu Button ***************************/
2045
2046 #if 0
2047 static void ui_warp_pointer(int x, int y)
2048 {
2049         /* XXX 2.50 which function to use for this? */
2050         /* OSX has very poor mouse-warp support, it sends events;
2051          * this causes a menu being pressed immediately ... */
2052 #  ifndef __APPLE__
2053         warp_pointer(x, y);
2054 #  endif
2055 }
2056 #endif
2057
2058 /********************* Color Button ****************/
2059
2060 /* for picker, while editing hsv */
2061 void ui_but_hsv_set(uiBut *but)
2062 {
2063         float col[3];
2064         ColorPicker *cpicker = but->custom_data;
2065         float *hsv = cpicker->color_data;
2066
2067         ui_color_picker_to_rgb_v(hsv, col);
2068
2069         ui_but_v3_set(but, col);
2070 }
2071
2072 /* Updates all buttons who share the same color picker as the one passed
2073  * also used by small picker, be careful with name checks below... */
2074 static void ui_update_color_picker_buts_rgb(uiBlock *block, ColorPicker *cpicker, const float rgb[3], bool is_display_space)
2075 {
2076         uiBut *bt;
2077         float *hsv = cpicker->color_data;
2078         struct ColorManagedDisplay *display = NULL;
2079         /* this is to keep the H and S value when V is equal to zero
2080          * and we are working in HSV mode, of course!
2081          */
2082         if (is_display_space) {
2083                 ui_rgb_to_color_picker_compat_v(rgb, hsv);
2084         }
2085         else {
2086                 /* we need to convert to display space to use hsv, because hsv is stored in display space */
2087                 float rgb_display[3];
2088
2089                 copy_v3_v3(rgb_display, rgb);
2090                 ui_block_cm_to_display_space_v3(block, rgb_display);
2091                 ui_rgb_to_color_picker_compat_v(rgb_display, hsv);
2092         }
2093
2094         if (block->color_profile)
2095                 display = ui_block_cm_display_get(block);
2096         
2097         /* this updates button strings, is hackish... but button pointers are on stack of caller function */
2098         for (bt = block->buttons.first; bt; bt = bt->next) {
2099                 if (bt->custom_data != cpicker)
2100                         continue;
2101
2102                 if (bt->rnaprop) {
2103                         
2104                         ui_but_v3_set(bt, rgb);
2105                         
2106                 }
2107                 else if (STREQ(bt->str, "Hex: ")) {
2108                         float rgb_gamma[3];
2109                         unsigned char rgb_gamma_uchar[3];
2110                         double intpart;
2111                         char col[16];
2112                         
2113                         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
2114                         
2115                         copy_v3_v3(rgb_gamma, rgb);
2116
2117                         if (display) {
2118                                 /* make a display version, for Hex code */
2119                                 IMB_colormanagement_scene_linear_to_display_v3(rgb_gamma, display);
2120                         }
2121                         
2122                         if (rgb_gamma[0] > 1.0f) rgb_gamma[0] = modf(rgb_gamma[0], &intpart);
2123                         if (rgb_gamma[1] > 1.0f) rgb_gamma[1] = modf(rgb_gamma[1], &intpart);
2124                         if (rgb_gamma[2] > 1.0f) rgb_gamma[2] = modf(rgb_gamma[2], &intpart);
2125
2126                         rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
2127                         BLI_snprintf(col, sizeof(col), "%02X%02X%02X", UNPACK3_EX((unsigned int), rgb_gamma_uchar, ));
2128                         
2129                         strcpy(bt->poin, col);
2130                 }
2131                 else if (bt->str[1] == ' ') {
2132                         if (bt->str[0] == 'R') {
2133                                 ui_but_value_set(bt, rgb[0]);
2134                         }
2135                         else if (bt->str[0] == 'G') {
2136                                 ui_but_value_set(bt, rgb[1]);
2137                         }
2138                         else if (bt->str[0] == 'B') {
2139                                 ui_but_value_set(bt, rgb[2]);
2140                         }
2141                         else if (bt->str[0] == 'H') {
2142                                 ui_but_value_set(bt, hsv[0]);
2143                         }
2144                         else if (bt->str[0] == 'S') {
2145                                 ui_but_value_set(bt, hsv[1]);
2146                         }
2147                         else if (bt->str[0] == 'V') {
2148                                 ui_but_value_set(bt, hsv[2]);
2149                         }
2150                         else if (bt->str[0] == 'L') {
2151                                 ui_but_value_set(bt, hsv[2]);
2152                         }
2153                 }
2154
2155                 ui_but_update(bt);
2156         }
2157 }
2158
2159 static void ui_colorpicker_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2160 {
2161         uiBut *but = (uiBut *)bt1;
2162         uiPopupBlockHandle *popup = but->block->handle;
2163         PropertyRNA *prop = but->rnaprop;
2164         PointerRNA ptr = but->rnapoin;
2165         float rgb[4];
2166         
2167         if (prop) {
2168                 RNA_property_float_get_array(&ptr, prop, rgb);
2169                 ui_update_color_picker_buts_rgb(but->block, but->custom_data, rgb, (RNA_property_subtype(prop) == PROP_COLOR_GAMMA));
2170         }
2171         
2172         if (popup)
2173                 popup->menuretval = UI_RETURN_UPDATE;
2174 }
2175
2176 static void ui_color_wheel_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2177 {
2178         uiBut *but = (uiBut *)bt1;
2179         uiPopupBlockHandle *popup = but->block->handle;
2180         float rgb[3];
2181         ColorPicker *cpicker = but->custom_data;
2182         float *hsv = cpicker->color_data;
2183         bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
2184
2185         ui_color_picker_to_rgb_v(hsv, rgb);
2186
2187         /* hsv is saved in display space so convert back */
2188         if (use_display_colorspace) {
2189                 ui_block_cm_to_scene_linear_v3(but->block, rgb);
2190         }
2191
2192         ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, !use_display_colorspace);
2193         
2194         if (popup)
2195                 popup->menuretval = UI_RETURN_UPDATE;
2196 }
2197
2198 static void ui_colorpicker_hex_rna_cb(bContext *UNUSED(C), void *bt1, void *hexcl)
2199 {
2200         uiBut *but = (uiBut *)bt1;
2201         uiPopupBlockHandle *popup = but->block->handle;
2202         ColorPicker *cpicker = but->custom_data;
2203         char *hexcol = (char *)hexcl;
2204         float rgb[3];
2205         
2206         hex_to_rgb(hexcol, rgb, rgb + 1, rgb + 2);
2207         
2208         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
2209         if (but->block->color_profile) {
2210                 /* so we need to linearise it for Blender */
2211                 ui_block_cm_to_scene_linear_v3(but->block, rgb);
2212         }
2213         
2214         ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, false);
2215         
2216         if (popup)
2217                 popup->menuretval = UI_RETURN_UPDATE;
2218 }
2219
2220 static void ui_popup_close_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2221 {
2222         uiBut *but = (uiBut *)bt1;
2223         uiPopupBlockHandle *popup = but->block->handle;
2224         
2225         if (popup)
2226                 popup->menuretval = UI_RETURN_OK;
2227 }
2228
2229 static void ui_colorpicker_hide_reveal(uiBlock *block, short colormode)
2230 {
2231         uiBut *bt;
2232         
2233         /* tag buttons */
2234         for (bt = block->buttons.first; bt; bt = bt->next) {
2235                 if ((bt->func == ui_colorpicker_rna_cb) && bt->type == UI_BTYPE_NUM_SLIDER && bt->rnaindex != 3) {
2236                         /* RGB sliders (color circle and alpha are always shown) */
2237                         if (colormode == 0) bt->flag &= ~UI_HIDDEN;
2238                         else bt->flag |= UI_HIDDEN;
2239                 }
2240                 else if (bt->func == ui_color_wheel_rna_cb) {
2241                         /* HSV sliders */
2242                         if (colormode == 1) bt->flag &= ~UI_HIDDEN;
2243                         else bt->flag |= UI_HIDDEN;
2244                 }
2245                 else if (bt->func == ui_colorpicker_hex_rna_cb || bt->type == UI_BTYPE_LABEL) {
2246                         /* hex input or gamma correction status label */
2247                         if (colormode == 2) bt->flag &= ~UI_HIDDEN;
2248                         else bt->flag |= UI_HIDDEN;
2249                 }
2250         }
2251 }
2252
2253 static void ui_colorpicker_create_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2254 {
2255         uiBut *bt = bt1;
2256         short colormode = ui_but_value_get(bt);
2257         ui_colorpicker_hide_reveal(bt->block, colormode);
2258 }
2259
2260 #define PICKER_H    (7.5f * U.widget_unit)
2261 #define PICKER_W    (7.5f * U.widget_unit)
2262 #define PICKER_SPACE    (0.3f * U.widget_unit)
2263 #define PICKER_BAR      (0.7f * U.widget_unit)
2264
2265 #define PICKER_TOTAL_W  (PICKER_W + PICKER_SPACE + PICKER_BAR)
2266
2267 static void ui_colorpicker_circle(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, ColorPicker *cpicker)
2268 {
2269         uiBut *bt;
2270         
2271         /* HS circle */
2272         bt = uiDefButR_prop(block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, PICKER_H, PICKER_W, ptr, prop, -1, 0.0, 0.0, 0.0, 0, TIP_("Color"));
2273         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2274         bt->custom_data = cpicker;
2275
2276         /* value */
2277         if (U.color_picker_type == USER_CP_CIRCLE_HSL) {
2278                 bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H, ptr, prop, -1, 0.0, 0.0, UI_GRAD_L_ALT, 0, "Lightness");
2279                 UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2280         }
2281         else {
2282                 bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H, ptr, prop, -1, 0.0, 0.0, UI_GRAD_V_ALT, 0, TIP_("Value"));
2283                 UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2284         }
2285         bt->custom_data = cpicker;
2286 }
2287
2288
2289 static void ui_colorpicker_square(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int type, ColorPicker *cpicker)
2290 {
2291         uiBut *bt;
2292         int bartype = type + 3;
2293         
2294         /* HS square */
2295         bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "",   0, PICKER_BAR + PICKER_SPACE, PICKER_TOTAL_W, PICKER_H, ptr, prop, -1, 0.0, 0.0, type, 0, TIP_("Color"));
2296         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2297         bt->custom_data = cpicker;
2298         
2299         /* value */
2300         bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "",       0, 0, PICKER_TOTAL_W, PICKER_BAR, ptr, prop, -1, 0.0, 0.0, bartype, 0, TIP_("Value"));
2301         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2302         bt->custom_data = cpicker;
2303 }
2304
2305
2306 /* a HS circle, V slider, rgb/hsv/hex sliders */
2307 static void ui_block_colorpicker(uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop, bool show_picker)
2308 {
2309         static short colormode = 0;  /* temp? 0=rgb, 1=hsv, 2=hex */
2310         uiBut *bt;
2311         int width, butwidth;
2312         static char tip[50];
2313         static char hexcol[128];
2314         float rgb_gamma[3];
2315         unsigned char rgb_gamma_uchar[3];
2316         float softmin, softmax, hardmin, hardmax, step, precision;
2317         int yco;
2318         ColorPicker *cpicker = ui_block_colorpicker_create(block);
2319         float *hsv = cpicker->color_data;
2320                 
2321         width = PICKER_TOTAL_W;
2322         butwidth = width - 1.5f * UI_UNIT_X;
2323         
2324         /* existence of profile means storage is in linear color space, with display correction */
2325         /* XXX That tip message is not use anywhere! */
2326         if (!block->color_profile) {
2327                 BLI_strncpy(tip, N_("Value in Display Color Space"), sizeof(tip));
2328                 copy_v3_v3(rgb_gamma, rgba);
2329         }
2330         else {
2331                 BLI_strncpy(tip, N_("Value in Linear RGB Color Space"), sizeof(tip));
2332
2333                 /* make a display version, for Hex code */
2334                 copy_v3_v3(rgb_gamma, rgba);
2335                 ui_block_cm_to_display_space_v3(block, rgb_gamma);
2336         }
2337         
2338         /* sneaky way to check for alpha */
2339         rgba[3] = FLT_MAX;
2340
2341         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2342         RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
2343         RNA_property_float_get_array(ptr, prop, rgba);
2344
2345         /* when the softmax isn't defined in the RNA,
2346          * using very large numbers causes sRGB/linear round trip to fail. */
2347         if (softmax == FLT_MAX) {
2348                 softmax = 1.0f;
2349         }
2350
2351         switch (U.color_picker_type) {
2352                 case USER_CP_SQUARE_SV:
2353                         ui_colorpicker_square(block, ptr, prop, UI_GRAD_SV, cpicker);
2354                         break;
2355                 case USER_CP_SQUARE_HS:
2356                         ui_colorpicker_square(block, ptr, prop, UI_GRAD_HS, cpicker);
2357                         break;
2358                 case USER_CP_SQUARE_HV:
2359                         ui_colorpicker_square(block, ptr, prop, UI_GRAD_HV, cpicker);
2360                         break;
2361
2362                 /* user default */
2363                 case USER_CP_CIRCLE_HSV:
2364                 case USER_CP_CIRCLE_HSL:
2365                 default:
2366                         ui_colorpicker_circle(block, ptr, prop, cpicker);
2367                         break;
2368         }
2369         
2370         /* mode */
2371         yco = -1.5f * UI_UNIT_Y;
2372         UI_block_align_begin(block);
2373         bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("RGB"), 0, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 0.0, 0, 0, "");
2374         UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
2375         bt->custom_data = cpicker;
2376         if (U.color_picker_type == USER_CP_CIRCLE_HSL)
2377                 bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("HSL"), width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
2378         else
2379                 bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("HSV"), width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
2380         UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
2381         bt->custom_data = cpicker;
2382         bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("Hex"), 2 * width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 2.0, 0, 0, "");
2383         UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
2384         bt->custom_data = cpicker;
2385         UI_block_align_end(block);
2386
2387         yco = -3.0f * UI_UNIT_Y;
2388         if (show_picker) {
2389                 bt = uiDefIconButO(block, UI_BTYPE_BUT, "UI_OT_eyedropper_color", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth + 10, yco, UI_UNIT_X, UI_UNIT_Y, NULL);
2390                 UI_but_func_set(bt, ui_popup_close_cb, bt, NULL);
2391                 bt->custom_data = cpicker;
2392         }
2393         
2394         /* RGB values */
2395         UI_block_align_begin(block);
2396         bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("R:"),  0, yco, butwidth, UI_UNIT_Y, ptr, prop, 0, 0.0, 0.0, 0, 3, TIP_("Red"));
2397         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2398         bt->custom_data = cpicker;
2399         bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("G:"),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 1, 0.0, 0.0, 0, 3, TIP_("Green"));
2400         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2401         bt->custom_data = cpicker;
2402         bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("B:"),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 2, 0.0, 0.0, 0, 3, TIP_("Blue"));
2403         UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2404         bt->custom_data = cpicker;
2405
2406         /* could use uiItemFullR(col, ptr, prop, -1, 0, UI_ITEM_R_EXPAND|UI_ITEM_R_SLIDER, "", ICON_NONE);
2407          * but need to use UI_but_func_set for updating other fake buttons */
2408         
2409         /* HSV values */
2410         yco = -3.0f * UI_UNIT_Y;
2411         UI_block_align_begin(block);
2412         bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("H:"),   0, yco, butwidth, UI_UNIT_Y, hsv, 0.0, 1.0, 10, 3, TIP_("Hue"));
2413         UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
2414         bt->custom_data = cpicker;
2415         bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("S:"),   0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 1, 0.0, 1.0, 10, 3, TIP_("Saturation"));
2416         UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
2417         bt->custom_data = cpicker;
2418         if (U.color_picker_type == USER_CP_CIRCLE_HSL)
2419                 bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("L:"),   0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 2, 0.0, 1.0, 10, 3, TIP_("Lightness"));
2420         else
2421                 bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("V:"),   0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 2, 0.0, softmax, 10, 3, TIP_("Value"));
2422
2423         bt->hardmax = hardmax;  /* not common but rgb  may be over 1.0 */
2424         UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
2425         bt->custom_data = cpicker;
2426
2427         UI_block_align_end(block);
2428
2429         if (rgba[3] != FLT_MAX) {
2430                 bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("A: "),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 3, 0.0, 0.0, 0, 3, TIP_("Alpha"));
2431                 UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
2432                 bt->custom_data = cpicker;
2433         }
2434         else {
2435                 rgba[3] = 1.0f;
2436         }
2437
2438         rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
2439         BLI_snprintf(hexcol, sizeof(hexcol), "%02X%02X%02X", UNPACK3_EX((unsigned int), rgb_gamma_uchar, ));
2440
2441         yco = -3.0f * UI_UNIT_Y;
2442         bt = uiDefBut(block, UI_BTYPE_TEXT, 0, IFACE_("Hex: "), 0, yco, butwidth, UI_UNIT_Y, hexcol, 0, 7, 0, 0, TIP_("Hex triplet for color (#RRGGBB)"));
2443         UI_but_func_set(bt, ui_colorpicker_hex_rna_cb, bt, hexcol);
2444         bt->custom_data = cpicker;
2445         uiDefBut(block, UI_BTYPE_LABEL, 0, IFACE_("(Gamma Corrected)"), 0, yco - UI_UNIT_Y, butwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2446
2447         ui_rgb_to_color_picker_v(rgb_gamma, hsv);
2448
2449         ui_colorpicker_hide_reveal(block, colormode);
2450 }
2451
2452
2453 static int ui_colorpicker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *block, const wmEvent *event)
2454 {
2455         float add = 0.0f;
2456         
2457         if (event->type == WHEELUPMOUSE)
2458                 add = 0.05f;
2459         else if (event->type == WHEELDOWNMOUSE)
2460                 add = -0.05f;
2461         
2462         if (add != 0.0f) {
2463                 uiBut *but;
2464                 
2465                 for (but = block->buttons.first; but; but = but->next) {
2466                         if (but->type == UI_BTYPE_HSVCUBE && but->active == NULL) {
2467                                 uiPopupBlockHandle *popup = block->handle;
2468                                 float rgb[3];
2469                                 ColorPicker *cpicker = but->custom_data;
2470                                 float *hsv = cpicker->color_data;
2471                                 bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
2472                                 
2473                                 ui_but_v3_get(but, rgb);
2474
2475                                 if (use_display_colorspace)
2476                                         ui_block_cm_to_display_space_v3(block, rgb);
2477
2478                                 ui_rgb_to_color_picker_compat_v(rgb, hsv);
2479
2480                                 hsv[2] = CLAMPIS(hsv[2] + add, 0.0f, 1.0f);
2481                                 ui_color_picker_to_rgb_v(hsv, rgb);
2482
2483                                 if (use_display_colorspace)
2484                                         ui_block_cm_to_scene_linear_v3(block, rgb);
2485
2486                                 ui_but_v3_set(but, rgb);
2487                                 
2488                                 ui_update_color_picker_buts_rgb(block, cpicker, rgb, !use_display_colorspace);
2489                                 if (popup)
2490                                         popup->menuretval = UI_RETURN_UPDATE;
2491                                 
2492                                 return 1;
2493                         }
2494                 }
2495         }
2496         return 0;
2497 }
2498
2499 uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_but)
2500 {
2501         uiBut *but = arg_but;
2502         uiBlock *block;
2503         bool show_picker = true;
2504         
2505         block = UI_block_begin(C, handle->region, __func__, UI_EMBOSS);
2506         
2507         if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
2508                 block->color_profile = false;
2509         }
2510
2511         if (but->block) {
2512                 /* if color block is invoked from a popup we wouldn't be able to set color properly
2513                  * this is because color picker will close popups first and then will try to figure
2514                  * out active button RNA, and of course it'll fail
2515                  */
2516                 show_picker = (but->block->flag & UI_BLOCK_POPUP) == 0;
2517         }
2518         
2519         copy_v3_v3(handle->retvec, but->editvec);
2520         
2521         ui_block_colorpicker(block, handle->retvec, &but->rnapoin, but->rnaprop, show_picker);
2522         
2523         block->flag = UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_OUT_1 | UI_BLOCK_MOVEMOUSE_QUIT;
2524         UI_block_bounds_set_normal(block, 0.5 * UI_UNIT_X);
2525         
2526         block->block_event_func = ui_colorpicker_small_wheel_cb;
2527         
2528         /* and lets go */
2529         block->direction = UI_DIR_UP;
2530         
2531         return block;
2532 }
2533
2534 /************************ Popup Menu Memory ****************************/
2535
2536 static unsigned int ui_popup_string_hash(const char *str)
2537 {
2538         /* sometimes button contains hotkey, sometimes not, strip for proper compare */
2539         int hash;
2540         const char *delimit = strrchr(str, UI_SEP_CHAR);
2541
2542         if (delimit) {
2543                 hash = BLI_ghashutil_strhash_n(str, delimit - str);
2544         }
2545         else {
2546                 hash = BLI_ghashutil_strhash(str);
2547         }
2548
2549         return hash;
2550 }
2551
2552 static unsigned int ui_popup_menu_hash(const char *str)
2553 {
2554         return BLI_ghashutil_strhash(str);
2555 }
2556
2557 /* but == NULL read, otherwise set */
2558 static uiBut *ui_popup_menu_memory__internal(uiBlock *block, uiBut *but)
2559 {
2560         static unsigned int mem[256];
2561         static bool first = true;
2562
2563         const unsigned int hash = block->puphash;
2564         const unsigned int hash_mod = hash & 255;
2565         
2566         if (first) {
2567                 /* init */
2568                 memset(mem, -1, sizeof(mem));
2569                 first = 0;
2570         }
2571
2572         if (but) {
2573                 /* set */
2574                 mem[hash_mod] = ui_popup_string_hash(but->str);
2575                 return NULL;
2576         }
2577         else {
2578                 /* get */
2579                 for (but = block->buttons.first; but; but = but->next)
2580                         if (ui_popup_string_hash(but->str) == mem[hash_mod])
2581                                 return but;
2582
2583                 return NULL;
2584         }
2585 }
2586
2587 uiBut *ui_popup_menu_memory_get(uiBlock *block)
2588 {
2589         return ui_popup_menu_memory__internal(block, NULL);
2590 }
2591
2592 void ui_popup_menu_memory_set(uiBlock *block, uiBut *but)
2593 {
2594         ui_popup_menu_memory__internal(block, but);
2595 }
2596
2597 /**
2598  * Translate any popup regions (so we can drag them).
2599  */
2600 void ui_popup_translate(bContext *C, ARegion *ar, const int mdiff[2])
2601 {
2602         uiBlock *block;
2603
2604         BLI_rcti_translate(&ar->winrct, UNPACK2(mdiff));
2605
2606         ED_region_update_rect(C, ar);
2607
2608         ED_region_tag_redraw(ar);
2609
2610         /* update blocks */
2611         for (block = ar->uiblocks.first; block; block = block->next) {
2612                 uiSafetyRct *saferct;
2613                 for (saferct = block->saferct.first; saferct; saferct = saferct->next) {
2614                         BLI_rctf_translate(&saferct->parent, UNPACK2(mdiff));
2615                         BLI_rctf_translate(&saferct->safety, UNPACK2(mdiff));
2616                 }
2617         }
2618 }
2619
2620 /******************** Popup Menu with callback or string **********************/
2621
2622 struct uiPopupMenu {
2623         uiBlock *block;
2624         uiLayout *layout;
2625         uiBut *but;
2626
2627         int mx, my;
2628         bool popup, slideout;
2629
2630         uiMenuCreateFunc menu_func;
2631         void *menu_arg;
2632 };
2633
2634 struct uiPieMenu {
2635         uiBlock *block_radial; /* radial block of the pie menu (more could be added later) */
2636         uiLayout *layout;
2637         int mx, my;
2638 };
2639
2640 static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, void *arg_pup)
2641 {
2642         uiBlock *block;
2643         uiBut *bt;
2644         uiPopupMenu *pup = arg_pup;
2645         int offset[2], minwidth, width, height;
2646         char direction;
2647         bool flip;
2648
2649         if (pup->menu_func) {
2650                 pup->block->handle = handle;
2651                 pup->menu_func(C, pup->layout, pup->menu_arg);
2652                 pup->block->handle = NULL;
2653         }
2654
2655         if (pup->but) {
2656                 /* minimum width to enforece */
2657                 minwidth = BLI_rctf_size_x(&pup->but->rect);
2658
2659                 /* settings (typically rna-enum-popups) show above the button,
2660                  * menu's like file-menu, show below */
2661                 if (pup->block->direction != 0) {
2662                         /* allow overriding the direction from menu_func */
2663                         direction = pup->block->direction;
2664                 }
2665                 else if ((pup->but->type == UI_BTYPE_PULLDOWN) ||
2666                          (UI_but_menutype_get(pup->but) != NULL))
2667                 {
2668                         direction = UI_DIR_DOWN;
2669                 }
2670                 else {
2671                         direction = UI_DIR_UP;
2672                 }
2673         }
2674         else {
2675                 minwidth = 50;
2676                 direction = UI_DIR_DOWN;
2677         }
2678
2679         flip = (direction == UI_DIR_DOWN);
2680
2681         block = pup->block;
2682         
2683         /* in some cases we create the block before the region,
2684          * so we set it delayed here if necessary */
2685         if (BLI_findindex(&handle->region->uiblocks, block) == -1)
2686                 UI_block_region_set(block, handle->region);
2687
2688         block->direction = direction;
2689
2690         UI_block_layout_resolve(block, &width, &height);
2691
2692         UI_block_flag_enable(block, UI_BLOCK_MOVEMOUSE_QUIT);
2693         
2694         if (pup->popup) {
2695                 uiBut *but_activate = NULL;
2696                 UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
2697                 UI_block_direction_set(block, direction);
2698
2699                 /* offset the mouse position, possibly based on earlier selection */
2700                 if ((block->flag & UI_BLOCK_POPUP_MEMORY) &&
2701                     (bt = ui_popup_menu_memory_get(block)))
2702                 {
2703                         /* position mouse on last clicked item, at 0.8*width of the
2704                          * button, so it doesn't overlap the text too much, also note
2705                          * the offset is negative because we are inverse moving the
2706                          * block to be under the mouse */
2707                         offset[0] = -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect));
2708                         offset[1] = -(bt->rect.ymin + 0.5f * UI_UNIT_Y);
2709
2710                         if (ui_but_is_editable(bt)) {
2711                                 but_activate = bt;
2712                         }
2713                 }
2714                 else {
2715                         /* position mouse at 0.8*width of the button and below the tile
2716                          * on the first item */
2717                         offset[0] = 0;
2718                         for (bt = block->buttons.first; bt; bt = bt->next)
2719                                 offset[0] = min_ii(offset[0], -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect)));
2720
2721                         offset[1] = 2.1 * UI_UNIT_Y;
2722
2723                         for (bt = block->buttons.first; bt; bt = bt->next) {
2724                                 if (ui_but_is_editable(bt)) {
2725                                         but_activate = bt;
2726                                         break;
2727                                 }
2728                         }
2729                 }
2730
2731                 /* in rare cases this is needed since moving the popup
2732                  * to be within the window bounds may move it away from the mouse,
2733                  * This ensures we set an item to be active. */
2734                 if (but_activate) {
2735                         ui_but_activate_over(C, handle->region, but_activate);
2736                 }
2737
2738                 block->minbounds = minwidth;
2739                 UI_block_bounds_set_menu(block, 1, offset[0], offset[1]);
2740         }
2741         else {
2742                 /* for a header menu we set the direction automatic */
2743                 if (!pup->slideout && flip) {
2744                         ScrArea *sa = CTX_wm_area(C);
2745                         if (sa && sa->headertype == HEADERDOWN) {
2746                                 ARegion *ar = CTX_wm_region(C);
2747                                 if (ar && ar->regiontype == RGN_TYPE_HEADER) {
2748                                         UI_block_direction_set(block, UI_DIR_UP);
2749                                         UI_block_order_flip(block);
2750                                 }
2751                         }
2752                 }
2753
2754                 block->minbounds = minwidth;
2755                 UI_block_bounds_set_text(block, 3.0f * UI_UNIT_X);
2756         }
2757
2758         /* if menu slides out of other menu, override direction */
2759         if (pup->slideout)
2760                 UI_block_direction_set(block, UI_DIR_RIGHT);
2761
2762         return pup->block;
2763 }
2764
2765 uiPopupBlockHandle *ui_popup_menu_create(
2766         bContext *C, ARegion *butregion, uiBut *but,
2767         uiMenuCreateFunc menu_func, void *arg)
2768 {
2769         wmWindow *window = CTX_wm_window(C);
2770         uiStyle *style = UI_style_get_dpi();
2771         uiPopupBlockHandle *handle;
2772         uiPopupMenu *pup;
2773
2774         pup = MEM_callocN(sizeof(uiPopupMenu), __func__);
2775         pup->block = UI_block_begin(C, NULL, __func__, UI_EMBOSS_PULLDOWN);
2776         pup->block->flag |= UI_BLOCK_NUMSELECT;  /* default menus to numselect */
2777         pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
2778         pup->slideout = but ? ui_block_is_menu(but->block) : false;
2779         pup->but = but;
2780         uiLayoutSetOperatorContext(pup->layout, WM_OP_INVOKE_REGION_WIN);
2781
2782         if (!but) {
2783                 /* no button to start from, means we are a popup */
2784                 pup->mx = window->eventstate->x;
2785                 pup->my = window->eventstate->y;
2786                 pup->popup = true;
2787                 pup->block->flag |= UI_BLOCK_NO_FLIP;
2788         }
2789         /* some enums reversing is strange, currently we have no good way to
2790          * reverse some enum's but not others, so reverse all so the first menu
2791          * items are always close to the mouse cursor */
2792         else {
2793 #if 0
2794                 /* if this is an rna button then we can assume its an enum
2795                  * flipping enums is generally not good since the order can be
2796                  * important [#28786] */
2797                 if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
2798                         pup->block->flag |= UI_BLOCK_NO_FLIP;
2799                 }
2800 #endif
2801                 if (but->context)
2802                         uiLayoutContextCopy(pup->layout, but->context);
2803         }
2804
2805         /* menu is created from a callback */
2806         pup->menu_func = menu_func;
2807         pup->menu_arg = arg;
2808         
2809         handle = ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
2810
2811         if (!but) {
2812                 handle->popup = true;
2813
2814                 UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
2815                 WM_event_add_mousemove(C);
2816         }
2817         
2818         handle->can_refresh = false;
2819         MEM_freeN(pup);
2820
2821         return handle;
2822 }
2823
2824 /******************** Popup Menu API with begin and end ***********************/
2825
2826 /**
2827  * Only return handler, and set optional title.
2828  * \param block_name: Assigned to uiBlock.name (useful info for debugging).
2829  */
2830 uiPopupMenu *UI_popup_menu_begin_ex(bContext *C, const char *title, const char *block_name, int icon)
2831 {
2832         uiStyle *style = UI_style_get_dpi();
2833         uiPopupMenu *pup = MEM_callocN(sizeof(uiPopupMenu), "popup menu");
2834         uiBut *but;
2835
2836         pup->block = UI_block_begin(C, NULL, block_name, UI_EMBOSS_PULLDOWN);
2837         pup->block->flag |= UI_BLOCK_POPUP_MEMORY | UI_BLOCK_IS_FLIP;
2838         pup->block->puphash = ui_popup_menu_hash(title);
2839         pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
2840
2841         /* note, this intentionally differs from the menu & submenu default because many operators
2842          * use popups like this to select one of their options - where having invoke doesn't make sense */
2843         uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
2844
2845         /* create in advance so we can let buttons point to retval already */
2846         pup->block->handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
2847         
2848         /* create title button */
2849         if (title[0]) {
2850                 char titlestr[256];
2851                 
2852                 if (icon) {
2853                         BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
2854                         uiDefIconTextBut(pup->block, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2855                 }
2856                 else {
2857                         but = uiDefBut(pup->block, UI_BTYPE_LABEL, 0, title, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2858                         but->drawflag = UI_BUT_TEXT_LEFT;
2859                 }
2860
2861                 uiItemS(pup->layout);
2862         }
2863
2864         return pup;
2865 }
2866
2867 uiPopupMenu *UI_popup_menu_begin(bContext *C, const char *title, int icon)
2868 {
2869         return UI_popup_menu_begin_ex(C, title, __func__, icon);
2870 }
2871
2872 /* set the whole structure to work */
2873 void UI_popup_menu_end(bContext *C, uiPopupMenu *pup)
2874 {
2875         wmWindow *window = CTX_wm_window(C);
2876         uiPopupBlockHandle *menu;
2877         
2878         pup->popup = true;
2879         pup->mx = window->eventstate->x;
2880         pup->my = window->eventstate->y;
2881         
2882         menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_POPUP, pup);
2883         menu->popup = true;
2884         
2885         UI_popup_handlers_add(C, &window->modalhandlers, menu, 0);
2886         WM_event_add_mousemove(C);
2887
2888         menu->can_refresh = false;
2889         MEM_freeN(pup);
2890 }
2891
2892 uiLayout *UI_popup_menu_layout(uiPopupMenu *pup)
2893 {
2894         return pup->layout;
2895 }
2896
2897 /*************************** Pie Menus ***************************************/
2898
2899 static uiBlock *ui_block_func_PIE(bContext *UNUSED(C), uiPopupBlockHandle *handle, void *arg_pie)
2900 {
2901         uiBlock *block;
2902         uiPieMenu *pie = arg_pie;
2903         int minwidth, width, height;
2904
2905         minwidth = 50;
2906         block = pie->block_radial;
2907
2908         /* in some cases we create the block before the region,
2909          * so we set it delayed here if necessary */
2910         if (BLI_findindex(&handle->region->uiblocks, block) == -1)
2911                 UI_block_region_set(block, handle->region);
2912
2913         UI_block_layout_resolve(block, &width, &height);
2914
2915         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
2916
2917         block->minbounds = minwidth;
2918         block->bounds = 1;
2919         block->mx = 0;
2920         block->my = 0;
2921         block->bounds_type = UI_BLOCK_BOUNDS_PIE_CENTER;
2922
2923         block->pie_data.pie_center_spawned[0] = pie->mx;
2924         block->pie_data.pie_center_spawned[1] = pie->my;
2925
2926         return pie->block_radial;
2927 }
2928
2929 static float ui_pie_menu_title_width(const char *name, int icon)
2930 {
2931         const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
2932         return (UI_fontstyle_string_width(fstyle, name) +
2933                  (UI_UNIT_X * (1.50f + (icon ? 0.25f : 0.0f))));
2934 }
2935
2936 uiPieMenu *UI_pie_menu_begin(struct bContext *C, const char *title, int icon, const wmEvent *event)
2937 {
2938         uiStyle *style;
2939         uiPieMenu *pie;
2940         short event_type;
2941
2942         wmWindow *win = CTX_wm_window(C);
2943
2944         style = UI_style_get_dpi();
2945         pie = MEM_callocN(sizeof(uiPopupMenu), "pie menu");
2946
2947         pie->block_radial = UI_block_begin(C, NULL, __func__, UI_EMBOSS);
2948         /* may be useful later to allow spawning pies
2949          * from old positions */
2950         /* pie->block_radial->flag |= UI_BLOCK_POPUP_MEMORY; */
2951         pie->block_radial->puphash = ui_popup_menu_hash(title);
2952         pie->block_radial->flag |= UI_BLOCK_RADIAL;
2953
2954         /* if pie is spawned by a left click, it is always assumed to be click style */
2955         if (event->type == LEFTMOUSE) {
2956                 pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
2957                 pie->block_radial->pie_data.event = EVENT_NONE;
2958                 win->lock_pie_event = EVENT_NONE;
2959         }
2960         else {
2961                 if (win->last_pie_event != EVENT_NONE) {
2962                         /* original pie key has been released, so don't propagate the event */
2963                         if (win->lock_pie_event == EVENT_NONE) {
2964                                 event_type = EVENT_NONE;
2965                                 pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
2966                         }
2967                         else
2968                                 event_type = win->last_pie_event;
2969                 }
2970                 else {
2971                         event_type = event->type;
2972                 }
2973
2974                 pie->block_radial->pie_data.event = event_type;
2975                 win->lock_pie_event = event_type;
2976         }
2977
2978         pie->layout = UI_block_layout(pie->block_radial, UI_LAYOUT_VERTICAL, UI_LAYOUT_PIEMENU, 0, 0, 200, 0, 0, style);
2979         pie->mx = event->x;
2980         pie->my = event->y;
2981
2982         /* create title button */
2983         if (title[0]) {
2984                 uiBut *but;
2985                 char titlestr[256];
2986                 int w;
2987                 if (icon) {
2988                         BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
2989                         w = ui_pie_menu_title_width(titlestr, icon);
2990                         but = uiDefIconTextBut(pie->block_radial, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2991                 }
2992                 else {
2993                         w = ui_pie_menu_title_width(title, 0);
2994                         but = uiDefBut(pie->block_radial, UI_BTYPE_LABEL, 0, title, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2995                 }
2996                 /* do not align left */
2997                 but->drawflag &= ~UI_BUT_TEXT_LEFT;
2998                 pie->block_radial->pie_data.title = but->str;
2999                 pie->block_radial->pie_data.icon = icon;
3000         }
3001
3002         return pie;
3003 }
3004
3005 void UI_pie_menu_end(bContext *C, uiPieMenu *pie)
3006 {
3007         wmWindow *window = CTX_wm_window(C);
3008         uiPopupBlockHandle *menu;
3009
3010         menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_PIE, pie);
3011         menu->popup = true;
3012         menu->towardstime = PIL_check_seconds_timer();
3013
3014         UI_popup_handlers_add(
3015                 C, &window->modalhandlers,
3016                 menu, WM_HANDLER_ACCEPT_DBL_CLICK);
3017         WM_event_add_mousemove(C);
3018
3019         menu->can_refresh = false;
3020         MEM_freeN(pie);
3021 }
3022
3023 uiLayout *UI_pie_menu_layout(uiPieMenu *pie)
3024 {
3025         return pie->layout;
3026 }
3027
3028 int UI_pie_menu_invoke(struct bContext *C, const char *idname, const wmEvent *event)
3029 {
3030         uiPieMenu *pie;
3031         uiLayout *layout;
3032         Menu menu;
3033         MenuType *mt = WM_menutype_find(idname, true);
3034
3035         if (mt == NULL) {
3036                 printf("%s: named menu \"%s\" not found\n", __func__, idname);
3037                 return OPERATOR_CANCELLED;
3038         }
3039
3040         if (mt->poll && mt->poll(C, mt) == 0)
3041                 /* cancel but allow event to pass through, just like operators do */
3042                 return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH);
3043
3044         pie = UI_pie_menu_begin(C, IFACE_(mt->label), ICON_NONE, event);
3045         layout = UI_pie_menu_layout(pie);
3046
3047         menu.layout = layout;
3048         menu.type = mt;
3049
3050         if (G.debug & G_DEBUG_WM) {
3051                 printf("%s: opening menu \"%s\"\n", __func__, idname);
3052         }
3053
3054         mt->draw(C, &menu);
3055
3056         UI_pie_menu_end(C, pie);
3057
3058         return OPERATOR_INTERFACE;
3059 }
3060
3061 int UI_pie_menu_invoke_from_operator_enum(
3062         struct bContext *C, const char *title, const char *opname,
3063         const char *propname, const wmEvent *event)
3064 {
3065         uiPieMenu *pie;
3066         uiLayout *layout;
3067
3068         pie = UI_pie_menu_begin(C, IFACE_(title), ICON_NONE, event);
3069         layout = UI_pie_menu_layout(pie);
3070
3071         layout = uiLayoutRadial(layout);
3072         uiItemsEnumO(layout, opname, propname);
3073
3074         UI_pie_menu_end(C, pie);
3075
3076         return OPERATOR_INTERFACE;
3077 }
3078
3079 int UI_pie_menu_invoke_from_rna_enum(
3080         struct bContext *C, const char *title, const char *path,
3081         const wmEvent *event)
3082 {
3083         PointerRNA ctx_ptr;
3084         PointerRNA r_ptr;
3085         PropertyRNA *r_prop;
3086         uiPieMenu *pie;
3087         uiLayout *layout;
3088
3089         RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
3090
3091         if (!RNA_path_resolve(&ctx_ptr, path, &r_ptr, &r_prop)) {
3092                 return OPERATOR_CANCELLED;
3093         }
3094
3095         /* invalid property, only accept enums */
3096         if (RNA_property_type(r_prop) != PROP_ENUM) {
3097                 BLI_assert(0);