public static string GetXukFilePath_SpineItem(string outputDirectory, string relativeFilePath, string title, int index) { relativeFilePath = FileDataProvider.EliminateForbiddenFileNameCharacters(relativeFilePath); string extension = Path.GetExtension(relativeFilePath); string croppedFileName = Path.GetFileNameWithoutExtension(relativeFilePath); if (croppedFileName.Length > 12) { croppedFileName = croppedFileName.Substring(0, 12); } croppedFileName = croppedFileName + extension; if (index >= 0) { croppedFileName = "_" + index + "_" + croppedFileName; } string xukFileName = croppedFileName.Replace('.', '_') + (!string.IsNullOrEmpty(title) ? "-" //"[" + CleanupTitle(title, 12) //+ "]" : "") + OpenXukAction.XUK_EXTENSION; #if DEBUG DebugFix.Assert(xukFileName.Length <= (1 + 12 + 6 + 1 + 12 + 4)); DebugFix.Assert(outputDirectory.Length + xukFileName.Length <= 250); #endif return(Path.Combine(outputDirectory, xukFileName)); }
public static XmlDocument CreateStub_DTBDocument(string language, string strInternalDTD, List <ExternalFileData> list_ExternalStyleSheets) { XmlDocument DTBDocument = new XmlDocument(); DTBDocument.XmlResolver = null; DTBDocument.CreateXmlDeclaration("1.0", "utf-8", null); if (list_ExternalStyleSheets != null) { foreach (ExternalFileData efd in list_ExternalStyleSheets) { string adjustedFilePath = FileDataProvider.EliminateForbiddenFileNameCharacters(efd.OriginalRelativePath); if (efd is CSSExternalFileData) { DTBDocument.AppendChild( DTBDocument.CreateProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"" + adjustedFilePath + "\"")); } else if (efd is XSLTExternalFileData && !efd.OriginalRelativePath.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA)) { DTBDocument.AppendChild( DTBDocument.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + adjustedFilePath + "\"")); } } } DTBDocument.AppendChild(DTBDocument.CreateDocumentType("dtbook", "-//NISO//DTD dtbook 2005-3//EN", "http://www.daisy.org/z3986/2005/dtbook-2005-3.dtd", strInternalDTD)); XmlNode DTBNode = DTBDocument.CreateElement(null, "dtbook", "http://www.daisy.org/z3986/2005/dtbook/"); DTBDocument.AppendChild(DTBNode); CreateAppendXmlAttribute(DTBDocument, DTBNode, "version", "2005-3"); CreateAppendXmlAttribute(DTBDocument, DTBNode, XmlReaderWriterHelper.XmlLang, (String.IsNullOrEmpty(language) ? "en-US" : language)); XmlNode headNode = DTBDocument.CreateElement(null, "head", DTBNode.NamespaceURI); DTBNode.AppendChild(headNode); XmlNode bookNode = DTBDocument.CreateElement(null, "book", DTBNode.NamespaceURI); DTBNode.AppendChild(bookNode); return(DTBDocument); }
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 XmlDocument CreateStub_XHTMLDocument(string language, List <ExternalFileData> list_ExternalStyleSheets) { XmlDocument xhtmlDocument = new XmlDocument(); xhtmlDocument.XmlResolver = null; xhtmlDocument.CreateXmlDeclaration("1.0", "utf-8", null); if (list_ExternalStyleSheets != null) { foreach (ExternalFileData efd in list_ExternalStyleSheets) { string adjustedFilePath = FileDataProvider.EliminateForbiddenFileNameCharacters(efd.OriginalRelativePath); if (efd is CSSExternalFileData) { xhtmlDocument.AppendChild( xhtmlDocument.CreateProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"" + adjustedFilePath + "\"")); } else if (efd is XSLTExternalFileData && !efd.OriginalRelativePath.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA)) { xhtmlDocument.AppendChild( xhtmlDocument.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + adjustedFilePath + "\"")); } } } XmlNode rootNode = xhtmlDocument.CreateElement(null, "html", DiagramContentModelHelper.NS_URL_XHTML); xhtmlDocument.AppendChild(rootNode); CreateAppendXmlAttribute(xhtmlDocument, rootNode, XmlReaderWriterHelper.XmlLang, (String.IsNullOrEmpty(language) ? "en-US" : language)); XmlNode headNode = xhtmlDocument.CreateElement(null, "head", rootNode.NamespaceURI); rootNode.AppendChild(headNode); XmlNode bookNode = xhtmlDocument.CreateElement(null, "book", rootNode.NamespaceURI); rootNode.AppendChild(bookNode); return(xhtmlDocument); }
public static void Backup(string path) { try { if (File.Exists(path)) { string parentdir = Path.GetDirectoryName(path); string fileName = Path.GetFileName(path); string pathBackup = path; do { //pathBackup = Path.ChangeExtension(Path.GetRandomFileName(), ".BAK"); string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd_HH:mm:ss_K", CultureInfo.InvariantCulture); timeStamp = FileDataProvider.EliminateForbiddenFileNameCharacters(timeStamp).Replace(' ', '_'); pathBackup = Path.Combine(parentdir, fileName + "_" + timeStamp); } while (File.Exists(pathBackup)); File.Copy(path, pathBackup); try { File.SetAttributes(pathBackup, FileAttributes.Normal); } catch { } } } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }
protected virtual void CreateExternalFiles() { foreach (ExternalFiles.ExternalFileData efd in m_Presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { reportProgress(-1, UrakawaSDK_daisy_Lang.CreatingExternalFiles); string filename = efd.OriginalRelativePath; if (filename.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA)) { filename = filename.Substring(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA.Length); } filename = FileDataProvider.EliminateForbiddenFileNameCharacters(filename); if (efd.IsPreservedForOutputFile && !m_FilesList_ExternalFiles.Contains(filename)) { string filePath = Path.Combine(m_OutputDirectory, filename); efd.DataProvider.ExportDataStreamToFile(filePath, true); m_FilesList_ExternalFiles.Add(filename); } } }
public static string CleanupTitle(string title, int maxLength) { string cleaned = title.Replace('.', ' ') .Replace(':', ' ') .Replace('—', ' ') .Replace('\'', ' ') .Replace('"', ' ') //.Replace('/', ' ') .Replace('\\', ' ') .Replace('!', ' ') .Replace('?', ' '); cleaned = Regex.Replace(cleaned, @"\s+", " "); cleaned = cleaned.Trim(); if (cleaned.IndexOf(' ') > 0) { string[] split = cleaned.Split(' '); cleaned = ""; foreach (string s in split) { char c = char.ToUpper(s[0]); string ss = c + (s.Length > 1 ? s.ToLower().Substring(1) : ""); cleaned += ss; } } cleaned = FileDataProvider.EliminateForbiddenFileNameCharacters(cleaned); if (cleaned.Length > maxLength) { cleaned = cleaned.Substring(0, maxLength); } return(cleaned); }
protected virtual void parseContentDocuments(List <string> spineOfContentDocuments, Dictionary <string, string> spineAttributes, List <Dictionary <string, string> > spineItemsAttributes, string coverImagePath, string navDocPath) { if (spineOfContentDocuments == null || spineOfContentDocuments.Count <= 0) { return; } Presentation spinePresentation = m_Project.Presentations.Get(0); spinePresentation.RootNode.GetOrCreateXmlProperty().SetQName("spine", ""); if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath)) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(OPF_ContainerRelativePath, "", m_OPF_ContainerRelativePath); } foreach (KeyValuePair <string, string> spineAttribute in spineAttributes) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(spineAttribute.Key, "", spineAttribute.Value); } if (m_PackagePrefixAttr != null) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute("prefix", "", m_PackagePrefixAttr.Value); } // Audio files may be shared between chapters of a book! m_OriginalAudioFile_FileDataProviderMap.Clear(); Presentation spineItemPresentation = null; int index = -1; foreach (string docPath in spineOfContentDocuments) { index++; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath)); //DirectoryInfo opfParentDir = Directory.GetParent(m_Book_FilePath); //string dirPath = opfParentDir.ToString(); string fullDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), docPath); fullDocPath = FileDataProvider.NormaliseFullFilePath(fullDocPath).Replace('/', '\\'); if (!File.Exists(fullDocPath)) { #if DEBUG Debugger.Break(); #endif //DEBUG continue; } addOPF_GlobalAssetPath(fullDocPath); TreeNode spineChild = spinePresentation.TreeNodeFactory.Create(); TextMedia txt = spinePresentation.MediaFactory.CreateTextMedia(); txt.Text = docPath; // Path.GetFileName(fullDocPath); spineChild.GetOrCreateChannelsProperty().SetMedia(spinePresentation.ChannelsManager.GetOrCreateTextChannel(), txt); spinePresentation.RootNode.AppendChild(spineChild); spineChild.GetOrCreateXmlProperty().SetQName("metadata", ""); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { spineChild.GetOrCreateXmlProperty().SetAttribute(spineItemAttribute.Key, "", spineItemAttribute.Value); } string ext = Path.GetExtension(fullDocPath); if (docPath == coverImagePath) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("cover-image", "", "true"); } if (docPath == navDocPath) { DebugFix.Assert( ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("nav", "", "true"); } if ( !ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.DTBOOK_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase) ) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); bool notExistYet = true; foreach (ExternalFiles.ExternalFileData externalFileData in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(externalFileData.OriginalRelativePath)) { bool notExist = docPath != externalFileData.OriginalRelativePath; notExistYet = notExistYet && notExist; if (!notExist) { break; } } } DebugFix.Assert(notExistYet); if (notExistYet) { ExternalFiles.ExternalFileData externalData = null; if (docPath == coverImagePath) { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>(); } else { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); } if (externalData != null) { externalData.InitializeWithData(fullDocPath, docPath, true, null); addOPF_GlobalAssetPath(fullDocPath); } } continue; } spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true"); XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDocPath, true, true); if (RequestCancellation) { return; } m_PublicationUniqueIdentifier = null; m_PublicationUniqueIdentifierNode = null; Project spineItemProject = new Project(); spineItemProject.PrettyFormat = m_XukPrettyFormat; string dataFolderPrefix = FileDataProvider.EliminateForbiddenFileNameCharacters(docPath); spineItemPresentation = spineItemProject.AddNewPresentation(new Uri(m_outDirectory), //Path.GetFileName(fullDocPath) dataFolderPrefix ); PCMFormatInfo pcmFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; spineItemPresentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataManager.EnforceSinglePCMFormat = true; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); TextChannel textChannel = spineItemPresentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == spineItemPresentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = spineItemPresentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == spineItemPresentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = spineItemPresentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == spineItemPresentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = spineItemPresentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == spineItemPresentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ //AudioLibPCMFormat previousPcm = null; if (m_AudioConversionSession != null) { //previousPcm = m_AudioConversionSession.FirstDiscoveredPCMFormat; RemoveSubCancellable(m_AudioConversionSession); m_AudioConversionSession = null; } m_AudioConversionSession = new AudioFormatConvertorSession( //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY, spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath, spineItemPresentation.MediaDataManager.DefaultPCMFormat, m_autoDetectPcmFormat, m_SkipACM); //if (previousPcm != null) //{ // m_AudioConversionSession.FirstDiscoveredPCMFormat = previousPcm; //} AddSubCancellable(m_AudioConversionSession); TreenodesWithoutManagedAudioMediaData = new List <TreeNode>(); //foreach (var key in m_OriginalAudioFile_FileDataProviderMap.Keys) //{ // FileDataProvider dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //VERSUS// // FileDataProvider dataProv = new FileDataProvider(); // dataProv.MimeType = DataProviderFactory.AUDIO_WAV_MIME_TYPE; //} //m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable if (RequestCancellation) { return; } if (parseContentDocParts(fullDocPath, spineItemProject, xmlDoc, docPath, DocumentMarkupType.NA)) { return; // user cancel } //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, docPath)); //parseMetadata(fullDocPath, project, xmlDoc); //if (RequestCancellation) return; //ParseHeadLinks(fullDocPath, project, xmlDoc); //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, docPath)); //parseContentDocument(fullDocPath, project, xmlDoc, null, fullDocPath, null, DocumentMarkupType.NA); string title = GetTitle(spineItemPresentation); if (!string.IsNullOrEmpty(title)) { spineChild.GetOrCreateXmlProperty().SetAttribute("title", "", title); } if (false) // do not copy metadata from project to individual chapter { foreach (Metadata metadata in m_Project.Presentations.Get(0).Metadatas.ContentsAs_Enumerable) { Metadata md = spineItemPresentation.MetadataFactory.CreateMetadata(); md.NameContentAttribute = metadata.NameContentAttribute.Copy(); foreach (MetadataAttribute metadataAttribute in metadata.OtherAttributes.ContentsAs_Enumerable) { MetadataAttribute mdAttr = metadataAttribute.Copy(); md.OtherAttributes.Insert(md.OtherAttributes.Count, mdAttr); } spineItemPresentation.Metadatas.Insert(spineItemPresentation.Metadatas.Count, md); } } //XmlNodeList listOfBodies = xmlDoc.GetElementsByTagName("body"); //if (listOfBodies.Count == 0) //{ // listOfBodies = xmlDoc.GetElementsByTagName("book"); //} //XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "body", null); //if (bodyElement == null) //{ // bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null); //} //if (bodyElement == null) //{ // continue; //} // TODO: return hierarchical outline where each node points to a XUK relative path, + XukAble.Uid (TreeNode are not corrupted during XukAbleManager.RegenerateUids(); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { if (spineItemAttribute.Key == "media-overlay") { string opfDirPath = Path.GetDirectoryName(m_Book_FilePath); string overlayPath = spineItemAttribute.Value; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMediaOverlay, overlayPath)); string fullOverlayPath = Path.Combine(opfDirPath, overlayPath); if (!File.Exists(fullOverlayPath)) { continue; } XmlDocument overlayXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullOverlayPath, false, false); IEnumerable <XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false); if (audioElements == null) { continue; } foreach (XmlNode audioNode in audioElements) { XmlAttributeCollection attrs = audioNode.Attributes; if (attrs == null) { continue; } XmlNode attrSrc = attrs.GetNamedItem("src"); if (attrSrc == null) { continue; } //XmlNode attrBegin = attrs.GetNamedItem("clipBegin"); //XmlNode attrEnd = attrs.GetNamedItem("clipEnd"); //string overlayDirPath = Path.GetDirectoryName(fullOverlayPath); //string fullAudioPath = Path.Combine(overlayDirPath, attrSrc.Value); //if (!File.Exists(fullAudioPath)) //{ // continue; //} //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullAudioPath))); TreeNode textTreeNode = null; XmlNodeList children = audioNode.ParentNode.ChildNodes; foreach (XmlNode child in children) { if (child == audioNode) { continue; } if (child.LocalName != "text") { continue; } XmlAttributeCollection textAttrs = child.Attributes; if (textAttrs == null) { continue; } XmlNode textSrc = textAttrs.GetNamedItem("src"); if (textSrc == null) { continue; } string urlDecoded = FileDataProvider.UriDecode(textSrc.Value); if (urlDecoded.IndexOf('#') > 0) { string[] srcParts = urlDecoded.Split('#'); if (srcParts.Length != 2) { continue; } string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), srcParts[0]); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } string txtId = srcParts[1]; textTreeNode = spineItemPresentation.RootNode.GetFirstDescendantWithXmlID(txtId); } else { string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), urlDecoded); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } textTreeNode = spineItemPresentation.RootNode; } } if (textTreeNode != null) { addAudio(textTreeNode, audioNode, false, fullOverlayPath); } } } } spinePresentation.MediaDataManager.DefaultPCMFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //copied! string xuk_FilePath = GetXukFilePath_SpineItem(m_outDirectory, docPath, title, index); string xukFileName = Path.GetFileName(xuk_FilePath); spineChild.GetOrCreateXmlProperty().SetAttribute("xukFileName", "", xukFileName); //deleteDataDirectoryIfEmpty(); string dataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(xuk_FilePath)); string newDataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; DebugFix.Assert(Directory.Exists(newDataFolderPath)); if (newDataFolderPath != dataFolderPath) { try { if (Directory.Exists(newDataFolderPath)) { FileDataProvider.TryDeleteDirectory(newDataFolderPath, false); } Directory.Move(dataFolderPath, newDataFolderPath); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(dataFolderPrefix); } } spineItemProject.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(spineItemProject, spineItemProject, new Uri(xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <ProgressEventArgs>( delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = -1; if (val != max) { percent = (int)((val / max) * 100); } reportProgress_Throttle(percent, val + "/" + max); //reportProgress(-1, action.LongDescription); if (RequestCancellation) { e.Cancel(); } } ); action.Finished += new EventHandler <FinishedEventArgs>( delegate(object sender, FinishedEventArgs e) { reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved); } ); action.Cancelled += new EventHandler <CancelledEventArgs>( delegate(object sender, CancelledEventArgs e) { reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving); } ); action.DoWork(); //if (first) //{ // Presentation presentation = m_Project.Presentations.Get(0); // XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); // xmlProp.LocalName = "book"; // presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI; // xmlProp.NamespaceUri = presentation.PropertyFactory.DefaultXmlNamespaceUri; // TreeNode treeNode = presentation.TreeNodeFactory.Create(); // treeNode.AddProperty(xmlProp); // presentation.RootNode = treeNode; // first = false; //} //foreach (XmlNode childOfBody in bodyElement.ChildNodes) //{ // parseContentDocument(childOfBody, m_Project.Presentations.Get(0).RootNode, fullDocPath); //} } }
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); }
static Daisy3_Import() { INTERNAL_DTD_NAME = FileDataProvider.EliminateForbiddenFileNameCharacters(INTERNAL_DTD_NAME); }
static SupportedMetadata_Z39862005() { MATHML_XSLT_METADATA = FileDataProvider.EliminateForbiddenFileNameCharacters(MATHML_XSLT_METADATA); m_IdentifierSynonyms = new List <string>(); m_IdentifierSynonyms.Add(DTB_UID); m_TitleSynonyms = new List <string>(); m_TitleSynonyms.Add(DTB_TITLE); m_UnrecognizedItem = new MetadataDefinition( "", MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_unrecognized, null); m_MetadataDefinitions = new List <MetadataDefinition>(); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Date, MetadataDataType.Date, MetadataOccurrence.Required, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcDate, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Title, MetadataDataType.String, MetadataOccurrence.Required, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcTitle, new List <string>(m_TitleSynonyms))); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Publisher, MetadataDataType.String, MetadataOccurrence.Required, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcPublisher, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Language, MetadataDataType.LanguageCode, MetadataOccurrence.Required, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcLanguage, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Identifier, MetadataDataType.String, MetadataOccurrence.Required, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcIdentifier, new List <string>(m_IdentifierSynonyms))); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Creator, MetadataDataType.String, MetadataOccurrence.Recommended, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcCreator, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Subject, MetadataDataType.String, MetadataOccurrence.Recommended, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcSubject, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Description, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcDescription, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Contributor, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcContributor, null)); m_MetadataDefinitions.Add(new MetadataDefinition( D_Source, MetadataDataType.String, MetadataOccurrence.Recommended, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcSource, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Relation, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcRelation, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Coverage, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcCoverage, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Rights, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dcRights, null)); //read-only: Tobi should fill them in for the user //things such as audio format might not be known until export m_MetadataDefinitions.Add(new MetadataDefinition( DC_Format, MetadataDataType.String, MetadataOccurrence.Required, true, true, UrakawaSDK_core_Lang.Metadata_desc_dcFormat, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DC_Type, MetadataDataType.String, MetadataOccurrence.Optional, true, true, UrakawaSDK_core_Lang.Metadata_desc_dcType, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_SOURCE_DATE, MetadataDataType.Date, MetadataOccurrence.Recommended, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbSourceDate, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_PRODUCED_DATE, MetadataDataType.Date, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbProducedDate, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_REVISION_DATE, MetadataDataType.Date, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbRevisionDate, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_SOURCE_EDITION, MetadataDataType.String, MetadataOccurrence.Recommended, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbSourceEdition, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_SOURCE_PUBLISHER, MetadataDataType.String, MetadataOccurrence.Recommended, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbSourcePublisher, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_SOURCE_RIGHTS, MetadataDataType.String, MetadataOccurrence.Recommended, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbSourceRights, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_SOURCE_TITLE, MetadataDataType.String, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbSourceTitle, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_NARRATOR, MetadataDataType.String, MetadataOccurrence.Recommended, false, true, UrakawaSDK_core_Lang.Metadata_desc_dtbNarrator, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_PRODUCER, MetadataDataType.String, MetadataOccurrence.Optional, false, true, UrakawaSDK_core_Lang.Metadata_desc_dtbProducer, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_REVISION_DESCRIPTION, MetadataDataType.String, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbRevisionDescription, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_REVISION, MetadataDataType.Number, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbRevision, null)); //from mathML m_MetadataDefinitions.Add(new MetadataDefinition( _z39_86_extension_version, MetadataDataType.Number, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_z3986ExtensionVersion, null)); m_MetadataDefinitions.Add(new MetadataDefinition( MATHML_XSLT_METADATA, MetadataDataType.FileUri, MetadataOccurrence.Optional, false, false, UrakawaSDK_core_Lang.Metadata_desc_dtbookXsltFallback, null)); //audioOnly, audioNCX, audioPartText, audioFullText, textPartAudio, textNCX m_MetadataDefinitions.Add(new MetadataDefinition( DTB_MULTIMEDIA_TYPE, MetadataDataType.String, MetadataOccurrence.Required, true, false, UrakawaSDK_core_Lang.Metadata_desc_dtbMultimediaType, null)); //audio, text, and image m_MetadataDefinitions.Add(new MetadataDefinition( DTB_MULTIMEDIA_CONTENT, MetadataDataType.String, MetadataOccurrence.Required, true, false, UrakawaSDK_core_Lang.Metadata_desc_dtbMultimediaContent, null)); m_MetadataDefinitions.Add(new MetadataDefinition( DTB_TOTAL_TIME, MetadataDataType.ClockValue, MetadataOccurrence.Required, true, false, UrakawaSDK_core_Lang.Metadata_desc_dtbTotalTime, null)); //MP4-AAC, MP3, WAV m_MetadataDefinitions.Add(new MetadataDefinition( DTB_AUDIO_FORMAT, MetadataDataType.String, MetadataOccurrence.Recommended, true, true, UrakawaSDK_core_Lang.Metadata_desc_dtbAudioFormat, null)); DefinitionSet = new MetadataDefinitionSet(); DefinitionSet.UnrecognizedItemFallbackDefinition = m_UnrecognizedItem; DefinitionSet.Definitions = m_MetadataDefinitions; }
protected virtual void CreateDTBookDocument() { // check if there is preserved internal DTD //string[] dtbFilesList = Directory.GetFiles(m_Presentation.DataProviderManager.DataFileDirectoryFullPath, daisy.import.Daisy3_Import.INTERNAL_DTD_NAME, SearchOption.AllDirectories); //string strInternalDTD = null; //if (dtbFilesList.Length > 0) //{ // strInternalDTD = File.ReadAllText(dtbFilesList[0]); // if (strInternalDTD.Trim() == "") strInternalDTD = null; //} List <ExternalFileData> list_ExternalStyleSheets = new List <ExternalFileData>(); string strInternalDTD = null; foreach (ExternalFiles.ExternalFileData efd in m_Presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (RequestCancellation) { return; } if (efd is ExternalFiles.DTDExternalFileData && efd.OriginalRelativePath == daisy.import.Daisy3_Import.INTERNAL_DTD_NAME && !efd.IsPreservedForOutputFile && string.IsNullOrEmpty(strInternalDTD)) { StreamReader sr = new StreamReader(efd.OpenInputStream(), Encoding.UTF8); strInternalDTD = sr.ReadToEnd(); } else if (efd is ExternalFiles.CSSExternalFileData || efd is XSLTExternalFileData //&& !efd.OriginalRelativePath.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA) ) { list_ExternalStyleSheets.Add(efd); } } if (RequestCancellation) { return; } //m_ProgressPercentage = 0; reportProgress(-1, UrakawaSDK_daisy_Lang.CreatingXMLFile); XmlDocument DTBookDocument = XmlDocumentHelper.CreateStub_DTBDocument(m_Presentation.Language, strInternalDTD, list_ExternalStyleSheets); string mathML_XSLT = null; foreach (ExternalFileData efd in list_ExternalStyleSheets) { string filename = efd.OriginalRelativePath; if (filename.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA)) { filename = filename.Substring(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA.Length); mathML_XSLT = filename; } filename = FileDataProvider.EliminateForbiddenFileNameCharacters(filename); if (efd.IsPreservedForOutputFile && !m_FilesList_ExternalFiles.Contains(filename)) { string filePath = Path.Combine(m_OutputDirectory, filename); efd.DataProvider.ExportDataStreamToFile(filePath, true); m_FilesList_ExternalFiles.Add(filename); } } string mathPrefix = m_Presentation.RootNode.GetXmlNamespacePrefix(DiagramContentModelHelper.NS_URL_MATHML); if (!string.IsNullOrEmpty(mathPrefix) && string.IsNullOrEmpty(mathML_XSLT)) { string appDir = System.AppDomain.CurrentDomain.BaseDirectory; string xsltFileName = FileDataProvider.EliminateForbiddenFileNameCharacters(SupportedMetadata_Z39862005._builtInMathMLXSLT); string xsltFullPath = Path.Combine(appDir, xsltFileName); if (File.Exists(xsltFullPath)) { string destFile = Path.Combine(m_OutputDirectory, xsltFileName); File.Copy(xsltFullPath, destFile, true); try { File.SetAttributes(destFile, FileAttributes.Normal); } catch { } m_FilesList_ExternalFiles.Add(xsltFileName); } } m_ListOfLevels = new List <TreeNode>(); Dictionary <string, string> old_New_IDMap = new Dictionary <string, string>(); List <XmlAttribute> referencingAttributesList = new List <XmlAttribute>(); // add metadata XmlNode headNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "head", null); //DTBookDocument.GetElementsByTagName("head")[0] Metadata mdId = AddMetadata_DtbUid(false, DTBookDocument, headNode); AddMetadata_Generator(DTBookDocument, headNode); bool hasMathML_z39_86_extension_version = false; bool hasMathML_DTBook_XSLTFallback = false; // todo: filter-out unecessary metadata for DTBOOK (e.g. dtb:multimediatype) foreach (Metadata m in m_Presentation.Metadatas.ContentsAs_Enumerable) { if (mdId == m) { continue; } XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); string name = m.NameContentAttribute.Name; if (name == SupportedMetadata_Z39862005._z39_86_extension_version) { hasMathML_z39_86_extension_version = true; } else if (name == SupportedMetadata_Z39862005.MATHML_XSLT_METADATA) { hasMathML_DTBook_XSLTFallback = true; } string prefix; string localName; urakawa.property.xml.XmlProperty.SplitLocalName(name, out prefix, out localName); if (!string.IsNullOrEmpty(prefix)) { // split the metadata name and make first alphabet upper, required for daisy 3.0 localName = localName.Substring(0, 1).ToUpper() + localName.Remove(0, 1); name = prefix + ":" + localName; } XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", name); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", m.NameContentAttribute.Value); // add metadata optional attributes if any foreach (MetadataAttribute ma in m.OtherAttributes.ContentsAs_Enumerable) { if (ma.Name == "id" || ma.Name == Metadata.PrimaryIdentifierMark) { continue; } XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, ma.Name, ma.Value); } } if (!string.IsNullOrEmpty(mathML_XSLT)) { DebugFix.Assert(hasMathML_z39_86_extension_version); DebugFix.Assert(hasMathML_DTBook_XSLTFallback); } if (!string.IsNullOrEmpty(mathPrefix) && !hasMathML_z39_86_extension_version) { XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", SupportedMetadata_Z39862005._z39_86_extension_version); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", "1.0"); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "scheme", DiagramContentModelHelper.NS_URL_MATHML); } if (!string.IsNullOrEmpty(mathPrefix) && !hasMathML_DTBook_XSLTFallback) { XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", SupportedMetadata_Z39862005.MATHML_XSLT_METADATA); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", string.IsNullOrEmpty(mathML_XSLT) ? SupportedMetadata_Z39862005._builtInMathMLXSLT : mathML_XSLT); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "scheme", DiagramContentModelHelper.NS_URL_MATHML); } // add elements to book body m_TreeNode_XmlNodeMap = new Dictionary <TreeNode, XmlNode>(); XmlNode bookNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "book", null); //DTBookDocument.GetElementsByTagName("book")[0]; if (bookNode == null) { bookNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "body", null); } XmlNode docRootNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "dtbook", null); if (docRootNode == null) { docRootNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "html", null); } if (false && !string.IsNullOrEmpty(mathML_XSLT)) // namespace prefix attribute automatically added for each m:math element because of MathML DTD { XmlDocumentHelper.CreateAppendXmlAttribute( DTBookDocument, bookNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + "dtbook", bookNode.NamespaceURI, XmlReaderWriterHelper.NS_URL_XMLNS ); } m_ListOfLevels.Add(m_Presentation.RootNode); m_TreeNode_XmlNodeMap.Add(m_Presentation.RootNode, bookNode); XmlNode currentXmlNode = null; bool isHeadingNodeAvailable = true; m_Presentation.RootNode.AcceptDepthFirst( delegate(TreeNode n) { if (RequestCancellation) { return(false); } // add to list of levels if xml property has level string //QualifiedName qName = n.GetXmlElementQName(); //if (qName != null && // (qName.LocalName.StartsWith("level") || qName.LocalName == "doctitle" || qName.LocalName == "docauthor")) //{ // m_ListOfLevels.Add(n); //} if (doesTreeNodeTriggerNewSmil(n)) { if (!isHeadingNodeAvailable && m_ListOfLevels.Count > 1) { m_ListOfLevels.RemoveAt(m_ListOfLevels.Count - 1); //System.Windows.Forms.MessageBox.Show ( "removing :" + m_ListOfLevels.Count.ToString () ); } m_ListOfLevels.Add(n); isHeadingNodeAvailable = false; reportProgress(-1, UrakawaSDK_daisy_Lang.CreatingXMLFile); } if (IsHeadingNode(n)) { isHeadingNodeAvailable = true; } if (n.HasXmlProperty && (n.GetXmlElementLocalName() == "note" || n.GetXmlElementLocalName() == "annotation")) { m_NotesNodeList.Add(n); } property.xml.XmlProperty xmlProp = n.GetXmlProperty(); if (xmlProp == null) { string txtx = n.GetTextMedia() != null ? n.GetTextMedia().Text : null; if (txtx != null) { XmlNode textNode = DTBookDocument.CreateTextNode(txtx); ExternalAudioMedia extAudio = GetExternalAudioMedia(n); if (extAudio == null) { m_TreeNode_XmlNodeMap[n.Parent].AppendChild(textNode); m_TreeNode_XmlNodeMap.Add(n, textNode); } else { Debug.Fail("TreeNode without XmlProperty but with TextMedia cannot have Audio attached to it ! (reason: at authoring time, an XmlProperty should have been added when audio was recorded for the pure-text TreeNode) => " + txtx); //XmlNode textParent = DTBookDocument.CreateElement(null, "sent", bookNode.NamespaceURI); //textParent.AppendChild(textNode); //m_TreeNode_XmlNodeMap[n.Parent].AppendChild(textParent); //m_TreeNode_XmlNodeMap.Add(n, textParent); } } return(true); } // create sml node in dtbook document // code removed because XmlProperty stores proper namespaces, useful for inline MathML, SVG, whatever... //string name = xmlProp.LocalName; //string prefix = name.Contains(":") ? name.Split(':')[0] : null; //string elementName = name.Contains(":") ? name.Split(':')[1] : name; //currentXmlNode = DTBookDocument.CreateElement(prefix, elementName, bookNode.NamespaceURI); bool notBookRoot = !"book".Equals(xmlProp.LocalName, StringComparison.OrdinalIgnoreCase) && !"body".Equals(xmlProp.LocalName, StringComparison.OrdinalIgnoreCase); bool forceXmlNamespacePrefix = false; if ( //xmlProp.LocalName.Equals("math", StringComparison.OrdinalIgnoreCase) xmlProp.GetNamespaceUri() == DiagramContentModelHelper.NS_URL_MATHML && bookNode.LocalName.Equals("book", StringComparison.OrdinalIgnoreCase) ) { // Hack, because some MathML in DAISY is produced // with redundant (and DTD-invalid) xmlns="http://MATHML" forceXmlNamespacePrefix = true; } if (!notBookRoot) { currentXmlNode = bookNode; } else { XmlNode xmlNodeParent = m_TreeNode_XmlNodeMap[n.Parent]; string nsUri = n.GetXmlNamespaceUri(); if (string.IsNullOrEmpty(nsUri)) { nsUri = xmlNodeParent.NamespaceURI; } DebugFix.Assert(!string.IsNullOrEmpty(nsUri)); if (string.IsNullOrEmpty(nsUri)) { nsUri = bookNode.NamespaceURI; } if (string.IsNullOrEmpty(nsUri)) { nsUri = DTBookDocument.DocumentElement.NamespaceURI; } if (string.IsNullOrEmpty(nsUri)) { nsUri = DTBookDocument.NamespaceURI; } string prefix = (forceXmlNamespacePrefix || n.NeedsXmlNamespacePrefix()) ? n.GetXmlNamespacePrefix(nsUri) : null; currentXmlNode = DTBookDocument.CreateElement( prefix, xmlProp.LocalName, nsUri); xmlNodeParent.AppendChild(currentXmlNode); m_TreeNode_XmlNodeMap.Add(n, currentXmlNode); } // add attributes for (int i = 0; i < xmlProp.Attributes.Count; i++) { property.xml.XmlAttribute xmlAttr = xmlProp.Attributes.Get(i); string prefix = xmlAttr.Prefix; string nameWithoutPrefix = xmlAttr.PrefixedLocalName != null ? xmlAttr.PrefixedLocalName : xmlAttr.LocalName; if (!string.IsNullOrEmpty(prefix)) { string nsUriPrefix = xmlProp.GetNamespaceUri(prefix); if (string.IsNullOrEmpty(nsUriPrefix)) { #if DEBUG Debugger.Break(); #endif //DEBUG nsUriPrefix = currentXmlNode.GetNamespaceOfPrefix(prefix); } if (!string.IsNullOrEmpty(nsUriPrefix) && string.IsNullOrEmpty(DTBookDocument.DocumentElement.GetNamespaceOfPrefix(prefix)) && string.IsNullOrEmpty(bookNode.GetNamespaceOfPrefix(prefix))) { XmlDocumentHelper.CreateAppendXmlAttribute( DTBookDocument, docRootNode, //bookNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + prefix, nsUriPrefix, XmlReaderWriterHelper.NS_URL_XMLNS ); } } //todo: check ID attribute, normalize with fresh new list of IDs // (warning: be careful maintaining ID REFS, such as idref attributes for annotation/annoref and prodnote/noteref // (be careful because idref contain URIs with hash character), // and also the special imgref and headers attributes which contain space-separated list of IDs, not URIs) if (nameWithoutPrefix == "id") // xmlAttr.LocalName == "id" || xmlAttr.LocalName == XmlReaderWriterHelper.XmlId) { string id_New = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "id", id_New); if (!old_New_IDMap.ContainsKey(xmlAttr.Value)) { old_New_IDMap.Add(xmlAttr.Value, id_New); } else { System.Diagnostics.Debug.Fail("Duplicate ID found in original DTBook document", "Original DTBook document has duplicate ID: " + xmlProp.Attributes.Get(i).Value); } } else { XmlNode xmlNd = null; if (currentXmlNode == bookNode && (prefix == XmlReaderWriterHelper.NS_PREFIX_XMLNS || nameWithoutPrefix == "lang")) { // Hack: to make sure DTD validation passes. xmlNd = docRootNode; } else { xmlNd = currentXmlNode; } if (forceXmlNamespacePrefix && nameWithoutPrefix == XmlReaderWriterHelper.NS_PREFIX_XMLNS && xmlAttr.Value == DiagramContentModelHelper.NS_URL_MATHML ) { bool debug = true; // skip xmlns="http://MATH" } else { XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, xmlNd, xmlAttr.LocalName, xmlAttr.Value, xmlAttr.GetNamespaceUri()); } } } // for loop ends if (!notBookRoot) { return(true); } if (xmlProp.LocalName == "imggroup") { m_TempImageId = new List <string>(1); } if (m_TempImageId != null && // !string.IsNullOrEmpty(m_TempImageId) (xmlProp.LocalName == "caption" || xmlProp.LocalName == "prodnote")) { string imgIds = ""; foreach (string imgId in m_TempImageId) { imgIds += imgId + " "; } imgIds = imgIds.Trim(); if (!string.IsNullOrEmpty(imgIds)) { XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "imgref", imgIds); } } XmlAttributeCollection currentXmlNodeAttrs = currentXmlNode.Attributes; // add id attribute in case it do not exists and it is required if (IsIDRequired(currentXmlNode.LocalName) && currentXmlNodeAttrs != null) { XmlNode idAttr = currentXmlNodeAttrs.GetNamedItem("id"); if (idAttr == null) { string id = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "id", id); } else if (xmlProp.LocalName != null && xmlProp.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase) && m_TempImageId != null) { string id = idAttr.Value; m_TempImageId.Add(id); } } // add text from text property string txt = n.GetTextMedia() != null ? n.GetTextMedia().Text : null; if (txt != null) { XmlNode textNode = DTBookDocument.CreateTextNode(txt); currentXmlNode.AppendChild(textNode); DebugFix.Assert(n.Children.Count == 0); } // if current xmlnode is referencing node, add its referencing attribute to referencingAttributesList AddReferencingNodeToReferencedAttributesList(currentXmlNode, referencingAttributesList); if (currentXmlNodeAttrs != null && currentXmlNode.LocalName != null) { bool isHTML = @"body".Equals(m_Presentation.RootNode.GetXmlElementLocalName(), StringComparison.OrdinalIgnoreCase); //n.Presentation // TODO: special treatment of subfolders in file paths (restore full hierarchy, including OPF, XHTMLs, etc., not just referenced media assets) if (currentXmlNode.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase)) { XmlAttribute imgSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); if (imgSrcAttribute != null && n.GetImageMedia() != null && n.GetImageMedia() is media.data.image.ManagedImageMedia) { media.data.image.ManagedImageMedia managedImage = (media.data.image.ManagedImageMedia)n.GetImageMedia(); //if (FileDataProvider.isHTTPFile(managedImage.ImageMediaData.OriginalRelativePath)) //exportImageName = Path.GetFileName(managedImage.ImageMediaData.OriginalRelativePath); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string destPath = Path.Combine(m_OutputDirectory, exportImageName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedImage.ImageMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } imgSrcAttribute.Value = FileDataProvider.UriEncode(exportImageName); if (!m_FilesList_Image.Contains(exportImageName)) { m_FilesList_Image.Add(exportImageName); } generateImageDescriptionInDTBook(n, currentXmlNode, exportImageName, DTBookDocument); } } else if (currentXmlNode.LocalName.Equals(DiagramContentModelHelper.Math, StringComparison.OrdinalIgnoreCase)) { XmlAttribute imgSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("altimg"); if (imgSrcAttribute != null && n.GetImageMedia() != null && n.GetImageMedia() is media.data.image.ManagedImageMedia) { media.data.image.ManagedImageMedia managedImage = (media.data.image.ManagedImageMedia)n.GetImageMedia(); //if (FileDataProvider.isHTTPFile(managedImage.ImageMediaData.OriginalRelativePath)) //exportImageName = Path.GetFileName(managedImage.ImageMediaData.OriginalRelativePath); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string destPath = Path.Combine(m_OutputDirectory, exportImageName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedImage.ImageMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } imgSrcAttribute.Value = FileDataProvider.UriEncode(exportImageName); if (!m_FilesList_Image.Contains(exportImageName)) { m_FilesList_Image.Add(exportImageName); } } } #if SUPPORT_AUDIO_VIDEO else if (currentXmlNode.LocalName.Equals("video", StringComparison.OrdinalIgnoreCase) || ( currentXmlNode.LocalName.Equals("source", StringComparison.OrdinalIgnoreCase) && currentXmlNode.ParentNode != null && currentXmlNode.ParentNode.LocalName.Equals("video", StringComparison.OrdinalIgnoreCase) ) ) { XmlAttribute videoSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); if (videoSrcAttribute != null && n.GetVideoMedia() != null && n.GetVideoMedia() is ManagedVideoMedia) { ManagedVideoMedia managedVideo = (ManagedVideoMedia)n.GetVideoMedia(); //if (FileDataProvider.isHTTPFile(managedVideo.VideoMediaData.OriginalRelativePath)) //exportVideoName = Path.GetFileName(managedVideo.VideoMediaData.OriginalRelativePath); string exportVideoName = FileDataProvider.EliminateForbiddenFileNameCharacters( managedVideo.VideoMediaData.OriginalRelativePath); string destPath = Path.Combine(m_OutputDirectory, exportVideoName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedVideo.VideoMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } videoSrcAttribute.Value = FileDataProvider.UriEncode(exportVideoName); if (!m_FilesList_Video.Contains(exportVideoName)) { m_FilesList_Video.Add(exportVideoName); } } } else if (currentXmlNode.LocalName.Equals("audio", StringComparison.OrdinalIgnoreCase) || ( currentXmlNode.LocalName.Equals("source", StringComparison.OrdinalIgnoreCase) && currentXmlNode.ParentNode != null && currentXmlNode.ParentNode.LocalName.Equals("audio", StringComparison.OrdinalIgnoreCase) ) ) { XmlAttribute audioSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); ManagedAudioMedia managedAudio = n.GetManagedAudioMedia(); if (audioSrcAttribute != null && managedAudio != null) { //if (FileDataProvider.isHTTPFile(managedAudio.AudioMediaData.OriginalRelativePath)) //exportAudioName = Path.GetFileName(managedAudio.AudioMediaData.OriginalRelativePath); string exportAudioName = FileDataProvider.EliminateForbiddenFileNameCharacters( managedAudio.AudioMediaData.OriginalRelativePath); string destPath = Path.Combine(m_OutputDirectory, exportAudioName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedAudio.AudioMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } audioSrcAttribute.Value = FileDataProvider.UriEncode(exportAudioName); if (!m_FilesList_Audio.Contains(exportAudioName)) { m_FilesList_Audio.Add(exportAudioName); } } } #endif } return(true); }, delegate(urakawa.core.TreeNode n) { property.xml.XmlProperty xmlProp = n.GetXmlProperty(); //QualifiedName qName = n.GetXmlElementQName(); if (xmlProp != null && xmlProp.LocalName == "imggroup") { m_TempImageId = null; } }); if (RequestCancellation) { return; } // set references to new ids foreach (XmlAttribute attr in referencingAttributesList) { string strIDToFind = attr.Value; if (strIDToFind.IndexOf('#') >= 0) //strIDToFind.Contains("#") { strIDToFind = strIDToFind.Split('#')[1]; } string str; old_New_IDMap.TryGetValue(strIDToFind, out str); if (!string.IsNullOrEmpty(str)) //old_New_IDMap.ContainsKey(strIDToFind)) { string id_New = str; // old_New_IDMap[strIDToFind]; attr.Value = "#" + id_New; } } m_DTBDocument = DTBookDocument; //CommonFunctions.WriteXmlDocumentToFile(DTBookDocument, // Path.Combine(m_OutputDirectory, m_Filename_Content)); }
protected string AdjustAudioFileName(ExternalAudioMedia externalAudio, TreeNode levelNode) { //#if !TOBI // // Obi should not use this, as the above AddSectionNameToAudioFileName() is used instead!! // Debugger.Break(); // return externalAudio.Src; //#endif // Obi should return below! if (!IsAdjustAudioFileNameEnabled) { return(externalAudio.Src); } if (externalAudio.Tag == null || !(externalAudio.Tag is TreeNode)) { #if DEBUG Debugger.Break(); #endif return(externalAudio.Src); } TreeNode node = externalAudio.Tag as TreeNode; // In some cases this occurs (for example with Great Painters, // or when m_audioExportDTBOOKElementNameTriggers / doesTreeNodeTriggerNewSmil() is set to level2 but not level1 // The generated SMIL and audio file structure looks okay, but the heading/section title is missing in the filename // DebugFix.Assert(node == levelNode); #if DEBUG if (node != levelNode) { bool breakpointHere = true; } // Debugger.Break(); #endif string src = null; m_adjustedExternalAudioFileNames.TryGetValue(node, out src); if (!string.IsNullOrEmpty(src)) { #if DEBUG //DebugFix.Assert(!src.Equals(externalAudio.Src, StringComparison.Ordinal)); //if (src.Equals(externalAudio.Src, StringComparison.Ordinal)) //{ // Debugger.Break(); //} #endif externalAudio.Src = src; return(src); } string strTitle = ""; bool html5_outlining = node.Presentation.RootNode.GetXmlElementLocalName() .Equals("body", StringComparison.OrdinalIgnoreCase); if (html5_outlining) { #if DEBUG Debugger.Break(); #endif //TODO? //List<Section> sections = node.Presentation.RootNode.GetOrCreateOutline() // spine item / HTML title?? } else { string localName = node.GetXmlElementLocalName(); #if DEBUG //protected virtual bool doesTreeNodeTriggerNewSmil(TreeNode node) DebugFix.Assert(node.HasXmlProperty); DebugFix.Assert(localName.StartsWith("level", StringComparison.OrdinalIgnoreCase) || localName.Equals("section", StringComparison.OrdinalIgnoreCase) || localName.Equals("book", StringComparison.OrdinalIgnoreCase) ); #endif TreeNode heading = null; if (TreeNode.IsLevel(localName)) { TreeNode level = node; if (level.Children.Count > 0) { TreeNode nd = level.Children.Get(0); if (nd != null) { localName = nd.HasXmlProperty ? nd.GetXmlElementLocalName() : null; if (localName != null && (localName == "pagenum" || localName == "img") && level.Children.Count > 1) { nd = level.Children.Get(1); if (nd != null) { localName = nd.GetXmlElementLocalName(); } } if (localName != null && (TreeNode.IsHeading(localName))) { heading = nd; } else { if (localName != null && (localName == "pagenum" || localName == "img") && level.Children.Count > 2) { nd = level.Children.Get(2); if (nd != null) { localName = nd.GetXmlElementLocalName(); } } if (localName != null && (TreeNode.IsHeading(localName))) { heading = nd; } } } } } else if (TreeNode.IsHeading(localName)) { #if DEBUG Debugger.Break(); #endif heading = node; } else if (!localName.Equals("book", StringComparison.OrdinalIgnoreCase)) { #if DEBUG Debugger.Break(); #endif } StringBuilder strBuilder = null; if (heading != null) { TreeNode.StringChunkRange range = heading.GetTextFlattened_(); if (!(range == null || range.First == null || string.IsNullOrEmpty(range.First.Str))) { strBuilder = new StringBuilder(range.GetLength()); TreeNode.ConcatStringChunks(range, -1, strBuilder); //strBuilder.Insert(0, "] "); //strBuilder.Insert(0, heading.GetXmlElementLocalName()); //strBuilder.Insert(0, "["); } } //else //{ // strBuilder = new StringBuilder(); // strBuilder.Append("["); // strBuilder.Append(level.GetXmlElementLocalName()); // strBuilder.Append("] "); // strBuilder.Append(Tobi_Plugin_NavigationPane_Lang.NoHeading); //} if (strBuilder != null) { strTitle = strBuilder.ToString().Trim(); } } if (strTitle.Length > 0) { strTitle = FileDataProvider.EliminateForbiddenFileNameCharacters(strTitle.Replace(" ", "_")); } int MAX_LENGTH = AudioFileNameCharsLimit > 0 ? AudioFileNameCharsLimit : 10; if (strTitle.Length > MAX_LENGTH) { strTitle = strTitle.Substring(0, MAX_LENGTH); } string filename = Path.GetFileName(externalAudio.Src); string source = Path.Combine(m_OutputDirectory, filename); if (File.Exists(source)) { if (strTitle.Length > 0) { string newFileName = filename; string name = Path.GetFileNameWithoutExtension(externalAudio.Src); name = name.Replace("aud", ""); string ext = Path.GetExtension(externalAudio.Src); newFileName = name + "_" + strTitle + ext; //externalAudio.Src = externalAudio.Src.Replace(filename, newFileName); externalAudio.Src = newFileName; m_adjustedExternalAudioFileNames.Add(node, externalAudio.Src); string dest = Path.Combine(m_OutputDirectory, newFileName); File.Move(source, dest); try { File.SetAttributes(dest, FileAttributes.Normal); } catch { } return(newFileName); } } return(filename); }
protected string AddSectionNameToAudioFileName(string externalAudioSrc, string sectionName) { string audioFileName = Path.GetFileNameWithoutExtension(externalAudioSrc) + "_" + FileDataProvider.EliminateForbiddenFileNameCharacters(sectionName.Replace(" ", "_")); if (AudioFileNameCharsLimit > 0) { //audioFileName = audioFileName.Replace("aud", ""); audioFileName = audioFileName.Remove(0, 3); if (audioFileName.Length > AudioFileNameCharsLimit) { audioFileName = audioFileName.Substring(0, AudioFileNameCharsLimit); } } audioFileName = audioFileName + Path.GetExtension(externalAudioSrc); string source = Path.Combine(m_OutputDirectory, Path.GetFileName(externalAudioSrc)); string dest = Path.Combine(m_OutputDirectory, audioFileName); if (File.Exists(source)) { File.Move(source, dest); try { File.SetAttributes(dest, FileAttributes.Normal); } catch { } } return(audioFileName); }