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