private ObservableCollection <StatisticsBuilding> GetStatisticBuildings(IEnumerable <IGrouping <string, LayoutObject> > groupedBuildingsByIdentifier, BuildingPresets buildingPresets)
        {
            if (groupedBuildingsByIdentifier is null || !groupedBuildingsByIdentifier.Any())
            {
                return(new ObservableCollection <StatisticsBuilding>());
            }

            var tempList = new List <StatisticsBuilding>();

            var validBuildingsGrouped = groupedBuildingsByIdentifier
                                        .Where(_ => !_.ElementAt(0).WrappedAnnoObject.Road&& _.ElementAt(0).Identifier != null)
                                        .Where(x => x.AsEnumerable().WithoutIgnoredObjects().Count() > 0)
                                        .OrderByDescending(_ => _.Count());

            foreach (var item in validBuildingsGrouped)
            {
                var statisticBuilding = new StatisticsBuilding();

                var identifierToCheck = item.ElementAt(0).Identifier;
                if (!string.IsNullOrWhiteSpace(identifierToCheck))
                {
                    //try to find building in presets by identifier
                    if (!_cachedPresetsBuilding.TryGetValue(identifierToCheck, out var building))
                    {
                        building = buildingPresets.Buildings.Find(_ => string.Equals(_.Identifier, identifierToCheck, StringComparison.OrdinalIgnoreCase));
                        _cachedPresetsBuilding.TryAdd(identifierToCheck, building);
                    }

                    var isUnknownObject = string.Equals(identifierToCheck, "Unknown Object", StringComparison.OrdinalIgnoreCase);
                    if (building != null || isUnknownObject)
                    {
                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name  = isUnknownObject ? _localizationHelper.GetLocalization("UnknownObject") : building.Localization[_commons.CurrentLanguageCode];
                    }
                    else
                    {
                        /// Ruled those 2 out to keep Building Name Changes done through the Labeling of the building
                        /// and when the building is not in the preset. Those statisticBuildings.name will not translated to
                        /// other luangages anymore, as users can give there own names.
                        /// However i made it so, that if localizations get those translations, it will translated.
                        /// 06-02-2021, on request of user(s) on Discord read this on
                        /// https://discord.com/channels/571011757317947406/571011757317947410/800118895855665203
                        //item.ElementAt(0).Identifier = "";
                        //statisticBuilding.Name = _localizationHelper.GetLocalization("StatNameNotFound");

                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name  = _localizationHelper.GetLocalization(item.ElementAt(0).Identifier);
                    }
                }
                else
                {
                    statisticBuilding.Count = item.Count();
                    statisticBuilding.Name  = _localizationHelper.GetLocalization("StatNameNotFound");
                }

                tempList.Add(statisticBuilding);
            }

            return(new ObservableCollection <StatisticsBuilding>(tempList.OrderByDescending(x => x.Count).ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase)));
        }
예제 #2
0
 private void ExecuteResetHotkeys(object param)
 {
     if (_messageBoxService.ShowQuestion(_localizationHelper.GetLocalization(RESET_ALL_CONFIRMATION_MESSAGE),
                                         _localizationHelper.GetLocalization(RESET_ALL)))
     {
         HotkeyCommandManager.ResetHotkeys();
     }
 }
예제 #3
0
 private void InitBuildingInfluences()
 {
     foreach (BuildingInfluenceType curInfluenceType in Enum.GetValues(typeof(BuildingInfluenceType)))
     {
         BuildingInfluences.Add(new BuildingInfluence
         {
             Name = _localizationHelper.GetLocalization(curInfluenceType.ToString()),
             Type = curInfluenceType
         });
     }
 }
        private ObservableCollection <StatisticsBuilding> GetStatisticBuildings(IEnumerable <IGrouping <string, LayoutObject> > groupedBuildingsByIdentifier, BuildingPresets buildingPresets)
        {
            if (groupedBuildingsByIdentifier is null || !groupedBuildingsByIdentifier.Any())
            {
                return(new ObservableCollection <StatisticsBuilding>());
            }

            var tempList = new List <StatisticsBuilding>();

            var validBuildingsGrouped = groupedBuildingsByIdentifier
                                        .Where(_ => !_.ElementAt(0).WrappedAnnoObject.Road&& _.ElementAt(0).Identifier != null)
                                        .OrderByDescending(_ => _.Count());

            foreach (var item in validBuildingsGrouped)
            {
                var statisticBuilding = new StatisticsBuilding();

                var identifierToCheck = item.ElementAt(0).Identifier;
                if (!string.IsNullOrWhiteSpace(identifierToCheck))
                {
                    //try to find building in presets by identifier
                    if (!_cachedPresetsBuilding.TryGetValue(identifierToCheck, out var building))
                    {
                        building = buildingPresets.Buildings.Find(_ => string.Equals(_.Identifier, identifierToCheck, StringComparison.OrdinalIgnoreCase));
                        _cachedPresetsBuilding.Add(identifierToCheck, building);
                    }

                    var isUnknownObject = string.Equals(identifierToCheck, "Unknown Object", StringComparison.OrdinalIgnoreCase);
                    if (building != null || isUnknownObject)
                    {
                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name  = isUnknownObject ? _localizationHelper.GetLocalization("UnknownObject") : building.Localization[_commons.CurrentLanguageCode];
                    }
                    else
                    {
                        item.ElementAt(0).Identifier = "";

                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name  = _localizationHelper.GetLocalization("StatNameNotFound");
                    }
                }
                else
                {
                    statisticBuilding.Count = item.Count();
                    statisticBuilding.Name  = _localizationHelper.GetLocalization("StatNameNotFound");
                }

                tempList.Add(statisticBuilding);
            }

            return(new ObservableCollection <StatisticsBuilding>(tempList.OrderByDescending(x => x.Count).ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase)));
        }
예제 #5
0
 /// <summary>
 /// Registers a <see cref="Hotkey"/> with the hotkey manager.
 /// </summary>
 /// <param name="hotkey"></param>
 public void AddHotkey(Hotkey hotkey)
 {
     if (!hotkeys.ContainsKey(hotkey.HotkeyId))
     {
         hotkey.PropertyChanged += Hotkey_PropertyChanged;
         hotkeys.Add(hotkey.HotkeyId, hotkey);
         _observableCollection.Add(hotkey);
         //Check for localization
         hotkey.Description = _localizationHelper.GetLocalization(hotkey.LocalizationKey);
         CheckHotkeyUserMappings();
     }
     else
     {
         throw new ArgumentException($"Key {hotkey.HotkeyId} already exists in collection.", "hotkey");
     }
 }
예제 #6
0
        public string DisplayName()
        {
            if (_localizationHelper is null)
            {
                return(Type.ToString());
            }

            return(_localizationHelper.GetLocalization("ColorType" + Type.ToString()));
        }
예제 #7
0
        public async Task ReplaceUpdatedPresetsFilesAsync()
        {
            try
            {
                await Task.Run(async() =>
                {
                    foreach (ReleaseType curReleaseType in Enum.GetValues(typeof(ReleaseType)))
                    {
                        var pathToUpdatedPresetsFile = GetPathToUpdatedPresetsFile(curReleaseType);
                        if (string.IsNullOrWhiteSpace(pathToUpdatedPresetsFile) || !File.Exists(pathToUpdatedPresetsFile))
                        {
                            continue;
                        }

                        logger.Debug($"Start replacing presets with update: {pathToUpdatedPresetsFile}");

                        if (curReleaseType == ReleaseType.PresetsAndIcons)
                        {
                            using (var archive = ZipFile.OpenRead(pathToUpdatedPresetsFile))
                            {
                                foreach (var curEntry in archive.Entries)
                                {
                                    var destinationPath      = Path.Combine(Path.GetDirectoryName(pathToUpdatedPresetsFile), curEntry.FullName);
                                    var destinationDirectory = Path.GetDirectoryName(destinationPath);

                                    if (!Directory.Exists(destinationDirectory))
                                    {
                                        Directory.CreateDirectory(destinationDirectory);
                                    }

                                    if (File.Exists(destinationPath))
                                    {
                                        FileHelper.ResetFileAttributes(destinationPath);
                                    }

                                    //Sometimes an entry has no name. (Temporary file? Directory?)
                                    if (!string.IsNullOrWhiteSpace(curEntry.Name))
                                    {
                                        curEntry.ExtractToFile(destinationPath, true);
                                    }
                                }
                            }

                            //wait extra time for extraction to finish (sometimes the disk needs extra time)
                            await Task.Delay(TimeSpan.FromMilliseconds(200));

                            File.Delete(pathToUpdatedPresetsFile);

                            logger.Debug("Finished extracting updated presets file.");

                            continue;
                        }

                        var originalPresetsFileName   = Path.GetFileName(pathToUpdatedPresetsFile).Replace(CoreConstants.PrefixUpdatedPresetsFile, string.Empty);
                        var pathToOriginalPresetsFile = Path.Combine(Path.GetDirectoryName(pathToUpdatedPresetsFile), originalPresetsFileName);
                        if (File.Exists(pathToOriginalPresetsFile))
                        {
                            FileHelper.ResetFileAttributes(pathToOriginalPresetsFile);
                            File.Delete(pathToOriginalPresetsFile);
                        }

                        File.Move(pathToUpdatedPresetsFile, pathToOriginalPresetsFile);

                        logger.Debug("Finished replacing presets with update.");
                    }
                });
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error replacing updated presets file.");

                _messageBoxService.ShowError(_localizationHelper.GetLocalization("UpdateErrorPresetMessage"),
                                             _localizationHelper.GetLocalization("Error"));
            }
        }
예제 #8
0
        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            // retrieve file argument if given
            if (e.Args.Length > 0)
            {
                if (!e.Args[0].Equals(Constants.Argument_Ask_For_Admin, StringComparison.OrdinalIgnoreCase))
                {
                    FilenameArgument = e.Args[0];
                }
            }

            using var mutexAnnoDesigner = new Mutex(true, MutexHelper.MUTEX_ANNO_DESIGNER, out var createdNewMutex);
            //Are there other processes still running?
            if (!createdNewMutex)
            {
                try
                {
                    var       currentTry = 0;
                    const int maxTrys    = 10;
                    while (!createdNewMutex && currentTry < maxTrys)
                    {
                        logger.Trace($"Waiting for other processes to finish. Try {currentTry} of {maxTrys}");

                        createdNewMutex = mutexAnnoDesigner.WaitOne(TimeSpan.FromSeconds(1), true);
                        currentTry++;
                    }

                    if (!createdNewMutex)
                    {
                        _messageBoxService.ShowMessage(Localization.Localization.Instance.GetLocalization("AnotherInstanceIsAlreadyRunning"));
                        Environment.Exit(-1);
                    }
                }
                catch (AbandonedMutexException)
                {
                    //mutex was killed
                    createdNewMutex = true;
                }
            }

            try
            {
                //check if file is not corrupt
                _appSettings.Reload();

                if (_appSettings.SettingsUpgradeNeeded)
                {
                    _appSettings.Upgrade();
                    _appSettings.SettingsUpgradeNeeded = false;
                    _appSettings.Save();
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                logger.Error(ex, "Error upgrading settings.");

                _messageBoxService.ShowError(_localizationHelper.GetLocalization("ErrorUpgradingSettings"));

                var fileName = "";
                if (!string.IsNullOrEmpty(ex.Filename))
                {
                    fileName = ex.Filename;
                }
                else
                {
                    if (ex.InnerException is ConfigurationErrorsException innerException && !string.IsNullOrEmpty(innerException.Filename))
                    {
                        fileName = innerException.Filename;
                    }
                }

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                _appSettings.Reload();
            }

            //var updateWindow = new UpdateWindow();
            await _updateHelper.ReplaceUpdatedPresetsFilesAsync();

            var recentFilesSerializer = new RecentFilesAppSettingsSerializer(_appSettings);

            IRecentFilesHelper recentFilesHelper = new RecentFilesHelper(recentFilesSerializer, _fileSystem);
            var mainVM = new MainViewModel(_commons, _appSettings, recentFilesHelper, _messageBoxService, _updateHelper, _localizationHelper, _fileSystem);

            //TODO MainWindow.ctor calls AnnoCanvas.ctor loads presets -> change logic when to load data
            MainWindow             = new MainWindow(_appSettings);
            MainWindow.DataContext = mainVM;

            //If language is not recognized, bring up the language selection screen
            if (!_commons.LanguageCodeMap.ContainsKey(_appSettings.SelectedLanguage))
            {
                var w = new Welcome();
                w.DataContext = mainVM.WelcomeViewModel;
                w.ShowDialog();
            }
            else
            {
                _commons.CurrentLanguage = _appSettings.SelectedLanguage;
            }

            MainWindow.ShowDialog();
        }
        public void LoadItems(BuildingPresets buildingPresets)
        {
            if (buildingPresets == null)
            {
                throw new ArgumentNullException(nameof(buildingPresets));
            }

            BuildingPresetsVersion = buildingPresets.Version;

#if DEBUG
            Stopwatch sw = new Stopwatch();
            sw.Start();
#endif

            Items.Clear();

            //manually add roads
            var roadTiles = GetRoadTiles();
            foreach (var curRoad in roadTiles)
            {
                Items.Add(curRoad);
            }

            if (!buildingPresets.Buildings.Any())
            {
                return;
            }

            //Each item needs an id for save/restore of tree state. We don't know how many roads were added.
            var itemId = Items.Count;

            //prepare data
            var headerAnno2205 = "(A6) Anno 2205";

            var excludedTemplates = new[] { "Ark", "Harbour", "OrnamentBuilding" };
            var excludedFactions  = new[] { "third party", "Facility Modules" };

            var filteredBuildingList = buildingPresets.Buildings
                                       .Where(x => !excludedTemplates.Contains(x.Template) &&
                                              !excludedFactions.Contains(x.Faction));

            //For Anno 2205 only
            var modulesList = buildingPresets.Buildings
                              .Where(x => string.Equals(x.Header, headerAnno2205, StringComparison.OrdinalIgnoreCase) &&
                                     string.Equals(x.Faction, "Facility Modules", StringComparison.OrdinalIgnoreCase) &&
                                     !string.Equals(x.Faction, "Facilities", StringComparison.OrdinalIgnoreCase))
                              .ToList();

            #region some checks
#if DEBUG
            var facilityList = filteredBuildingList.Where(x => string.Equals(x.Faction, "Facilities", StringComparison.OrdinalIgnoreCase)).ToList();

            //Get a list of nonMatchedModules;
            var nonMatchedModulesList = modulesList.Except(facilityList, new BuildingInfoComparer()).ToList();
            //These appear to all match. The below statement should notify the progammer if we need to add handling for non matching lists
            System.Diagnostics.Debug.Assert(nonMatchedModulesList.Count == 0, "Module lists do not match, implement handling for this");
#endif
            #endregion

            //add data to tree
            var groupedGames = filteredBuildingList.GroupBy(x => x.Header).OrderBy(x => x.Key);
            foreach (var curGame in groupedGames)
            {
                var gameHeader  = curGame.Key;
                var gameVersion = GetGameVersion(curGame.Key);
                if (gameVersion == CoreConstants.GameVersion.Unknown)
                {
                    gameHeader = _localizationHelper.GetLocalization(curGame.Key);
                }

                var gameItem = new GameHeaderTreeItem
                {
                    Header      = gameHeader,
                    GameVersion = gameVersion,
                    Id          = ++itemId
                };

                var groupedFactions = curGame.Where(x => x.Faction != null).GroupBy(x => x.Faction).OrderBy(x => x.Key);
                foreach (var curFaction in groupedFactions)
                {
                    var factionItem = new GenericTreeItem(gameItem)
                    {
                        Header = _localizationHelper.GetLocalization(curFaction.Key),
                        Id     = ++itemId
                    };

                    var groupedGroups = curFaction.Where(x => x.Group != null).GroupBy(x => x.Group).OrderBy(x => x.Key);
                    foreach (var curGroup in groupedGroups)
                    {
                        var groupItem = new GenericTreeItem(factionItem)
                        {
                            Header = _localizationHelper.GetLocalization(curGroup.Key),
                            Id     = ++itemId
                        };

                        foreach (var curBuildingInfo in curGroup.OrderBy(x => x.GetOrderParameter(_commons.CurrentLanguageCode)))
                        {
                            groupItem.Children.Add(new GenericTreeItem(groupItem)
                            {
                                Header     = curBuildingInfo.ToAnnoObject(_commons.CurrentLanguageCode).Label,
                                AnnoObject = curBuildingInfo.ToAnnoObject(_commons.CurrentLanguageCode),
                                Id         = ++itemId
                            });
                        }

                        //For 2205 only
                        //Add building modules to element list.
                        //Group will be the same for elements in the list.
                        if (string.Equals(curGame.Key, headerAnno2205, StringComparison.OrdinalIgnoreCase))
                        {
                            var moduleItem = new GenericTreeItem(groupItem)
                            {
                                Header = _localizationHelper.GetLocalization(curGroup.ElementAt(0).Group) + " " + _localizationHelper.GetLocalization("Modules"),
                                Id     = ++itemId
                            };

                            foreach (var fourthLevel in modulesList.Where(x => x.Group == curGroup.ElementAt(0).Group))
                            {
                                moduleItem.Children.Add(new GenericTreeItem(moduleItem)
                                {
                                    Header     = fourthLevel.ToAnnoObject(_commons.CurrentLanguageCode).Label,
                                    AnnoObject = fourthLevel.ToAnnoObject(_commons.CurrentLanguageCode),
                                    Id         = ++itemId
                                });
                            }

                            if (moduleItem.Children.Count > 0)
                            {
                                groupItem.Children.Add(moduleItem);
                            }
                        }

                        factionItem.Children.Add(groupItem);
                    }

                    var groupedFactionBuildings = curFaction.Where(x => x.Group == null).OrderBy(x => x.GetOrderParameter(_commons.CurrentLanguageCode));
                    foreach (var curGroup in groupedFactionBuildings)
                    {
                        factionItem.Children.Add(new GenericTreeItem(factionItem)
                        {
                            Header     = curGroup.ToAnnoObject(_commons.CurrentLanguageCode).Label,
                            AnnoObject = curGroup.ToAnnoObject(_commons.CurrentLanguageCode),
                            Id         = ++itemId
                        });
                    }

                    gameItem.Children.Add(factionItem);
                }

                Items.Add(gameItem);
            }

#if DEBUG
            sw.Stop();
            logger.Trace($"loading items for PresetsTree took: {sw.ElapsedMilliseconds}ms");
#endif
        }
예제 #10
0
        public async Task CheckForUpdates(bool isAutomaticUpdateCheck)
        {
            try
            {
                IsUpdateError           = false;
                IsAppUpToDate           = false;
                IsUpdateAvailable       = false;
                IsPresetUpdateAvailable = false;

                BusyContent = _localizationHelper.GetLocalization("UpdatePreferencesBusyCheckUpdates");
                IsBusy      = true;

                await CheckForNewAppVersionAsync();

                await CheckForPresetsAsync(isAutomaticUpdateCheck);

                if (!isAutomaticUpdateCheck)
                {
                    IsAppUpToDate = !IsUpdateAvailable && !IsPresetUpdateAvailable;
                }

                if (isAutomaticUpdateCheck)
                {
                    //If not already prompted
                    if (!_appSettings.PromptedForAutoUpdateCheck)
                    {
                        _appSettings.PromptedForAutoUpdateCheck = true;

                        if (!_messageBoxService.ShowQuestion(Application.Current.MainWindow,
                                                             _localizationHelper.GetLocalization("ContinueCheckingForUpdates"),
                                                             _localizationHelper.GetLocalization("ContinueCheckingForUpdatesTitle")))
                        {
                            AutomaticUpdateCheck = false;
                        }
                    }
                }

                IsBusy = false;
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error checking version.");

                IsUpdateError = true;

                IsBusy = false;

                if (isAutomaticUpdateCheck)
                {
                    _messageBoxService.ShowError(Application.Current.MainWindow,
                                                 _localizationHelper.GetLocalization("VersionCheckErrorMessage"),
                                                 _localizationHelper.GetLocalization("VersionCheckErrorTitle"));
                }
            }
        }