TimelineActions.cs 33.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using UnityEditor.ShortcutManagement;
using UnityEngine;
using UnityEngine.Timeline;
using MenuEntryPair = System.Collections.Generic.KeyValuePair<UnityEngine.GUIContent, UnityEditor.Timeline.TimelineAction>;

namespace UnityEditor.Timeline
{
    [ActiveInMode(TimelineModes.Default)]
    abstract class TimelineAction : MenuItemActionBase
    {
        public abstract bool Execute(WindowState state);

        public virtual MenuActionDisplayState GetDisplayState(WindowState state)
        {
            return MenuActionDisplayState.Visible;
        }

        public virtual bool IsChecked(WindowState state)
        {
            return false;
        }

        protected string GetDisplayName(WindowState state)
        {
            return menuName;
        }

        bool CanExecute(WindowState state)
        {
            return GetDisplayState(state) == MenuActionDisplayState.Visible;
        }

        public static void Invoke<T>(WindowState state) where T : TimelineAction
        {
            var action = AllActions.FirstOrDefault(x => x.GetType() == typeof(T));
            if (action != null && action.CanExecute(state))
                action.Execute(state);
        }

        // an instance of all TimelineActions
        public static readonly TimelineAction[] AllActions = GetActionsOfType(typeof(TimelineAction)).Select(x => (TimelineAction)x.GetConstructors()[0].Invoke(null)).ToArray();

        // an instance of all TimelineActions that should appear in a regular contextMenu
        public static readonly TimelineAction[] MenuActions = AllActions.Where(a => a.showInMenu && !(a is MarkerHeaderAction)).ToArray();

        public static void GetMenuEntries(IEnumerable<TimelineAction> actions, Vector2? mousePos, List<MenuActionItem> items)
        {
            var state = TimelineWindow.instance.state;
            var mode = TimelineWindow.instance.currentMode.mode;

            foreach (var action in actions)
            {
                var actionItem = action;
                action.mousePosition = mousePos;
                items.Add(
                    new MenuActionItem()
                    {
                        category =  action.category,
                        entryName = action.GetDisplayName(state),
                        shortCut = action.shortCut,
                        isChecked = action.IsChecked(state),
                        isActiveInMode = IsActionActiveInMode(action, mode),
                        priority = action.priority,
                        state = action.GetDisplayState(state),
                        callback = () =>
                        {
                            actionItem.mousePosition = mousePos;
                            actionItem.Execute(state);
                            actionItem.mousePosition = null;
                        }
                    }
                );
                action.mousePosition = null;
            }
        }

        public static bool HandleShortcut(WindowState state, Event evt)
        {
            if (EditorGUI.IsEditingTextField())
                return false;

            foreach (var action in AllActions)
            {
                var attr = action.GetType().GetCustomAttributes(typeof(ShortcutAttribute), true);

                foreach (ShortcutAttribute shortcut in attr)
                {
                    if (shortcut.MatchesEvent(evt))
                    {
                        if (s_ShowActionTriggeredByShortcut)
                            Debug.Log(action.GetType().Name);

                        if (!IsActionActiveInMode(action, TimelineWindow.instance.currentMode.mode))
                            return false;

                        var handled = action.Execute(state);
                        if (handled)
                            return true;
                    }
                }
            }

            return false;
        }

        protected static bool DoInternal(Type t, WindowState state)
        {
            var action = (TimelineAction)t.GetConstructors()[0].Invoke(null);

            if (action.CanExecute(state))
                return action.Execute(state);

            return false;
        }
    }

    // indicates the action only applies to the marker header menu
    abstract class MarkerHeaderAction : TimelineAction
    {
    }


    [MenuEntry("Copy", MenuOrder.TimelineAction.Copy)]
    [Shortcut("Main Menu/Edit/Copy", EventCommandNames.Copy)]
    class CopyAction : TimelineAction
    {
        public static bool Do(WindowState state)
        {
            return DoInternal(typeof(CopyAction), state);
        }

        public override MenuActionDisplayState GetDisplayState(WindowState state)
        {
            return SelectionManager.Count() > 0 ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled;
        }

        public override bool Execute(WindowState state)
        {
            TimelineEditor.clipboard.Clear();

            var clips = SelectionManager.SelectedClips().ToArray();
            if (clips.Length > 0)
            {
                ItemAction<TimelineClip>.Invoke<CopyClipsToClipboard>(state, clips);
            }
            var markers = SelectionManager.SelectedMarkers().ToArray();
            if (markers.Length > 0)
            {
                ItemAction<IMarker>.Invoke<CopyMarkersToClipboard>(state, markers);
            }
            var tracks = SelectionManager.SelectedTracks().ToArray();
            if (tracks.Length > 0)
            {
                CopyTracksToClipboard.Do(state, tracks);
            }

            return true;
        }
    }

    [MenuEntry("Paste", MenuOrder.TimelineAction.Paste)]
    [Shortcut("Main Menu/Edit/Paste", EventCommandNames.Paste)]
    class PasteAction : TimelineAction
    {
        public static bool Do(WindowState state)
        {
            return DoInternal(typeof(PasteAction), state);
        }

        public override MenuActionDisplayState GetDisplayState(WindowState state)
        {
            return CanPaste(state) ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled;
        }

        public override bool Execute(WindowState state)
        {
            if (!CanPaste(state))
                return false;

            PasteItems(state, mousePosition);
            PasteTracks(state);

            state.Refresh();

            mousePosition = null;
            return true;
        }

        bool CanPaste(WindowState state)
        {
            var copiedItems = TimelineEditor.clipboard.GetCopiedItems().ToList();

            if (!copiedItems.Any())
                return TimelineEditor.clipboard.GetTracks().Any();

            return CanPasteItems(copiedItems, state, mousePosition);
        }

        static bool CanPasteItems(ICollection<ItemsPerTrack> itemsGroups, WindowState state, Vector2? mousePosition)
        {
            var hasItemsCopiedFromMultipleTracks = itemsGroups.Count > 1;
            var allItemsCopiedFromCurrentAsset = itemsGroups.All(x => x.targetTrack.timelineAsset == state.editSequence.asset);
            var hasUsedShortcut = mousePosition == null;
            var anySourceLocked = itemsGroups.Any(x => x.targetTrack != null && x.targetTrack.lockedInHierarchy);

            var targetTrack = GetPickedTrack();
            if (targetTrack == null)
                targetTrack = SelectionManager.SelectedTracks().FirstOrDefault();

            //do not paste if the user copied items from another timeline
            //if the copied items comes from > 1 track (since we do not know where to paste the copied items)
            //or if a keyboard shortcut was used (since the user will not see the paste result)
            if (!allItemsCopiedFromCurrentAsset)
            {
                var isSelectedTrackInCurrentAsset = targetTrack != null && targetTrack.timelineAsset == state.editSequence.asset;
                if (hasItemsCopiedFromMultipleTracks || (hasUsedShortcut && !isSelectedTrackInCurrentAsset))
                    return false;
            }

            if (hasUsedShortcut)
                return !anySourceLocked; // copy/paste to same track

            if (hasItemsCopiedFromMultipleTracks)
            {
                //do not paste if the track which received the paste action does not contain a copied clip
                return !anySourceLocked && itemsGroups.Select(x => x.targetTrack).Contains(targetTrack);
            }

            var copiedItems = itemsGroups.SelectMany(i => i.items);
            return IsTrackValidForItems(targetTrack, copiedItems);
        }

        static void PasteItems(WindowState state, Vector2? mousePosition)
        {
            var copiedItems = TimelineEditor.clipboard.GetCopiedItems().ToList();
            var numberOfUniqueParentsInClipboard = copiedItems.Count();

            if (numberOfUniqueParentsInClipboard == 0) return;
            List<ITimelineItem> newItems;

            //if the copied items were on a single parent, then use the mouse position to get the parent OR the original parent
            if (numberOfUniqueParentsInClipboard == 1)
            {
                var itemsGroup = copiedItems.First();
                TrackAsset target = null;
                if (mousePosition.HasValue)
                    target = GetPickedTrack();
                if (target == null)
                    target = FindSuitableParentForSingleTrackPasteWithoutMouse(itemsGroup);

                var candidateTime = TimelineHelpers.GetCandidateTime(state, mousePosition, target);
                newItems = TimelineHelpers.DuplicateItemsUsingCurrentEditMode(state, TimelineEditor.clipboard.exposedPropertyTable, TimelineEditor.inspectedDirector, itemsGroup, target, candidateTime, "Paste Items").ToList();
            }
            //if copied items were on multiple parents, then the destination parents are the same as the original parents
            else
            {
                var time = TimelineHelpers.GetCandidateTime(state, mousePosition, copiedItems.Select(c => c.targetTrack).ToArray());
                newItems = TimelineHelpers.DuplicateItemsUsingCurrentEditMode(state, TimelineEditor.clipboard.exposedPropertyTable, TimelineEditor.inspectedDirector, copiedItems, time, "Paste Items").ToList();
            }

            TimelineHelpers.FrameItems(state, newItems);
            SelectionManager.RemoveTimelineSelection();
            foreach (var item in newItems)
            {
                SelectionManager.Add(item);
            }
        }

        static TrackAsset FindSuitableParentForSingleTrackPasteWithoutMouse(ItemsPerTrack itemsGroup)
        {
            var groupParent = itemsGroup.targetTrack; //set a main parent in the clipboard
            var selectedTracks = SelectionManager.SelectedTracks();

            if (selectedTracks.Contains(groupParent))
            {
                return groupParent;
            }

            //find a selected track suitable for all items
            var itemsToPaste = itemsGroup.items;
            var compatibleTrack = selectedTracks.FirstOrDefault(t => IsTrackValidForItems(t, itemsToPaste));
            return compatibleTrack != null ? compatibleTrack : groupParent;
        }

        static bool IsTrackValidForItems(TrackAsset track, IEnumerable<ITimelineItem> items)
        {
            if (track == null || track.lockedInHierarchy) return false;
            return items.All(i => i.IsCompatibleWithTrack(track));
        }

        static TrackAsset GetPickedTrack()
        {
            var rowGUI = PickerUtils.pickedElements.OfType<IRowGUI>().FirstOrDefault();
            if (rowGUI != null)
                return rowGUI.asset;

            return null;
        }

        static void PasteTracks(WindowState state)
        {
            var trackData = TimelineEditor.clipboard.GetTracks().ToList();
            if (trackData.Any())
            {
                SelectionManager.RemoveTimelineSelection();
            }

            foreach (var track in trackData)
            {
                var newTrack = track.item.Duplicate(TimelineEditor.clipboard.exposedPropertyTable, TimelineEditor.inspectedDirector, TimelineEditor.inspectedAsset);
                SelectionManager.Add(newTrack);
                foreach (var childTrack in newTrack.GetFlattenedChildTracks())
                {
                    SelectionManager.Add(childTrack);
                }

                if (track.parent != null && track.parent.timelineAsset == state.editSequence.asset)
                {
                    TrackExtensions.ReparentTracks(new List<TrackAsset> { newTrack }, track.parent, track.item);
                }
            }
        }
    }

    [MenuEntry("Duplicate", MenuOrder.TimelineAction.Duplicate)]
    [Shortcut("Main Menu/Edit/Duplicate", EventCommandNames.Duplicate)]
    class DuplicateAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return Execute(state, (item1, item2) => ItemsUtils.TimeGapBetweenItems(item1, item2, state));
        }

        internal bool Execute(WindowState state, Func<ITimelineItem, ITimelineItem, double> gapBetweenItems)
        {
            var selectedItems = SelectionManager.SelectedItems().ToItemsPerTrack().ToList();
            if (selectedItems.Any())
            {
                var requestedTime = CalculateDuplicateTime(selectedItems, gapBetweenItems);
                var duplicatedItems = TimelineHelpers.DuplicateItemsUsingCurrentEditMode(state, TimelineEditor.inspectedDirector, TimelineEditor.inspectedDirector, selectedItems, requestedTime, "Duplicate Items");

                TimelineHelpers.FrameItems(state, duplicatedItems);
                SelectionManager.RemoveTimelineSelection();
                foreach (var item in duplicatedItems)
                    SelectionManager.Add(item);
            }

            var tracks = SelectionManager.SelectedTracks().ToArray();
            if (tracks.Length > 0)
                TrackAction.Invoke<DuplicateTracks>(state, tracks);

            state.Refresh();
            return true;
        }

        static double CalculateDuplicateTime(IEnumerable<ItemsPerTrack> duplicatedItems, Func<ITimelineItem, ITimelineItem, double> gapBetweenItems)
        {
            //Find the end time of the rightmost item
            var itemsOnTracks = duplicatedItems.SelectMany(i => i.targetTrack.GetItems()).ToList();
            var time = itemsOnTracks.Max(i => i.end);

            //From all the duplicated items, select the leftmost items
            var firstDuplicatedItems = duplicatedItems.Select(i => i.leftMostItem);
            var leftMostDuplicatedItems = firstDuplicatedItems.OrderBy(i => i.start).GroupBy(i => i.start).FirstOrDefault();
            if (leftMostDuplicatedItems == null) return 0.0;

            foreach (var leftMostItem in leftMostDuplicatedItems)
            {
                var siblings = leftMostItem.parentTrack.GetItems();
                var rightMostSiblings = siblings.OrderByDescending(i => i.end).GroupBy(i => i.end).FirstOrDefault();
                if (rightMostSiblings == null) continue;

                foreach (var sibling in rightMostSiblings)
                    time = Math.Max(time, sibling.end + gapBetweenItems(leftMostItem, sibling));
            }

            return time;
        }
    }

    [MenuEntry("Delete", MenuOrder.TimelineAction.Delete)]
    [Shortcut("Main Menu/Edit/Delete", EventCommandNames.Delete)]
    [ShortcutPlatformOverride(RuntimePlatform.OSXEditor, KeyCode.Backspace, ShortcutModifiers.Action)]
    [ActiveInMode(TimelineModes.Default)]
    class DeleteAction : TimelineAction
    {
        public override MenuActionDisplayState GetDisplayState(WindowState state)
        {
            return CanDelete(state) ? MenuActionDisplayState.Visible : MenuActionDisplayState.Disabled;
        }

        static bool CanDelete(WindowState state)
        {
            if (state.editSequence.isReadOnly)
                return false;
            // All() returns true when empty
            return SelectionManager.SelectedTracks().All(x => !x.lockedInHierarchy) &&
                SelectionManager.SelectedItems().All(x => x.parentTrack == null || !x.parentTrack.lockedInHierarchy);
        }

        public override bool Execute(WindowState state)
        {
            if (SelectionManager.GetCurrentInlineEditorCurve() != null)
                return false;

            if (!CanDelete(state))
                return false;

            var selectedItems = SelectionManager.SelectedItems();
            DeleteItems(selectedItems);

            var tracks = SelectionManager.SelectedTracks().ToArray();
            if (tracks.Any())
                TrackAction.Invoke<DeleteTracks>(state, tracks);

            state.Refresh();
            return selectedItems.Any() ||  tracks.Length > 0;
        }

        internal static void DeleteItems(IEnumerable<ITimelineItem> items)
        {
            var tracks = items.GroupBy(c => c.parentTrack);

            foreach (var track in tracks)
                TimelineUndo.PushUndo(track.Key, "Delete Items");

            TimelineAnimationUtilities.UnlinkAnimationWindowFromClips(items.OfType<ClipItem>().Select(i => i.clip));

            EditMode.PrepareItemsDelete(ItemsUtils.ToItemsPerTrack(items));
            EditModeUtils.Delete(items);

            SelectionManager.RemoveAllClips();
        }
    }

    [MenuEntry("Match Content", MenuOrder.TimelineAction.MatchContent)]
    [Shortcut(Shortcuts.Timeline.matchContent)]
    class MatchContent : TimelineAction
    {
        public override MenuActionDisplayState GetDisplayState(WindowState state)
        {
            var clips = SelectionManager.SelectedClips().ToArray();

            if (!clips.Any() || SelectionManager.GetCurrentInlineEditorCurve() != null)
                return MenuActionDisplayState.Hidden;

            return clips.Any(TimelineHelpers.HasUsableAssetDuration)
                ? MenuActionDisplayState.Visible
                : MenuActionDisplayState.Disabled;
        }

        public override bool Execute(WindowState state)
        {
            if (SelectionManager.GetCurrentInlineEditorCurve() != null)
                return false;

            var clips = SelectionManager.SelectedClips().ToArray();
            return clips.Length > 0 && ClipModifier.MatchContent(clips);
        }
    }

    [Shortcut(Shortcuts.Timeline.play)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class PlayTimelineAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            var currentState = state.playing;
            state.SetPlaying(!currentState);
            return true;
        }
    }

    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectAllAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            // otherwise select all tracks.
            SelectionManager.Clear();
            state.GetWindow().allTracks.ForEach(x => SelectionManager.Add(x.track));

            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.previousFrame)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class PreviousFrameAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            state.editSequence.frame--;
            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.nextFrame)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class NextFrameAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            state.editSequence.frame++;
            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.frameAll)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class FrameAllAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            var inlineCurveEditor = SelectionManager.GetCurrentInlineEditorCurve();
            if (inlineCurveEditor != null && inlineCurveEditor.inlineCurvesSelected)
            {
                FrameSelectedAction.FrameInlineCurves(inlineCurveEditor, state, false);
                return true;
            }

            if (state.IsEditingASubItem())
                return false;

            var w = state.GetWindow();
            if (w == null || w.treeView == null)
                return false;

            var visibleTracks = w.treeView.visibleTracks.ToList();
            if (state.editSequence.asset != null && state.editSequence.asset.markerTrack != null)
                visibleTracks.Add(state.editSequence.asset.markerTrack);

            if (visibleTracks.Count == 0)
                return false;

            var startTime = float.MaxValue;
            var endTime = float.MinValue;

            foreach (var t in visibleTracks)
            {
                if (t == null)
                    continue;

                double trackStart, trackEnd;
                t.GetItemRange(out trackStart, out trackEnd);
                startTime = Mathf.Min(startTime, (float)trackStart);
                endTime = Mathf.Max(endTime, (float)(trackEnd));
            }

            if (startTime != float.MinValue)
            {
                FrameSelectedAction.FrameRange(startTime, endTime, state);
                return true;
            }

            return false;
        }
    }

    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class FrameSelectedAction : TimelineAction
    {
        public static void FrameRange(float startTime, float endTime, WindowState state)
        {
            if (startTime > endTime)
            {
                return;
            }

            var halfDuration = endTime - Math.Max(0.0f, startTime);

            if (halfDuration > 0.0f)
            {
                state.SetTimeAreaShownRange(Mathf.Max(-10.0f, startTime - (halfDuration * 0.1f)),
                    endTime + (halfDuration * 0.1f));
            }
            else
            {
                // start == end
                // keep the zoom level constant, only pan the time area to center the item
                var currentRange = state.timeAreaShownRange.y - state.timeAreaShownRange.x;
                state.SetTimeAreaShownRange(startTime - currentRange / 2, startTime + currentRange / 2);
            }

            TimelineZoomManipulator.InvalidateWheelZoom();
            state.Evaluate();
        }

        public override bool Execute(WindowState state)
        {
            var inlineCurveEditor = SelectionManager.GetCurrentInlineEditorCurve();
            if (inlineCurveEditor != null && inlineCurveEditor.inlineCurvesSelected)
            {
                FrameInlineCurves(inlineCurveEditor, state, true);
                return true;
            }

            if (state.IsEditingASubItem())
                return false;

            if (SelectionManager.Count() == 0)
                return false;

            var startTime = float.MaxValue;
            var endTime = float.MinValue;

            var clips = SelectionManager.SelectedClipGUI();
            var markers = SelectionManager.SelectedMarkers();
            if (!clips.Any() && !markers.Any())
                return false;

            foreach (var c in clips)
            {
                startTime = Mathf.Min(startTime, (float)c.clip.start);
                endTime = Mathf.Max(endTime, (float)c.clip.end);
                if (c.clipCurveEditor != null)
                {
                    c.clipCurveEditor.FrameClip();
                }
            }

            foreach (var marker in markers)
            {
                startTime = Mathf.Min(startTime, (float)marker.time);
                endTime = Mathf.Max(endTime, (float)marker.time);
            }

            FrameRange(startTime, endTime, state);

            return true;
        }

        public static void FrameInlineCurves(IClipCurveEditorOwner curveEditorOwner, WindowState state, bool selectionOnly)
        {
            var curveEditor = curveEditorOwner.clipCurveEditor.curveEditor;
            var frameBounds = selectionOnly ? curveEditor.GetSelectionBounds() : curveEditor.GetClipBounds();

            var clipGUI = curveEditorOwner as TimelineClipGUI;
            var areaOffset = 0.0f;

            if (clipGUI != null)
            {
                areaOffset = (float)Math.Max(0.0, clipGUI.clip.FromLocalTimeUnbound(0.0));

                var timeScale = (float)clipGUI.clip.timeScale;  // Note: The getter for clip.timeScale is guaranteed to never be zero.

                // Apply scaling
                var newMin = frameBounds.min.x / timeScale;
                var newMax = (frameBounds.max.x - frameBounds.min.x) / timeScale + newMin;

                frameBounds.SetMinMax(
                    new Vector3(newMin, frameBounds.min.y, frameBounds.min.z),
                    new Vector3(newMax, frameBounds.max.y, frameBounds.max.z));
            }

            curveEditor.Frame(frameBounds, true, true);

            var area = curveEditor.shownAreaInsideMargins;
            area.x += areaOffset;

            var curveStart = curveEditorOwner.clipCurveEditor.dataSource.start;
            FrameRange(curveStart + frameBounds.min.x, curveStart + frameBounds.max.x, state);
        }
    }

    [Shortcut(Shortcuts.Timeline.previousKey)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class PrevKeyAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            var keyTraverser = new Utilities.KeyTraverser(state.editSequence.asset, 0.01f / state.referenceSequence.frameRate);
            var time = keyTraverser.GetPrevKey((float)state.editSequence.time, state.dirtyStamp);
            if (time != state.editSequence.time)
            {
                state.editSequence.time = time;
            }

            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.nextKey)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class NextKeyAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            var keyTraverser = new Utilities.KeyTraverser(state.editSequence.asset, 0.01f / state.referenceSequence.frameRate);
            var time = keyTraverser.GetNextKey((float)state.editSequence.time, state.dirtyStamp);
            if (time != state.editSequence.time)
            {
                state.editSequence.time = time;
            }

            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.goToStart)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class GotoStartAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            state.editSequence.time = 0.0f;
            state.EnsurePlayHeadIsVisible();

            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.goToEnd)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class GotoEndAction : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            state.editSequence.time = state.editSequence.duration;
            state.EnsurePlayHeadIsVisible();

            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.zoomIn)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class ZoomIn : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            TimelineZoomManipulator.Instance.DoZoom(1.15f, state);
            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.zoomOut)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class ZoomOut : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            TimelineZoomManipulator.Instance.DoZoom(0.85f, state);
            return true;
        }
    }

    [Shortcut(Shortcuts.Timeline.collapseGroup)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class CollapseGroup : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.CollapseGroup(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.unCollapseGroup)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class UnCollapseGroup : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.UnCollapseGroup(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.selectLeftItem)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectLeftClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            // Switches to track header if no left track exists
            return KeyboardNavigation.SelectLeftItem(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.selectRightItem)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectRightClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectRightItem(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.selectUpItem)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectUpClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectUpItem(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.selectUpTrack)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectUpTrack : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectUpTrack();
        }
    }

    [Shortcut(Shortcuts.Timeline.selectDownItem)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectDownClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectDownItem(state);
        }
    }

    [Shortcut(Shortcuts.Timeline.selectDownTrack)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class SelectDownTrack : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            if (!KeyboardNavigation.ClipAreaActive() && !KeyboardNavigation.TrackHeadActive())
                return KeyboardNavigation.FocusFirstVisibleItem(state);
            else
                return KeyboardNavigation.SelectDownTrack();
        }
    }

    [Shortcut(Shortcuts.Timeline.multiSelectLeft)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class MultiselectLeftClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectLeftItem(state, true);
        }
    }

    [Shortcut(Shortcuts.Timeline.multiSelectRight)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class MultiselectRightClip : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectRightItem(state, true);
        }
    }

    [Shortcut(Shortcuts.Timeline.multiSelectUp)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class MultiselectUpTrack : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectUpTrack(true);
        }
    }

    [Shortcut(Shortcuts.Timeline.multiSelectDown)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class MultiselectDownTrack : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            return KeyboardNavigation.SelectDownTrack(true);
        }
    }

    [Shortcut(Shortcuts.Timeline.toggleClipTrackArea)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class ToggleClipTrackArea : TimelineAction
    {
        public override bool Execute(WindowState state)
        {
            if (KeyboardNavigation.TrackHeadActive())
                return KeyboardNavigation.FocusFirstVisibleItem(state, SelectionManager.SelectedTracks());

            if (!KeyboardNavigation.ClipAreaActive())
                return KeyboardNavigation.FocusFirstVisibleItem(state);

            var item = KeyboardNavigation.GetVisibleSelectedItems().LastOrDefault();
            if (item != null)
                SelectionManager.SelectOnly(item.parentTrack);
            return true;
        }
    }

    [MenuEntry("Mute", MenuOrder.TrackAction.MuteTrack)]
    class ToggleMuteMarkersOnTimeline : MarkerHeaderAction
    {
        public override bool IsChecked(WindowState state)
        {
            return IsMarkerTrackValid(state) && state.editSequence.asset.markerTrack.muted;
        }

        public override bool Execute(WindowState state)
        {
            if (state.showMarkerHeader)
                ToggleMute(state);
            return true;
        }

        static void ToggleMute(WindowState state)
        {
            var timeline = state.editSequence.asset;
            timeline.CreateMarkerTrack();

            TimelineUndo.PushUndo(timeline.markerTrack, "Toggle Mute");
            timeline.markerTrack.muted = !timeline.markerTrack.muted;
        }

        static bool IsMarkerTrackValid(WindowState state)
        {
            var timeline = state.editSequence.asset;
            return timeline != null && timeline.markerTrack != null;
        }
    }

    [MenuEntry("Show Markers", MenuOrder.TrackAction.ShowHideMarkers)]
    [ActiveInMode(TimelineModes.Default | TimelineModes.ReadOnly)]
    class ToggleShowMarkersOnTimeline : MarkerHeaderAction
    {
        public override bool IsChecked(WindowState state)
        {
            return state.showMarkerHeader;
        }

        public override bool Execute(WindowState state)
        {
            ToggleShow(state);
            return true;
        }

        static void ToggleShow(WindowState state)
        {
            state.GetWindow().SetShowMarkerHeader(!state.showMarkerHeader);
        }
    }
}