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