This commit replaces old "manual" Editors menu with nice RNA-based one (so once again...
[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
31
32 #include <stdarg.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_userdef_types.h"
40
41 #include "BLI_math.h"
42 #include "BLI_blenlib.h"
43 #include "BLI_utildefines.h"
44 #include "BLI_dynstr.h"
45 #include "BLI_ghash.h"
46
47 #include "BKE_context.h"
48 #include "BKE_screen.h"
49 #include "BKE_idcode.h"
50 #include "BKE_global.h"
51
52 #include "WM_api.h"
53 #include "WM_types.h"
54 #include "wm_draw.h"
55 #include "wm_subwindow.h"
56 #include "wm_window.h"
57
58 #include "RNA_access.h"
59
60 #include "BIF_gl.h"
61
62 #include "UI_interface.h"
63 #include "UI_interface_icons.h"
64 #include "UI_view2d.h"
65
66 #include "BLF_api.h"
67 #include "BLF_translation.h"
68
69 #include "ED_screen.h"
70
71 #include "IMB_colormanagement.h"
72
73 #include "interface_intern.h"
74
75 #define B_NOP               -1
76 #define MENU_TOP            8
77
78 /*********************** Menu Data Parsing ********************* */
79
80 typedef struct MenuEntry {
81         const char *str;
82         int retval;
83         int icon;
84         int sepr;
85 } MenuEntry;
86
87 typedef struct MenuData {
88         const char *instr;
89         const char *title;
90         int titleicon;
91         
92         MenuEntry *items;
93         int nitems, itemssize;
94 } MenuData;
95
96 static MenuData *menudata_new(const char *instr)
97 {
98         MenuData *md = MEM_mallocN(sizeof(*md), "MenuData");
99
100         md->instr = instr;
101         md->title = NULL;
102         md->titleicon = 0;
103         md->items = NULL;
104         md->nitems = md->itemssize = 0;
105         
106         return md;
107 }
108
109 static void menudata_set_title(MenuData *md, const char *title, int titleicon)
110 {
111         if (!md->title)
112                 md->title = title;
113         if (!md->titleicon)
114                 md->titleicon = titleicon;
115 }
116
117 static void menudata_add_item(MenuData *md, const char *str, int retval, int icon, int sepr)
118 {
119         if (md->nitems == md->itemssize) {
120                 int nsize = md->itemssize ? (md->itemssize << 1) : 1;
121                 MenuEntry *oitems = md->items;
122                 
123                 md->items = MEM_mallocN(nsize * sizeof(*md->items), "md->items");
124                 if (oitems) {
125                         memcpy(md->items, oitems, md->nitems * sizeof(*md->items));
126                         MEM_freeN(oitems);
127                 }
128                 
129                 md->itemssize = nsize;
130         }
131         
132         md->items[md->nitems].str = str;
133         md->items[md->nitems].retval = retval;
134         md->items[md->nitems].icon = icon;
135         md->items[md->nitems].sepr = sepr;
136         md->nitems++;
137 }
138
139 static void menudata_free(MenuData *md)
140 {
141         MEM_freeN((void *)md->instr);
142         if (md->items) {
143                 MEM_freeN(md->items);
144         }
145         MEM_freeN(md);
146 }
147
148 /**
149  * Parse menu description strings, string is of the
150  * form "[sss%t|]{(sss[%xNN]|), (%l|), (sss%l|)}", ssss%t indicates the
151  * menu title, sss or sss%xNN indicates an option,
152  * if %xNN is given then NN is the return value if
153  * that option is selected otherwise the return value
154  * is the index of the option (starting with 1). %l
155  * indicates a separator, sss%l indicates a label and
156  * new column.
157  *
158  * \param str String to be parsed.
159  * \retval new menudata structure, free with menudata_free()
160  */
161 static MenuData *decompose_menu_string(const char *str)
162 {
163         char *instr = BLI_strdup(str);
164         MenuData *md = menudata_new(instr);
165         const char *nitem = NULL;
166         char *s = instr;
167         int nicon = 0, nretval = 1, nitem_is_title = 0, nitem_is_sepr = 0;
168         
169         while (1) {
170                 char c = *s;
171
172                 if (c == '%') {
173                         if (s[1] == 'x') {
174                                 nretval = atoi(s + 2);
175
176                                 *s = '\0';
177                                 s++;
178                         }
179                         else if (s[1] == 't') {
180                                 nitem_is_title = (s != instr); /* check for empty title */
181
182                                 *s = '\0';
183                                 s++;
184                         }
185                         else if (s[1] == 'l') {
186                                 nitem_is_sepr = 1;
187                                 if (!nitem) nitem = "";
188
189                                 *s = '\0';
190                                 s++;
191                         }
192                         else if (s[1] == 'i') {
193                                 nicon = atoi(s + 2);
194                                 
195                                 *s = '\0';
196                                 s++;
197                         }
198                 }
199                 else if (c == '|' || c == '\n' || c == '\0') {
200                         if (nitem) {
201                                 *s = '\0';
202
203                                 if (nitem_is_title) {
204                                         menudata_set_title(md, nitem, nicon);
205                                         nitem_is_title = 0;
206                                 }
207                                 else if (nitem_is_sepr) {
208                                         /* prevent separator to get a value */
209                                         menudata_add_item(md, nitem, -1, nicon, 1);
210                                         nretval = md->nitems + 1;
211                                         nitem_is_sepr = 0;
212                                 }
213                                 else {
214                                         menudata_add_item(md, nitem, nretval, nicon, 0);
215                                         nretval = md->nitems + 1;
216                                 }
217                                 
218                                 nitem = NULL;
219                                 nicon = 0;
220                         }
221                         
222                         if (c == '\0') {
223                                 break;
224                         }
225                 }
226                 else if (!nitem) {
227                         nitem = s;
228                 }
229
230                 s++;
231         }
232         
233         return md;
234 }
235
236 void ui_set_name_menu(uiBut *but, int value)
237 {
238         MenuData *md;
239         int i;
240         
241         md = decompose_menu_string(but->str);
242         for (i = 0; i < md->nitems; i++) {
243                 if (md->items[i].retval == value) {
244                         BLI_strncpy(but->drawstr, md->items[i].str, sizeof(but->drawstr));
245                         break;
246                 }
247         }
248         
249         menudata_free(md);
250 }
251
252 int ui_step_name_menu(uiBut *but, int step)
253 {
254         MenuData *md;
255         int value = ui_get_but_val(but);
256         int i;
257         
258         md = decompose_menu_string(but->str);
259         for (i = 0; i < md->nitems; i++)
260                 if (md->items[i].retval == value)
261                         break;
262         
263         if (step == 1) {
264                 /* skip separators */
265                 for (; i < md->nitems - 1; i++) {
266                         if (md->items[i + 1].retval != -1) {
267                                 value = md->items[i + 1].retval;
268                                 break;
269                         }
270                 }
271         }
272         else {
273                 if (i > 0) {
274                         /* skip separators */
275                         for (; i > 0; i--) {
276                                 if (md->items[i - 1].retval != -1) {
277                                         value = md->items[i - 1].retval;
278                                         break;
279                                 }
280                         }
281                 }
282         }
283         
284         menudata_free(md);
285                 
286         return value;
287 }
288
289
290 /******************** Creating Temporary regions ******************/
291
292 static ARegion *ui_add_temporary_region(bScreen *sc)
293 {
294         ARegion *ar;
295
296         ar = MEM_callocN(sizeof(ARegion), "area region");
297         BLI_addtail(&sc->regionbase, ar);
298
299         ar->regiontype = RGN_TYPE_TEMPORARY;
300         ar->alignment = RGN_ALIGN_FLOAT;
301
302         return ar;
303 }
304
305 static void ui_remove_temporary_region(bContext *C, bScreen *sc, ARegion *ar)
306 {
307         wmWindow *win = CTX_wm_window(C);
308         if (win)
309                 wm_draw_region_clear(win, ar);
310
311         ED_region_exit(C, ar);
312         BKE_area_region_free(NULL, ar);     /* NULL: no spacetype */
313         BLI_freelinkN(&sc->regionbase, ar);
314 }
315
316 /************************* Creating Tooltips **********************/
317
318 typedef enum {
319         UI_TIP_LC_MAIN,
320         UI_TIP_LC_NORMAL,
321         UI_TIP_LC_PYTHON,
322         UI_TIP_LC_ALERT,
323         UI_TIP_LC_SUBMENU
324 } uiTooltipLineColor;
325 #define UI_TIP_LC_MAX 5
326
327 #define MAX_TOOLTIP_LINES 8
328 typedef struct uiTooltipData {
329         rcti bbox;
330         uiFontStyle fstyle;
331         char lines[MAX_TOOLTIP_LINES][512];
332         uiTooltipLineColor color_id[MAX_TOOLTIP_LINES];
333         int totline;
334         int toth, spaceh, lineh;
335 } uiTooltipData;
336
337 static void rgb_tint(float col[3],
338                      float h, float h_strength,
339                      float v, float v_strength)
340 {
341         float col_hsv_from[3];
342         float col_hsv_to[3];
343
344         rgb_to_hsv_v(col, col_hsv_from);
345
346         col_hsv_to[0] = h;
347         col_hsv_to[1] = h_strength;
348         col_hsv_to[2] = (col_hsv_from[2] * (1.0f - v_strength)) + (v * v_strength);
349
350         hsv_to_rgb_v(col_hsv_to, col);
351 }
352
353 static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
354 {
355         uiTooltipData *data = ar->regiondata;
356         uiWidgetColors *theme = ui_tooltip_get_theme();
357         rcti bbox = data->bbox;
358         float tip_colors[UI_TIP_LC_MAX][3];
359
360         float *main_color    = tip_colors[UI_TIP_LC_MAIN]; /* the color from the theme */
361         float *normal_color  = tip_colors[UI_TIP_LC_NORMAL];
362         float *python_color  = tip_colors[UI_TIP_LC_PYTHON];
363         float *alert_color   = tip_colors[UI_TIP_LC_ALERT];
364         float *submenu_color = tip_colors[UI_TIP_LC_SUBMENU];
365
366         float background_color[3];
367         float tone_bg;
368         int i, multisample_enabled;
369
370         /* disable AA, makes widgets too blurry */
371         multisample_enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
372         if (multisample_enabled)
373                 glDisable(GL_MULTISAMPLE_ARB);
374
375         /* draw background */
376         ui_draw_tooltip_background(UI_GetStyle(), NULL, &bbox);
377
378         /* set background_color */
379         rgb_uchar_to_float(background_color, (const unsigned char *)theme->inner);
380
381         /* calculate normal_color */
382         rgb_uchar_to_float(main_color, (const unsigned char *)theme->text);
383         copy_v3_v3(normal_color, main_color);
384         copy_v3_v3(python_color, main_color);
385         copy_v3_v3(alert_color, main_color);
386         copy_v3_v3(submenu_color, main_color);
387
388         /* find the brightness difference between background and text colors */
389         
390         tone_bg = rgb_to_grayscale(background_color);
391         /* tone_fg = rgb_to_grayscale(main_color); */
392
393         rgb_tint(normal_color, 0.0f, 0.0f, tone_bg, 0.3f);   /* a shade darker (to bg) */
394         rgb_tint(python_color, 0.666f, 0.25f, tone_bg, 0.3f); /* blue */
395         rgb_tint(alert_color, 0.0f, 0.8f, tone_bg, 0.1f);    /* bright red */
396         rgb_tint(submenu_color, 0.0f, 0.0f, tone_bg, 0.3f);  /* a shade darker (to bg) */
397
398         /* draw text */
399         uiStyleFontSet(&data->fstyle);
400
401         bbox.ymax = bbox.ymax - 0.5f * (BLI_rcti_size_y(&bbox) - data->toth);
402         bbox.ymin = bbox.ymax - data->lineh;
403
404         for (i = 0; i < data->totline; i++) {
405                 glColor3fv(tip_colors[data->color_id[i]]);
406                 uiStyleFontDraw(&data->fstyle, &bbox, data->lines[i]);
407                 bbox.ymin -= data->lineh + data->spaceh;
408                 bbox.ymax -= data->lineh + data->spaceh;
409         }
410
411         if (multisample_enabled)
412                 glEnable(GL_MULTISAMPLE_ARB);
413 }
414
415 static void ui_tooltip_region_free_cb(ARegion *ar)
416 {
417         uiTooltipData *data;
418
419         data = ar->regiondata;
420         MEM_freeN(data);
421         ar->regiondata = NULL;
422 }
423
424 ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
425 {
426         wmWindow *win = CTX_wm_window(C);
427         uiStyle *style = UI_GetStyle();
428         static ARegionType type;
429         ARegion *ar;
430         uiTooltipData *data;
431 /*      IDProperty *prop;*/
432         char buf[512];
433         float fonth, fontw, aspect = but->block->aspect;
434         int winx /*, winy */, ofsx, ofsy, w, h, a;
435         rctf rect_fl;
436         rcti rect_i;
437
438         uiStringInfo but_tip = {BUT_GET_TIP, NULL};
439         uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
440         uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
441         uiStringInfo op_keymap = {BUT_GET_OP_KEYMAP, NULL};
442         uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
443         uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
444
445         if (but->flag & UI_BUT_NO_TOOLTIP)
446                 return NULL;
447
448         /* create tooltip data */
449         data = MEM_callocN(sizeof(uiTooltipData), "uiTooltipData");
450
451         uiButGetStrInfo(C, but, &but_tip, &enum_label, &enum_tip, &op_keymap, &rna_struct, &rna_prop, NULL);
452
453         /* special case, enum rna buttons only have enum item description,
454          * use general enum description too before the specific one */
455
456         /* Tip */
457         if (but_tip.strinfo) {
458                 /* Expanded Bit-flag enums have a specific way to select multiple... */
459                 if ((but->type & ROW) && but->rnaprop && RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG) {
460                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
461                                      "%s %s", but_tip.strinfo, IFACE_("(Shift-click to select multiple)"));
462                 }
463                 else {
464                         BLI_strncpy(data->lines[data->totline], but_tip.strinfo, sizeof(data->lines[0]));
465                 }
466                 data->color_id[data->totline] = UI_TIP_LC_MAIN;
467                 data->totline++;
468         }
469         /* Enum item label & tip */
470         if (enum_label.strinfo && enum_tip.strinfo) {
471                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
472                              "%s: %s", enum_label.strinfo, enum_tip.strinfo);
473                 data->color_id[data->totline] = UI_TIP_LC_SUBMENU;
474                 data->totline++;
475         }
476
477         /* Op shortcut */
478         if (op_keymap.strinfo) {
479                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), op_keymap.strinfo);
480                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
481                 data->totline++;
482         }
483
484         if (ELEM4(but->type, TEX, IDPOIN, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
485                 /* full string */
486                 ui_get_but_string(but, buf, sizeof(buf));
487                 if (buf[0]) {
488                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Value: %s"), buf);
489                         data->color_id[data->totline] = UI_TIP_LC_NORMAL;
490                         data->totline++;
491                 }
492         }
493
494         if (but->rnaprop) {
495                 int unit_type = uiButGetUnitType(but);
496                 
497                 if (unit_type == PROP_UNIT_ROTATION) {
498                         if (RNA_property_type(but->rnaprop) == PROP_FLOAT) {
499                                 float value = RNA_property_array_check(but->rnaprop) ?
500                                                   RNA_property_float_get_index(&but->rnapoin, but->rnaprop, but->rnaindex) :
501                                                   RNA_property_float_get(&but->rnapoin, but->rnaprop);
502                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Radians: %f"), value);
503                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
504                                 data->totline++;
505                         }
506                 }
507                 
508                 if (but->flag & UI_BUT_DRIVEN) {
509                         if (ui_but_anim_expression_get(but, buf, sizeof(buf))) {
510                                 /* expression */
511                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Expression: %s"), buf);
512                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
513                                 data->totline++;
514                         }
515                 }
516
517                 if (but->rnapoin.id.data) {
518                         ID *id = but->rnapoin.id.data;
519                         if (id->lib && id->lib->name) {
520                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Library: %s"), id->lib->name);
521                                 data->color_id[data->totline] = UI_TIP_LC_NORMAL;
522                                 data->totline++;
523                         }
524                 }
525         }
526         else if (but->optype) {
527                 PointerRNA *opptr;
528                 char *str;
529                 opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
530
531                 /* so the context is passed to itemf functions (some py itemf functions use it) */
532                 WM_operator_properties_sanitize(opptr, false);
533
534                 str = WM_operator_pystring(C, but->optype, opptr, 0);
535
536                 /* operator info */
537                 if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
538                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s"), str);
539                         data->color_id[data->totline] = UI_TIP_LC_PYTHON;
540                         data->totline++;
541                 }
542
543                 MEM_freeN(str);
544
545                 /* second check if we are disabled - why */
546                 if (but->flag & UI_BUT_DISABLED) {
547                         const char *poll_msg;
548                         CTX_wm_operator_poll_msg_set(C, NULL);
549                         WM_operator_poll_context(C, but->optype, but->opcontext);
550                         poll_msg = CTX_wm_operator_poll_msg_get(C);
551                         if (poll_msg) {
552                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Disabled: %s"), poll_msg);
553                                 data->color_id[data->totline] = UI_TIP_LC_ALERT; /* alert */
554                                 data->totline++;
555                         }
556                 }
557         }
558         if ((U.flag & USER_TOOLTIPS_PYTHON) == 0 && !but->optype && rna_struct.strinfo) {
559                 if (rna_prop.strinfo) {
560                         /* Struct and prop */
561                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
562                                      TIP_("Python: %s.%s"),
563                                      rna_struct.strinfo, rna_prop.strinfo);
564                 }
565                 else {
566                         /* Only struct (e.g. menus) */
567                         BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
568                                      TIP_("Python: %s"), rna_struct.strinfo);
569                 }
570                 data->color_id[data->totline] = UI_TIP_LC_PYTHON;
571                 data->totline++;
572
573                 if (but->rnapoin.id.data) {
574                         /* this could get its own 'BUT_GET_...' type */
575                         PointerRNA *ptr = &but->rnapoin;
576                         PropertyRNA *prop = but->rnaprop;
577                         ID *id = ptr->id.data;
578
579                         char *id_path;
580                         char *data_path = NULL;
581
582                         /* never fails */
583                         id_path = RNA_path_full_ID_py(id);
584
585                         if (ptr->id.data && ptr->data && prop) {
586                                 data_path = RNA_path_from_ID_to_property(ptr, prop);
587                         }
588
589                         if (data_path) {
590                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
591                                              "%s.%s",  /* no need to translate */
592                                              id_path, data_path);
593                                 MEM_freeN(data_path);
594                         }
595                         else if (prop) {
596                                 /* can't find the path. be explicit in our ignorance "..." */
597                                 BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
598                                              "%s ... %s",  /* no need to translate */
599                                              id_path, rna_prop.strinfo ? rna_prop.strinfo : RNA_property_identifier(prop));
600                         }
601                         MEM_freeN(id_path);
602
603                         data->color_id[data->totline] = UI_TIP_LC_PYTHON;
604                         data->totline++;
605                 }
606         }
607
608         /* Free strinfo's... */
609         if (but_tip.strinfo)
610                 MEM_freeN(but_tip.strinfo);
611         if (enum_label.strinfo)
612                 MEM_freeN(enum_label.strinfo);
613         if (enum_tip.strinfo)
614                 MEM_freeN(enum_tip.strinfo);
615         if (op_keymap.strinfo)
616                 MEM_freeN(op_keymap.strinfo);
617         if (rna_struct.strinfo)
618                 MEM_freeN(rna_struct.strinfo);
619         if (rna_prop.strinfo)
620                 MEM_freeN(rna_prop.strinfo);
621
622         BLI_assert(data->totline < MAX_TOOLTIP_LINES);
623         
624         if (data->totline == 0) {
625                 MEM_freeN(data);
626                 return NULL;
627         }
628
629         /* create area region */
630         ar = ui_add_temporary_region(CTX_wm_screen(C));
631
632         memset(&type, 0, sizeof(ARegionType));
633         type.draw = ui_tooltip_region_draw_cb;
634         type.free = ui_tooltip_region_free_cb;
635         ar->type = &type;
636         
637         /* set font, get bb */
638         data->fstyle = style->widget; /* copy struct */
639         data->fstyle.align = UI_STYLE_TEXT_CENTER;
640         ui_fontscale(&data->fstyle.points, aspect);
641
642         uiStyleFontSet(&data->fstyle);
643
644         /* these defines tweaked depending on font */
645 #define TIP_MARGIN_Y (2.0f / aspect)
646 #define TIP_BORDER_X (16.0f / aspect)
647 #define TIP_BORDER_Y (6.0f / aspect)
648
649         h = BLF_height_max(data->fstyle.uifont_id);
650
651         for (a = 0, fontw = 0, fonth = 0; a < data->totline; a++) {
652                 w = BLF_width(data->fstyle.uifont_id, data->lines[a]);
653                 fontw = max_ff(fontw, (float)w);
654                 fonth += (a == 0) ? h : h + TIP_MARGIN_Y;
655         }
656
657         //fontw *= aspect;
658
659         ar->regiondata = data;
660
661         data->toth = fonth;
662         data->lineh = h;
663         data->spaceh = TIP_MARGIN_Y;
664
665         /* compute position */
666         ofsx = 0; //(but->block->panel) ? but->block->panel->ofsx : 0;
667         ofsy = 0; //(but->block->panel) ? but->block->panel->ofsy : 0;
668
669         rect_fl.xmin = BLI_rctf_cent_x(&but->rect) + ofsx - TIP_BORDER_X;
670         rect_fl.xmax = rect_fl.xmin + fontw + TIP_BORDER_X;
671         rect_fl.ymax = but->rect.ymin + ofsy - TIP_BORDER_Y;
672         rect_fl.ymin = rect_fl.ymax - fonth  - TIP_BORDER_Y;
673
674 #undef TIP_MARGIN_Y
675 #undef TIP_BORDER_X
676 #undef 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 ofsx_fl = rect_fl.xmin, ofsy_fl = rect_fl.ymax;
682                 ui_block_to_window_fl(butregion, but->block, &ofsx_fl, &ofsy_fl);
683                 BLI_rctf_translate(&rect_fl, ofsx_fl - rect_fl.xmin, ofsy_fl - rect_fl.ymax);
684         }
685         BLI_rcti_rctf_copy(&rect_i, &rect_fl);
686
687         /* clip with window boundaries */
688         winx = WM_window_pixels_x(win);
689
690         if (rect_i.xmax > winx) {
691                 /* super size */
692                 if (rect_i.xmax > winx + rect_i.xmin) {
693                         rect_i.xmax = winx;
694                         rect_i.xmin = 0;
695                 }
696                 else {
697                         rect_i.xmin -= rect_i.xmax - winx;
698                         rect_i.xmax = winx;
699                 }
700         }
701         /* ensure at least 5 px above screen bounds
702          * 25 is just a guess to be above the menu item */
703         if (rect_i.ymin < 5) {
704                 rect_i.ymax += (-rect_i.ymin) + 30;
705                 rect_i.ymin = 30;
706         }
707
708         /* widget rect, in region coords */
709         {
710                 int width = UI_ThemeMenuShadowWidth();
711                 
712                 data->bbox.xmin = width;
713                 data->bbox.xmax = BLI_rcti_size_x(&rect_i) + width;
714                 data->bbox.ymin = width;
715                 data->bbox.ymax = BLI_rcti_size_y(&rect_i) + width;
716                 
717                 /* region bigger for shadow */
718                 ar->winrct.xmin = rect_i.xmin - width;
719                 ar->winrct.xmax = rect_i.xmax + width;
720                 ar->winrct.ymin = rect_i.ymin - width;
721                 ar->winrct.ymax = rect_i.ymax + MENU_TOP;
722         }
723
724         /* adds subwindow */
725         ED_region_init(C, ar);
726         
727         /* notify change and redraw */
728         ED_region_tag_redraw(ar);
729
730         return ar;
731 }
732
733 void ui_tooltip_free(bContext *C, ARegion *ar)
734 {
735         ui_remove_temporary_region(C, CTX_wm_screen(C), ar);
736 }
737
738
739 /************************* Creating Search Box **********************/
740
741 struct uiSearchItems {
742         int maxitem, totitem, maxstrlen;
743         
744         int offset, offset_i; /* offset for inserting in array */
745         int more;  /* flag indicating there are more items */
746         
747         char **names;
748         void **pointers;
749         int *icons;
750
751         AutoComplete *autocpl;
752         void *active;
753 };
754
755 typedef struct uiSearchboxData {
756         rcti bbox;
757         uiFontStyle fstyle;
758         uiSearchItems items;
759         int active;     /* index in items array */
760         bool noback;    /* when menu opened with enough space for this */
761         bool preview;   /* draw thumbnail previews, rather than list */
762         int prv_rows, prv_cols;
763 } uiSearchboxData;
764
765 #define SEARCH_ITEMS    10
766
767 /* exported for use by search callbacks */
768 /* returns zero if nothing to add */
769 bool uiSearchItemAdd(uiSearchItems *items, const char *name, void *poin, int iconid)
770 {
771         /* hijack for autocomplete */
772         if (items->autocpl) {
773                 autocomplete_do_name(items->autocpl, name);
774                 return true;
775         }
776         
777         /* hijack for finding active item */
778         if (items->active) {
779                 if (poin == items->active)
780                         items->offset_i = items->totitem;
781                 items->totitem++;
782                 return true;
783         }
784         
785         if (items->totitem >= items->maxitem) {
786                 items->more = 1;
787                 return false;
788         }
789         
790         /* skip first items in list */
791         if (items->offset_i > 0) {
792                 items->offset_i--;
793                 return true;
794         }
795         
796         if (items->names)
797                 BLI_strncpy(items->names[items->totitem], name, items->maxstrlen);
798         if (items->pointers)
799                 items->pointers[items->totitem] = poin;
800         if (items->icons)
801                 items->icons[items->totitem] = iconid;
802         
803         items->totitem++;
804         
805         return true;
806 }
807
808 int uiSearchBoxHeight(void)
809 {
810         return SEARCH_ITEMS * UI_UNIT_Y + 2 * MENU_TOP;
811 }
812
813 int uiSearchBoxWidth(void)
814 {
815         /* was hardcoded at 150 */
816         return 9 * UI_UNIT_X;
817 }
818
819 int uiSearchItemFindIndex(uiSearchItems *items, const char *name)
820 {
821         int i;
822         for (i = 0; i < items->totitem; i++) {
823                 if (STREQ(name, items->names[i])) {
824                         return i;
825                 }
826         }
827         return -1;
828 }
829
830 /* ar is the search box itself */
831 static void ui_searchbox_select(bContext *C, ARegion *ar, uiBut *but, int step)
832 {
833         uiSearchboxData *data = ar->regiondata;
834         
835         /* apply step */
836         data->active += step;
837         
838         if (data->items.totitem == 0)
839                 data->active = 0;
840         else if (data->active > data->items.totitem) {
841                 if (data->items.more) {
842                         data->items.offset++;
843                         data->active = data->items.totitem;
844                         ui_searchbox_update(C, ar, but, false);
845                 }
846                 else
847                         data->active = data->items.totitem;
848         }
849         else if (data->active < 1) {
850                 if (data->items.offset) {
851                         data->items.offset--;
852                         data->active = 1;
853                         ui_searchbox_update(C, ar, but, false);
854                 }
855                 else if (data->active < 0)
856                         data->active = 0;
857         }
858         
859         ED_region_tag_redraw(ar);
860 }
861
862 static void ui_searchbox_butrect(rcti *rect, uiSearchboxData *data, int itemnr)
863 {
864         /* thumbnail preview */
865         if (data->preview) {
866                 int butw =  BLI_rcti_size_x(&data->bbox)                 / data->prv_cols;
867                 int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_TOP) / data->prv_rows;
868                 int row, col;
869                 
870                 *rect = data->bbox;
871                 
872                 col = itemnr % data->prv_cols;
873                 row = itemnr / data->prv_cols;
874                 
875                 rect->xmin += col * butw;
876                 rect->xmax = rect->xmin + butw;
877                 
878                 rect->ymax = data->bbox.ymax - MENU_TOP - (row * buth);
879                 rect->ymin = rect->ymax - buth;
880         }
881         /* list view */
882         else {
883                 int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_TOP) / SEARCH_ITEMS;
884                 
885                 *rect = data->bbox;
886                 rect->xmin = data->bbox.xmin + 3.0f;
887                 rect->xmax = data->bbox.xmax - 3.0f;
888                 
889                 rect->ymax = data->bbox.ymax - MENU_TOP - itemnr * buth;
890                 rect->ymin = rect->ymax - buth;
891         }
892         
893 }
894
895 int ui_searchbox_find_index(ARegion *ar, const char *name)
896 {
897         uiSearchboxData *data = ar->regiondata;
898         return uiSearchItemFindIndex(&data->items, name);
899 }
900
901 /* x and y in screencoords */
902 bool ui_searchbox_inside(ARegion *ar, int x, int y)
903 {
904         uiSearchboxData *data = ar->regiondata;
905         
906         return BLI_rcti_isect_pt(&data->bbox, x - ar->winrct.xmin, y - ar->winrct.ymin);
907 }
908
909 /* string validated to be of correct length (but->hardmax) */
910 bool ui_searchbox_apply(uiBut *but, ARegion *ar)
911 {
912         uiSearchboxData *data = ar->regiondata;
913
914         but->func_arg2 = NULL;
915         
916         if (data->active) {
917                 char *name = data->items.names[data->active - 1];
918                 char *cpoin = strchr(name, '|');
919                 
920                 if (cpoin) cpoin[0] = 0;
921                 BLI_strncpy(but->editstr, name, data->items.maxstrlen);
922                 if (cpoin) cpoin[0] = '|';
923                 
924                 but->func_arg2 = data->items.pointers[data->active - 1];
925
926                 return true;
927         }
928         else {
929                 return false;
930         }
931 }
932
933 void ui_searchbox_event(bContext *C, ARegion *ar, uiBut *but, const wmEvent *event)
934 {
935         uiSearchboxData *data = ar->regiondata;
936         int type = event->type, val = event->val;
937         
938         if (type == MOUSEPAN)
939                 ui_pan_to_scroll(event, &type, &val);
940         
941         switch (type) {
942                 case WHEELUPMOUSE:
943                 case UPARROWKEY:
944                         ui_searchbox_select(C, ar, but, -1);
945                         break;
946                 case WHEELDOWNMOUSE:
947                 case DOWNARROWKEY:
948                         ui_searchbox_select(C, ar, but, 1);
949                         break;
950                 case MOUSEMOVE:
951                         if (BLI_rcti_isect_pt(&ar->winrct, event->x, event->y)) {
952                                 rcti rect;
953                                 int a;
954                                 
955                                 for (a = 0; a < data->items.totitem; a++) {
956                                         ui_searchbox_butrect(&rect, data, a);
957                                         if (BLI_rcti_isect_pt(&rect, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin)) {
958                                                 if (data->active != a + 1) {
959                                                         data->active = a + 1;
960                                                         ui_searchbox_select(C, ar, but, 0);
961                                                         break;
962                                                 }
963                                         }
964                                 }
965                         }
966                         break;
967         }
968 }
969
970 /* ar is the search box itself */
971 void ui_searchbox_update(bContext *C, ARegion *ar, uiBut *but, const bool reset)
972 {
973         uiSearchboxData *data = ar->regiondata;
974         
975         /* reset vars */
976         data->items.totitem = 0;
977         data->items.more = 0;
978         if (reset == false) {
979                 data->items.offset_i = data->items.offset;
980         }
981         else {
982                 data->items.offset_i = data->items.offset = 0;
983                 data->active = 0;
984                 
985                 /* handle active */
986                 if (but->search_func && but->func_arg2) {
987                         data->items.active = but->func_arg2;
988                         but->search_func(C, but->search_arg, but->editstr, &data->items);
989                         data->items.active = NULL;
990                         
991                         /* found active item, calculate real offset by centering it */
992                         if (data->items.totitem) {
993                                 /* first case, begin of list */
994                                 if (data->items.offset_i < data->items.maxitem) {
995                                         data->active = data->items.offset_i + 1;
996                                         data->items.offset_i = 0;
997                                 }
998                                 else {
999                                         /* second case, end of list */
1000                                         if (data->items.totitem - data->items.offset_i <= data->items.maxitem) {
1001                                                 data->active = 1 + data->items.offset_i - data->items.totitem + data->items.maxitem;
1002                                                 data->items.offset_i = data->items.totitem - data->items.maxitem;
1003                                         }
1004                                         else {
1005                                                 /* center active item */
1006                                                 data->items.offset_i -= data->items.maxitem / 2;
1007                                                 data->active = 1 + data->items.maxitem / 2;
1008                                         }
1009                                 }
1010                         }
1011                         data->items.offset = data->items.offset_i;
1012                         data->items.totitem = 0;
1013                 }
1014         }
1015         
1016         /* callback */
1017         if (but->search_func)
1018                 but->search_func(C, but->search_arg, but->editstr, &data->items);
1019         
1020         /* handle case where editstr is equal to one of items */
1021         if (reset && data->active == 0) {
1022                 int a;
1023                 
1024                 for (a = 0; a < data->items.totitem; a++) {
1025                         char *cpoin = strchr(data->items.names[a], '|');
1026                         
1027                         if (cpoin) cpoin[0] = 0;
1028                         if (0 == strcmp(but->editstr, data->items.names[a]))
1029                                 data->active = a + 1;
1030                         if (cpoin) cpoin[0] = '|';
1031                 }
1032                 if (data->items.totitem == 1 && but->editstr[0])
1033                         data->active = 1;
1034         }
1035
1036         /* validate selected item */
1037         ui_searchbox_select(C, ar, but, 0);
1038         
1039         ED_region_tag_redraw(ar);
1040 }
1041
1042 void ui_searchbox_autocomplete(bContext *C, ARegion *ar, uiBut *but, char *str)
1043 {
1044         uiSearchboxData *data = ar->regiondata;
1045
1046         if (str[0]) {
1047                 data->items.autocpl = autocomplete_begin(str, ui_get_but_string_max_length(but));
1048
1049                 but->search_func(C, but->search_arg, but->editstr, &data->items);
1050
1051                 autocomplete_end(data->items.autocpl, str);
1052                 data->items.autocpl = NULL;
1053         }
1054 }
1055
1056 static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
1057 {
1058         uiSearchboxData *data = ar->regiondata;
1059         
1060         /* pixel space */
1061         wmOrtho2(-0.01f, ar->winx - 0.01f, -0.01f, ar->winy - 0.01f);
1062
1063         if (data->noback == false)
1064                 ui_draw_search_back(NULL, NULL, &data->bbox);  /* style not used yet */
1065         
1066         /* draw text */
1067         if (data->items.totitem) {
1068                 rcti rect;
1069                 int a;
1070                 
1071                 if (data->preview) {
1072                         /* draw items */
1073                         for (a = 0; a < data->items.totitem; a++) {
1074                                 ui_searchbox_butrect(&rect, data, a);
1075                                 
1076                                 /* widget itself */
1077                                 if (data->preview)
1078                                         ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a + 1) == data->active ? UI_ACTIVE : 0);
1079                                 else 
1080                                         ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a + 1) == data->active ? UI_ACTIVE : 0);
1081                         }
1082                         
1083                         /* indicate more */
1084                         if (data->items.more) {
1085                                 ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
1086                                 glEnable(GL_BLEND);
1087                                 UI_icon_draw(rect.xmax - 18, rect.ymin - 7, ICON_TRIA_DOWN);
1088                                 glDisable(GL_BLEND);
1089                         }
1090                         if (data->items.offset) {
1091                                 ui_searchbox_butrect(&rect, data, 0);
1092                                 glEnable(GL_BLEND);
1093                                 UI_icon_draw(rect.xmin, rect.ymax - 9, ICON_TRIA_UP);
1094                                 glDisable(GL_BLEND);
1095                         }
1096                         
1097                 }
1098                 else {
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_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a], (a + 1) == data->active ? UI_ACTIVE : 0);
1105                                 
1106                         }
1107                         /* indicate more */
1108                         if (data->items.more) {
1109                                 ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
1110                                 glEnable(GL_BLEND);
1111                                 UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
1112                                 glDisable(GL_BLEND);
1113                         }
1114                         if (data->items.offset) {
1115                                 ui_searchbox_butrect(&rect, data, 0);
1116                                 glEnable(GL_BLEND);
1117                                 UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
1118                                 glDisable(GL_BLEND);
1119                         }
1120                 }
1121         }
1122 }
1123
1124 static void ui_searchbox_region_free_cb(ARegion *ar)
1125 {
1126         uiSearchboxData *data = ar->regiondata;
1127         int a;
1128
1129         /* free search data */
1130         for (a = 0; a < data->items.maxitem; a++) {
1131                 MEM_freeN(data->items.names[a]);
1132         }
1133         MEM_freeN(data->items.names);
1134         MEM_freeN(data->items.pointers);
1135         MEM_freeN(data->items.icons);
1136         
1137         MEM_freeN(data);
1138         ar->regiondata = NULL;
1139 }
1140
1141 ARegion *ui_searchbox_create(bContext *C, ARegion *butregion, uiBut *but)
1142 {
1143         wmWindow *win = CTX_wm_window(C);
1144         uiStyle *style = UI_GetStyle();
1145         static ARegionType type;
1146         ARegion *ar;
1147         uiSearchboxData *data;
1148         float aspect = but->block->aspect;
1149         rctf rect_fl;
1150         rcti rect_i;
1151         int winx /*, winy */, ofsx, ofsy;
1152         int i;
1153         
1154         /* create area region */
1155         ar = ui_add_temporary_region(CTX_wm_screen(C));
1156         
1157         memset(&type, 0, sizeof(ARegionType));
1158         type.draw = ui_searchbox_region_draw_cb;
1159         type.free = ui_searchbox_region_free_cb;
1160         ar->type = &type;
1161         
1162         /* create searchbox data */
1163         data = MEM_callocN(sizeof(uiSearchboxData), "uiSearchboxData");
1164
1165         /* set font, get bb */
1166         data->fstyle = style->widget; /* copy struct */
1167         data->fstyle.align = UI_STYLE_TEXT_CENTER;
1168         ui_fontscale(&data->fstyle.points, aspect);
1169         uiStyleFontSet(&data->fstyle);
1170         
1171         ar->regiondata = data;
1172         
1173         /* special case, hardcoded feature, not draw backdrop when called from menus,
1174          * assume for design that popup already added it */
1175         if (but->block->flag & UI_BLOCK_SEARCH_MENU)
1176                 data->noback = true;
1177         
1178         if (but->a1 > 0 && but->a2 > 0) {
1179                 data->preview = true;
1180                 data->prv_rows = but->a1;
1181                 data->prv_cols = but->a2;
1182         }
1183         
1184         /* compute position */
1185         if (but->block->flag & UI_BLOCK_SEARCH_MENU) {
1186                 int width = UI_ThemeMenuShadowWidth();
1187                 /* this case is search menu inside other menu */
1188                 /* we copy region size */
1189
1190                 ar->winrct = butregion->winrct;
1191                 
1192                 /* widget rect, in region coords */
1193                 data->bbox.xmin = width;
1194                 data->bbox.xmax = BLI_rcti_size_x(&ar->winrct) - width;
1195                 data->bbox.ymin = width;
1196                 data->bbox.ymax = BLI_rcti_size_y(&ar->winrct) - width;
1197                 
1198                 /* check if button is lower half */
1199                 if (but->rect.ymax < BLI_rctf_cent_y(&but->block->rect)) {
1200                         data->bbox.ymin += BLI_rctf_size_y(&but->rect);
1201                 }
1202                 else {
1203                         data->bbox.ymax -= BLI_rctf_size_y(&but->rect);
1204                 }
1205         }
1206         else {
1207                 const int searchbox_width = uiSearchBoxWidth();
1208                 const int shadow_width = UI_ThemeMenuShadowWidth();
1209
1210                 rect_fl.xmin = but->rect.xmin - 5;   /* align text with button */
1211                 rect_fl.xmax = but->rect.xmax + 5;   /* symmetrical */
1212                 rect_fl.ymax = but->rect.ymin;
1213                 rect_fl.ymin = rect_fl.ymax - uiSearchBoxHeight();
1214
1215                 ofsx = (but->block->panel) ? but->block->panel->ofsx : 0;
1216                 ofsy = (but->block->panel) ? but->block->panel->ofsy : 0;
1217
1218                 BLI_rctf_translate(&rect_fl, ofsx, ofsy);
1219         
1220                 /* minimal width */
1221                 if (BLI_rctf_size_x(&rect_fl) < searchbox_width) {
1222                         rect_fl.xmax = rect_fl.xmin + searchbox_width;
1223                 }
1224                 
1225                 /* copy to int, gets projected if possible too */
1226                 BLI_rcti_rctf_copy(&rect_i, &rect_fl);
1227                 
1228                 if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
1229                         UI_view2d_to_region_no_clip(&butregion->v2d, rect_fl.xmin, rect_fl.ymin, &rect_i.xmin, &rect_i.ymin);
1230                         UI_view2d_to_region_no_clip(&butregion->v2d, rect_fl.xmax, rect_fl.ymax, &rect_i.xmax, &rect_i.ymax);
1231                 }
1232
1233                 BLI_rcti_translate(&rect_i, butregion->winrct.xmin, butregion->winrct.ymin);
1234
1235                 winx = WM_window_pixels_x(win);
1236                 // winy = WM_window_pixels_y(win);  /* UNUSED */
1237                 //wm_window_get_size(win, &winx, &winy);
1238                 
1239                 if (rect_i.xmax > winx) {
1240                         /* super size */
1241                         if (rect_i.xmax > winx + rect_i.xmin) {
1242                                 rect_i.xmax = winx;
1243                                 rect_i.xmin = 0;
1244                         }
1245                         else {
1246                                 rect_i.xmin -= rect_i.xmax - winx;
1247                                 rect_i.xmax = winx;
1248                         }
1249                 }
1250
1251                 if (rect_i.ymin < 0) {
1252                         int newy1;
1253                         UI_view2d_to_region_no_clip(&butregion->v2d, 0, but->rect.ymax + ofsy, NULL, &newy1);
1254                         newy1 += butregion->winrct.ymin;
1255
1256                         rect_i.ymax = BLI_rcti_size_y(&rect_i) + newy1;
1257                         rect_i.ymin = newy1;
1258                 }
1259
1260                 /* widget rect, in region coords */
1261                 data->bbox.xmin = shadow_width;
1262                 data->bbox.xmax = BLI_rcti_size_x(&rect_i) + shadow_width;
1263                 data->bbox.ymin = shadow_width;
1264                 data->bbox.ymax = BLI_rcti_size_y(&rect_i) + shadow_width;
1265                 
1266                 /* region bigger for shadow */
1267                 ar->winrct.xmin = rect_i.xmin - shadow_width;
1268                 ar->winrct.xmax = rect_i.xmax + shadow_width;
1269                 ar->winrct.ymin = rect_i.ymin - shadow_width;
1270                 ar->winrct.ymax = rect_i.ymax;
1271         }
1272         
1273         /* adds subwindow */
1274         ED_region_init(C, ar);
1275         
1276         /* notify change and redraw */
1277         ED_region_tag_redraw(ar);
1278         
1279         /* prepare search data */
1280         if (data->preview) {
1281                 data->items.maxitem = data->prv_rows * data->prv_cols;
1282         }
1283         else {
1284                 data->items.maxitem = SEARCH_ITEMS;
1285         }
1286         data->items.maxstrlen = but->hardmax;
1287         data->items.totitem = 0;
1288         data->items.names = MEM_callocN(data->items.maxitem * sizeof(void *), "search names");
1289         data->items.pointers = MEM_callocN(data->items.maxitem * sizeof(void *), "search pointers");
1290         data->items.icons = MEM_callocN(data->items.maxitem * sizeof(int), "search icons");
1291         for (i = 0; i < data->items.maxitem; i++)
1292                 data->items.names[i] = MEM_callocN(but->hardmax + 1, "search pointers");
1293         
1294         return ar;
1295 }
1296
1297 void ui_searchbox_free(bContext *C, ARegion *ar)
1298 {
1299         ui_remove_temporary_region(C, CTX_wm_screen(C), ar);
1300 }
1301
1302 /* sets red alert if button holds a string it can't find */
1303 /* XXX weak: search_func adds all partial matches... */
1304 void ui_but_search_test(uiBut *but)
1305 {
1306         uiSearchItems *items;
1307         int x1;
1308
1309         /* possibly very large lists (such as ID datablocks) only
1310          * only validate string RNA buts (not pointers) */
1311         if (but->rnaprop && RNA_property_type(but->rnaprop) != PROP_STRING) {
1312                 return;
1313         }
1314
1315         items = MEM_callocN(sizeof(uiSearchItems), "search items");
1316
1317         /* setup search struct */
1318         items->maxitem = 10;
1319         items->maxstrlen = 256;
1320         items->names = MEM_callocN(items->maxitem * sizeof(void *), "search names");
1321         for (x1 = 0; x1 < items->maxitem; x1++)
1322                 items->names[x1] = MEM_callocN(but->hardmax + 1, "search names");
1323         
1324         but->search_func(but->block->evil_C, but->search_arg, but->drawstr, items);
1325         
1326         /* only redalert when we are sure of it, this can miss cases when >10 matches */
1327         if (items->totitem == 0) {
1328                 uiButSetFlag(but, UI_BUT_REDALERT);
1329         }
1330         else if (items->more == 0) {
1331                 if (uiSearchItemFindIndex(items, but->drawstr) == -1) {
1332                         uiButSetFlag(but, UI_BUT_REDALERT);
1333                 }
1334         }
1335         
1336         for (x1 = 0; x1 < items->maxitem; x1++) {
1337                 MEM_freeN(items->names[x1]);
1338         }
1339         MEM_freeN(items->names);
1340         MEM_freeN(items);
1341 }
1342
1343
1344 /************************* Creating Menu Blocks **********************/
1345
1346 /* position block relative to but, result is in window space */
1347 static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but, uiBlock *block)
1348 {
1349         uiBut *bt;
1350         uiSafetyRct *saferct;
1351         rctf butrct;
1352         /*float aspect;*/ /*UNUSED*/
1353         int xsize, ysize, xof = 0, yof = 0, center;
1354         short dir1 = 0, dir2 = 0;
1355         
1356         /* transform to window coordinates, using the source button region/block */
1357         butrct = but->rect;
1358
1359         ui_block_to_window_fl(butregion, but->block, &butrct.xmin, &butrct.ymin);
1360         ui_block_to_window_fl(butregion, but->block, &butrct.xmax, &butrct.ymax);
1361
1362         /* widget_roundbox_set has this correction too, keep in sync */
1363         if (but->type != PULLDOWN) {
1364                 if (but->flag & UI_BUT_ALIGN_TOP)
1365                         butrct.ymax += U.pixelsize;
1366                 if (but->flag & UI_BUT_ALIGN_LEFT)
1367                         butrct.xmin -= U.pixelsize;
1368         }
1369         
1370         /* calc block rect */
1371         if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
1372                 if (block->buttons.first) {
1373                         BLI_rctf_init_minmax(&block->rect);
1374
1375                         for (bt = block->buttons.first; bt; bt = bt->next) {
1376                                 BLI_rctf_union(&block->rect, &bt->rect);
1377                         }
1378                 }
1379                 else {
1380                         /* we're nice and allow empty blocks too */
1381                         block->rect.xmin = block->rect.ymin = 0;
1382                         block->rect.xmax = block->rect.ymax = 20;
1383                 }
1384         }
1385                 
1386         /* aspect = (float)(BLI_rcti_size_x(&block->rect) + 4);*/ /*UNUSED*/
1387         ui_block_to_window_fl(butregion, but->block, &block->rect.xmin, &block->rect.ymin);
1388         ui_block_to_window_fl(butregion, but->block, &block->rect.xmax, &block->rect.ymax);
1389
1390         //block->rect.xmin -= 2.0; block->rect.ymin -= 2.0;
1391         //block->rect.xmax += 2.0; block->rect.ymax += 2.0;
1392         
1393         xsize = BLI_rctf_size_x(&block->rect) + 0.2f * UI_UNIT_X;  /* 4 for shadow */
1394         ysize = BLI_rctf_size_y(&block->rect) + 0.2f * UI_UNIT_Y;
1395         /* aspect /= (float)xsize;*/ /*UNUSED*/
1396
1397         {
1398                 int left = 0, right = 0, top = 0, down = 0;
1399                 int winx, winy;
1400                 // int offscreen;
1401
1402                 winx = WM_window_pixels_x(window);
1403                 winy = WM_window_pixels_y(window);
1404                 // wm_window_get_size(window, &winx, &winy);
1405
1406                 if (block->direction & UI_CENTER) center = ysize / 2;
1407                 else center = 0;
1408                 
1409                 /* check if there's space at all */
1410                 if (butrct.xmin - xsize > 0.0f) left = 1;
1411                 if (butrct.xmax + xsize < winx) right = 1;
1412                 if (butrct.ymin - ysize + center > 0.0f) down = 1;
1413                 if (butrct.ymax + ysize - center < winy) top = 1;
1414
1415                 if (top == 0 && down == 0) {
1416                         if (butrct.ymin - ysize < winy - butrct.ymax - ysize)
1417                                 top = 1;
1418                         else
1419                                 down = 1;
1420                 }
1421                 
1422                 dir1 = block->direction & UI_DIRECTION;
1423
1424                 /* secundary directions */
1425                 if (dir1 & (UI_TOP | UI_DOWN)) {
1426                         if (dir1 & UI_LEFT) dir2 = UI_LEFT;
1427                         else if (dir1 & UI_RIGHT) dir2 = UI_RIGHT;
1428                         dir1 &= (UI_TOP | UI_DOWN);
1429                 }
1430
1431                 if ((dir2 == 0) && (dir1 == UI_LEFT || dir1 == UI_RIGHT)) dir2 = UI_DOWN;
1432                 if ((dir2 == 0) && (dir1 == UI_TOP  || dir1 == UI_DOWN))  dir2 = UI_LEFT;
1433                 
1434                 /* no space at all? don't change */
1435                 if (left || right) {
1436                         if (dir1 == UI_LEFT && left == 0) dir1 = UI_RIGHT;
1437                         if (dir1 == UI_RIGHT && right == 0) dir1 = UI_LEFT;
1438                         /* this is aligning, not append! */
1439                         if (dir2 == UI_LEFT && right == 0) dir2 = UI_RIGHT;
1440                         if (dir2 == UI_RIGHT && left == 0) dir2 = UI_LEFT;
1441                 }
1442                 if (down || top) {
1443                         if (dir1 == UI_TOP && top == 0) dir1 = UI_DOWN;
1444                         if (dir1 == UI_DOWN && down == 0) dir1 = UI_TOP;
1445                         if (dir2 == UI_TOP && top == 0) dir2 = UI_DOWN;
1446                         if (dir2 == UI_DOWN && down == 0) dir2 = UI_TOP;
1447                 }
1448
1449                 if (dir1 == UI_LEFT) {
1450                         xof = butrct.xmin - block->rect.xmax;
1451                         if (dir2 == UI_TOP) yof = butrct.ymin - block->rect.ymin - center;
1452                         else yof = butrct.ymax - block->rect.ymax + center;
1453                 }
1454                 else if (dir1 == UI_RIGHT) {
1455                         xof = butrct.xmax - block->rect.xmin;
1456                         if (dir2 == UI_TOP) yof = butrct.ymin - block->rect.ymin - center;
1457                         else yof = butrct.ymax - block->rect.ymax + center;
1458                 }
1459                 else if (dir1 == UI_TOP) {
1460                         yof = butrct.ymax - block->rect.ymin;
1461                         if (dir2 == UI_RIGHT) xof = butrct.xmax - block->rect.xmax;
1462                         else xof = butrct.xmin - block->rect.xmin;
1463                         /* changed direction? */
1464                         if ((dir1 & block->direction) == 0) {
1465                                 if (block->direction & UI_SHIFT_FLIPPED)
1466                                         xof += dir2 == UI_LEFT ? 25 : -25;
1467                                 uiBlockFlipOrder(block);
1468                         }
1469                 }
1470                 else if (dir1 == UI_DOWN) {
1471                         yof = butrct.ymin - block->rect.ymax;
1472                         if (dir2 == UI_RIGHT) xof = butrct.xmax - block->rect.xmax;
1473                         else xof = butrct.xmin - block->rect.xmin;
1474                         /* changed direction? */
1475                         if ((dir1 & block->direction) == 0) {
1476                                 if (block->direction & UI_SHIFT_FLIPPED)
1477                                         xof += dir2 == UI_LEFT ? 25 : -25;
1478                                 uiBlockFlipOrder(block);
1479                         }
1480                 }
1481
1482                 /* and now we handle the exception; no space below or to top */
1483                 if (top == 0 && down == 0) {
1484                         if (dir1 == UI_LEFT || dir1 == UI_RIGHT) {
1485                                 /* align with bottom of screen */
1486                                 // yof = ysize; (not with menu scrolls)
1487                         }
1488                 }
1489                 
1490                 /* or no space left or right */
1491                 if (left == 0 && right == 0) {
1492                         if (dir1 == UI_TOP || dir1 == UI_DOWN) {
1493                                 /* align with left size of screen */
1494                                 xof = -block->rect.xmin + 5;
1495                         }
1496                 }
1497                 
1498 #if 0
1499                 /* clamp to window bounds, could be made into an option if its ever annoying */
1500                 if (     (offscreen = (block->rect.ymin + yof)) < 0) yof -= offscreen;   /* bottom */
1501                 else if ((offscreen = (block->rect.ymax + yof) - winy) > 0) yof -= offscreen;  /* top */
1502                 if (     (offscreen = (block->rect.xmin + xof)) < 0) xof -= offscreen;   /* left */
1503                 else if ((offscreen = (block->rect.xmax + xof) - winx) > 0) xof -= offscreen;  /* right */
1504 #endif
1505         }
1506         
1507         /* apply offset, buttons in window coords */
1508         
1509         for (bt = block->buttons.first; bt; bt = bt->next) {
1510                 ui_block_to_window_fl(butregion, but->block, &bt->rect.xmin, &bt->rect.ymin);
1511                 ui_block_to_window_fl(butregion, but->block, &bt->rect.xmax, &bt->rect.ymax);
1512
1513                 BLI_rctf_translate(&bt->rect, xof, yof);
1514
1515                 bt->aspect = 1.0f;
1516                 /* ui_check_but recalculates drawstring size in pixels */
1517                 ui_check_but(bt);
1518         }
1519         
1520         BLI_rctf_translate(&block->rect, xof, yof);
1521
1522         /* safety calculus */
1523         {
1524                 const float midx = BLI_rctf_cent_x(&butrct);
1525                 const float midy = BLI_rctf_cent_y(&butrct);
1526                 
1527                 /* when you are outside parent button, safety there should be smaller */
1528                 
1529                 /* parent button to left */
1530                 if (midx < block->rect.xmin) block->safety.xmin = block->rect.xmin - 3;
1531                 else block->safety.xmin = block->rect.xmin - 40;
1532                 /* parent button to right */
1533                 if (midx > block->rect.xmax) block->safety.xmax = block->rect.xmax + 3;
1534                 else block->safety.xmax = block->rect.xmax + 40;
1535
1536                 /* parent button on bottom */
1537                 if (midy < block->rect.ymin) block->safety.ymin = block->rect.ymin - 3;
1538                 else block->safety.ymin = block->rect.ymin - 40;
1539                 /* parent button on top */
1540                 if (midy > block->rect.ymax) block->safety.ymax = block->rect.ymax + 3;
1541                 else block->safety.ymax = block->rect.ymax + 40;
1542
1543                 /* exception for switched pulldowns... */
1544                 if (dir1 && (dir1 & block->direction) == 0) {
1545                         if (dir2 == UI_RIGHT) block->safety.xmax = block->rect.xmax + 3;
1546                         if (dir2 == UI_LEFT) block->safety.xmin = block->rect.xmin - 3;
1547                 }
1548                 block->direction = dir1;
1549         }
1550
1551         /* keep a list of these, needed for pulldown menus */
1552         saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1553         saferct->parent = butrct;
1554         saferct->safety = block->safety;
1555         BLI_freelistN(&block->saferct);
1556         BLI_duplicatelist(&block->saferct, &but->block->saferct);
1557         BLI_addhead(&block->saferct, saferct);
1558 }
1559
1560 static void ui_block_region_draw(const bContext *C, ARegion *ar)
1561 {
1562         uiBlock *block;
1563
1564         for (block = ar->uiblocks.first; block; block = block->next)
1565                 uiDrawBlock(C, block);
1566 }
1567
1568 static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
1569 {
1570         uiBut *bt;
1571         float xofs = 0.0f;
1572         int width = UI_SCREEN_MARGIN;
1573         int winx, winy;
1574
1575         if (block->flag & UI_BLOCK_NO_WIN_CLIP) {
1576                 return;
1577         }
1578
1579         winx = WM_window_pixels_x(window);
1580         winy = WM_window_pixels_y(window);
1581         
1582         /* shift menus to right if outside of view */
1583         if (block->rect.xmin < width) {
1584                 xofs = (width - block->rect.xmin);
1585                 block->rect.xmin += xofs;
1586                 block->rect.xmax += xofs;
1587         }
1588         /* or shift to left if outside of view */
1589         if (block->rect.xmax > winx - width) {
1590                 xofs = winx - width - block->rect.xmax;
1591                 block->rect.xmin += xofs;
1592                 block->rect.xmax += xofs;
1593         }
1594         
1595         if (block->rect.ymin < width)
1596                 block->rect.ymin = width;
1597         if (block->rect.ymax > winy - MENU_TOP)
1598                 block->rect.ymax = winy - MENU_TOP;
1599         
1600         /* ensure menu items draw inside left/right boundary */
1601         for (bt = block->buttons.first; bt; bt = bt->next) {
1602                 bt->rect.xmin += xofs;
1603                 bt->rect.xmax += xofs;
1604         }
1605
1606 }
1607
1608 void ui_popup_block_scrolltest(uiBlock *block)
1609 {
1610         uiBut *bt;
1611         
1612         block->flag &= ~(UI_BLOCK_CLIPBOTTOM | UI_BLOCK_CLIPTOP);
1613         
1614         for (bt = block->buttons.first; bt; bt = bt->next)
1615                 bt->flag &= ~UI_SCROLLED;
1616         
1617         if (block->buttons.first == block->buttons.last)
1618                 return;
1619         
1620         /* mark buttons that are outside boundary */
1621         for (bt = block->buttons.first; bt; bt = bt->next) {
1622                 if (bt->rect.ymin < block->rect.ymin) {
1623                         bt->flag |= UI_SCROLLED;
1624                         block->flag |= UI_BLOCK_CLIPBOTTOM;
1625                 }
1626                 if (bt->rect.ymax > block->rect.ymax) {
1627                         bt->flag |= UI_SCROLLED;
1628                         block->flag |= UI_BLOCK_CLIPTOP;
1629                 }
1630         }
1631
1632         /* mark buttons overlapping arrows, if we have them */
1633         for (bt = block->buttons.first; bt; bt = bt->next) {
1634                 if (block->flag & UI_BLOCK_CLIPBOTTOM) {
1635                         if (bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
1636                                 bt->flag |= UI_SCROLLED;
1637                 }
1638                 if (block->flag & UI_BLOCK_CLIPTOP) {
1639                         if (bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
1640                                 bt->flag |= UI_SCROLLED;
1641                 }
1642         }
1643 }
1644
1645 uiPopupBlockHandle *ui_popup_block_create(bContext *C, ARegion *butregion, uiBut *but,
1646                                           uiBlockCreateFunc create_func, uiBlockHandleCreateFunc handle_create_func,
1647                                           void *arg)
1648 {
1649         wmWindow *window = CTX_wm_window(C);
1650         static ARegionType type;
1651         ARegion *ar;
1652         uiBlock *block;
1653         uiPopupBlockHandle *handle;
1654         uiSafetyRct *saferct;
1655         int width = UI_ThemeMenuShadowWidth();
1656
1657         /* create handle */
1658         handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
1659
1660         /* store context for operator */
1661         handle->ctx_area = CTX_wm_area(C);
1662         handle->ctx_region = CTX_wm_region(C);
1663         
1664         /* create area region */
1665         ar = ui_add_temporary_region(CTX_wm_screen(C));
1666         handle->region = ar;
1667
1668         memset(&type, 0, sizeof(ARegionType));
1669         type.draw = ui_block_region_draw;
1670         ar->type = &type;
1671
1672         UI_add_region_handlers(&ar->handlers);
1673
1674         /* create ui block */
1675         if (create_func)
1676                 block = create_func(C, handle->region, arg);
1677         else
1678                 block = handle_create_func(C, handle, arg);
1679         
1680         if (block->handle) {
1681                 memcpy(block->handle, handle, sizeof(uiPopupBlockHandle));
1682                 MEM_freeN(handle);
1683                 handle = block->handle;
1684         }
1685         else
1686                 block->handle = handle;
1687
1688         ar->regiondata = handle;
1689
1690         /* set UI_BLOCK_NUMSELECT before uiEndBlock() so we get alphanumeric keys assigned */
1691         if (but) {
1692                 if (but->type == PULLDOWN) {
1693                         block->flag |= UI_BLOCK_NUMSELECT;
1694                 }
1695         }
1696         else {
1697                 block->flag |= UI_BLOCK_POPUP | UI_BLOCK_NUMSELECT;
1698         }
1699
1700         block->flag |= UI_BLOCK_LOOP;
1701
1702         if (!block->endblock)
1703                 uiEndBlock(C, block);
1704
1705         /* if this is being created from a button */
1706         if (but) {
1707                 block->aspect = but->block->aspect;
1708                 ui_block_position(window, butregion, but, block);
1709                 handle->direction = block->direction;
1710         }
1711         else {
1712                 /* keep a list of these, needed for pulldown menus */
1713                 saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
1714                 saferct->safety = block->safety;
1715                 BLI_addhead(&block->saferct, saferct);
1716         }
1717
1718         /* clip block with window boundary */
1719         ui_popup_block_clip(window, block);
1720         
1721         /* the block and buttons were positioned in window space as in 2.4x, now
1722          * these menu blocks are regions so we bring it back to region space.
1723          * additionally we add some padding for the menu shadow or rounded menus */
1724         ar->winrct.xmin = block->rect.xmin - width;
1725         ar->winrct.xmax = block->rect.xmax + width;
1726         ar->winrct.ymin = block->rect.ymin - width;
1727         ar->winrct.ymax = block->rect.ymax + MENU_TOP;
1728         
1729         ui_block_translate(block, -ar->winrct.xmin, -ar->winrct.ymin);
1730
1731         /* adds subwindow */
1732         ED_region_init(C, ar);
1733
1734         /* checks which buttons are visible, sets flags to prevent draw (do after region init) */
1735         ui_popup_block_scrolltest(block);
1736         
1737         /* get winmat now that we actually have the subwindow */
1738         wmSubWindowSet(window, ar->swinid);
1739         
1740         wm_subwindow_getmatrix(window, ar->swinid, block->winmat);
1741         
1742         /* notify change and redraw */
1743         ED_region_tag_redraw(ar);
1744
1745         return handle;
1746 }
1747
1748 void ui_popup_block_free(bContext *C, uiPopupBlockHandle *handle)
1749 {
1750         ui_remove_temporary_region(C, CTX_wm_screen(C), handle->region);
1751         
1752         if (handle->scrolltimer)
1753                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), handle->scrolltimer);
1754         
1755         MEM_freeN(handle);
1756 }
1757
1758 /***************************** Menu Button ***************************/
1759
1760 static void ui_block_func_MENUSTR(bContext *UNUSED(C), uiLayout *layout, void *arg_str)
1761 {
1762         uiBlock *block = uiLayoutGetBlock(layout);
1763         uiPopupBlockHandle *handle = block->handle;
1764         uiLayout *split, *column = NULL;
1765         uiBut *bt;
1766         MenuData *md;
1767         MenuEntry *entry;
1768         const char *instr = arg_str;
1769         int columns, rows, a, b;
1770         int column_start = 0, column_end = 0;
1771         int nbr_entries_nosepr = 0;
1772
1773         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1774         
1775         /* compute menu data */
1776         md = decompose_menu_string(instr);
1777
1778         /* Run some "tweaking" checks. */
1779         entry = md->items;
1780         for (a = 0; a < md->nitems; a++, entry++) {
1781                 if (entry->sepr) {
1782                         /* inconsistent, but menus with labels do not look good flipped */
1783                         if (entry->str[0]) {
1784                                 block->flag |= UI_BLOCK_NO_FLIP;
1785                                 nbr_entries_nosepr++;
1786                         }
1787                         /* We do not want simple separators in nbr_entries_nosepr count */
1788                         continue;
1789                 }
1790                 nbr_entries_nosepr++;
1791         }
1792
1793         /* Columns and row estimation. Ignore simple separators here. */
1794         columns = (nbr_entries_nosepr + 20) / 20;
1795         if (columns < 1)
1796                 columns = 1;
1797         if (columns > 8)
1798                 columns = (nbr_entries_nosepr + 25) / 25;
1799
1800         rows = md->nitems / columns;
1801         if (rows < 1)
1802                 rows = 1;
1803         while (rows * columns < md->nitems)
1804                 rows++;
1805
1806         /* create title */
1807         if (md->title) {
1808                 if (md->titleicon) {
1809                         uiItemL(layout, md->title, md->titleicon);
1810                 }
1811                 else {
1812                         uiItemL(layout, md->title, ICON_NONE);
1813                         bt = block->buttons.last;
1814                         bt->flag = UI_TEXT_LEFT;
1815                 }
1816         }
1817
1818         /* create items */
1819         split = uiLayoutSplit(layout, 0.0f, FALSE);
1820
1821         for (a = 0; a < md->nitems; a++) {
1822                 if (a == column_end) {
1823                         /* start new column, and find out where it ends in advance, so we
1824                          * can flip the order of items properly per column */
1825                         column_start = a;
1826                         column_end = md->nitems;
1827
1828                         for (b = a + 1; b < md->nitems; b++) {
1829                                 entry = &md->items[b];
1830
1831                                 /* new column on N rows or on separation label */
1832                                 if (((b - a) % rows == 0) || (entry->sepr && entry->str[0])) {
1833                                         column_end = b;
1834                                         break;
1835                                 }
1836                         }
1837
1838                         column = uiLayoutColumn(split, FALSE);
1839                 }
1840
1841                 if (block->flag & UI_BLOCK_NO_FLIP)
1842                         entry = &md->items[a];
1843                 else
1844                         entry = &md->items[column_start + column_end - 1 - a];
1845
1846                 if (entry->sepr) {
1847                         if (entry->str[0]) {
1848                                 uiItemL(column, entry->str, entry->icon);
1849                                 bt = block->buttons.last;
1850                                 bt->flag = UI_TEXT_LEFT;
1851                         }
1852                         else {
1853                                 uiItemS(column);
1854                         }
1855                 }
1856                 else if (entry->icon) {
1857                         uiDefIconTextButF(block, BUTM, B_NOP, entry->icon, entry->str, 0, 0,
1858                                           UI_UNIT_X * 5, UI_UNIT_Y, &handle->retvalue, (float) entry->retval, 0.0, 0, -1, "");
1859                 }
1860                 else {
1861                         uiDefButF(block, BUTM, B_NOP, entry->str, 0, 0,
1862                                   UI_UNIT_X * 5, UI_UNIT_X, &handle->retvalue, (float) entry->retval, 0.0, 0, -1, "");
1863                 }
1864         }
1865         
1866         menudata_free(md);
1867 }
1868
1869 void ui_block_func_ICONROW(bContext *UNUSED(C), uiLayout *layout, void *arg_but)
1870 {
1871         uiBlock *block = uiLayoutGetBlock(layout);
1872         uiPopupBlockHandle *handle = block->handle;
1873         uiBut *but = arg_but;
1874         int a;
1875         
1876         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1877         
1878         for (a = (int)but->hardmin; a <= (int)but->hardmax; a++)
1879                 uiDefIconButF(block, BUTM, B_NOP, but->icon + (a - but->hardmin), 0, 0, UI_UNIT_X * 5, UI_UNIT_Y,
1880                               &handle->retvalue, (float)a, 0.0, 0, -1, "");
1881 }
1882
1883 void ui_block_func_ICONTEXTROW(bContext *UNUSED(C), uiLayout *layout, void *arg_but)
1884 {
1885         uiBlock *block = uiLayoutGetBlock(layout);
1886         uiPopupBlockHandle *handle = block->handle;
1887         uiBut *but = arg_but, *bt;
1888         MenuData *md;
1889         MenuEntry *entry;
1890         int a;
1891         
1892         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
1893
1894         md = decompose_menu_string(but->str);
1895
1896         /* title */
1897         if (md->title) {
1898                 bt = uiDefBut(block, LABEL, 0, md->title, 0, 0, UI_UNIT_X * 5, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
1899                 bt->flag = UI_TEXT_LEFT;
1900         }
1901
1902         /* loop through the menu options and draw them out with icons & text labels */
1903         for (a = 0; a < md->nitems; a++) {
1904                 entry = &md->items[md->nitems - a - 1];
1905
1906                 if (entry->sepr)
1907                         uiItemS(layout);
1908                 else
1909                         uiDefIconTextButF(block, BUTM, B_NOP, (short)((but->icon) + (entry->retval - but->hardmin)), entry->str,
1910                                           0, 0, UI_UNIT_X * 5, UI_UNIT_Y, &handle->retvalue, (float) entry->retval, 0.0, 0, -1, "");
1911         }
1912
1913         menudata_free(md);
1914 }
1915
1916 #if 0
1917 static void ui_warp_pointer(int x, int y)
1918 {
1919         /* XXX 2.50 which function to use for this? */
1920         /* OSX has very poor mouse-warp support, it sends events;
1921          * this causes a menu being pressed immediately ... */
1922 #  ifndef __APPLE__
1923         warp_pointer(x, y);
1924 #  endif
1925 }
1926 #endif
1927
1928 /********************* Color Button ****************/
1929
1930 /* for picker, while editing hsv */
1931 void ui_set_but_hsv(uiBut *but)
1932 {
1933         float col[3];
1934         float *hsv = ui_block_hsv_get(but->block);
1935         
1936         hsv_to_rgb_v(hsv, col);
1937         ui_set_but_vectorf(but, col);
1938 }
1939
1940 /* also used by small picker, be careful with name checks below... */
1941 static void ui_update_block_buts_rgb(uiBlock *block, const float rgb[3])
1942 {
1943         uiBut *bt;
1944         float *hsv = ui_block_hsv_get(block);
1945         struct ColorManagedDisplay *display = NULL;
1946         
1947         /* this is to keep the H and S value when V is equal to zero
1948          * and we are working in HSV mode, of course!
1949          */
1950         rgb_to_hsv_compat_v(rgb, hsv);
1951
1952         if (block->color_profile)
1953                 display = ui_block_display_get(block);
1954         
1955         /* this updates button strings, is hackish... but button pointers are on stack of caller function */
1956         for (bt = block->buttons.first; bt; bt = bt->next) {
1957                 if (bt->rnaprop) {
1958                         
1959                         ui_set_but_vectorf(bt, rgb);
1960                         
1961                 }
1962                 else if (strcmp(bt->str, "Hex: ") == 0) {
1963                         float rgb_gamma[3];
1964                         double intpart;
1965                         char col[16];
1966                         
1967                         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
1968                         
1969                         copy_v3_v3(rgb_gamma, rgb);
1970
1971                         if (display) {
1972                                 /* make a display version, for Hex code */
1973                                 IMB_colormanagement_scene_linear_to_display_v3(rgb_gamma, display);
1974                         }
1975                         
1976                         if (rgb_gamma[0] > 1.0f) rgb_gamma[0] = modf(rgb_gamma[0], &intpart);
1977                         if (rgb_gamma[1] > 1.0f) rgb_gamma[1] = modf(rgb_gamma[1], &intpart);
1978                         if (rgb_gamma[2] > 1.0f) rgb_gamma[2] = modf(rgb_gamma[2], &intpart);
1979
1980                         BLI_snprintf(col, sizeof(col), "%02X%02X%02X",
1981                                      FTOCHAR(rgb_gamma[0]), FTOCHAR(rgb_gamma[1]), FTOCHAR(rgb_gamma[2]));
1982                         
1983                         strcpy(bt->poin, col);
1984                 }
1985                 else if (bt->str[1] == ' ') {
1986                         if (bt->str[0] == 'R') {
1987                                 ui_set_but_val(bt, rgb[0]);
1988                         }
1989                         else if (bt->str[0] == 'G') {
1990                                 ui_set_but_val(bt, rgb[1]);
1991                         }
1992                         else if (bt->str[0] == 'B') {
1993                                 ui_set_but_val(bt, rgb[2]);
1994                         }
1995                         else if (bt->str[0] == 'H') {
1996                                 ui_set_but_val(bt, hsv[0]);
1997                         }
1998                         else if (bt->str[0] == 'S') {
1999                                 ui_set_but_val(bt, hsv[1]);
2000                         }
2001                         else if (bt->str[0] == 'V') {
2002                                 ui_set_but_val(bt, hsv[2]);
2003                         }
2004                 }
2005
2006                 ui_check_but(bt);
2007         }
2008 }
2009
2010 static void do_picker_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2011 {
2012         uiBut *but = (uiBut *)bt1;
2013         uiPopupBlockHandle *popup = but->block->handle;
2014         PropertyRNA *prop = but->rnaprop;
2015         PointerRNA ptr = but->rnapoin;
2016         float rgb[4];
2017         
2018         if (prop) {
2019                 RNA_property_float_get_array(&ptr, prop, rgb);
2020                 ui_update_block_buts_rgb(but->block, rgb);
2021         }
2022         
2023         if (popup)
2024                 popup->menuretval = UI_RETURN_UPDATE;
2025 }
2026
2027 static void do_hsv_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2028 {
2029         uiBut *but = (uiBut *)bt1;
2030         uiPopupBlockHandle *popup = but->block->handle;
2031         float rgb[3];
2032         float *hsv = ui_block_hsv_get(but->block);
2033         
2034         hsv_to_rgb_v(hsv, rgb);
2035         
2036         ui_update_block_buts_rgb(but->block, rgb);
2037         
2038         if (popup)
2039                 popup->menuretval = UI_RETURN_UPDATE;
2040 }
2041
2042 static void do_hex_rna_cb(bContext *UNUSED(C), void *bt1, void *hexcl)
2043 {
2044         uiBut *but = (uiBut *)bt1;
2045         uiPopupBlockHandle *popup = but->block->handle;
2046         char *hexcol = (char *)hexcl;
2047         float rgb[3];
2048         
2049         hex_to_rgb(hexcol, rgb, rgb + 1, rgb + 2);
2050         
2051         /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
2052         if (but->block->color_profile) {
2053                 /* so we need to linearise it for Blender */
2054                 ui_block_to_scene_linear_v3(but->block, rgb);
2055         }
2056         
2057         ui_update_block_buts_rgb(but->block, rgb);
2058         
2059         if (popup)
2060                 popup->menuretval = UI_RETURN_UPDATE;
2061 }
2062
2063 static void close_popup_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2064 {
2065         uiBut *but = (uiBut *)bt1;
2066         uiPopupBlockHandle *popup = but->block->handle;
2067         
2068         if (popup)
2069                 popup->menuretval = UI_RETURN_OK;
2070 }
2071
2072 static void picker_new_hide_reveal(uiBlock *block, short colormode)
2073 {
2074         uiBut *bt;
2075         
2076         /* tag buttons */
2077         for (bt = block->buttons.first; bt; bt = bt->next) {
2078                 if (bt->func == do_picker_rna_cb && bt->type == NUMSLI && bt->rnaindex != 3) {
2079                         /* RGB sliders (color circle and alpha are always shown) */
2080                         if (colormode == 0) bt->flag &= ~UI_HIDDEN;
2081                         else bt->flag |= UI_HIDDEN;
2082                 }
2083                 else if (bt->func == do_hsv_rna_cb) {
2084                         /* HSV sliders */
2085                         if (colormode == 1) bt->flag &= ~UI_HIDDEN;
2086                         else bt->flag |= UI_HIDDEN;
2087                 }
2088                 else if (bt->func == do_hex_rna_cb || bt->type == LABEL) {
2089                         /* hex input or gamma correction status label */
2090                         if (colormode == 2) bt->flag &= ~UI_HIDDEN;
2091                         else bt->flag |= UI_HIDDEN;
2092                 }
2093         }
2094 }
2095
2096 static void do_picker_new_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
2097 {
2098         uiBut *bt = bt1;
2099         short colormode = ui_get_but_val(bt);
2100         picker_new_hide_reveal(bt->block, colormode);
2101 }
2102
2103 #define PICKER_H    (7.5f * U.widget_unit)
2104 #define PICKER_W    (7.5f * U.widget_unit)
2105 #define PICKER_SPACE    (0.3f * U.widget_unit)
2106 #define PICKER_BAR      (0.7f * U.widget_unit)
2107
2108 #define PICKER_TOTAL_W  (PICKER_W + PICKER_SPACE + PICKER_BAR)
2109
2110 static void circle_picker(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop)
2111 {
2112         uiBut *bt;
2113         
2114         /* HS circle */
2115         bt = uiDefButR_prop(block, HSVCIRCLE, 0, "", 0, 0, PICKER_H, PICKER_W, ptr, prop, -1, 0.0, 0.0, 0, 0, "Color");
2116         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2117         
2118         /* value */
2119         bt = uiDefButR_prop(block, HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H, ptr, prop, -1, 0.0, 0.0, UI_GRAD_V_ALT, 0, "Value");
2120         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2121 }
2122
2123
2124 static void square_picker(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int type)
2125 {
2126         uiBut *bt;
2127         int bartype = type + 3;
2128         
2129         /* HS square */
2130         bt = uiDefButR_prop(block, HSVCUBE, 0, "",   0, PICKER_BAR + PICKER_SPACE, PICKER_TOTAL_W, PICKER_H, ptr, prop, -1, 0.0, 0.0, type, 0, "Color");
2131         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2132         
2133         /* value */
2134         bt = uiDefButR_prop(block, HSVCUBE, 0, "",       0, 0, PICKER_TOTAL_W, PICKER_BAR, ptr, prop, -1, 0.0, 0.0, bartype, 0, "Value");
2135         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2136 }
2137
2138
2139 /* a HS circle, V slider, rgb/hsv/hex sliders */
2140 static void uiBlockPicker(uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop, int show_picker)
2141 {
2142         static short colormode = 0;  /* temp? 0=rgb, 1=hsv, 2=hex */
2143         uiBut *bt;
2144         int width, butwidth;
2145         static char tip[50];
2146         static char hexcol[128];
2147         float rgb_gamma[3];
2148         float min, max, step, precision;
2149         float *hsv = ui_block_hsv_get(block);
2150         int yco;
2151         
2152         ui_block_hsv_get(block);
2153         
2154         width = PICKER_TOTAL_W;
2155         butwidth = width - 1.5f * UI_UNIT_X;
2156         
2157         /* existence of profile means storage is in linear color space, with display correction */
2158         /* XXX That tip message is not use anywhere! */
2159         if (!block->color_profile) {
2160                 BLI_strncpy(tip, N_("Value in Display Color Space"), sizeof(tip));
2161                 copy_v3_v3(rgb_gamma, rgba);
2162         }
2163         else {
2164                 BLI_strncpy(tip, N_("Value in Linear RGB Color Space"), sizeof(tip));
2165
2166                 /* make a display version, for Hex code */
2167                 copy_v3_v3(rgb_gamma, rgba);
2168                 ui_block_to_display_space_v3(block, rgb_gamma);
2169         }
2170         
2171         /* sneaky way to check for alpha */
2172         rgba[3] = FLT_MAX;
2173
2174         RNA_property_float_ui_range(ptr, prop, &min, &max, &step, &precision);
2175         RNA_property_float_get_array(ptr, prop, rgba);
2176
2177         switch (U.color_picker_type) {
2178                 case USER_CP_CIRCLE:
2179                         circle_picker(block, ptr, prop);
2180                         break;
2181                 case USER_CP_SQUARE_SV:
2182                         square_picker(block, ptr, prop, UI_GRAD_SV);
2183                         break;
2184                 case USER_CP_SQUARE_HS:
2185                         square_picker(block, ptr, prop, UI_GRAD_HS);
2186                         break;
2187                 case USER_CP_SQUARE_HV:
2188                         square_picker(block, ptr, prop, UI_GRAD_HV);
2189                         break;
2190         }
2191         
2192         /* mode */
2193         yco = -1.5f * UI_UNIT_Y;
2194         uiBlockBeginAlign(block);
2195         bt = uiDefButS(block, ROW, 0, IFACE_("RGB"), 0, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 0.0, 0, 0, "");
2196         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2197         bt = uiDefButS(block, ROW, 0, IFACE_("HSV"), width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
2198         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2199         bt = uiDefButS(block, ROW, 0, IFACE_("Hex"), 2 * width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 2.0, 0, 0, "");
2200         uiButSetFunc(bt, do_picker_new_mode_cb, bt, NULL);
2201         uiBlockEndAlign(block);
2202
2203         yco = -3.0f * UI_UNIT_Y;
2204         if (show_picker) {
2205                 bt = uiDefIconButO(block, BUT, "UI_OT_eyedropper", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth + 10, yco, UI_UNIT_X, UI_UNIT_Y, NULL);
2206                 uiButSetFunc(bt, close_popup_cb, bt, NULL);
2207         }
2208         
2209         /* RGB values */
2210         uiBlockBeginAlign(block);
2211         bt = uiDefButR_prop(block, NUMSLI, 0, IFACE_("R "),  0, yco, butwidth, UI_UNIT_Y, ptr, prop, 0, 0.0, 0.0, 0, 3, TIP_("Red"));
2212         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2213         bt = uiDefButR_prop(block, NUMSLI, 0, IFACE_("G "),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 1, 0.0, 0.0, 0, 3, TIP_("Green"));
2214         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2215         bt = uiDefButR_prop(block, NUMSLI, 0, IFACE_("B "),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 2, 0.0, 0.0, 0, 3, TIP_("Blue"));
2216         uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2217
2218         /* could use uiItemFullR(col, ptr, prop, -1, 0, UI_ITEM_R_EXPAND|UI_ITEM_R_SLIDER, "", ICON_NONE);
2219          * but need to use uiButSetFunc for updating other fake buttons */
2220         
2221         /* HSV values */
2222         yco = -3.0f * UI_UNIT_Y;
2223         uiBlockBeginAlign(block);
2224         bt = uiDefButF(block, NUMSLI, 0, IFACE_("H "),   0, yco, butwidth, UI_UNIT_Y, hsv, 0.0, 1.0, 10, 3, TIP_("Hue"));
2225         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2226         bt = uiDefButF(block, NUMSLI, 0, IFACE_("S "),   0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 1, 0.0, 1.0, 10, 3, TIP_("Saturation"));
2227         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2228         bt = uiDefButF(block, NUMSLI, 0, IFACE_("V "),   0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 2, 0.0, max, 10, 3, TIP_("Value"));
2229         uiButSetFunc(bt, do_hsv_rna_cb, bt, hsv);
2230         uiBlockEndAlign(block);
2231
2232         if (rgba[3] != FLT_MAX) {
2233                 bt = uiDefButR_prop(block, NUMSLI, 0, IFACE_("A "),  0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 3, 0.0, 0.0, 0, 3, TIP_("Alpha"));
2234                 uiButSetFunc(bt, do_picker_rna_cb, bt, NULL);
2235         }
2236         else {
2237                 rgba[3] = 1.0f;
2238         }
2239
2240         BLI_snprintf(hexcol, sizeof(hexcol), "%02X%02X%02X", FTOCHAR(rgb_gamma[0]), FTOCHAR(rgb_gamma[1]), FTOCHAR(rgb_gamma[2]));
2241
2242         yco = -3.0f * UI_UNIT_Y;
2243         bt = uiDefBut(block, TEX, 0, IFACE_("Hex: "), 0, yco, butwidth, UI_UNIT_Y, hexcol, 0, 8, 0, 0, TIP_("Hex triplet for color (#RRGGBB)"));
2244         uiButSetFunc(bt, do_hex_rna_cb, bt, hexcol);
2245         uiDefBut(block, LABEL, 0, IFACE_("(Gamma Corrected)"), 0, yco - UI_UNIT_Y, butwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2246
2247         rgb_to_hsv_v(rgba, hsv);
2248
2249         picker_new_hide_reveal(block, colormode);
2250 }
2251
2252
2253 static int ui_picker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *block, const wmEvent *event)
2254 {
2255         float add = 0.0f;
2256         
2257         if (event->type == WHEELUPMOUSE)
2258                 add = 0.05f;
2259         else if (event->type == WHEELDOWNMOUSE)
2260                 add = -0.05f;
2261         
2262         if (add != 0.0f) {
2263                 uiBut *but;
2264                 
2265                 for (but = block->buttons.first; but; but = but->next) {
2266                         if (but->type == HSVCUBE && but->active == NULL) {
2267                                 uiPopupBlockHandle *popup = block->handle;
2268                                 float rgb[3];
2269                                 float *hsv = ui_block_hsv_get(block);
2270                                 
2271                                 ui_get_but_vectorf(but, rgb);
2272                                 
2273                                 rgb_to_hsv_compat_v(rgb, hsv);
2274                                 hsv[2] = CLAMPIS(hsv[2] + add, 0.0f, 1.0f);
2275                                 hsv_to_rgb_v(hsv, rgb);
2276
2277                                 ui_set_but_vectorf(but, rgb);
2278                                 
2279                                 ui_update_block_buts_rgb(block, rgb);
2280                                 if (popup)
2281                                         popup->menuretval = UI_RETURN_UPDATE;
2282                                 
2283                                 return 1;
2284                         }
2285                 }
2286         }
2287         return 0;
2288 }
2289
2290 uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_but)
2291 {
2292         uiBut *but = arg_but;
2293         uiBlock *block;
2294         bool show_picker = true;
2295         
2296         block = uiBeginBlock(C, handle->region, __func__, UI_EMBOSS);
2297         
2298         if (but->rnaprop) {
2299                 if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
2300                         block->color_profile = FALSE;
2301                 }
2302         }
2303
2304         if (but->block) {
2305                 /* if color block is invoked from a popup we wouldn't be able to set color properly
2306                  * this is because color picker will close popups first and then will try to figure
2307                  * out active button RNA, and of course it'll fail
2308                  */
2309                 show_picker = (but->block->flag & UI_BLOCK_POPUP) == 0;
2310         }
2311         
2312         copy_v3_v3(handle->retvec, but->editvec);
2313         
2314         uiBlockPicker(block, handle->retvec, &but->rnapoin, but->rnaprop, show_picker);
2315         
2316         block->flag = UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_KEEP_OPEN | UI_BLOCK_OUT_1 | UI_BLOCK_MOVEMOUSE_QUIT;
2317         uiBoundsBlock(block, 0.5 * UI_UNIT_X);
2318         
2319         block->block_event_func = ui_picker_small_wheel_cb;
2320         
2321         /* and lets go */
2322         block->direction = UI_TOP;
2323         
2324         return block;
2325 }
2326
2327 /************************ Popup Menu Memory ****************************/
2328
2329 static int ui_popup_string_hash(const char *str)
2330 {
2331         /* sometimes button contains hotkey, sometimes not, strip for proper compare */
2332         int hash;
2333         char *delimit = strchr(str, '|');
2334
2335         if (delimit) *delimit = 0;
2336         hash = BLI_ghashutil_strhash(str);
2337         if (delimit) *delimit = '|';
2338
2339         return hash;
2340 }
2341
2342 static int ui_popup_menu_hash(const char *str)
2343 {
2344         return BLI_ghashutil_strhash(str);
2345 }
2346
2347 /* but == NULL read, otherwise set */
2348 uiBut *ui_popup_menu_memory(uiBlock *block, uiBut *but)
2349 {
2350         static int mem[256], first = 1;
2351         int hash = block->puphash;
2352         
2353         if (first) {
2354                 /* init */
2355                 memset(mem, -1, sizeof(mem));
2356                 first = 0;
2357         }
2358
2359         if (but) {
2360                 /* set */
2361                 mem[hash & 255] = ui_popup_string_hash(but->str);
2362                 return NULL;
2363         }
2364         else {
2365                 /* get */
2366                 for (but = block->buttons.first; but; but = but->next)
2367                         if (ui_popup_string_hash(but->str) == mem[hash & 255])
2368                                 return but;
2369
2370                 return NULL;
2371         }
2372 }
2373
2374 /******************** Popup Menu with callback or string **********************/
2375
2376 struct uiPopupMenu {
2377         uiBlock *block;
2378         uiLayout *layout;
2379         uiBut *but;
2380
2381         int mx, my;
2382         bool popup, slideout;
2383
2384         uiMenuCreateFunc menu_func;
2385         void *menu_arg;
2386 };
2387
2388 static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, void *arg_pup)
2389 {
2390         uiBlock *block;
2391         uiBut *bt;
2392         uiPopupMenu *pup = arg_pup;
2393         int offset[2], direction, minwidth, width, height, flip;
2394
2395         if (pup->menu_func) {
2396                 pup->block->handle = handle;
2397                 pup->menu_func(C, pup->layout, pup->menu_arg);
2398                 pup->block->handle = NULL;
2399         }
2400
2401         if (pup->but) {
2402                 /* minimum width to enforece */
2403                 minwidth = BLI_rctf_size_x(&pup->but->rect);
2404
2405                 if (pup->but->type == PULLDOWN || pup->but->menu_create_func) {
2406                         direction = UI_DOWN;
2407                         flip = 1;
2408                 }
2409                 else {
2410                         direction = UI_TOP;
2411                         flip = 0;
2412                 }
2413         }
2414         else {
2415                 minwidth = 50;
2416                 direction = UI_DOWN;
2417                 flip = 1;
2418         }
2419
2420         block = pup->block;
2421         
2422         /* in some cases we create the block before the region,
2423          * so we set it delayed here if necessary */
2424         if (BLI_findindex(&handle->region->uiblocks, block) == -1)
2425                 uiBlockSetRegion(block, handle->region);
2426
2427         block->direction = direction;
2428
2429         uiBlockLayoutResolve(block, &width, &height);
2430
2431         uiBlockSetFlag(block, UI_BLOCK_MOVEMOUSE_QUIT);
2432         
2433         if (pup->popup) {
2434                 uiBlockSetFlag(block, UI_BLOCK_LOOP | UI_BLOCK_REDRAW | UI_BLOCK_NUMSELECT);
2435                 uiBlockSetDirection(block, direction);
2436
2437                 /* offset the mouse position, possibly based on earlier selection */
2438                 if ((block->flag & UI_BLOCK_POPUP_MEMORY) &&
2439                     (bt = ui_popup_menu_memory(block, NULL)))
2440                 {
2441                         /* position mouse on last clicked item, at 0.8*width of the
2442                          * button, so it doesn't overlap the text too much, also note
2443                          * the offset is negative because we are inverse moving the
2444                          * block to be under the mouse */
2445                         offset[0] = -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect));
2446                         offset[1] = -(bt->rect.ymin + 0.5f * UI_UNIT_Y);
2447                 }
2448                 else {
2449                         /* position mouse at 0.8*width of the button and below the tile
2450                          * on the first item */
2451                         offset[0] = 0;
2452                         for (bt = block->buttons.first; bt; bt = bt->next)
2453                                 offset[0] = min_ii(offset[0], -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect)));
2454
2455                         offset[1] = 1.5 * UI_UNIT_Y;
2456                 }
2457
2458                 block->minbounds = minwidth;
2459                 uiMenuPopupBoundsBlock(block, 1, offset[0], offset[1]);
2460         }
2461         else {
2462                 /* for a header menu we set the direction automatic */
2463                 if (!pup->slideout && flip) {
2464                         ScrArea *sa = CTX_wm_area(C);
2465                         if (sa && sa->headertype == HEADERDOWN) {
2466                                 ARegion *ar = CTX_wm_region(C);
2467                                 if (ar && ar->regiontype == RGN_TYPE_HEADER) {
2468                                         uiBlockSetDirection(block, UI_TOP);
2469                                         uiBlockFlipOrder(block);
2470                                 }
2471                         }
2472                 }
2473
2474                 block->minbounds = minwidth;
2475                 uiTextBoundsBlock(block, 2.5 * UI_UNIT_X);
2476         }
2477
2478         /* if menu slides out of other menu, override direction */
2479         if (pup->slideout)
2480                 uiBlockSetDirection(block, UI_RIGHT);
2481
2482         uiEndBlock(C, block);
2483
2484         return pup->block;
2485 }
2486
2487 uiPopupBlockHandle *ui_popup_menu_create(bContext *C, ARegion *butregion, uiBut *but,
2488                                          uiMenuCreateFunc menu_func, void *arg, char *str)
2489 {
2490         wmWindow *window = CTX_wm_window(C);
2491         uiStyle *style = UI_GetStyleDraw();
2492         uiPopupBlockHandle *handle;
2493         uiPopupMenu *pup;
2494         pup = MEM_callocN(sizeof(uiPopupMenu), __func__);
2495         pup->block = uiBeginBlock(C, NULL, __func__, UI_EMBOSSP);
2496         pup->block->flag |= UI_BLOCK_NUMSELECT;  /* default menus to numselect */
2497         pup->layout = uiBlockLayout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, style);
2498         pup->slideout = but ? ui_block_is_menu(but->block) : false;
2499         pup->but = but;
2500         uiLayoutSetOperatorContext(pup->layout, WM_OP_INVOKE_REGION_WIN);
2501
2502         if (!but) {
2503                 /* no button to start from, means we are a popup */
2504                 pup->mx = window->eventstate->x;
2505                 pup->my = window->eventstate->y;
2506                 pup->popup = true;
2507                 pup->block->flag |= UI_BLOCK_NO_FLIP;
2508         }
2509         /* some enums reversing is strange, currently we have no good way to
2510          * reverse some enum's but not others, so reverse all so the first menu
2511          * items are always close to the mouse cursor */
2512         else {
2513 #if 0
2514                 /* if this is an rna button then we can assume its an enum
2515                  * flipping enums is generally not good since the order can be
2516                  * important [#28786] */
2517                 if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
2518                         pup->block->flag |= UI_BLOCK_NO_FLIP;
2519                 }
2520 #endif
2521                 if (but->context)
2522                         uiLayoutContextCopy(pup->layout, but->context);
2523         }
2524
2525         if (str) {
2526                 /* menu is created from a string */
2527                 pup->menu_func = ui_block_func_MENUSTR;
2528                 pup->menu_arg = str;
2529         }
2530         else {
2531                 /* menu is created from a callback */
2532                 pup->menu_func = menu_func;
2533                 pup->menu_arg = arg;
2534         }
2535         
2536         handle = ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
2537
2538         if (!but) {
2539                 handle->popup = true;
2540
2541                 UI_add_popup_handlers(C, &window->modalhandlers, handle);
2542                 WM_event_add_mousemove(C);
2543         }
2544         
2545         MEM_freeN(pup);
2546
2547         return handle;
2548 }
2549
2550 /******************** Popup Menu API with begin and end ***********************/
2551
2552 /* only return handler, and set optional title */
2553 uiPopupMenu *uiPupMenuBegin(bContext *C, const char *title, int icon)
2554 {
2555         uiStyle *style = UI_GetStyleDraw();
2556         uiPopupMenu *pup = MEM_callocN(sizeof(uiPopupMenu), "popup menu");
2557         uiBut *but;
2558         
2559         pup->block = uiBeginBlock(C, NULL, __func__, UI_EMBOSSP);
2560         pup->block->flag |= UI_BLOCK_POPUP_MEMORY;
2561         pup->block->puphash = ui_popup_menu_hash(title);
2562         pup->layout = uiBlockLayout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, style);
2563
2564         /* note, this intentionally differs from the menu & submenu default because many operators
2565          * use popups like this to select one of their options - where having invoke doesn't make sense */
2566         uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
2567
2568         /* create in advance so we can let buttons point to retval already */
2569         pup->block->handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
2570         
2571         /* create title button */
2572         if (title && title[0]) {
2573                 char titlestr[256];
2574                 
2575                 if (icon) {
2576                         BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
2577                         uiDefIconTextBut(pup->block, LABEL, 0, icon, titlestr, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2578                 }
2579                 else {
2580                         but = uiDefBut(pup->block, LABEL, 0, title, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
2581                         but->flag = UI_TEXT_LEFT;
2582                 }
2583         }
2584
2585         return pup;
2586 }
2587
2588 /* set the whole structure to work */
2589 void uiPupMenuEnd(bContext *C, uiPopupMenu *pup)
2590 {
2591         wmWindow *window = CTX_wm_window(C);
2592         uiPopupBlockHandle *menu;
2593         
2594         pup->popup = true;
2595         pup->mx = window->eventstate->x;
2596         pup->my = window->eventstate->y;
2597         
2598         menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_POPUP, pup);
2599         menu->popup = true;
2600         
2601         UI_add_popup_handlers(C, &window->modalhandlers, menu);
2602         WM_event_add_mousemove(C);
2603         
2604         MEM_freeN(pup);
2605 }
2606
2607 uiLayout *uiPupMenuLayout(uiPopupMenu *pup)
2608 {
2609         return pup->layout;
2610 }
2611
2612 /*************************** Standard Popup Menus ****************************/
2613
2614 static void operator_name_cb(bContext *C, void *arg, int retval)
2615 {
2616         const char *opname = arg;
2617
2618         if (opname && retval > 0)
2619                 WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
2620 }
2621
2622 static void operator_cb(bContext *C, void *arg, int retval)
2623 {
2624         wmOperator *op = arg;
2625         
2626         if (op && retval > 0)
2627                 WM_operator_call(C, op);
2628         else
2629                 WM_operator_free(op);
2630 }
2631
2632 static void confirm_cancel_operator(bContext *UNUSED(C), void *opv)
2633 {
2634         WM_operator_free(opv);
2635 }
2636
2637 static void vconfirm_opname(bContext *C, const char *opname, const char *title, const char *itemfmt, va_list ap)
2638 #ifdef __GNUC__
2639 __attribute__ ((format(printf, 4, 0)))
2640 #endif
2641 ;
2642 static void vconfirm_opname(bContext *C, const char *opname, const char *title, const char *itemfmt, va_list ap)
2643 {
2644         uiPopupBlockHandle *handle;
2645         char *s, buf[512];
2646
2647         s = buf;
2648         if (title) s += sprintf(s, "%s%%t|", title);
2649         vsnprintf(s, sizeof(buf) - (s - buf), itemfmt, ap);
2650         buf[sizeof(buf) - 1] = '\0';
2651
2652         handle = ui_popup_menu_create(C, NULL, NULL, NULL, NULL, buf);
2653
2654         handle->popup_func = operator_name_cb;
2655         handle->popup_arg = (void *)opname;
2656 }
2657
2658 static void confirm_operator(bContext *C, wmOperator *op, const char *title, const char *item)
2659 {
2660         uiPopupBlockHandle *handle;
2661         char *s, buf[512];
2662         
2663         s = buf;
2664         if (title) s += BLI_snprintf(s, sizeof(buf), "%s%%t|%s", title, item);
2665         (void)s;
2666         
2667         handle = ui_popup_menu_create(C, NULL, NULL, NULL, NULL, buf);
2668
2669         handle->popup_func = operator_cb;
2670         handle->popup_arg = op;
2671         handle->cancel_func = confirm_cancel_operator;
2672 }
2673
2674 void uiPupMenuOkee(bContext *C, const char *opname, const char *str, ...)
2675 {
2676         va_list ap;
2677         char titlestr[256];
2678
2679         BLI_snprintf(titlestr, sizeof(titlestr), IFACE_("OK? %%i%d"), ICON_QUESTION);
2680
2681         va_start(ap, str);
2682         vconfirm_opname(C, opname, titlestr, str, ap);
2683         va_end(ap);
2684 }
2685
2686 /* note, only call this is the file exists,
2687  * the case where the file does not exist so can be saved without a
2688  * popup must be checked for already, since saving from here
2689  * will free the operator which will break invoke().
2690  * The operator state for this is implicitly OPERATOR_RUNNING_MODAL */
2691 void uiPupMenuSaveOver(bContext *C, wmOperator *op, const char *filename)
2692 {
2693         confirm_operator(C, op, IFACE_("Save Over?"), filename);
2694 }
2695
2696 void uiPupMenuNotice(bContext *C, const char *str, ...)
2697 {
2698         va_list ap;
2699
2700         va_start(ap, str);
2701         vconfirm_opname(C, NULL, NULL, str, ap);
2702         va_end(ap);
2703 }
2704
2705 void uiPupMenuError(bContext *C, const char *str, ...)
2706 {
2707         va_list ap;
2708         char nfmt[256];
2709         char titlestr[256];
2710
2711         BLI_snprintf(titlestr, sizeof(titlestr), IFACE_("Error %%i%d"), ICON_ERROR);
2712
2713         BLI_strncpy(nfmt, str, sizeof(nfmt));
2714
2715         va_start(ap, str);
2716         vconfirm_opname(C, NULL, titlestr, nfmt, ap);
2717         va_end(ap);
2718 }
2719
2720 void uiPupMenuReports(bContext *C, ReportList *reports)
2721 {
2722         Report *report;
2723         DynStr *ds;
2724         char *str;
2725
2726         if (!reports || !reports->list.first)
2727                 return;
2728         if (!CTX_wm_window(C))
2729                 return;
2730
2731         ds = BLI_dynstr_new();
2732
2733         for (report = reports->list.first; report; report = report->next) {
2734                 if (report->type < reports->printlevel) {
2735                         /* pass */
2736                 }
2737                 else if (report->type >= RPT_ERROR) {
2738                         BLI_dynstr_appendf(ds, IFACE_("Error %%i%d%%t|%s"), ICON_ERROR, report->message);
2739                 }
2740                 else if (report->type >= RPT_WARNING) {
2741                         BLI_dynstr_appendf(ds, IFACE_("Warning %%i%d%%t|%s"), ICON_ERROR, report->message);
2742                 }
2743                 else if (report->type >= RPT_INFO) {
2744                         BLI_dynstr_appendf(ds, IFACE_("Info %%i%d%%t|%s"), ICON_INFO, report->message);
2745                 }
2746         }
2747
2748         str = BLI_dynstr_get_cstring(ds);
2749         if (str[0] != '\0')
2750                 ui_popup_menu_create(C, NULL, NULL, NULL, NULL, str);
2751         MEM_freeN(str);
2752
2753         BLI_dynstr_free(ds);
2754 }
2755
2756 void uiPupMenuInvoke(bContext *C, const char *idname)
2757 {
2758         uiPopupMenu *pup;
2759         uiLayout *layout;
2760         Menu menu;
2761         MenuType *mt = WM_menutype_find(idname, true);
2762
2763         if (mt == NULL) {
2764                 printf("%s: named menu \"%s\" not found\n", __func__, idname);
2765                 return;
2766         }
2767
2768         if (mt->poll && mt->poll(C, mt) == 0)
2769                 return;
2770
2771         pup = uiPupMenuBegin(C, IFACE_(mt->label), ICON_NONE);
2772         layout = uiPupMenuLayout(pup);
2773
2774         menu.layout = layout;
2775         menu.type = mt;
2776
2777         if (G.debug & G_DEBUG_WM) {
2778                 printf("%s: opening menu \"%s\"\n", __func__, idname);
2779         }
2780
2781         mt->draw(C, &menu);
2782
2783         uiPupMenuEnd(C, pup);
2784 }
2785
2786
2787 /*************************** Popup Block API **************************/
2788
2789 void uiPupBlockO(bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext)
2790 {
2791         wmWindow *window = CTX_wm_window(C);
2792         uiPopupBlockHandle *handle;
2793         
2794         handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
2795         handle->popup = true;
2796         handle->optype = (opname) ? WM_operatortype_find(opname, 0) : NULL;
2797         handle->opcontext = opcontext;
2798         
2799         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2800         WM_event_add_mousemove(C);
2801 }
2802
2803 void uiPupBlock(bContext *C, uiBlockCreateFunc func, void *arg)
2804 {
2805         uiPupBlockO(C, func, arg, NULL, 0);
2806 }
2807
2808 void uiPupBlockEx(bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg)
2809 {
2810         wmWindow *window = CTX_wm_window(C);
2811         uiPopupBlockHandle *handle;
2812         
2813         handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
2814         handle->popup = true;
2815         handle->retvalue = 1;
2816
2817         handle->popup_arg = arg;
2818         handle->popup_func = popup_func;
2819         handle->cancel_func = cancel_func;
2820         // handle->opcontext = opcontext;
2821         
2822         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2823         WM_event_add_mousemove(C);
2824 }
2825
2826 #if 0 /* UNUSED */
2827 void uiPupBlockOperator(bContext *C, uiBlockCreateFunc func, wmOperator *op, int opcontext)
2828 {
2829         wmWindow *window = CTX_wm_window(C);
2830         uiPopupBlockHandle *handle;
2831         
2832         handle = ui_popup_block_create(C, NULL, NULL, func, NULL, op);
2833         handle->popup = 1;
2834         handle->retvalue = 1;
2835
2836         handle->popup_arg = op;
2837         handle->popup_func = operator_cb;
2838         handle->cancel_func = confirm_cancel_operator;
2839         handle->opcontext = opcontext;
2840         
2841         UI_add_popup_handlers(C, &window->modalhandlers, handle);
2842         WM_event_add_mousemove(C);
2843 }
2844 #endif
2845
2846 void uiPupBlockClose(bContext *C, uiBlock *block)
2847 {
2848         if (block->handle) {
2849                 wmWindow *win = CTX_wm_window(C);
2850
2851                 /* if loading new .blend while popup is open, window will be NULL */
2852                 if (win) {
2853                         UI_remove_popup_handlers(&win->modalhandlers, block->handle);
2854                         ui_popup_block_free(C, block->handle);
2855                 }
2856         }
2857 }
2858
2859 float *ui_block_hsv_get(uiBlock *block)
2860 {
2861         return block->_hsv;
2862 }