Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / interface / interface_templates.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  * Contributor(s): Blender Foundation 2009.
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/editors/interface/interface_templates.c
24  *  \ingroup edinterface
25  */
26
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_cachefile_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_object_force.h"
40 #include "DNA_brush_types.h"
41 #include "DNA_texture_types.h"
42
43 #include "BLI_utildefines.h"
44 #include "BLI_alloca.h"
45 #include "BLI_string.h"
46 #include "BLI_ghash.h"
47 #include "BLI_rect.h"
48 #include "BLI_math.h"
49 #include "BLI_listbase.h"
50 #include "BLI_fnmatch.h"
51 #include "BLI_timecode.h"
52
53 #include "BLF_api.h"
54 #include "BLT_translation.h"
55
56 #include "BKE_colortools.h"
57 #include "BKE_context.h"
58 #include "BKE_global.h"
59 #include "BKE_idcode.h"
60 #include "BKE_idprop.h"
61 #include "BKE_layer.h"
62 #include "BKE_library.h"
63 #include "BKE_linestyle.h"
64 #include "BKE_main.h"
65 #include "BKE_modifier.h"
66 #include "BKE_object.h"
67 #include "BKE_packedFile.h"
68 #include "BKE_particle.h"
69 #include "BKE_paint.h"
70 #include "BKE_report.h"
71 #include "BKE_sca.h"
72 #include "BKE_screen.h"
73 #include "BKE_texture.h"
74
75 #include "DEG_depsgraph.h"
76 #include "DEG_depsgraph_build.h"
77
78 #include "ED_screen.h"
79 #include "ED_object.h"
80 #include "ED_render.h"
81 #include "ED_util.h"
82
83 #include "RNA_access.h"
84
85 #include "WM_api.h"
86 #include "WM_types.h"
87
88 #include "UI_interface.h"
89 #include "UI_interface_icons.h"
90 #include "interface_intern.h"
91
92 #include "PIL_time.h"
93
94
95 // #define USE_OP_RESET_BUT  // we may want to make this optional, disable for now.
96
97 /* defines for templateID/TemplateSearch */
98 #define TEMPLATE_SEARCH_TEXTBUT_WIDTH  (UI_UNIT_X * 6)
99 #define TEMPLATE_SEARCH_TEXTBUT_HEIGHT  UI_UNIT_Y
100
101
102 void UI_template_fix_linking(void)
103 {
104 }
105
106 /**
107  * Add a block button for the search menu for templateID and templateSearch.
108  */
109 static void template_add_button_search_menu(
110         const bContext *C, uiLayout *layout, uiBlock *block,
111         PointerRNA *ptr, PropertyRNA *prop,
112         uiBlockCreateFunc block_func, void *block_argN, const char * const tip,
113         const bool use_previews, const bool editable)
114 {
115         PointerRNA active_ptr = RNA_property_pointer_get(ptr, prop);
116         ID *id = (active_ptr.data && RNA_struct_is_ID(active_ptr.type)) ? active_ptr.data : NULL;
117         const ID *idfrom = ptr->id.data;
118         const StructRNA *type = active_ptr.type ? active_ptr.type : RNA_property_pointer_type(ptr, prop);
119         uiBut *but;
120
121         if (use_previews) {
122                 ARegion *region = CTX_wm_region(C);
123                 const bool use_big_size = (region->regiontype != RGN_TYPE_HEADER); /* silly check, could be more generic */
124                 /* Ugly exception for screens here, drawing their preview in icon size looks ugly/useless */
125                 const bool use_preview_icon = use_big_size || (id && (GS(id->name) != ID_SCR));
126                 const short width = UI_UNIT_X * (use_big_size ? 6 : 1.6f);
127                 const short height = UI_UNIT_Y * (use_big_size ? 6 : 1);
128
129                 but = uiDefBlockButN(block, block_func, block_argN, "", 0, 0, width, height, tip);
130                 if (use_preview_icon) {
131                         int icon = id ? ui_id_icon_get(C, id, use_big_size) : RNA_struct_ui_icon(type);
132                         ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
133                 }
134                 else {
135                         ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON);
136                         UI_but_drawflag_enable(but, UI_BUT_ICON_LEFT);
137                 }
138
139                 if ((idfrom && idfrom->lib) || !editable)
140                         UI_but_flag_enable(but, UI_BUT_DISABLED);
141                 if (use_big_size) {
142                         uiLayoutRow(layout, true);
143                 }
144         }
145         else {
146                 but = uiDefBlockButN(block, block_func, block_argN, "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y, tip);
147                 ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON);
148                 if (id) {
149                         /* default dragging of icon for id browse buttons */
150                         UI_but_drag_set_id(but, id);
151                 }
152                 UI_but_drawflag_enable(but, UI_BUT_ICON_LEFT);
153
154                 if ((idfrom && idfrom->lib) || !editable)
155                         UI_but_flag_enable(but, UI_BUT_DISABLED);
156         }
157 }
158
159 static uiBlock *template_common_search_menu(
160         const bContext *C, ARegion *region,
161         uiButSearchFunc search_func, void *search_arg,
162         uiButHandleFunc handle_func, void *active_item,
163         const int preview_rows, const int preview_cols)
164 {
165         static char search[256];
166         wmWindow *win = CTX_wm_window(C);
167         uiBlock *block;
168         uiBut *but;
169
170         /* clear initial search string, then all items show */
171         search[0] = 0;
172
173         block = UI_block_begin(C, region, "_popup", UI_EMBOSS);
174         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_SEARCH_MENU);
175
176         /* preview thumbnails */
177         if (preview_rows > 0 && preview_cols > 0) {
178                 const int w = 4 * U.widget_unit * preview_cols;
179                 const int h = 5 * U.widget_unit * preview_rows;
180
181                 /* fake button, it holds space for search items */
182                 uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 26, w, h, NULL, 0, 0, 0, 0, NULL);
183
184                 but = uiDefSearchBut(
185                         block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, w, UI_UNIT_Y,
186                         preview_rows, preview_cols, "");
187         }
188         /* list view */
189         else {
190                 const int searchbox_width  = UI_searchbox_size_x();
191                 const int searchbox_height = UI_searchbox_size_y();
192
193                 /* fake button, it holds space for search items */
194                 uiDefBut(
195                         block, UI_BTYPE_LABEL, 0, "", 10, 15, searchbox_width, searchbox_height,
196                         NULL, 0, 0, 0, 0, NULL);
197                 but = uiDefSearchBut(
198                         block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0,
199                         searchbox_width, UI_UNIT_Y - 1, 0, 0, "");
200         }
201         UI_but_func_search_set(
202                 but, ui_searchbox_create_generic, search_func,
203                 search_arg, handle_func, active_item);
204
205
206         UI_block_bounds_set_normal(block, 0.3f * U.widget_unit);
207         UI_block_direction_set(block, UI_DIR_DOWN);
208
209         /* give search-field focus */
210         UI_but_focus_on_enter_event(win, but);
211         /* this type of search menu requires undo */
212         but->flag |= UI_BUT_UNDO;
213
214         return block;
215 }
216
217 /********************** Header Template *************************/
218
219 void uiTemplateHeader(uiLayout *layout, bContext *C)
220 {
221         uiBlock *block;
222
223         block = uiLayoutAbsoluteBlock(layout);
224         ED_area_header_switchbutton(C, block, 0);
225 }
226
227 /********************** Search Callbacks *************************/
228
229 typedef struct TemplateID {
230         PointerRNA ptr;
231         PropertyRNA *prop;
232
233         ListBase *idlb;
234         int prv_rows, prv_cols;
235         bool preview;
236 } TemplateID;
237
238 /* Search browse menu, assign  */
239 static void id_search_call_cb(bContext *C, void *arg_template, void *item)
240 {
241         TemplateID *template = (TemplateID *)arg_template;
242
243         /* ID */
244         if (item) {
245                 PointerRNA idptr;
246
247                 RNA_id_pointer_create(item, &idptr);
248                 RNA_property_pointer_set(&template->ptr, template->prop, idptr);
249                 RNA_property_update(C, &template->ptr, template->prop);
250         }
251 }
252
253 /* ID Search browse menu, do the search */
254 static void id_search_cb(const bContext *C, void *arg_template, const char *str, uiSearchItems *items)
255 {
256         TemplateID *template = (TemplateID *)arg_template;
257         ListBase *lb = template->idlb;
258         ID *id, *id_from = template->ptr.id.data;
259         int iconid;
260         int flag = RNA_property_flag(template->prop);
261
262         /* ID listbase */
263         for (id = lb->first; id; id = id->next) {
264                 if (!((flag & PROP_ID_SELF_CHECK) && id == id_from)) {
265
266                         /* use filter */
267                         if (RNA_property_type(template->prop) == PROP_POINTER) {
268                                 PointerRNA ptr;
269                                 RNA_id_pointer_create(id, &ptr);
270                                 if (RNA_property_pointer_poll(&template->ptr, template->prop, &ptr) == 0)
271                                         continue;
272                         }
273
274                         /* hide dot-datablocks, but only if filter does not force it visible */
275                         if (U.uiflag & USER_HIDE_DOT)
276                                 if ((id->name[2] == '.') && (str[0] != '.'))
277                                         continue;
278
279                         if (*str == '\0' || BLI_strcasestr(id->name + 2, str)) {
280                                 /* +1 is needed because BKE_id_ui_prefix used 3 letter prefix
281                                  * followed by ID_NAME-2 characters from id->name
282                                  */
283                                 char name_ui[MAX_ID_NAME + 1];
284                                 BKE_id_ui_prefix(name_ui, id);
285
286                                 iconid = ui_id_icon_get(C, id, template->preview);
287
288                                 if (false == UI_search_item_add(items, name_ui, id, iconid))
289                                         break;
290                         }
291                 }
292         }
293 }
294
295 /* ID Search browse menu, open */
296 static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
297 {
298         static TemplateID template;
299         PointerRNA active_item_ptr;
300
301         /* arg_litem is malloced, can be freed by parent button */
302         template = *((TemplateID *)arg_litem);
303         active_item_ptr = RNA_property_pointer_get(&template.ptr, template.prop);
304
305         return template_common_search_menu(
306                        C, ar, id_search_cb, &template, id_search_call_cb, active_item_ptr.data,
307                        template.prv_rows, template.prv_cols);
308 }
309
310 /************************ ID Template ***************************/
311 /* This is for browsing and editing the ID-blocks used */
312
313 /* for new/open operators */
314 void UI_context_active_but_prop_get_templateID(
315         bContext *C,
316         PointerRNA *r_ptr, PropertyRNA **r_prop)
317 {
318         TemplateID *template;
319         ARegion *ar = CTX_wm_region(C);
320         uiBlock *block;
321         uiBut *but;
322
323         memset(r_ptr, 0, sizeof(*r_ptr));
324         *r_prop = NULL;
325
326         if (!ar)
327                 return;
328
329         for (block = ar->uiblocks.first; block; block = block->next) {
330                 for (but = block->buttons.first; but; but = but->next) {
331                         /* find the button before the active one */
332                         if ((but->flag & (UI_BUT_LAST_ACTIVE | UI_ACTIVE))) {
333                                 if (but->func_argN) {
334                                         template = but->func_argN;
335                                         *r_ptr = template->ptr;
336                                         *r_prop = template->prop;
337                                         return;
338                                 }
339                         }
340                 }
341         }
342 }
343
344
345 static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
346 {
347         TemplateID *template = (TemplateID *)arg_litem;
348         PointerRNA idptr = RNA_property_pointer_get(&template->ptr, template->prop);
349         ID *id = idptr.data;
350         int event = GET_INT_FROM_POINTER(arg_event);
351         
352         switch (event) {
353                 case UI_ID_BROWSE:
354                 case UI_ID_PIN:
355                         RNA_warning("warning, id event %d shouldnt come here", event);
356                         break;
357                 case UI_ID_OPEN:
358                 case UI_ID_ADD_NEW:
359                         /* these call UI_context_active_but_prop_get_templateID */
360                         break;
361                 case UI_ID_DELETE:
362                         memset(&idptr, 0, sizeof(idptr));
363                         RNA_property_pointer_set(&template->ptr, template->prop, idptr);
364                         RNA_property_update(C, &template->ptr, template->prop);
365
366                         if (id && CTX_wm_window(C)->eventstate->shift) {
367                                 /* only way to force-remove data (on save) */
368                                 id_fake_user_clear(id);
369                                 id->us = 0;
370                         }
371
372                         break;
373                 case UI_ID_FAKE_USER:
374                         if (id) {
375                                 if (id->flag & LIB_FAKEUSER) id_us_plus(id);
376                                 else id_us_min(id);
377                         }
378                         else {
379                                 return;
380                         }
381                         break;
382                 case UI_ID_LOCAL:
383                         if (id) {
384                                 Main *bmain = CTX_data_main(C);
385                                 if (id_make_local(bmain, id, false, false)) {
386                                         BKE_main_id_clear_newpoins(bmain);
387
388                                         /* reassign to get get proper updates/notifiers */
389                                         idptr = RNA_property_pointer_get(&template->ptr, template->prop);
390                                         RNA_property_pointer_set(&template->ptr, template->prop, idptr);
391                                         RNA_property_update(C, &template->ptr, template->prop);
392                                 }
393                         }
394                         break;
395                 case UI_ID_ALONE:
396                         if (id) {
397                                 const bool do_scene_obj = (GS(id->name) == ID_OB) &&
398                                                           (template->ptr.type == &RNA_SceneObjects);
399
400                                 /* make copy */
401                                 if (do_scene_obj) {
402                                         Main *bmain = CTX_data_main(C);
403                                         Scene *scene = CTX_data_scene(C);
404                                         ED_object_single_user(bmain, scene, (struct Object *)id);
405                                         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
406                                         DEG_relations_tag_update(bmain);
407                                 }
408                                 else {
409                                         if (id) {
410                                                 Main *bmain = CTX_data_main(C);
411                                                 id_single_user(C, id, &template->ptr, template->prop);
412                                                 DEG_relations_tag_update(bmain);
413                                         }
414                                 }
415                         }
416                         break;
417 #if 0
418                 case UI_ID_AUTO_NAME:
419                         break;
420 #endif
421         }
422 }
423
424 static const char *template_id_browse_tip(const StructRNA *type)
425 {
426         if (type) {
427                 switch (RNA_type_to_ID_code(type)) {
428                         case ID_SCE: return N_("Browse Scene to be linked");
429                         case ID_OB:  return N_("Browse Object to be linked");
430                         case ID_ME:  return N_("Browse Mesh Data to be linked");
431                         case ID_CU:  return N_("Browse Curve Data to be linked");
432                         case ID_MB:  return N_("Browse Metaball Data to be linked");
433                         case ID_MA:  return N_("Browse Material to be linked");
434                         case ID_TE:  return N_("Browse Texture to be linked");
435                         case ID_IM:  return N_("Browse Image to be linked");
436                         case ID_LS:  return N_("Browse Line Style Data to be linked");
437                         case ID_LT:  return N_("Browse Lattice Data to be linked");
438                         case ID_LA:  return N_("Browse Lamp Data to be linked");
439                         case ID_CA:  return N_("Browse Camera Data to be linked");
440                         case ID_WO:  return N_("Browse World Settings to be linked");
441                         case ID_SCR: return N_("Choose Screen layout");
442                         case ID_TXT: return N_("Browse Text to be linked");
443                         case ID_SPK: return N_("Browse Speaker Data to be linked");
444                         case ID_SO:  return N_("Browse Sound to be linked");
445                         case ID_AR:  return N_("Browse Armature data to be linked");
446                         case ID_AC:  return N_("Browse Action to be linked");
447                         case ID_NT:  return N_("Browse Node Tree to be linked");
448                         case ID_BR:  return N_("Browse Brush to be linked");
449                         case ID_PA:  return N_("Browse Particle Settings to be linked");
450                         case ID_GD:  return N_("Browse Grease Pencil Data to be linked");
451                         case ID_MC:  return N_("Browse Movie Clip to be linked");
452                         case ID_MSK: return N_("Browse Mask to be linked");
453                         case ID_PAL: return N_("Browse Palette Data to be linked");
454                         case ID_PC:  return N_("Browse Paint Curve Data to be linked");
455                         case ID_CF:  return N_("Browse Cache Files to be linked");
456                         case ID_WS:  return N_("Browse Workspace to be linked");
457                         case ID_LP:  return N_("Browse LightProbe to be linked");
458                 }
459         }
460         return N_("Browse ID data to be linked");
461 }
462
463 /**
464  * \return a type-based i18n context, needed e.g. by "New" button.
465  * In most languages, this adjective takes different form based on gender of type name...
466  */
467 #ifdef WITH_INTERNATIONAL
468 static const char *template_id_context(StructRNA *type)
469 {
470         if (type) {
471                 return BKE_idcode_to_translation_context(RNA_type_to_ID_code(type));
472         }
473         return BLT_I18NCONTEXT_DEFAULT;
474 }
475 #endif
476
477 static void template_ID(
478         bContext *C, uiLayout *layout, TemplateID *template, StructRNA *type, short idcode, int flag,
479         const char *newop, const char *openop, const char *unlinkop)
480 {
481         uiBut *but;
482         uiBlock *block;
483         PointerRNA idptr;
484         // ListBase *lb; // UNUSED
485         ID *id, *idfrom;
486         const bool editable = RNA_property_editable(&template->ptr, template->prop);
487         const bool use_previews = template->preview = (flag & UI_ID_PREVIEWS) != 0;
488
489         idptr = RNA_property_pointer_get(&template->ptr, template->prop);
490         id = idptr.data;
491         idfrom = template->ptr.id.data;
492         // lb = template->idlb;
493
494         block = uiLayoutGetBlock(layout);
495         UI_block_align_begin(block);
496
497         if (idptr.type)
498                 type = idptr.type;
499
500         if (flag & UI_ID_BROWSE) {
501                 template_add_button_search_menu(
502                         C, layout, block, &template->ptr, template->prop,
503                         id_search_menu, MEM_dupallocN(template), TIP_(template_id_browse_tip(type)),
504                         use_previews, editable);
505         }
506
507         /* text button with name */
508         if (id) {
509                 char name[UI_MAX_NAME_STR];
510                 const bool user_alert = (id->us <= 0);
511
512                 //text_idbutton(id, name);
513                 name[0] = '\0';
514                 but = uiDefButR(
515                         block, UI_BTYPE_TEXT, 0, name, 0, 0, TEMPLATE_SEARCH_TEXTBUT_WIDTH, TEMPLATE_SEARCH_TEXTBUT_HEIGHT,
516                         &idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type));
517                 UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_RENAME));
518                 if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT);
519
520                 if (id->lib) {
521                         if (id->tag & LIB_TAG_INDIRECT) {
522                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_INDIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y,
523                                                    NULL, 0, 0, 0, 0, TIP_("Indirect library data-block, cannot change"));
524                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
525                         }
526                         else {
527                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_LIBRARY_DATA_DIRECT, 0, 0, UI_UNIT_X, UI_UNIT_Y,
528                                                    NULL, 0, 0, 0, 0, TIP_("Direct linked library data-block, click to make local"));
529                                 if (!id_make_local(CTX_data_main(C), id, true /* test */, false) || (idfrom && idfrom->lib))
530                                         UI_but_flag_enable(but, UI_BUT_DISABLED);
531                         }
532
533                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_LOCAL));
534                 }
535
536                 if (id->us > 1) {
537                         char numstr[32];
538                         short numstr_len;
539
540                         numstr_len = BLI_snprintf(numstr, sizeof(numstr), "%d", id->us);
541
542                         but = uiDefBut(block, UI_BTYPE_BUT, 0, numstr, 0, 0,
543                                        numstr_len * 0.2f * UI_UNIT_X + UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0,
544                                        TIP_("Display number of users of this data (click to make a single-user copy)"));
545                         but->flag |= UI_BUT_UNDO;
546
547                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ALONE));
548                         if (/* test only */
549                             (id_copy(CTX_data_main(C), id, NULL, true) == false) ||
550                             (idfrom && idfrom->lib) ||
551                             (!editable) ||
552                             /* object in editmode - don't change data */
553                             (idfrom && GS(idfrom->name) == ID_OB && (((Object *)idfrom)->mode & OB_MODE_EDIT)))
554                         {
555                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
556                         }
557                 }
558         
559                 if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT);
560                 
561                 if (id->lib == NULL && !(ELEM(GS(id->name), ID_GR, ID_SCE, ID_SCR, ID_TXT, ID_OB, ID_WS))) {
562                         uiDefButR(block, UI_BTYPE_TOGGLE, 0, "F", 0, 0, UI_UNIT_X, UI_UNIT_Y, &idptr, "use_fake_user", -1, 0, 0, -1, -1, NULL);
563                 }
564         }
565         
566         if (flag & UI_ID_ADD_NEW) {
567                 int w = id ? UI_UNIT_X : (flag & UI_ID_OPEN) ? UI_UNIT_X * 3 : UI_UNIT_X * 6;
568                 
569                 /* i18n markup, does nothing! */
570                 BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_DEFAULT,
571                                                  BLT_I18NCONTEXT_ID_SCENE,
572                                                  BLT_I18NCONTEXT_ID_OBJECT,
573                                                  BLT_I18NCONTEXT_ID_MESH,
574                                                  BLT_I18NCONTEXT_ID_CURVE,
575                                                  BLT_I18NCONTEXT_ID_METABALL,
576                                                  BLT_I18NCONTEXT_ID_MATERIAL,
577                                                  BLT_I18NCONTEXT_ID_TEXTURE,
578                                                  BLT_I18NCONTEXT_ID_IMAGE,
579                                                  BLT_I18NCONTEXT_ID_LATTICE,
580                                                  BLT_I18NCONTEXT_ID_LAMP,
581                                                  BLT_I18NCONTEXT_ID_CAMERA,
582                                                  BLT_I18NCONTEXT_ID_WORLD,
583                                                  BLT_I18NCONTEXT_ID_SCREEN,
584                                                  BLT_I18NCONTEXT_ID_TEXT,
585                 );
586                 BLT_I18N_MSGID_MULTI_CTXT("New", BLT_I18NCONTEXT_ID_SPEAKER,
587                                                  BLT_I18NCONTEXT_ID_SOUND,
588                                                  BLT_I18NCONTEXT_ID_ARMATURE,
589                                                  BLT_I18NCONTEXT_ID_ACTION,
590                                                  BLT_I18NCONTEXT_ID_NODETREE,
591                                                  BLT_I18NCONTEXT_ID_BRUSH,
592                                                  BLT_I18NCONTEXT_ID_PARTICLESETTINGS,
593                                                  BLT_I18NCONTEXT_ID_GPENCIL,
594                                                  BLT_I18NCONTEXT_ID_FREESTYLELINESTYLE,
595                                                  BLT_I18NCONTEXT_ID_WORKSPACE,
596                                                  BLT_I18NCONTEXT_ID_LIGHTPROBE,
597                 );
598                 
599                 if (newop) {
600                         but = uiDefIconTextButO(block, UI_BTYPE_BUT, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN,
601                                                 (id) ? "" : CTX_IFACE_(template_id_context(type), "New"), 0, 0, w, UI_UNIT_Y, NULL);
602                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
603                 }
604                 else {
605                         but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, (id) ? "" : CTX_IFACE_(template_id_context(type), "New"),
606                                                0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
607                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
608                 }
609
610                 if ((idfrom && idfrom->lib) || !editable)
611                         UI_but_flag_enable(but, UI_BUT_DISABLED);
612         }
613
614         /* Due to space limit in UI - skip the "open" icon for packed data, and allow to unpack.
615          * Only for images, sound and fonts */
616         if (id && BKE_pack_check(id)) {
617                 but = uiDefIconButO(block, UI_BTYPE_BUT, "FILE_OT_unpack_item", WM_OP_INVOKE_REGION_WIN, ICON_PACKAGE, 0, 0,
618                                     UI_UNIT_X, UI_UNIT_Y, TIP_("Packed File, click to unpack"));
619                 UI_but_operator_ptr_get(but);
620                 
621                 RNA_string_set(but->opptr, "id_name", id->name + 2);
622                 RNA_int_set(but->opptr, "id_type", GS(id->name));
623                 
624         }
625         else if (flag & UI_ID_OPEN) {
626                 int w = id ? UI_UNIT_X : (flag & UI_ID_ADD_NEW) ? UI_UNIT_X * 3 : UI_UNIT_X * 6;
627                 
628                 if (openop) {
629                         but = uiDefIconTextButO(block, UI_BTYPE_BUT, openop, WM_OP_INVOKE_DEFAULT, ICON_FILESEL, (id) ? "" : IFACE_("Open"),
630                                                 0, 0, w, UI_UNIT_Y, NULL);
631                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
632                 }
633                 else {
634                         but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILESEL, (id) ? "" : IFACE_("Open"), 0, 0, w, UI_UNIT_Y,
635                                                NULL, 0, 0, 0, 0, NULL);
636                         UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
637                 }
638
639                 if ((idfrom && idfrom->lib) || !editable)
640                         UI_but_flag_enable(but, UI_BUT_DISABLED);
641         }
642         
643         /* delete button */
644         /* don't use RNA_property_is_unlink here */
645         if (id && (flag & UI_ID_DELETE)) {
646                 /* allow unlink if 'unlinkop' is passed, even when 'PROP_NEVER_UNLINK' is set */
647                 but = NULL;
648
649                 if (unlinkop) {
650                         but = uiDefIconButO(block, UI_BTYPE_BUT, unlinkop, WM_OP_INVOKE_REGION_WIN, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
651                         /* so we can access the template from operators, font unlinking needs this */
652                         UI_but_funcN_set(but, NULL, MEM_dupallocN(template), NULL);
653                 }
654                 else {
655                         if ((RNA_property_flag(template->prop) & PROP_NEVER_UNLINK) == 0) {
656                                 but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0,
657                                                    TIP_("Unlink data-block "
658                                                         "(Shift + Click to set users to zero, data will then not be saved)"));
659                                 UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_DELETE));
660
661                                 if (RNA_property_flag(template->prop) & PROP_NEVER_NULL) {
662                                         UI_but_flag_enable(but, UI_BUT_DISABLED);
663                                 }
664                         }
665                 }
666
667                 if (but) {
668                         if ((idfrom && idfrom->lib) || !editable) {
669                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
670                         }
671                 }
672         }
673
674         if (idcode == ID_TE)
675                 uiTemplateTextureShow(layout, C, &template->ptr, template->prop);
676         
677         UI_block_align_end(block);
678 }
679
680 static void ui_template_id(
681         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
682         const char *openop, const char *unlinkop, int flag, int prv_rows, int prv_cols)
683 {
684         TemplateID *template;
685         PropertyRNA *prop;
686         StructRNA *type;
687         short idcode;
688
689         prop = RNA_struct_find_property(ptr, propname);
690
691         if (!prop || RNA_property_type(prop) != PROP_POINTER) {
692                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
693                 return;
694         }
695
696         template = MEM_callocN(sizeof(TemplateID), "TemplateID");
697         template->ptr = *ptr;
698         template->prop = prop;
699         template->prv_rows = prv_rows;
700         template->prv_cols = prv_cols;
701
702         if (newop)
703                 flag |= UI_ID_ADD_NEW;
704         if (openop)
705                 flag |= UI_ID_OPEN;
706
707         type = RNA_property_pointer_type(ptr, prop);
708         idcode = RNA_type_to_ID_code(type);
709         template->idlb = which_libbase(CTX_data_main(C), idcode);
710         
711         /* create UI elements for this template
712          *      - template_ID makes a copy of the template data and assigns it to the relevant buttons
713          */
714         if (template->idlb) {
715                 uiLayoutRow(layout, true);
716                 template_ID(C, layout, template, type, idcode, flag, newop, openop, unlinkop);
717         }
718
719         MEM_freeN(template);
720 }
721
722 void uiTemplateID(
723         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
724         const char *openop, const char *unlinkop)
725 {
726         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
727                        UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0);
728 }
729
730 void uiTemplateIDBrowse(
731         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
732         const char *openop, const char *unlinkop)
733 {
734         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, UI_ID_BROWSE | UI_ID_RENAME, 0, 0);
735 }
736
737 void uiTemplateIDPreview(
738         uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
739         const char *openop, const char *unlinkop, int rows, int cols)
740 {
741         ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
742                        UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols);
743 }
744
745 /************************ ID Chooser Template ***************************/
746
747 /**
748  * This is for selecting the type of ID-block to use, and then from the relevant type choosing the block to use
749  *
750  * - propname: property identifier for property that ID-pointer gets stored to
751  * - proptypename: property identifier for property used to determine the type of ID-pointer that can be used
752  */
753 void uiTemplateAnyID(
754         uiLayout *layout, PointerRNA *ptr, const char *propname, const char *proptypename,
755         const char *text)
756 {
757         PropertyRNA *propID, *propType;
758         uiLayout *split, *row, *sub;
759         
760         /* get properties... */
761         propID = RNA_struct_find_property(ptr, propname);
762         propType = RNA_struct_find_property(ptr, proptypename);
763
764         if (!propID || RNA_property_type(propID) != PROP_POINTER) {
765                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
766                 return;
767         }
768         if (!propType || RNA_property_type(propType) != PROP_ENUM) {
769                 RNA_warning("pointer-type property not found: %s.%s", RNA_struct_identifier(ptr->type), proptypename);
770                 return;
771         }
772         
773         /* Start drawing UI Elements using standard defines */
774         split = uiLayoutSplit(layout, 0.33f, false);  /* NOTE: split amount here needs to be synced with normal labels */
775         
776         /* FIRST PART ................................................ */
777         row = uiLayoutRow(split, false);
778         
779         /* Label - either use the provided text, or will become "ID-Block:" */
780         if (text) {
781                 if (text[0])
782                         uiItemL(row, text, ICON_NONE);
783         }
784         else {
785                 uiItemL(row, IFACE_("ID-Block:"), ICON_NONE);
786         }
787         
788         /* SECOND PART ................................................ */
789         row = uiLayoutRow(split, true);
790         
791         /* ID-Type Selector - just have a menu of icons */
792         sub = uiLayoutRow(row, true);                     /* HACK: special group just for the enum, otherwise we */
793         uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);  /*       we get ugly layout with text included too...  */
794         
795         uiItemFullR(sub, ptr, propType, 0, 0, UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
796         
797         /* ID-Block Selector - just use pointer widget... */
798         sub = uiLayoutRow(row, true);                       /* HACK: special group to counteract the effects of the previous */
799         uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_EXPAND);  /*       enum, which now pushes everything too far right         */
800         
801         uiItemFullR(sub, ptr, propID, 0, 0, 0, "", ICON_NONE);
802 }
803
804 /********************* Search Template ********************/
805
806 typedef struct TemplateSearch {
807         uiRNACollectionSearch search_data;
808
809         bool use_previews;
810         int preview_rows, preview_cols;
811 } TemplateSearch;
812
813 static void template_search_handle_cb(bContext *C, void *arg_template, void *item)
814 {
815         TemplateSearch *template_search = arg_template;
816         uiRNACollectionSearch *coll_search = &template_search->search_data;
817         StructRNA *type = RNA_property_pointer_type(&coll_search->target_ptr, coll_search->target_prop);
818         PointerRNA item_ptr;
819
820         RNA_pointer_create(NULL, type, item, &item_ptr);
821         RNA_property_pointer_set(&coll_search->target_ptr, coll_search->target_prop, item_ptr);
822         RNA_property_update(C, &coll_search->target_ptr, coll_search->target_prop);
823 }
824
825 static uiBlock *template_search_menu(bContext *C, ARegion *region, void *arg_template)
826 {
827         static TemplateSearch template_search;
828         PointerRNA active_ptr;
829
830         /* arg_template is malloced, can be freed by parent button */
831         template_search = *((TemplateSearch *)arg_template);
832         active_ptr = RNA_property_pointer_get(&template_search.search_data.target_ptr,
833                                               template_search.search_data.target_prop);
834
835         return template_common_search_menu(
836                        C, region, ui_rna_collection_search_cb, &template_search,
837                        template_search_handle_cb, active_ptr.data,
838                        template_search.preview_rows, template_search.preview_cols);
839 }
840
841 static void template_search_add_button_searchmenu(
842         const bContext *C, uiLayout *layout, uiBlock *block,
843         TemplateSearch *template_search, const bool editable)
844 {
845         const char *ui_description = RNA_property_ui_description(template_search->search_data.target_prop);
846
847         template_add_button_search_menu(
848                 C, layout, block,
849                 &template_search->search_data.target_ptr, template_search->search_data.target_prop,
850                 template_search_menu, MEM_dupallocN(template_search), ui_description,
851                 template_search->use_previews, editable);
852 }
853
854 static void template_search_add_button_name(
855         uiBlock *block, PointerRNA *active_ptr, const StructRNA *type)
856 {
857         uiDefAutoButR(
858                 block, active_ptr, RNA_struct_name_property(type), 0, "", ICON_NONE,
859                 0, 0, TEMPLATE_SEARCH_TEXTBUT_WIDTH, TEMPLATE_SEARCH_TEXTBUT_HEIGHT);
860 }
861
862 static void template_search_add_button_operator(
863         uiBlock *block, const char * const operator_name,
864         const int opcontext, const int icon, const bool editable)
865 {
866         if (!operator_name) {
867                 return;
868         }
869
870         uiBut *but = uiDefIconButO(
871                 block, UI_BTYPE_BUT, operator_name, opcontext, icon,
872                 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
873
874         if (!editable) {
875                 UI_but_drawflag_enable(but, UI_BUT_DISABLED);
876         }
877 }
878
879 static void template_search_buttons(
880         const bContext *C, uiLayout *layout, TemplateSearch *template_search,
881         const char *newop, const char *unlinkop)
882 {
883         uiBlock *block = uiLayoutGetBlock(layout);
884         uiRNACollectionSearch *search_data = &template_search->search_data;
885         StructRNA *type = RNA_property_pointer_type(&search_data->target_ptr, search_data->target_prop);
886         const bool editable = RNA_property_editable(&search_data->target_ptr, search_data->target_prop);
887         PointerRNA active_ptr = RNA_property_pointer_get(&search_data->target_ptr, search_data->target_prop);
888
889         if (active_ptr.type) {
890                 /* can only get correct type when there is an active item */
891                 type = active_ptr.type;
892         }
893
894         uiLayoutRow(layout, true);
895         UI_block_align_begin(block);
896
897         template_search_add_button_searchmenu(C, layout, block, template_search, editable);
898         template_search_add_button_name(block, &active_ptr, type);
899         template_search_add_button_operator(block, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, editable);
900         template_search_add_button_operator(block, unlinkop, WM_OP_INVOKE_REGION_WIN, ICON_X, editable);
901
902         UI_block_align_end(block);
903 }
904
905 static PropertyRNA *template_search_get_searchprop(
906         PointerRNA *targetptr, PropertyRNA *targetprop,
907         PointerRNA *searchptr, const char * const searchpropname)
908 {
909         PropertyRNA *searchprop;
910
911         if (searchptr && !searchptr->data) {
912                 searchptr = NULL;
913         }
914
915         if (!searchptr && !searchpropname) {
916                 /* both NULL means we don't use a custom rna collection to search in */
917         }
918         else if (!searchptr && searchpropname) {
919                 RNA_warning("searchpropname defined (%s) but searchptr is missing", searchpropname);
920         }
921         else if (searchptr && !searchpropname) {
922                 RNA_warning("searchptr defined (%s) but searchpropname is missing", RNA_struct_identifier(searchptr->type));
923         }
924         else if (!(searchprop = RNA_struct_find_property(searchptr, searchpropname))) {
925                 RNA_warning("search collection property not found: %s.%s",
926                             RNA_struct_identifier(searchptr->type), searchpropname);
927         }
928         else if (RNA_property_type(searchprop) != PROP_COLLECTION) {
929                 RNA_warning("search collection property is not a collection type: %s.%s",
930                             RNA_struct_identifier(searchptr->type), searchpropname);
931         }
932         /* check if searchprop has same type as targetprop */
933         else if (RNA_property_pointer_type(searchptr, searchprop) != RNA_property_pointer_type(targetptr, targetprop)) {
934                 RNA_warning("search collection items from %s.%s are not of type %s",
935                             RNA_struct_identifier(searchptr->type), searchpropname,
936                             RNA_struct_identifier(RNA_property_pointer_type(targetptr, targetprop)));
937         }
938         else {
939                 return searchprop;
940         }
941
942         return NULL;
943 }
944
945 static TemplateSearch *template_search_setup(
946         PointerRNA *ptr, const char * const propname,
947         PointerRNA *searchptr, const char * const searchpropname)
948 {
949         TemplateSearch *template_search;
950         PropertyRNA *prop, *searchprop;
951
952         prop = RNA_struct_find_property(ptr, propname);
953
954         if (!prop || RNA_property_type(prop) != PROP_POINTER) {
955                 RNA_warning("pointer property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
956                 return NULL;
957         }
958         searchprop = template_search_get_searchprop(ptr, prop, searchptr, searchpropname);
959
960         template_search = MEM_callocN(sizeof(*template_search), __func__);
961         template_search->search_data.target_ptr = *ptr;
962         template_search->search_data.target_prop = prop;
963         template_search->search_data.search_ptr = *searchptr;
964         template_search->search_data.search_prop = searchprop;
965
966         return template_search;
967 }
968
969 /**
970  * Search menu to pick an item from a collection.
971  * A version of uiTemplateID that works for non-ID types.
972  */
973 void uiTemplateSearch(
974         uiLayout *layout, bContext *C,
975         PointerRNA *ptr, const char *propname,
976         PointerRNA *searchptr, const char *searchpropname,
977         const char *newop, const char *unlinkop)
978 {
979         TemplateSearch *template_search = template_search_setup(ptr, propname, searchptr, searchpropname);
980         template_search_buttons(C, layout, template_search, newop, unlinkop);
981         MEM_freeN(template_search);
982 }
983
984 void uiTemplateSearchPreview(
985         uiLayout *layout, bContext *C,
986         PointerRNA *ptr, const char *propname,
987         PointerRNA *searchptr, const char *searchpropname,
988         const char *newop, const char *unlinkop,
989         const int rows, const int cols)
990 {
991         TemplateSearch *template_search = template_search_setup(ptr, propname, searchptr, searchpropname);
992
993         template_search->use_previews = true;
994         template_search->preview_rows = rows;
995         template_search->preview_cols = cols;
996
997         template_search_buttons(C, layout, template_search, newop, unlinkop);
998
999         MEM_freeN(template_search);
1000 }
1001
1002 /********************* RNA Path Builder Template ********************/
1003
1004 /* ---------- */
1005
1006 /**
1007  * This is creating/editing RNA-Paths
1008  *
1009  * - ptr: struct which holds the path property
1010  * - propname: property identifier for property that path gets stored to
1011  * - root_ptr: struct that path gets built from
1012  */
1013 void uiTemplatePathBuilder(uiLayout *layout, PointerRNA *ptr, const char *propname, PointerRNA *UNUSED(root_ptr),
1014                            const char *text)
1015 {
1016         PropertyRNA *propPath;
1017         uiLayout *row;
1018         
1019         /* check that properties are valid */
1020         propPath = RNA_struct_find_property(ptr, propname);
1021         if (!propPath || RNA_property_type(propPath) != PROP_STRING) {
1022                 RNA_warning("path property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
1023                 return;
1024         }
1025         
1026         /* Start drawing UI Elements using standard defines */
1027         row = uiLayoutRow(layout, true);
1028         
1029         /* Path (existing string) Widget */
1030         uiItemR(row, ptr, propname, 0, text, ICON_RNA);
1031         
1032         /* TODO: attach something to this to make allow searching of nested properties to 'build' the path */
1033 }
1034
1035 /************************ Modifier Template *************************/
1036
1037 #define ERROR_LIBDATA_MESSAGE IFACE_("Can't edit external libdata")
1038
1039 static void modifiers_convertToReal(bContext *C, void *ob_v, void *md_v)
1040 {
1041         Object *ob = ob_v;
1042         ModifierData *md = md_v;
1043         ModifierData *nmd = modifier_new(md->type);
1044
1045         modifier_copyData(md, nmd);
1046         nmd->mode &= ~eModifierMode_Virtual;
1047
1048         BLI_addhead(&ob->modifiers, nmd);
1049         
1050         modifier_unique_name(&ob->modifiers, nmd);
1051
1052         ob->partype = PAROBJECT;
1053
1054         WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob);
1055         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1056
1057         ED_undo_push(C, "Modifier convert to real");
1058 }
1059
1060 static int modifier_can_delete(ModifierData *md)
1061 {
1062         /* fluid particle modifier can't be deleted here */
1063         if (md->type == eModifierType_ParticleSystem)
1064                 if (((ParticleSystemModifierData *)md)->psys->part->type == PART_FLUID)
1065                         return 0;
1066
1067         return 1;
1068 }
1069
1070 /* Check whether Modifier is a simulation or not, this is used for switching to the physics/particles context tab */
1071 static int modifier_is_simulation(ModifierData *md)
1072 {
1073         /* Physic Tab */
1074         if (ELEM(md->type, eModifierType_Cloth, eModifierType_Collision, eModifierType_Fluidsim, eModifierType_Smoke,
1075                   eModifierType_Softbody, eModifierType_Surface, eModifierType_DynamicPaint))
1076         {
1077                 return 1;
1078         }
1079         /* Particle Tab */
1080         else if (md->type == eModifierType_ParticleSystem) {
1081                 return 2;
1082         }
1083         else {
1084                 return 0;
1085         }
1086 }
1087
1088 static uiLayout *draw_modifier(
1089         uiLayout *layout, Scene *scene, Object *ob,
1090         ModifierData *md, int index, int cageIndex, int lastCageIndex)
1091 {
1092         const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1093         PointerRNA ptr;
1094         uiBut *but;
1095         uiBlock *block;
1096         uiLayout *box, *column, *row, *sub;
1097         uiLayout *result = NULL;
1098         int isVirtual = (md->mode & eModifierMode_Virtual);
1099         char str[128];
1100
1101         /* create RNA pointer */
1102         RNA_pointer_create(&ob->id, &RNA_Modifier, md, &ptr);
1103
1104         column = uiLayoutColumn(layout, true);
1105         uiLayoutSetContextPointer(column, "modifier", &ptr);
1106
1107         /* rounded header ------------------------------------------------------------------- */
1108         box = uiLayoutBox(column);
1109         
1110         if (isVirtual) {
1111                 row = uiLayoutRow(box, false);
1112                 uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_EXPAND);
1113                 block = uiLayoutGetBlock(row);
1114                 /* VIRTUAL MODIFIER */
1115                 /* XXX this is not used now, since these cannot be accessed via RNA */
1116                 BLI_snprintf(str, sizeof(str), IFACE_("%s parent deform"), md->name);
1117                 uiDefBut(block, UI_BTYPE_LABEL, 0, str, 0, 0, 185, UI_UNIT_Y, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Modifier name"));
1118                 
1119                 but = uiDefBut(block, UI_BTYPE_BUT, 0, IFACE_("Make Real"), 0, 0, 80, 16, NULL, 0.0, 0.0, 0.0, 0.0,
1120                                TIP_("Convert virtual modifier to a real modifier"));
1121                 UI_but_func_set(but, modifiers_convertToReal, ob, md);
1122         }
1123         else {
1124                 /* REAL MODIFIER */
1125                 row = uiLayoutRow(box, false);
1126                 block = uiLayoutGetBlock(row);
1127                 
1128                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1129                 /* Open/Close .................................  */
1130                 uiItemR(row, &ptr, "show_expanded", 0, "", ICON_NONE);
1131                 
1132                 /* modifier-type icon */
1133                 uiItemL(row, "", RNA_struct_ui_icon(ptr.type));
1134                 UI_block_emboss_set(block, UI_EMBOSS);
1135                 
1136                 /* modifier name */
1137                 md->scene = scene;
1138                 if (mti->isDisabled && mti->isDisabled(md, 0)) {
1139                         uiLayoutSetRedAlert(row, true);
1140                 }
1141                 uiItemR(row, &ptr, "name", 0, "", ICON_NONE);
1142                 uiLayoutSetRedAlert(row, false);
1143                 
1144                 /* mode enabling buttons */
1145                 UI_block_align_begin(block);
1146                 /* Collision and Surface are always enabled, hide buttons! */
1147                 if (((md->type != eModifierType_Collision) || !(ob->pd && ob->pd->deflect)) &&
1148                     (md->type != eModifierType_Surface) )
1149                 {
1150                         uiItemR(row, &ptr, "show_render", 0, "", ICON_NONE);
1151                         uiItemR(row, &ptr, "show_viewport", 0, "", ICON_NONE);
1152                         
1153                         if (mti->flags & eModifierTypeFlag_SupportsEditmode) {
1154                                 sub = uiLayoutRow(row, true);
1155                                 if (!(md->mode & eModifierMode_Realtime)) {
1156                                         uiLayoutSetActive(sub, false);
1157                                 }
1158                                 uiItemR(sub, &ptr, "show_in_editmode", 0, "", ICON_NONE);
1159                         }
1160                 }
1161
1162                 if (ob->type == OB_MESH) {
1163                         if (modifier_supportsCage(scene, md) && (index <= lastCageIndex)) {
1164                                 sub = uiLayoutRow(row, true);
1165                                 if (index < cageIndex || !modifier_couldBeCage(scene, md)) {
1166                                         uiLayoutSetActive(sub, false);
1167                                 }
1168                                 uiItemR(sub, &ptr, "show_on_cage", 0, "", ICON_NONE);
1169                         }
1170                 } /* tessellation point for curve-typed objects */
1171                 else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
1172                         /* some modifiers could work with pre-tessellated curves only */
1173                         if (ELEM(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) {
1174                                 /* add disabled pre-tessellated button, so users could have
1175                                  * message for this modifiers */
1176                                 but = uiDefIconButBitI(block, UI_BTYPE_TOGGLE, eModifierMode_ApplyOnSpline, 0, ICON_SURFACE_DATA, 0, 0,
1177                                                        UI_UNIT_X - 2, UI_UNIT_Y, &md->mode, 0.0, 0.0, 0.0, 0.0,
1178                                                        TIP_("This modifier can only be applied on splines' points"));
1179                                 UI_but_flag_enable(but, UI_BUT_DISABLED);
1180                         }
1181                         else if (mti->type != eModifierTypeType_Constructive) {
1182                                 /* constructive modifiers tessellates curve before applying */
1183                                 uiItemR(row, &ptr, "use_apply_on_spline", 0, "", ICON_NONE);
1184                         }
1185                 }
1186
1187                 UI_block_align_end(block);
1188                 
1189                 /* Up/Down + Delete ........................... */
1190                 UI_block_align_begin(block);
1191                 uiItemO(row, "", ICON_TRIA_UP, "OBJECT_OT_modifier_move_up");
1192                 uiItemO(row, "", ICON_TRIA_DOWN, "OBJECT_OT_modifier_move_down");
1193                 UI_block_align_end(block);
1194                 
1195                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1196                 /* When Modifier is a simulation, show button to switch to context rather than the delete button. */
1197                 if (modifier_can_delete(md) &&
1198                     (!modifier_is_simulation(md) ||
1199                      STREQ(scene->view_render.engine_id, RE_engine_id_BLENDER_GAME)))
1200                 {
1201                         uiItemO(row, "", ICON_X, "OBJECT_OT_modifier_remove");
1202                 }
1203                 else if (modifier_is_simulation(md) == 1) {
1204                         uiItemStringO(row, "", ICON_BUTS, "WM_OT_properties_context_change", "context", "PHYSICS");
1205                 }
1206                 else if (modifier_is_simulation(md) == 2) {
1207                         uiItemStringO(row, "", ICON_BUTS, "WM_OT_properties_context_change", "context", "PARTICLES");
1208                 }
1209                 UI_block_emboss_set(block, UI_EMBOSS);
1210         }
1211
1212         
1213         /* modifier settings (under the header) --------------------------------------------------- */
1214         if (!isVirtual && (md->mode & eModifierMode_Expanded)) {
1215                 /* apply/convert/copy */
1216                 box = uiLayoutBox(column);
1217                 row = uiLayoutRow(box, false);
1218                 
1219                 if (!ELEM(md->type, eModifierType_Collision, eModifierType_Surface)) {
1220                         /* only here obdata, the rest of modifiers is ob level */
1221                         UI_block_lock_set(block, BKE_object_obdata_is_libdata(ob), ERROR_LIBDATA_MESSAGE);
1222                         
1223                         if (md->type == eModifierType_ParticleSystem) {
1224                                 ParticleSystem *psys = ((ParticleSystemModifierData *)md)->psys;
1225                                 
1226                                 if (!(ob->mode & OB_MODE_PARTICLE_EDIT)) {
1227                                         if (ELEM(psys->part->ren_as, PART_DRAW_GR, PART_DRAW_OB))
1228                                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Convert"), ICON_NONE,
1229                                                         "OBJECT_OT_duplicates_make_real");
1230                                         else if (psys->part->ren_as == PART_DRAW_PATH && psys->pathcache)
1231                                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Convert"), ICON_NONE,
1232                                                         "OBJECT_OT_modifier_convert");
1233                                 }
1234                         }
1235                         else {
1236                                 uiLayoutSetOperatorContext(row, WM_OP_INVOKE_DEFAULT);
1237                                 uiItemEnumO(row, "OBJECT_OT_modifier_apply", CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Apply"),
1238                                             0, "apply_as", MODIFIER_APPLY_DATA);
1239                                 
1240                                 if (modifier_isSameTopology(md) && !modifier_isNonGeometrical(md)) {
1241                                         uiItemEnumO(row, "OBJECT_OT_modifier_apply",
1242                                                     CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Apply as Shape Key"),
1243                                                     0, "apply_as", MODIFIER_APPLY_SHAPE);
1244                                 }
1245                         }
1246                         
1247                         UI_block_lock_clear(block);
1248                         UI_block_lock_set(block, ob && ID_IS_LINKED(ob), ERROR_LIBDATA_MESSAGE);
1249                         
1250                         if (!ELEM(md->type, eModifierType_Fluidsim, eModifierType_Softbody, eModifierType_ParticleSystem,
1251                                    eModifierType_Cloth, eModifierType_Smoke))
1252                         {
1253                                 uiItemO(row, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Copy"), ICON_NONE,
1254                                         "OBJECT_OT_modifier_copy");
1255                         }
1256                 }
1257                 
1258                 /* result is the layout block inside the box, that we return so that modifier settings can be drawn */
1259                 result = uiLayoutColumn(box, false);
1260                 block = uiLayoutAbsoluteBlock(box);
1261         }
1262         
1263         /* error messages */
1264         if (md->error) {
1265                 box = uiLayoutBox(column);
1266                 row = uiLayoutRow(box, false);
1267                 uiItemL(row, md->error, ICON_ERROR);
1268         }
1269         
1270         return result;
1271 }
1272
1273 uiLayout *uiTemplateModifier(uiLayout *layout, bContext *C, PointerRNA *ptr)
1274 {
1275         Scene *scene = CTX_data_scene(C);
1276         Object *ob;
1277         ModifierData *md, *vmd;
1278         VirtualModifierData virtualModifierData;
1279         int i, lastCageIndex, cageIndex;
1280
1281         /* verify we have valid data */
1282         if (!RNA_struct_is_a(ptr->type, &RNA_Modifier)) {
1283                 RNA_warning("Expected modifier on object");
1284                 return NULL;
1285         }
1286
1287         ob = ptr->id.data;
1288         md = ptr->data;
1289
1290         if (!ob || !(GS(ob->id.name) == ID_OB)) {
1291                 RNA_warning("Expected modifier on object");
1292                 return NULL;
1293         }
1294         
1295         UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
1296         
1297         /* find modifier and draw it */
1298         cageIndex = modifiers_getCageIndex(scene, ob, &lastCageIndex, 0);
1299
1300         /* XXX virtual modifiers are not accesible for python */
1301         vmd = modifiers_getVirtualModifierList(ob, &virtualModifierData);
1302
1303         for (i = 0; vmd; i++, vmd = vmd->next) {
1304                 if (md == vmd)
1305                         return draw_modifier(layout, scene, ob, md, i, cageIndex, lastCageIndex);
1306                 else if (vmd->mode & eModifierMode_Virtual)
1307                         i--;
1308         }
1309
1310         return NULL;
1311 }
1312
1313 /************************ Constraint Template *************************/
1314
1315 #include "DNA_constraint_types.h"
1316
1317 #include "BKE_action.h"
1318 #include "BKE_constraint.h"
1319
1320 #define B_CONSTRAINT_TEST           5
1321 // #define B_CONSTRAINT_CHANGETARGET   6
1322
1323 static void do_constraint_panels(bContext *C, void *ob_pt, int event)
1324 {
1325         Object *ob = (Object *)ob_pt;
1326
1327         switch (event) {
1328                 case B_CONSTRAINT_TEST:
1329                         break; /* no handling */
1330 #if 0   /* UNUSED */
1331                 case B_CONSTRAINT_CHANGETARGET:
1332                 {
1333                         Main *bmain = CTX_data_main(C);
1334                         if (ob->pose)
1335                                 BKE_pose_tag_recalc(bmain, ob->pose); /* checks & sorts pose channels */
1336                         DEG_relations_tag_update(bmain);
1337                         break;
1338                 }
1339 #endif
1340                 default:
1341                         break;
1342         }
1343
1344         /* note: RNA updates now call this, commenting else it gets called twice.
1345          * if there are problems because of this, then rna needs changed update functions.
1346          *
1347          * object_test_constraints(ob);
1348          * if (ob->pose) BKE_pose_update_constraint_flags(ob->pose); */
1349         
1350         if (ob->type == OB_ARMATURE) DEG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1351         else DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1352
1353         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1354 }
1355
1356 static void constraint_active_func(bContext *UNUSED(C), void *ob_v, void *con_v)
1357 {
1358         ED_object_constraint_set_active(ob_v, con_v);
1359 }
1360
1361 /* draw panel showing settings for a constraint */
1362 static uiLayout *draw_constraint(uiLayout *layout, Object *ob, bConstraint *con)
1363 {
1364         bPoseChannel *pchan = BKE_pose_channel_active(ob);
1365         const bConstraintTypeInfo *cti;
1366         uiBlock *block;
1367         uiLayout *result = NULL, *col, *box, *row;
1368         PointerRNA ptr;
1369         char typestr[32];
1370         short proxy_protected, xco = 0, yco = 0;
1371         // int rb_col; // UNUSED
1372
1373         /* get constraint typeinfo */
1374         cti = BKE_constraint_typeinfo_get(con);
1375         if (cti == NULL) {
1376                 /* exception for 'Null' constraint - it doesn't have constraint typeinfo! */
1377                 BLI_strncpy(typestr, (con->type == CONSTRAINT_TYPE_NULL) ? IFACE_("Null") : IFACE_("Unknown"), sizeof(typestr));
1378         }
1379         else
1380                 BLI_strncpy(typestr, IFACE_(cti->name), sizeof(typestr));
1381                 
1382         /* determine whether constraint is proxy protected or not */
1383         if (BKE_constraints_proxylocked_owner(ob, pchan))
1384                 proxy_protected = (con->flag & CONSTRAINT_PROXY_LOCAL) == 0;
1385         else
1386                 proxy_protected = 0;
1387
1388         /* unless button has own callback, it adds this callback to button */
1389         block = uiLayoutGetBlock(layout);
1390         UI_block_func_handle_set(block, do_constraint_panels, ob);
1391         UI_block_func_set(block, constraint_active_func, ob, con);
1392
1393         RNA_pointer_create(&ob->id, &RNA_Constraint, con, &ptr);
1394
1395         col = uiLayoutColumn(layout, true);
1396         uiLayoutSetContextPointer(col, "constraint", &ptr);
1397
1398         box = uiLayoutBox(col);
1399         row = uiLayoutRow(box, false);
1400         block = uiLayoutGetBlock(box);
1401
1402         /* Draw constraint header */
1403
1404         /* open/close */
1405         UI_block_emboss_set(block, UI_EMBOSS_NONE);
1406         uiItemR(row, &ptr, "show_expanded", UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
1407         UI_block_emboss_set(block, UI_EMBOSS);
1408
1409         /* name */
1410         uiDefBut(block, UI_BTYPE_LABEL, B_CONSTRAINT_TEST, typestr,
1411                  xco + 0.5f * UI_UNIT_X, yco, 5 * UI_UNIT_X, 0.9f * UI_UNIT_Y, NULL, 0.0, 0.0, 0.0, 0.0, "");
1412
1413         if (con->flag & CONSTRAINT_DISABLE)
1414                 uiLayoutSetRedAlert(row, true);
1415         
1416         if (proxy_protected == 0) {
1417                 uiItemR(row, &ptr, "name", 0, "", ICON_NONE);
1418         }
1419         else
1420                 uiItemL(row, con->name, ICON_NONE);
1421         
1422         uiLayoutSetRedAlert(row, false);
1423         
1424         /* proxy-protected constraints cannot be edited, so hide up/down + close buttons */
1425         if (proxy_protected) {
1426                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1427                 
1428                 /* draw a ghost icon (for proxy) and also a lock beside it, to show that constraint is "proxy locked" */
1429                 uiDefIconBut(block, UI_BTYPE_BUT, B_CONSTRAINT_TEST, ICON_GHOST, xco + 12.2f * UI_UNIT_X, yco, 0.95f * UI_UNIT_X, 0.95f * UI_UNIT_Y,
1430                              NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Proxy Protected"));
1431                 uiDefIconBut(block, UI_BTYPE_BUT, B_CONSTRAINT_TEST, ICON_LOCKED, xco + 13.1f * UI_UNIT_X, yco, 0.95f * UI_UNIT_X, 0.95f * UI_UNIT_Y,
1432                              NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Proxy Protected"));
1433                 
1434                 UI_block_emboss_set(block, UI_EMBOSS);
1435         }
1436         else {
1437                 short prev_proxylock, show_upbut, show_downbut;
1438                 
1439                 /* Up/Down buttons: 
1440                  *      Proxy-constraints are not allowed to occur after local (non-proxy) constraints
1441                  *      as that poses problems when restoring them, so disable the "up" button where
1442                  *      it may cause this situation. 
1443                  *
1444                  *  Up/Down buttons should only be shown (or not grayed - todo) if they serve some purpose.
1445                  */
1446                 if (BKE_constraints_proxylocked_owner(ob, pchan)) {
1447                         if (con->prev) {
1448                                 prev_proxylock = (con->prev->flag & CONSTRAINT_PROXY_LOCAL) ? 0 : 1;
1449                         }
1450                         else
1451                                 prev_proxylock = 0;
1452                 }
1453                 else
1454                         prev_proxylock = 0;
1455                         
1456                 show_upbut = ((prev_proxylock == 0) && (con->prev));
1457                 show_downbut = (con->next) ? 1 : 0;
1458                 
1459                 /* enabled */
1460                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1461                 uiItemR(row, &ptr, "mute", 0, "",
1462                         (con->flag & CONSTRAINT_OFF) ? ICON_RESTRICT_VIEW_ON : ICON_RESTRICT_VIEW_OFF);
1463                 UI_block_emboss_set(block, UI_EMBOSS);
1464                 
1465                 uiLayoutSetOperatorContext(row, WM_OP_INVOKE_DEFAULT);
1466                 
1467                 /* up/down */
1468                 if (show_upbut || show_downbut) {
1469                         UI_block_align_begin(block);
1470                         if (show_upbut)
1471                                 uiItemO(row, "", ICON_TRIA_UP, "CONSTRAINT_OT_move_up");
1472                                 
1473                         if (show_downbut)
1474                                 uiItemO(row, "", ICON_TRIA_DOWN, "CONSTRAINT_OT_move_down");
1475                         UI_block_align_end(block);
1476                 }
1477                 
1478                 /* Close 'button' - emboss calls here disable drawing of 'button' behind X */
1479                 UI_block_emboss_set(block, UI_EMBOSS_NONE);
1480                 uiItemO(row, "", ICON_X, "CONSTRAINT_OT_delete");
1481                 UI_block_emboss_set(block, UI_EMBOSS);
1482         }
1483
1484         /* Set but-locks for protected settings (magic numbers are used here!) */
1485         if (proxy_protected)
1486                 UI_block_lock_set(block, true, IFACE_("Cannot edit Proxy-Protected Constraint"));
1487
1488         /* Draw constraint data */
1489         if ((con->flag & CONSTRAINT_EXPAND) == 0) {
1490                 (yco) -= 10.5f * UI_UNIT_Y;
1491         }
1492         else {
1493                 box = uiLayoutBox(col);
1494                 block = uiLayoutAbsoluteBlock(box);
1495                 result = box;
1496         }
1497
1498         /* clear any locks set up for proxies/lib-linking */
1499         UI_block_lock_clear(block);
1500
1501         return result;
1502 }
1503
1504 uiLayout *uiTemplateConstraint(uiLayout *layout, PointerRNA *ptr)
1505 {
1506         Object *ob;
1507         bConstraint *con;
1508
1509         /* verify we have valid data */
1510         if (!RNA_struct_is_a(ptr->type, &RNA_Constraint)) {
1511                 RNA_warning("Expected constraint on object");
1512                 return NULL;
1513         }
1514
1515         ob = ptr->id.data;
1516         con = ptr->data;
1517
1518         if (!ob || !(GS(ob->id.name) == ID_OB)) {
1519                 RNA_warning("Expected constraint on object");
1520                 return NULL;
1521         }
1522         
1523         UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
1524
1525         /* hrms, the temporal constraint should not draw! */
1526         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
1527                 bKinematicConstraint *data = con->data;
1528                 if (data->flag & CONSTRAINT_IK_TEMP)
1529                         return NULL;
1530         }
1531
1532         return draw_constraint(layout, ob, con);
1533 }
1534
1535
1536 /************************* Preview Template ***************************/
1537
1538 #include "DNA_lamp_types.h"
1539 #include "DNA_material_types.h"
1540 #include "DNA_world_types.h"
1541
1542 #define B_MATPRV 1
1543
1544 static void do_preview_buttons(bContext *C, void *arg, int event)
1545 {
1546         switch (event) {
1547                 case B_MATPRV:
1548                         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_PREVIEW, arg);
1549                         break;
1550         }
1551 }
1552
1553 void uiTemplatePreview(
1554         uiLayout *layout, bContext *C, ID *id, int show_buttons, ID *parent, MTex *slot,
1555         const char *preview_id)
1556 {
1557         uiLayout *row, *col;
1558         uiBlock *block;
1559         uiPreview *ui_preview = NULL;
1560         ARegion *ar;
1561
1562         Material *ma = NULL;
1563         Tex *tex = (Tex *)id;
1564         ID *pid, *pparent;
1565         short *pr_texture = NULL;
1566         PointerRNA material_ptr;
1567         PointerRNA texture_ptr;
1568
1569         char _preview_id[UI_MAX_NAME_STR];
1570
1571         if (id && !ELEM(GS(id->name), ID_MA, ID_TE, ID_WO, ID_LA, ID_LS)) {
1572                 RNA_warning("Expected ID of type material, texture, lamp, world or line style");
1573                 return;
1574         }
1575
1576         /* decide what to render */
1577         pid = id;
1578         pparent = NULL;
1579
1580         if (id && (GS(id->name) == ID_TE)) {
1581                 if (parent && (GS(parent->name) == ID_MA))
1582                         pr_texture = &((Material *)parent)->pr_texture;
1583                 else if (parent && (GS(parent->name) == ID_WO))
1584                         pr_texture = &((World *)parent)->pr_texture;
1585                 else if (parent && (GS(parent->name) == ID_LA))
1586                         pr_texture = &((Lamp *)parent)->pr_texture;
1587                 else if (parent && (GS(parent->name) == ID_LS))
1588                         pr_texture = &((FreestyleLineStyle *)parent)->pr_texture;
1589
1590                 if (pr_texture) {
1591                         if (*pr_texture == TEX_PR_OTHER)
1592                                 pid = parent;
1593                         else if (*pr_texture == TEX_PR_BOTH)
1594                                 pparent = parent;
1595                 }
1596         }
1597
1598         if (!preview_id || (preview_id[0] == '\0')) {
1599                 /* If no identifier given, generate one from ID type. */
1600                 BLI_snprintf(_preview_id, UI_MAX_NAME_STR, "uiPreview_%s", BKE_idcode_to_name(GS(id->name)));
1601                 preview_id = _preview_id;
1602         }
1603
1604         /* Find or add the uiPreview to the current Region. */
1605         ar = CTX_wm_region(C);
1606         ui_preview = BLI_findstring(&ar->ui_previews, preview_id, offsetof(uiPreview, preview_id));
1607
1608         if (!ui_preview) {
1609                 ui_preview = MEM_callocN(sizeof(uiPreview), "uiPreview");
1610                 BLI_strncpy(ui_preview->preview_id, preview_id, sizeof(ui_preview->preview_id));
1611                 ui_preview->height = (short)(UI_UNIT_Y * 5.6f);
1612                 BLI_addtail(&ar->ui_previews, ui_preview);
1613         }
1614
1615         if (ui_preview->height < UI_UNIT_Y) {
1616                 ui_preview->height = UI_UNIT_Y;
1617         }
1618         else if (ui_preview->height > UI_UNIT_Y * 50) {  /* Rather high upper limit, yet not insane! */
1619                 ui_preview->height = UI_UNIT_Y * 50;
1620         }
1621
1622         /* layout */
1623         block = uiLayoutGetBlock(layout);
1624         row = uiLayoutRow(layout, false);
1625         col = uiLayoutColumn(row, false);
1626         uiLayoutSetKeepAspect(col, true);
1627
1628         /* add preview */
1629         uiDefBut(block, UI_BTYPE_EXTRA, 0, "", 0, 0, UI_UNIT_X * 10, ui_preview->height, pid, 0.0, 0.0, 0, 0, "");
1630         UI_but_func_drawextra_set(block, ED_preview_draw, pparent, slot);
1631         UI_block_func_handle_set(block, do_preview_buttons, NULL);
1632
1633         uiDefIconButS(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &ui_preview->height,
1634                       UI_UNIT_Y, UI_UNIT_Y * 50.0f, 0.0f, 0.0f, "");
1635
1636         /* add buttons */
1637         if (pid && show_buttons) {
1638                 if (GS(pid->name) == ID_MA || (pparent && GS(pparent->name) == ID_MA)) {
1639                         if (GS(pid->name) == ID_MA) ma = (Material *)pid;
1640                         else ma = (Material *)pparent;
1641                         
1642                         /* Create RNA Pointer */
1643                         RNA_pointer_create(&ma->id, &RNA_Material, ma, &material_ptr);
1644
1645                         col = uiLayoutColumn(row, true);
1646                         uiLayoutSetScaleX(col, 1.5);
1647                         uiItemR(col, &material_ptr, "preview_render_type", UI_ITEM_R_EXPAND, "", ICON_NONE);
1648                 }
1649
1650                 if (pr_texture) {
1651                         /* Create RNA Pointer */
1652                         RNA_pointer_create(id, &RNA_Texture, tex, &texture_ptr);
1653                         
1654                         uiLayoutRow(layout, true);
1655                         uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Texture"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1656                                   pr_texture, 10, TEX_PR_TEXTURE, 0, 0, "");
1657                         if (GS(parent->name) == ID_MA) {
1658                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Material"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1659                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1660                         }
1661                         else if (GS(parent->name) == ID_LA) {
1662                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Lamp"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1663                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1664                         }
1665                         else if (GS(parent->name) == ID_WO) {
1666                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("World"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1667                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1668                         }
1669                         else if (GS(parent->name) == ID_LS) {
1670                                 uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Line Style"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1671                                           pr_texture, 10, TEX_PR_OTHER, 0, 0, "");
1672                         }
1673                         uiDefButS(block, UI_BTYPE_ROW, B_MATPRV, IFACE_("Both"),  0, 0, UI_UNIT_X * 10, UI_UNIT_Y,
1674                                   pr_texture, 10, TEX_PR_BOTH, 0, 0, "");
1675                         
1676                         /* Alpha button for texture preview */
1677                         if (*pr_texture != TEX_PR_OTHER) {
1678                                 row = uiLayoutRow(layout, false);
1679                                 uiItemR(row, &texture_ptr, "use_preview_alpha", 0, NULL, ICON_NONE);
1680                         }
1681                 }
1682         }
1683 }
1684
1685 /********************** ColorRamp Template **************************/
1686
1687
1688 typedef struct RNAUpdateCb {
1689         PointerRNA ptr;
1690         PropertyRNA *prop;
1691 } RNAUpdateCb;
1692
1693 static void rna_update_cb(bContext *C, void *arg_cb, void *UNUSED(arg))
1694 {
1695         RNAUpdateCb *cb = (RNAUpdateCb *)arg_cb;
1696
1697         /* we call update here on the pointer property, this way the
1698          * owner of the curve mapping can still define it's own update
1699          * and notifier, even if the CurveMapping struct is shared. */
1700         RNA_property_update(C, &cb->ptr, cb->prop);
1701 }
1702
1703 static void colorband_add_cb(bContext *C, void *cb_v, void *coba_v)
1704 {
1705         ColorBand *coba = coba_v;
1706         float pos = 0.5f;
1707
1708         if (coba->tot > 1) {
1709                 if (coba->cur > 0) pos = (coba->data[coba->cur - 1].pos + coba->data[coba->cur].pos) * 0.5f;
1710                 else pos = (coba->data[coba->cur + 1].pos + coba->data[coba->cur].pos) * 0.5f;
1711         }
1712
1713         if (colorband_element_add(coba, pos)) {
1714                 rna_update_cb(C, cb_v, NULL);
1715                 ED_undo_push(C, "Add colorband");
1716         }
1717 }
1718
1719 static void colorband_del_cb(bContext *C, void *cb_v, void *coba_v)
1720 {
1721         ColorBand *coba = coba_v;
1722
1723         if (colorband_element_remove(coba, coba->cur)) {
1724                 ED_undo_push(C, "Delete colorband");
1725                 rna_update_cb(C, cb_v, NULL);
1726         }
1727 }
1728
1729 static void colorband_flip_cb(bContext *C, void *cb_v, void *coba_v)
1730 {
1731         CBData data_tmp[MAXCOLORBAND];
1732
1733         ColorBand *coba = coba_v;
1734         int a;
1735
1736         for (a = 0; a < coba->tot; a++) {
1737                 data_tmp[a] = coba->data[coba->tot - (a + 1)];
1738         }
1739         for (a = 0; a < coba->tot; a++) {
1740                 data_tmp[a].pos = 1.0f - data_tmp[a].pos;
1741                 coba->data[a] = data_tmp[a];
1742         }
1743
1744         /* may as well flip the cur*/
1745         coba->cur = coba->tot - (coba->cur + 1);
1746
1747         ED_undo_push(C, "Flip colorband");
1748
1749         rna_update_cb(C, cb_v, NULL);
1750 }
1751
1752 static void colorband_update_cb(bContext *UNUSED(C), void *bt_v, void *coba_v)
1753 {
1754         uiBut *bt = bt_v;
1755         ColorBand *coba = coba_v;
1756
1757         /* sneaky update here, we need to sort the colorband points to be in order,
1758          * however the RNA pointer then is wrong, so we update it */
1759         colorband_update_sort(coba);
1760         bt->rnapoin.data = coba->data + coba->cur;
1761 }
1762
1763 static void colorband_buttons_layout(
1764         uiLayout *layout, uiBlock *block, ColorBand *coba, const rctf *butr,
1765         RNAUpdateCb *cb, int expand)
1766 {
1767         uiLayout *row, *split, *subsplit;
1768         uiBut *bt;
1769         float unit = BLI_rctf_size_x(butr) / 14.0f;
1770         float xs = butr->xmin;
1771         float ys = butr->ymin;
1772         PointerRNA ptr;
1773
1774         RNA_pointer_create(cb->ptr.id.data, &RNA_ColorRamp, coba, &ptr);
1775
1776         split = uiLayoutSplit(layout, 0.4f, false);
1777
1778         UI_block_emboss_set(block, UI_EMBOSS_NONE);
1779         UI_block_align_begin(block);
1780         row = uiLayoutRow(split, false);
1781
1782         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, "", 0, 0, 2.0f * unit, UI_UNIT_Y, NULL,
1783                               0, 0, 0, 0, TIP_("Add a new color stop to the colorband"));
1784
1785         UI_but_funcN_set(bt, colorband_add_cb, MEM_dupallocN(cb), coba);
1786
1787         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMOUT, "", xs +  2.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1788                       NULL, 0, 0, 0, 0, TIP_("Delete the active position"));
1789         UI_but_funcN_set(bt, colorband_del_cb, MEM_dupallocN(cb), coba);
1790
1791         bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
1792                       NULL, 0, 0, 0, 0, TIP_("Flip the color ramp"));
1793         UI_but_funcN_set(bt, colorband_flip_cb, MEM_dupallocN(cb), coba);
1794         UI_block_align_end(block);
1795         UI_block_emboss_set(block, UI_EMBOSS);
1796
1797         row = uiLayoutRow(split, false);
1798
1799         UI_block_align_begin(block);
1800         uiItemR(row, &ptr, "color_mode", 0, "", ICON_NONE);
1801         if (ELEM(coba->color_mode, COLBAND_BLEND_HSV, COLBAND_BLEND_HSL)) {
1802                 uiItemR(row, &ptr, "hue_interpolation", 0, "", ICON_NONE);
1803         }
1804         else {  /* COLBAND_BLEND_RGB */
1805                 uiItemR(row, &ptr, "interpolation", 0, "", ICON_NONE);
1806         }
1807         UI_block_align_end(block);
1808
1809         row = uiLayoutRow(layout, false);
1810
1811         bt = uiDefBut(block, UI_BTYPE_COLORBAND, 0, "", xs, ys, BLI_rctf_size_x(butr), UI_UNIT_Y, coba, 0, 0, 0, 0, "");
1812         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1813
1814         row = uiLayoutRow(layout, false);
1815
1816         if (coba->tot) {
1817                 CBData *cbd = coba->data + coba->cur;
1818
1819                 RNA_pointer_create(cb->ptr.id.data, &RNA_ColorRampElement, cbd, &ptr);
1820
1821                 if (!expand) {
1822                         split = uiLayoutSplit(layout, 0.3f, false);
1823
1824                         row = uiLayoutRow(split, false);
1825                         uiDefButS(block, UI_BTYPE_NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1826                                   0, 0, TIP_("Choose active color stop"));
1827                         row = uiLayoutRow(split, false);
1828                         uiItemR(row, &ptr, "position", 0, IFACE_("Pos"), ICON_NONE);
1829                         bt = block->buttons.last;
1830                         bt->a1 = 1.0f; /* gives a bit more precision for modifying position */
1831                         UI_but_func_set(bt, colorband_update_cb, bt, coba);
1832
1833                         row = uiLayoutRow(layout, false);
1834                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1835                         bt = block->buttons.last;
1836                         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1837                 }
1838                 else {
1839                         split = uiLayoutSplit(layout, 0.5f, false);
1840                         subsplit = uiLayoutSplit(split, 0.35f, false);
1841
1842                         row = uiLayoutRow(subsplit, false);
1843                         uiDefButS(block, UI_BTYPE_NUM, 0, "", 0, 0, 5.0f * UI_UNIT_X, UI_UNIT_Y, &coba->cur, 0.0, (float)(MAX2(0, coba->tot - 1)),
1844                                   0, 0, TIP_("Choose active color stop"));
1845                         row = uiLayoutRow(subsplit, false);
1846                         uiItemR(row, &ptr, "position", UI_ITEM_R_SLIDER, IFACE_("Pos"), ICON_NONE);
1847                         bt = block->buttons.last;
1848                         bt->a1 = 1.0f; /* gives a bit more precision for modifying position */
1849                         UI_but_func_set(bt, colorband_update_cb, bt, coba);
1850
1851                         row = uiLayoutRow(split, false);
1852                         uiItemR(row, &ptr, "color", 0, "", ICON_NONE);
1853                         bt = block->buttons.last;
1854                         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
1855                 }
1856         }
1857 }
1858
1859 void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname, int expand)
1860 {
1861         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1862         PointerRNA cptr;
1863         RNAUpdateCb *cb;
1864         uiBlock *block;
1865         ID *id;
1866         rctf rect;
1867
1868         if (!prop || RNA_property_type(prop) != PROP_POINTER)
1869                 return;
1870
1871         cptr = RNA_property_pointer_get(ptr, prop);
1872         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_ColorRamp))
1873                 return;
1874
1875         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
1876         cb->ptr = *ptr;
1877         cb->prop = prop;
1878
1879         rect.xmin = 0; rect.xmax = 10.0f * UI_UNIT_X;
1880         rect.ymin = 0; rect.ymax = 19.5f * UI_UNIT_X;
1881
1882         block = uiLayoutAbsoluteBlock(layout);
1883
1884         id = cptr.id.data;
1885         UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
1886
1887         colorband_buttons_layout(layout, block, cptr.data, &rect, cb, expand);
1888
1889         UI_block_lock_clear(block);
1890
1891         MEM_freeN(cb);
1892 }
1893
1894
1895 /********************* Icon viewer Template ************************/
1896 typedef struct IconViewMenuArgs {
1897         PointerRNA ptr;
1898         PropertyRNA *prop;
1899         bool show_labels;
1900         float icon_scale;
1901 } IconViewMenuArgs;
1902
1903 /* ID Search browse menu, open */
1904 static uiBlock *ui_icon_view_menu_cb(bContext *C, ARegion *ar, void *arg_litem)
1905 {
1906         static IconViewMenuArgs args;
1907         uiBlock *block;
1908         uiBut *but;
1909         int icon, value;
1910         const EnumPropertyItem *item;
1911         int a;
1912         bool free;
1913         int w, h;
1914
1915         /* arg_litem is malloced, can be freed by parent button */
1916         args = *((IconViewMenuArgs *) arg_litem);
1917         w = UI_UNIT_X * (args.icon_scale);
1918         h = UI_UNIT_X * (args.icon_scale + args.show_labels);
1919
1920         block = UI_block_begin(C, ar, "_popup", UI_EMBOSS_PULLDOWN);
1921         UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NO_FLIP);
1922
1923         RNA_property_enum_items(C, &args.ptr, args.prop, &item, NULL, &free);
1924
1925         for (a = 0; item[a].identifier; a++) {
1926                 int x, y;
1927
1928                 x = (a % 8) * w;
1929                 y = -(a / 8) * h;
1930
1931                 icon = item[a].icon;
1932                 value = item[a].value;
1933                 if (args.show_labels) {
1934                         but = uiDefIconTextButR_prop(
1935                                 block, UI_BTYPE_ROW, 0, icon, item[a].name, x, y, w, h,
1936                                 &args.ptr, args.prop, -1, 0, value, -1, -1, NULL);
1937                 }
1938                 else {
1939                         but = uiDefIconButR_prop(
1940                                 block, UI_BTYPE_ROW, 0, icon, x, y, w, h,
1941                                 &args.ptr, args.prop, -1, 0, value, -1, -1, NULL);
1942                 }
1943                 ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
1944         }
1945
1946         UI_block_bounds_set_normal(block, 0.3f * U.widget_unit);
1947         UI_block_direction_set(block, UI_DIR_DOWN);
1948
1949         if (free) {
1950                 MEM_freeN((void *)item);
1951         }
1952         
1953         return block;
1954 }
1955
1956 /**
1957  * \param icon_scale: Scale of the icon, 1x == button height.
1958  */
1959 void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname, int show_labels, float icon_scale)
1960 {
1961         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
1962         IconViewMenuArgs *cb_args;
1963         const EnumPropertyItem *items;
1964         uiBlock *block;
1965         uiBut *but;
1966         int value, icon = ICON_NONE, tot_items;
1967         bool free_items;
1968
1969         if (!prop || RNA_property_type(prop) != PROP_ENUM) {
1970                 RNA_warning("property of type Enum not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
1971                 return;
1972         }
1973
1974         block = uiLayoutAbsoluteBlock(layout);
1975
1976         RNA_property_enum_items(block->evil_C, ptr, prop, &items, &tot_items, &free_items);
1977         value = RNA_property_enum_get(ptr, prop);
1978         RNA_enum_icon_from_value(items, value, &icon);
1979
1980         cb_args = MEM_callocN(sizeof(IconViewMenuArgs), __func__);
1981         cb_args->ptr = *ptr;
1982         cb_args->prop = prop;
1983         cb_args->show_labels = show_labels;
1984         cb_args->icon_scale = icon_scale;
1985
1986         but = uiDefBlockButN(block, ui_icon_view_menu_cb, cb_args, "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6, "");
1987
1988         ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
1989
1990         if (free_items) {
1991                 MEM_freeN((void *)items);
1992         }
1993 }
1994
1995 /********************* Histogram Template ************************/
1996
1997 void uiTemplateHistogram(uiLayout *layout, PointerRNA *ptr, const char *propname)
1998 {
1999         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2000         PointerRNA cptr;
2001         uiBlock *block;
2002         uiLayout *col;
2003         Histogram *hist;
2004
2005         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2006                 return;
2007
2008         cptr = RNA_property_pointer_get(ptr, prop);
2009         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Histogram))
2010                 return;
2011         hist = (Histogram *)cptr.data;
2012
2013         if (hist->height < UI_UNIT_Y) {
2014                 hist->height = UI_UNIT_Y;
2015         }
2016         else if (hist->height > UI_UNIT_Y * 20) {
2017                 hist->height = UI_UNIT_Y * 20;
2018         }
2019
2020         col = uiLayoutColumn(layout, true);
2021         block = uiLayoutGetBlock(col);
2022
2023         uiDefBut(block, UI_BTYPE_HISTOGRAM, 0, "", 0, 0, UI_UNIT_X * 10, hist->height, hist, 0, 0, 0, 0, "");
2024
2025         /* Resize grip. */
2026         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &hist->height,
2027                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2028 }
2029
2030 /********************* Waveform Template ************************/
2031
2032 void uiTemplateWaveform(uiLayout *layout, PointerRNA *ptr, const char *propname)
2033 {
2034         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2035         PointerRNA cptr;
2036         uiBlock *block;
2037         uiLayout *col;
2038         Scopes *scopes;
2039
2040         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2041                 return;
2042
2043         cptr = RNA_property_pointer_get(ptr, prop);
2044         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
2045                 return;
2046         scopes = (Scopes *)cptr.data;
2047
2048         col = uiLayoutColumn(layout, true);
2049         block = uiLayoutGetBlock(col);
2050
2051         if (scopes->wavefrm_height < UI_UNIT_Y) {
2052                 scopes->wavefrm_height = UI_UNIT_Y;
2053         }
2054         else if (scopes->wavefrm_height > UI_UNIT_Y * 20) {
2055                 scopes->wavefrm_height = UI_UNIT_Y * 20;
2056         }
2057
2058         uiDefBut(block, UI_BTYPE_WAVEFORM, 0, "", 0, 0, UI_UNIT_X * 10, scopes->wavefrm_height, scopes, 0, 0, 0, 0, "");
2059
2060         /* Resize grip. */
2061         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &scopes->wavefrm_height,
2062                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2063 }
2064
2065 /********************* Vectorscope Template ************************/
2066
2067 void uiTemplateVectorscope(uiLayout *layout, PointerRNA *ptr, const char *propname)
2068 {
2069         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2070         PointerRNA cptr;
2071         uiBlock *block;
2072         uiLayout *col;
2073         Scopes *scopes;
2074
2075         if (!prop || RNA_property_type(prop) != PROP_POINTER)
2076                 return;
2077
2078         cptr = RNA_property_pointer_get(ptr, prop);
2079         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Scopes))
2080                 return;
2081         scopes = (Scopes *)cptr.data;
2082
2083         if (scopes->vecscope_height < UI_UNIT_Y) {
2084                 scopes->vecscope_height = UI_UNIT_Y;
2085         }
2086         else if (scopes->vecscope_height > UI_UNIT_Y * 20) {
2087                 scopes->vecscope_height = UI_UNIT_Y * 20;
2088         }
2089
2090         col = uiLayoutColumn(layout, true);
2091         block = uiLayoutGetBlock(col);
2092
2093         uiDefBut(block, UI_BTYPE_VECTORSCOPE, 0, "", 0, 0, UI_UNIT_X * 10, scopes->vecscope_height, scopes, 0, 0, 0, 0, "");
2094
2095         /* Resize grip. */
2096         uiDefIconButI(block, UI_BTYPE_GRIP, 0, ICON_GRIP, 0, 0, UI_UNIT_X * 10, (short)(UI_UNIT_Y * 0.3f), &scopes->vecscope_height,
2097                       UI_UNIT_Y, UI_UNIT_Y * 20.0f, 0.0f, 0.0f, "");
2098 }
2099
2100 /********************* CurveMapping Template ************************/
2101
2102
2103 static void curvemap_buttons_zoom_in(bContext *C, void *cumap_v, void *UNUSED(arg))
2104 {
2105         CurveMapping *cumap = cumap_v;
2106         float d;
2107
2108         /* we allow 20 times zoom */
2109         if (BLI_rctf_size_x(&cumap->curr) > 0.04f * BLI_rctf_size_x(&cumap->clipr)) {
2110                 d = 0.1154f * BLI_rctf_size_x(&cumap->curr);
2111                 cumap->curr.xmin += d;
2112                 cumap->curr.xmax -= d;
2113                 d = 0.1154f * BLI_rctf_size_y(&cumap->curr);
2114                 cumap->curr.ymin += d;
2115                 cumap->curr.ymax -= d;
2116         }
2117
2118         ED_region_tag_redraw(CTX_wm_region(C));
2119 }
2120
2121 static void curvemap_buttons_zoom_out(bContext *C, void *cumap_v, void *UNUSED(unused))
2122 {
2123         CurveMapping *cumap = cumap_v;
2124         float d, d1;
2125
2126         /* we allow 20 times zoom, but don't view outside clip */
2127         if (BLI_rctf_size_x(&cumap->curr) < 20.0f * BLI_rctf_size_x(&cumap->clipr)) {
2128                 d = d1 = 0.15f * BLI_rctf_size_x(&cumap->curr);
2129
2130                 if (cumap->flag & CUMA_DO_CLIP) 
2131                         if (cumap->curr.xmin - d < cumap->clipr.xmin)
2132                                 d1 = cumap->curr.xmin - cumap->clipr.xmin;
2133                 cumap->curr.xmin -= d1;
2134
2135                 d1 = d;
2136                 if (cumap->flag & CUMA_DO_CLIP) 
2137                         if (cumap->curr.xmax + d > cumap->clipr.xmax)
2138                                 d1 = -cumap->curr.xmax + cumap->clipr.xmax;
2139                 cumap->curr.xmax += d1;
2140
2141                 d = d1 = 0.15f * BLI_rctf_size_y(&cumap->curr);
2142
2143                 if (cumap->flag & CUMA_DO_CLIP) 
2144                         if (cumap->curr.ymin - d < cumap->clipr.ymin)
2145                                 d1 = cumap->curr.ymin - cumap->clipr.ymin;
2146                 cumap->curr.ymin -= d1;
2147
2148                 d1 = d;
2149                 if (cumap->flag & CUMA_DO_CLIP) 
2150                         if (cumap->curr.ymax + d > cumap->clipr.ymax)
2151                                 d1 = -cumap->curr.ymax + cumap->clipr.ymax;
2152                 cumap->curr.ymax += d1;
2153         }
2154
2155         ED_region_tag_redraw(CTX_wm_region(C));
2156 }
2157
2158 static void curvemap_buttons_setclip(bContext *UNUSED(C), void *cumap_v, void *UNUSED(arg))
2159 {
2160         CurveMapping *cumap = cumap_v;
2161
2162         curvemapping_changed(cumap, false);
2163 }       
2164
2165 static void curvemap_buttons_delete(bContext *C, void *cb_v, void *cumap_v)
2166 {
2167         CurveMapping *cumap = cumap_v;
2168
2169         curvemap_remove(cumap->cm + cumap->cur, SELECT);
2170         curvemapping_changed(cumap, false);
2171
2172         rna_update_cb(C, cb_v, NULL);
2173 }
2174
2175 /* NOTE: this is a block-menu, needs 0 events, otherwise the menu closes */
2176 static uiBlock *curvemap_clipping_func(bContext *C, ARegion *ar, void *cumap_v)
2177 {
2178         CurveMapping *cumap = cumap_v;
2179         uiBlock *block;
2180         uiBut *bt;
2181         float width = 8 * UI_UNIT_X;
2182
2183         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
2184
2185         /* use this for a fake extra empy space around the buttons */
2186         uiDefBut(block, UI_BTYPE_LABEL, 0, "",           -4, 16, width + 8, 6 * UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
2187
2188         bt = uiDefButBitI(block, UI_BTYPE_TOGGLE, CUMA_DO_CLIP, 1, IFACE_("Use Clipping"),
2189                           0, 5 * UI_UNIT_Y, width, UI_UNIT_Y, &cumap->flag, 0.0, 0.0, 10, 0, "");
2190         UI_but_func_set(bt, curvemap_buttons_setclip, cumap, NULL);
2191
2192         UI_block_align_begin(block);
2193         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Min X "),   0, 4 * UI_UNIT_Y, width, UI_UNIT_Y,
2194                   &cumap->clipr.xmin, -100.0, cumap->clipr.xmax, 10, 2, "");
2195         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Min Y "),   0, 3 * UI_UNIT_Y, width, UI_UNIT_Y,
2196                   &cumap->clipr.ymin, -100.0, cumap->clipr.ymax, 10, 2, "");
2197         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Max X "),   0, 2 * UI_UNIT_Y, width, UI_UNIT_Y,
2198                   &cumap->clipr.xmax, cumap->clipr.xmin, 100.0, 10, 2, "");
2199         uiDefButF(block, UI_BTYPE_NUM, 0, IFACE_("Max Y "),   0, UI_UNIT_Y, width, UI_UNIT_Y,
2200                   &cumap->clipr.ymax, cumap->clipr.ymin, 100.0, 10, 2, "");
2201
2202         UI_block_direction_set(block, UI_DIR_RIGHT);
2203
2204         return block;
2205 }
2206
2207 /* only for curvemap_tools_dofunc */
2208 enum {
2209         UICURVE_FUNC_RESET_NEG,
2210         UICURVE_FUNC_RESET_POS,
2211         UICURVE_FUNC_RESET_VIEW,
2212         UICURVE_FUNC_HANDLE_VECTOR,
2213         UICURVE_FUNC_HANDLE_AUTO,
2214         UICURVE_FUNC_HANDLE_AUTO_ANIM,
2215         UICURVE_FUNC_EXTEND_HOZ,
2216         UICURVE_FUNC_EXTEND_EXP,
2217 };
2218
2219 static void curvemap_tools_dofunc(bContext *C, void *cumap_v, int event)
2220 {
2221         CurveMapping *cumap = cumap_v;
2222         CurveMap *cuma = cumap->cm + cumap->cur;
2223
2224         switch (event) {
2225                 case UICURVE_FUNC_RESET_NEG:
2226                 case UICURVE_FUNC_RESET_POS: /* reset */
2227                         curvemap_reset(cuma, &cumap->clipr, cumap->preset,
2228                                        (event == UICURVE_FUNC_RESET_NEG) ? CURVEMAP_SLOPE_NEGATIVE : CURVEMAP_SLOPE_POSITIVE);
2229                         curvemapping_changed(cumap, false);
2230                         break;
2231                 case UICURVE_FUNC_RESET_VIEW:
2232                         cumap->curr = cumap->clipr;
2233                         break;
2234                 case UICURVE_FUNC_HANDLE_VECTOR: /* set vector */
2235                         curvemap_handle_set(cuma, HD_VECT);
2236                         curvemapping_changed(cumap, false);
2237                         break;
2238                 case UICURVE_FUNC_HANDLE_AUTO: /* set auto */
2239                         curvemap_handle_set(cuma, HD_AUTO);
2240                         curvemapping_changed(cumap, false);
2241                         break;
2242                 case UICURVE_FUNC_HANDLE_AUTO_ANIM: /* set auto-clamped */
2243                         curvemap_handle_set(cuma, HD_AUTO_ANIM);
2244                         curvemapping_changed(cumap, false);
2245                         break;
2246                 case UICURVE_FUNC_EXTEND_HOZ: /* extend horiz */
2247                         cuma->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
2248                         curvemapping_changed(cumap, false);
2249                         break;
2250                 case UICURVE_FUNC_EXTEND_EXP: /* extend extrapolate */
2251                         cuma->flag |= CUMA_EXTEND_EXTRAPOLATE;
2252                         curvemapping_changed(cumap, false);
2253                         break;
2254         }
2255         ED_undo_push(C, "CurveMap tools");
2256         ED_region_tag_redraw(CTX_wm_region(C));
2257 }
2258
2259 static uiBlock *curvemap_tools_func(
2260         bContext *C, ARegion *ar, CurveMapping *cumap,
2261         bool show_extend, int reset_mode)
2262 {
2263         uiBlock *block;
2264         short yco = 0, menuwidth = 10 * UI_UNIT_X;
2265
2266         block = UI_block_begin(C, ar, __func__, UI_EMBOSS);
2267         UI_block_func_butmenu_set(block, curvemap_tools_dofunc, cumap);
2268
2269         {
2270                 uiDefIconTextBut(
2271                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Reset View"),
2272                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_RESET_VIEW, "");
2273                 uiDefIconTextBut(
2274                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Vector Handle"),
2275                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_VECTOR, "");
2276                 uiDefIconTextBut(
2277                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Auto Handle"),
2278                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO, "");
2279                 uiDefIconTextBut(
2280                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Auto Clamped Handle"),
2281                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_HANDLE_AUTO_ANIM, "");
2282         }
2283
2284         if (show_extend) {
2285                 uiDefIconTextBut(
2286                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Extend Horizontal"),
2287                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_HOZ, "");
2288                 uiDefIconTextBut(
2289                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Extend Extrapolated"),
2290                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, UICURVE_FUNC_EXTEND_EXP, "");
2291         }
2292
2293         {
2294                 uiDefIconTextBut(
2295                         block, UI_BTYPE_BUT_MENU, 1, ICON_BLANK1, IFACE_("Reset Curve"),
2296                         0, yco -= UI_UNIT_Y, menuwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, reset_mode, "");
2297         }
2298
2299         UI_block_direction_set(block, UI_DIR_RIGHT);
2300         UI_block_bounds_set_text(block, 50);
2301
2302         return block;
2303 }
2304
2305 static uiBlock *curvemap_tools_posslope_func(bContext *C, ARegion *ar, void *cumap_v)
2306 {
2307         return curvemap_tools_func(C, ar, cumap_v, true, UICURVE_FUNC_RESET_POS);
2308 }
2309
2310 static uiBlock *curvemap_tools_negslope_func(bContext *C, ARegion *ar, void *cumap_v)
2311 {
2312         return curvemap_tools_func(C, ar, cumap_v, true, UICURVE_FUNC_RESET_NEG);
2313 }
2314
2315 static uiBlock *curvemap_brush_tools_func(bContext *C, ARegion *ar, void *cumap_v)
2316 {
2317         return curvemap_tools_func(C, ar, cumap_v, false, UICURVE_FUNC_RESET_NEG);
2318 }
2319
2320 static void curvemap_buttons_redraw(bContext *C, void *UNUSED(arg1), void *UNUSED(arg2))
2321 {
2322         ED_region_tag_redraw(CTX_wm_region(C));
2323 }
2324
2325 static void curvemap_buttons_update(bContext *C, void *arg1_v, void *cumap_v)
2326 {
2327         CurveMapping *cumap = cumap_v;
2328         curvemapping_changed(cumap, true);
2329         rna_update_cb(C, arg1_v, NULL);
2330 }
2331
2332 static void curvemap_buttons_reset(bContext *C, void *cb_v, void *cumap_v)
2333 {
2334         CurveMapping *cumap = cumap_v;
2335         int a;
2336         
2337         cumap->preset = CURVE_PRESET_LINE;
2338         for (a = 0; a < CM_TOT; a++)
2339                 curvemap_reset(cumap->cm + a, &cumap->clipr, cumap->preset, CURVEMAP_SLOPE_POSITIVE);
2340         
2341         cumap->black[0] = cumap->black[1] = cumap->black[2] = 0.0f;
2342         cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f;
2343         curvemapping_set_black_white(cumap, NULL, NULL);
2344         
2345         curvemapping_changed(cumap, false);
2346
2347         rna_update_cb(C, cb_v, NULL);
2348 }
2349
2350 /* still unsure how this call evolves... we use labeltype for defining what curve-channels to show */
2351 static void curvemap_buttons_layout(
2352         uiLayout *layout, PointerRNA *ptr, char labeltype, int levels,
2353         int brush, int neg_slope, RNAUpdateCb *cb)
2354 {
2355         CurveMapping *cumap = ptr->data;
2356         CurveMap *cm = &cumap->cm[cumap->cur];
2357         CurveMapPoint *cmp = NULL;
2358         uiLayout *row, *sub, *split;
2359         uiBlock *block;
2360         uiBut *bt;
2361         float dx = UI_UNIT_X;
2362         int icon, size;
2363         int bg = -1, i;
2364
2365         block = uiLayoutGetBlock(layout);
2366
2367         /* curve chooser */
2368         row = uiLayoutRow(layout, false);
2369
2370         if (labeltype == 'v') {
2371                 /* vector */
2372                 sub = uiLayoutRow(row, true);
2373                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2374
2375                 if (cumap->cm[0].curve) {
2376                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "X", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2377                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2378                 }
2379                 if (cumap->cm[1].curve) {
2380                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "Y", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2381                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2382                 }
2383                 if (cumap->cm[2].curve) {
2384                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "Z", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2385                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2386                 }
2387         }
2388         else if (labeltype == 'c') {
2389                 /* color */
2390                 sub = uiLayoutRow(row, true);
2391                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2392
2393                 if (cumap->cm[3].curve) {
2394                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "C", 0, 0, dx, dx, &cumap->cur, 0.0, 3.0, 0.0, 0.0, "");
2395                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2396                 }
2397                 if (cumap->cm[0].curve) {
2398                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "R", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2399                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2400                 }
2401                 if (cumap->cm[1].curve) {
2402                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "G", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2403                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2404                 }
2405                 if (cumap->cm[2].curve) {
2406                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "B", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2407                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2408                 }
2409         }
2410         else if (labeltype == 'h') {
2411                 /* HSV */
2412                 sub = uiLayoutRow(row, true);
2413                 uiLayoutSetAlignment(sub, UI_LAYOUT_ALIGN_LEFT);
2414                 
2415                 if (cumap->cm[0].curve) {
2416                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "H", 0, 0, dx, dx, &cumap->cur, 0.0, 0.0, 0.0, 0.0, "");
2417                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2418                 }
2419                 if (cumap->cm[1].curve) {
2420                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "S", 0, 0, dx, dx, &cumap->cur, 0.0, 1.0, 0.0, 0.0, "");
2421                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2422                 }
2423                 if (cumap->cm[2].curve) {
2424                         bt = uiDefButI(block, UI_BTYPE_ROW, 0, "V", 0, 0, dx, dx, &cumap->cur, 0.0, 2.0, 0.0, 0.0, "");
2425                         UI_but_func_set(bt, curvemap_buttons_redraw, NULL, NULL);
2426                 }
2427         }
2428         else
2429                 uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_RIGHT);
2430         
2431         if (labeltype == 'h')
2432                 bg = UI_GRAD_H;
2433
2434         /* operation buttons */
2435         sub = uiLayoutRow(row, true);
2436
2437         UI_block_emboss_set(block, UI_EMBOSS_NONE);
2438
2439         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_ZOOM_IN, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom in"));
2440         UI_but_func_set(bt, curvemap_buttons_zoom_in, cumap, NULL);
2441
2442         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_ZOOM_OUT, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Zoom out"));
2443         UI_but_func_set(bt, curvemap_buttons_zoom_out, cumap, NULL);
2444
2445         if (brush)
2446                 bt = uiDefIconBlockBut(block, curvemap_brush_tools_func, cumap, 0, ICON_MODIFIER, 0, 0, dx, dx, TIP_("Tools"));
2447         else if (neg_slope)
2448                 bt = uiDefIconBlockBut(block, curvemap_tools_negslope_func, cumap, 0, ICON_MODIFIER,
2449                                        0, 0, dx, dx, TIP_("Tools"));
2450         else
2451                 bt = uiDefIconBlockBut(block, curvemap_tools_posslope_func, cumap, 0, ICON_MODIFIER,
2452                                        0, 0, dx, dx, TIP_("Tools"));
2453
2454         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2455
2456         icon = (cumap->flag & CUMA_DO_CLIP) ? ICON_CLIPUV_HLT : ICON_CLIPUV_DEHLT;
2457         bt = uiDefIconBlockBut(block, curvemap_clipping_func, cumap, 0, icon, 0, 0, dx, dx, TIP_("Clipping Options"));
2458         UI_but_funcN_set(bt, rna_update_cb, MEM_dupallocN(cb), NULL);
2459
2460         bt = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, dx, dx, NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Delete points"));
2461         UI_but_funcN_set(bt, curvemap_buttons_delete, MEM_dupallocN(cb), cumap);
2462
2463         UI_block_emboss_set(block, UI_EMBOSS);
2464
2465         UI_block_funcN_set(block, rna_update_cb, MEM_dupallocN(cb), NULL);
2466
2467         /* curve itself */
2468         size = uiLayoutGetWidth(layout);
2469         row = uiLayoutRow(layout, false);
2470         uiDefBut(block, UI_BTYPE_CURVE, 0, "", 0, 0, size, 8.0f * UI_UNIT_X, cumap, 0.0f, 1.0f, bg, 0, "");
2471
2472         /* sliders for selected point */
2473         for (i = 0; i < cm->totpoint; i++) {
2474                 if (cm->curve[i].flag & CUMA_SELECT) {
2475                         cmp = &cm->curve[i];
2476                         break;
2477                 }
2478         }
2479
2480         if (cmp) {
2481                 rctf bounds;
2482
2483                 if (cumap->flag & CUMA_DO_CLIP) {
2484                         bounds = cumap->clipr;
2485                 }
2486                 else {
2487                         bounds.xmin = bounds.ymin = -1000.0;
2488                         bounds.xmax = bounds.ymax =  1000.0;
2489                 }
2490
2491                 uiLayoutRow(layout, true);
2492                 UI_block_funcN_set(block, curvemap_buttons_update, MEM_dupallocN(cb), cumap);
2493                 uiDefButF(block, UI_BTYPE_NUM, 0, "X", 0, 2 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2494                           &cmp->x, bounds.xmin, bounds.xmax, 1, 5, "");
2495                 uiDefButF(block, UI_BTYPE_NUM, 0, "Y", 0, 1 * UI_UNIT_Y, UI_UNIT_X * 10, UI_UNIT_Y,
2496                           &cmp->y, bounds.ymin, bounds.ymax, 1, 5, "");
2497         }
2498
2499         /* black/white levels */
2500         if (levels) {
2501                 split = uiLayoutSplit(layout, 0.0f, false);
2502                 uiItemR(uiLayoutColumn(split, false), ptr, "black_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2503                 uiItemR(uiLayoutColumn(split, false), ptr, "white_level", UI_ITEM_R_EXPAND, NULL, ICON_NONE);
2504
2505                 uiLayoutRow(layout, false);
2506                 bt = uiDefBut(block, UI_BTYPE_BUT, 0, IFACE_("Reset"), 0, 0, UI_UNIT_X * 10, UI_UNIT_Y, NULL, 0.0f, 0.0f, 0, 0,
2507                               TIP_("Reset Black/White point and curves"));
2508                 UI_but_funcN_set(bt, curvemap_buttons_reset, MEM_dupallocN(cb), cumap);
2509         }
2510
2511         UI_block_funcN_set(block, NULL, NULL, NULL);
2512 }
2513
2514 void uiTemplateCurveMapping(
2515         uiLayout *layout, PointerRNA *ptr, const char *propname, int type,
2516         int levels, int brush, int neg_slope)
2517 {
2518         RNAUpdateCb *cb;
2519         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2520         PointerRNA cptr;
2521         ID *id;
2522         uiBlock *block = uiLayoutGetBlock(layout);
2523
2524         if (!prop) {
2525                 RNA_warning("curve property not found: %s.%s",
2526                             RNA_struct_identifier(ptr->type), propname);
2527                 return;
2528         }
2529
2530         if (RNA_property_type(prop) != PROP_POINTER) {
2531                 RNA_warning("curve is not a pointer: %s.%s",
2532                             RNA_struct_identifier(ptr->type), propname);
2533                 return;
2534         }
2535
2536         cptr = RNA_property_pointer_get(ptr, prop);
2537         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_CurveMapping))
2538                 return;
2539
2540         cb = MEM_callocN(sizeof(RNAUpdateCb), "RNAUpdateCb");
2541         cb->ptr = *ptr;
2542         cb->prop = prop;
2543
2544         id = cptr.id.data;
2545         UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
2546
2547         curvemap_buttons_layout(layout, &cptr, type, levels, brush, neg_slope, cb);
2548
2549         UI_block_lock_clear(block);
2550
2551         MEM_freeN(cb);
2552 }
2553
2554 /********************* ColorPicker Template ************************/
2555
2556 #define WHEEL_SIZE  (5 * U.widget_unit)
2557
2558 /* This template now follows User Preference for type - name is not correct anymore... */
2559 void uiTemplateColorPicker(
2560         uiLayout *layout, PointerRNA *ptr, const char *propname, int value_slider,
2561         int lock, int lock_luminosity, int cubic)
2562 {
2563         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2564         uiBlock *block = uiLayoutGetBlock(layout);
2565         uiLayout *col, *row;
2566         uiBut *but = NULL;
2567         ColorPicker *cpicker = ui_block_colorpicker_create(block);
2568         float softmin, softmax, step, precision;
2569
2570         if (!prop) {
2571                 RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2572                 return;
2573         }
2574
2575         RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
2576
2577         col = uiLayoutColumn(layout, true);
2578         row = uiLayoutRow(col, true);
2579
2580         switch (U.color_picker_type) {
2581                 case USER_CP_SQUARE_SV:
2582                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2583                                              -1, 0.0, 0.0, UI_GRAD_SV, 0, "");
2584                         break;
2585                 case USER_CP_SQUARE_HS:
2586                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2587                                              -1, 0.0, 0.0, UI_GRAD_HS, 0, "");
2588                         break;
2589                 case USER_CP_SQUARE_HV:
2590                         but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2591                                              -1, 0.0, 0.0, UI_GRAD_HV, 0, "");
2592                         break;
2593
2594                 /* user default */
2595                 case USER_CP_CIRCLE_HSV:
2596                 case USER_CP_CIRCLE_HSL:
2597                 default:
2598                         but = uiDefButR_prop(block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, WHEEL_SIZE, WHEEL_SIZE, ptr, prop,
2599                                              -1, 0.0, 0.0, 0, 0, "");
2600                         break;
2601
2602         }
2603
2604         but->custom_data = cpicker;
2605
2606         if (lock) {
2607                 but->flag |= UI_BUT_COLOR_LOCK;
2608         }
2609
2610         if (lock_luminosity) {
2611                 float color[4]; /* in case of alpha */
2612                 but->flag |= UI_BUT_VEC_SIZE_LOCK;
2613                 RNA_property_float_get_array(ptr, prop, color);
2614                 but->a2 = len_v3(color);
2615         }
2616
2617         if (cubic)
2618                 but->flag |= UI_BUT_COLOR_CUBIC;
2619
2620         
2621         if (value_slider) {
2622                 switch (U.color_picker_type) {
2623                         case USER_CP_CIRCLE_HSL:
2624                                 uiItemS(row);
2625                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop,
2626                                                      -1, softmin, softmax, UI_GRAD_L_ALT, 0, "");
2627                                 break;
2628                         case USER_CP_SQUARE_SV:
2629                                 uiItemS(col);
2630                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2631                                                      -1, softmin, softmax, UI_GRAD_SV + 3, 0, "");
2632                                 break;
2633                         case USER_CP_SQUARE_HS:
2634                                 uiItemS(col);
2635                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2636                                                      -1, softmin, softmax, UI_GRAD_HS + 3, 0, "");
2637                                 break;
2638                         case USER_CP_SQUARE_HV:
2639                                 uiItemS(col);
2640                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 4, WHEEL_SIZE, 18, ptr, prop,
2641                                                      -1, softmin, softmax, UI_GRAD_HV + 3, 0, "");
2642                                 break;
2643
2644                         /* user default */
2645                         case USER_CP_CIRCLE_HSV:
2646                         default:
2647                                 uiItemS(row);
2648                                 but = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", WHEEL_SIZE + 6, 0, 14, WHEEL_SIZE, ptr, prop,
2649                                                      -1, softmin, softmax, UI_GRAD_V_ALT, 0, "");
2650                                 break;
2651                 }
2652
2653                 but->custom_data = cpicker;
2654         }
2655 }
2656
2657 void uiTemplatePalette(uiLayout *layout, PointerRNA *ptr, const char *propname, int UNUSED(colors))
2658 {
2659         PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
2660         PointerRNA cptr;
2661         Palette *palette;
2662         PaletteColor *color;
2663         uiBlock *block;
2664         uiLayout *col;
2665         int row_cols = 0, col_id = 0;
2666         int cols_per_row = MAX2(uiLayoutGetWidth(layout) / UI_UNIT_X, 1);
2667
2668         if (!prop) {
2669                 RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2670                 return;
2671         }
2672
2673         cptr = RNA_property_pointer_get(ptr, prop);
2674         if (!cptr.data || !RNA_struct_is_a(cptr.type, &RNA_Palette))
2675                 return;
2676
2677         block = uiLayoutGetBlock(layout);
2678
2679         palette = cptr.data;
2680
2681         color = palette->colors.first;
2682
2683         col = uiLayoutColumn(layout, true);
2684         uiLayoutRow(col, true);
2685         uiDefIconButO(block, UI_BTYPE_BUT, "PALETTE_OT_color_add", WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
2686         uiDefIconButO(block, UI_BTYPE_BUT, "PALETTE_OT_color_delete", WM_OP_INVOKE_DEFAULT, ICON_ZOOMOUT, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
2687
2688         col = uiLayoutColumn(layout, true);
2689         uiLayoutRow(col, true);
2690
2691         for (; color; color = color->next) {
2692                 PointerRNA color_ptr;
2693
2694                 if (row_cols >= cols_per_row) {
2695                         uiLayoutRow(col, true);
2696                         row_cols = 0;
2697                 }
2698
2699                 RNA_pointer_create(&palette->id, &RNA_PaletteColor, color, &color_ptr);
2700                 uiDefButR(block, UI_BTYPE_COLOR, 0, "", 0, 0, UI_UNIT_X, UI_UNIT_Y, &color_ptr, "color", -1, 0.0, 1.0,
2701                           UI_PALETTE_COLOR, col_id, "");
2702                 row_cols++;
2703                 col_id++;
2704         }
2705 }
2706
2707
2708 /********************* Layer Buttons Template ************************/
2709
2710 static void handle_layer_buttons(bContext *C, void *arg1, void *arg2)
2711 {
2712         uiBut *but = arg1;
2713         int cur = GET_INT_FROM_POINTER(arg2);
2714         wmWindow *win = CTX_wm_window(C);
2715         int i, tot, shift = win->eventstate->shift;
2716
2717         if (!shift) {
2718                 tot = RNA_property_array_length(&but->rnapoin, but->rnaprop);
2719                 
2720                 /* Normally clicking only selects one layer */
2721                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, cur, true);
2722                 for (i = 0; i < tot; ++i) {
2723                         if (i != cur)
2724                                 RNA_property_boolean_set_index(&but->rnapoin, but->rnaprop, i, false);
2725                 }
2726         }
2727
2728         /* view3d layer change should update depsgraph (invisible object changed maybe) */
2729         /* see view3d_header.c */
2730 }
2731
2732 /**
2733  * \todo for now, grouping of layers is determined by dividing up the length of
2734  * the array of layer bitflags
2735  */
2736 void uiTemplateLayers(
2737         uiLayout *layout, PointerRNA *ptr, const char *propname,
2738         PointerRNA *used_ptr, const char *used_propname, int active_layer)
2739 {
2740         uiLayout *uRow, *uCol;
2741         PropertyRNA *prop, *used_prop = NULL;
2742         int groups, cols, layers;
2743         int group, col, layer, row;
2744         int cols_per_group = 5;
2745
2746         prop = RNA_struct_find_property(ptr, propname);
2747         if (!prop) {
2748                 RNA_warning("layers property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2749                 return;
2750         }
2751         
2752         /* the number of layers determines the way we group them 
2753          *      - we want 2 rows only (for now)
2754          *      - the number of columns (cols) is the total number of buttons per row
2755          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2756          *      - for now, only split into groups if group will have at least 5 items
2757          */
2758         layers = RNA_property_array_length(ptr, prop);
2759         cols = (layers / 2) + (layers % 2);
2760         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2761
2762         if (used_ptr && used_propname) {
2763                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2764                 if (!used_prop) {
2765                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2766                         return;
2767                 }
2768
2769                 if (RNA_property_array_length(used_ptr, used_prop) < layers)
2770                         used_prop = NULL;
2771         }
2772         
2773         /* layers are laid out going across rows, with the columns being divided into groups */
2774         
2775         for (group = 0; group < groups; group++) {
2776                 uCol = uiLayoutColumn(layout, true);
2777                 
2778                 for (row = 0; row < 2; row++) {
2779                         uiBlock *block;
2780                         uiBut *but;
2781
2782                         uRow = uiLayoutRow(uCol, true);
2783                         block = uiLayoutGetBlock(uRow);
2784                         layer = groups * cols_per_group * row + cols_per_group * group;
2785                         
2786                         /* add layers as toggle buts */
2787                         for (col = 0; (col < cols_per_group) && (layer < layers); col++, layer++) {
2788                                 int icon = 0;
2789                                 int butlay = 1 << layer;
2790
2791                                 if (active_layer & butlay)
2792                                         icon = ICON_LAYER_ACTIVE;
2793                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, layer))
2794                                         icon = ICON_LAYER_USED;
2795                                 
2796                                 but = uiDefAutoButR(block, ptr, prop, layer, "", icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2);
2797                                 UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(layer));
2798                                 but->type = UI_BTYPE_TOGGLE;
2799                         }
2800                 }
2801         }
2802 }
2803
2804 void uiTemplateGameStates(
2805         uiLayout *layout, PointerRNA *ptr, const char *propname,
2806         PointerRNA *used_ptr, const char *used_propname, int active_state)
2807 {
2808         uiLayout *uRow, *uCol;
2809         PropertyRNA *prop, *used_prop = NULL;
2810         int groups, cols, states;
2811         int group, col, state, row;
2812         int cols_per_group = 5;
2813         Object *ob = (Object *)ptr->id.data;
2814
2815         prop = RNA_struct_find_property(ptr, propname);
2816         if (!prop) {
2817                 RNA_warning("states property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
2818                 return;
2819         }
2820         
2821         /* the number of states determines the way we group them 
2822          *      - we want 2 rows only (for now)
2823          *      - the number of columns (cols) is the total number of buttons per row
2824          *        the 'remainder' is added to this, as it will be ok to have first row slightly wider if need be
2825          *      - for now, only split into groups if group will have at least 5 items
2826          */
2827         states = RNA_property_array_length(ptr, prop);
2828         cols = (states / 2) + (states % 2);
2829         groups = ((cols / 2) < cols_per_group) ? (1) : (cols / cols_per_group);
2830
2831         if (used_ptr && used_propname) {
2832                 used_prop = RNA_struct_find_property(used_ptr, used_propname);
2833                 if (!used_prop) {
2834                         RNA_warning("used layers property not found: %s.%s", RNA_struct_identifier(ptr->type), used_propname);
2835                         return;
2836                 }
2837
2838                 if (RNA_property_array_length(used_ptr, used_prop) < states)
2839                         used_prop = NULL;
2840         }
2841         
2842         /* layers are laid out going across rows, with the columns being divided into groups */
2843         
2844         for (group = 0; group < groups; group++) {
2845                 uCol = uiLayoutColumn(layout, true);
2846                 
2847                 for (row = 0; row < 2; row++) {
2848                         uiBlock *block;
2849                         uiBut *but;
2850
2851                         uRow = uiLayoutRow(uCol, true);
2852                         block = uiLayoutGetBlock(uRow);
2853                         state = groups * cols_per_group * row + cols_per_group * group;
2854                         
2855                         /* add layers as toggle buts */
2856                         for (col = 0; (col < cols_per_group) && (state < states); col++, state++) {
2857                                 int icon = 0;
2858                                 int butlay = 1 << state;
2859
2860                                 if (active_state & butlay)
2861                                         icon = ICON_LAYER_ACTIVE;
2862                                 else if (used_prop && RNA_property_boolean_get_index(used_ptr, used_prop, state))
2863                                         icon = ICON_LAYER_USED;
2864                                 
2865                                 but = uiDefIconButR_prop(block, UI_BTYPE_ICON_TOGGLE, 0, icon, 0, 0, UI_UNIT_X / 2, UI_UNIT_Y / 2, ptr, prop,
2866                                                          state, 0, 0, -1, -1, sca_state_name_get(ob, state));
2867                                 UI_but_func_set(but, handle_layer_buttons, but, SET_INT_IN_POINTER(state));
2868                                 but->type = UI_BTYPE_TOGGLE;
2869                         }
2870                 }
2871         }
2872 }
2873
2874
2875 /************************* List Template **************************/
2876 static void uilist_draw_item_default(
2877         struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout,
2878         struct PointerRNA *UNUSED(dataptr), struct PointerRNA *itemptr, int icon,
2879         struct PointerRNA *UNUSED(active_dataptr), const char *UNUSED(active_propname),
2880         int UNUSED(index), int UNUSED(flt_flag))
2881 {
2882         PropertyRNA *nameprop = RNA_struct_name_property(itemptr->type);
2883
2884         /* Simplest one! */
2885         switch (ui_list->layout_type) {
2886                 case UILST_LAYOUT_GRID:
2887                         uiItemL(layout, "", icon);
2888                         break;
2889                 case UILST_LAYOUT_DEFAULT:
2890                 case UILST_LAYOUT_COMPACT:
2891                 default:
2892                         if (nameprop) {
2893                                 uiItemFullR(layout, itemptr, nameprop, RNA_NO_INDEX, 0, UI_ITEM_R_NO_BG, "", icon);
2894                         }
2895                         else {
2896                                 uiItemL(layout, "", icon);
2897                         }
2898                         break;
2899         }
2900 }
2901
2902 static void uilist_draw_filter_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct uiLayout *layout)
2903 {
2904         PointerRNA listptr;
2905         uiLayout *row, *subrow;
2906
2907         RNA_pointer_create(NULL, &RNA_UIList, ui_list, &listptr);
2908
2909         row = uiLayoutRow(layout, false);
2910
2911         subrow = uiLayoutRow(row, true);
2912         uiItemR(subrow, &listptr, "filter_name", 0, "", ICON_NONE);
2913         uiItemR(subrow, &listptr, "use_filter_invert", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2914                 (ui_list->filter_flag & UILST_FLT_EXCLUDE) ? ICON_ZOOM_OUT : ICON_ZOOM_IN);
2915
2916         subrow = uiLayoutRow(row, true);
2917         uiItemR(subrow, &listptr, "use_filter_sort_alpha", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
2918         uiItemR(subrow, &listptr, "use_filter_sort_reverse", UI_ITEM_R_TOGGLE | UI_ITEM_R_ICON_ONLY, "",
2919                 (ui_list->filter_sort_flag & UILST_FLT_SORT_REVERSE) ? ICON_TRIA_UP : ICON_TRIA_DOWN);
2920 }
2921
2922 typedef struct {
2923         char name[MAX_IDPROP_NAME];
2924         int org_idx;
2925 } StringCmp;
2926
2927 static int cmpstringp(const void *p1, const void *p2)
2928 {
2929         /* Case-insensitive comparison. */
2930         return BLI_strcasecmp(((StringCmp *) p1)->name, ((StringCmp *) p2)->name);
2931 }
2932
2933 static void uilist_filter_items_default(struct uiList *ui_list, struct bContext *UNUSED(C), struct PointerRNA *dataptr,
2934                                         const char *propname)
2935 {
2936         uiListDyn *dyn_data = ui_list->dyn_data;
2937         PropertyRNA *prop = RNA_struct_find_property(dataptr, propname);
2938
2939         const char *filter_raw = ui_list->filter_byname;
2940         char *filter = (char *)filter_raw, filter_buff[32], *filter_dyn = NULL;
2941         const bool filter_exclude = (ui_list->filter_flag & UILST_FLT_EXCLUDE) != 0;
2942         const bool order_by_name = (ui_list->filter_sort_flag & UILST_FLT_SORT_ALPHA) != 0;
2943         int len = RNA_property_collection_length(dataptr, prop);
2944
2945         dyn_data->items_shown = dyn_data->items_len = len;
2946
2947         if (len && (order_by_name || filter_raw[0])) {
2948                 StringCmp *names = NULL;
2949                 int order_idx = 0, i = 0;
2950
2951                 if (order_by_name) {
2952                         names = MEM_callocN(sizeof(StringCmp) * len, "StringCmp");
2953                 }
2954                 if (filter_raw[0]) {
2955                         size_t slen = strlen(filter_raw);
2956
2957                         dyn_data->items_filter_flags = MEM_callocN(sizeof(int) * len, "items_filter_flags");
2958                         dyn_data->items_shown = 0;
2959
2960                         /* Implicitly add heading/trailing wildcards if needed. */
2961                         if (slen + 3 <= sizeof(filter_buff)) {
2962                                 filter = filter_buff;
2963                         }
2964                         else {
2965                                 filter = filter_dyn = MEM_mallocN((slen + 3) * sizeof(char), "filter_dyn");
2966                         }
2967                         BLI_strncpy_ensure_pad(filter, filter_raw, '*', slen + 3);
2968                 }
2969
2970                 RNA_PROP_BEGIN (dataptr, itemptr, prop)
2971                 {
2972                         char *namebuf;
2973                         const char *name;
2974                         bool do_order = false;
2975
2976                         namebuf = RNA_struct_name_get_alloc(&itemptr, NULL, 0, NULL);
2977                         name = namebuf ? namebuf : "";
2978
2979                         if (filter[0]) {
2980                                 /* Case-insensitive! */
2981                                 if (fnmatch(filter, name, FNM_CASEFOLD) == 0) {
2982                                         dyn_data->items_filter_flags[i] = UILST_FLT_ITEM;
2983                                         if (!filter_exclude) {
2984                                                 dyn_data->items_shown++;
2985                                                 do_order = order_by_name;
2986                                         }
2987                                         //printf("%s: '%s' matches '%s'\n", __func__, name, filter);
2988                                 }
2989                                 else if (filter_exclude) {
2990                                         dyn_data->items_shown++;
2991                                         do_order = order_by_name;
2992                                 }
2993                         }
2994                         else {
2995                                 do_order = order_by_name;
2996                         }
2997
2998                         if (do_order) {
2999                                 names[order_idx].org_idx = order_idx;
3000                                 BLI_strncpy(names[order_idx++].name, name, MAX_IDPROP_NAME);
3001                         }
3002
3003                         /* free name */
3004                         if (namebuf) {
3005                                 MEM_freeN(namebuf);
3006                         }
3007                         i++;
3008                 }
3009                 RNA_PROP_END;
3010
3011