private void RunTest(IFileFormat<List<FeatureItemGroup>> format)
 {
   var inputFile = @"../../../data/CMS-001.count.mapped.xml";
   var features = format.ReadFromFile(inputFile);
   var tempFile = inputFile + ".tmp";
   format.WriteToFile(tempFile, features);
   FileAssert.AreEqual(inputFile, tempFile);
   File.Delete(tempFile);
 }
예제 #2
0
		public void UnregisterFileFormat (IFileFormat format)
		{
			foreach (FileFormat f in fileFormats) {
				if (f.Format == format) {
					fileFormats.Remove (f);
					return;
				}
			}
		}
예제 #3
0
        /// <summary>
        /// Determines whether [is format valid for path] [the specified file format].
        /// </summary>
        /// <param name="fileFormat">The file format.</param>
        /// <param name="path">The path.</param>
        /// <returns>
        ///   <c>true</c> if [is format valid for path] [the specified file format]; otherwise, <c>false</c>.
        /// </returns>
        public virtual bool IsFormatValidForPath(IFileFormat fileFormat, string path)
        {
            //  Get the extension.
            string extension = Path.GetExtension(path).Substring(1);

            //  Go through each file type and see if we
            //  match it.
            foreach (var fileType in fileFormat.FileTypes)
                if (String.Compare(extension, fileType, true) == 0)
                    return true;

            return false;
        }
예제 #4
0
		public void RegisterFileFormat (IFileFormat format, string id, string name, bool canDefault)
		{
			FileFormat f = new FileFormat (format, id, name, canDefault);
			fileFormats.Add (f);
		}
예제 #5
0
        private void SaveNodeFormats(ObjectEditor editor, bool UseSaveDialog, bool UseCompressDialog)
        {
            foreach (var node in editor.GetNodes())
            {
                IFileFormat format = null;
                if (node is ArchiveBase)
                {
                    format = (IFileFormat)((ArchiveBase)node).ArchiveFile;

                    if (node is ArchiveRootNodeWrapper)
                    {
                        ((ArchiveRootNodeWrapper)node).UpdateFileNames();
                    }
                }
                else if (node is IFileFormat)
                {
                    format = ((IFileFormat)node);
                }
                if (format != null)
                {
                    if (!format.CanSave)
                    {
                        return;
                    }

                    string FileName = format.FilePath;
                    if (!File.Exists(FileName))
                    {
                        UseSaveDialog = true;
                    }

                    if (UseSaveDialog)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter   = Utils.GetAllFilters(format);
                        sfd.FileName = format.FileName;

                        if (sfd.ShowDialog() != DialogResult.OK)
                        {
                            return;
                        }

                        FileName = sfd.FileName;
                    }
                    Cursor.Current = Cursors.WaitCursor;

                    //Use the export method for particular formats like bfres for special save operations
                    if (format is STGenericWrapper && !(format is STGenericTexture))
                    {
                        ((STGenericWrapper)format).Export(FileName);
                        return;
                    }

                    if (node is ArchiveBase)
                    {
                        STFileSaver.SaveFileFormat(((IFileFormat)((ArchiveBase)node).ArchiveFile), FileName, UseCompressDialog);
                    }
                    else
                    {
                        STFileSaver.SaveFileFormat(((IFileFormat)node), FileName, UseCompressDialog);
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
예제 #6
0
 public static IImageCodec FromFileFormat(IFileFormat imageFormat)
 {
     return(GetImageCodecs(imageFormat).FirstOrDefault(codec => codec.IsSupportedFileFormat(imageFormat)));
 }
        protected async override Task <SendResult> Send(IWin32Window Owner, Output Output, ImageData ImageData)
        {
            try
            {
                string applicationPath = string.Empty;

                using (RegistryKey localMachineKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                {
                    using (RegistryKey classKey = localMachineKey.OpenSubKey("Software\\Classes\\.xcf", false))
                    {
                        if (classKey != null)
                        {
                            string classValue = Convert.ToString(classKey.GetValue(string.Empty, string.Empty));

                            using (RegistryKey commandKey = localMachineKey.OpenSubKey("Software\\Classes\\" + classValue + "\\shell\\open\\command", false))
                            {
                                if (commandKey != null)
                                {
                                    string openCommand = Convert.ToString(commandKey.GetValue(string.Empty, string.Empty));

                                    applicationPath = openCommand.Split(new char[] { Convert.ToChar("\"") }, StringSplitOptions.RemoveEmptyEntries)[0];
                                }
                            }
                        }
                    }
                }

                if (!File.Exists(applicationPath))
                {
                    return(new SendResult(Result.Failed, "Gimp is not installed."));
                }


                string fileName = AttributeHelper.ReplaceAttributes(Output.FileName, ImageData);

                if (Output.EditFileName)
                {
                    Send send = new Send(fileName);

                    var ownerHelper = new System.Windows.Interop.WindowInteropHelper(send);
                    ownerHelper.Owner = Owner.Handle;

                    if (send.ShowDialog() != true)
                    {
                        return(new SendResult(Result.Canceled));
                    }

                    fileName = send.FileName;
                }

                IFileFormat fileFormat = FileHelper.GetFileFormat(Output.FileFormatID);

                string filePath = Path.Combine(Path.GetTempPath(), fileName + "." + fileFormat.FileExtension);

                Byte[] fileBytes = FileHelper.GetFileBytes(Output.FileFormatID, ImageData);

                using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    file.Write(fileBytes, 0, fileBytes.Length);
                    file.Close();
                }

                Process.Start(applicationPath, "\"" + filePath + "\"");

                return(new SendResult(Result.Success));
            }
            catch (Exception ex)
            {
                return(new SendResult(Result.Failed, ex.Message));
            }
        }
        /// <summary>
        ///  Action for the File->Save command.
        /// </summary>
        /// 
        public void Save_Execute(object parameter)
        {
            string option = (parameter as string);

            if (!String.IsNullOrEmpty(lastSavePath) && option != "SaveAs")
            {
                save();
                return;
            }

            var dlg = new SaveFileDialog()
            {
                FileName = "Sample",
                DefaultExt = ".csv",
                Filter = saveFormats.GetFilterString(false),
                InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\Samples\\")
            };

            if (!String.IsNullOrEmpty(lastSavePath))
                dlg.InitialDirectory = lastSavePath;

            // Show save file dialog box
            var result = dlg.ShowDialog();

            if (result == true)
            {
                // Get the chosen format
                lastSaveFormat = saveFormats[dlg.FilterIndex - 1];
                lastSavePath = dlg.FileName;

                save();
            }
        }
예제 #9
0
		internal FileFormat GetFileFormat (IFileFormat format)
		{
			foreach (FileFormat f in fileFormats)
				if (f.Format == format)
					return f;
			return null;
		}
예제 #10
0
 public void ReloadArchiveFile(IFileFormat fileFormat)
 {
     this.treeViewCustom1.Nodes.Clear();
     AddIArchiveFile(fileFormat);
 }
예제 #11
0
        private object ReadFile(IProgressMonitor monitor, string file, Type expectedType, out IFileFormat format)
        {
            List <FileFormat> fileFormats = this.FormatManager.GetFileFormats(file, expectedType);

            if (fileFormats.Count == 0)
            {
                throw new InvalidOperationException("Unknown file format: " + file);
            }
            format = fileFormats[0];
            return(this.ReadFile(monitor, file, expectedType, format));
        }
예제 #12
0
        protected override async Task <SendResult> Send(IWin32Window Owner, Output Output, ImageData ImageData)
        {
            try
            {
                string userName            = Output.UserName;
                string password            = Output.Password;
                bool   showLogin           = string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password);
                bool   rememberCredentials = false;

                string fileName = AttributeHelper.ReplaceAttributes(Output.FileName, ImageData);

                while (true)
                {
                    if (showLogin)
                    {
                        // Show credentials window
                        Credentials credentials = new Credentials(Output.Url, userName, password, rememberCredentials);

                        var ownerHelper = new System.Windows.Interop.WindowInteropHelper(credentials);
                        ownerHelper.Owner = Owner.Handle;

                        if (credentials.ShowDialog() != true)
                        {
                            return(new SendResult(Result.Canceled));
                        }

                        userName            = credentials.UserName;
                        password            = credentials.Password;
                        rememberCredentials = credentials.Remember;
                    }

                    try
                    {
                        GetProjectsResult projectsResult = await UnfuddleStackProxy.GetProjects(Output.Url, userName, password);

                        switch (projectsResult.Status)
                        {
                        case ResultStatus.Success:
                            break;

                        case ResultStatus.LoginFailed:
                            showLogin = true;
                            continue;

                        case ResultStatus.Failed:
                            return(new SendResult(Result.Failed, projectsResult.FailedMessage));
                        }

                        // Show send window
                        Send send = new Send(Output.Url, Output.LastProjectID, Output.LastMessageID, Output.LastTicketNumber, projectsResult.Projects, fileName);

                        var ownerHelper = new System.Windows.Interop.WindowInteropHelper(send);
                        ownerHelper.Owner = Owner.Handle;

                        if (!send.ShowDialog() == true)
                        {
                            return(new SendResult(Result.Canceled));
                        }


                        int messageID    = Output.LastMessageID;;
                        int ticketNumber = Output.LastTicketNumber;

                        switch (send.ItemType)
                        {
                        case SendItemType.NewMessage:

                            CreateMessageResult createMessageResult = await UnfuddleStackProxy.CreateMessage(Output.Url, userName, password, send.ProjectID, send.MessageTitle, send.Message);

                            switch (createMessageResult.Status)
                            {
                            case ResultStatus.Success:
                                messageID = createMessageResult.MessageID;
                                break;

                            case ResultStatus.LoginFailed:
                                showLogin = true;
                                continue;

                            case ResultStatus.Failed:
                                return(new SendResult(Result.Failed, createMessageResult.FailedMessage));
                            }

                            break;

                        case SendItemType.AttachToMessage:
                            messageID = send.MessageID;
                            break;

                        case SendItemType.NewTicket:

                            CreateTicketResult createTicketResult = await UnfuddleStackProxy.CreateTicket(Output.Url, userName, password, send.ProjectID, send.TicketSummary, send.TicketDescription);

                            switch (createTicketResult.Status)
                            {
                            case ResultStatus.Success:
                                ticketNumber = createTicketResult.TicketNumber;
                                break;

                            case ResultStatus.LoginFailed:
                                showLogin = true;
                                continue;

                            case ResultStatus.Failed:
                                return(new SendResult(Result.Failed, createTicketResult.FailedMessage));
                            }

                            break;

                        case SendItemType.AttachToTicket:
                            ticketNumber = send.TicketNumber;
                            break;
                        }

                        IFileFormat fileFormat = FileHelper.GetFileFormat(Output.FileFormatID);

                        string fullFileName = String.Format("{0}.{1}", send.FileName, fileFormat.FileExtension);

                        byte[] fileBytes = FileHelper.GetFileBytes(Output.FileFormatID, ImageData);
                        string itemUrl   = string.Empty;

                        switch (send.ItemType)
                        {
                        case SendItemType.NewMessage:
                        case SendItemType.AttachToMessage:

                            AttachmentResult addAttachmentToMessage = await UnfuddleStackProxy.AddAttachmentToMessage(Output.Url, userName, password, send.ProjectID, messageID, fullFileName, fileBytes, fileFormat.MimeType);

                            switch (addAttachmentToMessage.Status)
                            {
                            case ResultStatus.Success:
                                itemUrl = String.Format("{0}/projects/{1}/messages/{2}", Output.Url, send.ProjectID, messageID);
                                break;

                            case ResultStatus.LoginFailed:
                                showLogin = true;
                                continue;

                            case ResultStatus.Failed:
                                return(new SendResult(Result.Failed, addAttachmentToMessage.FailedMessage));
                            }

                            break;

                        case SendItemType.NewTicket:
                        case SendItemType.AttachToTicket:

                            AttachmentResult addAttachmentToTicket = await UnfuddleStackProxy.AddAttachmentToTicket(Output.Url, userName, password, send.ProjectID, ticketNumber, fullFileName, fileBytes, fileFormat.MimeType);

                            switch (addAttachmentToTicket.Status)
                            {
                            case ResultStatus.Success:
                                itemUrl = String.Format("{0}/projects/{1}/tickets/by_number/{2}", Output.Url, send.ProjectID, ticketNumber);
                                break;

                            case ResultStatus.LoginFailed:
                                showLogin = true;
                                continue;

                            case ResultStatus.Failed:
                                return(new SendResult(Result.Failed, addAttachmentToTicket.FailedMessage));
                            }

                            break;
                        }


                        // Open issue in browser
                        if (Output.OpenItemInBrowser)
                        {
                            WebHelper.OpenUrl(itemUrl);
                        }


                        return(new SendResult(Result.Success,
                                              new Output(Output.Name,
                                                         Output.Url,
                                                         (rememberCredentials) ? userName : Output.UserName,
                                                         (rememberCredentials) ? password : Output.Password,
                                                         Output.FileName,
                                                         Output.FileFormatID,
                                                         Output.OpenItemInBrowser,
                                                         send.ProjectID,
                                                         messageID,
                                                         ticketNumber)));
                    }
                    catch (FaultException ex) when(ex.Reason.ToString() == "Access denied")
                    {
                        // Login failed
                        showLogin = true;
                    }
                }
            }
            catch (Exception ex)
            {
                return(new SendResult(Result.Failed, ex.Message));
            }
        }
예제 #13
0
 public static bool IsSupportedFileFormat(this IHasSupportedFileFormats obj, IFileFormat fileFormat)
 {
     return(obj.GetSupportedFileFormats().Any(supportedFileFormat => supportedFileFormat.Equals(fileFormat)));
 }
예제 #14
0
        private object ReadFile(IProgressMonitor monitor, string file, Type expectedType, IFileFormat format)
        {
            object obj = format.ReadFile(file, expectedType, monitor);

            if (obj == null)
            {
                throw new InvalidOperationException("Invalid file format: " + file);
            }
            return(obj);
        }
 public void RegisterFileFormat(IFileFormat format)
 {
     fileFormats.Add (format);
 }
예제 #16
0
        public static IArchive Open(this IArchiveFactory archiveFactory, string filePath, IFileFormat archiveFormat, IArchiveOptions archiveOptions)
        {
            if (archiveFormat is null)
            {
                archiveFormat = FileFormatFactory.Default.FromFileExtension(filePath);
            }

            FileAccess fileAccess = archiveOptions?.FileAccess ?? FileAccess.ReadWrite;
            FileMode   fileMode   = fileAccess == FileAccess.Read ? FileMode.Open : FileMode.OpenOrCreate;
            FileStream fileStream = new FileStream(filePath, fileMode, fileAccess);

            try {
                return(archiveFactory.Open(fileStream, archiveFormat, archiveOptions));
            }
            catch {
                fileStream.Dispose();

                throw;
            }
        }
예제 #17
0
        public static IArchive Open(this IArchiveFactory archiveFactory, Stream stream, IFileFormat archiveFormat)
        {
            if (archiveFormat is null)
            {
                stream = FileFormatFactory.Default.FromStream(stream, out archiveFormat);
            }

            return(archiveFactory.Open(stream, archiveFormat, ArchiveOptions.Default));
        }
예제 #18
0
 public SceneFileImporter(IImporter parent, string name, IFileFormat fileFormat) : base(parent, name)
 {
     _fileFormat = fileFormat;
 }
예제 #19
0
 public static IArchiveDecoder FromFileFormat(IFileFormat fileFormat)
 {
     return(CompressionPluginLoader.GetArchiveDecoders().FirstOrDefault(decoder => decoder.IsSupportedFileFormat(fileFormat)));
 }
예제 #20
0
		public void RegisterFileFormat (IFileFormat format, string id, string name)
		{
			FileFormat f = new FileFormat (format, id, name);
			fileFormats.Add (f);
		}
예제 #21
0
        public ResourceFile(IFileFormat handler)
        {
            ImageKey         = "bfres";
            SelectedImageKey = "bfres";
            FileHandler      = handler;

            ContextMenu = new ContextMenu();
            MenuItem save = new MenuItem("Save");

            ContextMenu.MenuItems.Add(save);
            save.Click += Save;

            MenuItem newMenu = new MenuItem("New");
            MenuItem import  = new MenuItem("Import");
            //       ContextMenu.MenuItems.Add(newMenu);
            //       ContextMenu.MenuItems.Add(import);

            MenuItem rename = new MenuItem("Rename");

            ContextMenu.MenuItems.Add(rename);
            rename.Click += Rename;
            MenuItem remove = new MenuItem("Remove");

            ContextMenu.MenuItems.Add(remove);
            remove.Click += Remove;

            if (Parent == null)
            {
                remove.Enabled = false;
            }

            if (BFRES.IsWiiU)
            {
            }
            else
            {
                MenuItem model    = new MenuItem("Model");
                MenuItem fska     = new MenuItem("Skeletal Animation");
                MenuItem fmaa     = new MenuItem("Material Animation");
                MenuItem bonevis  = new MenuItem("Bone Visual Animation");
                MenuItem shape    = new MenuItem("Shape Animation");
                MenuItem scene    = new MenuItem("Scene Animation");
                MenuItem embedded = new MenuItem("Embedded File");
                MenuItem texture  = new MenuItem("Texture File");
                texture.Click += NewTextureFile;
                newMenu.MenuItems.Add(model);
                newMenu.MenuItems.Add(fska);
                newMenu.MenuItems.Add(fmaa);
                newMenu.MenuItems.Add(bonevis);
                newMenu.MenuItems.Add(shape);
                newMenu.MenuItems.Add(scene);
                newMenu.MenuItems.Add(embedded);
                newMenu.MenuItems.Add(texture);

                MenuItem importmodel    = new MenuItem("Model");
                MenuItem importfska     = new MenuItem("Skeletal Animation");
                MenuItem importfmaa     = new MenuItem("Material Animation");
                MenuItem importbonevis  = new MenuItem("Bone Visual Animation");
                MenuItem importshape    = new MenuItem("Shape Animation");
                MenuItem importscene    = new MenuItem("Scene Animation");
                MenuItem importembedded = new MenuItem("Embedded File");
                MenuItem importtexture  = new MenuItem("Texture File");
                import.MenuItems.Add(importmodel);
                import.MenuItems.Add(importfska);
                import.MenuItems.Add(importfmaa);
                import.MenuItems.Add(importbonevis);
                import.MenuItems.Add(importshape);
                import.MenuItems.Add(importscene);
                import.MenuItems.Add(importembedded);
                import.MenuItems.Add(importtexture);
            }
        }
예제 #22
0
		internal FileFormat (IFileFormat format, string id, string name, bool canDefault)
		{
			this.id = id;
			this.name = name ?? id;
			this.format = format;
			this.CanDefault = canDefault;
		}
예제 #23
0
 public static bool IsSupportedFileFormat(IFileFormat fileFormat)
 {
     return(new GdiImageCodec().IsSupportedFileFormat(fileFormat));
 }
예제 #24
0
        public void AddIArchiveFile(IFileFormat FileFormat)
        {
            var FileRoot = new ArchiveRootNodeWrapper(FileFormat.FileName, (IArchiveFile)FileFormat);

            FileRoot.FillTreeNodes();
            AddNode(FileRoot);

            if (FileFormat is TreeNode) //It can still be both, so add all it's nodes
            {
                foreach (TreeNode n in ((TreeNode)FileFormat).Nodes)
                {
                    FileRoot.Nodes.Add(n);
                }
            }

            if (FileFormat is IArchiveQuickAccess)
            {
                var lookup = ((IArchiveQuickAccess)FileFormat).CategoryLookup;

                TreeNode quickAcessNode = new TreeNode("Quick access");
                AddNode(quickAcessNode);

                Dictionary <string, TreeNode> folders = new Dictionary <string, TreeNode>();
                for (int i = 0; i < FileRoot.FileNodes.Count; i++)
                {
                    string fileName = FileRoot.FileNodes[i].Item1.FileName;
                    string name     = System.IO.Path.GetFileName(fileName);
                    string ext      = Utils.GetExtension(fileName);

                    var fileNode = FileRoot.FileNodes[i].Item2;

                    string folder = "Other";
                    if (lookup.ContainsKey(ext))
                    {
                        folder = lookup[ext];
                    }

                    if (!folders.ContainsKey(folder))
                    {
                        var dirNode = new TreeNode(folder);
                        folders.Add(folder, dirNode);
                        quickAcessNode.Nodes.Add(dirNode);
                    }

                    folders[folder].Nodes.Add(new TreeNode()
                    {
                        Tag              = fileNode,
                        Text             = name,
                        ImageKey         = fileNode.ImageKey,
                        SelectedImageKey = fileNode.SelectedImageKey,
                    });
                    // dirNode.Nodes.Add(FileRoot.FileNodes[i].Item2);
                }
            }

            SelectNode(FileRoot);

            for (int i = 0; i < FileRoot.FileNodes.Count; i++)
            {
                if (FileRoot.FileNodes[i].Item1.OpenFileFormatOnLoad)
                {
                    if (FileRoot.FileNodes[i].Item2 is ArchiveFileWrapper)
                    {
                        try {
                            ((ArchiveFileWrapper)FileRoot.FileNodes[i].Item2).OpenFileFormat(treeViewCustom1);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
예제 #25
0
        public static string GetAllFilters(IEnumerable <IFileFormat> format, IFileFormat targetFormat = null)
        {
            var alltypes = format;

            string        Filter     = "All Supported Files|";
            List <string> FilterEach = new List <string>();

            //Set the current extension used by the target's file information if used
            if (targetFormat != null && targetFormat.FilePath != null)
            {
                string extension = Path.GetExtension(targetFormat.FilePath);
                if (extension != "" && !format.Any(x => x.Extension.Contains($"*{extension}")))
                {
                    Filter += $"*{extension};";
                    FilterEach.Add($"({extension}) |*{extension}|");
                }
            }

            foreach (IFileFormat f in format)
            {
                for (int i = 0; i < f.Extension.Length; i++)
                {
                    Filter += $"{f.Extension[i]};";
                    FilterEach.Add($"{f.Description[0]} ({f.Extension[i]}) |{f.Extension[i]}|");
                }
            }

            //Get compression formats
            foreach (ICompressionFormat f in FileManager.GetCompressionFormats())
            {
                for (int i = 0; i < f.Extension.Length; i++)
                {
                    Filter += $"{f.Extension[i]};";
                    FilterEach.Add($"{f.Description[0]} ({f.Extension[i]}) |{f.Extension[i]}|");
                }
            }

            Filter += $"{"*.z"};";
            Filter += $"{"*.cmp"};";
            Filter += $"{"*.yaz0"};";
            Filter += $"{"*.zstb"};";
            Filter += $"{"*.lz4"};";
            Filter += $"{"*.gz"};";
            Filter += $"{"*.szs"};";
            Filter += $"{"*.zs"};";
            Filter += $"{"*.yaz0"};";


            FilterEach.Add($"{"Compressed File"} ({"*.cmp"}) |{"*.cmp"}|");
            FilterEach.Add($"{"Zlib Compressed"} ({"*.z"}) |{"*.z"}|");
            FilterEach.Add($"{"Yaz0 Compressed"} ({"*.yaz0"}) |{"*.yaz0"}|");
            FilterEach.Add($"{"Zstb Compressed"} ({"*.zstb"}) |{"*.zstb"}|");
            FilterEach.Add($"{"Lz4 Compressed"} ({"*.lz4"}) |{"*.lz4"}|");
            FilterEach.Add($"{"GZIP Compressed"} ({"*.gz"}) |{"*.gz"}|");
            FilterEach.Add($"{"SZS ZSTD Compressed File"} ({"*.zs"}) |{"*.zs"}|");
            FilterEach.Add($"{"SZS Yaz0 Compressed"} ({"*.szs"}) |{"*.szs"}|");
            FilterEach.Add($"{"Yaz0 Compressed"} ({"*.yaz0"}) |{"*.yaz0"}|");

            Filter += "|";
            Filter += string.Join("", FilterEach.ToArray());
            Filter += "All files(*.*)|*.*";
            return(Filter);
        }
        /// <summary>
        ///  Action for the File->New command.
        /// </summary>
        /// 
        public void New_Execute(object parameter)
        {
            Values.Clear();
            lastSaveFormat = null;
            lastSavePath = null;

            Values.Add(new SampleViewModel() { Value = 0, Weight = 1 });
        }
예제 #27
0
 /// <summary>
 /// Creates a new instance of the <see cref="FileLoggerProvider"/> class
 /// </summary>
 public FileLoggerProvider(string name, string path, IFileNamingFormat namingFormat, IFileFormat format)
 {
     _name         = name;
     _path         = path;
     _namingFormat = namingFormat;
     _format       = format;
 }
예제 #28
0
        public void SetEditorForm(IFileFormat fileFormat)
        {
            if (fileFormat == null)
            {
                AddControl(new STUserControl()
                {
                    Dock = DockStyle.Fill
                });
                return;
            }

            Type objectType = fileFormat.GetType();

            foreach (var inter in objectType.GetInterfaces())
            {
                if (inter.IsGenericType && inter.GetGenericTypeDefinition() == typeof(IEditor <>))
                {
                    System.Reflection.MethodInfo method     = objectType.GetMethod("OpenForm");
                    System.Reflection.MethodInfo methodFill = objectType.GetMethod("FillEditor");

                    var Editor       = (UserControl)method.Invoke(fileFormat, new object[0]);
                    var ActiveEditor = GetActiveEditor(Editor.GetType());
                    if (ActiveEditor == null)
                    {
                        AddControl(Editor);
                    }
                    else
                    {
                        Editor = ActiveEditor;
                    }

                    methodFill.Invoke(fileFormat, new object[1] {
                        Editor
                    });
                    return;
                }
            }


            if (fileFormat is STGenericTexture)
            {
                var Editor       = ((STGenericTexture)fileFormat).GetEditor();
                var ActiveEditor = GetActiveEditor(Editor.GetType());
                if (ActiveEditor == null)
                {
                    AddControl(Editor);
                }
                else
                {
                    Editor = ActiveEditor;
                }

                ((STGenericTexture)fileFormat).FillEditor(Editor);
                return;
            }

            if (fileFormat is TreeNodeFile)
            {
                var Editor       = ((TreeNodeFile)fileFormat).GetEditor();
                var ActiveEditor = GetActiveEditor(Editor.GetType());
                if (ActiveEditor == null)
                {
                    AddControl(Editor);
                }
                else
                {
                    Editor = ActiveEditor;
                }

                ((TreeNodeFile)fileFormat).FillEditor(Editor);
                return;
            }
        }
		internal FileFormat (IFileFormat format, string id, string name)
		{
			this.id = id;
			this.name = name ?? id;
			this.format = format;
		}
예제 #30
0
 public static bool IsNativelySupportedImageFormat(IFileFormat imageFormat)
 {
     return(NativelySupportedImageFormats.Any(supportedImageFormat => supportedImageFormat.Equals(imageFormat)));
 }
예제 #31
0
 /// <summary>
 /// Method to export the mesh to a N3DT file format
 /// </summary>
 /// <param name="path">String value</param>
 public void ExportToN3dtFile(String path)
 {
     this.FileFormat = new N3DTFileFormat(this);
     this.FileFormat.Export(path);
     this.UpdateMainView();
 }
예제 #32
0
        protected override async Task <SendResult> Send(IWin32Window Owner, Output Output, ImageData ImageData)
        {
            try
            {
                string userName            = Output.UserName;
                string password            = Output.Password;
                bool   showLogin           = string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password);
                bool   rememberCredentials = false;

                string fileName = AttributeHelper.ReplaceAttributes(Output.FileName, ImageData);

                while (true)
                {
                    if (showLogin)
                    {
                        // Show credentials window
                        Credentials credentials = new Credentials(Output.Url, userName, password, rememberCredentials);

                        var credentialsOwnerHelper = new System.Windows.Interop.WindowInteropHelper(credentials);
                        credentialsOwnerHelper.Owner = Owner.Handle;

                        if (credentials.ShowDialog() != true)
                        {
                            return(new SendResult(Result.Canceled));
                        }

                        userName            = credentials.UserName;
                        password            = credentials.Password;
                        rememberCredentials = credentials.Remember;
                    }

                    LoginResult loginResult = await YouTrackProxy.Login(Output.Url, userName, password);

                    if (!loginResult.Success)
                    {
                        showLogin = true;
                        continue;
                    }

                    // Get projects
                    List <Project> projects = await YouTrackProxy.GetAccessibleProjects(Output.Url, loginResult.LoginCookies);

                    // Show send window
                    Send send = new Send(Output.Url, Output.LastProjectID, Output.LastIssueID, projects, fileName);

                    var sendOwnerHelper = new System.Windows.Interop.WindowInteropHelper(send);
                    sendOwnerHelper.Owner = Owner.Handle;

                    if (!send.ShowDialog() == true)
                    {
                        return(new SendResult(Result.Canceled));
                    }

                    string projectID = null;
                    string issueID   = null;

                    if (send.CreateNewIssue)
                    {
                        projectID = send.ProjectID;

                        CreateIssueResult createIssueResult = await YouTrackProxy.CreateIssue(Output.Url, loginResult.LoginCookies, projectID, send.Summary, send.Description);

                        if (!createIssueResult.Success)
                        {
                            return(new SendResult(Result.Failed, createIssueResult.FaultMessage));
                        }

                        issueID = createIssueResult.IssueID;
                    }
                    else
                    {
                        issueID   = send.IssueID;
                        projectID = Output.LastProjectID;
                    }

                    IFileFormat fileFormat = FileHelper.GetFileFormat(Output.FileFormatID);

                    string fullFileName = String.Format("{0}.{1}", send.FileName, fileFormat.FileExtension);

                    byte[] fileBytes = FileHelper.GetFileBytes(Output.FileFormatID, ImageData);

                    AddAttachmentResult addAttachmentResult = await YouTrackProxy.AddAttachment(Output.Url, loginResult.LoginCookies, issueID, fullFileName, fileBytes, fileFormat.MimeType);

                    if (!addAttachmentResult.Success)
                    {
                        return(new SendResult(Result.Failed, addAttachmentResult.FaultMessage));
                    }

                    // Open issue in browser
                    if (Output.OpenItemInBrowser)
                    {
                        WebHelper.OpenUrl(String.Format("{0}/issue/{1}", Output.Url, issueID));
                    }


                    return(new SendResult(Result.Success,
                                          new Output(Output.Name,
                                                     Output.Url,
                                                     (rememberCredentials) ? userName : Output.UserName,
                                                     (rememberCredentials) ? password : Output.Password,
                                                     Output.FileName,
                                                     Output.FileFormatID,
                                                     Output.OpenItemInBrowser,
                                                     projectID,
                                                     issueID)));
                }
            }
            catch (Exception ex)
            {
                return(new SendResult(Result.Failed, ex.Message));
            }
        }
예제 #33
0
        /// <summary>
        /// Saves the <see cref="IFileFormat"/> as a file from the given <param name="FileName">
        /// </summary>
        /// <param name="IFileFormat">The format instance of the file being saved</param>
        /// <param name="FileName">The name of the file</param>
        /// <param name="Alignment">The Alignment used for compression. Used for Yaz0 compression type. </param>
        /// <returns></returns>
        public static SaveLog SaveFileFormat(IFileFormat fileFormat, string fileName)
        {
            SaveLog   log       = new SaveLog();
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            fileFormat.FileInfo.FilePath = fileName;

            if (fileFormat.FileInfo.KeepOpen && File.Exists(fileName))
            {
                string savedPath = Path.GetDirectoryName(fileName);
                string tempPath  = Path.Combine(savedPath, "tempST.bin");

                //Save a temporary file first to not disturb the opened file
                using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    fileFormat.Save(fileStream);
                    if (fileFormat.FileInfo.Compression != null)
                    {
                        // Stream comp = CompressFile(File.OpenRead(tempPath), fileFormat);
                        //fileStream.CopyTo(comp);
                    }

                    if (fileFormat is IDisposable)
                    {
                        ((IDisposable)fileFormat).Dispose();
                    }

                    //After saving is done remove the existing file
                    File.Delete(fileName);

                    //Now move and rename our temp file to the new file path
                    File.Move(tempPath, fileName);

                    fileFormat.Load(File.OpenRead(fileName));
                }
            }
            else if (fileFormat.FileInfo.Compression != null)
            {
                MemoryStream mem = new MemoryStream();
                fileFormat.Save(mem);
                mem = new MemoryStream(mem.ToArray());
                var finalStream = CompressFile(mem, fileFormat);
                // File.WriteAllBytes(fileName, finalStream.ToArray());

                using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    finalStream.CopyTo(fileStream);
                }
            }
            else
            {
                using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    fileFormat.Save(fileStream);
                }
            }

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            log.SaveTime = string.Format("{0:D2}:{1:D2}:{2:D2}", ts.Minutes, ts.Seconds, ts.Milliseconds);

            return(log);
        }
예제 #34
0
        // Public members

        public static IArchive Open(string filePath, IFileFormat archiveFormat, IArchiveOptions archiveOptions = null)
        {
            return(ArchiveFactory.Default.Open(filePath, archiveFormat, archiveOptions));
        }
예제 #35
0
        public void LoadFile(AudioData audioData, IFileFormat fileFormat, bool ClearPlaylist = false)
        {
            if (ClearPlaylist)
            {
                audioListView.Items.Clear();
            }

            AudioFileFormats.Add(fileFormat);

            //Load Channel Info
            AudioFile file = new AudioFile();

            file.Title = fileFormat.FileName;
            if (fileFormat is VGAdudioFile)
            {
                file.vgAdudioFile = (VGAdudioFile)fileFormat;
            }

            //Loop through each channel and set it's own
            var format = audioData.GetAllFormats().ToArray()[0];

            for (int c = 0; c < format.ChannelCount; c++)
            {
                using (var memWav = new MemoryStream())
                {
                    AudioChannel audioChannel = new AudioChannel();
                    audioChannel.Name = $"Channel [{c}]";
                    file.Channels.Add(audioChannel);

                    //Load data and write to stream
                    var audio  = format.GetChannels(c).ToPcm16();
                    var writer = new WaveWriter();
                    writer.WriteToStream(audio, memWav);
                    audioChannel.Data = memWav.ToArray();

                    memWav.Position = 0;

                    //Load the player
                    audioChannel.audioPlayer.Open(new MemoryStream(audioChannel.Data), "test.wav", activeDevice);

                    /*     OpenFileDialog openFileDialog = new OpenFileDialog();
                     *   if (openFileDialog.ShowDialog() == DialogResult.OK)
                     *   {
                     *       audioChannel.audioPlayer.Open(openFileDialog.FileName, activeDevice);
                     *   }*/


                    audioChannel.audioPlayer.PlaybackStopped += (s, args) =>
                    {
                        //WasapiOut uses SynchronizationContext.Post to raise the event
                        //There might be already a new WasapiOut-instance in the background when the async Post method brings the PlaybackStopped-Event to us.
                        if (audioChannel.audioPlayer.PlaybackState != PlaybackState.Stopped)
                        {
                        }
                    };
                }
            }

            audioListView.AddObject(file);

            if (audioListView.Items.Count != 0)
            {
                audioListView.SelectedIndex = 0;
            }
        }
예제 #36
0
 /// <summary>
 /// Method to load a N3DT file (.n3dt)
 /// </summary>
 /// <param name="path">String value</param>
 private void ImportN3dtFile(String path)
 {
     this.FileFormat = new N3DTFileFormat(this);
     this.FileFormat.Load(path);
     this.UpdateMainView();
 }
예제 #37
0
 public static IImageOptimizer FromImageFormat(IFileFormat imageFormat)
 {
     return(GetImageOptimizers().FirstOrDefault(optimizer => optimizer.IsSupportedFileFormat(imageFormat)));
 }
예제 #38
0
 /// <summary>
 /// Method to export the mesh to a N3DT file format
 /// </summary>
 /// <param name="path">String value</param>
 public void ExportToObjFile(String path)
 {
     this.FileFormat = new OBJFileFormat(this);
     this.FileFormat.Export(path);
     this.UpdateMainView();
 }
        public static Stream FromStream(this IFileFormatFactory fileFormatFactory, Stream stream, out IFileFormat fileFormat)
        {
            // Read the file signature from the stream into a buffer, which is then concatenated with the original stream.
            // This allows us to read the file signature from streams that don't support seeking.

            int maxSignatureLength = fileFormatFactory.GetKnownFileFormats()
                                     .Where(format => format.Signatures is object && format.Signatures.Any())
                                     .SelectMany(format => format.Signatures.Select(sig => sig.Length))
                                     .OrderByDescending(length => length)
                                     .FirstOrDefault();

            MemoryStream fileSignatureBuffer = new MemoryStream(new byte[maxSignatureLength], 0, maxSignatureLength, writable: true, publiclyVisible: true);

            try {
                int bytesRead = stream.Read(fileSignatureBuffer.GetBuffer(), 0, maxSignatureLength);

                fileSignatureBuffer.SetLength(bytesRead);

                fileFormat = fileFormatFactory.FromStream(fileSignatureBuffer);

                fileSignatureBuffer.Seek(0, SeekOrigin.Begin);

                return(new ConcatStream(fileSignatureBuffer, stream));
            }
            catch (Exception) {
                fileSignatureBuffer.Dispose();

                throw;
            }
        }
 public override object BuildItem(object owner, ArrayList subItems, ConditionCollection conditions)
 {
     fileFormat = (IFileFormat) AddIn.CreateObject (Class);
     return this;
 }
예제 #41
0
 internal FileFormat(IFileFormat format, string id, string name)
 {
     this.id     = id;
     this.name   = name ?? id;
     this.format = format;
 }
예제 #42
0
 public static void Add(IFileFormat format)
 {
     formats.Add(format);
 }
예제 #43
0
        /// <summary>
        /// Saves the <see cref="IFileFormat"/> as a file from the given <param name="FileName">
        /// </summary>
        /// <param name="IFileFormat">The format instance of the file being saved</param>
        /// <param name="FileName">The name of the file</param>
        /// <param name="Alignment">The Alignment used for compression. Used for Yaz0 compression type. </param>
        /// <param name="EnableDialog">Toggle for showing compression dialog</param>
        /// <returns></returns>
        public static void SaveFileFormat(IFileFormat FileFormat, string FileName, bool EnableDialog = true, string DetailsLog = "")
        {
            //These always get created on loading a file,however not on creating a new file
            if (FileFormat.IFileInfo == null)
            {
                throw new System.NotImplementedException("Make sure to impliment a IFileInfo instance if a format is being created!");
            }

            Cursor.Current      = Cursors.WaitCursor;
            FileFormat.FilePath = FileName;

            if (FileFormat.IFileInfo.FileIsCompressed || FileFormat.IFileInfo.InArchive || Path.GetExtension(FileName) == ".szs")
            {
                //Todo find more optmial way to handle memory with files in archives
                //Also make compression require streams
                var mem = new System.IO.MemoryStream();
                FileFormat.Save(mem);
                mem = new System.IO.MemoryStream(mem.ToArray());

                FileFormat.IFileInfo.DecompressedSize = (uint)mem.Length;

                var finalStream = CompressFileFormat(
                    FileFormat.IFileInfo.FileCompression,
                    mem,
                    FileFormat.IFileInfo.FileIsCompressed,
                    FileFormat.IFileInfo.Alignment,
                    FileName,
                    EnableDialog);

                FileFormat.IFileInfo.CompressedSize = (uint)finalStream.Length;
                finalStream.ExportToFile(FileName);

                DetailsLog += "\n" + SatisfyFileTables(FileFormat, FileName, finalStream,
                                                       FileFormat.IFileInfo.DecompressedSize,
                                                       FileFormat.IFileInfo.CompressedSize,
                                                       FileFormat.IFileInfo.FileIsCompressed);

                finalStream.Flush();
                finalStream.Close();
            }
            else
            {
                //Check if a stream is active and the file is beinng saved to the same opened file
                if (FileFormat is ISaveOpenedFileStream && FileFormat.FilePath == FileName && File.Exists(FileName))
                {
                    string savedPath = Path.GetDirectoryName(FileName);
                    string tempPath  = Path.Combine(savedPath, "tempST.bin");

                    //Save a temporary file first to not disturb the opened file
                    using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);

                        //After saving is done remove the existing file
                        File.Delete(FileName);

                        //Now move and rename our temp file to the new file path
                        File.Move(tempPath, FileName);
                    }
                }
                else
                {
                    using (var fileStream = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);
                    }
                }
            }

            MessageBox.Show($"File has been saved to {FileName}", "Save Notification");

            //   STSaveLogDialog.Show($"File has been saved to {FileName}", "Save Notification", DetailsLog);
            Cursor.Current = Cursors.Default;
        }
예제 #44
0
		internal FileFormat (IFileFormat format, string id, string name)
			: this (format, id, name, false)
		{
		}
예제 #45
0
        private static string SatisfyFileTables(IFileFormat FileFormat, string FilePath, Stream Data, uint DecompressedSize, uint CompressedSize, bool IsYaz0Compressed)
        {
            string FileLog = "";

            bool IsBotwFile = FilePath.IsSubPathOf(Runtime.BotwGamePath);
            bool IsTPHDFile = FilePath.IsSubPathOf(Runtime.TpGamePath);

            if (Runtime.ResourceTables.BotwTable && IsBotwFile)
            {
                string newFilePath = FilePath.Replace(Runtime.BotwGamePath, string.Empty).Remove(0, 1);
                newFilePath = newFilePath.Replace(".s", ".");
                newFilePath = newFilePath.Replace(@"\", "/");

                string RealExtension = Path.GetExtension(newFilePath).Replace(".s", ".");

                string RstbPath = Path.Combine($"{Runtime.BotwGamePath}",
                                               "System", "Resource", "ResourceSizeTable.product.srsizetable");

                RSTB BotwResourceTable = new RSTB();
                BotwResourceTable.LoadFile(RstbPath);

                //Create a backup first if one doesn't exist
                if (!File.Exists($"{RstbPath}.backup"))
                {
                    STConsole.WriteLine($"RSTB File found. Creating backup...");

                    BotwResourceTable.Write(new FileWriter($"{RstbPath}.backup"));
                    File.WriteAllBytes($"{RstbPath}.backup", EveryFileExplorer.YAZ0.Compress($"{RstbPath}.backup"));
                }

                //Now apply the file table then save the table
                if (BotwResourceTable.IsInTable(newFilePath))
                {
                    FileLog += $"File found in resource table! {newFilePath}";
                    STConsole.WriteLine(FileLog, 1);
                }
                else
                {
                    FileLog += $"File NOT found in resource table! {newFilePath}";
                    STConsole.WriteLine(FileLog, 0);
                }

                BotwResourceTable.SetEntry(newFilePath, Data, IsYaz0Compressed);
                BotwResourceTable.Write(new FileWriter(RstbPath));
                File.WriteAllBytes(RstbPath, EveryFileExplorer.YAZ0.Compress(RstbPath));
            }

            if (Runtime.ResourceTables.TpTable && IsTPHDFile)
            {
                string newFilePath = FilePath.Replace(Runtime.TpGamePath, string.Empty).Remove(0, 1);
                newFilePath = newFilePath.Replace(@"\", "/");

                //Read the compressed tables and set the new sizes if paths match
                TPFileSizeTable CompressedFileTbl = new TPFileSizeTable();
                CompressedFileTbl.ReadCompressedTable(new FileReader($"{Runtime.TpGamePath}/FileSizeList.txt"));
                if (CompressedFileTbl.IsInFileSizeList(newFilePath))
                {
                    STConsole.WriteLine("Found matching path in File Size List table! " + newFilePath, 1);
                    CompressedFileTbl.SetFileSizeEntry(newFilePath, CompressedSize);
                }
                else
                {
                    STConsole.WriteLine("Failed to find path in File Size List table! " + newFilePath, 0);
                }

                //Read decompressed file sizes
                TPFileSizeTable DecompressedFileTbl = new TPFileSizeTable();
                DecompressedFileTbl.ReadDecompressedTable(new FileReader($"{Runtime.TpGamePath}/DecompressedSizeList.txt"));

                newFilePath = $"./DVDRoot/{newFilePath}";
                newFilePath = newFilePath.Replace(".gz", string.Empty);

                //Write the decompressed file size
                if (DecompressedFileTbl.IsInDecompressedFileSizeList(newFilePath))
                {
                    STConsole.WriteLine("Found matching path in File Size List table! " + newFilePath, 1);
                    DecompressedFileTbl.SetDecompressedFileSizeEntry(newFilePath, CompressedSize, DecompressedSize);
                }
                else
                {
                    STConsole.WriteLine("Failed to find path in File Size List table! " + newFilePath, 0);
                }

                if (FileFormat == null)
                {
                    return(FileLog);
                }

                //Check if archive type
                bool IsArchive = false;
                foreach (var inter in FileFormat.GetType().GetInterfaces())
                {
                    if (inter == typeof(IArchiveFile))
                    {
                        IsArchive = true;
                    }
                }


                //Write all the file sizes in the archive if it's an archive type
                //Note this seems uneeded atm
                //Todo store both compressed and decompressed sizes in archive info

                /*   if (IsArchive)
                 * {
                 *     IArchiveFile Archive = (IArchiveFile)FileFormat;
                 *     foreach (var file in Archive.Files)
                 *     {
                 *         uint DecompressedArchiveFileSize = (uint)file.FileData.Length;
                 *         string ArchiveFilePath = $"/DVDRoot/{file.FileName}";
                 *
                 *         if (DecompressedFileTbl.IsInDecompressedFileSizeList(ArchiveFilePath))
                 *         {
                 *             STConsole.WriteLine("Found matching path in File Size List table! " + ArchiveFilePath, 1);
                 *             DecompressedFileTbl.SetDecompressedFileSizeEntry(ArchiveFilePath, DecompressedArchiveFileSize, DecompressedArchiveFileSize);
                 *         }
                 *         else
                 *             STConsole.WriteLine("Failed to find path in File Size List table! " + ArchiveFilePath, 0);
                 *     }
                 * }*/

                CompressedFileTbl.WriteCompressedTable(new FileWriter($"{Runtime.TpGamePath}/FileSizeList.txt"));
                DecompressedFileTbl.WriteDecompressedTable(new FileWriter($"{Runtime.TpGamePath}/DecompressedSizeList.txt"));
            }

            return(FileLog);
        }
예제 #46
0
 public static void Add(IFileFormat format)
 {
     formats.Add(format);
 }
예제 #47
0
 internal FileLogger(string categoryName, string path, IFileFormat format, IFileNamingFormat namingFormat)
 {
     _categoryName = categoryName;
     _format       = format;
     _path         = path;
 }