Exemplo n.º 1
0
        private void NewCollection()
        {
            if (_collectionDirty &&
                MessageBox.Show("Your Creature Collection has been modified since it was last saved, " +
                                "are you sure you want to discard your changes and create a new Library without saving?",
                                "Discard Changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
            {
                return;
            }

            if (_creatureCollection.modIDs?.Any() ?? false)
            {
                // if old collection had additionalValues, load the original ones to reset all modded values
                var(statValuesLoaded, _) = LoadStatAndKibbleValues(applySettings: false);
                if (!statValuesLoaded)
                {
                    MessageBox.Show("Couldn't load stat values. Please redownload the application.", $"{Loc.S("error")} while loading the stat-values - {Utils.ApplicationNameVersion}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (_creatureCollection.serverMultipliers == null)
            {
                _creatureCollection.serverMultipliers = Values.V.serverMultipliersPresets.GetPreset(ServerMultipliersPresets.OFFICIAL);
            }
            // use previously used multipliers again in the new file
            ServerMultipliers oldMultipliers = _creatureCollection.serverMultipliers;

            _creatureCollection = new CreatureCollection
            {
                serverMultipliers = oldMultipliers,
                ModList           = new List <Mod>()
            };
            _creatureCollection.FormatVersion = CreatureCollection.CURRENT_FORMAT_VERSION;
            pedigree1.Clear();
            breedingPlan1.Clear();
            ApplySettingsToValues();
            InitializeCollection();

            UpdateCreatureListings();
            creatureBoxListView.Clear();
            Properties.Settings.Default.LastSaveFile = null;
            _currentFileName = null;
            _fileSync.ChangeFile(_currentFileName);
            SetCollectionChanged(false);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Import exported file. Used by a fileWatcher.
        /// </summary>
        /// <param name="filePath"></param>
        private void ImportExportedAddIfPossible(string filePath)
        {
            bool alreadyExists       = ExtractExportedFileInExtractor(filePath);
            bool added               = false;
            bool copyNameToClipboard = Properties.Settings.Default.copyNameToClipboardOnImportWhenAutoNameApplied &&
                                       (Properties.Settings.Default.applyNamePatternOnImportIfEmptyName ||
                                        (!alreadyExists && Properties.Settings.Default.applyNamePatternOnAutoImportForNewCreatures));
            Species species = speciesSelector1.SelectedSpecies;

            if (_extractor.uniqueResults ||
                (alreadyExists && _extractor.validResults))
            {
                AddCreatureToCollection(true, goToLibraryTab: false);
                SetMessageLabelText($"Successful {(alreadyExists ? "updated" : "added")} {creatureInfoInputExtractor.CreatureName} ({species.name}) of the exported file\n" + filePath, MessageBoxIcon.Information);
                added = true;
            }

            bool topLevels    = false;
            bool newTopLevels = false;

            // give feedback in overlay
            string    infoText;
            Color     textColor;
            const int colorSaturation = 200;

            if (added)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"{species.name} \"{creatureInfoInputExtractor.CreatureName}\" {(alreadyExists ? "updated in " : "added to")} the library.");
                if (copyNameToClipboard)
                {
                    sb.AppendLine("Name copied to clipboard.");
                }

                for (int s = 0; s < values.Values.STATS_COUNT; s++)
                {
                    int statIndex = values.Values.statsDisplayOrder[s];
                    if (!species.UsesStat(statIndex))
                    {
                        continue;
                    }

                    sb.Append($"{Utils.StatName(statIndex, true, species.IsGlowSpecies)}: {_statIOs[statIndex].LevelWild} ({_statIOs[statIndex].BreedingValue})");
                    if (_statIOs[statIndex].TopLevel == StatIOStatus.NewTopLevel)
                    {
                        sb.Append($" {Loc.S("newTopLevel")}");
                        newTopLevels = true;
                    }
                    else if (_statIOs[statIndex].TopLevel == StatIOStatus.TopLevel)
                    {
                        sb.Append($" {Loc.S("topLevel")}");
                        topLevels = true;
                    }
                    sb.AppendLine();
                }

                infoText  = sb.ToString();
                textColor = Color.FromArgb(colorSaturation, 255, colorSaturation);
            }
            else
            {
                infoText  = $"Creature \"{creatureInfoInputExtractor.CreatureName}\" couldn't be extracted uniquely, manual level selection is necessary.";
                textColor = Color.FromArgb(255, colorSaturation, colorSaturation);
            }

            if (_overlay != null)
            {
                _overlay.SetInfoText(infoText, textColor);
            }

            if (added)
            {
                if (Properties.Settings.Default.MoveAutoImportedFileToSubFolder)
                {
                    string importedPath = Path.Combine(Path.GetDirectoryName(filePath), "imported");
                    if (!FileService.TryCreateDirectory(importedPath, out string errorMessage))
                    {
                        MessageBox.Show($"Subfolder\n{importedPath}\ncould not be created.\n{errorMessage}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    FileService.TryMoveFile(filePath, Path.Combine(importedPath, Path.GetFileName(filePath)));
                }
                else if (Properties.Settings.Default.DeleteAutoImportedFile)
                {
                    FileService.TryDeleteFile(filePath);
                }
            }
            else if (copyNameToClipboard)
            {
                // extraction failed, user might expect the name of the new creature in the clipboard
                Clipboard.SetText("Automatic extraction was not possible");
            }

            if (Properties.Settings.Default.PlaySoundOnAutoImport)
            {
                if (added)
                {
                    if (newTopLevels)
                    {
                        Utils.BeepSignal(3);
                    }
                    else if (topLevels)
                    {
                        Utils.BeepSignal(2);
                    }
                    else
                    {
                        Utils.BeepSignal(1);
                    }
                }
                else
                {
                    Utils.BeepSignal(0);
                }
            }
        }
Exemplo n.º 3
0
        private void SaveCollectionToFileName(string filePath)
        {
            // remove expired timers if setting is set
            if (Properties.Settings.Default.DeleteExpiredTimersOnSaving)
            {
                timerList1.DeleteAllExpiredTimers(false, false);
            }

            // Wait until the file is writable
            const int numberOfRetries  = 5;
            const int delayOnRetryBase = 500;
            bool      fileSaved        = false;

            var tempSavePath = filePath + ".tmp";

            for (int i = 0; i < numberOfRetries; ++i)
            {
                try
                {
                    _fileSync.JustSaving();
                    using (StreamWriter file = File.CreateText(tempSavePath))
                    {
                        JsonSerializer serializer = new JsonSerializer()
                        {
                            Formatting           = Properties.Settings.Default.prettifyCollectionJson ? Formatting.Indented : Formatting.None,
                            DateTimeZoneHandling = DateTimeZoneHandling.Utc // save all date-times as UTC, so synced files don't change the timezones
                        };
                        serializer.Serialize(file, _creatureCollection);
                    }

                    if (new FileInfo(tempSavePath).Length == 0)
                    {
                        throw new IOException("Saved file is empty and contains no data.");
                    }

                    // if saving was successful, remove outdated library file and move successfully saved file
                    File.Delete(filePath);
                    File.Move(tempSavePath, filePath);

                    fileSaved = true;
                    Properties.Settings.Default.LastSaveFile = filePath;

                    break; // when file is saved, break
                }
                catch (IOException)
                {
                    // if file is not saveable wait a bit, each time longer
                    Thread.Sleep(delayOnRetryBase * (1 << i));
                }
                catch (System.Runtime.Serialization.SerializationException e)
                {
                    MessageBox.Show($"Error during serialization.\nErrormessage:\n\n{e.Message}" + (e.InnerException == null ? string.Empty : $"\n\nInnerException:{e.InnerException.Message}"),
                                    $"{Loc.S("error")} - {Utils.ApplicationNameVersion}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
                catch (InvalidOperationException e)
                {
                    MessageBox.Show($"Error during serialization.\nErrormessage:\n\n{e.Message}" + (e.InnerException == null ? string.Empty : $"\n\nInnerException:{e.InnerException.Message}"),
                                    $"{Loc.S("error")} - {Utils.ApplicationNameVersion}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }

            if (fileSaved)
            {
                SetCollectionChanged(false);
            }
            else
            {
                MessageBox.Show($"This file couldn\'t be saved:\n{filePath}\nMaybe the file is used by another application.", $"{Loc.S("error")} - {Utils.ApplicationNameVersion}", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Returns the formated timespan and also the DateTime when the timespan is over
 /// </summary>
 /// <param name="ts">timespan of countdown</param>
 /// <returns>Returns the timespan and the DateTime when the timespan is over</returns>
 public static string DurationUntil(TimeSpan ts)
 {
     return(ts.ToString("d':'hh':'mm':'ss") + " (" + Loc.S("until") + ": " + ShortTimeDate(DateTime.Now.Add(ts)) + ")");
 }
Exemplo n.º 5
0
        /// <summary>
        /// Imports the creatures from the given saveGame. ftp is possible.
        /// </summary>
        /// <returns>null on success, else an error message to show, or an empty string if the error was already displayed.</returns>
        private async Task <string> RunSavegameImport(ATImportFileLocation atImportFileLocation)
        {
            TsbQuickSaveGameImport.Enabled     = false;
            TsbQuickSaveGameImport.BackColor   = Color.Yellow;
            ToolStripStatusLabelImport.Text    = $"{Loc.S("ImportingSavegame")} {atImportFileLocation.ConvenientName}";
            ToolStripStatusLabelImport.Visible = true;

            try
            {
                string workingCopyFolderPath = Properties.Settings.Default.savegameExtractionPath;
                string workingCopyFilePath;

                // working dir not configured? use temp dir
                // luser configured savegame folder as working dir? use temp dir instead
                if (string.IsNullOrWhiteSpace(workingCopyFolderPath) ||
                    Path.GetDirectoryName(atImportFileLocation.FileLocation) == workingCopyFolderPath)
                {
                    workingCopyFolderPath = Path.GetTempPath();
                }


                if (Uri.TryCreate(atImportFileLocation.FileLocation, UriKind.Absolute, out var uri) &&
                    uri.Scheme != "file")
                {
                    switch (uri.Scheme)
                    {
                    case "ftp":
                        workingCopyFilePath = await CopyFtpFileAsync(uri, atImportFileLocation.ConvenientName,
                                                                     workingCopyFolderPath);

                        if (workingCopyFilePath == null)
                        {
                            // the user didn't enter credentials
                            return("no credentials");
                        }
                        break;

                    default:
                        throw new Exception($"Unsupported uri scheme: {uri.Scheme}");
                    }
                }
                else
                {
                    if (!File.Exists(atImportFileLocation.FileLocation))
                    {
                        return($"File not found: {atImportFileLocation.FileLocation}");
                    }

                    workingCopyFilePath = Path.Combine(workingCopyFolderPath,
                                                       Path.GetFileName(atImportFileLocation.FileLocation));
                    try
                    {
                        File.Copy(atImportFileLocation.FileLocation, workingCopyFilePath, true);
                    }
                    catch (Exception ex)
                    {
                        MessageBoxes.ExceptionMessageBox(ex, $"Error while copying the save game file to the working directory\n{workingCopyFolderPath}\nIt's recommended to leave the setting for the working folder empty.");
                        return(string.Empty);
                    }
                }

                await ImportSavegame.ImportCollectionFromSavegame(_creatureCollection, workingCopyFilePath,
                                                                  atImportFileLocation.ServerName);

                FileService.TryDeleteFile(workingCopyFilePath);

                UpdateParents(_creatureCollection.creatures);

                foreach (var creature in _creatureCollection.creatures)
                {
                    creature.RecalculateAncestorGenerations();
                }

                UpdateIncubationParents(_creatureCollection);

                // update UI
                SetCollectionChanged(true);
                UpdateCreatureListings();

                if (_creatureCollection.creatures.Any())
                {
                    tabControlMain.SelectedTab = tabPageLibrary;
                }

                // reapply last sorting
                listViewLibrary.Sort();

                UpdateTempCreatureDropDown();

                // if unknown mods are used in the savegame-file and the user wants to load the missing mod-files, do it
                if (_creatureCollection.ModValueReloadNeeded &&
                    LoadModValuesOfCollection(_creatureCollection, true, true))
                {
                    SetCollectionChanged(true);
                }
            }
            catch (Exception ex)
            {
                MessageBoxes.ExceptionMessageBox(ex, $"An error occurred while importing the file {atImportFileLocation.FileLocation}.", "Save file import error");
                return(string.Empty);
            }
            finally
            {
                TsbQuickSaveGameImport.Enabled     = true;
                TsbQuickSaveGameImport.BackColor   = SystemColors.Control;
                ToolStripStatusLabelImport.Visible = false;
            }

            return(null); // no error
        }
Exemplo n.º 6
0
        private void setLocalizations(bool init = true)
        {
            if (init)
            {
                initLocalization();
            }

            // menu
            Loc.ControlText(fileToolStripMenuItem);
            Loc.ControlText(newToolStripMenuItem);
            Loc.ControlText(loadToolStripMenuItem);
            Loc.ControlText(loadAndAddToolStripMenuItem);
            Loc.ControlText(saveToolStripMenuItem);
            Loc.ControlText(saveAsToolStripMenuItem);
            Loc.ControlText(importingFromSavegameToolStripMenuItem);
            Loc.ControlText(importingFromSavegameEmptyToolStripMenuItem);
            //Loc.ControlText(runDefaultExtractionAndImportFileToolStripMenuItem);
            //Loc.ControlText(runDefaultExtractionToolStripMenuItem);
            //Loc.ControlText(importCreatedJsonfileToolStripMenuItem);
            Loc.ControlText(importExportedCreaturesToolStripMenuItem);
            //Loc.ControlText(runDefaultExtractionAndImportFileToolStripMenuItem);
            //Loc.ControlText(runDefaultExtractionToolStripMenuItem);
            //Loc.ControlText(importCreatedJsonfileToolStripMenuItem);
            Loc.ControlText(modValueManagerToolStripMenuItem);
            Loc.ControlText(settingsToolStripMenuItem);
            Loc.ControlText(openSettingsToolStripMenuItem);
            Loc.ControlText(quitToolStripMenuItem);
            Loc.ControlText(editToolStripMenuItem);
            Loc.ControlText(exportValuesToClipboardToolStripMenuItem);
            Loc.ControlText(importValuesFromClipboardToolStripMenuItem);
            Loc.ControlText(setStatusToolStripMenuItem);
            Loc.ControlText(multiSetterToolStripMenuItem);
            Loc.ControlText(deleteSelectedToolStripMenuItem);
            Loc.ControlText(findDuplicatesToolStripMenuItem);
            Loc.ControlText(copyCreatureToolStripMenuItem);
            Loc.ControlText(pasteCreatureToolStripMenuItem);
            Loc.ControlText(libraryFilterToolStripMenuItem);
            Loc.ControlText(helpToolStripMenuItem);
            Loc.ControlText(aboutToolStripMenuItem);
            Loc.ControlText(onlinehelpToolStripMenuItem);
            Loc.ControlText(BreedingPlanHelpToolStripMenuItem);
            Loc.ControlText(extractionIssuesToolStripMenuItem);
            Loc.ControlText(checkForUpdatedStatsToolStripMenuItem);
            Loc.ControlText(toolStripButtonCopy2Tester);
            Loc.ControlText(toolStripButtonCopy2Extractor);
            Loc.ControlText(toolStripButtonClear);
            Loc.ControlText(toolStripButtonAddNote);
            Loc.ControlText(toolStripButtonRemoveNote);
            Loc.ControlText(toolStripButtonDeleteExpiredIncubationTimers);
            Loc.ControlText(toolStripButtonSaveCreatureValuesTemp);
            Loc.ControlText(toolStripButtonDeleteTempCreature);
            Loc.ControlText(tsBtAddAsExtractionTest);
            Loc.ControlText(copyToMultiplierTesterToolStripButton);

            // top bar
            Loc.ControlText(cbEventMultipliers, "Event");
            Loc.ControlText(cbGuessSpecies, _tt);
            Loc.ControlText(btReadValuesFromArk, _tt);
            Loc.ControlText(btImportLastExported, _tt);
            Loc.ControlText(cbToggleOverlay);

            // tester
            Loc.ControlText(tabPageStatTesting, "statTesting");
            Loc.ControlText(rbWildTester, "wild");
            Loc.ControlText(rbTamedTester, "tamed");
            Loc.ControlText(rbBredTester, "bred");
            Loc.ControlText(lbTesterWildLevel, "wildLvl");
            Loc.ControlText(lbTesterDomLevel, "domLvl");
            Loc.ControlText(lbCurrentValue, "currentValue");
            Loc.ControlText(lbBreedingValueTester, "breedingValue");
            Loc.ControlText(lbNotYetTamed);
            Loc.ControlText(gpPreviewEdit);
            Loc.ControlText(lbTestingInfo);
            Loc.ControlText(gbStatChart, "statChart");
            Loc.ControlText(lbCurrentCreature, "CurrentCreature");
            Loc.SetToolTip(lbImprintedCount, _tt);
            Loc.SetToolTip(lbTesterDomLevel, "domLevelExplanation", _tt);
            Loc.SetToolTip(lbTesterWildLevel, "wildLevelExplanation", _tt);

            // extractor
            Loc.ControlText(tabPageExtractor, "extractor");
            Loc.ControlText(lbCurrentStatEx, "currentStatValue");
            Loc.ControlText(lbExtractorWildLevel, "wildLvl");
            Loc.ControlText(lbExtractorDomLevel, "domLvl");
            Loc.ControlText(lbSum);
            Loc.ControlText(lbShouldBe);
            Loc.ControlText(lbImprintingFailInfo);
            Loc.ControlText(cbExactlyImprinting, _tt);
            Loc.ControlText(btExtractLevels);
            Loc.ControlText(cbQuickWildCheck, _tt);
            Loc.ControlText(rbWildExtractor, "wild");
            Loc.ControlText(rbTamedExtractor, "tamed");
            Loc.ControlText(rbBredExtractor, "bred");
            Loc.SetToolTip(lbImprintingCuddleCountExtractor, _tt);
            Loc.SetToolTip(lbSumWild, _tt);
            Loc.SetToolTip(lbSumDom, _tt);
            Loc.SetToolTip(lbSumDomSB, _tt);
            Loc.SetToolTip(lbListening, _tt);
            Loc.SetToolTip(lbExtractorDomLevel, "domLevelExplanation", _tt);
            Loc.SetToolTip(lbExtractorWildLevel, "wildLevelExplanation", _tt);
            var statNames = speciesSelector1.SelectedSpecies?.statNames;

            for (int si = 0; si < _statIOs.Count; si++)
            {
                _statIOs[si].Title    = Utils.StatName(si, false, statNames);
                _testingIOs[si].Title = Utils.StatName(si, false, statNames);
            }
            parentInheritanceExtractor.SetLocalizations();

            // library
            Loc.ControlText(tabPageLibrary, "library");
            columnHeaderName.Text       = Loc.S("Name");
            columnHeaderOwner.Text      = Loc.S("Owner");
            columnHeaderTribe.Text      = Loc.S("Tribe");
            columnHeaderNote.Text       = Loc.S("Note");
            columnHeaderServer.Text     = Loc.S("Server");
            columnHeaderHP.Text         = Utils.StatName(StatNames.Health, true);
            columnHeaderSt.Text         = Utils.StatName(StatNames.Stamina, true);
            columnHeaderOx.Text         = Utils.StatName(StatNames.Oxygen, true);
            columnHeaderFo.Text         = Utils.StatName(StatNames.Food, true);
            columnHeaderWe.Text         = Utils.StatName(StatNames.Weight, true);
            columnHeaderDm.Text         = Utils.StatName(StatNames.MeleeDamageMultiplier, true);
            columnHeaderSp.Text         = Utils.StatName(StatNames.SpeedMultiplier, true);
            columnHeaderTo.Text         = Utils.StatName(StatNames.Torpidity, true);
            columnHeaderWa.Text         = Utils.StatName(StatNames.CraftingSpeedMultiplier, true);
            columnHeaderTemp.Text       = Utils.StatName(StatNames.Temperature, true);
            columnHeaderCr.Text         = Utils.StatName(StatNames.Water, true);
            columnHeaderFr.Text         = Utils.StatName(StatNames.TemperatureFortitude, true);
            columnHeaderTopStatsNr.Text = Loc.S("Top");
            columnHeaderTopness.Text    = Loc.S("topPercentage");
            columnHeaderGen.Text        = Loc.S("Generation_Abb");
            columnHeaderLW.Text         = Loc.S("LevelWild_Abb");
            columnHeaderMutations.Text  = Loc.S("Mutations_Abb");
            columnHeaderAdded.Text      = Loc.S("added");
            columnHeaderCooldown.Text   = Loc.S("cooldownGrowing");
            columnHeaderColor0.Text     = Loc.S("C0");
            columnHeaderColor1.Text     = Loc.S("C1");
            columnHeaderColor2.Text     = Loc.S("C2");
            columnHeaderColor3.Text     = Loc.S("C3");
            columnHeaderColor4.Text     = Loc.S("C4");
            columnHeaderColor5.Text     = Loc.S("C5");

            // other tabs
            Loc.ControlText(tabPagePedigree, "pedigree");
            Loc.ControlText(tabPageTaming, "Taming");
            Loc.ControlText(tabPageBreedingPlan, "BreedingPlan");
            Loc.ControlText(tabPageRaising, "Raising");
            Loc.ControlText(tabPagePlayerTribes, "Player");

            // other controls
            creatureInfoInputTester.SetLocalizations();
            creatureInfoInputExtractor.SetLocalizations();
            pedigree1.SetLocalizations();
            tamingControl1.SetLocalizations();
            breedingPlan1.SetLocalizations();
            raisingControl1.SetLocalizations();
            _overlay?.SetLocatlizations();
        }
Exemplo n.º 7
0
 public static void InitializeLocalizations()
 {
     _statNames    = new[] { Loc.S("Health"), Loc.S("Stamina"), Loc.S("Torpidity"), Loc.S("Oxygen"), Loc.S("Food"), Loc.S("Water"), Loc.S("Temperature"), Loc.S("Weight"), Loc.S("Damage"), Loc.S("Speed"), Loc.S("Fortitude"), Loc.S("Crafting Speed") };
     _statNamesAbb = new[] { Loc.S("Health_Abb"), Loc.S("Stamina_Abb"), Loc.S("Torpidity_Abb"), Loc.S("Oxygen_Abb"), Loc.S("Food_Abb"), Loc.S("Water_Abb"), Loc.S("Temperature_Abb"), Loc.S("Weight_Abb"), Loc.S("Damage_Abb"), Loc.S("Speed_Abb"), Loc.S("Fortitude_Abb"), Loc.S("Crafting Speed_Abb") };
 }
Exemplo n.º 8
0
        private ListViewItem CreateLvi(string name, TimerListEntry tle)
        {
            // check if group of timers exists
            ListViewGroup g = null;

            foreach (ListViewGroup lvg in listViewTimer.Groups)
            {
                if (lvg.Header == tle.group)
                {
                    g = lvg;
                    break;
                }
            }
            if (g == null)
            {
                g = new ListViewGroup(tle.group);
                listViewTimer.Groups.Add(g);
            }
            ListViewItem lvi = new ListViewItem(new[] { name, tle.timerIsRunning ? tle.time.ToString() : Loc.S("paused"), string.Empty }, g)
            {
                Tag     = tle,
                Checked = Properties.Settings.Default.DisplayTimersInOverlayAutomatically
            };

            return(lvi);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new collection.
        /// </summary>
        /// <param name="resetCollection">If true, the user is not asked and a new collection is created. This can be used if something went wrong while loading a file and a clean collection is needed.</param>
        private void NewCollection(bool resetCollection = false)
        {
            if (!resetCollection &&
                _collectionDirty &&
                CustomMessageBox.Show(Loc.S("Collection changed discard and new?"),
                                      Loc.S("Discard changes?"), Loc.S("Discard changes and new"), buttonCancel: Loc.S("Cancel"), icon: MessageBoxIcon.Warning) != DialogResult.Yes
                )
            {
                return;
            }

            if (_creatureCollection.modIDs?.Any() ?? false)
            {
                // if old collection had additionalValues, load the original ones to reset all modded values
                var(statValuesLoaded, _) = LoadStatAndKibbleValues(applySettings: false);
                if (!statValuesLoaded)
                {
                    MessageBoxes.ShowMessageBox("Couldn't load stat values. Please redownload the application.", $"{Loc.S("error")} while loading the stat-values");
                }
            }

            if (_creatureCollection.serverMultipliers == null)
            {
                _creatureCollection.serverMultipliers = Values.V.serverMultipliersPresets.GetPreset(ServerMultipliersPresets.Official);
            }
            // use previously used multipliers again in the new file
            ServerMultipliers oldMultipliers = _creatureCollection.serverMultipliers;

            _creatureCollection = new CreatureCollection
            {
                serverMultipliers = oldMultipliers,
                ModList           = new List <Mod>()
            };
            pedigree1.Clear();
            breedingPlan1.Clear();
            creatureInfoInputExtractor.Clear(true);
            creatureInfoInputTester.Clear(true);
            ApplySettingsToValues();
            InitializeCollection();

            UpdateCreatureListings();
            creatureBoxListView.Clear();
            Properties.Settings.Default.LastSaveFile = null;
            _currentFileName = null;
            _fileSync.ChangeFile(_currentFileName);
            SetCollectionChanged(false);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Returns true if there are no unsaved changes or the user wants to discard the changes of the currently loaded library.
 /// </summary>
 private bool DiscardChangesAndLoadNewLibrary()
 {
     return(!_collectionDirty ||
            CustomMessageBox.Show(Loc.S("Collection changed discard and load?"),
                                  Loc.S("Discard changes?"), Loc.S("Discard changes and load file"), buttonCancel: Loc.S("Cancel"), icon: MessageBoxIcon.Warning) == DialogResult.Yes);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Imports the creatures from the given savegame. ftp is possible.
        /// </summary>
        /// <param name="atImportFileLocation"></param>
        private async void RunSavegameImport(ATImportFileLocation atImportFileLocation)
        {
            TsbImportLastSaveGame.Enabled      = false;
            TsbImportLastSaveGame.BackColor    = Color.Yellow;
            ToolStripStatusLabelImport.Text    = $"{Loc.S("ImportingSavegame")} {atImportFileLocation.ConvenientName}";
            ToolStripStatusLabelImport.Visible = true;
            try
            {
                string workingCopyfilename = Properties.Settings.Default.savegameExtractionPath;

                // working dir not configured? use temp dir
                // luser configured savegame folder as working dir? use temp dir instead
                if (string.IsNullOrWhiteSpace(workingCopyfilename) ||
                    Path.GetDirectoryName(atImportFileLocation.FileLocation) == workingCopyfilename)
                {
                    workingCopyfilename = Path.GetTempPath();
                }


                if (Uri.TryCreate(atImportFileLocation.FileLocation, UriKind.Absolute, out var uri) &&
                    uri.Scheme != "file")
                {
                    switch (uri.Scheme)
                    {
                    case "ftp":
                        workingCopyfilename = await CopyFtpFileAsync(uri, atImportFileLocation.ConvenientName,
                                                                     workingCopyfilename);

                        if (workingCopyfilename == null)
                        {
                            // the user didn't enter credentials
                            return;
                        }
                        break;

                    default:
                        throw new Exception($"Unsupported uri scheme: {uri.Scheme}");
                    }
                }
                else
                {
                    workingCopyfilename = Path.Combine(workingCopyfilename,
                                                       Path.GetFileName(atImportFileLocation.FileLocation));
                    File.Copy(atImportFileLocation.FileLocation, workingCopyfilename, true);
                }

                await ImportSavegame.ImportCollectionFromSavegame(_creatureCollection, workingCopyfilename,
                                                                  atImportFileLocation.ServerName);

                UpdateParents(_creatureCollection.creatures);

                foreach (var creature in _creatureCollection.creatures)
                {
                    creature.RecalculateAncestorGenerations();
                }

                UpdateIncubationParents(_creatureCollection);

                // update UI
                SetCollectionChanged(true);
                UpdateCreatureListings();

                if (_creatureCollection.creatures.Any())
                {
                    tabControlMain.SelectedTab = tabPageLibrary;
                }

                // reapply last sorting
                listViewLibrary.Sort();

                UpdateTempCreatureDropDown();

                // if unknown mods are used in the savegame-file and the user wants to load the missing mod-files, do it
                if (_creatureCollection.ModValueReloadNeeded &&
                    LoadModValuesOfCollection(_creatureCollection, true, true))
                {
                    SetCollectionChanged(true);
                }

                Properties.Settings.Default.LastImportedSaveGame = atImportFileLocation.ToString();
                TsbImportLastSaveGame.ToolTipText = $"Import savegame {atImportFileLocation.ConvenientName}";
            }
            catch (Exception ex)
            {
                string message = ex.Message
                                 + "\n\nException in " + ex.Source
                                 + "\n\nMethod throwing the error: " + ex.TargetSite.DeclaringType.FullName + "." +
                                 ex.TargetSite.Name
                                 + "\n\nStackTrace:\n" + ex.StackTrace
                                 + (ex.InnerException != null
                                     ? "\n\nInner Exception:\n" + ex.InnerException.Message
                                     : string.Empty)
                ;
                MessageBox.Show($"An error occured while importing. Message: \n\n{message}",
                                "Import Error", MessageBoxButtons.OK);
            }
            finally
            {
                TsbImportLastSaveGame.Enabled      = true;
                TsbImportLastSaveGame.BackColor    = SystemColors.Control;
                ToolStripStatusLabelImport.Visible = false;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// This displays the sum of the chosen levels. This is the last step before a creature-extraction is considered as valid or not valid.
        /// </summary>
        private void ShowSumOfChosenLevels()
        {
            // The speedLevel is not chosen, but calculated from the other chosen levels, and must not be included in the sum, except all the other levels are determined uniquely!

            // this method will show only the offset of the value, it's less confusing to the user and gives all the infos needed
            int  sumW = 0, sumD = 0;
            bool valid = true, inbound = true, allUnique = true;

            for (int s = 0; s < Values.STATS_COUNT; s++)
            {
                if (s == (int)StatNames.Torpidity)
                {
                    continue;
                }
                if (_extractor.Results[s].Count > _extractor.ChosenResults[s])
                {
                    sumW += _statIOs[s].LevelWild > 0 ? _statIOs[s].LevelWild : 0;
                    sumD += _statIOs[s].LevelDom;
                    if (_extractor.Results[s].Count != 1)
                    {
                        allUnique = false;
                    }
                }
                else
                {
                    valid = false;
                    break;
                }
                _statIOs[s].TopLevel = StatIOStatus.Neutral;
            }
            if (valid)
            {
                sumW -= allUnique || _statIOs[(int)StatNames.SpeedMultiplier].LevelWild < 0 ? 0 : _statIOs[(int)StatNames.SpeedMultiplier].LevelWild;
                string offSetWild = "✓";
                lbSumDom.Text = sumD.ToString();
                if (sumW <= _extractor.LevelWildSum)
                {
                    lbSumWild.ForeColor = SystemColors.ControlText;
                }
                else
                {
                    lbSumWild.ForeColor = Color.Red;
                    offSetWild          = "+" + (sumW - _extractor.LevelWildSum);
                    inbound             = false;
                }
                if (sumD == _extractor.LevelDomSum)
                {
                    lbSumDom.ForeColor = SystemColors.ControlText;
                }
                else
                {
                    lbSumDom.ForeColor = Color.Red;
                    inbound            = false;
                    // if there are no other combination options, the total level may be wrong
                    if (_extractor.UniqueResults)
                    {
                        numericUpDownLevel.BackColor = Color.LightSalmon;
                    }
                }
                lbSumWild.Text = offSetWild;
            }
            else
            {
                lbSumWild.Text = Loc.S("na");
                lbSumDom.Text  = Loc.S("na");
            }
            panelSums.BackColor = inbound ? SystemColors.Control : Color.FromArgb(255, 200, 200);

            bool torporLevelValid = numericUpDownLevel.Value > _statIOs[(int)StatNames.Torpidity].LevelWild;

            if (!torporLevelValid)
            {
                numericUpDownLevel.BackColor = Color.LightSalmon;
                _statIOs[(int)StatNames.Torpidity].Status = StatIOStatus.Error;
            }

            bool allValid = valid && inbound && torporLevelValid && _extractor.ValidResults;

            if (allValid)
            {
                radarChartExtractor.SetLevels(_statIOs.Select(s => s.LevelWild).ToArray());
                toolStripButtonSaveCreatureValuesTemp.Visible = false;
                cbExactlyImprinting.BackColor = Color.Transparent;
                if (_topLevels.TryGetValue(speciesSelector1.SelectedSpecies, out int[] topSpeciesLevels))