Example #1
0
 private void load(GameHost host, AudioManager audio)
 {
     Dependencies.Cache(rulesets = new RealmRulesetStore(Realm));
     Dependencies.Cache(beatmaps = new BeatmapManager(LocalStorage, Realm, rulesets, API, audio, Resources, host, Beatmap.Default));
     Dependencies.Cache(Realm);
 }
Example #2
0
        private void load(BindableBeatmap beatmap, BeatmapManager beatmaps, OsuColour colours, LocalisationEngine localisation)
        {
            this.beatmap.BindTo(beatmap);
            this.beatmaps     = beatmaps;
            this.localisation = localisation;

            Children = new Drawable[]
            {
                dragContainer = new DragContainer
                {
                    Anchor           = Anchor.Centre,
                    Origin           = Anchor.Centre,
                    RelativeSizeAxes = Axes.X,
                    AutoSizeAxes     = Axes.Y,
                    Children         = new Drawable[]
                    {
                        playlist = new PlaylistOverlay
                        {
                            RelativeSizeAxes = Axes.X,
                            Y            = player_height + 10,
                            OrderChanged = playlistOrderChanged
                        },
                        playerContainer = new Container
                        {
                            RelativeSizeAxes = Axes.X,
                            Height           = player_height,
                            Masking          = true,
                            CornerRadius     = 5,
                            EdgeEffect       = new EdgeEffectParameters
                            {
                                Type   = EdgeEffectType.Shadow,
                                Colour = Color4.Black.Opacity(40),
                                Radius = 5,
                            },
                            Children = new[]
                            {
                                background = new Background(),
                                title      = new OsuSpriteText
                                {
                                    Origin   = Anchor.BottomCentre,
                                    Anchor   = Anchor.TopCentre,
                                    Position = new Vector2(0, 40),
                                    TextSize = 25,
                                    Colour   = Color4.White,
                                    Text     = @"Nothing to play",
                                    Font     = @"Exo2.0-MediumItalic"
                                },
                                artist = new OsuSpriteText
                                {
                                    Origin   = Anchor.TopCentre,
                                    Anchor   = Anchor.TopCentre,
                                    Position = new Vector2(0, 45),
                                    TextSize = 15,
                                    Colour   = Color4.White,
                                    Text     = @"Nothing to play",
                                    Font     = @"Exo2.0-BoldItalic"
                                },
                                new Container
                                {
                                    Padding = new MarginPadding {
                                        Bottom = progress_height
                                    },
                                    Height           = bottom_black_area_height,
                                    RelativeSizeAxes = Axes.X,
                                    Origin           = Anchor.BottomCentre,
                                    Anchor           = Anchor.BottomCentre,
                                    Children         = new Drawable[]
                                    {
                                        new FillFlowContainer <IconButton>
                                        {
                                            AutoSizeAxes = Axes.Both,
                                            Direction    = FillDirection.Horizontal,
                                            Spacing      = new Vector2(5),
                                            Origin       = Anchor.Centre,
                                            Anchor       = Anchor.Centre,
                                            Children     = new[]
                                            {
                                                prevButton = new MusicIconButton
                                                {
                                                    Anchor = Anchor.Centre,
                                                    Origin = Anchor.Centre,
                                                    Action = prev,
                                                    Icon   = FontAwesome.fa_step_backward,
                                                },
                                                playButton = new MusicIconButton
                                                {
                                                    Anchor    = Anchor.Centre,
                                                    Origin    = Anchor.Centre,
                                                    Scale     = new Vector2(1.4f),
                                                    IconScale = new Vector2(1.4f),
                                                    Action    = play,
                                                    Icon      = FontAwesome.fa_play_circle_o,
                                                },
                                                nextButton = new MusicIconButton
                                                {
                                                    Anchor = Anchor.Centre,
                                                    Origin = Anchor.Centre,
                                                    Action = () => next(),
                                                    Icon   = FontAwesome.fa_step_forward,
                                                },
                                            }
                                        },
                                        playlistButton = new MusicIconButton
                                        {
                                            Origin   = Anchor.Centre,
                                            Anchor   = Anchor.CentreRight,
                                            Position = new Vector2(-bottom_black_area_height / 2, 0),
                                            Icon     = FontAwesome.fa_bars,
                                            Action   = () => playlist.ToggleVisibility(),
                                        },
                                    }
                                },
                                progressBar = new ProgressBar
                                {
                                    Origin     = Anchor.BottomCentre,
                                    Anchor     = Anchor.BottomCentre,
                                    Height     = progress_height,
                                    FillColour = colours.Yellow,
                                    OnSeek     = attemptSeek
                                }
                            },
                        },
                    }
                }
            };

            beatmapSets           = beatmaps.GetAllUsableBeatmapSets();
            beatmaps.ItemAdded   += handleBeatmapAdded;
            beatmaps.ItemRemoved += handleBeatmapRemoved;

            playlist.StateChanged += s => playlistButton.FadeColour(s == Visibility.Visible ? colours.Yellow : Color4.White, 200, Easing.OutQuint);
        }
Example #3
0
        private void load(BeatmapManager manager, SongSelect songSelect)
        {
            if (songSelect != null)
            {
                startRequested = b => songSelect.FinaliseSelection(b);
                if (songSelect.AllowEditing)
                {
                    editRequested = songSelect.Edit;
                }
            }

            if (manager != null)
            {
                hideRequested = manager.Hide;
            }

            Children = new Drawable[]
            {
                background = new Box
                {
                    RelativeSizeAxes = Axes.Both,
                },
                triangles = new Triangles
                {
                    TriangleScale    = 2,
                    RelativeSizeAxes = Axes.Both,
                    ColourLight      = Color4Extensions.FromHex(@"3a7285"),
                    ColourDark       = Color4Extensions.FromHex(@"123744")
                },
                new FillFlowContainer
                {
                    Padding      = new MarginPadding(5),
                    Direction    = FillDirection.Horizontal,
                    AutoSizeAxes = Axes.Both,
                    Anchor       = Anchor.CentreLeft,
                    Origin       = Anchor.CentreLeft,
                    Children     = new Drawable[]
                    {
                        new DifficultyIcon(beatmap, shouldShowTooltip: false)
                        {
                            Scale = new Vector2(1.8f),
                        },
                        new FillFlowContainer
                        {
                            Padding = new MarginPadding {
                                Left = 5
                            },
                            Direction    = FillDirection.Vertical,
                            AutoSizeAxes = Axes.Both,
                            Children     = new Drawable[]
                            {
                                new FillFlowContainer
                                {
                                    Direction    = FillDirection.Horizontal,
                                    Spacing      = new Vector2(4, 0),
                                    AutoSizeAxes = Axes.Both,
                                    Children     = new[]
                                    {
                                        new OsuSpriteText
                                        {
                                            Text   = beatmap.Version,
                                            Font   = OsuFont.GetFont(size: 20),
                                            Anchor = Anchor.BottomLeft,
                                            Origin = Anchor.BottomLeft
                                        },
                                        new OsuSpriteText
                                        {
                                            Text   = "mapped by",
                                            Anchor = Anchor.BottomLeft,
                                            Origin = Anchor.BottomLeft
                                        },
                                        new OsuSpriteText
                                        {
                                            Text   = $"{(beatmap.Metadata ?? beatmap.BeatmapSet.Metadata).Author.Username}",
                                            Font   = OsuFont.GetFont(italics: true),
                                            Anchor = Anchor.BottomLeft,
                                            Origin = Anchor.BottomLeft
                                        },
                                    }
                                },
                                new FillFlowContainer
                                {
                                    Direction    = FillDirection.Horizontal,
                                    Spacing      = new Vector2(4, 0),
                                    AutoSizeAxes = Axes.Both,
                                    Children     = new Drawable[]
                                    {
                                        new TopLocalRank(beatmap)
                                        {
                                            Scale = new Vector2(0.8f),
                                            Size  = new Vector2(40, 20)
                                        },
                                        starCounter = new StarCounter
                                        {
                                            Current = (float)beatmap.StarDifficulty,
                                            Scale   = new Vector2(0.8f),
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };
        }
Example #4
0
 private void load(GameHost host, AudioManager audio)
 {
     Dependencies.Cache(rulesets = new RulesetStore(ContextFactory));
     Dependencies.Cache(beatmaps = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, audio, Resources, host, Beatmap.Default));
 }
Example #5
0
        public override void Initialize()
        {
            if (Player.currentScore == null && InputManager.ReplayScore == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            spriteManagerWideBelow = new SpriteManager(true);
            InitializeLocalScore();

            if (score == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            if (BeatmapManager.Current == null || (!string.IsNullOrEmpty(score.FileChecksum) && BeatmapManager.Current.BeatmapChecksum != score.FileChecksum))
            {
                Beatmap lookup = BeatmapManager.GetBeatmapByChecksum(score.FileChecksum);
                if (lookup != null)
                {
                    BeatmapManager.Current = lookup;
                }
            }

            if (BeatmapManager.Current == null)
            {
                GameBase.ChangeModeInstant(OsuModes.Menu, true);
                return;
            }

            scrollableArea             = new pScrollableArea(new Rectangle(0, 0, GameBase.WindowManager.WidthScaled, GameBase.WindowManager.HeightScaled), new Vector2(GameBase.WindowManager.WidthScaled, GameBase.WindowManager.HeightScaled * (rankingDialog != null ? 1.875f : 1) - 60), true, 60);
            spriteManagerWideScrolling = scrollableArea.ContentSpriteManager;
            //if (rankingDialog != null) rankingDialog.spriteManager = spriteManagerWide;

            spriteManagerWideAbove = new SpriteManager(true);

            BackButton back = new BackButton(delegate { Exit(); });

            spriteManagerWideAbove.Add(back.SpriteCollection);

            bool Spectating = InputManager.ReplayStreaming;

            lock (StreamingManager.LockReplayScore)
            {
                InputManager.ReplayMode      = false;
                InputManager.ReplayStreaming = false;
                InputManager.ReplayStartTime = 0;
            }

            startTime = GameBase.Time + 300;

            KeyboardHandler.OnKeyPressed += GameBase_OnKeyPressed;
            InputManager.Bind(InputEventType.OnClick, onClick);

            backgroundOverlay =
                new pSprite(TextureManager.Load(@"ranking-background-overlay", SkinSource.Osu), Fields.TopRight,
                            Origins.Centre,
                            Clocks.Game, new Vector2(180, SkinManager.UseNewLayout ? 200 : 170), 0.05f, true, Color.White);
            backgroundOverlay.Additive = true;
            backgroundOverlay.Transformations.Add(new Transformation(TransformationType.Rotation, 0, (float)(2 * Math.PI), GameBase.Time, GameBase.Time + 20000));
            backgroundOverlay.Transformations[0].Loop = true;
            spriteManagerWideBelow.Add(backgroundOverlay);

            pSprite p =
                new pSprite(TextureManager.Load(@"ranking-title"), Fields.TopRight, Origins.TopRight,
                            Clocks.Game, new Vector2(20, 0), 0.991F, true, Color.White);

            p.ViewOffsetImmune = SkinManager.UseNewLayout;
            spriteManagerWideScrolling.Add(p);

            InitializeRankingPanel();

            stringTotalScore = String.Format(@"{0:00000000}", score.TotalScore);

            pSprite detailsBack =
                new pSprite(GameBase.WhitePixel, Fields.TopLeft,
                            Origins.TopLeft,
                            Clocks.Game,
                            new Vector2(0, 0), 0.99F, true, Color.Black);

            detailsBack.Alpha            = 0.8f;
            detailsBack.VectorScale      = new Vector2(GameBase.WindowManager.WidthScaled * 1.6f, 60 * 1.6f);
            detailsBack.ViewOffsetImmune = true;
            spriteManagerWideScrolling.Add(detailsBack);

            InitializeSpecifics();

            LoadScore(score);

            base.Initialize();

            if (!ReplayMode)
            {
                PopupRecord();
            }

            if (ReplayMode && !Spectating)
            {
                Progress(false);
            }
            else if (score.SectionResults.FindAll(t => t).Count > score.SectionResults.FindAll(t => !t).Count)
            {
                ApplauseChannel = AudioEngine.PlaySample(@"applause", 100, SkinSource.All);
            }
        }
Example #6
0
        private void load()
        {
            try
            {
                using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location))
                    VersionHash = str.ComputeMD5Hash();
            }
            catch
            {
                // special case for android builds, which can't read DLLs from a packed apk.
                // should eventually be handled in a better way.
                VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash();
            }

            Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));

            dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage));

            dependencies.CacheAs(Storage);

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.Cache(LocalConfig);

            AddFont(Resources, @"Fonts/osuFont");

            AddFont(Resources, @"Fonts/Torus-Regular");
            AddFont(Resources, @"Fonts/Torus-Light");
            AddFont(Resources, @"Fonts/Torus-SemiBold");
            AddFont(Resources, @"Fonts/Torus-Bold");

            AddFont(Resources, @"Fonts/Noto-Basic");
            AddFont(Resources, @"Fonts/Noto-Hangul");
            AddFont(Resources, @"Fonts/Noto-CJK-Basic");
            AddFont(Resources, @"Fonts/Noto-CJK-Compatibility");
            AddFont(Resources, @"Fonts/Noto-Thai");

            AddFont(Resources, @"Fonts/Venera-Light");
            AddFont(Resources, @"Fonts/Venera-Bold");
            AddFont(Resources, @"Fonts/Venera-Black");

            Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY;

            runMigrations();

            dependencies.Cache(SkinManager = new SkinManager(Storage, contextFactory, Host, Audio, new NamespacedResourceStore <byte[]>(Resources, "Skins/Legacy")));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            // needs to be done here rather than inside SkinManager to ensure thread safety of CurrentSkinInfo.
            SkinManager.ItemRemoved.BindValueChanged(weakRemovedInfo =>
            {
                if (weakRemovedInfo.NewValue.TryGetTarget(out var removedInfo))
                {
                    Schedule(() =>
                    {
                        // check the removed skin is not the current user choice. if it is, switch back to default.
                        if (removedInfo.ID == SkinManager.CurrentSkinInfo.Value.ID)
                        {
                            SkinManager.CurrentSkinInfo.Value = SkinInfo.Default;
                        }
                    });
                }
            });

            dependencies.CacheAs(API ??= new APIAccess(LocalConfig));

            dependencies.CacheAs(spectatorStreaming = new SpectatorStreamingClient());

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            dependencies.Cache(RulesetStore = new RulesetStore(contextFactory, Storage));
            dependencies.Cache(FileStore    = new FileStore(contextFactory, Storage));

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Host, () => DifficultyCache, LocalConfig));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap, true));

            // this should likely be moved to ArchiveModelManager when another case appers where it is necessary
            // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
            // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
            List <ScoreInfo> getBeatmapScores(BeatmapSetInfo set)
            {
                var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList();

                return(ScoreManager.QueryScores(s => beatmapIds.Contains(s.Beatmap.ID)).ToList());
            }

            BeatmapManager.ItemRemoved.BindValueChanged(i =>
            {
                if (i.NewValue.TryGetTarget(out var item))
                {
                    ScoreManager.Delete(getBeatmapScores(item), true);
                }
            });

            BeatmapManager.ItemUpdated.BindValueChanged(i =>
            {
                if (i.NewValue.TryGetTarget(out var item))
                {
                    ScoreManager.Undelete(getBeatmapScores(item), true);
                }
            });

            dependencies.Cache(DifficultyCache = new BeatmapDifficultyCache());
            AddInternal(DifficultyCache);

            dependencies.Cache(UserCache = new UserLookupCache());
            AddInternal(UserCache);

            var scorePerformanceManager = new ScorePerformanceCache();

            dependencies.Cache(scorePerformanceManager);
            AddInternal(scorePerformanceManager);

            dependencies.Cache(KeyBindingStore    = new KeyBindingStore(contextFactory, RulesetStore));
            dependencies.Cache(SettingsStore      = new SettingsStore(contextFactory));
            dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore));
            dependencies.Cache(new SessionStatics());
            dependencies.Cache(new OsuColour());

            RegisterImportHandler(BeatmapManager);
            RegisterImportHandler(ScoreManager);
            RegisterImportHandler(SkinManager);

            // tracks play so loud our samples can't keep up.
            // this adds a global reduction of track volume for the time being.
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(Beatmap);
            dependencies.CacheAs(Beatmap);

            FileStore.Cleanup();

            // add api components to hierarchy.
            if (API is APIAccess apiAccess)
            {
                AddInternal(apiAccess);
            }
            AddInternal(spectatorStreaming);

            AddInternal(RulesetConfigCache);

            MenuCursorContainer = new MenuCursorContainer {
                RelativeSizeAxes = Axes.Both
            };

            GlobalActionContainer globalBindings;

            MenuCursorContainer.Child = globalBindings = new GlobalActionContainer(this)
            {
                RelativeSizeAxes = Axes.Both,
                Child            = content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                {
                    RelativeSizeAxes = Axes.Both
                }
            };

            base.Content.Add(CreateScalingContainer().WithChild(MenuCursorContainer));

            KeyBindingStore.Register(globalBindings);
            dependencies.Cache(globalBindings);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager());
            Add(previewTrackManager);

            AddInternal(MusicController = new MusicController());
            dependencies.CacheAs(MusicController);

            Ruleset.BindValueChanged(onRulesetChanged);
        }
 private void load(BeatmapManager beatmaps)
 {
     this.beatmaps = beatmaps;
 }
Example #8
0
        private void load(IAPIProvider api, BeatmapManager beatmaps)
        {
            FillFlowContainer textSprites;

            AddRangeInternal(new Drawable[]
            {
                shakeContainer = new ShakeContainer
                {
                    Depth            = -1,
                    RelativeSizeAxes = Axes.Both,
                    Masking          = true,
                    CornerRadius     = 5,
                    Children         = new Drawable[]
                    {
                        button = new HeaderButton {
                            RelativeSizeAxes = Axes.Both
                        },
                        new Container
                        {
                            // cannot nest inside here due to the structure of button (putting things in its own content).
                            // requires framework fix.
                            Padding = new MarginPadding {
                                Horizontal = 10
                            },
                            RelativeSizeAxes = Axes.Both,
                            Children         = new Drawable[]
                            {
                                textSprites = new FillFlowContainer
                                {
                                    Depth            = -1,
                                    Anchor           = Anchor.CentreLeft,
                                    Origin           = Anchor.CentreLeft,
                                    AutoSizeAxes     = Axes.Both,
                                    AutoSizeDuration = 500,
                                    AutoSizeEasing   = Easing.OutQuint,
                                    Direction        = FillDirection.Vertical,
                                },
                                new SpriteIcon
                                {
                                    Depth  = -1,
                                    Anchor = Anchor.CentreRight,
                                    Origin = Anchor.CentreRight,
                                    Icon   = FontAwesome.fa_download,
                                    Size   = new Vector2(16),
                                    Margin = new MarginPadding {
                                        Right = 5
                                    },
                                },
                            }
                        },
                        new DownloadProgressBar(BeatmapSet.Value)
                        {
                            Depth  = -2,
                            Anchor = Anchor.BottomLeft,
                            Origin = Anchor.BottomLeft,
                        },
                    },
                },
            });

            button.Action = () =>
            {
                if (State.Value != DownloadState.NotDownloaded)
                {
                    shakeContainer.Shake();
                    return;
                }

                beatmaps.Download(BeatmapSet.Value, noVideo);
            };

            localUser.BindTo(api.LocalUser);
            localUser.BindValueChanged(userChanged, true);
            button.Enabled.BindValueChanged(enabledChanged, true);

            State.BindValueChanged(state =>
            {
                switch (state.NewValue)
                {
                case DownloadState.Downloading:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Downloading...",
                            Font = OsuFont.GetFont(size: 13, weight: FontWeight.Bold)
                        },
                    };
                    break;

                case DownloadState.Downloaded:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Importing...",
                            Font = OsuFont.GetFont(size: 13, weight: FontWeight.Bold)
                        },
                    };
                    break;

                case DownloadState.LocallyAvailable:
                    this.FadeOut(200);
                    break;

                case DownloadState.NotDownloaded:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Download",
                            Font = OsuFont.GetFont(size: 13, weight: FontWeight.Bold)
                        },
                        new OsuSpriteText
                        {
                            Text = BeatmapSet.Value.OnlineInfo.HasVideo && noVideo ? "without Video" : string.Empty,
                            Font = OsuFont.GetFont(size: 11, weight: FontWeight.Bold)
                        },
                    };
                    this.FadeIn(200);
                    break;
                }
            }, true);
        }
Example #9
0
        private void load(BeatmapManager manager, OsuConfigManager config)
        {
            this.manager = manager;

            randomType = config.GetBindable <SelectionRandomType>(OsuSetting.SelectionRandomType);
        }
Example #10
0
        private void load(ReadableKeyCombinationProvider keyCombinationProvider)
        {
            try
            {
                using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location))
                    VersionHash = str.ComputeMD5Hash();
            }
            catch
            {
                // special case for android builds, which can't read DLLs from a packed apk.
                // should eventually be handled in a better way.
                VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash();
            }

            Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));

            if (Storage.Exists(DatabaseContextFactory.DATABASE_NAME))
            {
                dependencies.Cache(EFContextFactory = new DatabaseContextFactory(Storage));
            }

            dependencies.Cache(realm = new RealmAccess(Storage, "client", EFContextFactory));

            dependencies.Cache(RulesetStore = new RulesetStore(realm, Storage));
            dependencies.CacheAs <IRulesetStore>(RulesetStore);

            // Backup is taken here rather than in EFToRealmMigrator to avoid recycling realm contexts
            // after initial usages below. It can be moved once a direction is established for handling re-subscription.
            // See https://github.com/ppy/osu/pull/16547 for more discussion.
            if (EFContextFactory != null)
            {
                const string backup_folder = "backups";

                string migration = $"before_final_migration_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";

                EFContextFactory.CreateBackup(Path.Combine(backup_folder, $"client.{migration}.db"));
                realm.CreateBackup(Path.Combine(backup_folder, $"client.{migration}.realm"));

                using (var source = Storage.GetStream("collection.db"))
                {
                    if (source != null)
                    {
                        using (var destination = Storage.GetStream(Path.Combine(backup_folder, $"collection.{migration}.db"), FileAccess.Write, FileMode.CreateNew))
                            source.CopyTo(destination);
                    }
                }
            }

            dependencies.CacheAs(Storage);

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.CacheAs(LocalConfig);

            InitialiseFonts();

            Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY;

            dependencies.Cache(SkinManager = new SkinManager(Storage, realm, Host, Resources, Audio, Scheduler));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            EndpointConfiguration endpoints = UseDevelopmentServer ? (EndpointConfiguration) new DevelopmentEndpointConfiguration() : new ProductionEndpointConfiguration();

            MessageFormatter.WebsiteRootUrl = endpoints.WebsiteRootUrl;

            dependencies.CacheAs(API ??= new APIAccess(LocalConfig, endpoints, VersionHash));

            dependencies.CacheAs(spectatorClient   = new OnlineSpectatorClient(endpoints));
            dependencies.CacheAs(multiplayerClient = new OnlineMultiplayerClient(endpoints));

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, realm, Scheduler, () => difficultyCache, LocalConfig));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, realm, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true));

            dependencies.Cache(BeatmapDownloader = new BeatmapModelDownloader(BeatmapManager, API));
            dependencies.Cache(ScoreDownloader   = new ScoreModelDownloader(ScoreManager, API));

            dependencies.Cache(difficultyCache = new BeatmapDifficultyCache());
            AddInternal(difficultyCache);

            dependencies.Cache(userCache = new UserLookupCache());
            AddInternal(userCache);

            dependencies.Cache(beatmapCache = new BeatmapLookupCache());
            AddInternal(beatmapCache);

            var scorePerformanceManager = new ScorePerformanceCache();

            dependencies.Cache(scorePerformanceManager);
            AddInternal(scorePerformanceManager);

            dependencies.CacheAs <IRulesetConfigCache>(rulesetConfigCache = new RulesetConfigCache(realm, RulesetStore));

            var powerStatus = CreateBatteryInfo();

            if (powerStatus != null)
            {
                dependencies.CacheAs(powerStatus);
            }

            dependencies.Cache(SessionStatics = new SessionStatics());
            dependencies.Cache(new OsuColour());

            RegisterImportHandler(BeatmapManager);
            RegisterImportHandler(ScoreManager);
            RegisterImportHandler(SkinManager);

            // drop track volume game-wide to leave some head-room for UI effects / samples.
            // this means that for the time being, gameplay sample playback is louder relative to the audio track, compared to stable.
            // we may want to revisit this if users notice or complain about the difference (consider this a bit of a trial).
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, globalTrackVolumeAdjust);

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(Beatmap);
            dependencies.CacheAs(Beatmap);

            // add api components to hierarchy.
            if (API is APIAccess apiAccess)
            {
                AddInternal(apiAccess);
            }
            AddInternal(spectatorClient);
            AddInternal(multiplayerClient);

            AddInternal(rulesetConfigCache);

            GlobalActionContainer globalBindings;

            base.Content.Add(new SafeAreaContainer
            {
                SafeAreaOverrideEdges = SafeAreaOverrideEdges,
                RelativeSizeAxes      = Axes.Both,
                Child = CreateScalingContainer().WithChildren(new Drawable[]
                {
                    (MenuCursorContainer = new MenuCursorContainer
                    {
                        RelativeSizeAxes = Axes.Both
                    }).WithChild(content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                    {
                        RelativeSizeAxes = Axes.Both
                    }),
                    // to avoid positional input being blocked by children, ensure the GlobalActionContainer is above everything.
                    globalBindings = new GlobalActionContainer(this)
                })
            });

            KeyBindingStore = new RealmKeyBindingStore(realm, keyCombinationProvider);
            KeyBindingStore.Register(globalBindings, RulesetStore.AvailableRulesets);

            dependencies.Cache(globalBindings);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager(BeatmapManager.BeatmapTrackStore));
            Add(previewTrackManager);

            AddInternal(MusicController = new MusicController());
            dependencies.CacheAs(MusicController);

            Ruleset.BindValueChanged(onRulesetChanged);
            Beatmap.BindValueChanged(onBeatmapChanged);
        }
Example #11
0
        private void load(BeatmapManager beatmaps, ScoreManager scores, SkinManager skins, [CanBeNull] CollectionManager collectionManager, [CanBeNull] StableImportManager stableImportManager, DialogOverlay dialogOverlay)
        {
            if (stableImportManager?.SupportsImportFromStable == true)
            {
                Add(importBeatmapsButton = new SettingsButton
                {
                    Text   = MaintenanceSettingsStrings.ImportBeatmapsFromStable,
                    Action = () =>
                    {
                        importBeatmapsButton.Enabled.Value = false;
                        stableImportManager.ImportFromStableAsync(StableContent.Beatmaps).ContinueWith(t => Schedule(() => importBeatmapsButton.Enabled.Value = true));
                    }
                });
            }

            Add(deleteBeatmapsButton = new DangerousSettingsButton
            {
                Text   = MaintenanceSettingsStrings.DeleteAllBeatmaps,
                Action = () =>
                {
                    dialogOverlay?.Push(new DeleteAllBeatmapsDialog(() =>
                    {
                        deleteBeatmapsButton.Enabled.Value = false;
                        Task.Run(() => beatmaps.Delete(beatmaps.GetAllUsableBeatmapSets())).ContinueWith(t => Schedule(() => deleteBeatmapsButton.Enabled.Value = true));
                    }));
                }
            });

            if (stableImportManager?.SupportsImportFromStable == true)
            {
                Add(importScoresButton = new SettingsButton
                {
                    Text   = MaintenanceSettingsStrings.ImportScoresFromStable,
                    Action = () =>
                    {
                        importScoresButton.Enabled.Value = false;
                        stableImportManager.ImportFromStableAsync(StableContent.Scores).ContinueWith(t => Schedule(() => importScoresButton.Enabled.Value = true));
                    }
                });
            }

            Add(deleteScoresButton = new DangerousSettingsButton
            {
                Text   = MaintenanceSettingsStrings.DeleteAllScores,
                Action = () =>
                {
                    dialogOverlay?.Push(new DeleteAllBeatmapsDialog(() =>
                    {
                        deleteScoresButton.Enabled.Value = false;
                        Task.Run(() => scores.Delete(scores.GetAllUsableScores())).ContinueWith(t => Schedule(() => deleteScoresButton.Enabled.Value = true));
                    }));
                }
            });

            if (stableImportManager?.SupportsImportFromStable == true)
            {
                Add(importSkinsButton = new SettingsButton
                {
                    Text   = MaintenanceSettingsStrings.ImportSkinsFromStable,
                    Action = () =>
                    {
                        importSkinsButton.Enabled.Value = false;
                        stableImportManager.ImportFromStableAsync(StableContent.Skins).ContinueWith(t => Schedule(() => importSkinsButton.Enabled.Value = true));
                    }
                });
            }

            Add(deleteSkinsButton = new DangerousSettingsButton
            {
                Text   = MaintenanceSettingsStrings.DeleteAllSkins,
                Action = () =>
                {
                    dialogOverlay?.Push(new DeleteAllBeatmapsDialog(() =>
                    {
                        deleteSkinsButton.Enabled.Value = false;
                        Task.Run(() => skins.Delete(skins.GetAllUserSkins())).ContinueWith(t => Schedule(() => deleteSkinsButton.Enabled.Value = true));
                    }));
                }
            });

            if (collectionManager != null)
            {
                if (stableImportManager?.SupportsImportFromStable == true)
                {
                    Add(importCollectionsButton = new SettingsButton
                    {
                        Text   = MaintenanceSettingsStrings.ImportCollectionsFromStable,
                        Action = () =>
                        {
                            importCollectionsButton.Enabled.Value = false;
                            stableImportManager.ImportFromStableAsync(StableContent.Collections).ContinueWith(t => Schedule(() => importCollectionsButton.Enabled.Value = true));
                        }
                    });
                }

                Add(new DangerousSettingsButton
                {
                    Text   = MaintenanceSettingsStrings.DeleteAllCollections,
                    Action = () =>
                    {
                        dialogOverlay?.Push(new DeleteAllBeatmapsDialog(collectionManager.DeleteAll));
                    }
                });
            }

            AddRange(new Drawable[]
            {
                restoreButton = new SettingsButton
                {
                    Text   = MaintenanceSettingsStrings.RestoreAllHiddenDifficulties,
                    Action = () =>
                    {
                        restoreButton.Enabled.Value = false;
                        Task.Run(() =>
                        {
                            foreach (var b in beatmaps.QueryBeatmaps(b => b.Hidden).ToList())
                            {
                                beatmaps.Restore(b);
                            }
                        }).ContinueWith(t => Schedule(() => restoreButton.Enabled.Value = true));
                    }
                },
                undeleteButton = new SettingsButton
                {
                    Text   = MaintenanceSettingsStrings.RestoreAllRecentlyDeletedBeatmaps,
                    Action = () =>
                    {
                        undeleteButton.Enabled.Value = false;
                        Task.Run(() => beatmaps.Undelete(beatmaps.QueryBeatmapSets(b => b.DeletePending).ToList())).ContinueWith(t => Schedule(() => undeleteButton.Enabled.Value = true));
                    }
                },
            });
        }
Example #12
0
 public DatabasedLegacyScoreParser(RulesetStore rulesets, BeatmapManager beatmaps)
 {
     this.rulesets = rulesets;
     this.beatmaps = beatmaps;
 }
Example #13
0
        public ScoreStore(DatabaseContextFactory factory, IIpcHost importHost = null, BeatmapManager beatmaps = null, RulesetStore rulesets = null) : base(factory)
        {
            this.beatmaps = beatmaps;
            this.rulesets = rulesets;

            if (importHost != null)
            {
                ipc = new ScoreIPCChannel(importHost, this);
            }
        }
Example #14
0
        private static void Run()
        {
            Connect();
            while (true)
            {
                if (GameBase.Time - lastPingTime > pingTimeout)
                {
                    Connect();
                    Thread.Sleep(20);
                    continue;
                }

                if (client != null && client.Connected)
                {
                    try
                    {
                        //Send any waiting requests.
                        if (Requests.Count > 0 && stream.CanWrite && Authenticated)
                        {
                            Requests.Dequeue().Send(stream);
                            sendSequence = (sendSequence + 1) % ushort.MaxValue;
                        }

                        while (Connected && stream != null && stream.DataAvailable)
                        {
                            lastPingTime = GameBase.Time;

                            readBytes += stream.Read(readByteArray, readBytes, readByteArray.Length - readBytes);

                            //Read header data
                            if (readBytes == readByteArray.Length && readingHeader)
                            {
                                readType    = (RequestType)BitConverter.ToUInt16(readByteArray, 0);
                                compression = readByteArray[2] == 1;
                                uint length = BitConverter.ToUInt32(readByteArray, 3);

                                Console.WriteLine("R" + length + ": " + readType);

                                ResetReadArray(false);
                                readByteArray = new byte[length];
                            }

                            //Read payload data
                            if (readBytes != readByteArray.Length)
                            {
                                continue;
                            }

                            switch (readType)
                            {
                            /* CONNECTION MANAGEMENT */

                            case RequestType.Bancho_LoginReply:
                                GameBase.User.Id = new bInt(readStream).number;
                                switch (GameBase.User.Id)
                                {
                                case -1:
                                    GameBase.ShowMessage(
                                        "Bancho authentication failed.  Please check your username/password by clicking the user pane on the main menu.",
                                        Color.Red, 4400);
                                    Authenticated = false;
                                    Disconnect(true);
                                    if (LoginResult != null)
                                    {
                                        LoginResult(false, null);
                                    }
                                    break;

                                case -2:
                                    GameBase.ShowMessage(
                                        "Bancho connection failed: Version mismatch",
                                        Color.Red, 4400);
                                    GameBase.CheckForUpdates();
                                    Authenticated = false;
                                    Disconnect(true);
                                    return;

                                default:
                                    Console.WriteLine("login success userid:" + GameBase.User.Id);

                                    ChatEngine.BanchoConnected();
                                    GameBase.ShowMessage("Welcome to osu!Bancho.", Color.SlateBlue, 4400);

                                    Status = bStatus.Idle;
                                    UpdateStatus();

                                    Authenticated = true;
                                    if (OnConnect != null)
                                    {
                                        OnConnect();
                                    }
                                    if (LoginResult != null)
                                    {
                                        LoginResult(true, null);
                                    }
                                    break;
                                }
                                break;

                            case RequestType.Bancho_Ping:
                                SendRequest(RequestType.Osu_Pong, null);
                                break;

                            case RequestType.Bancho_VersionUpdate:
                                GameBase.CheckForUpdates();
                                break;

                            /* CHAT and MESSAGING */

                            case RequestType.Bancho_SendIrcMessage:
                                ChatEngine.HandleMessage(new bMessage(readStream), false);
                                break;

                            case RequestType.Bancho_HandleIrcChangeUsername:
                                string message = new bString(readStream).text;
                                string oldname = message.Substring(0, message.IndexOf(">>>>"));
                                string newname = message.Remove(0, message.IndexOf(">>>>") + 4);
                                ChatEngine.HandleChangeUsername(oldname, newname);
                                break;

                            case RequestType.Bancho_HandleIrcQuit:
                                ChatEngine.HandleQuit("#osu", new bString(readStream).text);
                                break;

                            case RequestType.Bancho_HandleIrcJoin:
                                ChatEngine.HandleJoin("#osu", new bString(readStream).text);
                                break;

                            case RequestType.Bancho_HandleOsuQuit:
                                ChatEngine.HandleUserQuit(new bInt(readStream).number);
                                break;

                            /* STATISTICS */

                            case RequestType.Bancho_HandleOsuUpdate:
                                if (readStream == null)
                                {
                                    break;
                                }
                                bUserStats stats = new bUserStats(readStream);
                                ChatEngine.HandleUserUpdate(stats);
                                if (stats.userId == GameBase.User.Id)
                                {
                                    if (stats.username != null)
                                    {
                                        ConfigManager.sUsername = stats.username;
                                    }
                                    GameBase.User.bancho_StatsReceived(null, stats);
                                }
                                break;

                            /* SPECTATING */
                            case RequestType.Bancho_FellowSpectatorJoined:
                                lock (StreamingManager.Spectators)
                                {
                                    User u = GetUserById(new bInt(readStream).number);
                                    StreamingManager.HasSpectators = true;
                                    if (!StreamingManager.FellowSpectators.Contains(u))
                                    {
                                        StreamingManager.FellowSpectators.Add(u);
                                    }
                                    StreamingManager.FellowSpectators.Sort();
                                }
                                break;

                            case RequestType.Bancho_FellowSpectatorLeft:
                                lock (StreamingManager.Spectators)
                                {
                                    User u = GetUserById(new bInt(readStream).number);
                                    StreamingManager.FellowSpectators.Remove(u);
                                    if (StreamingManager.Spectators.Count == 0)
                                    {
                                        StreamingManager.HasSpectators = false;
                                    }
                                }
                                break;

                            case RequestType.Bancho_SpectatorJoined:
                                //Start sending spectator frames.
                                lock (StreamingManager.Spectators)
                                {
                                    User u = GetUserById(new bInt(readStream).number);
                                    u.CantSpectate = false;
                                    if (!StreamingManager.Spectators.Contains(u))
                                    {
                                        StreamingManager.Spectators.Add(u);
                                    }
                                    StreamingManager.HasSpectators = true;
                                    StreamingManager.Spectators.Sort();
                                }
                                break;

                            case RequestType.Bancho_SpectatorCantSpectate:
                                GetUserById(new bInt(readStream).number).CantSpectate = true;
                                break;

                            case RequestType.Bancho_SpectatorLeft:
                                //Stop sending spectator frames.
                                lock (StreamingManager.Spectators)
                                {
                                    User u = GetUserById(new bInt(readStream).number);
                                    u.CantSpectate = false;
                                    StreamingManager.Spectators.Remove(u);
                                    if (StreamingManager.Spectators.Count == 0)
                                    {
                                        StreamingManager.HasSpectators = false;
                                    }
                                }
                                break;

                            case RequestType.Bancho_SpectateFrames:
                                StreamingManager.HandleFrames(new bReplayFrameBundle(readStream));
                                //Received some spectator frames.
                                break;

                            case RequestType.Bancho_GetAttention:
                                ChatEngine.PendingShow = true;
                                break;

                            case RequestType.Bancho_Announce:
                                GameBase.ShowMessage(new bString(readStream).text.Replace("\\n", "\n"), Color.DarkMagenta, 10000);
                                break;

                            case RequestType.Bancho_MatchUpdate:
                            case RequestType.Bancho_MatchNew:
                                Lobby.IncomingMatch(new bMatch(readStream));
                                break;

                            case RequestType.Bancho_MatchStart:
                                MatchSetup.MatchStart(new bMatch(readStream));
                                break;

                            case RequestType.Bancho_MatchDisband:
                                Lobby.DisbandedMatch(new bInt(readStream).number);
                                break;

                            case RequestType.Bancho_LobbyJoin:
                            case RequestType.Bancho_LobbyPart:
                                User f = GetUserById(new bInt(readStream).number);
                                if (f != null)
                                {
                                    f.InLobby = readType == RequestType.Bancho_LobbyJoin;
                                }
                                Lobby.LobbyUpdatePending = true;
                                break;

                            case RequestType.Bancho_MatchJoinFail:
                                Lobby.OnJoinFail();
                                break;

                            case RequestType.Bancho_MatchJoinSuccess:
                                MatchSetup.Match = new bMatch(readStream);
                                Lobby.OnJoinSuccess();
                                break;

                            case RequestType.Bancho_MatchScoreUpdate:
                                if (GameBase.Mode == Modes.Play && Lobby.Status == LobbyStatus.Play)
                                {
                                    PlayerVs.MatchScoreUpdate(new bScoreFrame(readStream));
                                }
                                break;

                            case RequestType.Bancho_MatchTransferHost:
                                MatchSetup.MatchTransferHost();
                                break;

                            case RequestType.Bancho_MatchAllPlayersLoaded:
                                if (GameBase.Mode == Modes.Play && Lobby.Status == LobbyStatus.Play)
                                {
                                    PlayerVs.AllPlayersLoaded = true;
                                }
                                break;

                            case RequestType.Bancho_MatchPlayerFailed:
                                if (GameBase.Mode == Modes.Play && Lobby.Status == LobbyStatus.Play)
                                {
                                    PlayerVs.MatchPlayerFailed(new bInt(readStream).number);
                                }
                                break;

                            case RequestType.Bancho_MatchComplete:
                                if (GameBase.Mode == Modes.Play && Lobby.Status == LobbyStatus.Play)
                                {
                                    PlayerVs.MatchComplete();
                                }
                                break;

                            case RequestType.Bancho_MatchSkip:
                                if (GameBase.Mode == Modes.Play && Lobby.Status == LobbyStatus.Play)
                                {
                                    Player.QueueSkip();
                                }
                                break;

                            case RequestType.Bancho_Unauthorised:

                                break;

                            case RequestType.Bancho_ChannelJoinSuccess:
                                string  match   = new bString(readStream).text;
                                Channel channel = ChatEngine.channels.Find(ch => ch.name == match);
                                if (channel != null)
                                {
                                    channel.HandleJoinSuccess();
                                }
                                break;

                            case RequestType.Bancho_ChannelAvailable:
                                ChatEngine.AddChannel(new bString(readStream).text, false);
                                break;

                            case RequestType.Bancho_ChannelAvailableAutojoin:
                                ChatEngine.AddChannel(new bString(readStream).text, true);
                                break;

                            case RequestType.Bancho_ChannelRevoked:
                                ChatEngine.RemoveChannel(new bString(readStream).text);
                                break;

                            case RequestType.Bancho_BeatmapInfoReply:
                                BeatmapManager.IncomingBeatmapInfoReply(new bBeatmapInfoReply(readStream));
                                break;
                            }
                            ResetReadArray(true);
                        }
                    }
                    catch (Exception e)
                    {
                        if (firstError)
                        {
                            firstError = false;
                            if (Connected)
                            {
                                StringBuilder report = new StringBuilder();
                                report.AppendLine("----------------------BANCHO--------------------------------");
                                report.AppendLine("Bancho error from " + ConfigManager.sUsername + " at " +
                                                  DateTime.UtcNow.ToString(GameBase.nfi));
                                report.AppendLine();
                                report.AppendLine("Mode: " + GameBase.Mode);
                                report.AppendLine();
                                report.Append(e + "\n");
                                report.AppendLine();
                                report.AppendLine("------------------------------------------------------------");
                                try
                                {
                                    new RequestGeneric(RequestType.Osu_ErrorReport, new bString(report.ToString())).Send
                                        (stream);
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        FailConnection("An error occurred somewhere in bancho comms.  Reconnecting!", errorRetry);
                        errorRetry = (int)(errorRetry * 1.5);
                    }
                }

                if (Connected)
                {
                    CheckAfk();
                }

                Thread.Sleep(20);
            }
        }
Example #15
0
        private void load(IAPIProvider api, BeatmapManager beatmaps)
        {
            FillFlowContainer textSprites;

            AddInternal(shakeContainer = new ShakeContainer
            {
                RelativeSizeAxes = Axes.Both,
                Masking          = true,
                CornerRadius     = 5,
                Child            = button = new HeaderButton {
                    RelativeSizeAxes = Axes.Both
                },
            });

            button.AddRange(new Drawable[]
            {
                new Container
                {
                    Padding = new MarginPadding {
                        Horizontal = 10
                    },
                    RelativeSizeAxes = Axes.Both,
                    Children         = new Drawable[]
                    {
                        textSprites = new FillFlowContainer
                        {
                            Anchor           = Anchor.CentreLeft,
                            Origin           = Anchor.CentreLeft,
                            AutoSizeAxes     = Axes.Both,
                            AutoSizeDuration = 500,
                            AutoSizeEasing   = Easing.OutQuint,
                            Direction        = FillDirection.Vertical,
                        },
                        new SpriteIcon
                        {
                            Anchor = Anchor.CentreRight,
                            Origin = Anchor.CentreRight,
                            Icon   = FontAwesome.Solid.Download,
                            Size   = new Vector2(18),
                        },
                    }
                },
                new DownloadProgressBar(BeatmapSet.Value)
                {
                    Anchor = Anchor.BottomLeft,
                    Origin = Anchor.BottomLeft,
                },
            });

            button.Action = () =>
            {
                if (State.Value != DownloadState.NotDownloaded)
                {
                    shakeContainer.Shake();
                    return;
                }

                beatmaps.Download(BeatmapSet.Value, noVideo);
            };

            localUser.BindTo(api.LocalUser);
            localUser.BindValueChanged(userChanged, true);
            button.Enabled.BindValueChanged(enabledChanged, true);

            State.BindValueChanged(state =>
            {
                switch (state.NewValue)
                {
                case DownloadState.Downloading:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Downloading...",
                            Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold)
                        },
                    };
                    break;

                case DownloadState.Importing:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Importing...",
                            Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold)
                        },
                    };
                    break;

                case DownloadState.LocallyAvailable:
                    this.FadeOut(200);
                    break;

                case DownloadState.NotDownloaded:
                    textSprites.Children = new Drawable[]
                    {
                        new OsuSpriteText
                        {
                            Text = "Download",
                            Font = OsuFont.GetFont(size: text_size, weight: FontWeight.Bold)
                        },
                        new OsuSpriteText
                        {
                            Text = getVideoSuffixText(),
                            Font = OsuFont.GetFont(size: text_size - 2, weight: FontWeight.Bold)
                        },
                    };
                    this.FadeIn(200);
                    break;
                }
            }, true);
        }
Example #16
0
        private void load()
        {
            Resources.AddStore(new DllResourceStore(@"osu.Game.Resources.dll"));

            dependencies.Cache(contextFactory = new DatabaseContextFactory(Host.Storage));

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.Cache(LocalConfig);

            //this completely overrides the framework default. will need to change once we make a proper FontStore.
            dependencies.Cache(Fonts = new FontStore(new GlyphStore(Resources, @"Fonts/FontAwesome")));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));

            runMigrations();

            dependencies.Cache(SkinManager = new SkinManager(Host.Storage, contextFactory, Host, Audio));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            API = new APIAccess(LocalConfig);

            dependencies.CacheAs <IAPIProvider>(API);

            var defaultBeatmap = new DummyWorkingBeatmap(this);

            dependencies.Cache(RulesetStore       = new RulesetStore(contextFactory));
            dependencies.Cache(FileStore          = new FileStore(contextFactory, Host.Storage));
            dependencies.Cache(BeatmapManager     = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap));
            dependencies.Cache(ScoreManager       = new ScoreManager(RulesetStore, BeatmapManager, Host.Storage, contextFactory, Host));
            dependencies.Cache(KeyBindingStore    = new KeyBindingStore(contextFactory, RulesetStore));
            dependencies.Cache(SettingsStore      = new SettingsStore(contextFactory));
            dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore));
            dependencies.Cache(new OsuColour());

            fileImporters.Add(BeatmapManager);
            fileImporters.Add(ScoreManager);
            fileImporters.Add(SkinManager);

            // tracks play so loud our samples can't keep up.
            // this adds a global reduction of track volume for the time being.
            Audio.Track.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));

            beatmap = new OsuBindableBeatmap(defaultBeatmap, Audio);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(beatmap);
            dependencies.CacheAs(beatmap);

            FileStore.Cleanup();

            AddInternal(API);

            GlobalActionContainer globalBinding;

            MenuCursorContainer = new MenuCursorContainer {
                RelativeSizeAxes = Axes.Both
            };
            MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this)
            {
                RelativeSizeAxes = Axes.Both,
                Child            = content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                {
                    RelativeSizeAxes = Axes.Both
                }
            };

            base.Content.Add(new ScalingContainer(ScalingMode.Everything)
            {
                Child = MenuCursorContainer
            });

            KeyBindingStore.Register(globalBinding);
            dependencies.Cache(globalBinding);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager());
            Add(previewTrackManager);
        }
Example #17
0
        public ScoreStore(Storage storage, Func <OsuDbContext> factory, IIpcHost importHost = null, BeatmapManager beatmaps = null, RulesetStore rulesets = null) : base(factory)
        {
            this.storage  = storage;
            this.beatmaps = beatmaps;
            this.rulesets = rulesets;

            if (importHost != null)
            {
                ipc = new ScoreIPCChannel(importHost, this);
            }
        }
Example #18
0
        private void load()
        {
            dependencies.Cache(contextFactory = new DatabaseContextFactory(Host));

            dependencies.Cache(new LargeTextureStore(new RawTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures"))));

            dependencies.CacheAs(this);
            dependencies.Cache(LocalConfig);

            runMigrations();

            dependencies.Cache(API = new APIAccess
            {
                Username = LocalConfig.Get <string>(OsuSetting.Username),
                Token    = LocalConfig.Get <string>(OsuSetting.Token)
            });

            dependencies.Cache(RulesetStore    = new RulesetStore(contextFactory));
            dependencies.Cache(FileStore       = new FileStore(contextFactory, Host.Storage));
            dependencies.Cache(BeatmapManager  = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, API, Host));
            dependencies.Cache(ScoreStore      = new ScoreStore(Host.Storage, contextFactory, Host, BeatmapManager, RulesetStore));
            dependencies.Cache(KeyBindingStore = new KeyBindingStore(contextFactory, RulesetStore));
            dependencies.Cache(SettingsStore   = new SettingsStore(contextFactory));
            dependencies.Cache(new OsuColour());

            //this completely overrides the framework default. will need to change once we make a proper FontStore.
            dependencies.Cache(Fonts = new FontStore {
                ScaleAdjust = 100
            });

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/FontAwesome"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));

            var defaultBeatmap = new DummyWorkingBeatmap(this);

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);
            BeatmapManager.DefaultBeatmap = defaultBeatmap;

            // tracks play so loud our samples can't keep up.
            // this adds a global reduction of track volume for the time being.
            Audio.Track.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));

            Beatmap.ValueChanged += b =>
            {
                var trackLoaded = lastBeatmap?.TrackLoaded ?? false;

                // compare to last beatmap as sometimes the two may share a track representation (optimisation, see WorkingBeatmap.TransferTo)
                if (!trackLoaded || lastBeatmap?.Track != b.Track)
                {
                    if (trackLoaded)
                    {
                        Debug.Assert(lastBeatmap != null);
                        Debug.Assert(lastBeatmap.Track != null);

                        lastBeatmap.RecycleTrack();
                    }

                    Audio.Track.AddItem(b.Track);
                }

                lastBeatmap = b;
            };

            API.Register(this);

            FileStore.Cleanup();
        }
Example #19
0
        private void load()
        {
            Resources.AddStore(new DllResourceStore(@"osu.Game.Resources.dll"));

            dependencies.Cache(contextFactory = new DatabaseContextFactory(Host.Storage));

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.Cache(LocalConfig);

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));

            runMigrations();

            dependencies.Cache(SkinManager = new SkinManager(Host.Storage, contextFactory, Host, Audio));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            API = new APIAccess(LocalConfig);

            dependencies.CacheAs <IAPIProvider>(API);

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            dependencies.Cache(RulesetStore = new RulesetStore(contextFactory));
            dependencies.Cache(FileStore    = new FileStore(contextFactory, Host.Storage));

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Host.Storage, contextFactory, Host));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap));

            // this should likely be moved to ArchiveModelManager when another case appers where it is necessary
            // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
            // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
            List <ScoreInfo> getBeatmapScores(BeatmapSetInfo set)
            {
                var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList();

                return(ScoreManager.QueryScores(s => beatmapIds.Contains(s.Beatmap.ID)).ToList());
            }

            BeatmapManager.ItemRemoved += i => ScoreManager.Delete(getBeatmapScores(i), true);
            BeatmapManager.ItemAdded   += (i, existing) => ScoreManager.Undelete(getBeatmapScores(i), true);

            dependencies.Cache(KeyBindingStore    = new KeyBindingStore(contextFactory, RulesetStore));
            dependencies.Cache(SettingsStore      = new SettingsStore(contextFactory));
            dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore));
            dependencies.Cache(new OsuColour());

            fileImporters.Add(BeatmapManager);
            fileImporters.Add(ScoreManager);
            fileImporters.Add(SkinManager);

            // tracks play so loud our samples can't keep up.
            // this adds a global reduction of track volume for the time being.
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));

            beatmap = new OsuBindableBeatmap(defaultBeatmap);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(beatmap);
            dependencies.CacheAs(beatmap);

            FileStore.Cleanup();

            AddInternal(API);

            GlobalActionContainer globalBinding;

            MenuCursorContainer = new MenuCursorContainer {
                RelativeSizeAxes = Axes.Both
            };
            MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this)
            {
                RelativeSizeAxes = Axes.Both,
                Child            = content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                {
                    RelativeSizeAxes = Axes.Both
                }
            };

            base.Content.Add(new ScalingContainer(ScalingMode.Everything)
            {
                Child = MenuCursorContainer
            });

            KeyBindingStore.Register(globalBinding);
            dependencies.Cache(globalBinding);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager());
            Add(previewTrackManager);
        }
Example #20
0
        private void load(ReadableKeyCombinationProvider keyCombinationProvider)
        {
            try
            {
                using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location))
                    VersionHash = str.ComputeMD5Hash();
            }
            catch
            {
                // special case for android builds, which can't read DLLs from a packed apk.
                // should eventually be handled in a better way.
                VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash();
            }

            Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));

            if (Storage.Exists(DatabaseContextFactory.DATABASE_NAME))
            {
                dependencies.Cache(EFContextFactory = new DatabaseContextFactory(Storage));
            }

            dependencies.Cache(realm = new RealmAccess(Storage, CLIENT_DATABASE_FILENAME, Host.UpdateThread, EFContextFactory));

            dependencies.CacheAs <RulesetStore>(RulesetStore = new RealmRulesetStore(realm, Storage));
            dependencies.CacheAs <IRulesetStore>(RulesetStore);

            Decoder.RegisterDependencies(RulesetStore);

            dependencies.CacheAs(Storage);

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.CacheAs(LocalConfig);

            InitialiseFonts();

            Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY;

            dependencies.Cache(SkinManager = new SkinManager(Storage, realm, Host, Resources, Audio, Scheduler));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            EndpointConfiguration endpoints = CreateEndpoints();

            MessageFormatter.WebsiteRootUrl = endpoints.WebsiteRootUrl;

            dependencies.CacheAs(API ??= new APIAccess(LocalConfig, endpoints, VersionHash));

            dependencies.CacheAs(spectatorClient   = new OnlineSpectatorClient(endpoints));
            dependencies.CacheAs(multiplayerClient = new OnlineMultiplayerClient(endpoints));

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            dependencies.Cache(difficultyCache = new BeatmapDifficultyCache());

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, realm, Scheduler, difficultyCache, LocalConfig));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, realm, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true));

            dependencies.Cache(BeatmapDownloader = new BeatmapModelDownloader(BeatmapManager, API));
            dependencies.Cache(ScoreDownloader   = new ScoreModelDownloader(ScoreManager, API));

            // Add after all the above cache operations as it depends on them.
            AddInternal(difficultyCache);

            dependencies.Cache(userCache = new UserLookupCache());
            AddInternal(userCache);

            dependencies.Cache(beatmapCache = new BeatmapLookupCache());
            AddInternal(beatmapCache);

            var scorePerformanceManager = new ScorePerformanceCache();

            dependencies.Cache(scorePerformanceManager);
            AddInternal(scorePerformanceManager);

            dependencies.CacheAs <IRulesetConfigCache>(rulesetConfigCache = new RulesetConfigCache(realm, RulesetStore));

            var powerStatus = CreateBatteryInfo();

            if (powerStatus != null)
            {
                dependencies.CacheAs(powerStatus);
            }

            dependencies.Cache(SessionStatics = new SessionStatics());
            dependencies.Cache(new OsuColour());

            RegisterImportHandler(BeatmapManager);
            RegisterImportHandler(ScoreManager);
            RegisterImportHandler(SkinManager);

            // drop track volume game-wide to leave some head-room for UI effects / samples.
            // this means that for the time being, gameplay sample playback is louder relative to the audio track, compared to stable.
            // we may want to revisit this if users notice or complain about the difference (consider this a bit of a trial).
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, globalTrackVolumeAdjust);

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(Beatmap);
            dependencies.CacheAs(Beatmap);

            // add api components to hierarchy.
            if (API is APIAccess apiAccess)
            {
                AddInternal(apiAccess);
            }
            AddInternal(spectatorClient);
            AddInternal(multiplayerClient);

            AddInternal(rulesetConfigCache);

            GlobalActionContainer globalBindings;

            base.Content.Add(new SafeAreaContainer
            {
                SafeAreaOverrideEdges = SafeAreaOverrideEdges,
                RelativeSizeAxes      = Axes.Both,
                Child = CreateScalingContainer().WithChildren(new Drawable[]
                {
                    (MenuCursorContainer = new MenuCursorContainer
                    {
                        RelativeSizeAxes = Axes.Both
                    }).WithChild(content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                    {
                        RelativeSizeAxes = Axes.Both
                    }),
                    // to avoid positional input being blocked by children, ensure the GlobalActionContainer is above everything.
                    globalBindings = new GlobalActionContainer(this)
                })
            });

            KeyBindingStore = new RealmKeyBindingStore(realm, keyCombinationProvider);
            KeyBindingStore.Register(globalBindings, RulesetStore.AvailableRulesets);

            dependencies.Cache(globalBindings);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager(BeatmapManager.BeatmapTrackStore));
            Add(previewTrackManager);

            AddInternal(MusicController = new MusicController());
            dependencies.CacheAs(MusicController);

            Ruleset.BindValueChanged(onRulesetChanged);
            Beatmap.BindValueChanged(onBeatmapChanged);
        }
Example #21
0
 private void load(OsuGameBase game, BeatmapManager beatmaps)
 {
     this.beatmaps = beatmaps;
     beatmap.BindTo(game.Beatmap);
 }
Example #22
0
        public static Score ReadReplayFromFile(string filename, bool handlePickup)
        {
            //Make sure the score manager is already initialized.
            InitializeScoreManager();

            Score inScore = null;

            bool success = false;

            try
            {
                using (Stream stream = File.Open(filename, FileMode.Open))
                {
                    SerializationReader sr = new SerializationReader(stream);
                    inScore = ScoreFactory.Create((PlayModes)sr.ReadByte(), null);
                    inScore.ReadHeaderFromStream(sr);
                    if (ModManager.CheckActive(inScore.EnabledMods, Mods.Target))
                    {
                        inScore = new ScoreTarget(inScore);
                    }
                    inScore.ReadFromStream(sr);
                    if (inScore.Date < DateTime.UtcNow + new TimeSpan(365 * 5, 0, 0, 0))
                    {
                        success = true;
                    }
                }
            }
            catch { }


            if (!success)
            {
                try
                {
                    using (Stream stream = File.Open(filename, FileMode.Open))
                        inScore = (Score)DynamicDeserializer.Deserialize(stream);
                }
                catch
                {
                    NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                    return(null);
                }
            }

            if (inScore == null)
            {
                NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                return(null);
            }

            if (inScore.Date.Year > 2050 || inScore.Date == DateTime.MinValue)
            {
                string[] split = filename.Split('-');
                if (split.Length > 1)
                {
                    long outfiletime = 0;
                    if (long.TryParse(split[1].Replace(@".osr", string.Empty), out outfiletime))
                    {
                        inScore.Date = DateTime.FromFileTimeUtc(outfiletime);
                    }
                }
            }

            if (inScore.Date.Year > 2050)
            {
                //this score is TOTALLY f****d.
                File.Delete(filename);
                NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_ReplayCorrupt));
                return(null);
            }

            if (BeatmapManager.GetBeatmapByChecksum(inScore.FileChecksum) == null)
            {
                //attempt pickup.
                if (handlePickup)
                {
                    OsuDirect.HandlePickup(inScore.FileChecksum, null,
                                           delegate
                    {
                        NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.ScoreManager_DontHaveBeatmap));
                    });
                }
                return(null);
            }

            InsertScore(inScore, false);

            return(inScore);
        }
Example #23
0
        private void load()
        {
            Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));

            dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage));

            dependencies.CacheAs(Storage);

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.Cache(LocalConfig);

            AddFont(Resources, @"Fonts/osuFont");

            AddFont(Resources, @"Fonts/Torus-Regular");
            AddFont(Resources, @"Fonts/Torus-Light");
            AddFont(Resources, @"Fonts/Torus-SemiBold");
            AddFont(Resources, @"Fonts/Torus-Bold");

            AddFont(Resources, @"Fonts/Noto-Basic");
            AddFont(Resources, @"Fonts/Noto-Hangul");
            AddFont(Resources, @"Fonts/Noto-CJK-Basic");
            AddFont(Resources, @"Fonts/Noto-CJK-Compatibility");

            AddFont(Resources, @"Fonts/Venera-Light");
            AddFont(Resources, @"Fonts/Venera-Bold");
            AddFont(Resources, @"Fonts/Venera-Black");

            Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY;

            runMigrations();

            dependencies.Cache(SkinManager = new SkinManager(Storage, contextFactory, Host, Audio, new NamespacedResourceStore <byte[]>(Resources, "Skins/Legacy")));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            if (API == null)
            {
                API = new APIAccess(LocalConfig);
            }

            dependencies.CacheAs(API);

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            dependencies.Cache(RulesetStore = new RulesetStore(contextFactory, Storage));
            dependencies.Cache(FileStore    = new FileStore(contextFactory, Storage));

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Host));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap));

            // this should likely be moved to ArchiveModelManager when another case appers where it is necessary
            // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
            // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
            List <ScoreInfo> getBeatmapScores(BeatmapSetInfo set)
            {
                var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList();

                return(ScoreManager.QueryScores(s => beatmapIds.Contains(s.Beatmap.ID)).ToList());
            }

            BeatmapManager.ItemRemoved += i => ScoreManager.Delete(getBeatmapScores(i), true);
            BeatmapManager.ItemAdded   += i => ScoreManager.Undelete(getBeatmapScores(i), true);

            dependencies.Cache(KeyBindingStore    = new KeyBindingStore(contextFactory, RulesetStore));
            dependencies.Cache(SettingsStore      = new SettingsStore(contextFactory));
            dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore));
            dependencies.Cache(new SessionStatics());
            dependencies.Cache(new OsuColour());

            fileImporters.Add(BeatmapManager);
            fileImporters.Add(ScoreManager);
            fileImporters.Add(SkinManager);

            // tracks play so loud our samples can't keep up.
            // this adds a global reduction of track volume for the time being.
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);

            // ScheduleAfterChildren is safety against something in the current frame accessing the previous beatmap's track
            // and potentially causing a reload of it after just unloading.
            // Note that the reason for this being added *has* been resolved, so it may be feasible to removed this if required.
            Beatmap.BindValueChanged(b => ScheduleAfterChildren(() =>
            {
                // compare to last beatmap as sometimes the two may share a track representation (optimisation, see WorkingBeatmap.TransferTo)
                if (b.OldValue?.TrackLoaded == true && b.OldValue?.Track != b.NewValue?.Track)
                {
                    b.OldValue.RecycleTrack();
                }
            }));

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(Beatmap);
            dependencies.CacheAs(Beatmap);

            FileStore.Cleanup();

            if (API is APIAccess apiAcces)
            {
                AddInternal(apiAcces);
            }
            AddInternal(RulesetConfigCache);

            GlobalActionContainer globalBinding;

            MenuCursorContainer = new MenuCursorContainer {
                RelativeSizeAxes = Axes.Both
            };
            MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this)
            {
                RelativeSizeAxes = Axes.Both,
                Child            = content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
                {
                    RelativeSizeAxes = Axes.Both
                }
            };

            base.Content.Add(CreateScalingContainer().WithChild(MenuCursorContainer));

            KeyBindingStore.Register(globalBinding);
            dependencies.Cache(globalBinding);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager());
            Add(previewTrackManager);

            Ruleset.BindValueChanged(onRulesetChanged);
        }
Example #24
0
 private void load(BeatmapManager beatmapManager)
 {
     manager = beatmapManager;
 }
Example #25
0
        private void load()
        {
            dependencies.Cache(this);
            dependencies.Cache(LocalConfig);

            connection = createConnection();
            connection.CreateTable <StoreVersion>();

            dependencies.Cache(API = new APIAccess
            {
                Username = LocalConfig.Get <string>(OsuSetting.Username),
                Token    = LocalConfig.Get <string>(OsuSetting.Token)
            });

            dependencies.Cache(RulesetStore    = new RulesetStore(connection));
            dependencies.Cache(FileStore       = new FileStore(connection, Host.Storage));
            dependencies.Cache(BeatmapManager  = new BeatmapManager(Host.Storage, FileStore, connection, RulesetStore, API, Host));
            dependencies.Cache(ScoreStore      = new ScoreStore(Host.Storage, connection, Host, BeatmapManager, RulesetStore));
            dependencies.Cache(KeyBindingStore = new KeyBindingStore(connection, RulesetStore));
            dependencies.Cache(new OsuColour());

            //this completely overrides the framework default. will need to change once we make a proper FontStore.
            dependencies.Cache(Fonts = new FontStore {
                ScaleAdjust = 100
            }, true);

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/FontAwesome"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));

            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
            Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));

            var defaultBeatmap = new DummyWorkingBeatmap(this);

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);
            BeatmapManager.DefaultBeatmap = defaultBeatmap;

            Beatmap.ValueChanged += b =>
            {
                var trackLoaded = lastBeatmap?.TrackLoaded ?? false;

                // compare to last beatmap as sometimes the two may share a track representation (optimisation, see WorkingBeatmap.TransferTo)
                if (!trackLoaded || lastBeatmap?.Track != b.Track)
                {
                    if (trackLoaded)
                    {
                        Debug.Assert(lastBeatmap != null);
                        Debug.Assert(lastBeatmap.Track != null);

                        lastBeatmap.DisposeTrack();
                    }

                    Audio.Track.AddItem(b.Track);
                }

                lastBeatmap = b;
            };

            API.Register(this);
        }
Example #26
0
        private void load()
        {
            try
            {
                using (var str = File.OpenRead(typeof(OsuGameBase).Assembly.Location))
                    VersionHash = str.ComputeMD5Hash();
            }
            catch
            {
                // special case for android builds, which can't read DLLs from a packed apk.
                // should eventually be handled in a better way.
                VersionHash = $"{Version}-{RuntimeInfo.OS}".ComputeMD5Hash();
            }

            Resources.AddStore(new DllResourceStore(OsuResources.ResourceAssembly));

            dependencies.Cache(contextFactory = new DatabaseContextFactory(Storage));

            dependencies.Cache(realmFactory = new RealmContextFactory(Storage, "client"));

            updateThreadState = Host.UpdateThread.State.GetBoundCopy();
            updateThreadState.BindValueChanged(updateThreadStateChanged);

            AddInternal(realmFactory);

            dependencies.CacheAs(Storage);

            var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore <byte[]>(Resources, @"Textures")));

            largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore()));
            dependencies.Cache(largeStore);

            dependencies.CacheAs(this);
            dependencies.CacheAs(LocalConfig);

            InitialiseFonts();

            Audio.Samples.PlaybackConcurrency = SAMPLE_CONCURRENCY;

            runMigrations();

            dependencies.Cache(SkinManager = new SkinManager(Storage, contextFactory, Host, Resources, Audio));
            dependencies.CacheAs <ISkinSource>(SkinManager);

            // needs to be done here rather than inside SkinManager to ensure thread safety of CurrentSkinInfo.
            SkinManager.ItemRemoved.BindValueChanged(weakRemovedInfo =>
            {
                if (weakRemovedInfo.NewValue.TryGetTarget(out var removedInfo))
                {
                    Schedule(() =>
                    {
                        // check the removed skin is not the current user choice. if it is, switch back to default.
                        if (removedInfo.ID == SkinManager.CurrentSkinInfo.Value.ID)
                        {
                            SkinManager.CurrentSkinInfo.Value = SkinInfo.Default;
                        }
                    });
                }
            });

            EndpointConfiguration endpoints = UseDevelopmentServer ? (EndpointConfiguration) new DevelopmentEndpointConfiguration() : new ProductionEndpointConfiguration();

            MessageFormatter.WebsiteRootUrl = endpoints.WebsiteRootUrl;

            dependencies.CacheAs(API ??= new APIAccess(LocalConfig, endpoints, VersionHash));

            dependencies.CacheAs(spectatorClient   = new OnlineSpectatorClient(endpoints));
            dependencies.CacheAs(multiplayerClient = new OnlineMultiplayerClient(endpoints));

            var defaultBeatmap = new DummyWorkingBeatmap(Audio, Textures);

            dependencies.Cache(RulesetStore = new RulesetStore(contextFactory, Storage));
            dependencies.Cache(fileStore    = new FileStore(contextFactory, Storage));

            // ordering is important here to ensure foreign keys rules are not broken in ModelStore.Cleanup()
            dependencies.Cache(ScoreManager   = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Scheduler, Host, () => difficultyCache, LocalConfig));
            dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true));

            // this should likely be moved to ArchiveModelManager when another case appears where it is necessary
            // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
            // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
            List <ScoreInfo> getBeatmapScores(BeatmapSetInfo set)
            {
                var beatmapIds = BeatmapManager.QueryBeatmaps(b => b.BeatmapSetInfoID == set.ID).Select(b => b.ID).ToList();

                return(ScoreManager.QueryScores(s => beatmapIds.Contains(s.Beatmap.ID)).ToList());
            }

            BeatmapManager.ItemRemoved.BindValueChanged(i =>
            {
                if (i.NewValue.TryGetTarget(out var item))
                {
                    ScoreManager.Delete(getBeatmapScores(item), true);
                }
            });

            BeatmapManager.ItemUpdated.BindValueChanged(i =>
            {
                if (i.NewValue.TryGetTarget(out var item))
                {
                    ScoreManager.Undelete(getBeatmapScores(item), true);
                }
            });

            dependencies.Cache(difficultyCache = new BeatmapDifficultyCache());
            AddInternal(difficultyCache);

            dependencies.Cache(userCache = new UserLookupCache());
            AddInternal(userCache);

            var scorePerformanceManager = new ScorePerformanceCache();

            dependencies.Cache(scorePerformanceManager);
            AddInternal(scorePerformanceManager);

            migrateDataToRealm();

            dependencies.Cache(rulesetConfigCache = new RulesetConfigCache(realmFactory, RulesetStore));

            var powerStatus = CreateBatteryInfo();

            if (powerStatus != null)
            {
                dependencies.CacheAs(powerStatus);
            }

            dependencies.Cache(SessionStatics = new SessionStatics());
            dependencies.Cache(new OsuColour());

            RegisterImportHandler(BeatmapManager);
            RegisterImportHandler(ScoreManager);
            RegisterImportHandler(SkinManager);

            // drop track volume game-wide to leave some head-room for UI effects / samples.
            // this means that for the time being, gameplay sample playback is louder relative to the audio track, compared to stable.
            // we may want to revisit this if users notice or complain about the difference (consider this a bit of a trial).
            Audio.Tracks.AddAdjustment(AdjustableProperty.Volume, globalTrackVolumeAdjust);

            Beatmap = new NonNullableBindable <WorkingBeatmap>(defaultBeatmap);

            dependencies.CacheAs <IBindable <WorkingBeatmap> >(Beatmap);
            dependencies.CacheAs(Beatmap);

            fileStore.Cleanup();

            // add api components to hierarchy.
            if (API is APIAccess apiAccess)
            {
                AddInternal(apiAccess);
            }
            AddInternal(spectatorClient);
            AddInternal(multiplayerClient);

            AddInternal(rulesetConfigCache);

            GlobalActionContainer globalBindings;

            var mainContent = new Drawable[]
            {
                MenuCursorContainer = new MenuCursorContainer {
                    RelativeSizeAxes = Axes.Both
                },
                // to avoid positional input being blocked by children, ensure the GlobalActionContainer is above everything.
                globalBindings = new GlobalActionContainer(this)
            };

            MenuCursorContainer.Child = content = new OsuTooltipContainer(MenuCursorContainer.Cursor)
            {
                RelativeSizeAxes = Axes.Both
            };

            base.Content.Add(CreateScalingContainer().WithChildren(mainContent));

            KeyBindingStore = new RealmKeyBindingStore(realmFactory);
            KeyBindingStore.Register(globalBindings, RulesetStore.AvailableRulesets);

            dependencies.Cache(globalBindings);

            PreviewTrackManager previewTrackManager;

            dependencies.Cache(previewTrackManager = new PreviewTrackManager());
            Add(previewTrackManager);

            AddInternal(MusicController = new MusicController());
            dependencies.CacheAs(MusicController);

            Ruleset.BindValueChanged(onRulesetChanged);
        }
Example #27
0
        /// <summary>
        /// Detect and process new files in the songs folder.
        /// </summary>
        private static void processSongs()
        {
            int newFolderCount = -1;

            //Process any new files waiting to be imported.
            if (handleNewFiles() || BeatmapManager.ChangedPackages.Count > 0 || BeatmapManager.ChangedFolders.Count > 0)
            {
                //We might need a full refresh even with new files added, if this is signalled.
                forceFullRefresh = false;
            }
            else
            {
                //Check if the number of directories in the songs dir has changed.
                //If it has, then we definitely need to do a full pass over available maps.
                newFolderCount = Directory.GetDirectories(BeatmapManager.SongsDirectory).Length + Directory.GetFiles(BeatmapManager.SongsDirectory).Length;

                if (BeatmapManager.FolderFileCount != newFolderCount)
                {
                    Debug.Print(@"Folder/Filecount changed from {0} to {1}", BeatmapManager.FolderFileCount, newFolderCount);

                    string _status = null;
                    if (BeatmapManager.FolderFileCount == 0)
                    {
                        _status             = LocalisationManager.GetString(OsuString.BeatmapImport_TimeToPopulateAnEmptyDatabase);
                        promptOnFullProcess = false;
                    }
                    else if (BeatmapManager.FolderFileCount < newFolderCount)
                    {
                        _status = LocalisationManager.GetString(OsuString.BeatmapImport_DetectedNewMapsAdded);
                    }
                    else
                    {
                        _status = LocalisationManager.GetString(OsuString.BeatmapImport_DetectedMapsRemoved);
                    }

                    if (status != null)
                    {
                        status.SetStatus(_status);
                    }

                    forceFullRefresh = true;
                }
            }

            if (status != null)
            {
                BeatmapManager.AssignStatusHandler(status.SetStatus);
            }

            //confirm this operation if the user has a lot of maps.
            if (forceFullRefresh && promptOnFullProcess
#if !DEBUG
                && BeatmapManager.Beatmaps.Count > 1000
#endif
                )
            {
                bool response = false;

                GameBase.RunBackgroundThread(delegate
                {
                    pDialog pd = new pDialog(LocalisationManager.GetString(OsuString.BeatmapImport_FullProcess), false);
                    pd.Closed += delegate { promptOnFullProcess = false; };

                    pd.AddOption(LocalisationManager.GetString(OsuString.General_Confirm), Color.YellowGreen, delegate
                    {
                        response            = true;
                        promptOnFullProcess = false;
                    });

                    pd.AddOption(LocalisationManager.GetString(OsuString.General_Cancel), Color.OrangeRed, delegate
                    {
                        response            = false;
                        promptOnFullProcess = false;
                    });

                    GameBase.Scheduler.Add(delegate
                    {
                        GameBase.ShowDialog(pd);
                    });
                });

                while (promptOnFullProcess && GameBase.Mode == OsuModes.BeatmapImport)
                {
                    Thread.Sleep(50);
                }

                if (!response)
                {
                    GameBase.Scheduler.Add(Exit);
                    BeatmapManager.ClearStatusHandlers();
                    return;
                }
            }

            BeatmapManager.CheckAndProcess(forceFullRefresh, promptOnFullProcess);
            BeatmapManager.ClearStatusHandlers();

            if (newFolderCount >= 0)
            {
                BeatmapManager.FolderFileCount = newFolderCount;
            }

            GameBase.Scheduler.Add(Exit);
        }