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