/// <summary> /// Creates a UniFile based on the information from this FSNodeFile. /// </summary> /// <param name="onlyVirtual">Set to true to only return a UniFile if this file is virtual (otherwise null).</param> /// <param name="onlyLocal">Set to true to only return a UniFile if this file is local (otherwise null).</param> /// <returns></returns> public virtual UniFile GetUniFile(bool onlyVirtual = false, bool onlyLocal = false) { if (onlyVirtual) { return(null); } UniFile uniFile = null; try { // try to open it uniFile = new UniFile(GetPath()); } catch (Exception e) { UIHelper.ShowError( "An error occured while trying to load the file! Please ensure that it still exists! Info: {0}", e.Message); if (uniFile != null) { uniFile.Close(); } LoggingManager.HandleException(e); } return(uniFile); }
static public bool SetupConfigSystem(string configFilePath) { ModManager.ApplicationExit += ModManagerApplicationExit; LoggingManager.SendMessage("ConfigManager - Setting up config system..."); if (!File.Exists(configFilePath)) { LoggingManager.SendMessage("ConfingManager - No plugins.config found, creating one from scratch"); } s_sConfigFilePath = configFilePath; FileStream config = null; try { config = File.Open(configFilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); s_pluginsConfig = XmlConfigReader.Read(config); } catch (Exception e) { LoggingManager.SendMessage("ConfigManager - Failed to set up config system from file: " + configFilePath); LoggingManager.HandleException(e); return(false); } finally { if (config != null) { config.Close(); } } LoggingManager.SendMessage("ConfigManager - Config system set up successfully!"); return(true); }
static void ModManagerApplicationExit() { FileStream configFile = null; try { if (s_pluginsConfig != null) { configFile = File.Open(s_sConfigFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); XmlConfigWriter.Write(s_pluginsConfig, configFile); configFile.Flush(); } } catch (Exception ex) { LoggingManager.SendMessage("ConfigManager - Could not write config file"); LoggingManager.HandleException(ex); UIHelper.ShowError("Failed to save configuration file. See Log file for more information."); } finally { if (configFile != null) { configFile.Close(); } } }
static private void LoadPlugin(Assembly assembly) { try { foreach (Type type in assembly.GetTypes()) { if (!type.IsSubclassOf(typeof(ModToolPlugin))) { continue; } var plugin = type.GetConstructor(Type.EmptyTypes).Invoke(null) as ModToolPlugin; if (type.IsSubclassOf(typeof(FileTypePlugin))) { var ftp = plugin as FileTypePlugin; string[] exts = ftp.FileExtensions; foreach (string ext in exts) { if (!FileTypePlugins.ContainsKey(ext.ToLower())) { FileTypePlugins.Add(ext.ToLower(), new List <FileTypePlugin>()); } FileTypePlugins[ext.ToLower()].Add(ftp); } } var pluginMenu = new ToolStripMenuItem(plugin.PluginName) { Name = type.FullName }; plugin.Init(new PluginEnvironment(pluginMenu.DropDownItems, ModToolEnvironment.CombinedFileTreeContext, ModToolEnvironment.VirtualFileTreeContext)); if (pluginMenu.DropDownItems.Count > 0) { ModToolEnvironment.PluginMenu.Add(pluginMenu); } else { pluginMenu.Dispose(); } } } catch (ReflectionTypeLoadException e) { LoggingManager.SendMessage("PluginManager - Could not load plugin!"); LoggingManager.SendMessage("LoaderExceptions: "); foreach (Exception exc in e.LoaderExceptions) { LoggingManager.HandleException(exc); } LoggingManager.HandleException(e); UIHelper.ShowError("Could not load plugin " + assembly.FullName + ": " + e.Message); } catch (Exception e) { LoggingManager.SendMessage("PluginManager - Could not load plugin!"); LoggingManager.HandleException(e); UIHelper.ShowError("Could not load plugin " + assembly.FullName + ": " + e.Message); } }
static void LoadDoW2UCS() { if (File.Exists(DoW2UCSPath)) { LoggingManager.SendMessage("UCSManager - UCS file for vanilla DoW2 found."); if (s_dow2UCS == null) { FileStream ucs = null; try { ucs = File.Open(DoW2UCSPath, FileMode.Open, FileAccess.Read, FileShare.Read); s_dow2UCS = UCSReader.Read(ucs); } catch (CopeDoW2Exception ex) { LoggingManager.HandleException(ex); UIHelper.ShowError(ex.Message); ModManager.RequestAppExit(ex.Message); } finally { if (ucs != null) { ucs.Close(); } } } } else { LoggingManager.SendMessage("UCSManager - UCS file for vanilla DoW2 not found; we might operate in some strange place other than the DoW2 directory."); } }
static private void TryToGetKeyProvider() { const string flbPath = "simulation\\attrib\\fieldnames.flb"; if (!ToolSettings.IsInRetributionMode) { LoggingManager.SendMessage("ModManager - not in Retribuion-mode, no need to load KeyProvider"); return; } LoggingManager.SendMessage("ModManager - Trying to load the KeyProvider (FLB-file)"); try { FSNodeFile file = FileManager.AttribTree.RootNode.GetFileByPath(flbPath); if (file == null) { UIHelper.ShowWarning("Unable to find the FLB file! You probably won't be able to open RBFs."); LoggingManager.SendWarning("ModManager - Failed to load FLB-file from path " + flbPath); return; } UniFile uni = file.GetUniFile(); var flbFile = new FieldNameFile(uni); flbFile.ReadData(); RBFKeyProvider = flbFile; } catch (Exception ex) { UIHelper.ShowError("Unable to open or read the FLB file! You probably won't be able to open RBFs."); LoggingManager.SendError("ModManager - Error while loading FLB-file"); LoggingManager.HandleException(ex); return; } LoggingManager.SendMessage("ModManager - Successfully loaded KeyProvider from " + flbPath); }
public static void SaveUCS() { if (s_modUCS == null || s_modUCS.StringCount <= 0) { LoggingManager.SendMessage("UCSManager - UCS file is empty, nothing to save."); return; } LoggingManager.SendMessage("UCSManager - Saving UCS file for current mod..."); FileStream ucs = null; try { ucs = File.Create(ModUCSPath); UCSWriter.Write(s_modUCS, ucs); } catch (Exception ex) { LoggingManager.SendMessage("UCSManager - Failed to save UCS file!"); LoggingManager.HandleException(ex); UIHelper.ShowError("Failed to save UCS file! See the log for more details!"); return; } finally { if (ucs != null) { ucs.Close(); } } LoggingManager.SendMessage("UCSManager - Successfully saved UCS file!"); }
/// <exception cref="CopeException"><c>CopeException</c>.</exception> private void WriteDesignFile(string designFilePath, string archiveOutputPath) { if (File.Exists(designFilePath)) { try { File.Delete(designFilePath); } catch (Exception ex) { string msg = "Tried to delete archive design file, but failed. Path: " + designFilePath; LoggingManager.SendError("ArchiveCreator - " + msg); LoggingManager.HandleException(ex); throw new CopeException(ex, msg); } } try { StreamWriter designFile = File.CreateText(designFilePath); designFile.WriteLine(string.Format(Resources.ArchiveDesign, ArchiveAlias, TocName, Regex)); designFile.Flush(); designFile.Close(); } catch (Exception ex) { string msg = "Tried to write archive design file, but failed. Path: " + designFilePath; LoggingManager.SendError("ArchiveCreator - " + msg); LoggingManager.HandleException(ex); throw new CopeException(ex, msg); } }
/// <exception cref="CopeException">Could not start archive.exe</exception> private static Process StartPacker(string arguments) { Process archivePacker = null; try { string archiveToolPath = ArchiveToolHelper.GetArchiveToolPath(); var startInfo = new ProcessStartInfo { Arguments = arguments, CreateNoWindow = true, ErrorDialog = true, UseShellExecute = false, FileName = archiveToolPath, WorkingDirectory = archiveToolPath.SubstringBeforeLast('\\') }; LoggingManager.SendMessage("ArchiveCreator - Starting archive.exe with " + arguments); archivePacker = Process.Start(startInfo); return(archivePacker); } catch (Exception ex) { if (archivePacker != null) { archivePacker.Kill(); archivePacker.Dispose(); } LoggingManager.SendError("ArchiveCreator - Failed to start archive.exe"); LoggingManager.HandleException(ex); throw new CopeException(ex, "Could not start archive.exe" + ex.Message); } }
/// <summary> /// Returns a UniFile based on the information from this FSNodeVirtualFile. It will first search for a local file and if there's no local file it'll get the virtual file. /// </summary> /// <param name="onlyVirtual">Set to true to ignore local files.</param> /// <param name="onlyLocal">Set to true to ignore virtual files.</param> /// <returns></returns> public override UniFile GetUniFile(bool onlyVirtual = false, bool onlyLocal = false) { UniFile uniFile = null; if (!onlyVirtual && HasLocal) { try { // try to open it uniFile = new UniFile(GetPath()); } catch (Exception e) { UIHelper.ShowError( "An error occured while trying to load the file! Please ensure that it still exists! Info: {0}", e.Message); if (uniFile != null) { uniFile.Close(); } LoggingManager.HandleException(e); } return(uniFile); } // is it stored in a SGA archive? if (!onlyLocal || !HasLocal) { SGAStoredFile sgasfExtract = VirtualFile; try { // try to extract that file for our use into RAM uniFile = new UniFile(sgasfExtract.SGA.ExtractFile(sgasfExtract, (sgasfExtract.SGA.Stream))); } catch (Exception e) { UIHelper.ShowError( "An error occured while trying to load the file! Please ensure that it's SGA archive still exists! Info: {0}", e.Message); if (uniFile != null) { uniFile.Close(); } LoggingManager.HandleException(e); } // set a pseudo path that will be used when saving the file if (uniFile != null) { uniFile.FilePath = GetPath(); } } return(uniFile); }
private void DeleteDesignFile() { if (!File.Exists(m_sDesignFilePath)) { return; } try { File.Delete(m_sDesignFilePath); } catch (Exception ex) { LoggingManager.SendError("ArchiveCreator - tried to delete superfluous SGA-design file but failed"); LoggingManager.HandleException(ex); } }
static void LoadModUCS() { LoggingManager.SendMessage( "UCSManager - UCS file for current mod " + (File.Exists(ModUCSPath) ? "found." : "not found, will create a new one.")); FileStream ucs = null; try { if (File.Exists(ModUCSPath)) { ucs = File.Open(ModUCSPath, FileMode.Open, FileAccess.Read, FileShare.Read); s_modUCS = UCSReader.Read(ucs); } else { s_modUCS = new UCSStrings(); } } catch (CopeDoW2Exception ex) { LoggingManager.HandleException(ex); UIHelper.ShowError(ex.Message); ModManager.RequestAppExit(ex.Message); } finally { if (ucs != null) { ucs.Close(); } } if (s_modUCS.NextIndex > s_nextIndex) { s_nextIndex = s_modUCS.NextIndex; } else { s_modUCS.NextIndex = s_nextIndex; } s_modUCS.StringAdded += OnStringAdded; s_modUCS.StringModified += OnStringModified; s_modUCS.StringRemoved += OnStringRemoved; }
static public void LoadSGAFile(string path) { CloseAll(); LoggingManager.SendMessage("ModManager - Loading SGA file " + path); DateTime t1 = DateTime.Now; // the tool needs some paths to work with but SGAs of course don't provide these // so you need to set them up manually ModAttribDirectory = path.SubstringBeforeLast('.') + "\\ATTRIB\\"; ModDataDirectory = path.SubstringBeforeLast('.') + "\\DATA\\"; SGAFile sga; try { sga = new SGAFile(path, FileAccess.Read, FileShare.Read); } catch (Exception e) { LoggingManager.SendError("ModManager - Failed to load SGA file!"); LoggingManager.HandleException(e); UIHelper.ShowError("Can't open SGA file: " + e.Message + " See log file for more information"); if (LoadingFailed != null) { LoadingFailed(); } return; } ModAttribArchives.Add(sga); ModDataArchives.Add(sga); ModName = path.SubstringAfterLast('\\'); DateTime t2 = DateTime.Now; LoggingManager.SendMessage("ModManager - SGA file successfully loaded in " + (t2 - t1).TotalSeconds + " seconds"); FileManager.FillTrees(); TryToGetKeyProvider(); if (SGALoaded != null) { SGALoaded(); } }
static public void LoadPlugins() { LoggingManager.SendMessage("PluginManager - Attempting to load plugins from plugins-folder " + s_path); FileTypePlugins = new Dictionary <string, List <FileTypePlugin> >(); if (!Directory.Exists(s_path)) { return; } var fileTypeDir = new DirectoryInfo(s_path + "filetypes"); foreach (FileInfo file in fileTypeDir.GetFiles("*.dll")) { try { AssemblyName.GetAssemblyName(file.FullName); Assembly assembly = Assembly.LoadFile(file.FullName); LoadPlugin(assembly); } catch (BadImageFormatException) // for non-.NET DLLs { continue; } catch (Exception e) { LoggingManager.SendMessage("PluginManager - Could not load plugin '" + file.FullName + "'!"); LoggingManager.HandleException(e); UIHelper.ShowError("Could not load plugin '" + file.FullName + "': " + e.Message); } } foreach (var kvp in FileTypePlugins) { if (kvp.Value.Count == 1) { FileTypeManager.FileTypes[kvp.Key] = kvp.Value[0]; } } LoggingManager.SendMessage("PluginManager - Plugins successfully loaded!"); }
/// <summary> /// Launches an instance of the plugin associated with the extension of the specified file name. /// </summary> /// <param name="fileName"></param> /// <param name="infile"></param> /// <exception cref="CopeException">Will throw an exception if there's no plugin for this file type.</exception> /// <returns></returns> static public FileTool LaunchFromExt(string fileName, UniFile infile) { string ext = fileName.SubstringAfterLast('.').ToLower(); if (!s_fileTypes.ContainsKey(ext)) { throw new CopeException("Unknown file extension: " + ext); } FileTypePlugin plugin = s_fileTypes[ext]; try { return(plugin.LoadFile(infile)); } catch (Exception e) { Type t = plugin.GetType(); LoggingManager.SendMessage("FileTypeManager - Error launching plugin " + t.FullName); LoggingManager.HandleException(e); throw new CopeException(e, "Error launching plugin " + t.FullName + ": " + e.Message); } }
/// <summary> /// Tries to load the specified UniFile and returns the proper FileTool. /// </summary> /// <param name="file"></param> /// <param name="forceText">Set this to true to always use the Text-editor.</param> /// <returns></returns> static public FileTool LoadFile(UniFile file, bool forceText = false) { if (!AllowOpeningFilesTwice && s_openTools.ContainsKey(file.FilePath)) { return(s_openTools[file.FilePath]); } FileTool tmp; byte[] stream = file.ConsumeStream(); UniFile filecopy = new UniFile(stream); filecopy.FilePath = file.FilePath; if (forceText) { try { tmp = new TextEditor(filecopy); } catch (Exception e) { UIHelper.ShowError("Can't open the selected file " + file.FileName + " as Text: " + e.Message); return(null); } } else if (FileTypeManager.FileTypes.ContainsKey(filecopy.FileExtension)) { tmp = FileTypeManager.LaunchFromExt(filecopy.FileName, filecopy); } else { try { tmp = new RelicChunkyViewer(filecopy); } catch { try { filecopy = new UniFile(stream); file.Stream.Position = 0; tmp = new TextEditor(filecopy); } catch (Exception ex) { LoggingManager.SendError("Failed to open file"); LoggingManager.HandleException(ex); file.Close(); UIHelper.ShowError("Can't open the selected file " + file.FileName + ", no suitable plugin found!"); return(null); } } } tmp.OnSaved += FileTool_OnSaved; if (!s_openTools.ContainsKey(file.FilePath)) { s_openTools.Add(file.FilePath, tmp); } if (FileLoaded != null) { FileLoaded(file, tmp); } return(tmp); }
// Todo: clean up this method! it's a mess! /// <exception cref="CopeDoW2Exception">The global section of the selected module file is invalid!</exception> static public void LoadModule(string path) { if (IsAnythingLoaded) { CloseAll(); } LoggingManager.SendMessage("ModManager - Loading module file " + path); GameDirectory = path.SubstringBeforeLast('\\', true); DateTime t1 = DateTime.Now; ModuleFile = new ModuleFile(path); // get basic mod information from module file try { ModAttribDirectory = path.SubstringBeforeLast('\\', true) + ((ModuleFile.ModuleSectionFileList)ModuleFile["attrib:common"]).GetFolderByIndex(0) + '\\'; ModDataDirectory = path.SubstringBeforeLast('\\', true) + ((ModuleFile.ModuleSectionFileList)ModuleFile["data:common"]).GetFolderByIndex(0) + '\\'; var globalSection = ModuleFile["global"] as ModuleFile.ModuleSectionKeyValue; if (globalSection != null) { ModName = globalSection["Name"]; s_sModFolder = globalSection["ModFolder"]; if (globalSection.KeyExists("UCSBaseIndex")) { UCSManager.NextIndex = uint.Parse(globalSection["UCSBaseIndex"]); } } else { throw new CopeDoW2Exception("The global section of the selected module file is invalid!"); } } catch (CopeDoW2Exception e) { LoggingManager.SendError("ModManager - Error loading module file: " + e.Message); LoggingManager.HandleException(e); UIHelper.ShowError("Error loading module file " + path.SubstringAfterLast('\\') + ": " + e.Message + ". See log file for more information."); ModuleFile.Close(); if (LoadingFailed != null) { LoadingFailed(); } return; } if (ModAttribDirectory == ModDataDirectory) { LoggingManager.SendError( "ModManager - The data:common directory and the attrib:common directory of the mod overlap! May cause serious trouble!"); UIHelper.ShowError( "The data:common directory and the attrib:common directory of the mod overlap! This tool does NOT support such module files." + "Please correct the module file before loading it, read the user guide for help."); ModuleFile.Close(); if (LoadingFailed != null) { LoadingFailed(); } return; } // load mod data if (ModDataArchives == null) { ModDataArchives = new List <SGAFile>(); } else { ModDataArchives.Clear(); } if (ModAttribArchives == null) { ModAttribArchives = new List <SGAFile>(); } else { ModAttribArchives.Clear(); } LoggingManager.SendMessage("ModManager - Loading mod resources"); List <SGAFile> currentArchives; foreach (ModuleFile.ModuleSection ms in ModuleFile) { if (ms is ModuleFile.ModuleSectionFileList && ms.SectionName == "attrib:common") { currentArchives = ModAttribArchives; } else if (ms is ModuleFile.ModuleSectionFileList && ms.SectionName == "data:common") { currentArchives = ModDataArchives; } else { continue; } var tmp = (ModuleFile.ModuleSectionFileList)ms; for (int i = 0; i < tmp.ArchiveCount; i++) { if (!File.Exists(ModuleFile.FilePath.SubstringBeforeLast('\\', true) + tmp.GetArchiveByIndex(i))) { continue; } try { currentArchives.Add( new SGAFile(ModuleFile.FilePath.SubstringBeforeLast('\\', true) + tmp.GetArchiveByIndex(i), FileAccess.Read, FileShare.Read)); } catch (Exception e) { LoggingManager.SendError("ModManager - Error loading SGA-file '" + tmp.GetArchiveByIndex(i) + "':" + e.Message); LoggingManager.HandleException(e); UIHelper.ShowError("Error loading SGA-files: " + e.Message + " See log file for more information."); ModuleFile.Close(); if (LoadingFailed != null) { LoadingFailed(); } return; } } } ModuleFile.Close(); DateTime t2 = DateTime.Now; LoggingManager.SendMessage("ModManager - Module file successfully loaded in " + (t2 - t1).TotalSeconds + " seconds"); FileManager.FillTrees(); TryToGetKeyProvider(); if (ModLoaded != null) { ModLoaded(); } }
/// <summary> /// Injects the FOB into DoW2. /// </summary> /// <param name="o"></param> private static void Inject(object o) { LogMessage("Searching for DoW2 process..."); Process[] ps = Process.GetProcessesByName("DoW2"); for (int i = 0; i < 10; i++) { Thread.Sleep(1000); ps = Process.GetProcessesByName("DoW2"); if (ps.Length > 0) { break; } } if (ps.Length <= 0) { LogMessage("TIME OUT! Could not find DoW2 process 10 seconds after launch. Please try again."); return; } LogMessage("Process found!"); Process dow2 = ps[0]; // Retribution does not use GFWL anymore, no need to patch the memory if (!ToolSettings.IsInRetributionMode) { LogMessage("Preparing process..."); try { dow2.ReplaceSequence(s_memoryCheckSignature, s_memoryCheckPatch, "xlive.dll", 1); } catch (Exception e) { LoggingManager.SendMessage("DebugManager - Patching failed!"); LoggingManager.HandleException(e); UIHelper.ShowError("Error launching DoW2, please try again."); return; } } LogMessage("Injecting Cope's Forward Operations Base"); try { s_callbackReceiver = new DummyReceiver(); s_client = dow2.InjectForwardOperationalBase(s_callbackReceiver); } catch (Exception e) { LoggingManager.SendMessage("DebugManager - Injecting FOB failed!"); LoggingManager.HandleException(e); UIHelper.ShowError("Failed to start debugging system, please try again"); return; } string currentDir = Directory.GetCurrentDirectory() + '\\'; LogMessage("Injecting ModDebug.dll and initializing DebugManager..."); try { //dow2.InjectDll("M:\\Steam\\steamapps\\common\\dawn of war 2\\CopeLua.dll"); //dow2.InjectDll(currentDir + "LuaLibLoad.dll"); s_client.LoadAssemblyAndStartMethod(currentDir + "ModDebug.dll", "ModDebug.DebugManager", "Init", true); } catch (Exception e) { LoggingManager.SendMessage("DebugManager - Initializtaion of remote DebugManager failed!"); LoggingManager.HandleException(e); UIHelper.ShowError("Initialization of the remote DebugManager failed!"); return; } LogMessage("Setup done!"); dow2.Exited += OnGameExited; }
static void WatcherError(object sender, ErrorEventArgs e) { LoggingManager.SendMessage("FileSystemWatcher buffer overflow!"); LoggingManager.HandleException(e.GetException()); }