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