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