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