<commit_before>﻿// Copyright (c) 2007-2017 ppy Pty Ltd <<EMAIL>>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Configuration;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.MathUtils;
using System.Diagnostics;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Caching;
using osu.Framework.Threading;
using osu.Framework.Configuration;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Cursor;
using osu.Game.Screens.Select.Carousel;

namespace osu.Game.Screens.Select
{
    public class BeatmapCarousel : OsuScrollContainer
    {
        /// <summary>
        /// Triggered when the <see cref="BeatmapSets"/> loaded change and are completely loaded.
        /// </summary>
        public Action BeatmapSetsChanged;

        /// <summary>
        /// The currently selected beatmap.
        /// </summary>
        public BeatmapInfo SelectedBeatmap => selectedBeatmap?.Beatmap;

        private CarouselBeatmap selectedBeatmap => selectedBeatmapSet?.Beatmaps.FirstOrDefault(s => s.State == CarouselItemState.Selected);

        /// <summary>
        /// The currently selected beatmap set.
        /// </summary>
        public BeatmapSetInfo SelectedBeatmapSet => selectedBeatmapSet?.BeatmapSet;

        private CarouselBeatmapSet selectedBeatmapSet;

        /// <summary>
        /// Raised when the <see cref="SelectedBeatmap"/> is changed.
        /// </summary>
        public Action<BeatmapInfo> SelectionChanged;

        public override bool HandleInput => AllowSelection;

        /// <summary>
        /// Used to avoid firing null selections before the initial beatmaps have been loaded via <see cref="BeatmapSets"/>.
        /// </summary>
        private bool initialLoadComplete;

        private IEnumerable<CarouselBeatmapSet> beatmapSets => root.Children.OfType<CarouselBeatmapSet>();

        public IEnumerable<BeatmapSetInfo> BeatmapSets
        {
            get { return beatmapSets.Select(g => g.BeatmapSet); }
            set
            {
                CarouselGroup newRoot = new CarouselGroupEagerSelect();

                Task.Run(() =>
                {
                    value.Select(createCarouselSet).Where(g => g != null).ForEach(newRoot.AddChild);
                    newRoot.Filter(activeCriteria);

                    // preload drawables as the ctor overhead is quite high currently.
                    var _ = newRoot.Drawables;
                }).ContinueWith(_ => Schedule(() =>
                {
                    root = newRoot;
                    scrollableContent.Clear(false);
                    itemsCache.Invalidate();
                    scrollPositionCache.Invalidate();

                    Schedule(() =>
                    {
                        BeatmapSetsChanged?.Invoke();
                        initialLoadComplete = true;
                    });
                }));
            }
        }

        private readonly List<float> yPositions = new List<float>();
        private Cached itemsCache = new Cached();
        private Cached scrollPositionCache = new Cached();

        private readonly Container<DrawableCarouselItem> scrollableContent;

        public Bindable<RandomSelectAlgorithm> RandomAlgorithm = new Bindable<RandomSelectAlgorithm>();
        private readonly List<CarouselBeatmapSet> previouslyVisitedRandomSets = new List<CarouselBeatmapSet>();
        private readonly Stack<CarouselBeatmap> randomSelectedBeatmaps = new Stack<CarouselBeatmap>();

        protected List<DrawableCarouselItem> Items = new List<DrawableCarouselItem>();
        private CarouselGroup root = new CarouselGroupEagerSelect();

        public BeatmapCarousel()
        {
            Child = new OsuContextMenuContainer
            {
                RelativeSizeAxes = Axes.X,
                AutoSizeAxes = Axes.Y,
                Child = scrollableContent = new Container<DrawableCarouselItem>
                {
                    RelativeSizeAxes = Axes.X,
                }
            };
        }

        [BackgroundDependencyLoader(permitNulls: true)]
        private void load(OsuConfigManager config)
        {
            config.BindWith(OsuSetting.RandomSelectAlgorithm, RandomAlgorithm);
        }

        public void RemoveBeatmapSet(BeatmapSetInfo beatmapSet)
        {
            Schedule(() =>
            {
                var existingSet = beatmapSets.FirstOrDefault(b => b.BeatmapSet.ID == beatmapSet.ID);

                if (existingSet == null)
                    return;

                root.RemoveChild(existingSet);
                itemsCache.Invalidate();
            });
        }

        public void UpdateBeatmapSet(BeatmapSetInfo beatmapSet)
        {
            Schedule(() =>
            {
                CarouselBeatmapSet existingSet = beatmapSets.FirstOrDefault(b => b.BeatmapSet.ID == beatmapSet.ID);

                bool hadSelection = existingSet?.State?.Value == CarouselItemState.Selected;

                var newSet = createCarouselSet(beatmapSet);

                if (existingSet != null)
                    root.RemoveChild(existingSet);

                if (newSet == null)
                {
                    itemsCache.Invalidate();
                    return;
                }

                root.AddChild(newSet);

                applyActiveCriteria(false, false);

                //check if we can/need to maintain our current selection.
                if (hadSelection)
                    select((CarouselItem)newSet.Beatmaps.FirstOrDefault(b => b.Beatmap.ID == selectedBeatmap?.Beatmap.ID) ?? newSet);

                itemsCache.Invalidate();
                Schedule(() => BeatmapSetsChanged?.Invoke());
            });
        }

        public void SelectBeatmap(BeatmapInfo beatmap)
        {
            if (beatmap?.Hidden != false)
                return;

            foreach (CarouselBeatmapSet group in beatmapSets)
            {
                var item = group.Beatmaps.FirstOrDefault(p => p.Beatmap.Equals(beatmap));
                if (item != null)
                {
                    select(item);
                    return;
                }
            }
        }

        /// <summary>
        /// Increment selection in the carousel in a chosen direction.
        /// </summary>
        /// <param name="direction">The direction to increment. Negative is backwards.</param>
        /// <param name="skipDifficulties">Whether to skip individual difficulties and only increment over full groups.</param>
        public void SelectNext(int direction = 1, bool skipDifficulties = true)
        {
            if (!Items.Any())
                return;

            int originalIndex = Items.IndexOf(selectedBeatmap?.Drawables.First());
            int currentIndex = originalIndex;
<commit_msg>fix for Drawables being empty crashing<commit_after>﻿// Copyright (c) 2007-2017 ppy Pty Ltd <<EMAIL>>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using OpenTK;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Configuration;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.MathUtils;
using System.Diagnostics;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Caching;
using osu.Framework.Threading;
using osu.Framework.Configuration;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Cursor;
using osu.Game.Screens.Select.Carousel;

namespace osu.Game.Screens.Select
{
    public class BeatmapCarousel : OsuScrollContainer
    {
        /// <summary>
        /// Triggered when the <see cref="BeatmapSets"/> loaded change and are completely loaded.
        /// </summary>
        public Action BeatmapSetsChanged;

        /// <summary>
        /// The currently selected beatmap.
        /// </summary>
        public BeatmapInfo SelectedBeatmap => selectedBeatmap?.Beatmap;

        private CarouselBeatmap selectedBeatmap => selectedBeatmapSet?.Beatmaps.FirstOrDefault(s => s.State == CarouselItemState.Selected);

        /// <summary>
        /// The currently selected beatmap set.
        /// </summary>
        public BeatmapSetInfo SelectedBeatmapSet => selectedBeatmapSet?.BeatmapSet;

        private CarouselBeatmapSet selectedBeatmapSet;

        /// <summary>
        /// Raised when the <see cref="SelectedBeatmap"/> is changed.
        /// </summary>
        public Action<BeatmapInfo> SelectionChanged;

        public override bool HandleInput => AllowSelection;

        /// <summary>
        /// Used to avoid firing null selections before the initial beatmaps have been loaded via <see cref="BeatmapSets"/>.
        /// </summary>
        private bool initialLoadComplete;

        private IEnumerable<CarouselBeatmapSet> beatmapSets => root.Children.OfType<CarouselBeatmapSet>();

        public IEnumerable<BeatmapSetInfo> BeatmapSets
        {
            get { return beatmapSets.Select(g => g.BeatmapSet); }
            set
            {
                CarouselGroup newRoot = new CarouselGroupEagerSelect();

                Task.Run(() =>
                {
                    value.Select(createCarouselSet).Where(g => g != null).ForEach(newRoot.AddChild);
                    newRoot.Filter(activeCriteria);

                    // preload drawables as the ctor overhead is quite high currently.
                    var _ = newRoot.Drawables;
                }).ContinueWith(_ => Schedule(() =>
                {
                    root = newRoot;
                    scrollableContent.Clear(false);
                    itemsCache.Invalidate();
                    scrollPositionCache.Invalidate();

                    Schedule(() =>
                    {
                        BeatmapSetsChanged?.Invoke();
                        initialLoadComplete = true;
                    });
                }));
            }
        }

        private readonly List<float> yPositions = new List<float>();
        private Cached itemsCache = new Cached();
        private Cached scrollPositionCache = new Cached();

        private readonly Container<DrawableCarouselItem> scrollableContent;

        public Bindable<RandomSelectAlgorithm> RandomAlgorithm = new Bindable<RandomSelectAlgorithm>();
        private readonly List<CarouselBeatmapSet> previouslyVisitedRandomSets = new List<CarouselBeatmapSet>();
        private readonly Stack<CarouselBeatmap> randomSelectedBeatmaps = new Stack<CarouselBeatmap>();

        protected List<DrawableCarouselItem> Items = new List<DrawableCarouselItem>();
        private CarouselGroup root = new CarouselGroupEagerSelect();

        public BeatmapCarousel()
        {
            Child = new OsuContextMenuContainer
            {
                RelativeSizeAxes = Axes.X,
                AutoSizeAxes = Axes.Y,
                Child = scrollableContent = new Container<DrawableCarouselItem>
                {
                    RelativeSizeAxes = Axes.X,
                }
            };
        }

        [BackgroundDependencyLoader(permitNulls: true)]
        private void load(OsuConfigManager config)
        {
            config.BindWith(OsuSetting.RandomSelectAlgorithm, RandomAlgorithm);
        }

        public void RemoveBeatmapSet(BeatmapSetInfo beatmapSet)
        {
            Schedule(() =>
            {
                var existingSet = beatmapSets.FirstOrDefault(b => b.BeatmapSet.ID == beatmapSet.ID);

                if (existingSet == null)
                    return;

                root.RemoveChild(existingSet);
                itemsCache.Invalidate();
            });
        }

        public void UpdateBeatmapSet(BeatmapSetInfo beatmapSet)
        {
            Schedule(() =>
            {
                CarouselBeatmapSet existingSet = beatmapSets.FirstOrDefault(b => b.BeatmapSet.ID == beatmapSet.ID);

                bool hadSelection = existingSet?.State?.Value == CarouselItemState.Selected;

                var newSet = createCarouselSet(beatmapSet);

                if (existingSet != null)
                    root.RemoveChild(existingSet);

                if (newSet == null)
                {
                    itemsCache.Invalidate();
                    return;
                }

                root.AddChild(newSet);

                applyActiveCriteria(false, false);

                //check if we can/need to maintain our current selection.
                if (hadSelection)
                    select((CarouselItem)newSet.Beatmaps.FirstOrDefault(b => b.Beatmap.ID == selectedBeatmap?.Beatmap.ID) ?? newSet);

                itemsCache.Invalidate();
                Schedule(() => BeatmapSetsChanged?.Invoke());
            });
        }

        public void SelectBeatmap(BeatmapInfo beatmap)
        {
            if (beatmap?.Hidden != false)
                return;

            foreach (CarouselBeatmapSet group in beatmapSets)
            {
                var item = group.Beatmaps.FirstOrDefault(p => p.Beatmap.Equals(beatmap));
                if (item != null)
                {
                    select(item);
                    return;
                }
            }
        }

        /// <summary>
        /// Increment selection in the carousel in a chosen direction.
        /// </summary>
        /// <param name="direction">The direction to increment. Negative is backwards.</param>
        /// <param name="skipDifficulties">Whether to skip individual difficulties and only increment over full groups.</param>
        public void SelectNext(int direction = 1, bool skipDifficulties = true)
        {
            if (!Items.Any())
                return;

            var d = selectedBeatmap?.Drawables.FirstOrDefault();
            if (d == null)
                return;

            int originalIndex = Items.IndexOf(d);
            int currentIndex = originalIndex;

{'fraction_non_alphanumeric': 0.09354726194628532, 'fraction_numerical': 0.0012556679455877223, 'mean_word_length': 1.8810289389067525, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 115, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '921716', 'n_tokens_mistral': 3739, 'n_tokens_neox': 3437, 'n_words': 798}