8791a34548909b6e1409388cde54ba4c9d8965f9
[blender.git] / source / blender / editors / armature / poselib.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007, Blender Foundation
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/armature/poselib.c
27  *  \ingroup edarmature
28  */
29
30  
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <stddef.h>
34 #include <string.h>
35 #include <math.h>
36 #include <float.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42 #include "BLI_dynstr.h"
43 #include "BLI_dlrbTree.h"
44 #include "BLI_utildefines.h"
45
46 #include "BLF_translation.h"
47
48 #include "DNA_anim_types.h"
49 #include "DNA_armature_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52
53 #include "BKE_animsys.h"
54 #include "BKE_action.h"
55 #include "BKE_armature.h"
56 #include "BKE_depsgraph.h"
57 #include "BKE_idprop.h"
58 #include "BKE_library.h"
59 #include "BKE_object.h"
60
61 #include "BKE_context.h"
62 #include "BKE_report.h"
63
64 #include "RNA_access.h"
65 #include "RNA_define.h"
66 #include "RNA_enum_types.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "UI_interface.h"
72 #include "UI_resources.h"
73
74 #include "ED_anim_api.h"
75 #include "ED_armature.h"
76 #include "ED_keyframes_draw.h"
77 #include "ED_keyframing.h"
78 #include "ED_keyframes_edit.h"
79 #include "ED_screen.h"
80 #include "ED_object.h"
81
82 #include "armature_intern.h"
83
84 /* ******* XXX ********** */
85
86 static void action_set_activemarker(void *UNUSED(a), void *UNUSED(b), void *UNUSED(c)) {}
87
88 /* ************************************************************* */
89 /* == POSE-LIBRARY TOOL FOR BLENDER == 
90  *      
91  * Overview: 
92  *      This tool allows animators to store a set of frequently used poses to dump into
93  *      the active action to help in "budget" productions to quickly block out new actions.
94  *      It acts as a kind of "glorified clipboard for poses", allowing for naming of poses.
95  *
96  * Features:
97  *      - PoseLibs are simply normal Actions
98  *      - Each "pose" is simply a set of keyframes that occur on a particular frame
99  *              -> a set of TimeMarkers that belong to each Action, help 'label' where a 'pose' can be
100  *                 found in the Action
101  *      - The Scrollwheel or PageUp/Down buttons when used in a special mode or after pressing/holding
102  *        [a modifier] key, cycles through the poses available for the active pose's poselib, allowing the
103  *        animator to preview what action best suits that pose
104  */
105 /* ************************************************************* */
106
107
108 /* gets the first available frame in poselib to store a pose on 
109  *      - frames start from 1, and a pose should occur on every frame... 0 is error!
110  */
111 static int poselib_get_free_index (bAction *act)
112 {
113         TimeMarker *marker;
114         int low=0, high=0;
115         short changed = 0;
116         
117         /* sanity checks */
118         if (ELEM(NULL, act, act->markers.first)) return 1;
119         
120         /* As poses are not stored in chronological order, we must iterate over this list 
121          * a few times until we don't make any new discoveries (mostly about the lower bound).
122          * Prevents problems with deleting then trying to add new poses [#27412]
123          */
124         do {
125                 changed = 0;
126                 
127                 for (marker= act->markers.first; marker; marker= marker->next) {
128                         /* only increase low if value is 1 greater than low, to find "gaps" where
129                          * poses were removed from the poselib
130                          */
131                         if (marker->frame == (low + 1)) {
132                                 low++;
133                                 changed = 1;
134                         }
135                         
136                         /* value replaces high if it is the highest value encountered yet */
137                         if (marker->frame > high) {
138                                 high= marker->frame;
139                                 changed = 1;
140                         }
141                 }
142         } while (changed != 0);
143         
144         /* - if low is not equal to high, then low+1 is a gap 
145          * - if low is equal to high, then high+1 is the next index (add at end) 
146          */
147         if (low < high) 
148                 return (low + 1);
149         else 
150                 return (high + 1);
151 }
152
153 /* returns the active pose for a poselib */
154 static TimeMarker *poselib_get_active_pose (bAction *act)
155 {       
156         if ((act) && (act->active_marker))
157                 return BLI_findlink(&act->markers, act->active_marker-1);
158         else
159                 return NULL;
160 }
161
162 /* Get object that Pose Lib should be found on */
163  /* XXX C can be zero */
164 static Object *get_poselib_object (bContext *C)
165 {
166         ScrArea *sa;
167         
168         /* sanity check */
169         if (C == NULL)
170                 return NULL;
171         
172         sa = CTX_wm_area(C);
173         
174         if (sa && (sa->spacetype == SPACE_BUTS)) 
175                 return ED_object_context(C);
176         else
177                 return object_pose_armature_get(CTX_data_active_object(C));
178 }
179
180 /* Poll callback for operators that require existing PoseLib data (with poses) to work */
181 static int has_poselib_pose_data_poll (bContext *C)
182 {
183         Object *ob = get_poselib_object(C);
184         return (ob && ob->poselib);
185 }
186
187 /* ----------------------------------- */
188
189 /* Initialize a new poselib (whether it is needed or not) */
190 static bAction *poselib_init_new (Object *ob)
191 {
192         /* sanity checks - only for armatures */
193         if (ELEM(NULL, ob, ob->pose))
194                 return NULL;
195         
196         /* init object's poselib action (unlink old one if there) */
197         if (ob->poselib)
198                 id_us_min(&ob->poselib->id);
199         ob->poselib= add_empty_action("PoseLib");
200         
201         return ob->poselib;
202 }
203
204 /* Initialize a new poselib (checks if that needs to happen) */
205 static bAction *poselib_validate (Object *ob)
206 {
207         if (ELEM(NULL, ob, ob->pose))
208                 return NULL;
209         else if (ob->poselib == NULL)
210                 return poselib_init_new(ob);
211         else
212                 return ob->poselib;
213 }
214
215 /* ************************************************************* */
216 /* Pose Lib UI Operators */
217
218 static int poselib_new_exec (bContext *C, wmOperator *UNUSED(op))
219 {
220         Object *ob = get_poselib_object(C);
221         
222         /* sanity checks */
223         if (ob == NULL)
224                 return OPERATOR_CANCELLED;
225                 
226         /* new method here deals with the rest... */
227         poselib_init_new(ob);
228         
229         /* notifier here might evolve? */
230         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, NULL);
231         
232         return OPERATOR_FINISHED;
233 }
234
235 void POSELIB_OT_new(wmOperatorType *ot)
236 {
237         /* identifiers */
238         ot->name = "New Pose Library";
239         ot->idname = "POSELIB_OT_new";
240         ot->description = "Add New Pose Library to active Object";
241         
242         /* callbacks */
243         ot->exec = poselib_new_exec;
244         ot->poll = ED_operator_posemode;
245         
246         /* flags */
247         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
248 }
249
250 /* ------------------------------------------------ */
251
252 static int poselib_unlink_exec (bContext *C, wmOperator *UNUSED(op))
253 {
254         Object *ob = get_poselib_object(C);
255         
256         /* sanity checks */
257         if (ELEM(NULL, ob, ob->poselib))
258                 return OPERATOR_CANCELLED;
259                 
260         /* there should be a poselib (we just checked above!), so just lower its user count and remove */
261         id_us_min(&ob->poselib->id);
262         ob->poselib = NULL;
263         
264         /* notifier here might evolve? */
265         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, NULL);
266         
267         return OPERATOR_FINISHED;
268 }
269
270 void POSELIB_OT_unlink(wmOperatorType *ot)
271 {
272         /* identifiers */
273         ot->name = "Unlink Pose Library";
274         ot->idname = "POSELIB_OT_unlink";
275         ot->description = "Remove Pose Library from active Object";
276         
277         /* callbacks */
278         ot->exec = poselib_unlink_exec;
279         ot->poll = has_poselib_pose_data_poll;
280         
281         /* flags */
282         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
283 }
284
285 /* ************************************************************* */
286 /* Pose Editing Operators */
287
288 /* This tool automagically generates/validates poselib data so that it corresponds to the data 
289  * in the action. This is for use in making existing actions usable as poselibs.
290  */
291 static int poselib_sanitise_exec (bContext *C, wmOperator *op)
292 {
293         Object *ob = get_poselib_object(C);
294         bAction *act = (ob)? ob->poselib : NULL;
295         DLRBT_Tree keys;
296         ActKeyColumn *ak;
297         TimeMarker *marker, *markern;
298         
299         /* validate action */
300         if (act == NULL) {
301                 BKE_report(op->reports, RPT_WARNING, "No Action to validate");
302                 return OPERATOR_CANCELLED;
303         }
304         
305         /* determine which frames have keys */
306         BLI_dlrbTree_init(&keys);
307                 action_to_keylist(NULL, act, &keys, NULL);
308         BLI_dlrbTree_linkedlist_sync(&keys);
309         
310         /* for each key, make sure there is a corresponding pose */
311         for (ak= keys.first; ak; ak= ak->next) {
312                 /* check if any pose matches this */
313                 // TODO: don't go looking through the list like this every time...
314                 for (marker= act->markers.first; marker; marker= marker->next) {
315                         if (IS_EQ(marker->frame, (double)ak->cfra)) {
316                                 marker->flag = -1;
317                                 break;
318                         }
319                 }
320                 
321                 /* add new if none found */
322                 if (marker == NULL) {
323                         /* add pose to poselib */
324                         marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
325                         
326                         BLI_strncpy(marker->name, "Pose", sizeof(marker->name));
327                         
328                         marker->frame= (int)ak->cfra;
329                         marker->flag= -1;
330                         
331                         BLI_addtail(&act->markers, marker);
332                 }
333         }
334         
335         /* remove all untagged poses (unused), and remove all tags */
336         for (marker= act->markers.first; marker; marker= markern) {
337                 markern= marker->next;
338                 
339                 if (marker->flag != -1)
340                         BLI_freelinkN(&act->markers, marker);
341                 else
342                         marker->flag = 0;
343         }
344         
345         /* free temp memory */
346         BLI_dlrbTree_free(&keys);
347         
348         /* send notifiers for this - using keyframe editing notifiers, since action 
349          * may be being shown in anim editors as active action 
350          */
351         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
352         
353         return OPERATOR_FINISHED;
354 }
355
356 void POSELIB_OT_action_sanitise(wmOperatorType *ot)
357 {
358         /* identifiers */
359         ot->name = "Sanitise Pose Library Action";
360         ot->idname = "POSELIB_OT_action_sanitise";
361         ot->description = "Make action suitable for use as a Pose Library";
362         
363         /* callbacks */
364         ot->exec = poselib_sanitise_exec;
365         ot->poll = has_poselib_pose_data_poll;
366         
367         /* flags */
368         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
369 }
370
371 /* ------------------------------------------ */
372
373 static void poselib_add_menu_invoke__replacemenu (bContext *C, uiLayout *layout, void *UNUSED(arg))
374 {
375         Object *ob= get_poselib_object(C);
376         bAction *act= ob->poselib; /* never NULL */
377         TimeMarker *marker;
378         
379         wmOperatorType *ot = WM_operatortype_find("POSELIB_OT_pose_add", 1);
380
381         BLI_assert(ot != NULL);
382
383         /* set the operator execution context correctly */
384         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
385         
386         /* add each marker to this menu */
387         for (marker= act->markers.first; marker; marker= marker->next) {
388                 PointerRNA props_ptr;
389                 
390                 props_ptr = uiItemFullO_ptr(layout, ot,
391                                             marker->name, ICON_ARMATURE_DATA, NULL,
392                                             WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
393                 
394                 RNA_int_set(&props_ptr, "frame", marker->frame);
395                 RNA_string_set(&props_ptr, "name", marker->name);
396         }
397 }
398
399 static int poselib_add_menu_invoke (bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
400 {
401         Scene *scene= CTX_data_scene(C);
402         Object *ob= get_poselib_object(C);
403         bPose *pose= (ob) ? ob->pose : NULL;
404         uiPopupMenu *pup;
405         uiLayout *layout;
406         
407         /* sanity check */
408         if (ELEM(NULL, ob, pose)) 
409                 return OPERATOR_CANCELLED;
410         
411         /* start building */
412         pup= uiPupMenuBegin(C, op->type->name, ICON_NONE);
413         layout= uiPupMenuLayout(pup);
414         uiLayoutSetOperatorContext(layout, WM_OP_EXEC_DEFAULT);
415         
416         /* add new (adds to the first unoccupied frame) */
417         uiItemIntO(layout, IFACE_("Add New"), ICON_NONE, "POSELIB_OT_pose_add", "frame", poselib_get_free_index(ob->poselib));
418         
419         /* check if we have any choices to add a new pose in any other way */
420         if ((ob->poselib) && (ob->poselib->markers.first)) {
421                 /* add new (on current frame) */
422                 uiItemIntO(layout, IFACE_("Add New (Current Frame)"), ICON_NONE, "POSELIB_OT_pose_add", "frame", CFRA);
423                 
424                 /* replace existing - submenu */
425                 uiItemMenuF(layout, IFACE_("Replace Existing..."), 0, poselib_add_menu_invoke__replacemenu, NULL);
426         }
427         
428         uiPupMenuEnd(C, pup);
429         
430         /* this operator is only for a menu, not used further */
431         return OPERATOR_CANCELLED;
432 }
433
434
435 static int poselib_add_exec (bContext *C, wmOperator *op)
436 {
437         Object *ob= get_poselib_object(C);
438         bAction *act = poselib_validate(ob);
439         bPose *pose= (ob) ? ob->pose : NULL;
440         TimeMarker *marker;
441         KeyingSet *ks= ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_WHOLE_CHARACTER_ID); /* this includes custom props :)*/
442         int frame= RNA_int_get(op->ptr, "frame");
443         char name[64];
444         
445         /* sanity check (invoke should have checked this anyway) */
446         if (ELEM(NULL, ob, pose)) 
447                 return OPERATOR_CANCELLED;
448         
449         /* get name to give to pose */
450         RNA_string_get(op->ptr, "name", name);
451         
452         /* add pose to poselib - replaces any existing pose there
453          *      - for the 'replace' option, this should end up finding the appropriate marker,
454          *        so no new one will be added
455          */
456         for (marker= act->markers.first; marker; marker= marker->next) {
457                 if (marker->frame == frame) {
458                         BLI_strncpy(marker->name, name, sizeof(marker->name));
459                         break;
460                 }
461         }
462         if (marker == NULL) {
463                 marker= MEM_callocN(sizeof(TimeMarker), "ActionMarker");
464                 
465                 BLI_strncpy(marker->name, name, sizeof(marker->name));
466                 marker->frame= frame;
467                 
468                 BLI_addtail(&act->markers, marker);
469         }
470         
471         /* validate name */
472         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
473         
474         /* use Keying Set to determine what to store for the pose */
475         // FIXME: in the past, the Keying Set respected selections (LocRotScale), but the current one doesn't (WholeCharacter)
476         // so perhaps we need either a new Keying Set, or just to add overrides here...
477         ANIM_apply_keyingset(C, NULL, act, ks, MODIFYKEY_MODE_INSERT, (float)frame);
478         
479         /* store new 'active' pose number */
480         act->active_marker= BLI_countlist(&act->markers);
481         
482         /* done */
483         return OPERATOR_FINISHED;
484 }
485
486 void POSELIB_OT_pose_add(wmOperatorType *ot)
487 {
488         /* identifiers */
489         ot->name = "PoseLib Add Pose";
490         ot->idname = "POSELIB_OT_pose_add";
491         ot->description = "Add the current Pose to the active Pose Library";
492         
493         /* api callbacks */
494         ot->invoke = poselib_add_menu_invoke;
495         ot->exec = poselib_add_exec;
496         ot->poll = ED_operator_posemode;
497         
498         /* flags */
499         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
500         
501         /* properties */
502         RNA_def_int(ot->srna, "frame", 1, 0, INT_MAX, "Frame", "Frame to store pose on", 0, INT_MAX);
503         RNA_def_string(ot->srna, "name", "Pose", 64, "Pose Name", "Name of newly added Pose");
504 }
505
506 /* ----- */
507
508 /* can be called with C == NULL */
509 static EnumPropertyItem *poselib_stored_pose_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), int *free)
510 {
511         Object *ob = get_poselib_object(C);
512         bAction *act = (ob) ? ob->poselib : NULL;
513         TimeMarker *marker;
514         EnumPropertyItem *item= NULL, item_tmp= {0};
515         int totitem= 0;
516         int i= 0;
517
518         if (C == NULL) {
519                 return DummyRNA_NULL_items;
520         }
521         
522         /* check that the action exists */
523         if (act) {
524                 /* add each marker to the list */
525                 for (marker=act->markers.first, i=0; marker; marker= marker->next, i++) {
526                         item_tmp.identifier= item_tmp.name= marker->name;
527                         item_tmp.icon= ICON_ARMATURE_DATA;
528                         item_tmp.value= i;
529                         RNA_enum_item_add(&item, &totitem, &item_tmp);
530                 }
531         }
532
533         RNA_enum_item_end(&item, &totitem);
534         *free= 1;
535
536         return item;
537 }
538
539 static int poselib_remove_exec (bContext *C, wmOperator *op)
540 {
541         Object *ob= get_poselib_object(C);
542         bAction *act= (ob) ? ob->poselib : NULL;
543         TimeMarker *marker;
544         int marker_index;
545         FCurve *fcu;
546         PropertyRNA *prop;
547
548         /* check if valid poselib */
549         if (act == NULL) {
550                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
551                 return OPERATOR_CANCELLED;
552         }
553
554         prop = RNA_struct_find_property(op->ptr, "pose");
555         if (RNA_property_is_set(op->ptr, prop)) {
556                 marker_index = RNA_property_enum_get(op->ptr, prop);
557         }
558         else {
559                 marker_index = act->active_marker - 1;
560         }
561
562         /* get index (and pointer) of pose to remove */
563         marker = BLI_findlink(&act->markers, marker_index);
564         if (marker == NULL) {
565                 BKE_reportf(op->reports, RPT_ERROR, "Invalid Pose specified %d", marker_index);
566                 return OPERATOR_CANCELLED;
567         }
568         
569         /* remove relevant keyframes */
570         for (fcu= act->curves.first; fcu; fcu= fcu->next) {
571                 BezTriple *bezt;
572                 unsigned int i;
573                 
574                 if (fcu->bezt) {
575                         for (i=0, bezt=fcu->bezt; i < fcu->totvert; i++, bezt++) {
576                                 /* check if remove */
577                                 if (IS_EQ(bezt->vec[1][0], marker->frame)) {
578                                         delete_fcurve_key(fcu, i, 1);
579                                         break;
580                                 }
581                         }
582                 }
583         }
584         
585         /* remove poselib from list */
586         BLI_freelinkN(&act->markers, marker);
587         
588         /* fix active pose number */
589         act->active_marker= 0;
590         
591         /* send notifiers for this - using keyframe editing notifiers, since action 
592          * may be being shown in anim editors as active action 
593          */
594         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
595         
596         /* done */
597         return OPERATOR_FINISHED;
598 }
599
600 void POSELIB_OT_pose_remove(wmOperatorType *ot)
601 {
602         PropertyRNA *prop;
603         
604         /* identifiers */
605         ot->name = "PoseLib Remove Pose";
606         ot->idname = "POSELIB_OT_pose_remove";
607         ot->description = "Remove nth pose from the active Pose Library";
608         
609         /* api callbacks */
610         ot->invoke = WM_menu_invoke;
611         ot->exec = poselib_remove_exec;
612         ot->poll = has_poselib_pose_data_poll;
613         
614         /* flags */
615         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
616         
617         /* properties */
618         prop = RNA_def_enum(ot->srna, "pose", DummyRNA_NULL_items, 0, "Pose", "The pose to remove");
619         RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
620         ot->prop = prop;
621 }
622
623 static int poselib_rename_invoke (bContext *C, wmOperator *op, wmEvent *evt)
624 {
625         Object *ob= get_poselib_object(C);
626         bAction *act= (ob) ? ob->poselib : NULL;
627         TimeMarker *marker;
628         
629         /* check if valid poselib */
630         if (act == NULL) {
631                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
632                 return OPERATOR_CANCELLED;
633         }
634         
635         /* get index (and pointer) of pose to remove */
636         marker= BLI_findlink(&act->markers, act->active_marker-1);
637         if (marker == NULL) {
638                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
639                 return OPERATOR_CANCELLED;
640         }
641         else {
642                 /* use the existing name of the marker as the name, and use the active marker as the one to rename */
643                 RNA_enum_set(op->ptr, "pose", act->active_marker-1);
644                 RNA_string_set(op->ptr, "name", marker->name);
645         }
646         
647         /* part to sync with other similar operators... */
648         return WM_operator_props_popup(C, op, evt);
649 }
650
651 static int poselib_rename_exec (bContext *C, wmOperator *op)
652 {
653         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
654         bAction *act= (ob) ? ob->poselib : NULL;
655         TimeMarker *marker;
656         char newname[64];
657         
658         /* check if valid poselib */
659         if (act == NULL) {
660                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have PoseLib data");
661                 return OPERATOR_CANCELLED;
662         }
663         
664         /* get index (and pointer) of pose to remove */
665         marker= BLI_findlink(&act->markers, RNA_int_get(op->ptr, "pose"));
666         if (marker == NULL) {
667                 BKE_report(op->reports, RPT_ERROR, "Invalid index for Pose");
668                 return OPERATOR_CANCELLED;
669         }
670         
671         /* get new name */
672         RNA_string_get(op->ptr, "name", newname);
673         
674         /* copy name and validate it */
675         BLI_strncpy(marker->name, newname, sizeof(marker->name));
676         BLI_uniquename(&act->markers, marker, "Pose", '.', offsetof(TimeMarker, name), sizeof(marker->name));
677         
678         /* send notifiers for this - using keyframe editing notifiers, since action 
679          * may be being shown in anim editors as active action 
680          */
681         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
682         
683         /* done */
684         return OPERATOR_FINISHED;
685 }
686
687 void POSELIB_OT_pose_rename(wmOperatorType *ot)
688 {
689         PropertyRNA *prop;
690         static EnumPropertyItem prop_poses_dummy_types[] = {
691                 {0, NULL, 0, NULL, NULL}
692         };
693         
694         /* identifiers */
695         ot->name = "PoseLib Rename Pose";
696         ot->idname = "POSELIB_OT_pose_rename";
697         ot->description = "Rename specified pose from the active Pose Library";
698         
699         /* api callbacks */
700         ot->invoke = poselib_rename_invoke;
701         ot->exec = poselib_rename_exec;
702         ot->poll = has_poselib_pose_data_poll;
703         
704         /* flags */
705         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
706         
707         /* properties */
708                 /* NOTE: name not pose is the operator's "main" property, so that it will get activated in the popup for easy renaming */
709         ot->prop = RNA_def_string(ot->srna, "name", "RenamedPose", 64, "New Pose Name", "New name for pose");
710         prop= RNA_def_enum(ot->srna, "pose", prop_poses_dummy_types, 0, "Pose", "The pose to rename");
711                 RNA_def_enum_funcs(prop, poselib_stored_pose_itemf);
712 }
713
714 /* ************************************************************* */
715 /* Pose-Lib Browsing/Previewing Operator */
716
717 /* Simple struct for storing settings/data for use during PoseLib preview */
718 typedef struct tPoseLib_PreviewData {
719         ListBase backups;               /* tPoseLib_Backup structs for restoring poses */
720         ListBase searchp;               /* LinkData structs storing list of poses which match the current search-string */
721         
722         Scene *scene;                   /* active scene */
723         ScrArea *sa;                    /* active area */
724         
725         PointerRNA rna_ptr;             /* RNA-Pointer to Object 'ob' */
726         Object *ob;                             /* object to work on */
727         bArmature *arm;                 /* object's armature data */
728         bPose *pose;                    /* object's pose */
729         bAction *act;                   /* poselib to use */
730         TimeMarker *marker;             /* 'active' pose */
731         
732         int selcount;                   /* number of selected elements to work on */
733         int totcount;                   /* total number of elements to work on */
734         
735         short state;                    /* state of main loop */
736         short redraw;                   /* redraw/update settings during main loop */
737         short flag;                             /* flags for various settings */
738         
739         short search_cursor;    /* position of cursor in searchstr (cursor occurs before the item at the nominated index) */
740         char searchstr[64];             /* (Part of) Name to search for to filter poses that get shown */
741         char searchold[64];             /* Previously set searchstr (from last loop run), so that we can detected when to rebuild searchp */
742         
743         char headerstr[200];    /* Info-text to print in header */
744 } tPoseLib_PreviewData;
745
746 /* defines for tPoseLib_PreviewData->state values */
747 enum {
748         PL_PREVIEW_ERROR = -1,
749         PL_PREVIEW_RUNNING,
750         PL_PREVIEW_CONFIRM,
751         PL_PREVIEW_CANCEL,
752         PL_PREVIEW_RUNONCE 
753 };
754
755 /* defines for tPoseLib_PreviewData->redraw values */
756 enum {
757         PL_PREVIEW_NOREDRAW = 0,
758         PL_PREVIEW_REDRAWALL,
759         PL_PREVIEW_REDRAWHEADER,
760 };
761
762 /* defines for tPoseLib_PreviewData->flag values */
763 enum {
764         PL_PREVIEW_FIRSTTIME    = (1<<0),
765         PL_PREVIEW_SHOWORIGINAL = (1<<1)
766 };
767
768 /* ---------------------------- */
769
770 /* simple struct for storing backup info */
771 typedef struct tPoseLib_Backup {
772         struct tPoseLib_Backup *next, *prev;
773         
774         bPoseChannel *pchan;            /* pose channel backups are for */
775         
776         bPoseChannel olddata;           /* copy of pose channel's old data (at start) */
777         IDProperty *oldprops;           /* copy (needs freeing) of pose channel's properties (at start) */
778 } tPoseLib_Backup;
779
780 /* Makes a copy of the current pose for restoration purposes - doesn't do constraints currently */
781 static void poselib_backup_posecopy (tPoseLib_PreviewData *pld)
782 {
783         bActionGroup *agrp;
784         bPoseChannel *pchan;
785         
786         /* for each posechannel that has an actionchannel in */
787         for (agrp= pld->act->groups.first; agrp; agrp= agrp->next) {
788                 /* try to find posechannel */
789                 pchan= get_pose_channel(pld->pose, agrp->name);
790                 
791                 /* backup data if available */
792                 if (pchan) {
793                         tPoseLib_Backup *plb;
794                         
795                         /* store backup */
796                         plb= MEM_callocN(sizeof(tPoseLib_Backup), "tPoseLib_Backup");
797                         
798                         plb->pchan= pchan;
799                         memcpy(&plb->olddata, plb->pchan, sizeof(bPoseChannel));
800                         
801                         if (pchan->prop)
802                                 plb->oldprops= IDP_CopyProperty(pchan->prop);
803                         
804                         BLI_addtail(&pld->backups, plb);
805                         
806                         /* mark as being affected */
807                         if ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))
808                                 pld->selcount++;
809                         pld->totcount++;
810                 }
811         }
812 }
813
814 /* Restores original pose */
815 static void poselib_backup_restore (tPoseLib_PreviewData *pld)
816 {
817         tPoseLib_Backup *plb;
818         
819         for (plb= pld->backups.first; plb; plb= plb->next) {
820                 /* copy most of data straight back */
821                 memcpy(plb->pchan, &plb->olddata, sizeof(bPoseChannel));
822                 
823                 /* just overwrite values of properties from the stored copies (there should be some) */
824                 if (plb->oldprops)
825                         IDP_SyncGroupValues(plb->pchan->prop, plb->oldprops);
826                         
827                 // TODO: constraints settings aren't restored yet, even though these could change (though not that likely)
828         }
829 }
830
831 /* Free list of backups, including any side data it may use */
832 static void poselib_backup_free_data (tPoseLib_PreviewData *pld)
833 {
834         tPoseLib_Backup *plb, *plbn;
835         
836         for (plb= pld->backups.first; plb; plb= plbn) {
837                 plbn= plb->next;
838                 
839                 /* free custom data */
840                 if (plb->oldprops) {
841                         IDP_FreeProperty(plb->oldprops);
842                         MEM_freeN(plb->oldprops);
843                 }
844                 
845                 /* free backup element now */
846                 BLI_freelinkN(&pld->backups, plb);
847         }
848 }
849
850 /* ---------------------------- */
851
852 /* Applies the appropriate stored pose from the pose-library to the current pose
853  *      - assumes that a valid object, with a poselib has been supplied
854  *      - gets the string to print in the header
855  *      - this code is based on the code for extract_pose_from_action in blenkernel/action.c
856  */
857 static void poselib_apply_pose (tPoseLib_PreviewData *pld)
858 {
859         PointerRNA *ptr= &pld->rna_ptr;
860         bArmature *arm= pld->arm;
861         bPose *pose= pld->pose;
862         bPoseChannel *pchan;
863         bAction *act= pld->act;
864         bActionGroup *agrp;
865         
866         KeyframeEditData ked= {{NULL}};
867         KeyframeEditFunc group_ok_cb;
868         int frame= 1;
869         
870         /* get the frame */
871         if (pld->marker)
872                 frame= pld->marker->frame;
873         else
874                 return; 
875         
876         
877         /* init settings for testing groups for keyframes */
878         group_ok_cb= ANIM_editkeyframes_ok(BEZT_OK_FRAMERANGE);
879         ked.f1= ((float)frame) - 0.5f;
880         ked.f2= ((float)frame) + 0.5f;
881         
882         
883         /* start applying - only those channels which have a key at this point in time! */
884         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
885                 /* check if group has any keyframes */
886                 if (ANIM_animchanneldata_keyframes_loop(&ked, NULL, agrp, ALE_GROUP, NULL, group_ok_cb, NULL)) {
887                         /* has keyframe on this frame, so try to get a PoseChannel with this name */
888                         pchan= get_pose_channel(pose, agrp->name);
889                         
890                         if (pchan) {    
891                                 short ok= 0;
892                                 
893                                 /* check if this bone should get any animation applied */
894                                 if (pld->selcount == 0) {
895                                         /* if no bones are selected, then any bone is ok */
896                                         ok= 1;
897                                 }
898                                 else if (pchan->bone) {
899                                         /* only ok if bone is visible and selected */
900                                         if ((pchan->bone->flag & BONE_SELECTED) &&
901                                             (pchan->bone->flag & BONE_HIDDEN_P) == 0 &&
902                                             (pchan->bone->layer & arm->layer))
903                                         {
904                                                 ok = 1;
905                                         }
906                                 }
907                                 
908                                 if (ok) 
909                                         animsys_evaluate_action_group(ptr, act, agrp, NULL, (float)frame);
910                         }
911                 }
912         }
913 }
914
915 /* Auto-keys/tags bones affected by the pose used from the poselib */
916 static void poselib_keytag_pose (bContext *C, Scene *scene, tPoseLib_PreviewData *pld)
917 {
918         bPose *pose= pld->pose;
919         bPoseChannel *pchan;
920         bAction *act= pld->act;
921         bActionGroup *agrp;
922         
923         KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_WHOLE_CHARACTER_ID);
924         ListBase dsources = {NULL, NULL};
925         short autokey = autokeyframe_cfra_can_key(scene, &pld->ob->id);
926         
927         /* start tagging/keying */
928         for (agrp= act->groups.first; agrp; agrp= agrp->next) {
929                 /* only for selected bones unless there aren't any selected, in which case all are included  */
930                 pchan= get_pose_channel(pose, agrp->name);
931                 
932                 if (pchan) {
933                         if ( (pld->selcount == 0) || ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED)) ) {
934                                 if (autokey) {
935                                         /* add datasource override for the PoseChannel, to be used later */
936                                         ANIM_relative_keyingset_add_source(&dsources, &pld->ob->id, &RNA_PoseBone, pchan); 
937                                         
938                                         /* clear any unkeyed tags */
939                                         if (pchan->bone)
940                                                 pchan->bone->flag &= ~BONE_UNKEYED;
941                                 }
942                                 else {
943                                         /* add unkeyed tags */
944                                         if (pchan->bone)
945                                                 pchan->bone->flag |= BONE_UNKEYED;
946                                 }
947                         }
948                 }
949         }
950         
951         /* perform actual auto-keying now */
952         if (autokey) {
953                 /* insert keyframes for all relevant bones in one go */
954                 ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, (float)CFRA);
955                 BLI_freelistN(&dsources);
956         }
957         
958         /* send notifiers for this */
959         WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME|NA_EDITED, NULL);
960 }
961
962 /* Apply the relevant changes to the pose */
963 static void poselib_preview_apply (bContext *C, wmOperator *op)
964 {
965         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
966         
967         /* only recalc pose (and its dependencies) if pose has changed */
968         if (pld->redraw == PL_PREVIEW_REDRAWALL) {
969                 /* don't clear pose if firsttime */
970                 if ((pld->flag & PL_PREVIEW_FIRSTTIME)==0)
971                         poselib_backup_restore(pld);
972                 else
973                         pld->flag &= ~PL_PREVIEW_FIRSTTIME;
974                         
975                 /* pose should be the right one to draw (unless we're temporarily not showing it) */
976                 if ((pld->flag & PL_PREVIEW_SHOWORIGINAL)==0) {
977                         RNA_int_set(op->ptr, "pose_index", BLI_findindex(&pld->act->markers, pld->marker));
978                         poselib_apply_pose(pld);
979                 }
980                 else
981                         RNA_int_set(op->ptr, "pose_index", -2); /* -2 means don't apply any pose */
982                 
983                 /* old optimize trick... this enforces to bypass the depgraph 
984                  *      - note: code copied from transform_generics.c -> recalcData()
985                  */
986                 // FIXME: shouldn't this use the builtin stuff?
987                 if ((pld->arm->flag & ARM_DELAYDEFORM)==0)
988                         DAG_id_tag_update(&pld->ob->id, OB_RECALC_DATA);  /* sets recalc flags */
989                 else
990                         where_is_pose(pld->scene, pld->ob);
991         }
992         
993         /* do header print - if interactively previewing */
994         if (pld->state == PL_PREVIEW_RUNNING) {
995                 if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
996                         BLI_strncpy(pld->headerstr,
997                                     "PoseLib Previewing Pose: [Showing Original Pose] | Use Tab to start previewing poses again",
998                                     sizeof(pld->headerstr));
999                         ED_area_headerprint(pld->sa, pld->headerstr);
1000                 }
1001                 else if (pld->searchstr[0]) {
1002                         char tempstr[65];
1003                         char markern[64];
1004                         short index;
1005                         
1006                         /* get search-string */
1007                         index= pld->search_cursor;
1008                         
1009                         if (index >= 0 && index <= sizeof(tempstr) - 1) {
1010                                 memcpy(&tempstr[0], &pld->searchstr[0], index);
1011                                 tempstr[index]= '|';
1012                                 memcpy(&tempstr[index+1], &pld->searchstr[index], (sizeof(tempstr) - 1) - index);
1013                         }
1014                         else {
1015                                 BLI_strncpy(tempstr, pld->searchstr, sizeof(tempstr));
1016                         }
1017                         
1018                         /* get marker name */
1019                         BLI_strncpy(markern, pld->marker ? pld->marker->name : "No Matches", sizeof(markern));
1020
1021                         BLI_snprintf(pld->headerstr, sizeof(pld->headerstr),
1022                                      "PoseLib Previewing Pose: Filter - [%s] | "
1023                                      "Current Pose - \"%s\"  | "
1024                                      "Use ScrollWheel or PageUp/Down to change",
1025                                      tempstr, markern);
1026                         ED_area_headerprint(pld->sa, pld->headerstr);
1027                 }
1028                 else {
1029                         BLI_snprintf(pld->headerstr, sizeof(pld->headerstr),
1030                                      "PoseLib Previewing Pose: \"%s\"  | "
1031                                      "Use ScrollWheel or PageUp/Down to change",
1032                                      pld->marker->name);
1033                         ED_area_headerprint(pld->sa, pld->headerstr);
1034                 }
1035         }
1036         
1037         /* request drawing of view + clear redraw flag */
1038         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, pld->ob);
1039         pld->redraw= PL_PREVIEW_NOREDRAW;
1040 }
1041
1042 /* ---------------------------- */
1043
1044 /* This helper function is called during poselib_preview_poses to find the 
1045  * pose to preview next (after a change event)
1046  */
1047 static void poselib_preview_get_next (tPoseLib_PreviewData *pld, int step)
1048 {
1049         /* stop if not going anywhere, as we assume that there is a direction to move in */
1050         if (step == 0)
1051                 return;
1052         
1053         /* search-string dictates a special approach */
1054         if (pld->searchstr[0]) {
1055                 TimeMarker *marker;
1056                 LinkData *ld, *ldn, *ldc;
1057                 
1058                 /* free and rebuild if needed (i.e. if search-str changed) */
1059                 if (strcmp(pld->searchstr, pld->searchold)) {
1060                         /* free list of temporary search matches */
1061                         BLI_freelistN(&pld->searchp);
1062                         
1063                         /* generate a new list of search matches */
1064                         for (marker= pld->act->markers.first; marker; marker= marker->next) {
1065                                 /* does the name partially match? 
1066                                  *      - don't worry about case, to make it easier for users to quickly input a name (or 
1067                                  *        part of one), which is the whole point of this feature
1068                                  */
1069                                 if (BLI_strcasestr(marker->name, pld->searchstr)) {
1070                                         /* make link-data to store reference to it */
1071                                         ld= MEM_callocN(sizeof(LinkData), "PoseMatch");
1072                                         ld->data= marker;
1073                                         BLI_addtail(&pld->searchp, ld);
1074                                 }
1075                         }
1076                         
1077                         /* set current marker to NULL (so that we start from first) */
1078                         pld->marker= NULL;
1079                 }
1080                 
1081                 /* check if any matches */
1082                 if (pld->searchp.first == NULL) { 
1083                         pld->marker= NULL;
1084                         return;
1085                 }
1086                 
1087                 /* find first match */
1088                 for (ldc= pld->searchp.first; ldc; ldc= ldc->next) {
1089                         if (ldc->data == pld->marker)
1090                                 break;
1091                 }
1092                 if (ldc == NULL)
1093                         ldc= pld->searchp.first;
1094                         
1095                 /* Loop through the matches in a cyclic fashion, incrementing/decrementing step as appropriate 
1096                  * until step == 0. At this point, marker should be the correct marker.
1097                  */
1098                 if (step > 0) {
1099                         for (ld=ldc; ld && step; ld=ldn, step--)
1100                                 ldn= (ld->next) ? ld->next : pld->searchp.first;
1101                 }
1102                 else {
1103                         for (ld=ldc; ld && step; ld=ldn, step++)
1104                                 ldn= (ld->prev) ? ld->prev : pld->searchp.last;
1105                 }
1106                 
1107                 /* set marker */
1108                 if (ld)
1109                         pld->marker= ld->data;
1110         }
1111         else {
1112                 TimeMarker *marker, *next;
1113                 
1114                 /* if no marker, because we just ended searching, then set that to the start of the list */
1115                 if (pld->marker == NULL)
1116                         pld->marker= pld->act->markers.first;
1117                 
1118                 /* Loop through the markers in a cyclic fashion, incrementing/decrementing step as appropriate 
1119                  * until step == 0. At this point, marker should be the correct marker.
1120                  */
1121                 if (step > 0) {
1122                         for (marker=pld->marker; marker && step; marker=next, step--)
1123                                 next= (marker->next) ? marker->next : pld->act->markers.first;
1124                 }
1125                 else {
1126                         for (marker=pld->marker; marker && step; marker=next, step++)
1127                                 next= (marker->prev) ? marker->prev : pld->act->markers.last;
1128                 }
1129                 
1130                 /* it should be fairly impossible for marker to be NULL */
1131                 if (marker)
1132                         pld->marker= marker;
1133         }
1134 }
1135
1136 /* specially handle events for searching */
1137 static void poselib_preview_handle_search (tPoseLib_PreviewData *pld, unsigned short event, char ascii)
1138 {
1139         /* try doing some form of string manipulation first */
1140         switch (event) {
1141                 case BACKSPACEKEY:
1142                         if (pld->searchstr[0] && pld->search_cursor) {
1143                                 short len= strlen(pld->searchstr);
1144                                 short index= pld->search_cursor;
1145                                 short i;
1146                                 
1147                                 for (i = index; i <= len; i++) 
1148                                         pld->searchstr[i-1] = pld->searchstr[i];
1149                                 
1150                                 pld->search_cursor--;
1151                                 
1152                                 poselib_preview_get_next(pld, 1);
1153                                 pld->redraw = PL_PREVIEW_REDRAWALL;
1154                                 return;
1155                         }       
1156                         break;
1157                         
1158                 case DELKEY:
1159                         if (pld->searchstr[0] && pld->searchstr[1]) {
1160                                 short len= strlen(pld->searchstr);
1161                                 short index= pld->search_cursor;
1162                                 int i;
1163                                 
1164                                 if (index < len) {
1165                                         for (i = index; i < len; i++) 
1166                                                 pld->searchstr[i] = pld->searchstr[i+1];
1167                                                 
1168                                         poselib_preview_get_next(pld, 1);
1169                                         pld->redraw = PL_PREVIEW_REDRAWALL;
1170                                         return;
1171                                 }
1172                         }
1173                         break;
1174         }
1175         
1176         if (ascii) {
1177                 /* character to add to the string */
1178                 short index= pld->search_cursor;
1179                 short len= (pld->searchstr[0]) ? strlen(pld->searchstr) : 0;
1180                 short i;
1181                 
1182                 if (len) {
1183                         for (i = len; i > index; i--)  
1184                                 pld->searchstr[i]= pld->searchstr[i-1];
1185                 }
1186                 else
1187                         pld->searchstr[1]= 0;
1188                         
1189                 pld->searchstr[index]= ascii;
1190                 pld->search_cursor++;
1191                 
1192                 poselib_preview_get_next(pld, 1);
1193                 pld->redraw = PL_PREVIEW_REDRAWALL;
1194         }
1195 }
1196
1197 /* handle events for poselib_preview_poses */
1198 static int poselib_preview_handle_event (bContext *UNUSED(C), wmOperator *op, wmEvent *event)
1199 {
1200         tPoseLib_PreviewData *pld= op->customdata; 
1201         int ret = OPERATOR_RUNNING_MODAL;
1202         
1203         /* only accept 'press' event, and ignore 'release', so that we don't get double actions */
1204         if (ELEM(event->val, KM_PRESS, KM_NOTHING) == 0) {
1205                 //printf("PoseLib: skipping event with type '%s' and val %d\n", WM_key_event_string(event->type), event->val);
1206                 return ret; 
1207         }
1208         
1209         /* backup stuff that needs to occur before every operation
1210          *      - make a copy of searchstr, so that we know if cache needs to be rebuilt
1211          */
1212         BLI_strncpy(pld->searchold, pld->searchstr, sizeof(pld->searchold));
1213         
1214         /* if we're currently showing the original pose, only certain events are handled */
1215         if (pld->flag & PL_PREVIEW_SHOWORIGINAL) {
1216                 switch (event->type) {
1217                         /* exit - cancel */
1218                         case ESCKEY:
1219                         case RIGHTMOUSE:
1220                                 pld->state= PL_PREVIEW_CANCEL;
1221                                 break;
1222                                 
1223                         /* exit - confirm */
1224                         case LEFTMOUSE:
1225                         case RETKEY:
1226                         case PADENTER:
1227                         case SPACEKEY:
1228                                 pld->state= PL_PREVIEW_CONFIRM;
1229                                 break;
1230                         
1231                         /* view manipulation */
1232                         /* we add pass through here, so that the operators responsible for these can still run, 
1233                          * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1234                          */
1235                         case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1236                         case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1237                         case PADPLUSKEY: case PADMINUS: 
1238                         case MIDDLEMOUSE: case MOUSEMOVE:
1239                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1240                                 ret = OPERATOR_PASS_THROUGH;
1241                                 break;
1242                                 
1243                         /* quicky compare to original */
1244                         case TABKEY:
1245                                 pld->flag &= ~PL_PREVIEW_SHOWORIGINAL;
1246                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1247                                 break;
1248                 }
1249                 
1250                 /* EXITS HERE... */
1251                 return ret;
1252         }
1253         
1254         /* NORMAL EVENT HANDLING... */
1255         /* searching takes priority over normal activity */
1256         switch (event->type) {
1257                 /* exit - cancel */
1258                 case ESCKEY:
1259                 case RIGHTMOUSE:
1260                         pld->state= PL_PREVIEW_CANCEL;
1261                         break;
1262                         
1263                 /* exit - confirm */
1264                 case LEFTMOUSE:
1265                 case RETKEY:
1266                 case PADENTER:
1267                 case SPACEKEY:
1268                         pld->state= PL_PREVIEW_CONFIRM;
1269                         break;
1270                         
1271                 /* toggle between original pose and poselib pose*/
1272                 case TABKEY:
1273                         pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1274                         pld->redraw= PL_PREVIEW_REDRAWALL;
1275                         break;
1276                 
1277                 /* change to previous pose (cyclic) */
1278                 case PAGEUPKEY:
1279                 case WHEELUPMOUSE:
1280                         poselib_preview_get_next(pld, -1);
1281                         pld->redraw= PL_PREVIEW_REDRAWALL;
1282                         break;
1283                 
1284                 /* change to next pose (cyclic) */
1285                 case PAGEDOWNKEY:
1286                 case WHEELDOWNMOUSE:
1287                         poselib_preview_get_next(pld, 1);
1288                         pld->redraw= PL_PREVIEW_REDRAWALL;
1289                         break;
1290                 
1291                 /* jump 5 poses (cyclic, back) */
1292                 case DOWNARROWKEY:
1293                         poselib_preview_get_next(pld, -5);
1294                         pld->redraw= PL_PREVIEW_REDRAWALL;
1295                         break;
1296                 
1297                 /* jump 5 poses (cyclic, forward) */
1298                 case UPARROWKEY:
1299                         poselib_preview_get_next(pld, 5);
1300                         pld->redraw= PL_PREVIEW_REDRAWALL;
1301                         break;
1302                 
1303                 /* change to next pose or searching cursor control */
1304                 case RIGHTARROWKEY:
1305                         if (pld->searchstr[0]) {
1306                                 /* move text-cursor to the right */
1307                                 if (pld->search_cursor < strlen(pld->searchstr))
1308                                         pld->search_cursor++;
1309                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1310                         }
1311                         else {
1312                                 /* change to next pose (cyclic) */
1313                                 poselib_preview_get_next(pld, 1);
1314                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1315                         }
1316                         break;
1317                         
1318                 /* change to next pose or searching cursor control */
1319                 case LEFTARROWKEY:
1320                         if (pld->searchstr[0]) {
1321                                 /* move text-cursor to the left */
1322                                 if (pld->search_cursor)
1323                                         pld->search_cursor--;
1324                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1325                         }
1326                         else {
1327                                 /* change to previous pose (cyclic) */
1328                                 poselib_preview_get_next(pld, -1);
1329                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1330                         }
1331                         break;
1332                         
1333                 /* change to first pose or start of searching string */
1334                 case HOMEKEY:
1335                         if (pld->searchstr[0]) {
1336                                 pld->search_cursor= 0;
1337                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1338                         }
1339                         else {
1340                                 /* change to first pose */
1341                                 pld->marker= pld->act->markers.first;
1342                                 pld->act->active_marker= 1;
1343                                 
1344                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1345                         }
1346                         break;
1347                         
1348                 /* change to last pose or start of searching string */
1349                 case ENDKEY:
1350                         if (pld->searchstr[0]) {
1351                                 pld->search_cursor= strlen(pld->searchstr);
1352                                 pld->redraw= PL_PREVIEW_REDRAWHEADER;
1353                         }
1354                         else {
1355                                 /* change to last pose */
1356                                 pld->marker= pld->act->markers.last;
1357                                 pld->act->active_marker= BLI_countlist(&pld->act->markers);
1358                                 
1359                                 pld->redraw= PL_PREVIEW_REDRAWALL;
1360                         }
1361                         break;
1362                 
1363                 /* view manipulation */
1364                 /* we add pass through here, so that the operators responsible for these can still run, 
1365                  * even though we still maintain control (as RUNNING_MODAL flag is still set too)
1366                  */
1367                 case MIDDLEMOUSE: case MOUSEMOVE:
1368                         //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1369                         ret = OPERATOR_PASS_THROUGH;
1370                         break;
1371                         
1372                 /* view manipulation, or searching */
1373                 case PAD0: case PAD1: case PAD2: case PAD3: case PAD4:
1374                 case PAD5: case PAD6: case PAD7: case PAD8: case PAD9:
1375                 case PADPLUSKEY: case PADMINUS:
1376                         if (pld->searchstr[0]) {
1377                                 /* searching... */
1378                                 poselib_preview_handle_search(pld, event->type, event->ascii);
1379                         }
1380                         else {
1381                                 /* view manipulation (see above) */
1382                                 //pld->redraw= PL_PREVIEW_REDRAWHEADER;
1383                                 ret = OPERATOR_PASS_THROUGH;
1384                         }
1385                         break;
1386                         
1387                 /* otherwise, assume that searching might be able to handle it */
1388                 default:
1389                         poselib_preview_handle_search(pld, event->type, event->ascii);
1390                         break;
1391         }
1392         
1393         return ret;
1394 }
1395
1396 /* ---------------------------- */
1397
1398 /* Init PoseLib Previewing data */
1399 static void poselib_preview_init_data (bContext *C, wmOperator *op)
1400 {
1401         tPoseLib_PreviewData *pld;
1402         Object *ob= get_poselib_object(C);
1403         int pose_index = RNA_int_get(op->ptr, "pose_index");
1404         
1405         /* set up preview state info */
1406         op->customdata= pld= MEM_callocN(sizeof(tPoseLib_PreviewData), "PoseLib Preview Data");
1407         
1408         /* get basic data */
1409         pld->ob= ob;
1410         pld->arm= (ob) ? (ob->data) : NULL;
1411         pld->pose= (ob) ? (ob->pose) : NULL;
1412         pld->act= (ob) ? (ob->poselib) : NULL;
1413         
1414         pld->scene= CTX_data_scene(C);
1415         pld->sa= CTX_wm_area(C);
1416         
1417         /* get starting pose based on RNA-props for this operator */
1418         if (pose_index == -1)
1419                 pld->marker= poselib_get_active_pose(pld->act);
1420         else if (pose_index == -2)
1421                 pld->flag |= PL_PREVIEW_SHOWORIGINAL;
1422         else
1423                 pld->marker= (pld->act) ? BLI_findlink(&pld->act->markers, pose_index) : NULL;
1424         
1425         /* check if valid poselib */
1426         if (ELEM3(NULL, pld->ob, pld->pose, pld->arm)) {
1427                 BKE_report(op->reports, RPT_ERROR, "PoseLib is only for Armatures in PoseMode");
1428                 pld->state= PL_PREVIEW_ERROR;
1429                 return;
1430         }
1431         if (pld->act == NULL) {
1432                 BKE_report(op->reports, RPT_ERROR, "Object doesn't have a valid PoseLib");
1433                 pld->state= PL_PREVIEW_ERROR;
1434                 return;
1435         }
1436         if (pld->marker == NULL) {
1437                 if (pld->act->markers.first) {
1438                         /* just use first one then... */
1439                         pld->marker= pld->act->markers.first;
1440                         if (pose_index > -2) 
1441                                 BKE_report(op->reports, RPT_WARNING, "PoseLib had no active pose");
1442                 }
1443                 else {
1444                         BKE_report(op->reports, RPT_ERROR, "PoseLib has no poses to preview/apply");
1445                         pld->state= PL_PREVIEW_ERROR;
1446                         return;
1447                 }
1448         }
1449         
1450         /* get ID pointer for applying poses */
1451         RNA_id_pointer_create(&ob->id, &pld->rna_ptr);
1452         
1453         /* make backups for restoring pose */
1454         poselib_backup_posecopy(pld);
1455         
1456         /* set flags for running */
1457         pld->state= PL_PREVIEW_RUNNING;
1458         pld->redraw= PL_PREVIEW_REDRAWALL;
1459         pld->flag |= PL_PREVIEW_FIRSTTIME;
1460         
1461         /* set depsgraph flags */
1462                 /* make sure the lock is set OK, unlock can be accidentally saved? */
1463         pld->pose->flag |= POSE_LOCKED;
1464         pld->pose->flag &= ~POSE_DO_UNLOCK;
1465         
1466         /* clear strings + search */
1467         pld->headerstr[0]= pld->searchstr[0]= pld->searchold[0]= '\0';
1468         pld->search_cursor= 0;
1469 }
1470
1471 /* After previewing poses */
1472 static void poselib_preview_cleanup (bContext *C, wmOperator *op)
1473 {
1474         tPoseLib_PreviewData *pld= (tPoseLib_PreviewData *)op->customdata;
1475         Scene *scene= pld->scene;
1476         Object *ob= pld->ob;
1477         bPose *pose= pld->pose;
1478         bArmature *arm= pld->arm;
1479         bAction *act= pld->act;
1480         TimeMarker *marker= pld->marker;
1481         
1482         /* redraw the header so that it doesn't show any of our stuff anymore */
1483         ED_area_headerprint(pld->sa, NULL);
1484         
1485         /* this signal does one recalc on pose, then unlocks, so ESC or edit will work */
1486         pose->flag |= POSE_DO_UNLOCK;
1487         
1488         /* clear pose if canceled */
1489         if (pld->state == PL_PREVIEW_CANCEL) {
1490                 poselib_backup_restore(pld);
1491                 
1492                 /* old optimize trick... this enforces to bypass the depgraph 
1493                  *      - note: code copied from transform_generics.c -> recalcData()
1494                  */
1495                 if ((arm->flag & ARM_DELAYDEFORM)==0)
1496                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
1497                 else
1498                         where_is_pose(scene, ob);
1499                 
1500         }
1501         else if (pld->state == PL_PREVIEW_CONFIRM) {
1502                 /* tag poses as appropriate */
1503                 poselib_keytag_pose(C, scene, pld);
1504                 
1505                 /* change active pose setting */
1506                 act->active_marker= BLI_findindex(&act->markers, marker) + 1;
1507                 action_set_activemarker(act, marker, NULL);
1508                 
1509                 /* Update event for pose and deformation children */
1510                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1511                 
1512                 /* updates */
1513                 if (IS_AUTOKEY_MODE(scene, NORMAL)) {
1514                         //remake_action_ipos(ob->action);
1515                 }
1516                 else
1517                         where_is_pose(scene, ob);
1518         }
1519         
1520         /* free memory used for backups and searching */
1521         poselib_backup_free_data(pld);
1522         BLI_freelistN(&pld->searchp);
1523         
1524         /* free temp data for operator */
1525         MEM_freeN(pld);
1526         op->customdata= NULL;
1527 }
1528
1529 /* End previewing operation */
1530 static int poselib_preview_exit (bContext *C, wmOperator *op)
1531 {
1532         tPoseLib_PreviewData *pld= op->customdata;
1533         int exit_state = pld->state;
1534         
1535         /* finish up */
1536         poselib_preview_cleanup(C, op);
1537         
1538         if (ELEM(exit_state, PL_PREVIEW_CANCEL, PL_PREVIEW_ERROR))
1539                 return OPERATOR_CANCELLED;
1540         else
1541                 return OPERATOR_FINISHED;
1542 }
1543
1544 /* Cancel previewing operation (called when exiting Blender) */
1545 static int poselib_preview_cancel (bContext *C, wmOperator *op)
1546 {
1547         poselib_preview_exit(C, op);
1548         return OPERATOR_CANCELLED;
1549 }
1550
1551 /* main modal status check */
1552 static int poselib_preview_modal (bContext *C, wmOperator *op, wmEvent *event)
1553 {
1554         tPoseLib_PreviewData *pld= op->customdata;
1555         int ret;
1556         
1557         /* 1) check state to see if we're still running */
1558         if (pld->state != PL_PREVIEW_RUNNING)
1559                 return poselib_preview_exit(C, op);
1560         
1561         /* 2) handle events */
1562         ret= poselib_preview_handle_event(C, op, event);
1563         
1564         /* 3) apply changes and redraw, otherwise, confirming goes wrong */
1565         if (pld->redraw)
1566                 poselib_preview_apply(C, op);
1567         
1568         return ret;
1569 }
1570
1571 /* Modal Operator init */
1572 static int poselib_preview_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1573 {
1574         tPoseLib_PreviewData *pld;
1575         
1576         /* check if everything is ok, and init settings for modal operator */
1577         poselib_preview_init_data(C, op);
1578         pld= (tPoseLib_PreviewData *)op->customdata;
1579         
1580         if (pld->state == PL_PREVIEW_ERROR) {
1581                 /* an error occurred, so free temp mem used */
1582                 poselib_preview_cleanup(C, op);
1583                 return OPERATOR_CANCELLED;
1584         }
1585         
1586         /* do initial apply to have something to look at */
1587         poselib_preview_apply(C, op);
1588         
1589         /* add temp handler if we're running as a modal operator */
1590         WM_event_add_modal_handler(C, op);
1591
1592         return OPERATOR_RUNNING_MODAL;
1593 }
1594
1595 /* Repeat operator */
1596 static int poselib_preview_exec (bContext *C, wmOperator *op)
1597 {
1598         tPoseLib_PreviewData *pld;
1599         
1600         /* check if everything is ok, and init settings for modal operator */
1601         poselib_preview_init_data(C, op);
1602         pld= (tPoseLib_PreviewData *)op->customdata;
1603         
1604         if (pld->state == PL_PREVIEW_ERROR) {
1605                 /* an error occurred, so free temp mem used */
1606                 poselib_preview_cleanup(C, op);
1607                 return OPERATOR_CANCELLED;
1608         }
1609         
1610         /* the exec() callback is effectively a 'run-once' scenario, so set the state to that
1611          * so that everything draws correctly
1612          */
1613         pld->state = PL_PREVIEW_RUNONCE;
1614         
1615         /* apply the active pose */
1616         poselib_preview_apply(C, op);
1617         
1618         /* now, set the status to exit */
1619         pld->state = PL_PREVIEW_CONFIRM;
1620         
1621         /* cleanup */
1622         return poselib_preview_exit(C, op);
1623 }
1624
1625 void POSELIB_OT_browse_interactive(wmOperatorType *ot)
1626 {
1627         /* identifiers */
1628         ot->name = "PoseLib Browse Poses";
1629         ot->idname = "POSELIB_OT_browse_interactive";
1630         ot->description = "Interactively browse poses in 3D-View";
1631         
1632         /* callbacks */
1633         ot->invoke = poselib_preview_invoke;
1634         ot->modal = poselib_preview_modal;
1635         ot->cancel = poselib_preview_cancel;
1636         ot->exec = poselib_preview_exec;
1637         ot->poll = has_poselib_pose_data_poll;
1638         
1639         /* flags */
1640         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1641         
1642         /* properties */        
1643                 // TODO: make the pose_index into a proper enum instead of a cryptic int...
1644         ot->prop = RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
1645         
1646         // XXX: percentage vs factor?
1647         /* not used yet */
1648         /* RNA_def_float_factor(ot->srna, "blend_factor", 1.0f, 0.0f, 1.0f, "Blend Factor", "Amount that the pose is applied on top of the existing poses", 0.0f, 1.0f); */
1649 }
1650
1651 void POSELIB_OT_apply_pose(wmOperatorType *ot)
1652 {
1653         /* identifiers */
1654         ot->name = "Apply Pose Library Pose";
1655         ot->idname = "POSELIB_OT_apply_pose";
1656         ot->description = "Apply specified Pose Library pose to the rig";
1657         
1658         /* callbacks */
1659         ot->exec = poselib_preview_exec;
1660         ot->poll = has_poselib_pose_data_poll;
1661         
1662         /* flags */
1663         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1664         
1665         /* properties */        
1666                 // TODO: make the pose_index into a proper enum instead of a cryptic int...
1667         ot->prop = RNA_def_int(ot->srna, "pose_index", -1, -2, INT_MAX, "Pose", "Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)", 0, INT_MAX);
1668 }