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