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