/// <summary>
        /// Reads the LanguageDictionary entry from an XmlNode.
        /// </summary>
        /// <param name="nodes">The XmlNode to read the LanguageDictionary entry from.</param>
        /// <param name="language">The Language of the new LanguageDictionary entry.</param>
        private void ReadNodes(XmlNodeList nodes, string language)
        {
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes != null && node.Attributes[NAME] != null && node.Attributes[VALUE] != null)
                {
                    string key     = node.Attributes[NAME].Value.Trim();
                    string myValue = ControlTranslator.GetXmlUnescapedString(node.Attributes[VALUE].Value.Trim());
                    if (mLanguageDictionary[language].ContainsKey(key))
                    {
                        Messenger.AddError(string.Format(MSG_DUPLICATE_KEY_0_1_2_3, language, key, mLanguageDictionary[language][key], myValue));
                        mLanguageDictionary[language][key] = myValue;
                    }
                    else
                    {
                        mLanguageDictionary[language].Add(key, myValue);
                    }
                }

                if (node.HasChildNodes)
                {
                    ReadNodes(node.ChildNodes, language);
                }
            }
        }
        /// <summary>
        /// Loads the config.
        /// </summary>
        public static void Load(string path, ref List <ModNode> modNodes)
        {
            ModNode root = new ModNode()
            {
                Key = Constants.ROOT
            };

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList moVersion = doc.GetElementsByTagName(Constants.VERSION);
                if (moVersion.Count > 0)
                {
                    switch (moVersion[0].InnerText.ToLower())
                    {
                    case "v1.0":
                        root = LoadV1_0(doc);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format("Error during KSPMods.cfg. \"{0}\"", ex.Message), ex);
            }

            modNodes.AddRange(root.Nodes.Cast <ModNode>());
        }
        public static void CreateKMA2Flag()
        {
            // TODO: Get CreateKMAFlag from AppConfig.
            if (!CreateKMAFlag)
            {
                return;
            }

            try
            {
                var fullpath = Path.Combine(MyFlagsFullPath, FLAG_FILENAME);
                if (!File.Exists(fullpath))
                {
                    // Create the folder if it does not exist
                    if (!Directory.Exists(MyFlagsFullPath))
                    {
                        Directory.CreateDirectory(MyFlagsFullPath);
                    }

                    Image image = Resources.KMA2_Flag;
                    image.Save(fullpath);
                    image.Dispose();
                    Messenger.AddInfo(string.Format(Messages.MSG_FLAG_0_ADDED, Path.GetFileNameWithoutExtension(fullpath)));
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError("Error! Can't create KMA² flag.", ex);
            }
        }
示例#4
0
        /// <summary>
        /// Loads the config.
        /// </summary>
        /// <returns>True on success.</returns>
        public static bool Load(string path)
        {
            bool result = false;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList moVersion = doc.GetElementsByTagName(Constants.VERSION);
                if (moVersion.Count > 0)
                {
                    switch (moVersion[0].InnerText.ToLower())
                    {
                    case "v1.0":
                        result = LoadV1_0(doc);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format("Error during KSPModAdmin.cfg. \"{0}\"", ex.Message), ex);
            }

            return(result);
        }
        internal static LanguageFileContent LoadSelectedLanguage(string filename)
        {
            LanguageFileContent result = null;

            if (string.IsNullOrEmpty(filename) || !File.Exists(filename))
            {
                return(result);
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);

                XmlNodeList nodes = doc.GetElementsByTagName(Constants.LANGUAGE);
                if (nodes.Count > 0)
                {
                    result = new LanguageFileContent(filename, nodes[0]);
                    CreateChildEntries(nodes[0], ref result);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format(Messages.MSG_ERROR_0_DURING_LOADING_LANGUAGES, ex.Message);
                Messenger.AddError(msg, ex);
                MessageBox.Show(View.ParentForm, msg, Core.Messages.MSG_TITLE_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(result);
        }
        internal static LanguageSelectInfo[] GetAvailableLanguages(string filePath = null)
        {
            List <LanguageSelectInfo> result = new List <LanguageSelectInfo>();

            if (string.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(Constants.LANGUAGE_FOLDER, string.Empty);
            }

            try
            {
                if (!Directory.Exists(filePath))
                {
                    return(result.ToArray());
                }

                foreach (var file in Directory.GetFiles(filePath))
                {
                    result.Add(new LanguageSelectInfo()
                    {
                        Name = Path.GetFileName(file), Path = file
                    });
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format(Messages.MSG_ERROR_0_DURING_LOADING_LANGUAGES, ex.Message);
                Messenger.AddError(msg, ex);
                MessageBox.Show(View.ParentForm, msg, Core.Messages.MSG_TITLE_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(result.ToArray());
        }
示例#7
0
        /// <summary>
        /// Reads the backup directory and fills the backup TreeView.
        /// </summary>
        public static void ScanBackupDirectory()
        {
            model.Nodes.Clear();

            try
            {
                if (Directory.Exists(BackupPath))
                {
                    foreach (string file in Directory.EnumerateFiles(BackupPath, "*" + Constants.EXT_ZIP))
                    {
                        string dispTxt = GetBackupDisplayName(file);
                        string note    = GetNote(dispTxt);
                        model.Nodes.Add(new BackupNode(file, dispTxt, note));
                    }

                    SaveBackupSettings();
                }
                else
                {
                    if (string.IsNullOrEmpty(BackupPath))
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_FOLDER_NOT_FOUND_0, BackupPath));
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format(Messages.MSG_BACKUP_LOAD_ERROR_0, ex.Message), ex);
            }

            View.InvalidateView();
        }
示例#8
0
        /// <summary>
        /// Event handler for the KSPMAStarted event.
        /// Starts the app and mod update checks.
        /// </summary>
        protected static void KSPMAStarted(object sender)
        {
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            ModSelectionController.View.ShowBusy = true;

            AsyncTask <bool> .DoWork(() =>
            {
                // Auto KSP MA update check.
                OptionsController.Check4AppUpdates();

                // Auto mod update check.
                OptionsController.Check4ModUpdates(true);

                return(true);
            },
                                     (result, ex) =>
            {
                EventDistributor.InvokeAsyncTaskDone(Instance);
                ModSelectionController.View.ShowBusy = false;
                if (ex != null)
                {
                    Messenger.AddError(string.Format("Error during startup update checks! {0}", ex.Message), ex);
                }
            }
                                     );
        }
示例#9
0
        /// <summary>
        /// Takes a site url and parses the site for mod info
        /// </summary>
        /// <param name="modInfo">The modInfo to add data to</param>
        public void ParseSite(ref ModInfo modInfo)
        {
            try
            {
                var htmlDoc = new HtmlWeb().Load(GetPathToReleases(modInfo.ModURL));
                htmlDoc.OptionFixNestedTags = true;

                // get the node that contains all releases (indepandend of label or tags view)
                // Easy way to get XPATH search: use chrome, inspect element, highlight the needed data, right-click and copy XPATH
                var timeLineNode = htmlDoc.DocumentNode.SelectSingleNode(xPathGitHubTimeLine);
                var lableNode    = timeLineNode.SelectSingleNode(xPathGitHubLabel);
                var tagsNode     = timeLineNode.SelectSingleNode(xPathGitHubTags);
                var tagsNode2    = timeLineNode.SelectSingleNode(xPathGitHubTags2);

                if (lableNode == null && tagsNode == null && tagsNode2 == null)
                {
                    Messenger.AddError("Error! Can't parse GitHib version or creation date!");
                    return;
                }

                // get data from label or tag view.
                HtmlNode versionNode = null;
                HtmlNode updateNode  = null;
                if (lableNode != null)
                {
                    versionNode = lableNode.SelectSingleNode(xPathGitHubLabelVersion);
                    updateNode  = lableNode.SelectSingleNode(xPathGitHubLabelDate);
                }
                else if (tagsNode != null)
                {
                    versionNode = tagsNode.SelectSingleNode(xPathGitHubTagsVersion);
                    updateNode  = tagsNode.SelectSingleNode(xPathGitHubTagsDate);
                }
                else if (tagsNode2 != null)
                {
                    versionNode = tagsNode2.SelectSingleNode(xPathGitHubTags2Version);
                    updateNode  = tagsNode2.SelectSingleNode(xPathGitHubTags2Date);
                }

                if (versionNode == null || updateNode == null)
                {
                    Messenger.AddError("Error! Can't parse GitHib version or creation date!");
                }

                if (versionNode != null)
                {
                    modInfo.Version = Regex.Replace(versionNode.InnerText, @"[A-z]", string.Empty);
                }
                if (updateNode != null)
                {
                    modInfo.ChangeDateAsDateTime = DateTime.Parse(updateNode.Attributes["datetime"].Value);
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError("Error! Can't parse GitHib version or creation date!", ex);
                throw ex;
            }
        }
        /// <summary>
        /// Refreshes the Flags tab.
        /// Searches the KSP install dir for flags and adds them to the ListView.
        /// </summary>
        public static void RefreshFlagTab()
        {
            if (ignoreIndexChange)
            {
                return;
            }

            Messenger.AddInfo(Messages.MSG_FLAG_SCAN_STARTED);

            ignoreIndexChange = true;
            string lastFilter = View.SelectedFilter;

            View.ClearAll();
            flags.Clear();

            // add default Filter
            View.AddFilter(FILTER_ALL);
            View.AddFilter(FILTER_MYFLAG);

            View.ShowProcessingIcon = true;
            EventDistributor.InvokeAsyncTaskStarted(Instance);

            AsyncTask <bool> .DoWork(() =>
            {
                SearchDir4FlagsDirs(KSPPathHelper.GetPath(KSPPaths.GameData));
                return(true);
            },
                                     (bool result, Exception ex) =>
            {
                View.ShowProcessingIcon = false;
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (ex != null)
                {
                    Messenger.AddError(Messages.MSG_ERROR_DURING_FLAG_SCAN, ex);
                }
                else
                {
                    Messenger.AddInfo(Core.Messages.MSG_DONE);
                }

                if (lastFilter != null &&
                    (lastFilter == FILTER_ALL || lastFilter == FILTER_MYFLAG || View.GetGroup(lastFilter) != null))
                {
                    View.SelectedFilter = lastFilter;
                }
                else
                {
                    View.SelectedFilter = FILTER_ALL;
                }

                ignoreIndexChange = false;

                View.FillListView(flags);
            });
        }
        /// <summary>
        /// Parses the line for part informations.
        /// </summary>
        /// <param name="file">Full path to the part cfg file.</param>
        /// <param name="line">The line to parse.</param>
        /// <param name="partNode">The node to write the informations to.</param>
        private static void ParsePartLine(string file, string line, ref PartNode partNode)
        {
            string tempLine = line.Trim();

            // TODO: change name to title!
            if (tempLine.ToLower().StartsWith("name =") || tempLine.ToLower().StartsWith("name="))
            {
                string[] nameValuePair = tempLine.Split('=');
                if (nameValuePair.Length != 2)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_PART_READING_0_NAME_TITLE_MISSMATCH, file));
                }

                else
                {
                    string name = nameValuePair[1].Trim();
                    partNode.Title = name;
                    partNode.Name  = name;
                }
            }

            else if (tempLine.ToLower().StartsWith("title =") || tempLine.ToLower().StartsWith("title="))
            {
                string[] nameValuePair = tempLine.Split('=');
                if (nameValuePair.Length != 2)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_PART_READING_0_NAME_TITLE_MISSMATCH, file));
                }

                else
                {
                    string name = nameValuePair[1].Trim();
                    partNode.Title = name;
                }
            }

            else if (tempLine.ToLower().StartsWith("category =") || tempLine.ToLower().StartsWith("category="))
            {
                string[] nameValuePair = tempLine.Split('=');
                if (nameValuePair.Length != 2)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_PART_READING_0_NAME_TITLE_MISSMATCH, file));
                }

                else
                {
                    int    categoryIndex = -1;
                    string category      = nameValuePair[1].Trim();
                    if (int.TryParse(category, out categoryIndex))
                    {
                        category = TranslateCategoryIndex(categoryIndex);
                    }
                    partNode.Category = category;
                }
            }
        }
        /// <summary>
        /// Starts the Import of a new flag.
        /// </summary>
        public static void ImportFlag()
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = Constants.IMAGE_FILTER;
            if (dlg.ShowDialog(View.ParentForm) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                try
                {
                    CreateNeededDirectories();

                    // delete file with same name.
                    string savePath = Path.Combine(MyFlagsFullPath, Path.GetFileNameWithoutExtension(filename) + EXTENSION_PNG);
                    if (File.Exists(savePath))
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_DELETE_EXISTING_FLAG_0, savePath));
                        File.Delete(savePath);
                    }

                    // save image with max flag size to gamedata/myflags/flags/.
                    using (var image = Image.FromFile(filename))
                    {
                        if (image.Size.Width != FLAG_WIDTH || image.Size.Height != FLAG_HEIGHT)
                        {
                            Messenger.AddInfo(Messages.MSG_ADJUSTING_FLAG_SIZE);
                            Bitmap newImage = new Bitmap(FLAG_WIDTH, FLAG_HEIGHT);
                            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
                            {
                                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                graphicsHandle.DrawImage(image, 0, 0, FLAG_WIDTH, FLAG_HEIGHT);
                            }
                            Messenger.AddInfo(string.Format(Messages.MSG_SAVING_FLAG_0, savePath));
                            newImage.Save(savePath, ImageFormat.Png);
                        }
                        else
                        {
                            Messenger.AddInfo(string.Format(Messages.MSG_COPY_FLAG_0, savePath));
                            image.Save(savePath, ImageFormat.Png);
                        }
                    }

                    AddFlagToList(savePath);
                }
                catch (Exception ex)
                {
                    Messenger.AddError(Messages.MSG_ERROR_FLAG_CREATION_FAILED, ex);
                }

                RefreshFlagTab();
            }
        }
        /// <summary>
        /// Gets or sets the value for the specified language and key.
        /// </summary>
        /// <param name="language">The language of the key value.</param>
        /// <param name="key">The key to get the value from.</param>
        /// <returns>The value for the specified language and key..</returns>
        public string this[string language, string key]
        {
            get
            {
                // Does wanted language exists?
                string lang = language;
                if (!mLanguageDictionary.ContainsKey(language))
                {
                    // no, fall back to default language.
                    if (!mLanguageDictionary.ContainsKey(DefaultLanguage))
                    {
                        throw new ArgumentOutOfRangeException(string.Format(MSG_KEY_0_NOT_DEFINED_FOR_LANGUAGE_1, key, lang));
                    }

                    lang = DefaultLanguage;
                }

                // Does wanted value exists?
                if (mLanguageDictionary[lang].ContainsKey(key))
                {
                    return(mLanguageDictionary[lang, key]);
                }

                // no, try default language.
                else if (lang != DefaultLanguage && mLanguageDictionary.ContainsKey(DefaultLanguage))
                {
                    return(mLanguageDictionary[DefaultLanguage, key]);
                }

                // key not found!
                else
                {
                    Messenger.AddError(string.Format(MSG_KEY_0_NOT_FOUND_FOR_LANGUAGE_1, key, lang));
                    return(string.Empty);
                }
            }
            set
            {
                if (!mLanguageDictionary.ContainsKey(language))
                {
                    mLanguageDictionary.Add(language, new Dictionary <string, string>());
                }

                if (ContainsKey(language, key))
                {
                    mLanguageDictionary[language, key] = value;
                }
                else
                {
                    mLanguageDictionary[language].Add(key, value);
                }
            }
        }
        /// <summary>
        /// Loads all language files of passed filename array.
        /// </summary>
        /// <param name="langFiles">Array of paths to the language files.</param>
        /// <returns>True, if load was without any errors.</returns>
        public bool LoadLanguageFiles(string[] langFiles, bool defaultLanguageRequired = false, bool xml = true)
        {
            bool result = false;

            if (langFiles.Length <= 0)
            {
                return(false);
            }

            string currentFile = string.Empty;

            try
            {
                foreach (var langFile in langFiles)
                {
                    currentFile = langFile;
                    if (xml)
                    {
                        if (LoadLanguageFromXml(langFile))
                        {
                            result = true;
                        }
                    }
                    else
                    {
                        if (LoadLanguage(langFile))
                        {
                            result = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format(MSG_ERROR_DURING_LOADING_LANGUAGE_0, currentFile), ex);
                return(false);
            }

            if (defaultLanguageRequired && !mLanguageDictionary.ContainsKey(DefaultLanguage))
            {
                Messenger.AddError(string.Format(MSG_DEFAULT_LANGUAGE_0_FILE_FOUND, DefaultLanguage));
                return(false);
            }

            if (!result)
            {
                Messenger.AddError(MSG_NO_LANGUAGE_FILE_FOUND);
                return(false);
            }

            return(result);
        }
        /// <summary>
        /// Downloads the mod.
        /// </summary>
        /// <param name="modInfo">The infos of the mod. Must have at least ModURL and LocalPath</param>
        /// <param name="downloadProgressCallback">Callback function for download progress.</param>
        /// <returns>True if the mod was downloaded.</returns>
        public bool DownloadMod(ref ModInfo modInfo, DownloadProgressCallback downloadProgressCallback = null)
        {
            Messenger.AddError("No download support for KSP Forum mods, update check only!");
            MessageBox.Show("No download support for KSP Forum mods, update check only!", Messages.MSG_TITLE_ATTENTION);
            return(false);
            ////if (modInfo == null)
            ////    return false;

            ////string downloadUrl = GetDownloadUrl(modInfo);
            ////modInfo.LocalPath = Path.Combine(OptionsController.DownloadPath, GetDownloadName(downloadUrl));
            ////Www.DownloadFile(downloadUrl, modInfo.LocalPath, downloadProgressHandler);

            ////return File.Exists(modInfo.LocalPath);
        }
示例#16
0
 private void _AddMessage(string msg, bool error = false, Exception ex = null)
 {
     InvokeIfRequired(() => lblCurrentAction.Text = msg);
     if (!error)
     {
         Messenger.AddInfo(msg);
     }
     else if (ex == null)
     {
         Messenger.AddError(msg);
     }
     else
     {
         Messenger.AddError(msg, ex);
     }
 }
示例#17
0
        /// <summary>
        /// Callback function after a backup.
        /// </summary>
        private static void BackupDirFinished(string name, Exception ex)
        {
            EventDistributor.InvokeAsyncTaskDone(Instance);
            View.ShowProcessing = false;

            if (ex != null)
            {
                Messenger.AddError(Messages.MSG_BACKUP_CREATION_ERROR, ex);
            }
            else
            {
                ScanBackupDirectory();

                Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_COMPLETE, name));
            }
        }
        private void btnLunchKSP_Click(object sender, EventArgs e)
        {
            string fullpath   = KSPPathHelper.GetPath(KSPPaths.KSPExe);
            string fullpath64 = KSPPathHelper.GetPath(KSPPaths.KSPX64Exe);

            try
            {
                if (File.Exists(fullpath64) && cbUse64Bit.Checked)
                {
                    fullpath = fullpath64;
                }

                if (File.Exists(fullpath))
                {
                    WriteKSPSettings();

                    EventDistributor.InvokeStartingKSP(this);

                    Messenger.AddInfo(Messages.MSG_STARTING_KSP);
                    System.Diagnostics.Process kspexe = new System.Diagnostics.Process();
#if __MonoCS__
                    kspexe.StartInfo.UseShellExecute = false;
                    kspexe.StartInfo.EnvironmentVariables.Add("LC_ALL", "C");
#endif
                    kspexe.StartInfo.FileName         = fullpath;
                    kspexe.StartInfo.WorkingDirectory = Path.GetDirectoryName(fullpath);
                    if (rbWindowed.Checked && cbBorderlessWin.Checked)
                    {
                        kspexe.StartInfo.Arguments = PARAM_POPUPWINDOW;
                    }
                    if (cbForceOpenGL.Checked)
                    {
                        kspexe.StartInfo.Arguments += " " + PARAM_FORCE_OPENGL;
                    }

                    kspexe.Start();
                }
                else
                {
                    Messenger.AddError(Messages.MSG_CANT_FIND_KSP_EXE);
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(Messages.MSG_KSP_LAUNCH_FAILED, ex);
            }
        }
        /// <summary>
        /// Downloads the Ckan Repository archive to full path.
        /// </summary>
        /// <param name="repo">The Ckan Repository to get the Ckan Repository archive for.</param>
        /// <param name="fullpath">The full path to write the downloaded file to.</param>
        /// <param name="onDownloadComplete">Callback function for the DownloadComplete event.</param>
        /// <param name="onDownloadProgressChanged">Callback function for the DownloadProgressChanged event.</param>
        /// <returns>The new created CkanArchive which was constructed from the downloaded Ckan Repository archive.</returns>
        public static bool DownloadRepositoryArchive(CkanRepository repo, string fullpath, AsyncCompletedEventHandler onDownloadComplete = null, DownloadProgressChangedEventHandler onDownloadProgressChanged = null)
        {
            var async = onDownloadComplete != null;

            Messenger.AddInfo($"Downloading repository archive \"{repo.name}\" from \"{repo.uri.AbsoluteUri}\"...");
            try
            {
                using (var client = new WebClient())
                {
                    if (onDownloadProgressChanged != null)
                    {
                        client.DownloadProgressChanged += onDownloadProgressChanged;
                    }

                    if (onDownloadComplete != null)
                    {
                        client.DownloadFileCompleted += (sender, args) =>
                        {
                            onDownloadComplete(sender, args);
                            Messenger.AddInfo($"Downloading repository archive \"{repo.name}\" done.");
                        }
                    }
                    ;

                    if (async)
                    {
                        client.DownloadFileAsync(repo.uri, fullpath);
                    }
                    else
                    {
                        client.DownloadFile(repo.uri, fullpath);
                    }
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError($"Error during downloading repository archive \"{repo.name}\" Error message: \"{ex.Message}\".", ex);
            }

            if (async)
            {
                return(false);
            }

            Messenger.AddInfo($"Downloading repository archive \"{repo.name}\" done.");
            return(File.Exists(fullpath));
        }
示例#20
0
        /// <summary>
        /// Takes a site url and parses the site for mod info
        /// </summary>
        /// <param name="modInfo">The modInfo to add data to</param>
        public void ParseSite(ref ModInfo modInfo)
        {
            var htmlDoc = new HtmlWeb().Load(GetPathToReleases(modInfo.ModURL));

            htmlDoc.OptionFixNestedTags = true;

            // get the node that contains all releases (indepandend of label or tags view)
            // Easy way to get XPATH search: use chrome, inspect element, highlight the needed data, right-click and copy XPATH
            var timeLineNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id=\"js-repo-pjax-container\"]/div[2]/div[1]/div[2]");
            var lableNode    = timeLineNode.SelectSingleNode("//*[@class=\"release label-latest\"]");
            var tagsNode     = timeLineNode.SelectSingleNode("//*[@class=\"release-timeline-tags\"]");

            if (lableNode == null && tagsNode == null)
            {
                Messenger.AddError("Error! Can't parse GitHib version or creation date!");
                return;
            }

            // get data from label or tag view.
            HtmlNode versionNode = null;
            HtmlNode updateNode  = null;

            if (lableNode != null)
            {
                versionNode = lableNode.SelectSingleNode("//*[@class='release label-latest']/div/ul/li/a/span");
                updateNode  = lableNode.SelectSingleNode("//*[@class='release label-latest']/div[2]/div/p/relative-time");
            }
            else if (tagsNode != null)
            {
                versionNode = tagsNode.SelectSingleNode("//*/li[1]/div/div/h3/a/span");
                updateNode  = tagsNode.SelectSingleNode("//*/li/span/relative-time");
            }

            if (versionNode == null || updateNode == null)
            {
                Messenger.AddError("Error! Can't parse GitHib version or creation date!");
            }

            if (versionNode != null)
            {
                modInfo.Version = Regex.Replace(versionNode.InnerText, @"[A-z]", string.Empty);
            }
            if (updateNode != null)
            {
                modInfo.ChangeDateAsDateTime = DateTime.Parse(updateNode.Attributes["datetime"].Value);
            }
        }
        private static Image DdsToBitMap(string file)
        {
            Image image = null;

            try
            {
                image = Resources.Cant_Display_DDS;
                // TODO: Load DDS to BitMap
            }
            catch (Exception ex)
            {
                image = Resources.Cant_Display_DDS;
                Messenger.AddError(string.Format("Error while reading dds image \"{0}\"", file), ex);
            }

            return(image);
        }
示例#22
0
        /// <summary>
        /// Starts the backup of a directory.
        /// </summary>
        /// <param name="dir">The directory to backup.</param>
        /// <param name="name">Name of the backup file.</param>
        /// <param name="backupPath">The path to write the backup file to.</param>
        /// <param name="zipPath">Base path within the zip archive.</param>
        private static void BackupDirectoryAsync(string dir, string name = "", string backupPath = "", string zipPath = "")
        {
            try
            {
                string nameAuto;
                string backupPathAuto;
                string zipPathAuto;
                nameAuto = CreateBackupFilename(dir, out backupPathAuto, out zipPathAuto);

                if (string.IsNullOrEmpty(name))
                {
                    name = nameAuto;
                }

                if (string.IsNullOrEmpty(backupPath))
                {
                    backupPath = backupPathAuto;
                }

                if (string.IsNullOrEmpty(zipPath))
                {
                    zipPath = zipPathAuto;
                }

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

                if (Directory.Exists(dir))
                {
                    EventDistributor.InvokeAsyncTaskStarted(Instance);
                    View.ShowProcessing = true;
                    Messenger.AddInfo(Messages.MSG_BACKUP_STARTED);
                    AsyncTask <string> .DoWork(() => BackupDir(dir, name, backupPath), BackupDirFinished);
                }
                else
                {
                    Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_SRC_FOLDER_NOT_FOUND, dir));
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format(Messages.MSG_BACKUP_ERROR, ex.Message), ex);
            }
        }
示例#23
0
        /// <summary>
        /// Downloads the CKAN Repositories from CkanRepoManager.MasterRepoListURL.
        /// And updates the View.
        /// </summary>
        /// <param name="finishedCallback">Optional callback function. Will be called after finishing the async get.</param>
        public static void RefreshCkanRepositories(Action finishedCallback = null)
        {
            var parent = ModBrowserViewController.View;

            if (parent != null)
            {
                parent.ShowProcessing = true;
            }

            Messenger.AddInfo(Messages.MSG_REFRESHING_REPOSITORIES);
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            AsyncTask <CkanRepositories> .DoWork(() =>
            {
                return(CkanRepoManager.GetRepositoryList());    // CkanRepoManager.MasterRepoListURL);
            },
                                                 (result, ex) =>
            {
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (parent != null)
                {
                    parent.ShowProcessing = false;
                }

                if (ex != null)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_REFRESH_REPOSITORIES_0, ex.Message), ex);
                }
                else
                {
                    // CkanRepository last = View.SelectedRepository;
                    View.Repositories       = result;
                    View.SelectedRepository = result.repositories.FirstOrDefault();     // last;
                }

                Messenger.AddInfo(Messages.MSG_REFRESHING_REPOSITORIES_DONE);

                if (finishedCallback != null)
                {
                    finishedCallback();
                }
            });
        }
示例#24
0
 /// <summary>
 /// Deletes the backup file.
 /// </summary>
 /// <param name="file">The file to delete.</param>
 public static void RemoveBackup(string file)
 {
     if (File.Exists(file))
     {
         try
         {
             File.Delete(file);
             Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_DELETED, Path.GetFileName(file)));
         }
         catch (Exception ex)
         {
             Messenger.AddError(string.Format(Messages.MSG_BACKUP_DELETED_ERROR, Path.GetFileName(file)), ex);
         }
     }
     else
     {
         Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_NOT_FOUND, Path.GetFileName(file)));
     }
 }
 /// <summary>
 /// Gets or sets the value for the specified key for the CurrentLanguage.
 /// </summary>
 /// <param name="key">The key to get the value from.</param>
 /// <returns>The value for the specified key for the CurrentLanguage.</returns>
 public string this[string key]
 {
     get
     {
         if (mLanguageDictionary.ContainsKey(CurrentLanguage) && mLanguageDictionary[CurrentLanguage].ContainsKey(key))
         {
             return(mLanguageDictionary[CurrentLanguage][key]);
         }
         else if (mLanguageDictionary.ContainsKey(DEFAULT_LANGUAGE) && mLanguageDictionary[DEFAULT_LANGUAGE].ContainsKey(key))
         {
             Messenger.AddError(string.Format(MSG_KEY_0_NOT_FOUND_FOR_LANGUAGE_1, key, CurrentLanguage));
             return(mLanguageDictionary[DEFAULT_LANGUAGE][key]);
         }
         else
         {
             Messenger.AddError(string.Format(MSG_KEY_0_NOT_FOUND_FOR_LANGUAGE_1, key, CurrentLanguage));
             return(string.Empty);
         }
     }
 }
        /// <summary>
        /// Adds a Flag to the internal list of flags.
        /// </summary>
        /// <param name="file">Full path to the Flag file.</param>
        private static void AddFlagToList(string file)
        {
            try
            {
                if (File.Exists(file))
                {
                    Image image = null;

                    string extension = Path.GetExtension(file);
                    if (extension.Equals(EXTENSION_DDS, StringComparison.CurrentCultureIgnoreCase))
                    {
                        image = DdsToBitMap(file);
                    }
                    else
                    {
                        image = Image.FromFile(file);
                    }

                    if (image == null)
                    {
                        return;
                    }

                    string groupName = GetGroupName(file);
                    string flagname  = Path.GetFileNameWithoutExtension(file);

                    if (flagname.Equals(Path.GetFileNameWithoutExtension(FLAG_FILENAME), StringComparison.CurrentCultureIgnoreCase))
                    {
                        groupName = KMA2;
                    }

                    var item = View.CreateNewFlagItem(flagname, groupName, image, file);
                    flags.Add(new KeyValuePair <string, ListViewItem>(groupName, item));
                    Messenger.AddInfo(string.Format(Messages.MSG_FLAG_0_ADDED, flagname));
                }
            }
            catch (Exception ex)
            {
                Messenger.AddError(string.Format(Messages.MSG_ERROR_FLAG_0_ADD_FAILED, file), ex);
            }
        }
示例#27
0
 /// <summary>
 /// Saves the KSPConfig to the selected KSP folder.
 /// </summary>
 public static void SaveKSPConfig()
 {
     try
     {
         string path = KSPPathHelper.GetPath(KSPPaths.KSPConfig);
         if (path != string.Empty && Directory.Exists(Path.GetDirectoryName(path)))
         {
             Messenger.AddInfo(Messages.MSG_SAVING_KSP_MOD_SETTINGS);
             KSPConfig.Save(path, ModSelectionController.Mods);
         }
         else
         {
             Messenger.AddError(Messages.MSG_KSP_MOD_SETTINGS_PATH_INVALID);
         }
     }
     catch (Exception ex)
     {
         Messenger.AddError(Messages.MSG_ERROR_DURING_SAVING_KSP_MOD_SETTINGS, ex);
         ShowAdminRightsDlg(ex);
     }
 }
示例#28
0
 /// <summary>
 /// Saves the AppConfig to "c:\ProgramData\..."
 /// </summary>
 protected static void SaveAppConfig()
 {
     try
     {
         Messenger.AddInfo(Messages.MSG_SAVING_KSPMA_SETTINGS);
         string path = KSPPathHelper.GetPath(KSPPaths.AppConfig);
         if (path != string.Empty && Directory.Exists(Path.GetDirectoryName(path)))
         {
             AdminConfig.Save(path);
         }
         else
         {
             Messenger.AddError(Messages.MSG_KSPMA_SETTINGS_PATH_INVALID);
         }
     }
     catch (Exception ex)
     {
         Messenger.AddError(Messages.MSG_ERROR_DURING_SAVING_KSPMA_SETTINGS, ex);
         ShowAdminRightsDlg(ex);
     }
 }
示例#29
0
        /// <summary>
        /// Loads all Plugins for KSP Mod Admin.
        /// </summary>
        protected static void LoadPlugins()
        {
            Messenger.AddDebug("Loading plugins ...");
            List <IKSPMAPlugin> plugins = null;

            try
            {
                plugins = PluginLoader.LoadPlugins <IKSPMAPlugin>(KSPPathHelper.GetPath(KSPPaths.KSPMA_Plugins));
            }
            catch (Exception ex)
            {
                Messenger.AddError("Error during plugin loading! Plugin loading aborded!", ex);
            }

            if (plugins == null)
            {
                return;
            }

            foreach (IKSPMAPlugin plugin in plugins)
            {
                try
                {
                    Messenger.AddDebug(string.Format("Try add plugin \"{0}\" ...", plugin.Name));

                    TabView[] tabViews = plugin.MainTabViews;
                    foreach (TabView tabView in tabViews)
                    {
                        if (!mAddedTabViews.ContainsKey(tabView.TabUserControl.GetTabCaption()))
                        {
                            Log.AddDebugS(string.Format("Try add TabPage \"{0}\" ...", tabView.TabUserControl.GetTabCaption()));

                            TabPage tabPage = new TabPage();
                            tabPage.Tag  = tabView.UniqueIdentifier.ToString();
                            tabPage.Text = tabView.TabUserControl.GetTabCaption();
                            tabPage.Name = tabView.UniqueIdentifier.ToString(); // this is needed so that tabs can be switched to by plugin GUID
                            tabPage.Controls.Add(tabView.TabUserControl);
                            tabView.TabUserControl.Dock = DockStyle.Fill;
                            if (tabView.TabIcon != null)
                            {
                                View.TabControl.ImageList.Images.Add(tabView.TabIcon);
                                tabPage.ImageIndex = View.TabControl.ImageList.Images.Count - 1;
                            }
                            View.TabControl.TabPages.Add(tabPage);

                            mAddedTabViews.Add(tabView.TabUserControl.GetTabCaption(), tabView);
                        }
                        else
                        {
                            Messenger.AddError(string.Format(Messages.MSG_ERROR_PLUGIN_LOADING_TABVIEWS_0,
                                                             tabView.TabUserControl.GetTabCaption()));
                        }
                    }

                    tabViews = plugin.OptionTabViews;
                    if (tabViews == null)
                    {
                        continue;
                    }

                    foreach (TabView tabView in tabViews)
                    {
                        if (!mAddedTabViews.ContainsKey(tabView.TabUserControl.GetTabCaption()))
                        {
                            Log.AddDebugS(string.Format("Try add Options TabPage \"{0}\" ...", tabView.TabUserControl.GetTabCaption()));

                            TabPage tabPage = new TabPage();
                            tabPage.Text = tabView.TabUserControl.GetTabCaption();
                            tabPage.Name = tabView.UniqueIdentifier.ToString();
                            tabPage.Controls.Add(tabView.TabUserControl);
                            tabView.TabUserControl.Dock = DockStyle.Fill;
                            OptionsController.View.TabControl.TabPages.Add(tabPage);

                            mAddedTabViews.Add(tabView.TabUserControl.GetTabCaption(), tabView);
                        }
                        else
                        {
                            Messenger.AddError(string.Format(Messages.MSG_ERROR_PLUGIN_LOADING_OPTIONVIEWS_0,
                                                             tabView.TabUserControl.GetTabCaption()));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Messenger.AddError(string.Format("Error during loading of plugin \"{0}\"", plugin.Name), ex);
                }
            }
        }
示例#30
0
        /// <summary>
        /// Creates a list of DownloadInfos from a GitHub release
        /// </summary>
        /// <param name="modInfo">The mod to generate the list from</param>
        /// <returns>A list of one or more DownloadInfos for the most recent release of the selected repository</returns>
        private static List <DownloadInfo> GetDownloadInfo(ModInfo modInfo)
        {
            var htmlDoc = new HtmlWeb().Load(GetPathToReleases(modInfo.ModURL));

            htmlDoc.OptionFixNestedTags = true;

            var releases = new List <DownloadInfo>();

            // get the node that contains all releases (indepandend of label or tags view)
            // Easy way to get XPATH search: use chrome, inspect element, highlight the needed data, right-click and copy XPATH
            var timeLineNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@id=\"js-repo-pjax-container\"]/div[2]/div[1]/div[2]");
            var lableNode    = timeLineNode.SelectSingleNode("//*[@class=\"release label-latest\"]");
            var tagsNode     = timeLineNode.SelectSingleNode("//*[@class=\"release-timeline-tags\"]");

            if (lableNode == null && tagsNode == null)
            {
                Messenger.AddError("Error! Can't parse GitHib for binaries!");
                return(releases);
            }

            // get data from label or tag view.
            HtmlNodeCollection releaseNodes = null;

            if (lableNode != null)
            {
                // try find last release (select all link nodes of the download section within the class 'release label-latest')
                releaseNodes = lableNode.SelectNodes("//*[@class='release label-latest']/div[2]/ul/li[1]/a");

                // try find other releases (select all link nodes of the download section within the classes 'release label-latest')
                if (releaseNodes == null)
                {
                    releaseNodes = lableNode.SelectNodes("//*[@class='release label-']/div[2]/ul/li[1]/a");
                }
            }
            else if (tagsNode != null)
            {
                // try find last release (select all link nodes of the download section within the class 'release label-latest')
                releaseNodes = tagsNode.SelectNodes("//*[@class='release-timeline-tags']/li/div/div/ul/li[2]/a");
            }

            if (releaseNodes != null)
            {
                // iterate over all link nodes and get only urls with 'releases' in it.
                foreach (var s in releaseNodes)
                {
                    var url = "https://github.com" + s.Attributes["href"].Value;

                    if (!url.Contains("releases") && !url.Contains("archive"))
                    {
                        continue;
                    }

                    var dInfo = new DownloadInfo
                    {
                        DownloadURL = url,
                        Filename    = GetUrlParts(url).Last(),
                        Name        = Path.GetFileNameWithoutExtension(GetUrlParts(url).Last())
                    };

                    releases.Add(dInfo);
                }
            }

            return(releases);
        }