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