Ejemplo n.º 1
0
        public static void Load()
        {
            var foundConfig = false;

            try
            {
                if (File.Exists("config.xml"))
                {
                    _config = XmlManager <Config> .Load("config.xml");

                    foundConfig = true;
                }
                else if (File.Exists(Instance.AppDataPath + @"\config.xml"))
                {
                    _config = XmlManager <Config> .Load(Instance.AppDataPath + @"\config.xml");

                    foundConfig = true;
                }
                else if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
                {
                    //save locally if appdata doesn't exist (when e.g. not on C)
                    Instance.SaveConfigInAppData = false;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    e.Message + "\n\n" + e.InnerException + "\n\n If you don't know how to fix this, please delete "
                    + Instance.ConfigPath, "Error loading config.xml");
                Application.Current.Shutdown();
            }

            if (!foundConfig)
            {
                if (Instance.ConfigDir != string.Empty)
                {
                    Directory.CreateDirectory(Instance.ConfigDir);
                }
                using (var sr = new StreamWriter(Instance.ConfigPath, false))
                    sr.WriteLine("<Config></Config>");
            }
            else if (Instance.SaveConfigInAppData != null)
            {
                if (Instance.SaveConfigInAppData.Value)                //check if config needs to be moved
                {
                    if (File.Exists("config.xml"))
                    {
                        Directory.CreateDirectory(Instance.ConfigDir);
                        SaveBackup(true);                         //backup in case the file already exists
                        File.Move("config.xml", Instance.ConfigPath);
                        Logger.WriteLine("Moved config to appdata");
                    }
                }
                else if (File.Exists(Instance.AppDataPath + @"\config.xml"))
                {
                    SaveBackup(true);                     //backup in case the file already exists
                    File.Move(Instance.AppDataPath + @"\config.xml", Instance.ConfigPath);
                    Logger.WriteLine("Moved config to local");
                }
            }
        }
Ejemplo n.º 2
0
        public static void Load()
        {
            var foundConfig = false;

            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                var config = Path.Combine(AppDataPath, "config.xml");
#if (SQUIRREL)
                if (File.Exists(config))
                {
                    _config = XmlManager <Config> .Load(config);

                    foundConfig = true;
                }
#else
                if (File.Exists("config.xml"))
                {
                    _config = XmlManager <Config> .Load("config.xml");

                    foundConfig = true;
                }
                else if (File.Exists(config))
                {
                    _config = XmlManager <Config> .Load(config);

                    foundConfig = true;
                }
                else if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)))
                {
                    //save locally if appdata doesn't exist (when e.g. not on C)
                    Instance.SaveConfigInAppData = false;
                }
#endif
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                try
                {
                    if (File.Exists("config.xml"))
                    {
                        File.Move("config.xml", Helper.GetValidFilePath(".", "config_corrupted", "xml"));
                    }
                    else if (File.Exists(AppDataPath + @"\config.xml"))
                    {
                        File.Move(AppDataPath + @"\config.xml", Helper.GetValidFilePath(AppDataPath, "config_corrupted", "xml"));
                    }
                }
                catch (Exception ex1)
                {
                    Log.Error(ex1);
                }
                _config = BackupManager.TryRestore <Config>("config.xml");
            }

            if (!foundConfig)
            {
                if (Instance.ConfigDir != string.Empty)
                {
                    Directory.CreateDirectory(Instance.ConfigDir);
                }
                Save();
            }
#if (!SQUIRREL)
            else if (Instance.SaveConfigInAppData != null)
            {
                if (Instance.SaveConfigInAppData.Value)                //check if config needs to be moved
                {
                    if (File.Exists("config.xml"))
                    {
                        Directory.CreateDirectory(Instance.ConfigDir);
                        SaveBackup(true);                         //backup in case the file already exists
                        File.Move("config.xml", Instance.ConfigPath);
                        Log.Info("Moved config to appdata");
                    }
                }
                else if (File.Exists(AppDataPath + @"\config.xml"))
                {
                    SaveBackup(true);                     //backup in case the file already exists
                    File.Move(AppDataPath + @"\config.xml", Instance.ConfigPath);
                    Log.Info("Moved config to local");
                }
            }
#endif
            if (Instance.Id == Guid.Empty.ToString())
            {
                Instance.Id = Guid.NewGuid().ToString();
                Save();
            }
        }
        public MainWindow()
        {
            // Set working directory to path of executable
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            InitializeComponent();

            Trace.Listeners.Add(new TextBoxTraceListener(Options.TextBoxLog));

            EnableMenuItems(false);

            try
            {
                if (File.Exists("Updater_new.exe"))
                {
                    if (File.Exists("Updater.exe"))
                    {
                        File.Delete("Updater.exe");
                    }
                    File.Move("Updater_new.exe", "Updater.exe");
                }
            }
            catch
            {
                Logger.WriteLine("Error updating updater");
            }

            Helper.MainWindow = this;
            /*_configPath =*/
            Config.Load();
            HsLogReader.Create();

            var configVersion = string.IsNullOrEmpty(Config.Instance.CreatedByVersion)
                                                                        ? null
                                                                        : new Version(Config.Instance.CreatedByVersion);

            Version currentVersion;

            if (Config.Instance.CheckForUpdates)
            {
                currentVersion   = Helper.CheckForUpdates(out NewVersion);
                _lastUpdateCheck = DateTime.Now;
            }
            else
            {
                currentVersion = Helper.GetCurrentVersion();
            }

            var versionString = string.Empty;

            if (currentVersion != null)
            {
                versionString             = string.Format("{0}.{1}.{2}", currentVersion.Major, currentVersion.Minor, currentVersion.Build);
                Help.TxtblockVersion.Text = "Version: " + versionString;

                // Assign current version to the config instance so that it will be saved when the config
                // is rewritten to disk, thereby telling us what version of the application created it
                Config.Instance.CreatedByVersion = currentVersion.ToString();
            }

            ConvertLegacyConfig(currentVersion, configVersion);

            if (Config.Instance.SelectedTags.Count == 0)
            {
                Config.Instance.SelectedTags.Add("All");
            }

            _foundHsDirectory = FindHearthstoneDir();

            if (_foundHsDirectory)
            {
                _updatedLogConfig = UpdateLogConfigFile();
            }

            //hearthstone, loads db etc - needs to be loaded before playerdecks, since cards are only saved as ids now
            Game.Reset();

            _decksPath = Config.Instance.DataDir + "PlayerDecks.xml";
            SetupDeckListFile();
            try
            {
                DeckList = XmlManager <Decks> .Load(_decksPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(
                    e.Message + "\n\n" + e.InnerException +
                    "\n\n If you don't know how to fix this, please delete " + _decksPath +
                    " (this will cause you to lose your decks).",
                    "Error loading PlayerDecks.xml");
                Application.Current.Shutdown();
            }

            foreach (var deck in DeckList.DecksList)
            {
                DeckPickerList.AddDeck(deck);
            }

            SetupDefaultDeckStatsFile();
            DefaultDeckStats.Load();


            SetupDeckStatsFile();
            DeckStatsList.Load();

            _notifyIcon = new NotifyIcon {
                Icon = new Icon(@"Images/HearthstoneDeckTracker16.ico"), Visible = true, ContextMenu = new ContextMenu(), Text = "Hearthstone Deck Tracker v" + versionString
            };
            _notifyIcon.ContextMenu.MenuItems.Add("Use no deck", (sender, args) => DeselectDeck());
            _notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Autoselect deck")
            {
                MenuItems =
                {
                    new MenuItem("On",
                                 (sender, args) =>
                                 AutoDeckDetection(true)),
                    new MenuItem("Off",
                                 (sender, args) =>
                                 AutoDeckDetection(false))
                }
            }); _notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Class cards first")
            {
                MenuItems =
                {
                    new MenuItem("Yes",
                                 (sender, args) =>
                                 SortClassCardsFirst(true)),
                    new MenuItem("No",
                                 (sender, args) =>
                                 SortClassCardsFirst(false))
                }
            });
            _notifyIcon.ContextMenu.MenuItems.Add("Show", (sender, args) => ActivateWindow());
            _notifyIcon.ContextMenu.MenuItems.Add("Exit", (sender, args) => Close());
            _notifyIcon.MouseClick += (sender, args) => { if (args.Button == MouseButtons.Left)
                                                          {
                                                              ActivateWindow();
                                                          }
            };

            //create overlay
            Overlay = new OverlayWindow {
                Topmost = true
            };

            PlayerWindow   = new PlayerWindow(Config.Instance, Game.IsUsingPremade ? Game.PlayerDeck : Game.PlayerDrawn);
            OpponentWindow = new OpponentWindow(Config.Instance, Game.OpponentCards);
            TimerWindow    = new TimerWindow(Config.Instance);
            StatsWindow    = new StatsWindow();

            if (Config.Instance.PlayerWindowOnStart)
            {
                PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                TimerWindow.Show();
            }
            if (!DeckList.AllTags.Contains("All"))
            {
                DeckList.AllTags.Add("All");
                WriteDecks();
            }
            if (!DeckList.AllTags.Contains("Favorite"))
            {
                if (DeckList.AllTags.Count > 1)
                {
                    DeckList.AllTags.Insert(1, "Favorite");
                }
                else
                {
                    DeckList.AllTags.Add("Favorite");
                }
                WriteDecks();
            }
            if (!DeckList.AllTags.Contains("Arena"))
            {
                DeckList.AllTags.Add("Arena");
                WriteDecks();
            }
            if (!DeckList.AllTags.Contains("Constructed"))
            {
                DeckList.AllTags.Add("Constructed");
                WriteDecks();
            }
            if (!DeckList.AllTags.Contains("None"))
            {
                DeckList.AllTags.Add("None");
                WriteDecks();
            }

            Options.ComboboxAccent.ItemsSource    = ThemeManager.Accents;
            Options.ComboboxTheme.ItemsSource     = ThemeManager.AppThemes;
            Options.ComboboxLanguages.ItemsSource = Helper.LanguageDict.Keys;

            Options.ComboboxKeyPressGameStart.ItemsSource = EventKeys;
            Options.ComboboxKeyPressGameEnd.ItemsSource   = EventKeys;

            LoadConfig();

            FillElementSorters();

            //this has to happen before reader starts
            var lastDeck = DeckList.DecksList.FirstOrDefault(d => d.Name == Config.Instance.LastDeck);

            DeckPickerList.SelectDeck(lastDeck);

            TurnTimer.Create(90);

            SortFilterDecksFlyout.HideStuffToCreateNewTag();
            TagControlEdit.OperationSwitch.Visibility = Visibility.Collapsed;
            TagControlEdit.PnlSortDecks.Visibility    = Visibility.Collapsed;


            UpdateDbListView();

            _doUpdate = _foundHsDirectory;
            UpdateOverlayAsync();

            _initialized = true;
            Options.MainWindowInitialized();

            DeckPickerList.UpdateList();
            if (lastDeck != null)
            {
                DeckPickerList.SelectDeck(lastDeck);
                UpdateDeckList(lastDeck);
                UseDeck(lastDeck);
            }

            if (_foundHsDirectory)
            {
                HsLogReader.Instance.Start();
            }

            Helper.SortCardCollection(ListViewDeck.Items, Config.Instance.CardSortingClassFirst);
            DeckPickerList.SortDecks();
        }
        //public Guid ActiveDeckId { get; set; }

        public static void Load()
        {
            var file = Config.Instance.DataDir + "PlayerDecks.xml";

            if (!File.Exists(file))
            {
                return;
            }
            try
            {
                _instance = XmlManager <DeckList> .Load(file);
            }
            catch (Exception)
            {
                //failed loading deckstats
                var corruptedFile = Helper.GetValidFilePath(Config.Instance.DataDir, "PlayerDecks_corrupted", "xml");
                try
                {
                    File.Move(file, corruptedFile);
                }
                catch (Exception)
                {
                    throw new Exception(
                              "Can not load or move PlayerDecks.xml file. Please manually delete the file in \"%appdata\\HearthstoneDeckTracker\".");
                }

                //get latest backup file
                var backup =
                    new DirectoryInfo(Config.Instance.DataDir).GetFiles("PlayerDecks_backup*").OrderByDescending(x => x.CreationTime).FirstOrDefault();
                if (backup != null)
                {
                    try
                    {
                        File.Copy(backup.FullName, file);
                        _instance = XmlManager <DeckList> .Load(file);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(
                                  "Error restoring PlayerDecks backup. Please manually rename \"PlayerDecks_backup.xml\" to \"PlayerDecks.xml\" in \"%appdata\\HearthstoneDeckTracker\".",
                                  ex);
                    }
                }
                else
                {
                    throw new Exception("PlayerDecks.xml is corrupted.");
                }
            }

            var save = false;

            if (!Instance.AllTags.Contains("All"))
            {
                Instance.AllTags.Add("All");
                save = true;
            }
            if (!Instance.AllTags.Contains("Favorite"))
            {
                if (Instance.AllTags.Count > 1)
                {
                    Instance.AllTags.Insert(1, "Favorite");
                }
                else
                {
                    Instance.AllTags.Add("Favorite");
                }
                save = true;
            }
            if (!Instance.AllTags.Contains("Arena"))
            {
                Instance.AllTags.Add("Arena");
                save = true;
            }
            if (!Instance.AllTags.Contains("Constructed"))
            {
                Instance.AllTags.Add("Constructed");
                save = true;
            }
            if (!Instance.AllTags.Contains("None"))
            {
                Instance.AllTags.Add("None");
                save = true;
            }
            if (save)
            {
                Save();
            }
            //Instance.ActiveDeck = Instance.Decks.FirstOrDefault(d => d.DeckId == Config.Instance.ActiveDeckId);
        }
        public MainWindow()
        {
            InitializeComponent();

            Helper.CheckForUpdates();

            //check for log config and create if not existing
            try
            {
                if (!File.Exists(_logConfigPath))
                {
                    File.Copy("Files/log.config", _logConfigPath);
                }
                else
                {
                    //update log.config if newer
                    var localFile = new FileInfo(_logConfigPath);
                    var file      = new FileInfo("Files/log.config");
                    if (file.LastWriteTime > localFile.LastWriteTime)
                    {
                        File.Copy("Files/log.config", _logConfigPath, true);
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Not authorized write " + _logConfigPath + ". Start as admin(?)");
                Console.WriteLine(ex.Message);
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }

            //load config
            _config           = new Config();
            _xmlManagerConfig = new XmlManager <Config> {
                Type = typeof(Config)
            };
            _config = _xmlManagerConfig.Load("config.xml");

            //load saved decks
            if (!File.Exists("PlayerDecks.xml"))
            {
                //avoid overwriting decks file with new releases.
                using (var sr = new StreamWriter("PlayerDecks.xml", false))
                {
                    sr.WriteLine("<Decks></Decks>");
                }
            }
            _xmlManager = new XmlManager <Decks> {
                Type = typeof(Decks)
            };
            _deckList = _xmlManager.Load("PlayerDecks.xml");

            //add saved decks to gui
            foreach (var deck in _deckList.DecksList)
            {
                ComboBoxDecks.Items.Add(deck.Name);
            }
            ComboBoxDecks.SelectedItem = _config.LastDeck;


            //hearthstone, loads db etc
            _hearthstone = new Hearthstone();



            //create overlay
            _overlay = new OverlayWindow(_config, _hearthstone)
            {
                Topmost = true
            };
            _overlay.Show();

            _playerWindow   = new PlayerWindow(_config, _hearthstone.PlayerDeck);
            _opponentWindow = new OpponentWindow(_config, _hearthstone.EnemyCards);

            LoadConfig();

            //find hs directory
            if (!File.Exists(_config.HearthstoneDirectory + @"\Hearthstone.exe"))
            {
                MessageBox.Show("Please specify your Hearthstone directory", "Hearthstone directory not found",
                                MessageBoxButton.OK);
                var dialog = new OpenFileDialog();
                dialog.Title      = "Select Hearthstone.exe";
                dialog.DefaultExt = "Hearthstone.exe";
                dialog.Filter     = "Hearthstone.exe|Hearthstone.exe";
                var result = dialog.ShowDialog();
                if (result != true)
                {
                    return;
                }
                _config.HearthstoneDirectory = Path.GetDirectoryName(dialog.FileName);
                _xmlManagerConfig.Save("config.xml", _config);
            }

            //log reader
            _logReader = new HsLogReader(_config.HearthstoneDirectory);
            _logReader.CardMovement    += LogReaderOnCardMovement;
            _logReader.GameStateChange += LogReaderOnGameStateChange;


            UpdateDbListView();

            _options = new OptionsWindow(_config, _overlay, _xmlManagerConfig, _playerWindow, _opponentWindow);

            _updateThread = new Thread(Update);
            _updateThread.Start();

            _initialized = true;

            UpdateDeckList();
            UseSelectedDeck();

            _logReader.Start();
        }
Ejemplo n.º 6
0
        private void BtnFile_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Title      = "Select Deck File",
                DefaultExt = "*.xml;*.txt",
                Filter     = "Deck Files|*.txt;*.xml"
            };
            var dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                try
                {
                    Deck deck = null;

                    if (dialog.FileName.EndsWith(".txt"))
                    {
                        using (var sr = new StreamReader(dialog.FileName))
                        {
                            deck = new Deck();
                            var lines = sr.ReadToEnd().Split('\n');
                            foreach (var line in lines)
                            {
                                var card = Game.GetCardFromName(line.Trim());
                                if (card.Name == "")
                                {
                                    continue;
                                }

                                if (string.IsNullOrEmpty(deck.Class) && card.PlayerClass != "Neutral")
                                {
                                    deck.Class = card.PlayerClass;
                                }

                                if (deck.Cards.Contains(card))
                                {
                                    var deckCard = deck.Cards.First(c => c.Equals(card));
                                    deck.Cards.Remove(deckCard);
                                    deckCard.Count++;
                                    deck.Cards.Add(deckCard);
                                }
                                else
                                {
                                    deck.Cards.Add(card);
                                }
                            }
                        }
                    }
                    else if (dialog.FileName.EndsWith(".xml"))
                    {
                        deck = XmlManager <Deck> .Load(dialog.FileName);

                        //not all required information is saved in xml
                        foreach (var card in deck.Cards)
                        {
                            card.Load();
                        }
                        TagControlEdit.SetSelectedTags(deck.Tags);
                    }
                    SetNewDeck(deck);
                }
                catch (Exception ex)
                {
                    Logger.WriteLine("Error getting deck from file: \n" + ex.Message + "\n" + ex.StackTrace);
                }
            }
        }