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