private void SaveCore(
            CartridgeTag tag,
            CartridgeSavegame cs,
            Action <CartridgeTag, CartridgeSavegame> continuation,
            bool displayError)
        {
            try
            {
                // Performs the savegame.
                _appViewModel.Model.Core.SaveAsync(cs)
                .ContinueWith(t =>
                {
                    // Continues.
                    continuation(tag, cs);
                }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception ex)
            {
                // Keeps track of the error.
                DebugUtils.DumpException(ex);

                // Displays an error if needed.
                if (displayError)
                {
                    MessageBox.Show("An error occured while preparing the savegame. Please try again.", "Error", MessageBoxButton.OK);
                }
            }
        }
        private void SaveCore(
            CartridgeTag tag,
            Dictionary <CartridgeTag, CartridgeSavegame> savegameDict,
            Func <CartridgeTag, CartridgeSavegame> generator,
            bool displayError)
        {
            // Gets the current session' preferred save for the cartridge.
            CartridgeSavegame savegame;

            if (!savegameDict.TryGetValue(tag, out savegame))
            {
                // If there's none, makes one.
                savegame = generator(tag);
            }

            // Saves the game, updates the savegame metadata and cleans the history.
            SaveCore(tag, savegame, (t, s) =>
            {
                // Updates the savegame's attributes.
                s.Timestamp = DateTime.Now;

                // Saves the savegame to the store and adds it to the tag if needed.
                t.RefreshOrAddSavegame(s);

                // Ensures there's a unique history entry for this savegame.
                History history = _appViewModel.Model.History;
                history.RemoveAllOf(t.Guid, s.Name, HistoryEntry.Type.Saved);
                history.AddSavedGame(t, s);
            }, displayError);
        }
Пример #3
0
        private void RunHistoryEntryAction(HistoryEntry entry)
        {
            // Is the entry is related to saving the game?
            bool isRelatedToSavegame = entry.EntryType == HistoryEntry.Type.Saved ||
                                       entry.EntryType == HistoryEntry.Type.Restored;

            // Gets the cartridge tag if it still exists.
            CartridgeTag tag = entry.CartridgeTag;

            // Does the cartridge still exist?
            // NO -> Asks for clearing the history.
            if (tag == null)
            {
                // Asks for clearing the history.
                if (System.Windows.MessageBox.Show(String.Format("The cartridge {0} could not be found, perhaps because it is not installed anymore.\n\nDo you want to remove the history entries for this cartridge?", entry.RelatedCartridgeName), "Cartridge not found", MessageBoxButton.OKCancel) == System.Windows.MessageBoxResult.OK)
                {
                    // Clears the history of the entries related to this cartridge.
                    Model.History.RemoveAllOf(entry.RelatedCartridgeGuid);
                }

                // No more to do.
                return;
            }

            // Is the entry is related to saving the game?
            // YES -> Asks if the user wants to restore it.
            // NO -> Go to the cartridge info page.
            if (isRelatedToSavegame)
            {
                // Gets the savegame if it still exists.
                CartridgeSavegame savegame = entry.Savegame;

                // Does the savegame still exist?
                // NO -> Asks for removing the entry.
                // YES -> Restore it.
                if (savegame == null)
                {
                    // Asks for removing the entry.
                    if (System.Windows.MessageBox.Show(String.Format("The savegame {0} could not be found, perhaps because it is not installed anymore.\n\nDo you want to remove history entries for this cartridge?", entry.RelatedSavegameName), "Savegame not found", MessageBoxButton.OKCancel) == System.Windows.MessageBoxResult.OK)
                    {
                        // Clears the history of the entries related to this cartridge.
                        Model.History.RemoveAllOf(entry.RelatedCartridgeGuid);
                    }
                }
                else
                {
                    // Restores the cartridge.
                    App.Current.ViewModel.NavigationManager.NavigateToGameHome(tag.Cartridge.Filename, savegame);
                }
            }
            else
            {
                // Navigates to the cartridge info.
                // (We know the cartridge tag exists at this point.)
                ShowCartridgeInfo(tag);
            }
        }
        /// <summary>
        /// Makes a savegame of the currently playing cartridge and prompts the user for a name.
        /// </summary>
        public void SaveAndPrompt()
        {
            // Creates a savegame container
            CartridgeTag      tag = GetCurrentTag();
            CartridgeSavegame cs  = new CartridgeSavegame(tag);

            // Saves the game, displays a prompt, and a message in case of error.
            SaveCore(tag, cs, (t, c) => ShowNewSavegameMessageBox(c), true);
        }
Пример #5
0
 /// <summary>
 /// Displays a message when the async initialization failed,
 /// and returns back to the main menu.
 /// </summary>
 /// <param name="ex"></param>
 /// <param name="tag"></param>
 /// <param name="isRestore"></param>
 private void FailInit(AggregateException ex, CartridgeTag tag, bool isRestore = false)
 {
     // Let the app view model handle this crash.
     App.Current.ViewModel.HandleGameCrash(
         isRestore ? AppViewModel.CrashMessageType.Restore : AppViewModel.CrashMessageType.NewGame,
         ex,
         tag.Cartridge
         );
 }
        private void DeleteSaveGame(CartridgeSavegame savegame)
        {
            // Confirm
            if (MessageBox.Show(
                    String.Format("Savegame {0} will be deleted. Do you want to continue?", savegame.Name),
                    "Delete savegame",
                    MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                return;
            }

            // Delete.
            CartridgeTag.RemoveSavegame(savegame);
        }
Пример #7
0
        /// <summary>
        /// Plays a media sound.
        /// </summary>
        /// <param name="media">The sound to play.</param>
        public void PlayMediaSound(Media media)
        {
            // Sanity check.
            if (!SoundManager.IsPlayableSound(media))
            {
                System.Diagnostics.Debug.WriteLine("AppViewModel: Ignored playing sound of unsupported type: " + media.Type.ToString());
                return;
            }

            // Gets the media filename in cache.
            CartridgeTag tag      = Model.CartridgeStore.GetCartridgeTag(Model.Core.Cartridge);
            string       filename = tag.GetMediaCachePath(media, true);

            // Plays the file.
            SoundManager.PlaySound(filename);
        }
Пример #8
0
        private void DeleteCartridge(CartridgeTag tag)
        {
            /// Makes a confirmation message.

            ICartridgeProvider provider = Model.CartridgeStore.GetCartridgeTagProvider(tag);
            int savegameCount           = tag.Savegames.Count();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.AppendFormat("Geowigo will delete {0} and all its contents", tag.Title);
            if (savegameCount > 0)
            {
                sb.AppendFormat(", including {0} savegames.", savegameCount);
            }
            else
            {
                sb.Append(".");
            }
            sb.AppendLine();
            sb.AppendLine();

            if (provider != null)
            {
                sb.AppendFormat(
                    "Since {0} was downloaded from {1}, it may be downloaded again the next time Geowigo will sync with {1}, unless you remove it from the Geowigo folder on your {1}.",
                    tag.Title,
                    provider.ServiceName);
                sb.AppendLine();
                sb.AppendLine();
            }

            sb.AppendLine("Do you want to continue?");

            /// Asks for confirmation.
            if (System.Windows.MessageBox.Show(sb.ToString(), "Delete " + tag.Title, MessageBoxButton.OKCancel) != System.Windows.MessageBoxResult.OK)
            {
                // Cancels.
                return;
            }

            /// Deletes everything.
            Model.DeleteCartridgeAndContent(tag);
        }
        /// <summary>
        /// Initializes quick and auto savegames for a new game session.
        /// </summary>
        /// <param name="tag">Cartridge being played</param>
        /// <param name="savegameCandidate">Savegame that started the game session, or null if it is a new game.</param>
        public void InitSessionSavegames(CartridgeTag tag, CartridgeSavegame savegameCandidate)
        {
            // Inits the session's quick save from the restored savegame if it is a quicksave, or makes a new one if not.
            if (savegameCandidate != null && savegameCandidate.IsQuicksave)
            {
                _quickSaves[tag] = savegameCandidate;
            }
            else
            {
                CreateQuickSavegame(tag);
            }

            // Inits the session's auto save from the restored savegame if it is an autosave, or makes a new one if not.
            if (savegameCandidate != null && savegameCandidate.IsAutosave)
            {
                _autoSaves[tag] = savegameCandidate;
            }
            else
            {
                CreateAutoSavegame(tag);
            }
        }
        private CartridgeSavegame CreateSavegame(CartridgeTag tag, string nameRoot, string suffixFormat, bool isQuickSave, bool isAutoSave, Dictionary <CartridgeTag, CartridgeSavegame> dict)
        {
            if (!isQuickSave && !isAutoSave)
            {
                throw new InvalidOperationException("Savegame must be either quick save or auto save");
            }

            // Makes a savegame.
            string            intPattern = " {0}";
            int               saveId     = tag.GetLastSavegameNameInteger(nameRoot, intPattern) + 1;
            CartridgeSavegame cs         = new CartridgeSavegame(tag, nameRoot + String.Format(intPattern, saveId))
            {
                IsQuicksave = isQuickSave,
                IsAutosave  = isAutoSave
            };

            // Sets it as the current save for the tag.
            dict[tag] = cs;

            // Returns
            return(cs);
        }
Пример #11
0
        protected override void InitFromNavigation(NavigationInfo nav)
        {
            base.InitFromNavigation(nav);

            // We probably have a lot of things to do.
            // Let's block the UI and show some progress bar.
            RefreshProgressBar(Model.Core.GameState);

            System.Windows.Navigation.NavigationContext navCtx = nav.NavigationContext;

            // Tries to get a particular section to display.
            string section;

            if (navCtx.QueryString.TryGetValue(SectionKey, out section))
            {
                ShowSection(section);
            }

            // Refreshes the application bar.
            RefreshAppBar();

            // Nothing more to do if a cartridge exists already.
            if (Cartridge != null)
            {
                return;
            }

            // Makes sure the screen lock is disabled.
            App.Current.ViewModel.IsScreenLockEnabled = false;

            // Resets the custom status text.
            App.Current.ViewModel.SystemTrayManager.StatusText = null;

            // Tries to get the filename to query for.
            string filename;

            if (navCtx.QueryString.TryGetValue(CartridgeFilenameKey, out filename))
            {
                // Gets the cartridge tag for this cartridge.
                CartridgeTag = Model.CartridgeStore.GetCartridgeTag(filename);

                string gwsFilename;

                // Restores the cartridge or starts a new game?
                if (navCtx.QueryString.TryGetValue(SavegameFilenameKey, out gwsFilename))
                {
                    // Starts restoring the game.
                    RunOrDeferIfNotReady(
                        new Action(() =>
                    {
                        // Starts logging.
                        if (Model.Settings.CanGenerateCartridgeLog)
                        {
                            Model.Core.StartLogging(CartridgeTag.CreateLogFile());
                        }

                        // Restores the game.
                        Model.Core.InitAndRestoreCartridgeAsync(filename, gwsFilename)
                        .ContinueWith(t =>
                        {
                            // Keeps the cartridge.
                            try
                            {
                                Cartridge = t.Result;
                            }
                            catch (AggregateException ex)
                            {
                                FailInit(ex, CartridgeTag, true);
                            }

                            // Registers a history entry.
                            CartridgeSavegame savegame = CartridgeTag.Savegames.FirstOrDefault(cs => cs.SavegameFile == gwsFilename);
                            Model.History.AddRestoredGame(CartridgeTag, savegame);

                            // Lets the view model know we started the game.
                            App.Current.ViewModel.HandleGameStarted(CartridgeTag, savegame);
                        }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
                    }));
                }
                else
                {
                    // Starts a new game.
                    RunOrDeferIfNotReady(
                        new Action(() =>
                    {
                        // Starts logging.
                        if (Model.Settings.CanGenerateCartridgeLog)
                        {
                            Model.Core.StartLogging(CartridgeTag.CreateLogFile());
                        }

                        // Starts the game.
                        Model.Core.InitAndStartCartridgeAsync(filename)
                        .ContinueWith(t =>
                        {
                            // Stores the result of the cartridge.
                            try
                            {
                                Cartridge = t.Result;
                            }
                            catch (AggregateException ex)
                            {
                                FailInit(ex, CartridgeTag);
                            }

                            // Registers a history entry.
                            Model.History.AddStartedGame(CartridgeTag);

                            // Lets the view model know we started the game.
                            App.Current.ViewModel.HandleGameStarted(CartridgeTag);
                        }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
                    }));
                }
            }

            // TODO: Cancel nav if no cartridge in parameter?
        }
Пример #12
0
 private void ShowCartridgeInfo(CartridgeTag cartTag)
 {
     // Show the cartridge info!
     App.Current.ViewModel.NavigationManager.NavigateToCartridgeInfo(cartTag);
 }
 /// <summary>
 /// Navigates the app to the info page of a cartridge.
 /// </summary>
 public void NavigateToCartridgeInfo(CartridgeTag tag)
 {
     NavigateCore(new Uri(String.Format("/Views/CartridgeInfoPage.xaml?{0}={1}&{2}={3}", CartridgeInfoViewModel.CartridgeFilenameKey, tag.Cartridge.Filename, CartridgeInfoViewModel.CartridgeIdKey, tag.Guid), UriKind.Relative));
 }
Пример #14
0
 /// <summary>
 /// Called when a game started.
 /// </summary>
 /// <param name="tag">Cartridge that started.</param>
 /// <param name="savegame">Optional savegame restored when the game started.</param>
 public void HandleGameStarted(CartridgeTag tag, CartridgeSavegame savegame = null)
 {
     // Resets the session quick save.
     SavegameManager.InitSessionSavegames(tag, savegame);
 }
 private CartridgeSavegame CreateAutoSavegame(CartridgeTag tag)
 {
     return(CreateSavegame(tag, "Auto Save", " {0}", false, true, _autoSaves));
 }
 private CartridgeSavegame CreateQuickSavegame(CartridgeTag tag)
 {
     return(CreateSavegame(tag, "Quick Save", " {0}", true, false, _quickSaves));
 }
        private void OnSavegameCustomMessageBoxDismissed(object sender, DismissedEventArgs e)
        {
            CustomMessageBox cmb = (CustomMessageBox)sender;

            // Unregisters events.
            cmb.Dismissed -= new EventHandler <DismissedEventArgs>(OnSavegameCustomMessageBoxDismissed);

            // Only moves on if OK has been pushed.
            if (e.Result != CustomMessageBoxResult.LeftButton)
            {
                return;
            }

            // Gets the associated savegame.
            Controls.SavegameMessageBoxContentControl content = cmb.Content as Controls.SavegameMessageBoxContentControl;
            if (content == null)
            {
                throw new InvalidOperationException("Message box has no SavegameMessageBoxContentControl.");
            }
            CartridgeSavegame cs = content.Savegame;

            if (cs == null)
            {
                throw new InvalidOperationException("SavegameMessageBoxContentControl has no CartridgeSavegame.");
            }

            // If the name already exists, asks if the old savegame should be replaced.
            CartridgeTag      tag = GetCurrentTag();
            CartridgeSavegame oldCSWithSameName = GetSavegameByName(content.Name);

            if (oldCSWithSameName != null)
            {
                // Asks for replacing the savegame.
                if (MessageBox.Show(
                        String.Format("A savegame named {0} already exists for this cartridge. Do you want to override it?", content.Name),
                        "Replace savegame?",
                        MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Go: deletes the old savegame and continues.
                    tag.RemoveSavegame(oldCSWithSameName);
                }
                else
                {
                    // No-go: prompt for another name.
                    ShowNewSavegameMessageBox(cs);

                    // Don't go further
                    return;
                }
            }

            // Edits the savegame.
            cs.Name      = content.Name;
            cs.HashColor = content.HashColor;

            // Commit.
            cs.ExportToIsoStore();

            // Adds an history entry for this savegame.
            _appViewModel.Model.History.AddSavedGame(tag, cs);

            // Adds the savegame to the tag.
            tag.AddSavegame(cs);
        }