public EncryptionInfo(DirectoryNode dir) { DocumentInputStream dis = dir.CreateDocumentInputStream("EncryptionInfo"); versionMajor = dis.ReadShort(); versionMinor = dis.ReadShort(); encryptionFlags = dis.ReadInt(); if (versionMajor == 4 && versionMinor == 4 && encryptionFlags == 0x40) { StringBuilder builder = new StringBuilder(); byte[] xmlDescriptor = new byte[dis.Available()]; dis.Read(xmlDescriptor); foreach (byte b in xmlDescriptor) builder.Append((char)b); string descriptor = builder.ToString(); header = new EncryptionHeader(descriptor); verifier = new EncryptionVerifier(descriptor); } else { int hSize = dis.ReadInt(); header = new EncryptionHeader(dis); if (header.Algorithm == EncryptionHeader.ALGORITHM_RC4) { verifier = new EncryptionVerifier(dis, 20); } else { verifier = new EncryptionVerifier(dis, 32); } } }
public static void DisplayDirectory(DirectoryNode dir, String indent) { Console.WriteLine(indent + dir.Name + " -"); String newIndent = indent + " "; IEnumerator it = dir.Entries; while (it.MoveNext()) { Object entry = it.Current; if (entry is DirectoryNode) { DisplayDirectory((DirectoryNode)entry, newIndent); } else { DocumentNode doc = (DocumentNode)entry; String name = doc.Name; if (name[0] < 10) { String altname = "(0x0" + (int)name[0] + ")" + name.Substring(1); name = name.Substring(1) + " <" + altname + ">"; } Console.WriteLine(newIndent + name); } } }
public void TestConstructor() { DirectoryProperty property1 = new DirectoryProperty("directory"); RawDataBlock[] rawBlocks = new RawDataBlock[4]; MemoryStream stream = new MemoryStream(new byte[2048]); for (int j = 0; j < 4; j++) { rawBlocks[j] = new RawDataBlock(stream); } POIFSDocument document = new POIFSDocument("document", rawBlocks, 2000); DocumentProperty property2 = document.DocumentProperty; DirectoryNode parent = new DirectoryNode(property1, (POIFSFileSystem)null, null); DocumentNode node = new DocumentNode(property2, parent); // Verify we can retrieve the document Assert.AreEqual(property2.Document, node.Document); // Verify we can Get the size Assert.AreEqual(property2.Size, node.Size); // Verify isDocumentEntry returns true Assert.IsTrue(node.IsDocumentEntry); // Verify isDirectoryEntry returns false Assert.IsTrue(!node.IsDirectoryEntry); // Verify GetName behaves correctly Assert.AreEqual(property2.Name, node.Name); // Verify GetParent behaves correctly Assert.AreEqual(parent, node.Parent); }
public DirectoryNode(DirectoryNode parent, string name) { this.parent = parent; Name = name; Files = new Dictionary<string, AssetEntry>(); children = new Dictionary<string, DirectoryNode>(); }
static void ExcludeDirectoryNode(DirectoryNode directoryNode) { if (directoryNode.ProjectItem != null) { ProjectService.RemoveProjectItem(directoryNode.Project, directoryNode.ProjectItem); directoryNode.ProjectItem = null; } directoryNode.FileNodeStatus = FileNodeStatus.None; }
public static void CopyDirectory(string directoryName, DirectoryNode node, bool includeInProject) { directoryName = FileUtility.NormalizePath(directoryName); string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(directoryName)); LoggingService.Debug("Copy " + directoryName + " to " + copiedFileName); if (!FileUtility.IsEqualFileName(directoryName, copiedFileName)) { if (includeInProject && ProjectService.OpenSolution != null) { // get ProjectItems in source directory foreach (IProject project in ProjectService.OpenSolution.Projects) { if (!FileUtility.IsBaseDirectory(project.Directory, directoryName)) continue; LoggingService.Debug("Searching for child items in " + project.Name); foreach (ProjectItem item in project.Items) { FileProjectItem fileItem = item as FileProjectItem; if (fileItem == null) continue; string virtualFullName = Path.Combine(project.Directory, fileItem.VirtualName); if (FileUtility.IsBaseDirectory(directoryName, virtualFullName)) { if (item.ItemType == ItemType.Folder && FileUtility.IsEqualFileName(directoryName, virtualFullName)) { continue; } LoggingService.Debug("Found file " + virtualFullName); FileProjectItem newItem = new FileProjectItem(node.Project, fileItem.ItemType); if (FileUtility.IsBaseDirectory(directoryName, fileItem.FileName)) { newItem.FileName = FileUtility.RenameBaseDirectory(fileItem.FileName, directoryName, copiedFileName); } else { newItem.FileName = fileItem.FileName; } fileItem.CopyMetadataTo(newItem); if (fileItem.IsLink) { string newVirtualFullName = FileUtility.RenameBaseDirectory(virtualFullName, directoryName, copiedFileName); fileItem.SetEvaluatedMetadata("Link", FileUtility.GetRelativePath(node.Project.Directory, newVirtualFullName)); } ProjectService.AddProjectItem(node.Project, newItem); } } } } FileService.CopyFile(directoryName, copiedFileName, true, false); DirectoryNode newNode = new DirectoryNode(copiedFileName); newNode.InsertSorted(node); if (includeInProject) { IncludeFileInProject.IncludeDirectoryNode(newNode, false); } newNode.Expanding(); } else if (includeInProject) { foreach (TreeNode childNode in node.Nodes) { if (childNode is DirectoryNode) { DirectoryNode directoryNode = (DirectoryNode)childNode; if (FileUtility.IsEqualFileName(directoryNode.Directory, copiedFileName)) { IncludeFileInProject.IncludeDirectoryNode(directoryNode, true); } } } } }
public MainWindow() { InitializeComponent(); var dir = new DirectoryNode(@"c:\"); treeview1.Items.Add(dir.ToTreeViewItem()); treeview1.Focus(); (treeview1.Items[0] as TreeViewItem).IsSelected = true; }
/// <summary> /// Creates an instance of this class from an embedded OLE Object. The OLE Object is expected /// to include a stream "{01}Ole10Native" which contains the actual /// data relevant for this class. /// </summary> /// <param name="directory">directory POI Filesystem object</param> /// <returns>Returns an instance of this class</returns> public static Ole10Native CreateFromEmbeddedOleObject(DirectoryNode directory) { DocumentEntry nativeEntry = (DocumentEntry)directory.GetEntry(OLE10_NATIVE); byte[] data = new byte[nativeEntry.Size]; directory.CreateDocumentInputStream(nativeEntry).Read(data); return new Ole10Native(data, 0); }
public AbstractBrowserNode BuildProjectTreeNode(Project project) { ProjectBrowserNode projectNode = new ProjectBrowserNode(project); //projectNode.IconImage = iconService.GetImageForProjectType(project.ProjectType); // create 'empty' directories for (int i = 0; i < project.ProjectFiles.Count; ++i) { if (project.ProjectFiles[i].Subtype == Subtype.Directory) { string directoryName = fileUtilityService.AbsoluteToRelativePath(project.BaseDirectory, project.ProjectFiles[i].Name); // if directoryname starts with ./ oder .\ if (directoryName.StartsWith(".")) { directoryName = directoryName.Substring(2); } string parentDirectory = Path.GetFileName(directoryName); AbstractBrowserNode currentPathNode = GetPath(directoryName, projectNode, true); DirectoryNode newFolderNode = new DirectoryNode(project.ProjectFiles[i].Name); //newFolderNode.OpenedImage = resourceService.GetBitmap ("Icons.16x16.OpenFolderBitmap"); //newFolderNode.ClosedImage = resourceService.GetBitmap ("Icons.16x16.ClosedFolderBitmap"); currentPathNode.Nodes.Add(newFolderNode); } } // create file tree for (int i = 0; i < project.ProjectFiles.Count; ++i) { if (project.ProjectFiles[i].Subtype != Subtype.Directory) { ProjectFile fileInformation = project.ProjectFiles[i]; string relativeFile = fileUtilityService.AbsoluteToRelativePath(project.BaseDirectory, fileInformation.Name); string fileName = Path.GetFileName(fileInformation.Name); switch (fileInformation.BuildAction) { case BuildAction.Exclude: break; default: AbstractBrowserNode currentPathNode = GetPath(relativeFile, projectNode, true); AbstractBrowserNode newNode = new FileNode(fileInformation); newNode.ContextmenuAddinTreePath = FileNode.ProjectFileContextMenuPath; currentPathNode.Nodes.Add(newNode); break; } } } return projectNode; }
public void TestEmptyConstructor() { POIFSFileSystem fs = new POIFSFileSystem(); DirectoryProperty property1 = new DirectoryProperty("parent"); DirectoryProperty property2 = new DirectoryProperty("child"); DirectoryNode parent = new DirectoryNode(property1, fs, null); DirectoryNode node = new DirectoryNode(property2, fs, parent); Assert.AreEqual(0, parent.Path.Length); Assert.AreEqual(1, node.Path.Length); Assert.AreEqual("child", node.Path.GetComponent(0)); // Verify that GetEntries behaves correctly int count = 0; IEnumerator iter = node.Entries; while (iter.MoveNext()) { count++; } Assert.AreEqual(0, count); // Verify behavior of IsEmpty Assert.IsTrue(node.IsEmpty); // Verify behavior of EntryCount Assert.AreEqual(0, node.EntryCount); // Verify behavior of Entry try { node.GetEntry("foo"); Assert.Fail("Should have caught FileNotFoundException"); } catch (FileNotFoundException ) { // as expected } // Verify behavior of isDirectoryEntry Assert.IsTrue(node.IsDirectoryEntry); // Verify behavior of GetName Assert.AreEqual(property2.Name, node.Name); // Verify behavior of isDocumentEntry Assert.IsTrue(!node.IsDocumentEntry); // Verify behavior of GetParent Assert.AreEqual(parent, node.Parent); }
private NPOIFSFileSystem(bool newFS) { _header = new HeaderBlock(bigBlockSize); _property_table = new NPropertyTable(_header); _mini_store = new NPOIFSMiniStore(this, _property_table.Root, new List<BATBlock>(), _header); _xbat_blocks = new List<BATBlock>(); _bat_blocks = new List<BATBlock>(); _root = null; if (newFS) { // Data needs to Initially hold just the header block, // a single bat block, and an empty properties section _data = new ByteArrayBackedDataSource(new byte[bigBlockSize.GetBigBlockSize() * 3]); } }
private void addChilds(DirectoryNode parent, Storage parentStorage) { foreach (Storage storage in parentStorage) { try { var child = GetDirectoryNodeFromStorage(storage); parent.Nodes.Add(child); if (storage.isFolder()) addChilds(child, storage); } catch (Exception ex) { } } }
public static DirectoryNode GetFolderFilesInfo(string path,string basePath,bool isBase,bool md5) { DirectoryNode baseNode; string name = path; DirectoryInfo TheFolder = new DirectoryInfo(path); if (isBase) { baseNode = new DirectoryNode("Server", TheFolder.FullName, true); } else baseNode = new DirectoryNode(TheFolder.Name, TheFolder.FullName, true); baseNode.CreateTime = TheFolder.CreationTime; baseNode.ModifyTime = TheFolder.LastWriteTime; foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories()) { var node = GetFolderFilesInfo(NextFolder.FullName, path, false, md5); baseNode.Children.Add(node); } foreach (FileInfo NextFile in TheFolder.GetFiles()) { DirectoryNode node = new DirectoryNode(NextFile.Name, NextFile.FullName, false); node.Extension = NextFile.Extension; node.CreateTime = NextFile.CreationTime; node.ModifyTime = NextFile.LastWriteTime; var info= FileVersionInfo.GetVersionInfo(NextFile.FullName); //node.FileVersionInfo = FileVersionInfo.GetVersionInfo(NextFile.FullName); node.FileVersion = info.FileVersion; node.ProductVersion = info.ProductVersion; node.Size = NextFile.Length; if (md5) node.MD5 = GetMD5HashFromFile(NextFile.FullName); baseNode.Children.Add(node); } return baseNode; }
/** * create a DocumentNode. This method Is not public by design; it * Is intended strictly for the internal use of this package * * @param property the DocumentProperty for this DocumentEntry * @param parent the parent of this entry */ public DocumentNode(DocumentProperty property, DirectoryNode parent):base(property, parent) { _document = property.Document; }
private async Task <ContentEntryBase> CheckDirectoryNode(DirectoryNode directory, CancellationToken cancellation) { if (directory.Parent?.NameLowerCase == "python" && directory.Parent.Parent?.NameLowerCase == "apps" || directory.HasSubFile(directory.Name + ".py")) { var id = directory.Name; if (id == null) { // It’s unlikely there will be a car or a track in apps/python directory return(null); } // App? var root = directory.Parent?.Parent?.Parent; var gui = root?.GetSubDirectory("content")?.GetSubDirectory("gui")?.GetSubDirectory("icons"); // Collecting values… var missing = false; var uiAppFound = false; string version = null, name = null; // Maybe, it’s done nicely? var uiApp = directory.GetSubDirectory("ui")?.GetSubFile("ui_app.json"); if (uiApp != null) { uiAppFound = true; var data = await uiApp.Info.ReadAsync(); if (data == null) { missing = true; } else { var parsed = JsonExtension.Parse(data.ToUtf8String()); name = parsed.GetStringValueOnly("name"); version = parsed.GetStringValueOnly("version"); } } // Let’s try to guess version if (version == null && !uiAppFound) { foreach (var c in PythonAppObject.VersionSources.Select(directory.GetSubFile).NonNull()) { var r = await c.Info.ReadAsync(); if (r == null) { missing = true; } else { version = PythonAppObject.GetVersion(r.ToUtf8String()); if (version != null) { break; } } } } // And icon byte[] icon; List <FileNode> icons; if (gui != null) { icons = gui.Files.Where(x => x.NameLowerCase.EndsWith("_on.png") || x.NameLowerCase.EndsWith("_off.png")).ToList(); var mainIcon = icons.GetByIdOrDefault(directory.NameLowerCase + "_off.png") ?? icons.OrderByDescending(x => x.NameLowerCase.Length).FirstOrDefault(); icon = await(mainIcon?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); if (mainIcon != null && icon == null) { missing = true; } cancellation.ThrowIfCancellationRequested(); } else { icon = null; icons = null; } if (missing) { throw new MissingContentException(); } return(new PythonAppContentEntry(directory.Key ?? "", id, name ?? id, version, icon, icons?.Select(x => x.Key))); } var ui = directory.GetSubDirectory("ui"); if (ui != null) { // Is it a car? var uiCar = ui.GetSubFile("ui_car.json"); if (uiCar != null) { var icon = await(ui.GetSubFile("badge.png")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); var data = await uiCar.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); var carId = directory.Name ?? directory.GetSubDirectory("sfx")?.Files.Select(x => x.NameLowerCase) .FirstOrDefault(x => x.EndsWith(@".bank") && x.Count('.') == 1 && x != @"common.bank")?.ApartFromLast(@".bank"); if (carId != null) { return(new CarContentEntry(directory.Key ?? "", carId, parsed.GetStringValueOnly("parent") != null, parsed.GetStringValueOnly("name"), parsed.GetStringValueOnly("version"), icon)); } } // A track? var foundTrack = await CheckDirectoryNodeForTrack(directory, cancellation); if (foundTrack != null) { return(foundTrack); } // Or maybe a showroom? var uiShowroom = ui.GetSubFile(@"ui_showroom.json"); if (uiShowroom != null) { var icon = await(directory.GetSubFile(@"preview.jpg")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); var data = await uiShowroom.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); var showroomId = directory.Name ?? directory.Files.Where(x => x.NameLowerCase.EndsWith(@".kn5")).OrderByDescending(x => x.Info.Size) .FirstOrDefault()?.NameLowerCase.ApartFromLast(@".kn5"); if (showroomId != null) { return(new ShowroomContentEntry(directory.Key ?? "", showroomId, parsed.GetStringValueOnly("name"), parsed.GetStringValueOnly("version"), icon)); } } } else { // Another case for showrooms if (directory.Name != null && directory.HasSubFile(directory.Name + @".kn5") && directory.HasSubFile(@"colorCurves.ini") && directory.HasSubFile(@"ppeffects.ini")) { var icon = directory.HasSubFile(@"preview.jpg") ? await(directory.GetSubFile(@"preview.jpg")?.Info.ReadAsync() ?? throw new MissingContentException()) : null; cancellation.ThrowIfCancellationRequested(); return(new ShowroomContentEntry(directory.Key ?? "", directory.Name ?? throw new ArgumentException(), iconData: icon)); } } var uiTrackSkin = directory.GetSubFile("ui_track_skin.json"); if (uiTrackSkin != null && TracksManager.Instance != null) { var icon = await(directory.GetSubFile("preview.png")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); var data = await uiTrackSkin.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); var skinId = parsed.GetStringValueOnly("id") ?? directory.Name; var trackId = parsed.GetStringValueOnly("track"); var name = parsed.GetStringValueOnly("name"); if (skinId != null && trackId != null) { return(new TrackSkinContentEntry(directory.Key ?? "", skinId, trackId, name, parsed.GetStringValueOnly("version"), icon)); } } if (directory.HasSubFile("settings.ini")) { var kn5 = directory.Files.Where(x => x.NameLowerCase.EndsWith(@".kn5")).ToList(); var id = directory.Name; if (id != null) { if (kn5.Any(x => x.NameLowerCase.ApartFromLast(@".kn5") == directory.NameLowerCase)) { var icon = await(directory.GetSubFile("preview.jpg")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); return(new ShowroomContentEntry(directory.Key ?? "", id, AcStringValues.NameFromId(id), null, icon)); } } } var weatherIni = directory.GetSubFile("weather.ini"); if (weatherIni != null) { var icon = await(directory.GetSubFile("preview.jpg")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); var data = await weatherIni.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = IniFile.Parse(data.ToUtf8String()); var name = parsed["LAUNCHER"].GetNonEmpty("NAME"); if (name != null) { var id = directory.Name ?? name; return(new WeatherContentEntry(directory.Key ?? "", id, name, icon)); } } var uiCarSkin = directory.GetSubFile("ui_skin.json"); if ((uiCarSkin != null || directory.HasSubFile("preview.jpg") && directory.HasSubFile("livery.png")) && CarsManager.Instance != null /* for crawlers only */) { var icon = await(directory.GetSubFile("livery.png")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); cancellation.ThrowIfCancellationRequested(); string carId; var skinFor = await(directory.GetSubFile("cm_skin_for.json")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); if (skinFor != null) { carId = JsonExtension.Parse(skinFor.ToUtf8String())[@"id"]?.ToString(); } else { carId = _installationParams.CarId; if (carId == null && directory.Parent?.NameLowerCase == "skins") { carId = directory.Parent.Parent?.Name; } if (carId == null) { carId = AcContext.Instance.CurrentCar?.Id; } } if (carId == null) { throw new Exception("Can’t figure out car’s ID"); } var skinId = directory.Name; if (skinId != null) { string name; if (uiCarSkin != null) { var data = await uiCarSkin.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); name = parsed.GetStringValueOnly("name"); } else { name = AcStringValues.NameFromId(skinId); } return(new CarSkinContentEntry(directory.Key ?? "", skinId, carId, name, icon)); } } // New textures if (directory.NameLowerCase == "damage" && directory.HasSubFile("flatspot_fl.png")) { return(new TexturesConfigEntry(directory.Key ?? "", directory.Name ?? @"damage")); } if (directory.Parent?.NameLowerCase == "crew_brand" && directory.HasSubFile("Brands_Crew.dds") && directory.HasSubFile("Brands_Crew.jpg") && directory.HasSubFile("Brands_Crew_NM.dds")) { return(new CrewBrandEntry(directory.Key ?? "", directory.Name ?? @"unknown")); } if (directory.Parent?.NameLowerCase == "crew_helmet" && directory.HasSubFile("Crew_HELMET_Color.dds")) { return(new CrewHelmetEntry(directory.Key ?? "", directory.Name ?? @"unknown")); } // TODO: More driver and crew textures if (directory.NameLowerCase == "clouds" && directory.Files.Any( x => (x.NameLowerCase.StartsWith(@"cloud") || directory.Parent?.NameLowerCase == "texture") && x.NameLowerCase.EndsWith(@".dds"))) { return(new TexturesConfigEntry(directory.Key ?? "", directory.Name ?? @"clouds")); } if (directory.NameLowerCase == "clouds_shared" && directory.Files.Any( x => (x.NameLowerCase.StartsWith(@"cloud") || directory.Parent?.NameLowerCase == "texture") && x.NameLowerCase.EndsWith(@".dds"))) { return(new TexturesConfigEntry(directory.Key ?? "", directory.Name ?? @"clouds_shared")); } if (directory.NameLowerCase == "people" && (directory.HasSubFile("crowd_sit.dds") || directory.HasSubFile("people_sit.dds"))) { return(new TexturesConfigEntry(directory.Key ?? "", directory.Name ?? @"people")); } if (directory.HasSubFile("dwrite.dll") && directory.HasSubDirectory("extension")) { var dwrite = directory.GetSubFile("dwrite.dll"); var extension = directory.GetSubDirectory("extension"); var description = directory.GetSubFile("description.jsgme"); string version; if (description != null) { var data = await description.Info.ReadAsync() ?? throw new MissingContentException(); version = Regex.Match(data.ToUtf8String(), @"(?<=v)\d.*").Value?.TrimEnd('.').Or(null); } else { var parent = directory; while (parent.Parent?.Name != null) { parent = parent.Parent; } version = parent.Name != null?Regex.Match(parent.Name, @"(?<=v)\d.*").Value?.TrimEnd('.').Or(null) : null; } return(new ShadersPatchEntry(directory.Key ?? "", new[] { dwrite.Key, extension.Key }, version)); } if (directory.NameLowerCase == "__gbwsuite") { return(new CustomFolderEntry(directory.Key ?? "", new[] { directory.Key }, "GBW scripts", "__gbwSuite")); } if (directory.HasSubFile("weather.lua") && directory.Parent.NameLowerCase == "weather") { return(new CustomFolderEntry(directory.Key ?? "", new[] { directory.Key }, $"Weather FX script “{AcStringValues.NameFromId(directory.Name)}”", Path.Combine(AcRootDirectory.Instance.RequireValue, "extension", "weather", directory.Name), 1e5)); } if (directory.HasSubFile("controller.lua") && directory.Parent.NameLowerCase == "weather-controllers") { return(new CustomFolderEntry(directory.Key ?? "", new[] { directory.Key }, $"Weather FX controller “{AcStringValues.NameFromId(directory.Name)}”", Path.Combine(AcRootDirectory.Instance.RequireValue, "extension", "weather-controllers", directory.Name), 1e5)); } // Mod if (directory.Parent?.NameLowerCase == "mods" && (directory.HasAnySubDirectory("content", "apps", "system", "launcher", "extension") || directory.HasSubFile("dwrite.dll"))) { var name = directory.Name; if (name != null && directory.GetSubDirectory("content")?.GetSubDirectory("tracks")?.Directories.Any( x => x.GetSubDirectory("skins")?.GetSubDirectory("default")?.GetSubFile("ui_track_skin.json") != null) != true) { var description = directory.Files.FirstOrDefault(x => x.NameLowerCase.EndsWith(@".jsgme")); if (description == null && directory.HasSubDirectory("documentation")) { description = directory.GetSubDirectory("documentation")?.Files.FirstOrDefault(x => x.NameLowerCase.EndsWith(@".jsgme")); } if (description != null) { var data = await description.Info.ReadAsync() ?? throw new MissingContentException(); return(new GenericModConfigEntry(directory.Key ?? "", name, data.ToUtf8String())); } return(new GenericModConfigEntry(directory.Key ?? "", name)); } } return(null); }
/** * given a POI POIFSFileSystem object, and a specific directory * within it, read in its Workbook and populate the high and * low level models. If you're reading in a workbook...start here. * * @param directory the POI filesystem directory to process from * @param preserveNodes whether to preseve other nodes, such as * macros. This takes more memory, so only say yes if you * need to. If set, will store all of the POIFSFileSystem * in memory * @see org.apache.poi.poifs.filesystem.POIFSFileSystem * @exception IOException if the stream cannot be read */ public HSSFWorkbook(DirectoryNode directory, bool preserveNodes):base(directory) { String workbookName = GetWorkbookDirEntryName(directory); this.preserveNodes = preserveNodes; // If we're not preserving nodes, don't track the // POIFS any more if (!preserveNodes) { this.directory = null; } _sheets = new List<HSSFSheet>(INITIAL_CAPACITY); names = new List<HSSFName>(INITIAL_CAPACITY); // Grab the data from the workbook stream, however // it happens to be spelled. Stream stream = directory.CreatePOIFSDocumentReader(workbookName); List<Record> records = RecordFactory.CreateRecords(stream); workbook = InternalWorkbook.CreateWorkbook(records); SetPropertiesFromWorkbook(workbook); int recOffset = workbook.NumRecords; // Convert all LabelRecord records to LabelSSTRecord ConvertLabelRecords(records, recOffset); RecordStream rs = new RecordStream(records, recOffset); while (rs.HasNext()) { InternalSheet sheet = InternalSheet.CreateSheet(rs); _sheets.Add(new HSSFSheet(this, sheet)); } for (int i = 0; i < workbook.NumNames; ++i) { NameRecord nameRecord = workbook.GetNameRecord(i); HSSFName name = new HSSFName(this, workbook.GetNameRecord(i), workbook.GetNameCommentRecord(nameRecord)); names.Add(name); } }
private static String GetWorkbookDirEntryName(DirectoryNode directory) { String[] potentialNames = WORKBOOK_DIR_ENTRY_NAMES; for (int i = 0; i < potentialNames.Length; i++) { String wbName = potentialNames[i]; try { directory.GetEntry(wbName); return wbName; } catch (FileNotFoundException) { // continue - to try other options } } // Check for previous version of file format try { directory.GetEntry("Book"); throw new OldExcelFormatException("The supplied spreadsheet seems to be Excel 5.0/7.0 (BIFF5) format. " + "POI only supports BIFF8 format (from Excel versions 97/2000/XP/2003)"); } catch (FileNotFoundException) { // fall through } throw new ArgumentException("The supplied POIFSFileSystem does not contain a BIFF8 'Workbook' entry. " + "Is it really an excel file?"); }
/// <summary> /// Initializes a new instance of the <see cref="ColorCodePage"/> class. /// </summary> public ColorCodePage(DirectoryNode directoryNode) { InitializeComponent(); Model = new ColorCodePageViewModel(directoryNode, this); //GroupHeaderElement.UpdateHeader(6, ApplicationContext.FolderPathName, ApplicationContext.TotalEndpoint);//Text, }
// Because of AC layouts, it’s the most difficult bit of guessing. Basic track without layouts, // track with layouts, extra layout for a multi-layout track, basic track for a multi-layout track (as a layout), // extra layout for a basic track… private async Task <ContentEntryBase> CheckDirectoryNodeForTrack(DirectoryNode directory, CancellationToken cancellation) { var ui = directory.GetSubDirectory("ui"); if (ui == null) { return(null); } Logging.Write("Candidate to be a track: " + directory.Key); // First of all, let’s find out if it’s a track at all var uiTrack = ui.GetSubFile("ui_track.json"); var uiTrackSubs = ui.Directories.Select(x => x.GetSubFile("ui_track.json")).NonNull().ToList(); if (uiTrack == null && uiTrackSubs.Count == 0) { // It’s not a track Logging.Write("Not a track"); return(null); } // INI-files with modes var iniTrack = uiTrack == null ? null : directory.GetSubFile("models.ini"); var iniTrackSubs = new List <FileNode>(); for (var i = uiTrackSubs.Count - 1; i >= 0; i--) { var layoutName = uiTrackSubs[i].Parent.NameLowerCase; var models = directory.GetSubFile($"models_{layoutName}.ini"); if (models == null) { uiTrackSubs.RemoveAt(i); } else { iniTrackSubs.Add(models); } } // Let’s get missing content stuff out of the way (we’ll still keep throwing that exception // later if needed, this piece is just to ensure all required files are asked for in the first pass) var missingContent = uiTrack?.Info.IsAvailable() == false | iniTrack?.Info.IsAvailable() == false | uiTrackSubs.Aggregate(false, (v, x) => v | !x.Info.IsAvailable()) | iniTrackSubs.Aggregate(false, (v, x) => v | !x.Info.IsAvailable()); if (missingContent) { // And, if it’s just a first step, let’s ask for outlines as well foreach (var node in uiTrackSubs.Append(uiTrack).NonNull()) { node.GetSibling("outline.png")?.Info.IsAvailable(); } Logging.Write("Missing content…"); throw new MissingContentException(); } // It’s a track, let’s find out layout IDs // var layoutLowerCaseIds = uiTrackSubs.Select(x => x.Parent.NameLowerCase).ToList(); // And track ID (so far, without layouts) var trackId = directory.Name; if (trackId == null) { Logging.Write("Directory’s name is null, let’s try to guess track’s ID"); if (iniTrack != null || iniTrackSubs.Count > 0) { // Looks like KN5 are referenced via ini-files, we can’t rely on KN5 name to determine // missing track ID // UPD: Let’s try anyway, by looking for the biggest referenced KN5-file with an unusual name Logging.Debug("CAN’T FOUND PROPER TRACK ID NOWHERE! LET’S TRY TO GUESS…"); bool IsNameUnusual(string name) { var n = name.ToLowerInvariant().ApartFromLast(".kn5"); if (n.Length < 5) { // Could be some sort of shortening. return(false); } if (n.Contains(" ")) { // It might be the right name, but it’s unlikely. return(false); } if (double.TryParse(n, NumberStyles.Any, CultureInfo.InvariantCulture, out double v)) { // Numbers: 0.kn5, 10.kn5, … // Kunos name their extra files like that. return(false); } var marks = "drift|circuit|sprint|race|trackday|full|layout|start|trees|grass|normal|reverse|chicane|oval|wet|dtm|gp|pit"; if (Regex.IsMatch(n, $@"^(?:{marks})(?![a-z])|(?<![a-z])(?:{marks})$")) { // Might look like some extra layouts. return(false); } return(true); } var potentialId = (await iniTrackSubs.Prepend(iniTrack).NonNull().Select(x => x.Info.ReadAsync()).WhenAll()) .SelectMany(x => TrackContentEntry.GetLayoutModelsNames(IniFile.Parse(x.ToUtf8String())).ToList()) .Distinct().Where(IsNameUnusual).OrderByDescending(x => directory.GetSubFile(x)?.Info.Size) .FirstOrDefault()?.ToLowerInvariant().ApartFromLast(".kn5"); if (potentialId != null) { trackId = potentialId; } else { Logging.Write("Can’t determine ID because of ini-files"); return(null); } } else { trackId = directory.Files.Where(x => x.NameLowerCase.EndsWith(".kn5")).OrderByDescending(x => x.Size) .FirstOrDefault()?.NameLowerCase.ApartFromLast(".kn5"); if (trackId == null) { Logging.Write("Can’t determine ID"); return(null); } } Logging.Write("Guessed ID: " + trackId); } Logging.Write("Track ID: " + directory.Name); // Some functions async Task <Tuple <string, string, byte[]> > LoadNameVersionIcon(FileNode uiFile) { var icon = await(uiFile.GetSibling("outline.png")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); var data = await uiFile.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); cancellation.ThrowIfCancellationRequested(); return(Tuple.Create(parsed.GetStringValueOnly("name"), parsed.GetStringValueOnly("version"), icon)); } // Tuple: (models in array; required, but missing models) async Task <Tuple <List <string>, List <string> > > LoadModelsIni(FileNode node) { var data = node == null ? null : await node.Info.ReadAsync(); cancellation.ThrowIfCancellationRequested(); if (data == null) { return(null); } var names = TrackContentEntry.GetModelsNames(IniFile.Parse(data.ToUtf8String())).ToList(); var existing = names.Where(directory.HasSubFile).ToList(); return(Tuple.Create(existing, names.ApartFrom(existing).ToList())); } Task <Tuple <List <string>, List <string> > > LoadMainModelsIni() { if (iniTrack != null) { return(LoadModelsIni(iniTrack)); } var name = $@"{trackId}.kn5"; return(Task.FromResult(directory.HasSubFile(name) ? Tuple.Create(new List <string> { name }, new List <string>(0)) : Tuple.Create(new List <string>(0), new List <string> { name }))); } if (uiTrack != null && uiTrackSubs.Count == 0) { // It’s a basic track, no layouts Logging.Write("Basic type of track"); var nvi = await LoadNameVersionIcon(uiTrack); var models = await LoadMainModelsIni(); return(await TrackContentEntry.Create(directory.Key ?? "", trackId, models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } // Let’s prepare layouts if (uiTrackSubs.Count == 0) { Logging.Write("Layouts not found"); return(null); } // It’s a basic track, no layouts Logging.Write("Layouts"); var layouts = new List <TrackContentLayoutEntry>(uiTrackSubs.Count); for (var i = 0; i < uiTrackSubs.Count; i++) { var sub = uiTrackSubs[i]; var nvi = await LoadNameVersionIcon(sub); var models = await LoadModelsIni(iniTrackSubs[i]); layouts.Add(new TrackContentLayoutEntry(sub.Parent.Name ?? "-", models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } if (uiTrack != null) { var nvi = await LoadNameVersionIcon(uiTrack); var models = await LoadMainModelsIni(); layouts.Add(new TrackContentLayoutEntry("", models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } return(await TrackContentEntry.Create(directory.Key ?? "", trackId, layouts)); }
private void FileEventManager_ResourceCreated(object sender, ResourceEventArgs e) { bool alreadyAdded = this.NodeFromPath(e.Path) != null; // Don't add Resources that are already present. if (!alreadyAdded) { // Register newly detected ressource file if (File.Exists(e.Path) && Resource.IsResourceFile(e.Path)) { NodeBase newNode = this.ScanFile(e.Path); Node parentNode = this.NodeFromPath(Path.GetDirectoryName(e.Path)); if (parentNode == null) parentNode = this.folderModel.Root; this.InsertNodeSorted(newNode, parentNode); this.RegisterNodeTree(newNode); newNode.NotifyVisible(); } // Add new directory tree else if (e.IsDirectory) { // Actually, only add the directory itsself. Each file will trigger its own ResourceCreated event DirectoryNode newNode = new DirectoryNode(e.Path); //NodeBase newNode = this.ScanDirectory(e.Path); Node parentNode = this.NodeFromPath(Path.GetDirectoryName(e.Path)); if (parentNode == null) parentNode = this.folderModel.Root; this.InsertNodeSorted(newNode, parentNode); this.RegisterNodeTree(newNode); newNode.NotifyVisible(); } } // Perform previously scheduled selection this.PerformScheduleSelect(Path.GetFullPath(e.Path)); }
public override void Run() { ProjectBrowserPad.Instance.BringToFront(); DirectoryNode node = ProjectBrowserPad.Instance.ProjectBrowserControl.SelectedDirectoryNode; if (node == null) { return; } node.Expanding(); node.Expand(); using (FolderBrowserDialog dlg = new FolderBrowserDialog()) { dlg.SelectedPath = node.Directory; dlg.ShowNewFolderButton = false; if (dlg.ShowDialog(WorkbenchSingleton.MainWin32Window) == DialogResult.OK) { string folderName = dlg.SelectedPath; string copiedFolderName = Path.Combine(node.Directory, Path.GetFileName(folderName)); if (!FileUtility.IsEqualFileName(folderName, copiedFolderName)) { if (FileUtility.IsBaseDirectory(folderName, node.Directory)) { MessageService.ShowError("Cannot copy " + folderName + " to " + copiedFolderName); return; } if (Directory.Exists(copiedFolderName)) { MessageService.ShowError("Cannot copy " + folderName + " to " + copiedFolderName + ": target already exists."); return; } int res = MessageService.ShowCustomDialog( "${res:ProjectComponent.ContextMenu.ExistingFolder}", "${res:ProjectComponent.ContextMenu.ExistingFolder.CopyQuestion}", 0, 1, "${res:ProjectComponent.ContextMenu.AddExistingFiles.Copy}", "${res:Global.CancelButtonText}"); if (res != 0) { return; } if (!FileService.CopyFile(folderName, copiedFolderName, true, false)) { return; } } // ugly HACK to get IncludeDirectoryNode to work properly AbstractProjectBrowserTreeNode.ShowAll = true; try { node.RecreateSubNodes(); DirectoryNode newNode = node.AllNodes.OfType <DirectoryNode>() .FirstOrDefault(dir => FileUtility.IsEqualFileName(copiedFolderName, dir.Directory)); if (newNode != null) { newNode.Expanding(); IncludeFileInProject.IncludeDirectoryNode(newNode, true); } } finally { AbstractProjectBrowserTreeNode.ShowAll = false; } node.RecreateSubNodes(); } } }
/** * Adds a new OLE Package Shape * * @param anchor the client anchor describes how this picture is * attached to the sheet. * @param storageId the storageId returned by {@Link HSSFWorkbook.AddOlePackage} * @param pictureIndex the index of the picture (used as preview image) in the * workbook collection of pictures. * * @return newly Created shape */ public HSSFObjectData CreateObjectData(HSSFClientAnchor anchor, int storageId, int pictureIndex) { ObjRecord obj = new ObjRecord(); CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord(); ftCmo.ObjectType = (/*setter*/ CommonObjectType.Picture); // ftCmo.ObjectId=(/*setter*/oleShape.ShapeId); ... will be Set by onCreate(...) ftCmo.IsLocked = (/*setter*/ true); ftCmo.IsPrintable = (/*setter*/ true); ftCmo.IsAutoFill = (/*setter*/ true); ftCmo.IsAutoline = (/*setter*/ true); ftCmo.Reserved1 = (/*setter*/ 0); ftCmo.Reserved2 = (/*setter*/ 0); ftCmo.Reserved3 = (/*setter*/ 0); obj.AddSubRecord(ftCmo); // FtCf (pictFormat) FtCfSubRecord ftCf = new FtCfSubRecord(); HSSFPictureData pictData = Sheet.Workbook.GetAllPictures()[(pictureIndex - 1)] as HSSFPictureData; switch ((PictureType)pictData.Format) { case PictureType.WMF: case PictureType.EMF: // this needs patch #49658 to be applied to actually work ftCf.Flags = (/*setter*/ FtCfSubRecord.METAFILE_BIT); break; case PictureType.DIB: case PictureType.PNG: case PictureType.JPEG: case PictureType.PICT: ftCf.Flags = (/*setter*/ FtCfSubRecord.BITMAP_BIT); break; } obj.AddSubRecord(ftCf); // FtPioGrbit (pictFlags) FtPioGrbitSubRecord ftPioGrbit = new FtPioGrbitSubRecord(); ftPioGrbit.SetFlagByBit(FtPioGrbitSubRecord.AUTO_PICT_BIT, true); obj.AddSubRecord(ftPioGrbit); EmbeddedObjectRefSubRecord ftPictFmla = new EmbeddedObjectRefSubRecord(); ftPictFmla.SetUnknownFormulaData(new byte[] { 2, 0, 0, 0, 0 }); ftPictFmla.OLEClassName = (/*setter*/ "Paket"); ftPictFmla.SetStorageId(storageId); obj.AddSubRecord(ftPictFmla); obj.AddSubRecord(new EndSubRecord()); String entryName = "MBD" + HexDump.ToHex(storageId); DirectoryEntry oleRoot; try { DirectoryNode dn = (_sheet.Workbook as HSSFWorkbook).RootDirectory; if (dn == null) { throw new FileNotFoundException(); } oleRoot = (DirectoryEntry)dn.GetEntry(entryName); } catch (FileNotFoundException e) { throw new InvalidOperationException("trying to add ole shape without actually Adding data first - use HSSFWorkbook.AddOlePackage first", e); } // create picture shape, which need to be minimal modified for oleshapes HSSFPicture shape = new HSSFPicture(null, anchor); shape.PictureIndex = (/*setter*/ pictureIndex); EscherContainerRecord spContainer = shape.GetEscherContainer(); EscherSpRecord spRecord = spContainer.GetChildById(EscherSpRecord.RECORD_ID) as EscherSpRecord; spRecord.Flags = (/*setter*/ spRecord.Flags | EscherSpRecord.FLAG_OLESHAPE); HSSFObjectData oleShape = new HSSFObjectData(spContainer, obj, oleRoot); AddShape(oleShape); OnCreate(oleShape); return(oleShape); }
DirectoryNode GetDirectoryChildNodeAtIndex(DirectoryNode directoryNode, int index) { return(GetChildNodesOfType <DirectoryNode>(directoryNode).ElementAt(index)); }
public OldExcelExtractor(DirectoryNode directory) { Open(directory); }
protected override NodeBase GetChild(string name, DirectoryNode parent) { return(_store[parent].Children.FirstOrDefault(child => child.Name == name)); }
public void RefreshTreeAfterAdded(DirectoryNode nodeSelected) { _view.DataTree.SelectedDataItems = null; SetNodeStateAfterAdded(_view.DataTree.Nodes, nodeSelected); }
/// <summary> /// refresh the tree data /// </summary> /// <param name="nodeSelected">The node selected.</param> public void RefreshTreeData(DirectoryNode nodeSelected, bool isEdited = false) { _view.DataTree.SelectedDataItems = null; SetNodeExpandedState(_view.DataTree.Nodes, true, nodeSelected, isEdited); }
/// <summary> /// Initializes a new instance of the virtual file system. /// </summary> public static void Setup() { rootDirectory = new DirectoryNode(null); rootNode = DirectoryEntry.AllocateRoot(rootDirectory); // FIXME: Add an entry of the virtual file system to /system/filesystems }
protected DirectoryNode ScanDefaultContent() { DirectoryNode thisNode = new DirectoryNode(ContentProvider.VirtualContentPath, true); List<ContentRef<Resource>> defaultContent = ContentProvider.GetDefaultContent<Resource>(); foreach (ContentRef<Resource> resRef in defaultContent) { string[] pathSplit = resRef.Path.Split(':'); DirectoryNode curDirNode = thisNode; // Generate virtual subdirectory nodes string curDirPath = pathSplit[0]; for (int i = 1; i < pathSplit.Length - 1; i++) { curDirPath += ":" + pathSplit[i]; DirectoryNode subNode = curDirNode.Nodes.FirstOrDefault(delegate(Node n) { return n is DirectoryNode && n.Text == pathSplit[i]; }) as DirectoryNode; if (subNode == null) { subNode = new DirectoryNode(curDirPath + ":", true); this.InsertNodeSorted(subNode, curDirNode); curDirNode.Nodes.Add(subNode); } curDirNode = subNode; } // Generate virtual ressource node NodeBase res = this.ScanDefaultRessource(resRef); if (res != null) this.InsertNodeSorted(res, curDirNode); } return thisNode; }
protected IEnumerable <FileProjectItem> AddExistingItems() { DirectoryNode node = ProjectBrowserPad.Instance.ProjectBrowserControl.SelectedDirectoryNode; if (node == null) { return(null); } node.Expanding(); node.Expand(); List <FileProjectItem> addedItems = new List <FileProjectItem>(); using (OpenFileDialog fdiag = new OpenFileDialog()) { fdiag.AddExtension = true; var fileFilters = ProjectService.GetFileFilters(); fdiag.InitialDirectory = node.Directory; fdiag.FilterIndex = GetFileFilterIndex(node.Project, fileFilters); fdiag.Filter = String.Join("|", fileFilters); fdiag.Multiselect = true; fdiag.CheckFileExists = true; fdiag.Title = StringParser.Parse("${res:ProjectComponent.ContextMenu.AddExistingFiles}"); if (fdiag.ShowDialog(ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.MainWin32Window) == DialogResult.OK) { List <KeyValuePair <string, string> > fileNames = new List <KeyValuePair <string, string> >(fdiag.FileNames.Length); foreach (string fileName in fdiag.FileNames) { fileNames.Add(new KeyValuePair <string, string>(fileName, "")); } bool addedDependentFiles = false; foreach (string fileName in fdiag.FileNames) { foreach (string additionalFile in FindAdditionalFiles(fileName)) { if (!fileNames.Exists(delegate(KeyValuePair <string, string> pair) { return(FileUtility.IsEqualFileName(pair.Key, additionalFile)); })) { addedDependentFiles = true; fileNames.Add(new KeyValuePair <string, string>(additionalFile, Path.GetFileName(fileName))); } } } string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(fileNames[0].Key)); if (!FileUtility.IsEqualFileName(fileNames[0].Key, copiedFileName)) { int res = MessageService.ShowCustomDialog( fdiag.Title, "${res:ProjectComponent.ContextMenu.AddExistingFiles.Question}", 0, 2, "${res:ProjectComponent.ContextMenu.AddExistingFiles.Copy}", "${res:ProjectComponent.ContextMenu.AddExistingFiles.Link}", "${res:Global.CancelButtonText}"); if (res == 1) { // Link foreach (KeyValuePair <string, string> pair in fileNames) { string fileName = pair.Key; string relFileName = FileUtility.GetRelativePath(node.Project.Directory, fileName); FileNode fileNode = new FileNode(fileName, FileNodeStatus.InProject); FileProjectItem fileProjectItem = new FileProjectItem(node.Project, node.Project.GetDefaultItemType(fileName), relFileName); fileProjectItem.SetEvaluatedMetadata("Link", Path.Combine(node.RelativePath, Path.GetFileName(fileName))); fileProjectItem.DependentUpon = pair.Value; addedItems.Add(fileProjectItem); fileNode.ProjectItem = fileProjectItem; fileNode.InsertSorted(node); ProjectService.AddProjectItem(node.Project, fileProjectItem); } node.Project.Save(); if (addedDependentFiles) { node.RecreateSubNodes(); } return(addedItems.AsReadOnly()); } if (res == 2) { // Cancel return(addedItems.AsReadOnly()); } // only continue for res==0 (Copy) } bool replaceAll = false; foreach (KeyValuePair <string, string> pair in fileNames) { copiedFileName = Path.Combine(node.Directory, Path.GetFileName(pair.Key)); if (!replaceAll && File.Exists(copiedFileName) && !FileUtility.IsEqualFileName(pair.Key, copiedFileName)) { ReplaceExistingFile res = ShowReplaceExistingFileDialog(fdiag.Title, Path.GetFileName(pair.Key), true); if (res == ReplaceExistingFile.YesToAll) { replaceAll = true; } else if (res == ReplaceExistingFile.No) { continue; } else if (res == ReplaceExistingFile.Cancel) { break; } } FileProjectItem item = CopyFile(pair.Key, node, true); if (item != null) { addedItems.Add(item); item.DependentUpon = pair.Value; } } node.Project.Save(); if (addedDependentFiles) { node.RecreateSubNodes(); } } } return(addedItems.AsReadOnly()); }
DirectoryNode CreateNewDirectory(DirectoryNode upper, string directoryName) { upper.Expanding(); Directory.CreateDirectory(directoryName); FileService.FireFileCreated(directoryName, true); DirectoryNode directoryNode = new DirectoryNode(directoryName, FileNodeStatus.InProject); directoryNode.InsertSorted(upper); IncludeFileInProject.IncludeDirectoryNode(directoryNode, false); return directoryNode; }
protected DirectoryNode ScanDirectory(string dirPath) { if (!PathHelper.IsPathVisible(dirPath)) return null; DirectoryNode thisNode = new DirectoryNode(dirPath); string[] subDirs = Directory.GetDirectories(dirPath); foreach (string dir in subDirs) { DirectoryNode dirNode = this.ScanDirectory(dir); if (dirNode != null) this.InsertNodeSorted(dirNode, thisNode); } string[] files = Directory.GetFiles(dirPath); foreach (string file in files) { NodeBase fileNode = this.ScanFile(file); if (fileNode != null) this.InsertNodeSorted(fileNode, thisNode); } return thisNode; }
static void Main(string[] args) { string dir = string.Empty; if (args.Length == 2) { dir = args[1]; } else if (args.Length == 1) { dir = args[0] + ".ext"; } else { Console.WriteLine("Usage: wiidiscextractor /path/to/disc.iso /extract/path"); return; } Directory.CreateDirectory(dir); try { if (!Directory.Exists(args[0])) { throw new FormatException(); } DelayedStreamCache cache = new DelayedStreamCache(); DirectoryNode dirn = DirectoryNode.FromPath(args[0], cache, FileAccess.Read, FileShare.Read); DirectoryNode gen = dirn.Navigate("gen", false, true) as DirectoryNode; if (gen == null) // Just in case we're given the "wrong" directory that directly contains the ark { gen = dirn; } List <Pair <int, Stream> > arkfiles = new List <Pair <int, Stream> >(); Stream hdrfile = null; foreach (FileNode file in gen.Files) { if (file.Name.ToLower().EndsWith(".hdr")) { hdrfile = file.Data; } else if (file.Name.ToLower().EndsWith(".ark")) { Match match = Regex.Match(file.Name.ToLower(), @"_(\d+).ark"); if (match.Success) { arkfiles.Add(new Pair <int, Stream>(int.Parse(match.Groups[1].Value), file.Data)); } else { arkfiles.Add(new Pair <int, Stream>(0, file.Data)); } } } // FreQuency/Amplitude where the header is the ark if (hdrfile == null) { if (arkfiles.Count == 1) { hdrfile = arkfiles[0].Value; arkfiles.Clear(); } else { throw new FormatException(); } } Ark ark = new Ark(new EndianReader(hdrfile, Endianness.LittleEndian), arkfiles.OrderBy(f => f.Key).Select(f => f.Value).ToArray()); ark.Root.Extract(dir); cache.Dispose(); } catch (FormatException) { Stream stream = new FileStream(args[0], FileMode.Open, FileAccess.Read); try { Iso9660 iso = new Iso9660(stream); iso.Root.Extract(dir); } catch (Exception) { try { stream.Position = 0; Disc disc = new Disc(stream); File.WriteAllText(Path.Combine(dir, "title"), disc.Title); foreach (var partition in disc.Partitions) { string path = Path.Combine(dir, "partition" + disc.Partitions.IndexOf(partition).ToString()); Directory.CreateDirectory(path); partition.Root.Root.Extract(Path.Combine(path, "data")); FileStream file = new FileStream(Path.Combine(path, "partition.tik"), FileMode.Create, FileAccess.Write); partition.Ticket.Save(file); file.Close(); file = new FileStream(Path.Combine(path, "partition.tmd"), FileMode.Create, FileAccess.Write); partition.TMD.Save(file); file.Close(); file = new FileStream(Path.Combine(path, "partition.certs"), FileMode.Create, FileAccess.Write); file.Write(partition.CertificateChain); file.Close(); } } catch { try { stream.Position = 0; DlcBin bin = new DlcBin(stream); U8 u8 = new U8(bin.Data); u8.Root.Extract(dir); } catch { try { stream.Position = 0; U8 u8 = new U8(stream); u8.Root.Extract(dir); } catch { stream.Position = 0; Rarc rarc = new Rarc(stream); rarc.Root.Extract(dir); } } } } stream.Close(); } }
public static void CopyDirectory(string directoryName, DirectoryNode node, bool includeInProject) { directoryName = FileUtility.NormalizePath(directoryName); string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(directoryName)); LoggingService.Debug("Copy " + directoryName + " to " + copiedFileName); if (!FileUtility.IsEqualFileName(directoryName, copiedFileName)) { if (includeInProject && ProjectService.OpenSolution != null) { // get ProjectItems in source directory foreach (IProject project in ProjectService.OpenSolution.Projects) { if (!FileUtility.IsBaseDirectory(project.Directory, directoryName)) { continue; } LoggingService.Debug("Searching for child items in " + project.Name); foreach (ProjectItem item in project.Items) { FileProjectItem fileItem = item as FileProjectItem; if (fileItem == null) { continue; } string virtualFullName = Path.Combine(project.Directory, fileItem.VirtualName); if (FileUtility.IsBaseDirectory(directoryName, virtualFullName)) { if (item.ItemType == ItemType.Folder && FileUtility.IsEqualFileName(directoryName, virtualFullName)) { continue; } LoggingService.Debug("Found file " + virtualFullName); FileProjectItem newItem = new FileProjectItem(node.Project, fileItem.ItemType); if (FileUtility.IsBaseDirectory(directoryName, fileItem.FileName)) { newItem.FileName = FileUtility.RenameBaseDirectory(fileItem.FileName, directoryName, copiedFileName); } else { newItem.FileName = fileItem.FileName; } fileItem.CopyMetadataTo(newItem); if (fileItem.IsLink) { string newVirtualFullName = FileUtility.RenameBaseDirectory(virtualFullName, directoryName, copiedFileName); fileItem.SetEvaluatedMetadata("Link", FileUtility.GetRelativePath(node.Project.Directory, newVirtualFullName)); } ProjectService.AddProjectItem(node.Project, newItem); } } } } FileService.CopyFile(directoryName, copiedFileName, true, false); DirectoryNode newNode = new DirectoryNode(copiedFileName); newNode.InsertSorted(node); if (includeInProject) { IncludeFileInProject.IncludeDirectoryNode(newNode, false); } newNode.Expanding(); } else if (includeInProject) { foreach (TreeNode childNode in node.Nodes) { if (childNode is DirectoryNode) { DirectoryNode directoryNode = (DirectoryNode)childNode; if (FileUtility.IsEqualFileName(directoryNode.Directory, copiedFileName)) { IncludeFileInProject.IncludeDirectoryNode(directoryNode, true); } } } } }
public async Task <Scanned> GetEntriesAsync([NotNull] List <IFileInfo> list, string baseId, string baseName, [CanBeNull] IProgress <AsyncProgressEntry> progress, CancellationToken cancellation) { progress?.Report(AsyncProgressEntry.FromStringIndetermitate("Scanning…")); var result = new List <ContentEntryBase>(); var missingContent = false; Exception readException = null; var s = Stopwatch.StartNew(); var root = new DirectoryNode(_installationParams.FallbackId ?? baseId, null); root.ForceName(baseName); foreach (var info in list) { root.Add(info); } Logging.Debug($"Building tree: {s.Elapsed.TotalMilliseconds:F1} ms"); s.Restart(); var queue = new Queue <DirectoryNode>(); queue.Enqueue(root); while (queue.Count > 0) { var directory = queue.Dequeue(); ContentEntryBase found; try { found = await CheckDirectoryNode(directory, cancellation).ConfigureAwait(false); // WHY IT DOES NOT WORK? if (cancellation.IsCancellationRequested) { break; } } catch (Exception e) when(e.IsCancelled()) { break; } catch (MissingContentException) { missingContent = true; continue; } catch (Exception e) { Logging.Warning(e); readException = e; continue; } if (found != null) { result.Add(found); } else { foreach (var value in directory.Directories) { queue.Enqueue(value); } foreach (var value in directory.Files) { try { found = await CheckFileNode(value, cancellation).ConfigureAwait(false); if (cancellation.IsCancellationRequested) { break; } } catch (Exception e) when(e.IsCancelled()) { break; } catch (MissingContentException) { missingContent = true; continue; } catch (Exception e) { Logging.Warning(e); readException = e; continue; } if (found != null) { result.Add(found); } } } } Logging.Debug($"Scanning directories: {s.Elapsed.TotalMilliseconds:F1} ms"); return(new Scanned(result, missingContent, readException)); }
protected override void CreateEncryptionInfoEntry(DirectoryNode dir, FileInfo tmpFile) { ((AgileEncryptor)encryptor).CreateEncryptionInfoEntry(dir, tmpFile); }
/// <summary> /// Returns the next Event or {@code null} if there are no more events or /// the walker is closed. /// </summary> internal virtual Event Next() { DirectoryNode top = Stack.Peek(); if (top == null) { return(null); // stack is empty, we are done } // continue iteration of the directory at the top of the stack Event ev; do { Path entry = null; IOException ioe = null; // get next entry in the directory if (!top.Skipped()) { IEnumerator <Path> iterator = top.Iterator(); try { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: if (iterator.hasNext()) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: entry = iterator.next(); } } catch (DirectoryIteratorException x) { ioe = x.InnerException; } } // no next entry so close and pop directory, creating corresponding event if (entry == null) { try { top.Stream().Close(); } catch (IOException e) { if (ioe != null) { ioe = e; } else { ioe.AddSuppressed(e); } } Stack.Pop(); return(new Event(EventType.END_DIRECTORY, top.Directory(), ioe)); } // visit the entry ev = Visit(entry, true, true); // canUseCached - ignoreSecurityException } while (ev == null); return(ev); }
public FileNode(IFileInfo info, DirectoryNode parent) : base(info.Key, parent) { Info = info; Size = info.Size; }
public POIDocument(DirectoryNode dir, POIFSFileSystem fs) { this.directory = dir; //POILogFactory.GetLogger(this.GetType()); }
private FileSystemNode GetOrCreateInternal(List <VolumeNode> volumes, string path, bool shouldCreate, bool isContextOfFile) { if (_directorySeparatorChar == '\\') { if (!isContextOfFile) { path = path.TrimPath() + _directorySeparatorChar; } path = Path.GetFullPath(path); } if (!isContextOfFile) { path = path.TrimPath(); } string[] pathNodes = FileSystemUtility.ParsePath(path, _directorySeparatorChar); VolumeNode volume = GetOrCreateVolume(volumes, pathNodes[0], shouldCreate); if (volume == null) { return(null); } StringComparer stringComparer = volume.StringComparer; ContainerNode current = volume; if (pathNodes.Length <= 1) { return(current); } int i; for (i = 1; i < pathNodes.Length - 1; i++) { bool found = false; var child = current.Directories[pathNodes[i]]; if (child != null) { found = true; current = child; } if (!found) { if (!shouldCreate) { return(null); } break; } } if (i >= pathNodes.Length && Debugger.IsAttached) { Debugger.Break(); } var pathNode = pathNodes[i]; var directory = current.Directories[pathNode]; if (directory != null) { return(directory); } var file = current.Files[pathNode]; if (file != null) { return(file); } if (!shouldCreate) { return(null); } for (int j = i; j < pathNodes.Length - 1; j++, i = j) { var directoryName = pathNodes[j]; DirectoryNode existingDirectory = current.Directories[directoryName]; if (existingDirectory == null) { DirectoryNode newDirectory = new DirectoryNode(this, directoryName, stringComparer) { LastWriteTime = DateTime.Now, }; current.Directories.Add(newDirectory); current = newDirectory; } else { current = existingDirectory; } } if (!isContextOfFile) { var directoryName = pathNodes[i]; lock (current.Directories.SyncLock) { DirectoryNode existingDirectory = current.Directories[directoryName]; if (existingDirectory == null) { DirectoryNode newDirectory = new DirectoryNode(this, directoryName, stringComparer) { LastWriteTime = DateTime.Now, }; current.Directories.Add(newDirectory); return(newDirectory); } return(existingDirectory); } } var fileName = pathNodes[i]; lock (current.Files.SyncLock) { FileNode existingFile = current.Files[fileName]; if (existingFile == null) { FileNode fileNode = new FileNode(this) { Name = fileName, LastWriteTime = DateTime.Now, }; current.Files.Add(fileNode); return(fileNode); } return(existingFile); } }
/// <summary> /// Create a DocumentNode. ThIs method Is not public by design; it /// Is intended strictly for the internal use of extending classes /// </summary> /// <param name="property">the Property for this Entry</param> /// <param name="parent">the parent of this entry</param> protected EntryNode(Property property, DirectoryNode parent) { _property = property; _parent = parent; }
bool IsImmediateParentForNewFile(DirectoryNode directoryNode) { return(FileUtility.IsBaseDirectory(DirectoryForNewFileAddedToProject, directoryNode.Directory)); }
/// <summary> /// given a POI POIFSFileSystem object, and a specific directory /// within it, Read in its Workbook and populate the high and /// low level models. If you're Reading in a workbook...start here. /// </summary> /// <param name="directory">the POI filesystem directory to Process from</param> /// <param name="fs">the POI filesystem that Contains the Workbook stream.</param> /// <param name="preserveNodes">whether to preseve other nodes, such as /// macros. This takes more memory, so only say yes if you /// need to. If Set, will store all of the POIFSFileSystem /// in memory</param> public HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, bool preserveNodes) : this(directory, preserveNodes) { }
void AddChildDirectoryNodeForNewFileTo(DirectoryNode parentNode) { string childDirectory = GetMissingChildDirectory(parentNode.Directory); AddDirectoryNodeTo(parentNode, childDirectory); }
public AbstractBrowserNode GetPath(string filename, AbstractBrowserNode root, bool create) { string directory = Path.GetDirectoryName(filename); string[] treepath = directory.Split(new char[] { Path.DirectorySeparatorChar }); AbstractBrowserNode curpathnode = root; foreach (string path in treepath) { if (path.Length == 0 || path[0] == '.') { continue; } AbstractBrowserNode node = null; //AbstractBrowserNode node = GetNodeFromCollection(curpathnode.Nodes, path); if (node == null) { if (create) { DirectoryNode newFolderNode = new DirectoryNode(fileUtilityService.GetDirectoryNameWithSeparator(ConstructFolderName(curpathnode)) + path); curpathnode.Nodes.Add(newFolderNode); curpathnode = newFolderNode; continue; } else { return null; } } curpathnode = node; } return curpathnode; }
void AddDirectoryNodeTo(TreeNode parentNode, string directory) { var directoryNode = new DirectoryNode(directory, FileNodeStatus.InProject); directoryNode.InsertSorted(parentNode); }
public override Stream GetDataStream(DirectoryNode dir) { DocumentInputStream dr = dir.CreateDocumentInputStream("EncryptedPackage"); long size = dr.ReadLong(); return new ChunkedCipherInputStream(dr, size, this); }
bool IsChildFileNodeAlreadyAddedForNewFile(DirectoryNode parentDirectoryNode) { return(GetChildFileNodes(parentDirectoryNode) .Any(childFileNode => FileNodeMatchesNewFileAdded(childFileNode))); }
public override Stream GetDataStream(DirectoryNode dir) { DocumentInputStream dr = dir.CreateDocumentInputStream("EncryptedPackage"); long size = dr.ReadLong(); SymmetricAlgorithm cipher=GetCipher(); return new CryptoStream(dr, cipher.CreateDecryptor(cipher.Key, cipher.IV), CryptoStreamMode.Read); }
bool IsChildDirectoryNodeMissingForNewFile(DirectoryNode parentDirectoryNode) { return(!IsChildDirectoryNodeAlreadyAddedForNewFile(parentDirectoryNode)); }
protected POIDocument(DirectoryNode dir) { this.directory = dir; }
static void ExcludeDirectoryNode(DirectoryNode directoryNode) { if (directoryNode.ProjectItem != null) { ProjectService.RemoveProjectItem(directoryNode.Project, directoryNode.ProjectItem); directoryNode.ProjectItem = null; } directoryNode.FileNodeStatus = FileNodeStatus.None; if (directoryNode.Parent is ExtTreeNode) { ((ExtTreeNode)directoryNode.Parent).UpdateVisibility(); } }
protected DirectoryNode ScanDirectory(string dirPath) { if (!PathHelper.IsPathVisible(dirPath)) return null; DirectoryNode thisNode = new DirectoryNode(dirPath); foreach (string dir in Directory.EnumerateDirectories(dirPath)) { DirectoryNode dirNode = this.ScanDirectory(dir); if (dirNode != null) this.InsertNodeSorted(dirNode, thisNode); } foreach (string file in Directory.EnumerateFiles(dirPath)) { NodeBase fileNode = this.ScanFile(file); if (fileNode != null) this.InsertNodeSorted(fileNode, thisNode); } return thisNode; }
bool ShouldVisitDirectoryNode(DirectoryNode directoryNode) { return(directoryNode.IsInitialized && IsNewFileInsideDirectory(directoryNode)); }
public static FileProjectItem CopyFile(string fileName, DirectoryNode node, bool includeInProject) { string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(fileName)); if (!FileUtility.IsEqualFileName(fileName, copiedFileName)) { FileService.CopyFile(fileName, copiedFileName, false, true); } if (includeInProject) { FileNode fileNode; foreach (TreeNode childNode in node.AllNodes) { if (childNode is FileNode) { fileNode = (FileNode)childNode; if (FileUtility.IsEqualFileName(fileNode.FileName, copiedFileName)) { if (fileNode.FileNodeStatus == FileNodeStatus.Missing) { fileNode.FileNodeStatus = FileNodeStatus.InProject; } else if (fileNode.FileNodeStatus == FileNodeStatus.None) { return IncludeFileInProject.IncludeFileNode(fileNode); } return fileNode.ProjectItem as FileProjectItem; } } } fileNode = new FileNode(copiedFileName); fileNode.InsertSorted(node); return IncludeFileInProject.IncludeFileNode(fileNode); } return null; }
bool IsNewFileInsideDirectory(DirectoryNode directoryNode) { return(FileUtility.IsBaseDirectory(directoryNode.Directory, DirectoryForNewFileAddedToProject)); }
bool IsChildDirectoryNodeAlreadyAddedForNewFile(DirectoryNode parentDirectoryNode) { return(GetChildDirectoryNodes(parentDirectoryNode) .Any(childDirectoryNode => DirectoryOfNewFileStartsWith(childDirectoryNode))); }
public DirectoryNode(string key, DirectoryNode parent) : base(key, parent) { }
public static void IncludeDirectoryNode(DirectoryNode directoryNode, bool includeSubNodes) { if (directoryNode.Parent is DirectoryNode && !(directoryNode.Parent is ProjectNode)) { if (((DirectoryNode)directoryNode.Parent).FileNodeStatus != FileNodeStatus.InProject) { IncludeDirectoryNode((DirectoryNode)directoryNode.Parent, false); } } FileProjectItem newItem = new FileProjectItem( directoryNode.Project, ItemType.Folder, FileUtility.GetRelativePath(directoryNode.Project.Directory, directoryNode.Directory) ); ProjectService.AddProjectItem(directoryNode.Project, newItem); directoryNode.ProjectItem = newItem; directoryNode.FileNodeStatus = FileNodeStatus.InProject; if (includeSubNodes) { foreach (TreeNode childNode in directoryNode.Nodes) { if (childNode is ExtTreeNode) { ((ExtTreeNode)childNode).Expanding(); } if (childNode is FileNode) { IncludeFileNode((FileNode)childNode); } else if (childNode is DirectoryNode) { IncludeDirectoryNode((DirectoryNode)childNode, includeSubNodes); } } } directoryNode.Project.Save(); }
bool DirectoryOfNewFileStartsWith(DirectoryNode directoryNode) { return(FileUtility.IsBaseDirectory(directoryNode.Directory, DirectoryForNewFileAddedToProject)); }