private static void CreateNeededDirectories()
        {
            string path = KSPPathHelper.GetPath(KSPPaths.GameData);

            if (path == string.Empty)
            {
                Messenger.AddInfo("Invalid KSP path.");
                return;
            }

            // Create .../GameData if not exist.
            if (!Directory.Exists(path))
            {
                Messenger.AddInfo(string.Format(Messages.MSG_CREATING_DIR_0, path));
                Directory.CreateDirectory(path);
            }

            // Create .../MyFlgas/Flags is not exist.
            path = MyFlagsFullPath;
            if (!Directory.Exists(path))
            {
                Messenger.AddInfo(string.Format(Messages.MSG_CREATING_DIR_0, path));
                path = MyFlagsPath;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                // Forlder must be named like "Flags" case sensitive!!!!
                Directory.CreateDirectory(MyFlagsFullPath);
            }
        }
Example #2
0
        /// <summary>
        /// Starts the backup of a directory.
        /// </summary>
        /// <param name="dir">The directory to backup.</param>
        /// <param name="name">The name of the backup file.</param>
        /// <param name="backupPath">The path to write the backup to.</param>
        /// <returns>The new name of the backup file.</returns>
        public static string BackupDir(string dir, string name, string backupPath)
        {
            using (var archive = ZipArchive.Create())
            {
                if (name != string.Empty && backupPath != string.Empty)
                {
                    // TODO: Add file/dir wise, not whole dir at once ...
                    foreach (string file in Directory.GetFiles(dir))
                    {
                        string directoryName = Path.GetDirectoryName(file);
                        if (directoryName != null)
                        {
                            string temp =
                                Path.Combine(directoryName.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty),
                                             Path.GetFileName(file));
                            archive.AddEntry(temp, file);
                        }
                    }

                    AddSubDirs(dir, archive);

                    archive.SaveTo(backupPath, CompressionType.None);
                }
                else
                {
                    Messenger.AddInfo(Messages.MSG_BACKUP_CREATION_ERROR);
                }
            }

            return(name);
        }
Example #3
0
        /// <summary>
        /// Loads all available languages.
        /// </summary>
        protected static void LoadLanguages()
        {
            Log.AddDebugS("Loading languages ...");

            // Try load languages.
            bool langLoadFailed = false;

            try
            {
                Localizer.GlobalInstance.DefaultLanguage = "eng";
                langLoadFailed = !Localizer.GlobalInstance.LoadLanguages(new[]
                {
                    KSPPathHelper.GetPath(KSPPaths.LanguageFolder),
                    Path.Combine(KSPPathHelper.GetPath(KSPPaths.KSPMA_Plugins), Constants.LANGUAGE_FOLDER)
                }, true);
            }
            catch (Exception ex)
            {
                Log.AddErrorS("Error in MainController.LoadLanguages()", ex);
                langLoadFailed = true;
            }

            if (langLoadFailed)
            {
                MessageBox.Show("Can not load languages!" + Environment.NewLine + "Fall back to defalut language: English", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Localizer.GlobalInstance.Clear();
            }

            Log.AddDebugS(string.Format("Loading languages done. ({0})", string.Join(", ", Localizer.GlobalInstance.AvailableLanguages)));
        }
Example #4
0
 /// <summary>
 /// Recovers the selected backup.
 /// </summary>
 public static void RecoverSelectedBackup()
 {
     if (SelectedBackup != null && ValidBackupDirectory(BackupPath))
     {
         string file = SelectedBackup.Key;
         if (File.Exists(file))
         {
             string savesPath = KSPPathHelper.GetPath(KSPPaths.Saves);
             if (Directory.Exists(savesPath))
             {
                 string kspPath = KSPPathHelper.GetPath(KSPPaths.KSPRoot);
                 using (IArchive archive = ArchiveFactory.Open(file))
                 {
                     foreach (IArchiveEntry entry in archive.Entries)
                     {
                         string dir = Path.GetDirectoryName(entry.FilePath);
                         CreateNeededDir(dir);
                         entry.WriteToDirectory(Path.Combine(kspPath, dir));
                     }
                 }
                 Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_REINSTALLED, SelectedBackup.Name));
             }
             else
             {
                 Messenger.AddInfo(string.Format(Messages.MSG_FOLDER_NOT_FOUND, savesPath));
             }
         }
     }
     else
     {
         MessageBox.Show(View.ParentForm, Messages.MSG_BACKUP_SRC_MISSING);
     }
 }
Example #5
0
        /// <summary>
        /// Loads the AppConfig and KSPConfig.
        /// </summary>
        protected static void LoadConfigs()
        {
            Messenger.AddInfo(Messages.MSG_LOADING_KSPMA_SETTINGS);
            string path = KSPPathHelper.GetPath(KSPPaths.AppConfig);

            if (File.Exists(path))
            {
                if (AdminConfig.Load(path))
                {
                    Messenger.AddInfo(Messages.MSG_DONE);

                    // LoadKSPConfig will be started by KSPPathChange event.
                    ////if (KSPPathHelper.IsKSPInstallFolder(OptionsController.SelectedKSPPath))
                    ////    LoadKSPConfig();
                }
                else
                {
                    Messenger.AddInfo(Messages.MSG_LOADING_KSPMA_SETTINGS_FAILED);
                }
            }
            else
            {
                Messenger.AddInfo(Messages.MSG_KSPMA_SETTINGS_NOT_FOUND);
            }

            DeleteOldAppConfigs();
        }
Example #6
0
 /// <summary>
 /// Creates a backup of the saves folder of the current selected KSP install.
 /// </summary>
 public static void BackupSaves()
 {
     if (ValidBackupDirectory(BackupPath))
     {
         BackupDirectoryAsync(KSPPathHelper.GetPath(KSPPaths.Saves));
     }
 }
        private void ReadKSPSettings()
        {
            string path = Path.Combine(KSPPathHelper.GetPath(KSPPaths.KSPRoot), PARAM_SETTINGS_CFG);

            if (File.Exists(path))
            {
                string fileContent = File.ReadAllText(path);
                int    index1      = fileContent.IndexOf(Constants.SCREEN_WIDTH) + Constants.SCREEN_WIDTH.Length;
                int    index2      = fileContent.IndexOf(Environment.NewLine, index1);
                string width       = fileContent.Substring(index1, index2 - index1).Replace(EQUALS, string.Empty).Trim();
                index1 = fileContent.IndexOf(Constants.SCREEN_HEIGHT) + Constants.SCREEN_HEIGHT.Length;
                index2 = fileContent.IndexOf(Environment.NewLine, index1);
                string height = fileContent.Substring(index1, index2 - index1).Replace(EQUALS, string.Empty).Trim();
                ScreenResolution = string.Format(PARAM_0_X_1, width, height);
                index1           = fileContent.IndexOf(Constants.FULLSCREEN) + Constants.FULLSCREEN.Length;
                index2           = fileContent.IndexOf(Environment.NewLine, index1);
                Fullscreen       = fileContent.Substring(index1, index2 - index1).Replace(EQUALS, string.Empty).Trim().ToLower() == TRUE;

                settingsFileFound = true;
            }
            else
            {
                Messenger.AddInfo(Messages.MSG_CANT_FIND_KSP_SETTINGS);
                settingsFileFound = false;
            }
        }
Example #8
0
        /// <summary>
        /// Creates a Backup of the saves folder with the name "KSPLaunchBackup_{yyyyMMdd_HHmm}.zip".
        /// </summary>
        public static void KSPLaunchBackup()
        {
            Messenger.AddInfo("Backup on KSP launch started.");
            string dir     = KSPPathHelper.GetPath(KSPPaths.Saves);
            string zipPath = dir.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty);
            string name    = String.Format("KSPLaunchBackup_{0}{1}", DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);

            BackupDirectoryAsync(dir, name, Path.Combine(BackupPath, name), zipPath);
        }
        /// <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);
            });
        }
Example #10
0
        /// <summary>
        /// First run initialization of config directory.
        /// </summary>
        protected static void CreateConfigDir()
        {
            string path = KSPPathHelper.GetPath(KSPPaths.AppConfig);

            path = Directory.GetParent(path).ToString();
            if (!Directory.Exists(path))
            {
                Messenger.AddDebug("Creating config directory: " + path);
                Directory.CreateDirectory(path);
            }
        }
Example #11
0
        /// <summary>
        /// Opens the SelectFolderDialog to select a folder to backup
        /// and Starts the backup process async.
        /// </summary>
        public static void NewBackup()
        {
            if (!ValidBackupDirectory(BackupPath))
            {
                return;
            }

            FolderSelectDialog dlg = new FolderSelectDialog();

            dlg.Title            = "Source folder selection";
            dlg.InitialDirectory = KSPPathHelper.GetPath(KSPPaths.KSPRoot);
            if (dlg.ShowDialog(View.ParentForm.Handle))
            {
                BackupDirectoryAsync(dlg.FileName);
            }
        }
        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);
            }
        }
Example #13
0
        /// <summary>
        /// Adds the sub directory to the Archive.
        /// </summary>
        /// <param name="parentDir">Parent directory to scan for sub directories and files.</param>
        /// <param name="archive">The Archive to add the directories and files to.</param>
        private static void AddSubDirs(string parentDir, ZipArchive archive)
        {
            foreach (string subDir in Directory.GetDirectories(parentDir))
            {
                foreach (string file in Directory.GetFiles(subDir))
                {
                    string directoryName = Path.GetDirectoryName(file);
                    if (directoryName != null)
                    {
                        string temp = Path.Combine(directoryName.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty), Path.GetFileName(file));
                        archive.AddEntry(temp, file);
                    }
                }

                AddSubDirs(subDir, archive);
            }
        }
Example #14
0
        /// <summary>
        /// Loads and registers all SiteHandler.
        /// </summary>
        protected static void LoadSiteHandler()
        {
            // Add default SiteHandler
            var siteHandlers = PluginLoader.GetPlugins <ISiteHandler>(new[] { Assembly.GetExecutingAssembly() });

            foreach (ISiteHandler handler in siteHandlers)
            {
                SiteHandlerManager.RegisterSiteHandler(handler);
            }

            // Add additional SiteHandlers
            siteHandlers = PluginLoader.LoadPlugins <ISiteHandler>(KSPPathHelper.GetPath(KSPPaths.KSPMA_Plugins));
            foreach (ISiteHandler handler in siteHandlers)
            {
                SiteHandlerManager.RegisterSiteHandler(handler);
            }
        }
        private void WriteKSPSettings()
        {
            string settingsPath = Path.Combine(KSPPathHelper.GetPath(KSPPaths.KSPRoot), PARAM_SETTINGS_CFG);

            if (File.Exists(settingsPath))
            {
                if (ScreenResolution == null)
                {
                    return;
                }

                int      index1  = -1;
                int      index2  = -1;
                string   temp    = string.Empty;
                string   allText = File.ReadAllText(settingsPath);
                string[] size    = ScreenResolution.Split("x");
                if (size.Length == 2)
                {
                    index1  = allText.IndexOf(Constants.SCREEN_WIDTH);
                    index2  = allText.IndexOf(Environment.NewLine, index1);
                    temp    = allText.Substring(index1, index2 - index1);
                    allText = allText.Replace(temp, string.Format(PARAM_0_EQUALS_1, Constants.SCREEN_WIDTH, size[0]));

                    index1  = allText.IndexOf(Constants.SCREEN_HEIGHT);
                    index2  = allText.IndexOf(Environment.NewLine, index1);
                    temp    = allText.Substring(index1, index2 - index1);
                    allText = allText.Replace(temp, string.Format(PARAM_0_EQUALS_1, Constants.SCREEN_HEIGHT, size[1]));
                }

                index1  = allText.IndexOf(Constants.FULLSCREEN);
                index2  = allText.IndexOf(Environment.NewLine, index1);
                temp    = allText.Substring(index1, index2 - index1);
                allText = allText.Replace(temp, string.Format(PARAM_0_EQUALS_1, Constants.FULLSCREEN, rbFullscreen.Checked));
                File.WriteAllText(settingsPath, allText);
                Messenger.AddInfo(Messages.MSG_UPDATE_KSP_SETTINGS);

                settingsFileFound = true;
            }
            else
            {
                Messenger.AddInfo(Messages.MSG_CANT_FIND_KSP_SETTINGS);
                settingsFileFound = false;
            }
        }
Example #16
0
        /// <summary>
        /// Deletes older config paths and files.
        /// </summary>
        protected static void DeleteOldAppConfigs()
        {
            string path = KSPPathHelper.GetPath(KSPPaths.AppConfig);

            string[] dirs = Directory.GetDirectories(Path.GetDirectoryName(path));
            foreach (string dir in dirs)
            {
                try
                {
                    if (!Directory.Exists(dir))
                    {
                        continue;
                    }

                    Directory.Delete(dir, true);
                }
                catch (Exception)
                { }
            }
        }
Example #17
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);
     }
 }
Example #18
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);
     }
 }
Example #19
0
        /// <summary>
        /// Creates the name for a backup file.
        /// </summary>
        /// <param name="dir">The path to backup to.</param>
        /// <param name="fullpath">Full path of the created backup file.</param>
        /// <param name="zipPath">Path within the zip archive.</param>
        /// <returns>The created name of the backup file.</returns>
        private static string CreateBackupFilename(string dir, out string fullpath, out string zipPath)
        {
            // create the name of the backupfile from the backup directory
            string name     = dir.Substring(dir.LastIndexOf(Path.DirectorySeparatorChar) + 1, dir.Length - (dir.LastIndexOf(Path.DirectorySeparatorChar) + 1));
            string filename = String.Format("{0}_{1}{2}", name, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);

            fullpath = Path.Combine(BackupPath, filename);

            // get zip intern dir
            zipPath = dir.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty);

            // add _(x) to the filename if the file already exists.
            int i = 1;

            while (File.Exists(fullpath))
            {
                fullpath = Path.GetDirectoryName(fullpath) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fullpath) + "_" + (i++).ToString("00") + Path.GetExtension(fullpath);
            }

            return(name);
        }
Example #20
0
        /// <summary>
        /// Loads the KSPConfig from the selected KSP folder.
        /// </summary>
        protected static void LoadKSPConfig()
        {
            ModSelectionController.ClearMods();

            string configPath = KSPPathHelper.GetPath(KSPPaths.KSPConfig);

            if (File.Exists(configPath))
            {
                Messenger.AddInfo(Messages.MSG_LOADING_KSP_MOD_CONFIGURATION);
                List <ModNode> mods = new List <ModNode>();
                KSPConfig.Load(configPath, ref mods);
                ModSelectionController.AddMods(mods.ToArray());
                ModSelectionController.SortModSelection();
            }
            else
            {
                Messenger.AddInfo(Messages.MSG_KSP_MOD_CONFIGURATION_NOT_FOUND);
            }

            ModSelectionController.RefreshCheckedStateAllMods();
            Messenger.AddInfo(Messages.MSG_DONE);
        }
Example #21
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the CB_Dest.
        /// </summary>
        private void CB_Dest_SelectedIndexChanged(object sender, EventArgs e)
        {
            // "Other folder ..." selected?
            if (cbDestination.SelectedIndex == 0)
            {
                FolderSelectDialog dlg = new FolderSelectDialog();
                dlg.Title            = Messages.MSG_DESTINATION_FOLDER_SELECTION_TITLE;
                dlg.InitialDirectory = KSPPathHelper.GetPath(KSPPaths.KSPRoot);
                if (dlg.ShowDialog(this.Handle))
                {
                    string dest = dlg.FileName;
                    int    i    = dest.LastIndexOf(Path.DirectorySeparatorChar);
                    if (i >= 0)
                    {
                        dest = dest.Substring(i);
                    }
                    cbDestination.Items.Add(new DestInfo(dest, dlg.FileName));
                    cbDestination.SelectedIndex = cbDestination.Items.Count - 1;
                }
                else
                {
                    cbDestination.SelectedIndex = -1;
                }

                ////FolderBrowserDialog dlg = new FolderBrowserDialog();
                ////dlg.Description = "Select a destination folder.";
                ////dlg.SelectedPath = KSPPathHelper.GetPath(KSPPaths.KSPRoot);
                ////if (dlg.ShowDialog() == DialogResult.OK)
                ////{
                ////    string dest = dlg.SelectedPath;
                ////    string destName = dest.Substring(dest.LastIndexOf(Path.DirectorySeparatorChar));
                ////    cbDestination.Items.Add(new DestInfo(destName, dlg.SelectedPath));
                ////    cbDestination.SelectedIndex = cbDestination.Items.Count - 1;
                ////}
                ////else
                ////    cbDestination.SelectedIndex = -1;
            }
        }
Example #22
0
 /// <summary>
 /// Creates the directory if it not exists.
 /// </summary>
 /// <param name="directory">The directory to create.</param>
 private static void CreateNeededDir(string directory)
 {
     try
     {
         string path = KSPPathHelper.GetPath(KSPPaths.KSPRoot);
         if (!Directory.Exists(Path.Combine(path, directory)))
         {
             string[] dirs = directory.Split(Path.DirectorySeparatorChar);
             foreach (string dir in dirs)
             {
                 path = Path.Combine(path, dir);
                 if (!Directory.Exists(path))
                 {
                     Directory.CreateDirectory(path);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Log.AddErrorS("Error in UcBackupViewController.CreateNeededDir()", ex);
     }
 }
Example #23
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);
                }
            }
        }
Example #24
0
        /// <summary>
        /// Creates a auto backup of the saves folder.
        /// </summary>
        private static void DoAutoBackup()
        {
            int    count   = 1;
            string name    = string.Format("AutoBackup_{0}_{1}{2}", count, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);
            string dir     = KSPPathHelper.GetPath(KSPPaths.Saves);
            string zipPath = dir.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty);

            if (Directory.Exists(BackupPath))
            {
                FileInfo        fileInfo    = null;
                string[]        autoBackups = Directory.EnumerateFiles(BackupPath, "AutoBackup_*" + Constants.EXT_ZIP).ToArray();
                List <FileInfo> list        = new List <FileInfo>();
                foreach (string file in autoBackups)
                {
                    FileInfo fi = GetFileInfoFromFilename(file);
                    if (fi == null)
                    {
                        continue;
                    }

                    list.Add(fi);
                    list.Sort(delegate(FileInfo a, FileInfo b) { return(a.Number.CompareTo(b.Number)); });
                }

                while (list.Count > MaxBackupFiles)
                {
                    list.RemoveAt(list.Count - 1);
                }

                if (list.Count == MaxBackupFiles)
                {
                    list.Sort(delegate(FileInfo a, FileInfo b)
                    {
                        if (b.DateTime.CompareTo(a.DateTime) == 0)
                        {
                            return(b.Number.CompareTo(a.Number));
                        }

                        return(b.DateTime.CompareTo(a.DateTime));
                    });

                    fileInfo = list.Last();
                    string fname = string.Format("AutoBackup_{0}_{1}{2}", fileInfo.Number, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);
                    if (File.Exists(fileInfo.FullPath))
                    {
                        File.Delete(fileInfo.FullPath);
                        Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_DELETED, Path.GetFileName(fileInfo.FullPath)));
                    }
                    fileInfo = new FileInfo(Path.Combine(BackupPath, fname), DateTime.Now, fileInfo.Number);
                }
                else if (list.Count > 0)
                {
                    int    number = 1;
                    string fname  = string.Empty;
                    for (; number <= MaxBackupFiles; ++number)
                    {
                        bool   found = false;
                        string key   = string.Format("AutoBackup_{0}", number);
                        foreach (FileInfo fi in list)
                        {
                            var fileName = Path.GetFileName(fi.FullPath);
                            if (fileName == null || !fileName.StartsWith(key))
                            {
                                continue;
                            }

                            found = true;
                            break;
                        }

                        if (found)
                        {
                            continue;
                        }

                        fname = string.Format("AutoBackup_{0}_{1}{2}", number, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);
                        break;
                    }

                    if (fname == string.Empty)
                    {
                        fileInfo = list.Last();
                        number   = fileInfo.Number;
                        fname    = string.Format("AutoBackup_{0}_{1}{2}", number, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);
                        if (File.Exists(fileInfo.FullPath))
                        {
                            File.Delete(fileInfo.FullPath);
                            Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_DELETED, Path.GetFileName(fileInfo.FullPath)));
                        }
                    }

                    fileInfo = new FileInfo(Path.Combine(BackupPath, fname), DateTime.Now, number);
                }

                if (fileInfo == null)
                {
                    string fname = string.Format("AutoBackup_{0}_{1}{2}", 1, DateTime.Now.ToString("yyyyMMdd_HHmm"), Constants.EXT_ZIP);
                    fileInfo = new FileInfo(Path.Combine(BackupPath, fname), DateTime.Now, 1);
                }

                if (File.Exists(fileInfo.FullPath))
                {
                    File.Delete(fileInfo.FullPath);
                    Messenger.AddInfo(string.Format(Messages.MSG_BACKUP_DELETED, Path.GetFileName(fileInfo.FullPath)));
                }

                name = Path.GetFileName(fileInfo.FullPath);

                if (name != null)
                {
                    Messenger.AddInfo("Autobackup started.");
                    BackupDirectoryAsync(dir, name, Path.Combine(BackupPath, name), zipPath);
                }
            }
            else
            {
                Messenger.AddInfo(string.Format(Messages.MSG_FOLDER_NOT_FOUND, BackupPath));
            }
        }
Example #25
0
        /// <summary>
        /// Scans the KSP install directory and sub directories for *.craft files.
        /// </summary>
        private static void ScanDir()
        {
            View.ShowProcessingIcon = true;
            EventDistributor.InvokeAsyncTaskStarted(Instance);

            ResetView();

            AsyncTask <bool> .DoWork(() =>
            {
                Messenger.AddInfo(Messages.MSG_CRAFT_SCAN_STARTED);

                // Get *.craft files from GameData folder.
                string gameDatePath = KSPPathHelper.GetPath(KSPPaths.GameData);
                string[] files      = Directory.GetFiles(gameDatePath, EXTENSION_CRAFT, SearchOption.AllDirectories);

                // Get *.craft files from additional folders.
                string path1      = KSPPathHelper.GetPath(KSPPaths.VAB);
                string path2      = KSPPathHelper.GetPath(KSPPaths.SPH);
                string[] addPaths = new[] { path1, path2 };
                foreach (var path in addPaths)
                {
                    string[] files2 = Directory.GetFiles(path, EXTENSION_CRAFT, SearchOption.AllDirectories);
                    int oldLength   = files.Length;
                    Array.Resize <string>(ref files, oldLength + files2.Length);
                    Array.Copy(files2, 0, files, oldLength, files2.Length);
                }

                // Create CraftNodes from each file.
                var nodes = new List <CraftNode>();
                if (files.Length > 0)
                {
                    foreach (string file in files)
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_SCAN_FILE_0_FOR_CRAFTS, file));
                        var newNodes = CreateCraftEntry(file);
                        foreach (var newNode in newNodes)
                        {
                            if (newNode != null && !string.IsNullOrEmpty(newNode.Name) && !nodes.Contains(newNode))
                            {
                                nodes.Add(newNode);
                            }
                        }
                    }
                }
                else
                {
                    Messenger.AddInfo(string.Format(Messages.MSG_NO_CRAFTCFG_FOUND_0, gameDatePath));
                }

                allCrafts.Clear();
                foreach (CraftNode node in nodes)
                {
                    allCrafts.Add(node);
                }

                Messenger.AddInfo(Messages.MSG_CRAFT_SCAN_DONE);

                return(true);
            },
                                     (bool result, Exception ex) =>
            {
                View.ShowProcessingIcon = false;
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (ex != null)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_CRAFT_READING_0, ex.Message), ex);
                }
                else
                {
                    RefreshTreeView();
                    ValidateCrafts();
                }
            });
        }
        /// <summary>
        /// Scans the KSP install directory and sub directories for *.craft files.
        /// </summary>
        private static void ScanDir()
        {
            allModFilter.Clear();
            allModFilter.Add(All);
            allModFilter.Add(Squad);
            View.SelectedModFilter = All;

            model.Nodes.Clear();

            View.ShowProcessingIcon = true;
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            AsyncTask <bool> .DoWork(() =>
            {
                Messenger.AddInfo(Messages.MSG_PART_SCAN_STARTED);

                // Get part.cfg files from GameData folder.
                string gameDatePath = KSPPathHelper.GetPath(KSPPaths.GameData);
                string[] files      = Directory.GetFiles(gameDatePath, EXTENSION_CFG, SearchOption.AllDirectories);

                // Get part.cfg files from additional folders.
                string partsPath  = KSPPathHelper.GetPath(KSPPaths.Parts);
                string[] addPaths = new[] { partsPath };
                foreach (var path in addPaths)
                {
                    string[] files2 = Directory.GetFiles(path, EXTENSION_CFG, SearchOption.AllDirectories);
                    int oldLength   = files.Length;
                    Array.Resize <string>(ref files, oldLength + files2.Length);
                    Array.Copy(files2, 0, files, oldLength, files2.Length);
                }

                // Create PartNodes from each file.
                var nodes = new List <PartNode>();
                if (files.Length > 0)
                {
                    foreach (string file in files)
                    {
                        Messenger.AddInfo(string.Format(Messages.MSG_SCAN_FILE_0_FOR_PARTS, file));
                        var newNodes = CreatePartNodes(file);
                        foreach (var newNode in newNodes)
                        {
                            if (newNode != null && !string.IsNullOrEmpty(newNode.Name) && !nodes.Contains(newNode))
                            {
                                nodes.Add(newNode);
                            }
                        }
                    }
                }
                else
                {
                    Messenger.AddInfo(string.Format(Messages.MSG_NO_PARTCFG_FOUND_0, gameDatePath));
                }

                allNodes.Clear();
                foreach (PartNode node in nodes)
                {
                    allNodes.Add(node);
                }

                Messenger.AddInfo(Messages.MSG_PART_SCAN_DONE);

                return(true);
            },
                                     (result, ex) =>
            {
                View.ShowProcessingIcon = false;
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (ex != null)
                {
                    Messenger.AddError(string.Format(Messages.MSG_ERROR_DURING_PART_READING_0, ex.Message), ex);
                }
                else
                {
                    RefreshTreeView();
                }

                if (ScanComplete != null)
                {
                    ScanComplete(Parts);
                }
            });
        }