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