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