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 ImportSavegamesCache(IsolatedStorageFile isf)
        {
            List <CartridgeSavegame> cSavegames = new List <CartridgeSavegame>();

            string[] gwsFiles = isf.GetFileNames(PathToSavegames + "/*.gws");
            if (gwsFiles != null)
            {
                // For each file, imports its metadata.
                foreach (string file in gwsFiles)
                {
                    try
                    {
                        cSavegames.Add(CartridgeSavegame.FromIsoStore(PathToSavegames + "/" + file, isf));
                    }
                    catch (Exception ex)
                    {
                        // Outputs the exception.
                        System.Diagnostics.Debug.WriteLine("CartridgeTag: WARNING: Exception during savegame import.");
                        DebugUtils.DumpException(ex);
                    }
                }
            }

            // Sets the savegame list.
            savegames = cSavegames;
            RaisePropertyChanged("Savegames");
        }
        private void ShowNewSavegameMessageBox(CartridgeSavegame cs)
        {
            if (cs == null)
            {
                throw new ArgumentNullException("cs");
            }

            // Creates a custom message box.
            CustomMessageBox cmb = new CustomMessageBox()
            {
                Caption = "Savegame",
                Content = new Controls.SavegameMessageBoxContentControl()
                {
                    Savegame = cs
                },
                LeftButtonContent  = "OK",
                RightButtonContent = "Cancel"
            };

            // Adds event handlers.
            cmb.Dismissed += new EventHandler <DismissedEventArgs>(OnSavegameCustomMessageBoxDismissed);

            // Shows the message box.
            _appViewModel.MessageBoxManager.AcceptAndShow(cmb);
        }
 private void ResumeGame(CartridgeSavegame savegame)
 {
     // Resumes the game!
     if (CanCartridgeRun(Cartridge))
     {
         App.Current.ViewModel.NavigationManager.NavigateToGameHome(Cartridge.Filename, savegame);
     }
 }
        /// <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);
        }
 /// <summary>
 /// Navigates the app to the game main page of a cartridge and restores a
 /// savegame.
 /// </summary>
 public void NavigateToGameHome(string filename, CartridgeSavegame savegame)
 {
     NavigateCore(new Uri(String.Format(
                              "/Views/GameHomePage.xaml?{0}={1}&{2}={3}",
                              GameHomeViewModel.CartridgeFilenameKey,
                              filename,
                              GameHomeViewModel.SavegameFilenameKey,
                              savegame.SavegameFile), UriKind.Relative));
 }
Example #7
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>
        /// Removes a savegame's contents from the isolated storage and removes
        /// it from this tag.
        /// </summary>
        public void RemoveSavegame(CartridgeSavegame cs)
        {
            // Removes the savegame.
            savegames.Remove(cs);

            // Makes sure the savegame is cleared from cache.
            cs.RemoveFromIsoStore();

            // Notifies of a change.
            RaisePropertyChanged("Savegames");
        }
Example #9
0
 private void OnSavegameChanged(CartridgeSavegame cs)
 {
     if (cs == null)
     {
         Name      = null;
         HashColor = default(Color);
     }
     else
     {
         Name      = cs.Name;
         HashColor = cs.HashColor;
     }
 }
        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);
        }
        private void ExportSaveGame(CartridgeSavegame savegame)
        {
            // Opens a save file picker.
            FileSavePicker picker = new FileSavePicker();
            string         ext    = Path.GetExtension(savegame.SavegameFile);

            picker.DefaultFileExtension = ext;
            picker.FileTypeChoices.Add(String.Format("Wherigo Savegame ({0})", ext), new List <string>()
            {
                ext
            });
            picker.SuggestedFileName = Path.GetFileNameWithoutExtension(savegame.SavegameFile);
            picker.ContinuationData.Add(BaseViewModel.ContinuationOperationKey, ExportSavegameOperationValue);
            picker.ContinuationData.Add(ExportSavegameSourceFileKey, savegame.SavegameFile);
            picker.PickSaveFileAndContinue();
        }
        /// <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);
        }
        /// <summary>
        /// Exports a savegame to the isolated storage and adds it to this tag.
        /// </summary>
        /// <param name="cs">The savegame to add.</param>
        public void AddSavegame(CartridgeSavegame cs)
        {
            // Sanity check: a savegame with similar name should
            // not exist.
            CartridgeSavegame sameNameCS;

            if ((sameNameCS = Savegames.SingleOrDefault(c => c.Name == cs.Name)) != null)
            {
                System.Diagnostics.Debug.WriteLine("CartridgeTag: Removing savegame to make room for new one: " + sameNameCS.Name);

                // Removes the previous savegame that bears the same name.
                RemoveSavegame(sameNameCS);
            }

            // Makes sure the savegame is exported to the cache.
            cs.ExportToIsoStore();

            // Adds the savegame.
            savegames.Add(cs);

            // Notifies of a change.
            RaisePropertyChanged("Savegames");
        }
        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);
        }
Example #16
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);
 }
Example #17
0
 private void OnSavegameNameChanged(string newValue)
 {
     HashColor = CartridgeSavegame.GetHashColor(newValue ?? "");
 }
Example #18
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?
        }