static void OnModLoaded() { LoggingManager.SendMessage("UCSManager - Trying to load UCS files..."); LoadModUCS(); LoadDoW2UCS(); LoggingManager.SendMessage("UCSManager - Done loading UCS files!"); }
/// <exception cref="CopeException"><c>CopeException</c>.</exception> public ArchivePackerInfo PackArchive(string outputPath) { if (!ArchiveToolHelper.IsArchiveToolPresent()) { string msg = "Archive tool has not been found! Searched at: " + ArchiveToolHelper.GetArchiveToolPath(); LoggingManager.SendError("ArchiveCreator - " + msg); throw new CopeException(msg); } if (!outputPath.EndsWith('\\')) { outputPath += '\\'; } string uniqueName = ArchiveName + '_' + DateTime.Now.ToProperString('_'); string designFilePath = ArchiveToolHelper.GetArchiveToolDirectory() + uniqueName + ".sga_design"; WriteDesignFile(designFilePath, outputPath + ArchiveName); string arguments = string.Format(ARCHIVE_ARGUMENTS, InputDirectory.RemoveLast(1), outputPath + ArchiveName, uniqueName); Process packer = StartPacker(arguments); if (packer == null || packer.Id == 0 || packer.Id == 1) { LoggingManager.SendError("ArchiveCreator - failed to start packer. Arguments: " + arguments); throw new CopeException("Failed to start archive.exe"); } return(new ArchivePackerInfo(packer, designFilePath, outputPath + ArchiveName)); }
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."); } }
public static void ReloadModUCS() { LoggingManager.SendMessage("UCSManager - Reloading Mod-UCS file"); s_nextIndex = 0; LoadModUCS(); LoggingManager.SendMessage("UCSManager - Finished reloading"); }
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); } }
public static void Init() { LoggingManager.SendMessage("UCSManager - Initializing..."); ModManager.ModLoaded += OnModLoaded; ModManager.ModUnloaded += OnModUnloaded; ModManager.ModLanguageChanged += OnModLanguageChanged; }
/// <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); }
static internal void ReleaseFileTrees() { LoggingManager.SendMessage("FileManager - Releasing file trees"); if (s_attribTree != null) { s_attribTree.ShutDown(); } s_attribTree = null; if (s_dataTree != null) { s_dataTree.ShutDown(); } s_dataTree = null; }
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 internal void FillTrees() { LoggingManager.SendMessage("FileManager - Filling file trees"); DateTime t1 = DateTime.Now; if (ModManager.ModDataArchives != null) { s_dataTree = new FileTree(ModManager.ModDataDirectory, ModManager.ModDataArchives, "data"); } if (ModManager.ModAttribArchives != null) { s_attribTree = new FileTree(ModManager.ModAttribDirectory, ModManager.ModAttribArchives, "attrib"); } DateTime t2 = DateTime.Now; LoggingManager.SendMessage("FileManager - File trees filled in" + (t2 - t1).TotalSeconds + " seconds"); if (FileTreesChanged != null) { FileTreesChanged(); } }
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!"); }
static public void CloseAll() { LoggingManager.SendMessage("ModManager - Closing current mod (if any is loaded)"); if (ModuleFile != null) { ModuleFile.Close(); ModuleFile = null; } if (ModAttribArchives != null) { foreach (SGAFile sga in ModAttribArchives) { sga.Close(); } ModAttribArchives.Clear(); } if (ModDataArchives != null) { foreach (SGAFile sga in ModDataArchives) { sga.Close(); } ModDataArchives.Clear(); } FileManager.ReleaseFileTrees(); if (ModUnloaded != null) { ModUnloaded(); } ModName = null; // normally it isn't a good idea to manually invoke the GarbageCollection but in this case we're releasing // gigabytes of resources; the overall performance greatly benefits from this LoggingManager.SendMessage("ModManager - Manual GarbageCollection in all generations in progess..."); GC.Collect(); }
/// <summary> /// Closes any open connection, searches for DoW2 and injects the ForwardOperationsBase. /// </summary> public static void StartDebugging() { LoggingManager.SendMessage("DebugManager - Advanced mode started"); if (s_client != null) { try { s_client.Close(); } catch (Exception) { } s_client = null; } ClearLog(); if (s_window == null || s_window.IsDisposed) { s_window = new DebugWindow(); } ThreadPool.QueueUserWorkItem(Inject); ShowDebugWindow(); }
/// <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> /// Adds all nodes from this FileTree to a TreeNodeCollection. /// </summary> /// <param name="owner">The owner of the TreeNodeCollection, e.g. the TreeView.</param> /// <param name="collection">The collection to add the File nodes to.</param> /// <param name="rootName">The name of the rootnode.</param> /// <param name="usePictures">Set to true to set the picture index for the TreeNodes.</param> /// <param name="noVirtual">Set to true to exclude virtual files.</param> /// <param name="noLocal">Set to true to exclude local files.</param> /// <param name="colorLocalFiles">Set to true to color local files.</param> /// <param name="colorLocalDirs">Set to true to color local directories.</param> public void TransferIntoTreeNodeCollection(Control owner, TreeNodeCollection collection, string rootName, bool usePictures = true, bool noVirtual = false, bool noLocal = false, bool colorLocalFiles = true, bool colorLocalDirs = true) { if (m_rootNode == null) { LoggingManager.SendWarning("Tried to convert a FileTree without a RootNode to a node collection"); return; } var root = new TreeNode(rootName) { Name = 'D' + rootName }; TransferIntoTnc(owner, m_rootNode, root.Nodes, noVirtual, noLocal, usePictures, colorLocalFiles, colorLocalDirs); if (owner.InvokeRequired) { MethodInvoker k = () => collection.Add(root); owner.Invoke(k); } else { collection.Add(root); } }
// 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(); } }
static DebugManager() { LoggingManager.SendMessage("DebugManager - Initializing DebugManager"); ModManager.ApplicationExit += ModManagerApplicationExit; LoggingManager.SendMessage("DebugManager - Initialization finished"); }
/// <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()); }
/// <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); }