public Daisy3_Import(string bookfile, string outDir, bool skipACM, SampleRate audioProjectSampleRate, bool stereo, bool autoDetectPcmFormat, bool xukPrettyFormat) { m_XukPrettyFormat = xukPrettyFormat; m_SkipACM = skipACM; m_audioProjectSampleRate = audioProjectSampleRate; m_audioStereo = stereo; m_autoDetectPcmFormat = autoDetectPcmFormat; reportProgress(10, UrakawaSDK_daisy_Lang.InitializeImport); m_PackageUniqueIdAttr = null; m_Book_FilePath = bookfile; m_outDirectory = outDir; if (!m_outDirectory.EndsWith("" + Path.DirectorySeparatorChar)) { m_outDirectory += Path.DirectorySeparatorChar; } if (!Directory.Exists(m_outDirectory)) { FileDataProvider.CreateDirectory(m_outDirectory); } m_Xuk_FilePath = GetXukFilePath(m_outDirectory, m_Book_FilePath, null, false); if (RequestCancellation) { return; } //initializeProject(); //reportProgress(100, UrakawaSDK_daisy_Lang.ImportInitialized); }
static AudioFormatConvertorSession() { if (!Directory.Exists(TEMP_AUDIO_DIRECTORY)) { FileDataProvider.CreateDirectory(TEMP_AUDIO_DIRECTORY); } }
public static string GetAndCreateImageDescriptionDirectoryPath(bool create, string imageSRC, string outputDirectory) { string imageDescriptionDirName = FileDataProvider.EliminateForbiddenFileNameCharacters(imageSRC).Replace('.', '_') + IMAGE_DESCRIPTION_DIRECTORY_SUFFIX; string imageDescriptionDirectoryPath = Path.Combine(outputDirectory, imageDescriptionDirName); if (create && !Directory.Exists(imageDescriptionDirectoryPath)) { FileDataProvider.CreateDirectory(imageDescriptionDirectoryPath); } return(imageDescriptionDirectoryPath); }
public static void WriteXmlDocument(XmlDocument xmlDoc, string path, XmlWriterSettings settings) { string parentDir = Path.GetDirectoryName(path); if (!Directory.Exists(parentDir)) { FileDataProvider.CreateDirectory(parentDir); } const bool pretty = true; xmlDoc.PreserveWhitespace = false; xmlDoc.XmlResolver = null; FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); if (settings == null) { settings = GetDefaultXmlWriterConfiguration(pretty); } XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(fileStream, settings); if (pretty && xmlWriter is XmlTextWriter) { ((XmlTextWriter)xmlWriter).Formatting = Formatting.Indented; } xmlDoc.Save(xmlWriter); } finally { if (xmlWriter != null) { xmlWriter.Close(); } if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } }
//public ushort BitRate_Mp3 //{ // get { return m_BitRate_Mp3; } // set { m_BitRate_Mp3 = value; } //} /// <summary> /// initializes instance with presentation and list of element names for which navList will be created, /// if null is passed as list parameter , no navList will be created /// </summary> /// <param name="presentation"></param> /// <param name="navListElementNamesList"></param> public Daisy3_Export(Presentation presentation, string exportDirectory, List <string> navListElementNamesList, bool encodeAudioFiles, double bitRate_Encoding, SampleRate sampleRate, bool stereo, bool skipACM, bool includeImageDescriptions, bool generateSmilNoteReferences) { m_includeImageDescriptions = includeImageDescriptions; m_generateSmilNoteReferences = generateSmilNoteReferences; m_encodeAudioFiles = encodeAudioFiles; m_sampleRate = sampleRate; m_audioStereo = stereo; m_SkipACM = skipACM; m_BitRate_Encoding = bitRate_Encoding; RequestCancellation = false; if (!Directory.Exists(exportDirectory)) { FileDataProvider.CreateDirectory(exportDirectory); } m_OutputDirectory = exportDirectory; m_Presentation = presentation; if (navListElementNamesList != null) { m_NavListElementNamesList = navListElementNamesList; } else { m_NavListElementNamesList = new List <string>(); } if (!m_NavListElementNamesList.Contains("note")) { m_NavListElementNamesList.Add("note"); } }
static ExternalFilesDataManager() { #if USE_ISOLATED_STORAGE using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { store.CreateDirectory(dirName); FieldInfo fi = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance); STORAGE_FOLDER_PATH = (string)fi.GetValue(store) + Path.DirectorySeparatorChar + STORAGE_FOLDER_NAME; } #else STORAGE_FOLDER_PATH = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + STORAGE_FOLDER_NAME; if (!Directory.Exists(STORAGE_FOLDER_PATH)) { FileDataProvider.CreateDirectory(STORAGE_FOLDER_PATH); } #endif //USE_ISOLATED_STORAGE }
private string CreateLocalDTDFileFromWebStream(string strWebDTDPath, Stream webStream) { FileStream fs = null; try { #if USE_ISOLATED_STORAGE using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { fs = new IsolatedStorageFileStream(Path.GetFileName(strWebDTDPath), FileMode.Create, FileAccess.Write, FileShare.None, store); } // NOTE: we could actually use the same code as below, which gives more control over the subdirectory and doesn't have any size limits: #else string dirpath = Path.Combine(ExternalFilesDataManager.STORAGE_FOLDER_PATH, m_DtdStoreDirName); if (!Directory.Exists(dirpath)) { FileDataProvider.CreateDirectory(dirpath); } string filepath = Path.Combine(dirpath, Path.GetFileName(strWebDTDPath)); fs = File.Create(filepath); #endif //USE_ISOLATED_STORAGE const uint BUFFER_SIZE = 1024; // 1 KB MAX BUFFER StreamUtils.Copy(webStream, 0, fs, BUFFER_SIZE); return(filepath); } finally { if (fs != null) { fs.Close(); } } }
public override bool Validate() { if (m_Session.IsXukSpine) { return(true); } //#if DEBUG // m_DtdRegex.Reset(); //#endif // DEBUG if (!Settings.Default.EnableMarkupValidation) { resetToValid(); return(IsValid); } String dtdIdentifier = DTDs.DTDs.DTBOOK_2005_3_MATHML; if (m_Session.DocumentProject != null && "body".Equals(m_Session.DocumentProject.Presentations.Get(0).RootNode.GetXmlElementLocalName(), StringComparison.OrdinalIgnoreCase)) { dtdIdentifier = DTDs.DTDs.HTML5; //// TODO: a DTD does not exist per-say for HTML5 (as this is not an SGML-based markup language), //// and Tobi's own HTML5 DTD hack does not cut it...just way too many false positives, //// as well as incorrect handling of "transparent" elements that can have dual block inline content models. //// So, the document is always considered valid. resetToValid(); return(IsValid); } bool dtdHasChanged = String.IsNullOrEmpty(m_DtdIdentifier) || m_DtdIdentifier != dtdIdentifier; m_DtdIdentifier = dtdIdentifier; if (dtdHasChanged || m_DtdRegex.DtdRegexTable == null || m_DtdRegex.DtdRegexTable.Count == 0) { loadDTD(m_DtdIdentifier); string dtdCache = m_DtdIdentifier + ".cache"; string dirpath = Path.Combine(ExternalFilesDataManager.STORAGE_FOLDER_PATH, m_DtdStoreDirName); string path = Path.Combine(dirpath, dtdCache); //cache the dtd and save it as dtdIdenfier + ".cache" #if USE_ISOLATED_STORAGE using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { stream = new IsolatedStorageFileStream(dtdCache, FileMode.Create, FileAccess.Write, FileShare.None, store); } // NOTE: we could actually use the same code as below, which gives more control over the subdirectory and doesn't have any size limits: #else if (!Directory.Exists(dirpath)) { FileDataProvider.CreateDirectory(dirpath); } Stream stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None); #endif //USE_ISOLATED_STORAGE var writer = new StreamWriter(stream); try { m_DtdRegex.WriteToCache(writer); } finally { writer.Flush(); writer.Close(); } } if (m_Session.DocumentProject != null) { resetToValid(); if (m_DtdRegex == null || m_DtdRegex.DtdRegexTable == null || m_DtdRegex.DtdRegexTable.Count == 0) { MissingDtdValidationError error = new MissingDtdValidationError() { DtdIdentifier = m_DtdIdentifier }; addValidationItem(error); } else { var strBuilder = new StringBuilder(); ValidateNode(strBuilder, m_Session.DocumentProject.Presentations.Get(0).RootNode); } } return(IsValid); }
/// <summary> /// takes wav file / mp3 file as input and converts it to wav file with audio format info supplied as parameter /// </summary> /// <param name="SourceFilePath"></param> /// <param name="destinationDirectory"></param> /// <param name="destinationFormatInfo"></param> /// <returns> full file path of converted file </returns> private string ConvertToDefaultFormat(string SourceFilePath, string destinationDirectory, PCMFormatInfo destinationFormatInfo, bool skipACM) { if (!File.Exists(SourceFilePath)) { throw new FileNotFoundException(SourceFilePath); } if (!Directory.Exists(destinationDirectory)) { FileDataProvider.CreateDirectory(destinationDirectory); } AudioFileType sourceFileType = GetAudioFileType(SourceFilePath); switch (sourceFileType) { case AudioFileType.WavUncompressed: case AudioFileType.WavCompressed: { if (FirstDiscoveredPCMFormat == null) { Stream wavStream = null; try { wavStream = File.Open(SourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); uint dataLength; AudioLibPCMFormat pcmInfo = null; pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); //FirstDiscoveredPCMFormat = new PCMFormatInfo(pcmInfo); FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); FirstDiscoveredPCMFormat.CopyFrom(pcmInfo); } finally { if (wavStream != null) { wavStream.Close(); } } } WavFormatConverter formatConverter1 = new WavFormatConverter(true, skipACM); AddSubCancellable(formatConverter1); // Preserve existing WAV PCM format, the call below to ConvertSampleRate detects the equality of PCM formats and copies the audio file instead of resampling. AudioLibPCMFormat pcmFormat = m_autoDetectPcmFormat ? FirstDiscoveredPCMFormat : (destinationFormatInfo != null ? destinationFormatInfo.Data : new AudioLibPCMFormat()); string result = null; try { AudioLibPCMFormat originalPcmFormat; result = formatConverter1.ConvertSampleRate(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); if (originalPcmFormat != null && FirstDiscoveredPCMFormat != null) { DebugFix.Assert(FirstDiscoveredPCMFormat.Equals(originalPcmFormat)); } } finally { RemoveSubCancellable(formatConverter1); } return(result); } case AudioFileType.Mp4_AAC: case AudioFileType.Mp3: { WavFormatConverter formatConverter2 = new WavFormatConverter(true, skipACM); AddSubCancellable(formatConverter2); string result = null; try { AudioLibPCMFormat pcmFormat = m_autoDetectPcmFormat ? FirstDiscoveredPCMFormat : // can be null! (destinationFormatInfo != null ? destinationFormatInfo.Data : new AudioLibPCMFormat()); AudioLibPCMFormat originalPcmFormat; if (sourceFileType == AudioFileType.Mp3) { result = formatConverter2.UnCompressMp3File(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); } else { DebugFix.Assert(sourceFileType == AudioFileType.Mp4_AAC); result = formatConverter2.UnCompressMp4_AACFile(SourceFilePath, destinationDirectory, pcmFormat, out originalPcmFormat); } if (originalPcmFormat != null) { if (FirstDiscoveredPCMFormat == null) { //FirstDiscoveredPCMFormat = new PCMFormatInfo(originalPcmFormat); FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); FirstDiscoveredPCMFormat.CopyFrom(originalPcmFormat); } } } finally { RemoveSubCancellable(formatConverter2); } return(result); } default: throw new Exception("Source file format not supported"); } }
/// <summary> /// initializes instance with presentation and list of element names for which navList will be created, /// if null is passed as list parameter , no navList will be created /// </summary> /// <param name="presentation"></param> /// <param name="navListElementNamesList"></param> public Daisy3_Export(Presentation presentation, //bool useTitleInFileName, string exportDirectory, List <string> navListElementNamesList, bool encodeAudioFiles, double bitRate_Encoding, SampleRate sampleRate, bool stereo, bool skipACM, bool includeImageDescriptions, bool generateSmilNoteReferences, string audioExportDTBOOKElementNameTriggers) { //m_useTitleInFileName = useTitleInFileName; if (!string.IsNullOrEmpty(audioExportDTBOOKElementNameTriggers)) { string[] elementNames = audioExportDTBOOKElementNameTriggers.Split(new char[] { ',', ' ', ';', '/' }); m_audioExportDTBOOKElementNameTriggers = new List <string>(elementNames.Length); foreach (string n in elementNames) { string n_ = n.Trim(); //.ToLower(); if (!string.IsNullOrEmpty(n_)) { m_audioExportDTBOOKElementNameTriggers.Add(n_); } } if (m_audioExportDTBOOKElementNameTriggers.Count == 0) { m_audioExportDTBOOKElementNameTriggers = null; } } m_includeImageDescriptions = includeImageDescriptions; m_generateSmilNoteReferences = generateSmilNoteReferences; m_encodeAudioFiles = encodeAudioFiles; m_sampleRate = sampleRate; m_audioStereo = stereo; m_SkipACM = skipACM; m_BitRate_Encoding = bitRate_Encoding; RequestCancellation = false; if (!Directory.Exists(exportDirectory)) { FileDataProvider.CreateDirectory(exportDirectory); } m_OutputDirectory = exportDirectory; m_Presentation = presentation; if (navListElementNamesList != null) { m_NavListElementNamesList = navListElementNamesList; } else { m_NavListElementNamesList = new List <string>(); } if (!m_NavListElementNamesList.Contains("note")) { m_NavListElementNamesList.Add("note"); } }
private void unzipEPubAndParseOpf() { if (RequestCancellation) { return; } /*string directoryName = Path.GetTempPath(); * if (!directoryName.EndsWith("" + Path.DirectorySeparatorChar)) * { * directoryName += Path.DirectorySeparatorChar; * }*/ string unzipDirectory = Path.Combine( Path.GetDirectoryName(m_Book_FilePath), //m_outDirectory, //FileDataProvider.EliminateForbiddenFileNameCharacters(m_Book_FilePath) //m_Book_FilePath.Replace('.', '_') m_Book_FilePath + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); #if ENABLE_SHARPZIP ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(m_Book_FilePath)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { if (RequestCancellation) { return; } string zipEntryName = Path.GetFileName(zipEntry.Name); if (!String.IsNullOrEmpty(zipEntryName)) // || zipEntryName.IndexOf(".ini") >= 0 { // string unzippedFilePath = Path.Combine(unzipDirectory, zipEntryName); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + zipEntry.Name; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } FileStream fileStream = File.Create(unzippedFilePath); //byte[] data = new byte[2 * 1024]; // 2 KB buffer //int bytesRead = 0; try { const uint BUFFER_SIZE = 1024 * 2; // 2 KB MAX BUFFER StreamUtils.Copy(zipInputStream, 0, fileStream, BUFFER_SIZE); //while ((bytesRead = zipInputStream.Read(data, 0, data.Length)) > 0) //{ // fileStream.Write(data, 0, bytesRead); //} } finally { fileStream.Close(); } } } zipInputStream.Close(); #else //ENABLE_SHARPZIP ZipStorer zip = ZipStorer.Open(File.OpenRead(m_Book_FilePath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { if (RequestCancellation) { return; } reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } //zip.Close(); zip.Dispose(); #endif //ENABLE_SHARPZIP string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); #if NET40 IEnumerable <FileInfo> opfFiles = dirInfo.EnumerateFiles("*.opf", SearchOption.AllDirectories); #else FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); #endif // string[] fileNames = Directory.GetFiles(unzipDirectory, "*.opf", //#if NET40 // SearchOption.AllDirectories //#endif // ); foreach (FileInfo fileInfo in opfFiles) { if (RequestCancellation) { return; } m_Book_FilePath = Path.Combine(unzipDirectory, fileInfo.FullName); m_OPF_ContainerRelativePath = null; openAndParseOPF(m_Book_FilePath); break; } } else { parseContainerXML(containerPath); } // string opfPath = ""; // string parentDir = Path.GetDirectoryName(opfPath); // while (!string.IsNullOrEmpty(parentDir)) // { // DirectoryInfo dirInfo = new DirectoryInfo(parentDir); // DirectoryInfo[] metaInfDirs = dirInfo.GetDirectories(@"META-INF", SearchOption.TopDirectoryOnly); // if (RequestCancellation) return; // foreach (DirectoryInfo dirInfo in metaInfDirs) // { // string containerPath = Path.Combine(parentDir, dirInfo.FullName + Path.DirectorySeparatorChar + @"container.xml"); // if (!File.Exists(containerPath)) // { //#if DEBUG // Debugger.Break(); //#endif // } // else // { // if (!parseContainerXML(containerPath)) // { // openAndParseOPF(opfPath); // } // } // break; // } // DirectoryInfo parentDirInfo = dirInfo.Parent; // if (parentDirInfo != null) // { // parentDir = parentDirInfo.FullName; // } // else // { // parentDir = null; // } // } // // final fallback // openAndParseOPF(opfPath); }
public static string unzipEPubAndGetOpfPath(string EPUBFullPath) { //if (RequestCancellation) return; string parentDirectoryFullPath = Directory.GetParent(EPUBFullPath).ToString(); string unzipDirectory = Path.Combine( parentDirectoryFullPath, Path.GetFileNameWithoutExtension(EPUBFullPath) + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); ZipStorer zip = ZipStorer.Open(File.OpenRead(EPUBFullPath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { //if (RequestCancellation) return; //reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; if (Path.GetExtension(unzippedFilePath).ToLower() == ".opf" || Path.GetExtension(unzippedFilePath).ToLower() == ".xml") { string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } } zip.Dispose(); string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); string opfFullPath = null; if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); foreach (FileInfo fileInfo in opfFiles) { opfFullPath = Path.Combine(unzipDirectory, fileInfo.FullName); //m_OPF_ContainerRelativePath = null; break; } } else { //parseContainerXML(containerPath); XmlDocument containerDoc = XmlReaderWriterHelper.ParseXmlDocument(containerPath, false, false); XmlNode rootFileNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(containerDoc, true, @"rootfile", containerDoc.DocumentElement.NamespaceURI); #if DEBUG XmlNode mediaTypeAttr = rootFileNode.Attributes.GetNamedItem(@"media-type"); DebugFix.Assert(mediaTypeAttr != null && mediaTypeAttr.Value == @"application/oebps-package+xml"); #endif XmlNode fullPathAttr = rootFileNode.Attributes.GetNamedItem(@"full-path"); string rootDirectory = Path.GetDirectoryName(containerPath); rootDirectory = rootDirectory.Substring(0, rootDirectory.IndexOf(@"META-INF")); string OPF_ContainerRelativePath = FileDataProvider.UriDecode(fullPathAttr.Value); if (OPF_ContainerRelativePath.StartsWith(@"./")) { OPF_ContainerRelativePath = OPF_ContainerRelativePath.Substring(2); } opfFullPath = Path.Combine(rootDirectory, OPF_ContainerRelativePath.Replace('/', '\\')); } return(opfFullPath); }
static ApplicationConstants() { //Directory.GetCurrentDirectory() //string apppath = (new FileInfo(Assembly.GetExecutingAssembly().CodeBase)).DirectoryName; //AppDomain.CurrentDomain.BaseDirectory if (String.IsNullOrEmpty(STORAGE_FOLDER_PATH)) { //static ExternalFilesDataManager not initialised on time! #if DEBUG Debugger.Break(); #endif #if USE_ISOLATED_STORAGE using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { store.CreateDirectory(dirName); FieldInfo fi = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance); STORAGE_FOLDER_PATH = (string)fi.GetValue(store) + Path.DirectorySeparatorChar + ExternalFilesDataManager.STORAGE_FOLDER_NAME; } #else STORAGE_FOLDER_PATH = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + ExternalFilesDataManager.STORAGE_FOLDER_NAME; if (!Directory.Exists(STORAGE_FOLDER_PATH)) { FileDataProvider.CreateDirectory(STORAGE_FOLDER_PATH); } #endif //USE_ISOLATED_STORAGE } //string currentAssemblyDirectoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); LOG_FILE_PATH = STORAGE_FOLDER_PATH + Path.DirectorySeparatorChar + LOG_FILE_NAME; //@"\" APP_VERSION = GetVersion(); string coreLibVersion = null; string name = ""; foreach (Assembly item in AppDomain.CurrentDomain.GetAssemblies()) { if (item.GlobalAssemblyCache) { if (!string.IsNullOrEmpty(item.FullName) && item.FullName.Contains("mscorlib")) { name = item.FullName; coreLibVersion = item.ImageRuntimeVersion; break; } } } bool isV4 = !string.IsNullOrEmpty(coreLibVersion) && coreLibVersion.Contains("v4.") || name.Contains("Version=4"); #if NET40 const string NET4 = " [.NET 4]"; DOTNET_INFO = NET4; #else const string NET4_ButTobi3 = " [.NET 3/4]"; const string NET3 = " [.NET 3]"; DOTNET_INFO = (isV4 ? NET4_ButTobi3 : NET3); #endif OS_INFORMATION = getOSInfo() + DOTNET_INFO + " -- (" + (IsRunning64() ? "64-bit" : "32-bit") + " .NET)"; }
/// <summary> /// Constructor /// </summary> /// <param name="destUri">The <see cref="Uri"/> of the destination (cannot be null)</param> /// <param name="xukAble">The source <see cref="IXukAble"/>(cannot be null)</param> public SaveXukAction(Project proj, IXukAble xukAble, Uri destUri, bool skipBackup) { if (proj == null) { throw new exception.MethodParameterIsNullException( "The source Project of the SaveXukAction cannot be null"); } if (destUri == null) { throw new exception.MethodParameterIsNullException( "The destination URI of the SaveXukAction cannot be null"); } if (xukAble == null) { throw new exception.MethodParameterIsNullException( "The source XukAble of the SaveXukAction cannot be null"); } m_Project = proj; mDestUri = destUri; mSourceXukAble = xukAble; int currentPercentage = 0; EventHandler <ProgressEventArgs> progressing = delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = (int)((val / max) * 100); if (percent != currentPercentage) { currentPercentage = percent; reportProgress_Throttle(currentPercentage, val + " / " + max); //backWorker.ReportProgress(currentPercentage); } if (RequestCancellation) { e.Cancel(); } }; Progress += progressing; Finished += delegate(object sender, FinishedEventArgs e) { Progress -= progressing; }; Cancelled += delegate(object sender, CancelledEventArgs e) { Progress -= progressing; }; string path = mDestUri.LocalPath; string parentdir = Path.GetDirectoryName(path); if (!Directory.Exists(parentdir)) { FileDataProvider.CreateDirectory(parentdir); } if (!skipBackup) { Backup(path); } mDestStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); bool pretty = mSourceXukAble.PrettyFormat; XmlWriterSettings settings = XmlReaderWriterHelper.GetDefaultXmlWriterConfiguration(pretty); mXmlWriter = XmlWriter.Create(mDestStream, settings); if (pretty && mXmlWriter is XmlTextWriter) { ((XmlTextWriter)mXmlWriter).Formatting = Formatting.Indented; } }
private void OnClick_ButtonExport(object sender, RoutedEventArgs e) { m_Logger.Log("DescriptionView.OnClick_ButtonExport", Category.Debug, Priority.Medium); Tuple <TreeNode, TreeNode> selection = m_Session.GetTreeNodeSelection(); TreeNode node = selection.Item2 ?? selection.Item1; if (node == null || node.GetAlternateContentProperty() == null || node.GetImageMedia() == null || !(node.GetImageMedia() is ManagedImageMedia)) { return; } SampleRate sampleRate = SampleRate.Hz22050; sampleRate = Urakawa.Settings.Default.AudioExportSampleRate; bool encodeToMp3 = true; encodeToMp3 = Urakawa.Settings.Default.AudioExportEncodeToMp3; var combo = new ComboBox { Margin = new Thickness(0, 0, 0, 12) }; ComboBoxItem item1 = new ComboBoxItem(); item1.Content = AudioLib.SampleRate.Hz11025.ToString(); combo.Items.Add(item1); ComboBoxItem item2 = new ComboBoxItem(); item2.Content = AudioLib.SampleRate.Hz22050.ToString(); combo.Items.Add(item2); ComboBoxItem item3 = new ComboBoxItem(); item3.Content = AudioLib.SampleRate.Hz44100.ToString(); combo.Items.Add(item3); switch (sampleRate) { case AudioLib.SampleRate.Hz11025: { combo.SelectedItem = item1; combo.Text = item1.Content.ToString(); break; } case AudioLib.SampleRate.Hz22050: { combo.SelectedItem = item2; combo.Text = item2.Content.ToString(); break; } case AudioLib.SampleRate.Hz44100: { combo.SelectedItem = item3; combo.Text = item3.Content.ToString(); break; } } var checkBox = new CheckBox { IsThreeState = false, IsChecked = encodeToMp3, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var label_ = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.ExportEncodeMp3, Margin = new Thickness(8, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var panel__ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; panel__.Children.Add(label_); panel__.Children.Add(checkBox); var panel_ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Vertical, HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; panel_.Children.Add(combo); panel_.Children.Add(panel__); var windowPopup_ = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Urakawa_Lang.ExportSettings), panel_, PopupModalWindow.DialogButtonsSet.OkCancel, PopupModalWindow.DialogButton.Ok, false, 300, 180, null, 40, m_DescriptionPopupModalWindow); windowPopup_.EnableEnterKeyDefault = true; windowPopup_.ShowModal(); if (!PopupModalWindow.IsButtonOkYesApply(windowPopup_.ClickedDialogButton)) { return; } encodeToMp3 = checkBox.IsChecked.Value; Urakawa.Settings.Default.AudioExportEncodeToMp3 = checkBox.IsChecked.Value; if (combo.SelectedItem == item1) { sampleRate = SampleRate.Hz11025; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item2) { sampleRate = SampleRate.Hz22050; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } else if (combo.SelectedItem == item3) { sampleRate = SampleRate.Hz44100; Urakawa.Settings.Default.AudioExportSampleRate = sampleRate; } string rootFolder = Path.GetDirectoryName(m_Session.DocumentFilePath); var dlg = new FolderBrowserDialog { RootFolder = Environment.SpecialFolder.MyComputer, SelectedPath = rootFolder, ShowNewFolderButton = true, Description = @"Tobi: " + UserInterfaceStrings.EscapeMnemonic("Export DIAGRAM XML") }; DialogResult result = DialogResult.Abort; m_ShellView.DimBackgroundWhile(() => { result = dlg.ShowDialog(); }); if (result != DialogResult.OK && result != DialogResult.Yes) { return; } if (!Directory.Exists(dlg.SelectedPath)) { return; } ManagedImageMedia managedImage = (ManagedImageMedia)node.GetImageMedia(); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string imageDescriptionDirectoryPath = Daisy3_Export.GetAndCreateImageDescriptionDirectoryPath(false, exportImageName, dlg.SelectedPath); if (Directory.Exists(imageDescriptionDirectoryPath)) { if (!m_Session.askUserConfirmOverwriteFileFolder(imageDescriptionDirectoryPath, true, m_DescriptionPopupModalWindow)) { return; } FileDataProvider.TryDeleteDirectory(imageDescriptionDirectoryPath, true); } FileDataProvider.CreateDirectory(imageDescriptionDirectoryPath); PCMFormatInfo audioFormat = node.Presentation.MediaDataManager.DefaultPCMFormat; AudioLibPCMFormat pcmFormat = audioFormat.Data; if ((ushort)sampleRate != pcmFormat.SampleRate) { pcmFormat.SampleRate = (ushort)sampleRate; } Application.Current.MainWindow.Cursor = Cursors.Wait; this.Cursor = Cursors.Wait; //m_ShellView try { string descriptionFile = Daisy3_Export.CreateImageDescription( Urakawa.Settings.Default.AudioCodecDisableACM, pcmFormat, encodeToMp3, 0, imageDescriptionDirectoryPath, exportImageName, node.GetAlternateContentProperty(), null, null, null); } finally { Application.Current.MainWindow.Cursor = Cursors.Arrow; this.Cursor = Cursors.Arrow; //m_ShellView } m_ShellView.ExecuteShellProcess(imageDescriptionDirectoryPath); }
public Dictionary <string, string> readTTSVoicesMapping(out string text) { text = ""; Dictionary <string, string> ttsVoiceMap = new Dictionary <string, string>(); string prefix_VOICE = "[TTS_VOICE]"; List <VoiceInfo> voices = TTSVoices; if (!File.Exists(TTS_VOICE_MAPPING_FILE)) { if (!Directory.Exists(TTS_VOICE_MAPPING_DIRECTORY)) { FileDataProvider.CreateDirectory(TTS_VOICE_MAPPING_DIRECTORY); } StreamWriter streamWriter = new StreamWriter(TTS_VOICE_MAPPING_FILE, false, Encoding.UTF8); try { string line = null; foreach (VoiceInfo voice in voices) { line = prefix_VOICE + " " + voice.Name; streamWriter.WriteLine(line); text += (line + '\n'); line = "element_name_1"; streamWriter.WriteLine(line); text += (line + '\n'); line = "element_name_2"; streamWriter.WriteLine(line); text += (line + '\n'); line = "etc."; streamWriter.WriteLine(line); text += (line + '\n'); streamWriter.WriteLine(""); text += ("" + '\n'); //// useless for now, could be used when ttsVoiceMap is hard-coded here? //foreach (String key in ttsVoiceMap.Keys) //{ // string name = ttsVoiceMap[key]; // if (name.Equals(voice.Name, StringComparison.Ordinal)) // { // streamWriter.WriteLine(key); // } //} } } finally { streamWriter.Close(); } } else { List <string> voicesPresent = new List <string>(); string line = null; StreamReader streamReader = new StreamReader(TTS_VOICE_MAPPING_FILE, Encoding.UTF8); try { string currentVoice = null; while ((line = streamReader.ReadLine()) != null) { text += (line + '\n'); line = line.Trim(); if (string.IsNullOrEmpty(line)) { continue; } if (line.StartsWith(prefix_VOICE)) { currentVoice = line.Substring(prefix_VOICE.Length).Trim(); if (!voicesPresent.Contains(currentVoice)) { voicesPresent.Add(currentVoice); } if (!string.IsNullOrEmpty(currentVoice)) { bool found = false; foreach (VoiceInfo voice in voices) { if (currentVoice.Equals(voice.Name, StringComparison.Ordinal)) { found = true; break; } } if (!found) { currentVoice = null; } } } else if (!string.IsNullOrEmpty(currentVoice)) { if (ttsVoiceMap.ContainsKey(line)) { ttsVoiceMap.Remove(line); } ttsVoiceMap.Add(line, currentVoice); } } } finally { streamReader.Close(); } foreach (VoiceInfo voice in voices) { if (voicesPresent.Contains(voice.Name)) { continue; } text += ("" + '\n'); line = prefix_VOICE + " " + voice.Name; text += (line + '\n'); line = "element_name_1"; text += (line + '\n'); line = "element_name_2"; text += (line + '\n'); line = "etc."; text += (line + '\n'); text += ("" + '\n'); } } return(ttsVoiceMap); }
public List <Tuple <string, string> > readMetadataImport(out string text) { text = ""; List <Tuple <string, string> > metadatas = new List <Tuple <string, string> >(); if (!File.Exists(METADATA_IMPORT_FILE)) { if (!Directory.Exists(METADATA_IMPORT_DIRECTORY)) { FileDataProvider.CreateDirectory(METADATA_IMPORT_DIRECTORY); } StreamWriter streamWriter = new StreamWriter(METADATA_IMPORT_FILE, false, Encoding.UTF8); try { string line = "//"; streamWriter.WriteLine(line); text += (line + '\n'); line = "// PLEASE EDIT THIS EXAMPLE (CHANGES WILL BE SAVED)"; streamWriter.WriteLine(line); text += (line + '\n'); line = "//"; streamWriter.WriteLine(line); text += (line + '\n'); line = "// Each metadata item is a [ key + value ] pair."; streamWriter.WriteLine(line); text += (line + '\n'); line = "// [key] on one line"; streamWriter.WriteLine(line); text += (line + '\n'); line = "// [value] on the next line"; streamWriter.WriteLine(line); text += (line + '\n'); line = "// (empty lines are ignored)"; streamWriter.WriteLine(line); text += (line + '\n'); line = "//"; streamWriter.WriteLine(line); text += (line + '\n'); line = ""; streamWriter.WriteLine(line); text += (line + '\n'); string key = "dc:Creator"; string value = "Firstname Surname"; metadatas.Add(new Tuple <string, string>(key, value)); streamWriter.WriteLine(key); text += (key + '\n'); streamWriter.WriteLine(value); text += (value + '\n'); streamWriter.WriteLine(""); text += ("" + '\n'); key = "dc:Title"; value = "The Title"; metadatas.Add(new Tuple <string, string>(key, value)); streamWriter.WriteLine(key); text += (key + '\n'); streamWriter.WriteLine(value); text += (value + '\n'); streamWriter.WriteLine(""); text += ("" + '\n'); key = "dc:Identifier"; value = "UUID"; metadatas.Add(new Tuple <string, string>(key, value)); streamWriter.WriteLine(key); text += (key + '\n'); streamWriter.WriteLine(value); text += (value + '\n'); streamWriter.WriteLine(""); text += ("" + '\n'); } finally { streamWriter.Close(); } } else { StreamReader streamReader = new StreamReader(METADATA_IMPORT_FILE, Encoding.UTF8); try { string key = null; string value = null; string line; while ((line = streamReader.ReadLine()) != null) { text += (line + '\n'); line = line.Trim(); if (string.IsNullOrEmpty(line)) { continue; } if (line.StartsWith("//")) { continue; } if (string.IsNullOrEmpty(key)) { key = line; } else { value = line; metadatas.Add(new Tuple <string, string>(key, value)); key = null; value = null; } } } finally { streamReader.Close(); } } return(metadatas); }