public static string GrabIdentifier(string xhtmlPath) { string uId = null; XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(xhtmlPath, false, false); XmlNode headNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc.DocumentElement, true, "head", xmlDoc.DocumentElement.NamespaceURI); if (headNode != null) { foreach (XmlNode metaNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headNode, true, "meta", headNode.NamespaceURI, false)) { string name = metaNode.Attributes.GetNamedItem("name") != null?metaNode.Attributes.GetNamedItem("name").Value : null; string content = metaNode.Attributes.GetNamedItem("content") != null?metaNode.Attributes.GetNamedItem("content").Value : null; if (name == null) { continue; } if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(content) && name.ToLower() == "dc:identifier") { return(content); } } } return(uId); }
private void ImportFromXHTML() { try { XmlDocument nccDocument = null; if (m_Settings.Project_ImportNCCFileWithWindows1252Encoding) { // some old files may have 7 bit encoding. StreamReader sr = new StreamReader(m_NccPath, Encoding.GetEncoding(1252), false); string xmlData = sr.ReadToEnd(); nccDocument = XmlReaderWriterHelper.ParseXmlDocumentFromString(xmlData, false, false); } else { nccDocument = XmlReaderWriterHelper.ParseXmlDocument(m_NccPath, false, false); } XmlNode headNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(nccDocument.DocumentElement, true, "head", nccDocument.DocumentElement.NamespaceURI); PopulateMetadataFromNcc(headNode); XmlNode bodyNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(nccDocument.DocumentElement, true, "body", nccDocument.DocumentElement.NamespaceURI); ParseNccDocument(bodyNode); if (RequestCancellation) { return; } reportProgress(20, ""); AppendPhrasesFromSmil(); reportProgress(100, ""); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } }
private void openAndParseOPF(string opfPath) { XmlDocument opfXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(opfPath, false, false); if (RequestCancellation) { return; } reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingOPF, Path.GetFileName(opfPath))); parseOpf(opfXmlDoc); handleAdditionalManifestItems(opfPath, opfXmlDoc); }
public string GetXmlFragment(bool absoluteLinks) { if (!HasXmlProperty) { return(null); } //StringWriter strWriter = new StringWriter(); //strWriter.NewLine = Environment.NewLine; ////strWriter.NewLine = @"\n"; ////strWriter.Encoding = Encoding.UTF8; StringBuilder strWriter = new StringBuilder(); bool pretty = true; XmlWriterSettings settings = XmlReaderWriterHelper.GetDefaultXmlWriterConfiguration(pretty); XmlWriter xmlWriter = XmlWriter.Create(strWriter, settings); if (pretty && xmlWriter is XmlTextWriter) { ((XmlTextWriter)xmlWriter).Formatting = Formatting.Indented; } //XmlTextWriter xmlWriter = new XmlTextWriter(strWriter); //xmlWriter.Formatting = Formatting.Indented; //xmlWriter.Indentation = 4; //xmlWriter.IndentChar = ' '; //xmlWriter.Namespaces = true; //xmlWriter.QuoteChar = '"'; GetXmlFragment_(xmlWriter, absoluteLinks); xmlWriter.Flush(); xmlWriter.Close(); //string xmlFragment = Encoding.UTF8.GetString(memStream.GetBuffer()); string xmlFragment = strWriter.ToString(); return(xmlFragment); }
private void AppendPhrasesFromSmil() { if (m_SectionNodesToSmilReferenceMap.Count == 0) { return; } int progressIncrement = 80 / m_SectionNodesToSmilReferenceMap.Count; int progressCounter = 20; foreach (SectionNode section in m_SectionNodesToSmilReferenceMap.Keys) { if (RequestCancellation) { return; } string smilReferenceString = m_SectionNodesToSmilReferenceMap[section]; if (smilReferenceString == null) { continue; } string[] StringArray = smilReferenceString.Split('#'); string smilFileName = StringArray[0]; string strId = StringArray[1]; string fullSmilFilePath = Path.Combine(Path.GetDirectoryName(m_NccPath), smilFileName); if (!File.Exists(fullSmilFilePath)) { continue; } XmlDocument smilDocument = XmlReaderWriterHelper.ParseXmlDocument(fullSmilFilePath, false, false); Console.WriteLine(section.Label + " : " + smilFileName); XmlNode mainSeqNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(smilDocument.DocumentElement, true, "seq", smilDocument.DocumentElement.NamespaceURI); ParseSmilDocument(section, mainSeqNode, smilFileName, strId); progressCounter += progressIncrement; if (progressCounter < 100) { reportProgress(progressCounter, ""); } } }
private void ImportFromXHTML() { try { XmlDocument nccDocument = XmlReaderWriterHelper.ParseXmlDocument(m_NccPath, false, false); XmlNode headNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(nccDocument.DocumentElement, true, "head", nccDocument.DocumentElement.NamespaceURI); PopulateMetadataFromNcc(headNode); XmlNode bodyNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(nccDocument.DocumentElement, true, "body", nccDocument.DocumentElement.NamespaceURI); ParseNccDocument(bodyNode); if (RequestCancellation) { return; } reportProgress(20, ""); AppendPhrasesFromSmil(); reportProgress(100, ""); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } }
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); }
protected override 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; } // assign obi project file path to xuk path to prevent creation of xukspine file. XukPath = m_session.Path; //Console.WriteLine(XukPath); Presentation spinePresentation = m_Project.Presentations.Get(0); m_IsTOCFromNavDoc = false; if (navDocPath != null) { string fullNavPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), navDocPath); XmlDocument navDoc = urakawa.xuk.XmlReaderWriterHelper.ParseXmlDocument(fullNavPath, true, true); ParseNCXDocument(navDoc); m_IsTOCFromNavDoc = true; } //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(); TreenodesWithoutManagedAudioMediaData = new List <TreeNode>(); Presentation spineItemPresentation = null; int index = -1; foreach (string docPath in spineOfContentDocuments) { index++; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath)); //System.Windows.Forms.MessageBox.Show(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 (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) { ExternalFileData externalData = null; if (docPath == coverImagePath) { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <CoverImageExternalFileData>(); } else { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <GenericExternalFileData>(); } if (externalData != null) { externalData.InitializeWithData(fullDocPath, docPath, true, null); addOPF_GlobalAssetPath(fullDocPath); } } continue; } //spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true"); XmlDocument xmlDoc = urakawa.xuk.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), //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; //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()); if (m_AudioConversionSession != null) { RemoveSubCancellable(m_AudioConversionSession); m_AudioConversionSession = null; } m_AudioConversionSession = new AudioFormatConvertorSession( m_Presentation.DataProviderManager.DataFileDirectoryFullPath, m_Presentation.MediaDataManager.DefaultPCMFormat, m_autoDetectPcmFormat, true); //AddSubCancellable(m_AudioConversionSession); if (RequestCancellation) { return; } if (parseContentDocParts(fullDocPath, m_Project, xmlDoc, docPath, DocumentMarkupType.NA)) { return; // user cancel } /* * 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); * } * } */ 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); SectionNode section = m_Presentation.FirstSection; IEnumerable <XmlNode> textElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "text", null, false); if (textElements == null) { continue; } // audio list replaced by text list //IEnumerable<XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false); //if (audioElements == null) //{ //continue; //} //foreach (XmlNode audioNode in audioElements) foreach (XmlNode textNode in textElements) { XmlAttributeCollection attrs = textNode.Attributes; if (attrs == null) { continue; } //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; XmlNode audioNode = null; PageNumber pgNumber = null; //XmlNodeList children = audioNode.ParentNode.ChildNodes; XmlNodeList children = textNode.ParentNode.ChildNodes; foreach (XmlNode child in children) { //if (child == audioNode) //{ //continue; //} //if (child.LocalName != "text") //{ //continue; //} if (child.LocalName == "audio") { audioNode = child; } //XmlAttributeCollection textAttrs = child.Attributes; XmlAttributeCollection textAttrs = textNode.Attributes; if (textAttrs == null) { continue; } XmlNode textSrc = textAttrs.GetNamedItem("src"); if (textSrc == null) { continue; } string urlDecoded = FileDataProvider.UriDecode(textSrc.Value); string contentFilesDirectoryPath = Path.GetDirectoryName(fullOverlayPath); if (urlDecoded.StartsWith("./")) { urlDecoded = urlDecoded.Remove(0, 2); } if (urlDecoded.StartsWith("../")) { urlDecoded = urlDecoded.Remove(0, 3); contentFilesDirectoryPath = Path.GetDirectoryName(contentFilesDirectoryPath); } if (urlDecoded.IndexOf('#') > 0) { string[] srcParts = urlDecoded.Split('#'); if (srcParts.Length != 2) { continue; } string fullTextRefPath = Path.Combine(contentFilesDirectoryPath, 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); // replacing it //System.Windows.Forms.MessageBox.Show("retrieving: " + urlDecoded); if (m_XmlIdToSectionNodeMap.ContainsKey(urlDecoded)) { textTreeNode = m_XmlIdToSectionNodeMap[urlDecoded]; } else if (m_XmlIdToSectionNodeMap.ContainsKey(srcParts[0])) { textTreeNode = m_XmlIdToSectionNodeMap[srcParts[0]]; } if (textTreeNode != null) { section = (SectionNode)textTreeNode; //System.Windows.Forms.MessageBox.Show(((SectionNode)textTreeNode).Label); } } 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 (m_XmlIdToPageNodeMap.ContainsKey(urlDecoded) && m_XmlIdToPageNodeMap[urlDecoded] != null) { EmptyNode pgNode = m_XmlIdToPageNodeMap[urlDecoded]; pgNumber = pgNode.PageNumber; // if the section does not match then the parent of the page node should become the section. if (pgNode.IsRooted && textTreeNode == null && pgNode.Parent != section) { section = pgNode.ParentAs <SectionNode>(); //Console.WriteLine("text node is null"); } if (pgNode.IsRooted) { pgNode.Detach(); } // the phrases following the page phrase in smil will refer to same content doc ID. so to avoid reassigning page, the page node in dictionary is assigned to null. m_XmlIdToPageNodeMap[urlDecoded] = null; } } if (section != null && audioNode != null) { PhraseNode audioWrapperNode = m_Presentation.CreatePhraseNode(); section.AppendChild(audioWrapperNode); addAudio(audioWrapperNode, audioNode, false, fullOverlayPath); if (audioWrapperNode.Duration == 0 && !TreenodesWithoutManagedAudioMediaData.Contains(audioWrapperNode)) { TreenodesWithoutManagedAudioMediaData.Add(audioWrapperNode); } if (pgNumber != null) { audioWrapperNode.PageNumber = pgNumber; pgNumber = null; } } audioNode = null; } } } //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); * } */ } } }
private void parseSmilForNCX(string fullSmilPath) { //foreach (string s in m_SmilRefToNavPointTreeNodeMap.Keys) System.Windows.Forms.MessageBox.Show(s + " : " + m_SmilRefToNavPointTreeNodeMap[s].GetXmlElementLocalName() ); if (RequestCancellation) { return; } XmlDocument smilXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullSmilPath, false, false); if (RequestCancellation) { return; } m_SmilXmlNodeToTreeNodeMap = new Dictionary <XmlNode, TreeNode>(); //we skip SMIL metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs) //parseMetadata(smilXmlDoc); //XmlNodeList allTextNodes = smilXmlDoc.GetElementsByTagName("text"); //if (allTextNodes.Count == 0) //{ // return; //} //reportProgress(-1, "Parsing SMIL: [" + Path.GetFileName(fullSmilPath) + "]"); TreeNode navPointTreeNode = null; XmlNamespaceManager firstDocNSManager = new XmlNamespaceManager(smilXmlDoc.NameTable); firstDocNSManager.AddNamespace("firstNS", smilXmlDoc.DocumentElement.NamespaceURI); bool isHeading = false; bool isPageInProcess = false; TreeNode audioWrapperNode = null; XmlNodeList smilNodeList = smilXmlDoc.DocumentElement.SelectNodes(".//firstNS:seq | .//firstNS:par", firstDocNSManager); //foreach (XmlNode parNode in XmlDocumentHelper.GetChildrenElementsWithName(smilXmlDoc, true, "par", null, false)) foreach (XmlNode parNode in smilNodeList) { XmlAttributeCollection parNodeAttrs = parNode.Attributes; if (parNodeAttrs == null || parNodeAttrs.Count == 0) { continue; } //XmlNode textNodeAttrSrc = parNodeAttrs.GetNamedItem("src"); XmlNode parNodeID = parNodeAttrs.GetNamedItem("id"); if (parNodeID == null || String.IsNullOrEmpty(parNodeID.Value)) { continue; } string ncxContentSRC = Path.GetFileName(fullSmilPath) + "#" + parNodeID.Value; TreeNode obj; m_SmilRefToNavPointTreeNodeMap.TryGetValue(ncxContentSRC, out obj); // for now we are assuming the first phrase as heading phrase. this need refinement such that phrase anywhere in section can be imported as heading) if (obj != null) //m_SmilRefToNavPointTreeNodeMap.ContainsKey(ncxContentSRC)) { m_IsDocTitleCreated = true; navPointTreeNode = obj; // m_SmilRefToNavPointTreeNodeMap[ncxContentSRC]; //System.Windows.Forms.MessageBox.Show(ncxContentSRC + " section:" + navPointTreeNode.GetXmlElementLocalName() + " : " + Path.GetFileName( fullSmilPath ) ); //: audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, true); //isHeading = true; } // handle doctitle if audio exists before first heading by adding doctitle node as first treenode if (navPointTreeNode == null && !m_IsDocTitleCreated && (XmlDocumentHelper.GetFirstChildElementOrSelfWithName(parNode, false, "audio", null) != null || XmlDocumentHelper.GetFirstChildElementOrSelfWithName(parNode, false, "text", null) != null)) { m_IsDocTitleCreated = true; navPointTreeNode = CreateTreeNodeForNavPoint(m_Project.Presentations.Get(0).RootNode, m_DocTitleXmlNode); m_NavPointNode_NavLabelMap.Add(navPointTreeNode, m_DocTitleXmlNode); } //else if (m_PageReferencesMapDictionaryForNCX.ContainsKey(ncxContentSRC) if (m_PageReferencesMapDictionaryForNCX.ContainsKey(ncxContentSRC) || (parNode.Attributes.GetNamedItem("customTest") != null && parNode.Attributes.GetNamedItem("customTest").Value == "pagenum")) { isPageInProcess = true; if (navPointTreeNode == null) { continue; } //:audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, false); } if (navPointTreeNode == null) { continue; } //System.Windows.Forms.MessageBox.Show(parNode.LocalName); ManagedAudioMedia textTreeNodeAudio = navPointTreeNode.GetManagedAudioMedia(); if (textTreeNodeAudio != null) { //Ignore. continue; } XmlNodeList textPeers = parNode.ChildNodes; foreach (XmlNode textPeerNode in textPeers) //foreach (XmlNode textPeerNode in XmlDocumentHelper.GetChildrenElementsWithName(parNode, true, "audio", null, false)) { if (RequestCancellation) { return; } //if (XmlDocumentHelper.GetFirstChildElementWithName(parNode, false, "audio", null) == null) continue; if (textPeerNode.NodeType != XmlNodeType.Element) { continue; } if (textPeerNode.LocalName == "audio") { audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, isHeading, textPeerNode, fullSmilPath); CheckAndAssignForHeadingAudio(navPointTreeNode, audioWrapperNode, textPeerNode); XmlProperty xmlProp = navPointTreeNode.Presentation.PropertyFactory.CreateXmlProperty(); audioWrapperNode.AddProperty(xmlProp); // +":" + navPointTreeNode.GetTextFlattened(false); xmlProp.SetQName("phrase", ""); string pageRefInSmil = Path.GetFileName(fullSmilPath) + "#" + parNode.Attributes.GetNamedItem("id").Value; XmlNode xNode; m_PageReferencesMapDictionaryForNCX.TryGetValue(pageRefInSmil, out xNode); if (xNode != null && //m_PageReferencesMapDictionaryForNCX.ContainsKey(pageRefInSmil) isPageInProcess) { isPageInProcess = false; XmlNode pageTargetNode = xNode; //m_PageReferencesMapDictionaryForNCX[pageRefInSmil]; AddPagePropertiesToAudioNode(audioWrapperNode, pageTargetNode); } isHeading = false; addAudio(audioWrapperNode, textPeerNode, false, fullSmilPath); break; } else if (textPeerNode.LocalName == "a") { XmlNodeList aChildren = textPeerNode.ChildNodes; foreach (XmlNode aChild in aChildren) { if (aChild.LocalName == "audio") { //addAudio(audioWrapperNode, aChild, false, fullSmilPath); audioWrapperNode = CreateTreeNodeForAudioNode(navPointTreeNode, false, aChild, fullSmilPath); addAudio(audioWrapperNode, aChild, false, fullSmilPath); break; } else { AddAnchorNode(navPointTreeNode, textPeerNode, fullSmilPath); break; } } } else if (textPeerNode.LocalName == "seq" || textPeerNode.LocalName == "par") { if (audioWrapperNode != null) { m_SmilXmlNodeToTreeNodeMap.Add(textPeerNode, audioWrapperNode); } /* * XmlNodeList seqChildren = textPeerNode.ChildNodes; * foreach (XmlNode seqChild in seqChildren) * //1{ * if (seqChild.LocalName == "audio") * {//2 * addAudio(audioWrapperNode, seqChild, true, fullSmilPath); * }//-2 * }//-1 * * SequenceMedia seqManAudioMedia = audioWrapperNode.GetManagedAudioSequenceMedia(); * if (seqManAudioMedia == null) * {//1 * //Debug.Fail("This should never happen !"); * break; * }//-1 * * ManagedAudioMedia managedAudioMedia = audioWrapperNode.Presentation.MediaFactory.CreateManagedAudioMedia(); * AudioMediaData mediaData = audioWrapperNode.Presentation.MediaDataFactory.CreateAudioMediaData(); * managedAudioMedia.AudioMediaData = mediaData; * * foreach (Media seqChild in seqManAudioMedia.ChildMedias.ContentsAs_YieldEnumerable) * {//1 * ManagedAudioMedia seqManMedia = (ManagedAudioMedia)seqChild; * mediaData.MergeWith(seqManMedia.AudioMediaData); * }//-1 * * ChannelsProperty chProp = audioWrapperNode.GetChannelsProperty(); * chProp.SetMedia(m_audioChannel, null); * chProp.SetMedia(m_audioChannel, managedAudioMedia); */ break; } } } }
private void parseContainerXML(string 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")); m_OPF_ContainerRelativePath = FileDataProvider.UriDecode(fullPathAttr.Value); if (m_OPF_ContainerRelativePath.StartsWith(@"./")) { m_OPF_ContainerRelativePath = m_OPF_ContainerRelativePath.Substring(2); } m_Book_FilePath = Path.Combine(rootDirectory, m_OPF_ContainerRelativePath.Replace('/', '\\')); openAndParseOPF(m_Book_FilePath); //if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath)) string metaInfDir = Path.GetDirectoryName(containerPath); DirectoryInfo dirInfo = new DirectoryInfo(metaInfDir); #if NET40 IEnumerable <FileInfo> fileInfos = dirInfo.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly); #else FileInfo[] fileInfos = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly); #endif foreach (FileInfo fileInfo in fileInfos) { ExternalFiles.ExternalFileData efd = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); try { string relativePath = META_INF_prefix + fileInfo.Name; efd.InitializeWithData(fileInfo.FullName, relativePath, true, null); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } }
private void parseOpf(XmlDocument opfXmlDoc) { List <string> spine; Dictionary <string, string> spineAttributes; List <Dictionary <string, string> > spineItemsAttributes; string spineMimeType; string dtbookPath; string ncxPath; string navDocPath; string coverImagePath; if (RequestCancellation) { return; } XmlNode packageNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "package", null); if (packageNode != null) { XmlAttributeCollection packageNodeAttrs = packageNode.Attributes; if (packageNodeAttrs != null && packageNodeAttrs.Count > 0) { m_PackageUniqueIdAttr = packageNodeAttrs.GetNamedItem("unique-identifier"); m_PackagePrefixAttr = packageNodeAttrs.GetNamedItem("prefix"); } } string idCoverImageFromMetadata = null; IEnumerable <XmlNode> metaElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(opfXmlDoc, true, "meta", null, false); foreach (XmlNode metaElement in metaElements) { XmlAttributeCollection metaElementAttributes = metaElement.Attributes; if (metaElementAttributes == null || metaElementAttributes.Count <= 0) { continue; } XmlNode attrName = metaElementAttributes.GetNamedItem("name"); if (attrName == null || string.IsNullOrEmpty(attrName.Value) || attrName.Value != @"cover") { continue; } XmlNode attrContent = metaElementAttributes.GetNamedItem("content"); if (attrContent == null && string.IsNullOrEmpty(attrContent.Value)) { continue; } idCoverImageFromMetadata = attrContent.Value; break; } parseOpfManifest(opfXmlDoc, out spine, out spineAttributes, out spineItemsAttributes, out spineMimeType, out dtbookPath, out ncxPath, out navDocPath, out coverImagePath, idCoverImageFromMetadata); if (RequestCancellation) { return; } m_IsSpine = spineMimeType == DataProviderFactory.XHTML_MIME_TYPE || spineMimeType == DataProviderFactory.IMAGE_SVG_MIME_TYPE; DebugFix.Assert(m_IsSpine == !(spineMimeType == DataProviderFactory.SMIL_MIME_TYPE_)); if (m_IsSpine) { reInitialiseProjectSpine(); } XmlNode metadataXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc.DocumentElement, true, "metadata", null); parseMetadata(m_Book_FilePath, m_Project, opfXmlDoc, metadataXmlNode); m_PublicationUniqueIdentifier_OPF = m_PublicationUniqueIdentifier; m_PublicationUniqueIdentifierNode_OPF = m_PublicationUniqueIdentifierNode; if (dtbookPath != null && !m_IsSpine && !AudioNCXImport) { if (RequestCancellation) { return; } string fullDtbookPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), dtbookPath); XmlDocument dtbookXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDtbookPath, true, true); if (parseContentDocParts(fullDtbookPath, m_Project, dtbookXmlDoc, dtbookPath, DocumentMarkupType.DTBOOK)) { return; // user cancel } //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, dtbookPath)); //parseMetadata(m_Book_FilePath, m_Project, dtbookXmlDoc); //if (RequestCancellation) return; //ParseHeadLinks(m_Book_FilePath, m_Project, dtbookXmlDoc); //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, dtbookPath)); //parseContentDocument(m_Book_FilePath, m_Project, dtbookXmlDoc, null, fullDtbookPath, null, DocumentMarkupType.DTBOOK); } //if (false && ncxPath != null) //we skip NCX metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs) if ( //(string.IsNullOrEmpty(dtbookPath) && !string.IsNullOrEmpty(ncxPath)) || AudioNCXImport) { //m_IsAudioNCX = true; if (RequestCancellation) { return; } string fullNcxPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), ncxPath); XmlDocument ncxXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullNcxPath, false, false); if (RequestCancellation) { return; } reportProgress(-1, "Parsing metadata: [" + ncxPath + "]"); XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(ncxXmlDoc.DocumentElement, true, "head", null); parseMetadata(fullNcxPath, m_Project, ncxXmlDoc, headXmlNode); if (AudioNCXImport) { ParseNCXDocument(ncxXmlDoc); } } if (RequestCancellation) { return; } switch (spineMimeType) { case DataProviderFactory.SMIL_MIME_TYPE_: { parseSmiles(spine); break; } case DataProviderFactory.XHTML_MIME_TYPE: case DataProviderFactory.IMAGE_SVG_MIME_TYPE: { if (!string.IsNullOrEmpty(coverImagePath) && !spine.Contains(coverImagePath)) { string fullCoverImagePath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), coverImagePath); fullCoverImagePath = FileDataProvider.NormaliseFullFilePath(fullCoverImagePath).Replace('/', '\\'); if (File.Exists(fullCoverImagePath)) { ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>(); try { externalData.InitializeWithData(fullCoverImagePath, coverImagePath, true, null); addOPF_GlobalAssetPath(fullCoverImagePath); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } #if DEBUG else { Debugger.Break(); } #endif } if (!string.IsNullOrEmpty(navDocPath) && !spine.Contains(navDocPath)) { string fullNavDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), navDocPath); fullNavDocPath = FileDataProvider.NormaliseFullFilePath(fullNavDocPath).Replace('/', '\\'); if (File.Exists(fullNavDocPath)) { ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.NavDocExternalFileData>(); try { externalData.InitializeWithData(fullNavDocPath, navDocPath, true, null); addOPF_GlobalAssetPath(fullNavDocPath); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } #if DEBUG else { Debugger.Break(); } #endif } if (!string.IsNullOrEmpty(ncxPath)) { string fullNcxPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), ncxPath); fullNcxPath = FileDataProvider.NormaliseFullFilePath(fullNcxPath).Replace('/', '\\'); if (File.Exists(fullNcxPath)) { ExternalFiles.ExternalFileData externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.NCXExternalFileData>(); try { externalData.InitializeWithData(fullNcxPath, ncxPath, true, null); addOPF_GlobalAssetPath(fullNcxPath); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } #if DEBUG else { Debugger.Break(); } #endif } parseContentDocuments(spine, spineAttributes, spineItemsAttributes, coverImagePath, navDocPath); break; } } }
private bool doImport() { m_Logger.Log(String.Format(@"UrakawaSession.doImport() [{0}]", DocumentFilePath), Category.Debug, Priority.Medium); string ext = Path.GetExtension(DocumentFilePath); if (".opf".Equals(ext, StringComparison.OrdinalIgnoreCase)) { int levelsUp = 0; string parentDir = Path.GetDirectoryName(DocumentFilePath); DirectoryInfo parentDirInfo = new DirectoryInfo(parentDir); tryAgain: levelsUp++; #if NET40 IEnumerable <DirectoryInfo> metaInfDirs = parentDirInfo.EnumerateDirectories("META-INF", SearchOption.TopDirectoryOnly); #else DirectoryInfo[] metaInfDirs = parentDirInfo.GetDirectories("META-INF", SearchOption.TopDirectoryOnly); #endif bool found = false; foreach (DirectoryInfo dirInfo in metaInfDirs) { string containerXml = Path.Combine(dirInfo.FullName, "container.xml"); if (File.Exists(containerXml)) { DocumentFilePath = containerXml; ext = Path.GetExtension(DocumentFilePath); found = true; break; } } if (!found && levelsUp <= 2 && parentDirInfo.Parent != null) { parentDirInfo = parentDirInfo.Parent; goto tryAgain; } } if (DataProviderFactory.EPUB_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { checkEpub(DocumentFilePath, null); } else if (DataProviderFactory.XML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase) && FileDataProvider.NormaliseFullFilePath(DocumentFilePath).IndexOf( @"META-INF" //+ Path.DirectorySeparatorChar + '/' + @"container.xml" , StringComparison.OrdinalIgnoreCase) >= 0 //DocumentFilePath.IndexOf("container.xml", StringComparison.OrdinalIgnoreCase) >= 0 ) { string parentDir = Path.GetDirectoryName(DocumentFilePath); DirectoryInfo dirInfo = new DirectoryInfo(parentDir); if (dirInfo.Parent != null) { string checkEpubPath = dirInfo.Parent.FullName; checkEpub(checkEpubPath, "exp"); } } else if (".opf".Equals(ext, StringComparison.OrdinalIgnoreCase)) { if (!checkDAISY(DocumentFilePath)) { //checkEpub(DocumentFilePath, "opf"); assume container.xml was found (see above) } } else if (DataProviderFactory.HTML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase) || DataProviderFactory.XHTML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { //MessageBox.Show messageBoxAlert("WARNING: single HTML import is an experimental and incomplete EPUB feature!", null); checkEpub(DocumentFilePath, "xhtml"); } else if (DataProviderFactory.XML_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { //checkDAISY(DocumentFilePath); if (false && // TODO: Pipeline 2 with better support for DTBOOK validation (currently skips metadata values) askUser("DAISY Check?", DocumentFilePath)) { string pipeline_ExePath = obtainPipelineExe(); if (!string.IsNullOrEmpty(pipeline_ExePath)) { string outDir = Path.GetDirectoryName(DocumentFilePath); outDir = Path.Combine(outDir, Path.GetFileName(DocumentFilePath) + "_PIPEVAL"); bool success = false; Func <String, String> checkErrorsOrWarning = (string report) => { if (report.IndexOf("[DP2] DONE", StringComparison.Ordinal) < 0) { return("Pipeline job doesn't appear to have completed?"); } string reportFile = Path.Combine(outDir, "report.xhtml"); if (File.Exists(reportFile)) { string reportXmlSource = File.ReadAllText(reportFile); if (!string.IsNullOrEmpty(reportXmlSource)) { string xmlInfo = ""; XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocumentFromString(reportXmlSource, false, false); IEnumerable <XmlNode> lis = XmlDocumentHelper.GetChildrenElementsOrSelfWithName( xmlDoc.DocumentElement, true, "li", null, false); foreach (XmlNode li in lis) { if (li.Attributes == null) { continue; } XmlNode classAttr = li.Attributes.GetNamedItem("class"); if (classAttr == null || classAttr.Value != "error") { continue; } xmlInfo += li.InnerText; xmlInfo += Environment.NewLine; } if (string.IsNullOrEmpty(xmlInfo)) { success = true; return(null); } return(xmlInfo); } } success = true; return(null); }; try { string workingDir = Path.GetDirectoryName(pipeline_ExePath); //Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); executeProcess( workingDir, "DAISY Pipeline (validation)", //"\"" + pipeline_ExePath //+ "\"" , "dtbook-validator " + "--i-source \"" + DocumentFilePath + "\" " + "--x-output-dir \"" + outDir + "\" ", checkErrorsOrWarning); } catch (Exception ex) { messageBoxText("Oops :(", "Problem running DAISY Pipeline (validation)!", ex.Message + Environment.NewLine + ex.StackTrace); } if (Directory.Exists(outDir)) { //m_ShellView.ExecuteShellProcess(outDir); FileDataProvider.TryDeleteDirectory(outDir, false); } } } } string outputDirectory = Path.Combine( Path.GetDirectoryName(DocumentFilePath), Daisy3_Import.GetXukDirectory(DocumentFilePath)); //string xukPath = Daisy3_Import.GetXukFilePath(outputDirectory, DocumentFilePath); //if (File.Exists(xukPath)) if (Directory.Exists(outputDirectory)) { if (!askUserConfirmOverwriteFileFolder(outputDirectory, true, null)) { return(false); } FileDataProvider.TryDeleteDirectory(outputDirectory, true); } var combo = new ComboBox { Margin = new Thickness(0, 0, 0, 0), HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; 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 (Settings.Default.AudioProjectSampleRate) { 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 label_ = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.Stereo, Margin = new Thickness(0, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var checkBox = new CheckBox { IsThreeState = false, IsChecked = Settings.Default.AudioProjectStereo, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var panel__ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 8, 0, 22), }; panel__.Children.Add(label_); panel__.Children.Add(checkBox); var label = new TextBlock { Text = Tobi_Plugin_Urakawa_Lang.UseSourceAudioFormat, Margin = new Thickness(0, 0, 8, 0), HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.Wrap }; var checkAuto = new CheckBox { IsThreeState = false, IsChecked = false, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, }; var panel_ = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 0, 12), }; panel_.Children.Add(label); panel_.Children.Add(checkAuto); var panel = new StackPanel { Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Center, }; panel.Children.Add(combo); panel.Children.Add(panel__); panel.Children.Add(panel_); //var line = new Separator() //{ // Margin = new Thickness(0, 8, 0, 8), //}; //line.HorizontalAlignment = HorizontalAlignment.Stretch; //line.VerticalAlignment = VerticalAlignment.Center; //panel.Children.Add(line); var details = new TextBoxReadOnlyCaretVisible { FocusVisualStyle = (Style)Application.Current.Resources["MyFocusVisualStyle"], BorderThickness = new Thickness(1), Padding = new Thickness(6), TextReadOnly = Tobi_Plugin_Urakawa_Lang.UseSourceAudioFormatTip }; var windowPopup = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Urakawa_Lang.ProjectAudioFormat), panel, PopupModalWindow.DialogButtonsSet.OkCancel, PopupModalWindow.DialogButton.Ok, false, 320, 200, details, 40, null); windowPopup.EnableEnterKeyDefault = true; windowPopup.ShowModal(); if (!PopupModalWindow.IsButtonOkYesApply(windowPopup.ClickedDialogButton)) { return(false); } Settings.Default.AudioProjectStereo = checkBox.IsChecked.Value; if (combo.SelectedItem == item1) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz11025; } else if (combo.SelectedItem == item2) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz22050; } else if (combo.SelectedItem == item3) { Settings.Default.AudioProjectSampleRate = SampleRate.Hz44100; } var converter = new Daisy3_Import(DocumentFilePath, outputDirectory, IsAcmCodecsDisabled, Settings.Default.AudioProjectSampleRate, Settings.Default.AudioProjectStereo, checkAuto.IsChecked.Value, Settings.Default.XUK_PrettyFormat ); //Directory.GetParent(bookfile).FullName //converter.VerifyHtml5OutliningAlgorithmUsingPipelineTestSuite(); bool cancelled = false; bool error = m_ShellView.RunModalCancellableProgressTask(true, Tobi_Plugin_Urakawa_Lang.Importing, converter, () => { cancelled = true; DocumentFilePath = null; DocumentProject = null; }, () => { cancelled = false; if (string.IsNullOrEmpty(converter.XukPath)) { return; } //DocumentFilePath = converter.XukPath; //DocumentProject = converter.Project; //AddRecentFile(new Uri(DocumentFilePath, UriKind.Absolute)); }); if (!cancelled) { //DebugFix.Assert(!report); string xukPath = converter.XukPath; if (string.IsNullOrEmpty(xukPath)) { return(false); } string projectDir = Path.GetDirectoryName(xukPath); DebugFix.Assert(outputDirectory == projectDir); string title = converter.GetTitle(); if (!string.IsNullOrEmpty(title)) { string fileName = Daisy3_Import.GetXukFilePath(projectDir, DocumentFilePath, title, false); fileName = Path.GetFileNameWithoutExtension(fileName); string parent = Path.GetDirectoryName(projectDir); //string fileName = Path.GetFileNameWithoutExtension(xukPath); ////while (fileName.StartsWith("_")) ////{ //// fileName = fileName.Substring(1, fileName.Length - 1); ////} //char[] chars = new char[] { '_' }; //fileName = fileName.TrimStart(chars); string newProjectDir = Path.Combine(parent, fileName); // + Daisy3_Import.XUK_DIR if (newProjectDir != projectDir) { bool okay = true; if (Directory.Exists(newProjectDir)) { if (askUserConfirmOverwriteFileFolder(newProjectDir, true, null)) { try { FileDataProvider.TryDeleteDirectory(newProjectDir, false); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); okay = false; } } else { okay = false; } } if (okay) { Directory.Move(projectDir, newProjectDir); xukPath = Path.Combine(newProjectDir, Path.GetFileName(xukPath)); } } } DocumentFilePath = null; DocumentProject = null; try { OpenFile(xukPath); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, m_ShellView); return(false); } } return(!cancelled); }
protected virtual void CreateOpfDocument() { //m_ProgressPercentage = 90; //reportProgress(m_ProgressPercentage, UrakawaSDK_daisy_Lang.AllFilesCreated); if (RequestCancellation) { return; } XmlDocument opfDocument = CreateStub_OpfDocument(); XmlNode manifestNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfDocument, true, "manifest", null); //opfDocument.GetElementsByTagName("manifest")[0]; m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Title); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Creator); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Subject); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Description); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Identifier); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Publisher); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Contributor); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Date); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Type); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Format); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.D_Source); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Language); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Relation); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Coverage); m_AllowedInDcMetadata.Add(SupportedMetadata_Z39862005.DC_Rights); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_SOURCE_DATE); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_SOURCE_EDITION); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_SOURCE_PUBLISHER); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_SOURCE_RIGHTS); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_SOURCE_TITLE); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_MULTIMEDIA_TYPE); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_MULTIMEDIA_CONTENT); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_NARRATOR); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_PRODUCER); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_PRODUCED_DATE); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_REVISION); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_REVISION_DATE); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_REVISION_DESCRIPTION); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_TOTAL_TIME); m_DtbAllowedInXMetadata.Add(SupportedMetadata_Z39862005.DTB_AUDIO_FORMAT); AddFilenameToManifest(opfDocument, manifestNode, m_Filename_Ncx, "ncx", DataProviderFactory.NCX_MIME_TYPE); if (m_Filename_Content != null) { AddFilenameToManifest(opfDocument, manifestNode, m_Filename_Content, GetNextID(ID_OpfPrefix), DataProviderFactory.DTBOOK_MIME_TYPE); } AddFilenameToManifest(opfDocument, manifestNode, m_Filename_Opf, GetNextID(ID_OpfPrefix), DataProviderFactory.XML_MIME_TYPE); foreach (string externalFileName in m_FilesList_ExternalFiles) { // ALREADY escaped! //externalFileName = FileDataProvider.EliminateForbiddenFileNameCharacters(externalFileName); string strID = GetNextID(ID_OpfPrefix); string ext = Path.GetExtension(externalFileName); if (DataProviderFactory.CSS_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { AddFilenameToManifest(opfDocument, manifestNode, externalFileName, strID, DataProviderFactory.CSS_MIME_TYPE); } else if (DataProviderFactory.XSLT_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase) || DataProviderFactory.XSL_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { AddFilenameToManifest(opfDocument, manifestNode, externalFileName, strID, DataProviderFactory.XSLT_MIME_TYPE_); } else if (DataProviderFactory.DTD_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { AddFilenameToManifest(opfDocument, manifestNode, externalFileName, strID, DataProviderFactory.DTD_MIME_TYPE); } } if (RequestCancellation) { return; } List <string> smilIDListInPlayOrder = new List <string>(); foreach (string smilFileName in m_FilesList_Smil) { string strID = GetNextID(ID_OpfPrefix); AddFilenameToManifest(opfDocument, manifestNode, smilFileName, strID, DataProviderFactory.SMIL_MIME_TYPE_); smilIDListInPlayOrder.Add(strID); } if (RequestCancellation) { return; } foreach (string audioFileName in m_FilesList_SmilAudio) { string strID = GetNextID(ID_OpfPrefix); string ext = Path.GetExtension(audioFileName); string mime = DataProviderFactory.GetMimeTypeFromExtension(ext); AddFilenameToManifest(opfDocument, manifestNode, audioFileName, strID, mime); } if (RequestCancellation) { return; } foreach (string imageFileName in m_FilesList_Image) { string strID = GetNextID(ID_OpfPrefix); string ext = Path.GetExtension(imageFileName); string mime = DataProviderFactory.GetMimeTypeFromExtension(ext); AddFilenameToManifest(opfDocument, manifestNode, imageFileName, strID, mime); } #if SUPPORT_AUDIO_VIDEO if (RequestCancellation) { return; } foreach (string videoFileName in m_FilesList_Video) { string strID = GetNextID(ID_OpfPrefix); string ext = Path.GetExtension(videoFileName); string mime = DataProviderFactory.GetMimeTypeFromExtension(ext); AddFilenameToManifest(opfDocument, manifestNode, videoFileName, strID, mime); } foreach (string audioFileName in m_FilesList_Audio) { string strID = GetNextID(ID_OpfPrefix); string ext = Path.GetExtension(audioFileName); string mime = DataProviderFactory.GetMimeTypeFromExtension(ext); AddFilenameToManifest(opfDocument, manifestNode, audioFileName, strID, mime); } #endif if (RequestCancellation) { return; } bool textOnly = m_TotalTime == null || m_TotalTime.AsLocalUnits == 0; if (true || !textOnly) { // copy resource files and place entry in manifest string sourceDirectoryPath = System.AppDomain.CurrentDomain.BaseDirectory; string ResourceRes_Filename = "tpbnarrator.res"; string resourceAudio_Filename = "tpbnarrator_res.mp3"; string ResourceRes_Filename_fullPath = Path.Combine(sourceDirectoryPath, ResourceRes_Filename); string resourceAudio_Filename_fullPath = Path.Combine(sourceDirectoryPath, resourceAudio_Filename); if (File.Exists(ResourceRes_Filename_fullPath) && File.Exists(resourceAudio_Filename_fullPath)) { if (RequestCancellation) { return; } string destRes = Path.Combine(m_OutputDirectory, ResourceRes_Filename); if (!textOnly) { File.Copy(ResourceRes_Filename_fullPath, destRes, true); try { File.SetAttributes(destRes, FileAttributes.Normal); } catch { } } else { string resXml = File.ReadAllText(ResourceRes_Filename_fullPath); int i = -1; int j = 0; while ((i = resXml.IndexOf("<audio", j)) >= 0) { j = resXml.IndexOf("/>", i); if (j > i) { int len = j - i + 2; resXml = resXml.Remove(i, len); string fill = ""; for (int k = 1; k <= len; k++) { fill += ' '; //k.ToString(); } resXml = resXml.Insert(i, fill); } else { #if DEBUG Debugger.Break(); #endif break; } } StreamWriter streamWriter = File.CreateText(destRes); try { streamWriter.Write(resXml); } finally { streamWriter.Close(); } } AddFilenameToManifest(opfDocument, manifestNode, ResourceRes_Filename, "resource", DataProviderFactory.DTB_RES_MIME_TYPE); if (!textOnly) { string destFile = Path.Combine(m_OutputDirectory, resourceAudio_Filename); File.Copy(resourceAudio_Filename_fullPath, destFile, true); try { File.SetAttributes(destFile, FileAttributes.Normal); } catch { } AddFilenameToManifest(opfDocument, manifestNode, resourceAudio_Filename, GetNextID(ID_OpfPrefix), DataProviderFactory.AUDIO_MP3_MIME_TYPE); } } } // create spine XmlNode spineNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfDocument, true, "spine", null); //opfDocument.GetElementsByTagName("spine")[0]; foreach (string strSmilID in smilIDListInPlayOrder) { XmlNode itemRefNode = opfDocument.CreateElement(null, "itemref", spineNode.NamespaceURI); spineNode.AppendChild(itemRefNode); XmlDocumentHelper.CreateAppendXmlAttribute(opfDocument, itemRefNode, "idref", strSmilID); } if (RequestCancellation) { return; } AddMetadata_Opf(opfDocument); if (RequestCancellation) { opfDocument = null; return; } XmlReaderWriterHelper.WriteXmlDocument(opfDocument, OpfFilePath, null); }
public const string DIAGRAM_CSS_CLASS_PREFIX = @"DIAGRAM "; // space character is crucial! public static string CreateImageDescriptionHTML(string imageDescriptionDirectoryPath, string imageSRC, AlternateContentProperty altProperty, out bool hasMathML, out bool hasSVG, Dictionary <AlternateContent, string> map_AltContentAudio_TO_RelativeExportedFilePath, Dictionary <string, List <string> > map_DiagramElementName_TO_TextualDescriptions, bool onlyLongDesc) { #if DEBUG DebugFix.Assert(!altProperty.IsEmpty); #endif //DEBUG XmlDocument htmlDocument = new XmlDocument(); htmlDocument.XmlResolver = null; htmlDocument.CreateXmlDeclaration("1.0", "utf-8", null); //XmlDocumentType doctype = xmlDoc.CreateDocumentType("html", "", "", null); //XmlDocumentType doctype = xmlDoc.CreateDocumentType("html", null, null, ""); XmlDocumentType doctype = htmlDocument.CreateDocumentType("html", null, null, null); htmlDocument.AppendChild(doctype); XmlNode htmlNode = htmlDocument.CreateElement(null, @"html", DiagramContentModelHelper.NS_URL_XHTML); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, htmlNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS, DiagramContentModelHelper.NS_URL_XHTML); htmlDocument.AppendChild(htmlNode); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, htmlNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM, DiagramContentModelHelper.NS_URL_DIAGRAM); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, htmlNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM_METADATA, DiagramContentModelHelper.NS_URL_DIAGRAM); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, htmlNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DC, DiagramContentModelHelper.NS_URL_DC); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, htmlNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DCTERMS, DiagramContentModelHelper.NS_URL_DCTERMS); //createDiagramHeadMetadata(descriptionDocument, descriptionNode, altProperty); XmlNode head = htmlDocument.CreateElement(null, @"head", htmlNode.NamespaceURI); htmlNode.AppendChild(head); string css = "body { margin: 0; padding: 0; background: white; color: black; font-size: 130%; font-family: serif; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX.Substring(0, Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX.Length - 1) + ":before { content: attr(class); font-family: sans-serif; font-weight: bold; display: block; border: 1px dashed black; padding: 0.5em; margin: 0; margin-bottom: 0.5em; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX + "{ border: 2px solid black; padding: 0.5em; margin: 0; margin-top: 1em; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX + ".d\\:tour { border: 2px solid green; padding: 0.5em; margin: 0; margin-top: 1em; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX + ".d\\:tour:before { content: \"DIAGRAM d\\:tour\"; font-family: sans-serif; font-weight: bold; display: block; border: 1px dashed green; padding: 0.5em; margin: 0; margin-bottom: 0.5em; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX + "img { display: block; padding: 0; margin: 0; margin-top: 1em; margin-bottom: 0.5em; } ." + Daisy3_Export.DIAGRAM_CSS_CLASS_PREFIX + "audio { display: block; padding: 0; margin: 0; margin-top: 1em; margin-bottom: 0.5em; }"; XmlNode style = htmlDocument.CreateElement(@"style", htmlDocument.DocumentElement.NamespaceURI); head.AppendChild(style); XmlDocumentHelper.CreateAppendXmlAttribute(htmlDocument, style, @"type", @"text/css"); XmlNode cssNode = htmlDocument.CreateTextNode(css); style.AppendChild(cssNode); createDiagramBodyContentHTML(htmlDocument, htmlNode, altProperty, imageDescriptionDirectoryPath, out hasMathML, out hasSVG, map_AltContentAudio_TO_RelativeExportedFilePath, map_DiagramElementName_TO_TextualDescriptions, onlyLongDesc); string descFileName = Path.GetFileNameWithoutExtension(imageSRC) + IMAGE_DESCRIPTION_XML_SUFFIX + DataProviderFactory.XHTML_EXTENSION; XmlReaderWriterHelper.WriteXmlDocument(htmlDocument, Path.Combine(imageDescriptionDirectoryPath, descFileName), null); string relativePath = Path.GetFileName(imageDescriptionDirectoryPath); DirectoryInfo d = new DirectoryInfo(imageDescriptionDirectoryPath); DebugFix.Assert(relativePath == d.Name); return(Path.Combine(relativePath, descFileName)); }
public static string CreateImageDescription( bool skipACM, AudioLibPCMFormat pcmFormat, bool encodeToMp3, double bitRate_Mp3, string imageDescriptionDirectoryPath, string imageSRC, AlternateContentProperty altProperty, Dictionary <string, List <string> > map_DiagramElementName_TO_TextualDescriptions, Dictionary <AlternateContentProperty, Description> map_AltProperty_TO_Description, Dictionary <AlternateContent, string> map_AltContentAudio_TO_RelativeExportedFilePath ) { #if DEBUG DebugFix.Assert(!altProperty.IsEmpty); #endif //DEBUG XmlDocument descriptionDocument = new XmlDocument(); //m_AltProperrty_DiagramDocument.Add(altProperty, descriptionDocument); // <?xml-stylesheet type="text/xsl" href="desc2html.xsl"?> //string processingInstructionData = "type=\"text/xsl\" href=\"desc2html.xsl\""; //descriptionDocument.AppendChild(descriptionDocument.CreateProcessingInstruction("xml-stylesheet", processingInstructionData)); //string xsltFileName = "desc2html.xsl"; //string sourceXsltPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, xsltFileName); //string destXsltPath = Path.Combine(imageDescriptionDirectoryPath, xsltFileName); //if (!File.Exists(destXsltPath)) File.Copy(sourceXsltPath, destXsltPath); XmlNode descriptionNode = descriptionDocument.CreateElement( DiagramContentModelHelper.NS_PREFIX_DIAGRAM, DiagramContentModelHelper.StripNSPrefix(DiagramContentModelHelper.D_Description), DiagramContentModelHelper.NS_URL_DIAGRAM); XmlDocumentHelper.CreateAppendXmlAttribute(descriptionDocument, descriptionNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS, DiagramContentModelHelper.NS_URL_ZAI); descriptionDocument.AppendChild(descriptionNode); XmlDocumentHelper.CreateAppendXmlAttribute(descriptionDocument, descriptionNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM, DiagramContentModelHelper.NS_URL_DIAGRAM); XmlDocumentHelper.CreateAppendXmlAttribute(descriptionDocument, descriptionNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DIAGRAM_METADATA, DiagramContentModelHelper.NS_URL_DIAGRAM); XmlDocumentHelper.CreateAppendXmlAttribute(descriptionDocument, descriptionNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DC, DiagramContentModelHelper.NS_URL_DC); XmlDocumentHelper.CreateAppendXmlAttribute(descriptionDocument, descriptionNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + DiagramContentModelHelper.NS_PREFIX_DCTERMS, DiagramContentModelHelper.NS_URL_DCTERMS); createDiagramHeadMetadata(descriptionDocument, descriptionNode, altProperty); createDiagramBodyContent(skipACM, descriptionDocument, descriptionNode, altProperty, map_DiagramElementName_TO_TextualDescriptions, imageDescriptionDirectoryPath, map_AltProperty_TO_Description, encodeToMp3, bitRate_Mp3, pcmFormat, map_AltContentAudio_TO_RelativeExportedFilePath); string descFileName = Path.GetFileNameWithoutExtension(imageSRC) + IMAGE_DESCRIPTION_XML_SUFFIX + DataProviderFactory.XML_EXTENSION; XmlReaderWriterHelper.WriteXmlDocument(descriptionDocument, Path.Combine(imageDescriptionDirectoryPath, descFileName), null); string relativePath = Path.GetFileName(imageDescriptionDirectoryPath); DirectoryInfo d = new DirectoryInfo(imageDescriptionDirectoryPath); DebugFix.Assert(relativePath == d.Name); return(Path.Combine(relativePath, descFileName)); }
private void transformBook() { //FileInfo DTBFilePathInfo = new FileInfo(m_Book_FilePath); //switch (DTBFilePathInfo.Extension) //int indexOfDot = m_Book_FilePath.LastIndexOf('.'); //if (indexOfDot < 0 || indexOfDot == m_Book_FilePath.Length - 1) //{ // return; //} if (RequestCancellation) { return; } string extension = Path.GetExtension(m_Book_FilePath); //m_Book_FilePath.Substring(indexOfDot); if (!string.IsNullOrEmpty(extension)) { bool isHTML = extension.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) || extension.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase); bool isXML = extension.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase); if (extension.Equals(".opf", StringComparison.OrdinalIgnoreCase)) { m_OPF_ContainerRelativePath = null; openAndParseOPF(m_Book_FilePath); } else if ( isHTML || isXML ) { if (isHTML) { //MessageBox.Show("(X)HTML support is experimental and incomplete, please use with caution!"); string htmlPath = m_Book_FilePath; string parent = Path.GetDirectoryName(m_Book_FilePath); string fileName = Path.GetFileNameWithoutExtension(m_Book_FilePath); m_Book_FilePath = Path.Combine(parent, fileName + ".opf"); reInitialiseProjectSpine(); List <string> spineOfContentDocuments = new List <string>(); spineOfContentDocuments.Add(Path.GetFileName(htmlPath)); List <Dictionary <string, string> > spineItemsAttributes = new List <Dictionary <string, string> >(); spineItemsAttributes.Add(new Dictionary <string, string>()); parseContentDocuments(spineOfContentDocuments, new Dictionary <string, string>(), spineItemsAttributes, null, null); } else if (isXML && FileDataProvider.NormaliseFullFilePath(m_Book_FilePath).IndexOf( @"META-INF" //+ Path.DirectorySeparatorChar + '/' + @"container.xml" , StringComparison.OrdinalIgnoreCase) >= 0) { parseContainerXML(m_Book_FilePath); } else { XmlDocument contentXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(m_Book_FilePath, true, true); if (parseContentDocParts(m_Book_FilePath, m_Project, contentXmlDoc, Path.GetFileName(m_Book_FilePath), DocumentMarkupType.NA)) { return; // user cancel } } } else if (extension.Equals(DataProviderFactory.EPUB_EXTENSION, StringComparison.OrdinalIgnoreCase) || extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { unzipEPubAndParseOpf(); } else { return; } } else { return; } if (RequestCancellation) { return; } if (m_PackageUniqueIdAttr != null) { m_PublicationUniqueIdentifier = m_PublicationUniqueIdentifier_OPF; m_PublicationUniqueIdentifierNode = m_PublicationUniqueIdentifierNode_OPF; } metadataPostProcessing(m_Book_FilePath, m_Project); /* * if (!String.IsNullOrEmpty(m_PublicationUniqueIdentifier)) * { * Metadata meta = addMetadata("dc:Identifier", m_PublicationUniqueIdentifier, m_PublicationUniqueIdentifierNode); * meta.IsMarkedAsPrimaryIdentifier = true; * } * //if no unique publication identifier could be determined, see how many identifiers there are * //if there is only one, then make that the unique publication identifier * //this code assumes that all metadata parsing has been completed, which seems to be the case * //at the moment. however, should additional documents start getting parsed for metadata, * //then this code should be moved to a spot after that parsing has finished. * else * { * if (m_Project.Presentations.Count > 0) * { * List<Metadata> identifiers = new List<Metadata>(); * * foreach (Metadata md in m_Project.Presentations.Get(0).Metadatas.ContentsAs_YieldEnumerable) * { * //get this metadata's definition (and search synonyms too) * MetadataDefinition definition = SupportedMetadata_Z39862005.DefinitionSet.GetMetadataDefinition( * md.NameContentAttribute.Name, true); * * if (definition.Name == "dc:Identifier") identifiers.Add(md); * } * * //if there is only one identifier, then make it the publication UID * if (identifiers.Count == 1) * { * identifiers[0].IsMarkedAsPrimaryIdentifier = true; * * //if dtb:uid is our only identifier, rename it dc:identifier * if (identifiers[0].NameContentAttribute.Name == "dtb:uid") * identifiers[0].NameContentAttribute.Name = "dc:Identifier"; * } * } * } * * //add any missing required metadata entries * IEnumerable<Metadata> metadatas = * m_Project.Presentations.Get(0).Metadatas.ContentsAs_YieldEnumerable; * foreach (MetadataDefinition metadataDefinition in SupportedMetadata_Z39862005.DefinitionSet.Definitions) * { * if (!metadataDefinition.IsReadOnly && metadataDefinition.Occurrence == MetadataOccurrence.Required) * { * bool found = false; * foreach (Metadata m in metadatas) * { * if (m.NameContentAttribute.Name.ToLower() == metadataDefinition.Name.ToLower()) * { * found = true; * break; * } * } * if (!found) * { * Metadata metadata = m_Project.Presentations.Get(0).MetadataFactory.CreateMetadata(); * metadata.NameContentAttribute = new MetadataAttribute(); * metadata.NameContentAttribute.Name = metadataDefinition.Name; * metadata.NameContentAttribute.Value = SupportedMetadata_Z39862005.MagicStringEmpty; * m_Project.Presentations.Get(0).Metadatas.Insert * (m_Project.Presentations.Get(0).Metadatas.Count, metadata); * } * * } * } * */ if (RequestCancellation) { return; } reportProgress(100, UrakawaSDK_daisy_Lang.TransformComplete); }
private void parseSmil(string fullSmilPath) { if (RequestCancellation) { return; } XmlDocument smilXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullSmilPath, false, false); if (RequestCancellation) { return; } //we skip SMIL metadata parsing (we get publication metadata only from OPF and DTBOOK/XHTMLs) //parseMetadata(smilXmlDoc); //XmlNodeList allTextNodes = smilXmlDoc.GetElementsByTagName("text"); //if (allTextNodes.Count == 0) //{ // return; //} //reportProgress(-1, "Parsing SMIL: [" + Path.GetFileName(fullSmilPath) + "]"); foreach (XmlNode textNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(smilXmlDoc, true, "text", null, false)) { XmlAttributeCollection textNodeAttrs = textNode.Attributes; if (textNodeAttrs == null || textNodeAttrs.Count == 0) { continue; } XmlNode textNodeAttrSrc = textNodeAttrs.GetNamedItem("src"); if (textNodeAttrSrc == null || String.IsNullOrEmpty(textNodeAttrSrc.Value)) { continue; } string src = FileDataProvider.UriDecode(textNodeAttrSrc.Value); int index = src.LastIndexOf('#'); if (index == src.Length - 1) { return; } string srcFragmentId = src.Substring(index + 1); TreeNode textTreeNode = m_Project.Presentations.Get(0).RootNode.GetFirstDescendantOrSelfWithXmlID(srcFragmentId); if (textTreeNode == null) { continue; } ManagedAudioMedia textTreeNodeAudio = textTreeNode.GetManagedAudioMedia(); if (textTreeNodeAudio != null) { //Ignore. continue; } XmlNode parent = textNode.ParentNode; if (parent != null && parent.LocalName == "a") { parent = parent.ParentNode; } if (parent == null) { continue; } if (parent.LocalName != "par") { //System.Diagnostics.Debug.Fail("Text node in SMIL has no parallel time container as parent ! {0}", parent.Name); continue; } XmlNodeList textPeers = parent.ChildNodes; foreach (XmlNode textPeerNode in textPeers) { if (RequestCancellation) { return; } if (textPeerNode.NodeType != XmlNodeType.Element) { continue; } if (textPeerNode.LocalName == "audio") { addAudio(textTreeNode, textPeerNode, false, fullSmilPath); break; } else if (textPeerNode.LocalName == "a") { XmlNodeList aChildren = textPeerNode.ChildNodes; foreach (XmlNode aChild in aChildren) { if (aChild.LocalName == "audio") { addAudio(textTreeNode, aChild, false, fullSmilPath); break; } } } else if (textPeerNode.LocalName == "seq") { #if DEBUG Debugger.Break(); #endif //DEBUG XmlNodeList seqChildren = textPeerNode.ChildNodes; foreach (XmlNode seqChild in seqChildren) { if (seqChild.LocalName == "audio") { addAudio(textTreeNode, seqChild, true, fullSmilPath); } } #if ENABLE_SEQ_MEDIA SequenceMedia seqManAudioMedia = textTreeNode.GetManagedAudioSequenceMedia(); if (seqManAudioMedia == null) { Debug.Fail("This should never happen !"); break; } ManagedAudioMedia managedAudioMedia = textTreeNode.Presentation.MediaFactory.CreateManagedAudioMedia(); AudioMediaData mediaData = textTreeNode.Presentation.MediaDataFactory.CreateAudioMediaData(); managedAudioMedia.AudioMediaData = mediaData; foreach (Media seqChild in seqManAudioMedia.ChildMedias.ContentsAs_Enumerable) { ManagedAudioMedia seqManMedia = (ManagedAudioMedia)seqChild; // WARNING: WavAudioMediaData implementation differs from AudioMediaData: // the latter is naive and performs a stream binary copy, the latter is optimized and re-uses existing WavClips. // WARNING 2: The audio data from the given parameter gets emptied ! mediaData.MergeWith(seqManMedia.AudioMediaData); //Stream stream = seqManMedia.AudioMediaData.OpenPcmInputStream(); //try //{ // mediaData.AppendPcmData(stream, null); //} //finally //{ // stream.Close(); //} //seqManMedia.AudioMediaData.Delete(); // doesn't actually removes the FileDataProviders (need to call Presentation.Cleanup()) ////textTreeNode.Presentation.DataProviderManager.RemoveDataProvider(); } ChannelsProperty chProp = textTreeNode.GetChannelsProperty(); chProp.SetMedia(m_audioChannel, null); chProp.SetMedia(m_audioChannel, managedAudioMedia); #endif //ENABLE_SEQ_MEDIA break; } } } }
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); //} } }
public void ImportDiagramXML(string xmlFilePath) { Tuple <TreeNode, TreeNode> selection = m_UrakawaSession.GetTreeNodeSelection(); TreeNode treeNode = selection.Item2 ?? selection.Item1; var altProp = treeNode.GetAlternateContentProperty(); XmlDocument diagramXML = XmlReaderWriterHelper.ParseXmlDocument(xmlFilePath, false, false); XmlNode description = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(diagramXML, false, "description", DiagramContentModelHelper.NS_URL_DIAGRAM); if (description == null) { return; } XmlAttributeCollection descrAttrs = description.Attributes; if (descrAttrs != null) { for (int i = 0; i < descrAttrs.Count; i++) { XmlAttribute attr = descrAttrs[i]; if (!attr.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XML + ":")) { continue; } Metadata altContMetadata = treeNode.Presentation.MetadataFactory.CreateMetadata(); altContMetadata.NameContentAttribute = new MetadataAttribute(); altContMetadata.NameContentAttribute.Name = attr.Name; altContMetadata.NameContentAttribute.NamespaceUri = XmlReaderWriterHelper.NS_URL_XML; altContMetadata.NameContentAttribute.Value = attr.Value; AlternateContentMetadataAddCommand cmd_AltPropMetadata_XML = treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand( treeNode, altProp, null, altContMetadata, null ); treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadata_XML); } } XmlNode head = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(description, false, "head", DiagramContentModelHelper.NS_URL_DIAGRAM); if (head != null) { foreach (XmlNode metaNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(head, true, "meta", DiagramContentModelHelper.NS_URL_ZAI, false)) { if (metaNode.NodeType != XmlNodeType.Element || metaNode.LocalName != "meta") { #if DEBUG Debugger.Break(); #endif // DEBUG continue; } //XmlNode childMetadata = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(node, false, "meta", DiagramContentModelHelper.NS_URL_ZAI); //if (childMetadata != null) //{ // continue; //} bool foundAtLeastOneChildMeta = false; foreach (XmlNode child in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(metaNode, false, "meta", DiagramContentModelHelper.NS_URL_ZAI, false)) { if (child == metaNode) { continue; } foundAtLeastOneChildMeta = true; break; } if (foundAtLeastOneChildMeta) { continue; } XmlAttributeCollection mdAttributes = metaNode.Attributes; if (mdAttributes == null || mdAttributes.Count <= 0) { continue; } XmlNode attrName = mdAttributes.GetNamedItem("name"); XmlNode attrProperty = mdAttributes.GetNamedItem("property"); string property = (attrName != null && !String.IsNullOrEmpty(attrName.Value)) ? attrName.Value : (attrProperty != null && !String.IsNullOrEmpty(attrProperty.Value) ? attrProperty.Value : null); XmlNode attrContent = mdAttributes.GetNamedItem("content"); string content = (attrContent != null && !String.IsNullOrEmpty(attrContent.Value)) ? attrContent.Value : metaNode.InnerText; if (!( String.IsNullOrEmpty(property) && String.IsNullOrEmpty(content) || !String.IsNullOrEmpty(property) && !String.IsNullOrEmpty(content) )) { continue; } Metadata altContMetadata = treeNode.Presentation.MetadataFactory.CreateMetadata(); altContMetadata.NameContentAttribute = new MetadataAttribute(); altContMetadata.NameContentAttribute.Name = String.IsNullOrEmpty(property) ? DiagramContentModelHelper.NA : property; altContMetadata.NameContentAttribute.NamespaceUri = String.IsNullOrEmpty(property) ? null : ( property.StartsWith(DiagramContentModelHelper.NS_PREFIX_DIAGRAM_METADATA + ":") ? DiagramContentModelHelper.NS_URL_DIAGRAM : (property.StartsWith(SupportedMetadata_Z39862005.NS_PREFIX_DUBLIN_CORE + ":") ? SupportedMetadata_Z39862005.NS_URL_DUBLIN_CORE : null) ) ; altContMetadata.NameContentAttribute.Value = String.IsNullOrEmpty(content) ? DiagramContentModelHelper.NA : content; AlternateContentMetadataAddCommand cmd_AltPropMetadata = treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand( treeNode, altProp, null, altContMetadata, null ); treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadata); bool parentIsMeta = metaNode.ParentNode.LocalName == "meta"; var listAttrs = new List <XmlAttribute>(mdAttributes.Count + (parentIsMeta && metaNode.ParentNode.Attributes != null ? metaNode.ParentNode.Attributes.Count : 0) ); for (int i = 0; i < mdAttributes.Count; i++) { XmlAttribute attribute = mdAttributes[i]; listAttrs.Add(attribute); } if (parentIsMeta && metaNode.ParentNode.Attributes != null) { for (int i = 0; i < metaNode.ParentNode.Attributes.Count; i++) { XmlAttribute attribute = metaNode.ParentNode.Attributes[i]; if (mdAttributes.GetNamedItem(attribute.LocalName, attribute.NamespaceURI) == null) { listAttrs.Add(attribute); } } } foreach (var attribute in listAttrs) { if (attribute.LocalName == DiagramContentModelHelper.Name || attribute.LocalName == DiagramContentModelHelper.Property || attribute.LocalName == DiagramContentModelHelper.Content) { continue; } if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":")) { // } else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS) { // } else { MetadataAttribute metadatattribute = new MetadataAttribute(); metadatattribute.Name = attribute.Name; metadatattribute.NamespaceUri = attribute.Name.IndexOf(':') >= 0 //attribute.Name.Contains(":") ? attribute.NamespaceURI : null; metadatattribute.Value = attribute.Value; AlternateContentMetadataAddCommand cmd_AltPropMetadataAttr = treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand( treeNode, altProp, null, altContMetadata, metadatattribute ); treeNode.Presentation.UndoRedoManager.Execute(cmd_AltPropMetadataAttr); } } } } XmlNode body = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(description, false, "body", DiagramContentModelHelper.NS_URL_DIAGRAM); if (body != null) { diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_Summary); diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_LondDesc); diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_SimplifiedLanguageDescription); diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_Tactile); diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.D_SimplifiedImage); //#if true || SUPPORT_ANNOTATION_ELEMENT // diagramXmlParseBodySpecific(xmlFilePath, treeNode, body, DiagramContentModelHelper.Annotation); //#endif //SUPPORT_ANNOTATION_ELEMENT diagramXmlParseBody(xmlFilePath, treeNode, body); } OnPanelLoaded(); }
public void ParseXml() { XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(m_ConfigurationFilePath, false, false); XmlNode importNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc.DocumentElement, true, "import", xmlDoc.DocumentElement.NamespaceURI); foreach (XmlNode n in importNode.ChildNodes) { string innerText = n.InnerText; if (n.LocalName == "obiprojectdirectory") { m_ObiProjectDirectoryPath = innerText.Trim(); } else if (n.LocalName == "audiosamplerate") { string strSampleRate = innerText.Trim(); m_ImportSampleRate = int.Parse(strSampleRate); m_ImportSampleRateEnum = strSampleRate == "44100" ? AudioLib.SampleRate.Hz44100 : strSampleRate == "22050" ? AudioLib.SampleRate.Hz22050 : AudioLib.SampleRate.Hz11025; } else if (n.LocalName == "audiochannels") { string strChannels = innerText.Trim(); m_ImportChannels = int.Parse(strChannels.Trim()); } } foreach (XmlNode exportNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(xmlDoc.DocumentElement, true, "export", xmlDoc.DocumentElement.NamespaceURI, false)) { ExportFormat exportStandards = ExportFormat.DAISY3_0; string exportDirectory = null; bool encodeExportedAudioFiles = false; AudioLib.AudioFileFormats encodingAudioFileFormat = AudioLib.AudioFileFormats.WAV; AudioLib.SampleRate exportSampleRate = AudioLib.SampleRate.Hz44100; int exportChannels = 1; double exportEncodingBitrate = 64; foreach (XmlNode n in exportNode.ChildNodes) { if (n.LocalName == "directory") { exportDirectory = n.InnerText.Trim(); } else if (n.LocalName == "standard") { string strStandard = n.InnerText.Trim(); exportStandards = strStandard == "daisy2.02" ? ExportFormat.DAISY2_02 : strStandard == "daisy3" ? ExportFormat.DAISY3_0 : ExportFormat.EPUB3; } else if (n.LocalName == "audioencoding") { string strEncoding = n.InnerText.Trim(); encodeExportedAudioFiles = strEncoding.ToLower() != "wav"; if (encodeExportedAudioFiles) { encodingAudioFileFormat = (strEncoding.ToLower() == "mp4" || strEncoding.ToLower() == "m4a") ? AudioLib.AudioFileFormats.MP4 : AudioLib.AudioFileFormats.MP3; } } else if (n.LocalName == "bitrate") { string strBitrate = n.InnerText.Trim(); exportEncodingBitrate = int.Parse(strBitrate); } else if (n.LocalName == "audiosamplerate") { string strSampleRate = n.InnerText; exportSampleRate = strSampleRate == "44100" ? AudioLib.SampleRate.Hz44100 : strSampleRate == "22050" ? AudioLib.SampleRate.Hz22050 : AudioLib.SampleRate.Hz11025; } else if (n.LocalName == "audiochannels") { string strChannels = n.InnerText; exportChannels = int.Parse(strChannels.Trim()); } } ExportParameters exportObject = new ExportParameters(exportStandards, exportDirectory, encodeExportedAudioFiles, encodingAudioFileFormat, exportSampleRate, exportChannels, exportEncodingBitrate); // assign export parameters to respective properties if (exportObject.ExportStandards == ExportFormat.DAISY3_0) { m_DAISY3ExportParameters = exportObject; } else if (exportObject.ExportStandards == ExportFormat.DAISY2_02) { m_DAISY202ExportParameters = exportObject; } else if (exportObject.ExportStandards == ExportFormat.EPUB3) { m_EPUB3ExportParameters = exportObject; } Console.WriteLine("Config file export parameters: " + exportObject.ExportStandards); Console.WriteLine("export channels: " + exportObject.ExportChannels + ", directory:" + exportObject.ExportDirectory); Console.WriteLine("encoding: " + exportObject.EncodeExportedAudioFiles + " " + exportObject.EncodingAudioFileFormat + ", bit rate:" + exportObject.ExportEncodingBitrate + ", sample rate:" + exportObject.ExportSampleRate); } xmlDoc = null; }