public static string GetJobOutputEpubFilePath(string id) { XmlDocument doc = GetJob(id); XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("ns", "http://www.daisy.org/ns/pipeline/data"); XmlNodeList nodes = doc.SelectNodes("//ns:job/ns:results/ns:result[@name='output-dir']/ns:result[contains(@file, '.epub')]", manager); if (nodes.Count <= 0) { nodes = doc.SelectNodes("//ns:job/ns:results/ns:result[@name='output']/ns:result[contains(@file, '.epub')]", manager); } if (nodes.Count > 0) { string path = nodes[0].Attributes.GetNamedItem("file").Value; path = FileDataProvider.UriDecode(path); path = path.Replace("file:/", "").Replace('/', '\\'); if (path.StartsWith("\\")) { path = path.Substring(1); } return(path); } return(null); }
private void CollectPagesFromPageList(XmlNode navMap) { m_PageReferencesMapDictionaryForNCX = new Dictionary <string, XmlNode>(); //XmlNode pageListNode = XmlDocumentHelper.GetFirstChildElementWithName(navMap, true, "pageList", navMap.NamespaceURI); XmlNode pageListNode = navMap.OwnerDocument.GetElementsByTagName("pageList")[0]; if (pageListNode != null) { foreach (XmlNode pageTargetNode in XmlDocumentHelper.GetChildrenElementsOrSelfWithName(pageListNode, true, "pageTarget", navMap.NamespaceURI, false)) { XmlNode contentNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(pageTargetNode, true, "content", pageTargetNode.NamespaceURI); string urlDecoded = FileDataProvider.UriDecode(contentNode.Attributes.GetNamedItem("src").Value); m_PageReferencesMapDictionaryForNCX.Add(urlDecoded, pageTargetNode); } } }
private void ParseNCXNodes(Presentation presentation, XmlNode node, TreeNode tNode) { //if (node.ChildNodes == null || node.ChildNodes.Count == 0) //{ //System.Windows.Forms.MessageBox.Show("returning " + node.LocalName); //return; //} //else //{ //System.Windows.Forms.MessageBox.Show("working " + node.LocalName); TreeNode treeNode = null; if (node.LocalName == "navPoint") { treeNode = CreateTreeNodeForNavPoint(tNode, node); XmlNode contentNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(node, true, "content", node.NamespaceURI); string urlDecoded = FileDataProvider.UriDecode(contentNode.Attributes.GetNamedItem("src").Value); m_SmilRefToNavPointTreeNodeMap.Add(urlDecoded, treeNode); XmlNode navLabelXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(node, true, "navLabel", node.NamespaceURI); if (navLabelXmlNode != null) { m_NavPointNode_NavLabelMap.Add(treeNode, navLabelXmlNode); } } if (node.ChildNodes == null || node.ChildNodes.Count == 0) { return; } foreach (XmlNode n in node.ChildNodes) { ParseNCXNodes(presentation, n, treeNode != null ? treeNode : tNode); } //} }
protected void addAudio(TreeNode treeNode, XmlNode xmlNode, bool isSequence, string fullSmilPath) { if (RequestCancellation) { return; } string dirPath = Path.GetDirectoryName(fullSmilPath); XmlAttributeCollection audioAttrs = xmlNode.Attributes; if (audioAttrs == null || audioAttrs.Count == 0) { return; } XmlNode audioAttrSrc = audioAttrs.GetNamedItem("src"); if (audioAttrSrc == null || String.IsNullOrEmpty(audioAttrSrc.Value)) { return; } string src = FileDataProvider.UriDecode(audioAttrSrc.Value); XmlNode audioAttrClipBegin = audioAttrs.GetNamedItem("clipBegin"); XmlNode audioAttrClipEnd = audioAttrs.GetNamedItem("clipEnd"); Presentation presentation = treeNode.Presentation; // m_Project.Presentations.Get(0); ManagedAudioMedia media = null; string fullPath = Path.Combine(dirPath, src); fullPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); addOPF_GlobalAssetPath(fullPath); string ext = Path.GetExtension(src); if (ext.Equals(DataProviderFactory.AUDIO_WAV_EXTENSION, StringComparison.OrdinalIgnoreCase)) { FileDataProvider dataProv = null; if (!File.Exists(fullPath)) { Debug.Fail("File not found: " + fullPath); media = null; } else { //bool deleteSrcAfterCompletion = false; string fullWavPath = fullPath; FileDataProvider obj; m_OriginalAudioFile_FileDataProviderMap.TryGetValue(fullWavPath, out obj); if (obj != null) //m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullWavPath)) { if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { DebugFix.Assert(obj.Presentation != presentation); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(((WavClip.PcmFormatAndTime)appData).mFormat); } } if (obj.Presentation != presentation) { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(obj.DataFileFullPath))); dataProv.InitByCopyingExistingFile(obj.DataFileFullPath); //m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Remove(fullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { dataProv.AppData = new WavClip.PcmFormatAndTime(((WavClip.PcmFormatAndTime)appData).mFormat, ((WavClip.PcmFormatAndTime)appData).mTime); } } else { dataProv = obj; // m_OriginalAudioFile_FileDataProviderMap[fullWavPath]; } } else // create FileDataProvider { Stream wavStream = null; try { wavStream = File.Open(fullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); uint dataLength; AudioLibPCMFormat pcmInfo = null; pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { //m_AudioConversionSession.FirstDiscoveredPCMFormat = new PCMFormatInfo(pcmInfo); m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(pcmInfo); } if (RequestCancellation) { return; } //if (m_firstTimePCMFormat) //{ // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); // m_firstTimePCMFormat = false; //} if (!presentation.MediaDataManager.DefaultPCMFormat.Data.IsCompatibleWith(pcmInfo)) { wavStream.Close(); wavStream = null; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ConvertingAudio, Path.GetFileName(fullWavPath))); string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullWavPath); if (RequestCancellation) { return; } dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); if (RequestCancellation) { return; } } else // use original wav file by copying it to data directory { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullWavPath) + " = " + dataProv.DataFileRelativePath); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(fullWavPath))); dataProv.InitByCopyingExistingFile(fullWavPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullWavPath, dataProv); if (RequestCancellation) { return; } } } finally { if (wavStream != null) { wavStream.Close(); } } } } // FileDataProvider key check ends if (RequestCancellation) { return; } media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd, treeNode); //media = addAudioWav ( fullWavPath, deleteSrcAfterCompletion, audioAttrClipBegin, audioAttrClipEnd ); } else if (ext.Equals(DataProviderFactory.AUDIO_MP3_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.AUDIO_MP4_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.AUDIO_MP4_EXTENSION_, StringComparison.OrdinalIgnoreCase)) { if (!File.Exists(fullPath)) { Debug.Fail("File not found: {0}", fullPath); return; } if (RequestCancellation) { return; } reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullPath))); if (RequestCancellation) { return; } string fullMp34PathOriginal = fullPath; FileDataProvider obj; m_OriginalAudioFile_FileDataProviderMap.TryGetValue(fullMp34PathOriginal, out obj); FileDataProvider dataProv = null; if (obj != null) //m_OriginalAudioFile_FileDataProviderMap.ContainsKey(fullMp3PathOriginal)) { if (m_AudioConversionSession.FirstDiscoveredPCMFormat == null) { DebugFix.Assert(obj.Presentation != presentation); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { m_AudioConversionSession.FirstDiscoveredPCMFormat = new AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(((WavClip.PcmFormatAndTime)appData).mFormat); } } if (obj.Presentation != presentation) { dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.CopyingAudio, Path.GetFileName(obj.DataFileFullPath))); dataProv.InitByCopyingExistingFile(obj.DataFileFullPath); //m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Remove(fullMp34PathOriginal); m_OriginalAudioFile_FileDataProviderMap.Add(fullMp34PathOriginal, dataProv); Object appData = obj.AppData; DebugFix.Assert(appData != null); if (appData != null && appData is WavClip.PcmFormatAndTime) { dataProv.AppData = new WavClip.PcmFormatAndTime(((WavClip.PcmFormatAndTime)appData).mFormat, ((WavClip.PcmFormatAndTime)appData).mTime); } } else { dataProv = obj; // m_OriginalAudioFile_FileDataProviderMap[fullMp3PathOriginal]; } } else { string newfullWavPath = m_AudioConversionSession.ConvertAudioFileFormat(fullMp34PathOriginal); dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //Console.WriteLine("Source audio file to SDK audio file map (before creating SDK audio file): " + Path.GetFileName(fullMp34PathOriginal) + " = " + dataProv.DataFileRelativePath); dataProv.InitByMovingExistingFile(newfullWavPath); m_AudioConversionSession.RelocateDestinationFilePath(newfullWavPath, dataProv.DataFileFullPath); m_OriginalAudioFile_FileDataProviderMap.Add(fullMp34PathOriginal, dataProv); if (RequestCancellation) { return; } } if (dataProv != null) { //if (m_firstTimePCMFormat) //{ // Stream wavStream = null; // try // { // wavStream = File.Open(newfullWavPath, FileMode.Open, FileAccess.Read, FileShare.Read); // uint dataLength; // AudioLibPCMFormat pcmInfo = null; // pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength); // presentation.MediaDataManager.DefaultPCMFormat = new PCMFormatInfo(pcmInfo); // } // finally // { // if (wavStream != null) wavStream.Close(); // m_firstTimePCMFormat = false; // } //} if (RequestCancellation) { return; } //media = addAudioWav(newfullWavPath, true, audioAttrClipBegin, audioAttrClipEnd); media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd, treeNode); if (RequestCancellation) { return; } if (media == null) { #if DEBUG Debugger.Break(); #endif } } //} } if (RequestCancellation) { return; } if (media == null) { if (!TreenodesWithoutManagedAudioMediaData.Contains(treeNode)) { TreenodesWithoutManagedAudioMediaData.Add(treeNode); } Debug.Fail("Creating ExternalAudioMedia ??"); Time timeClipBegin = null; ExternalAudioMedia exmedia = presentation.MediaFactory.CreateExternalAudioMedia(); exmedia.Src = src; if (audioAttrClipBegin != null && !string.IsNullOrEmpty(audioAttrClipBegin.Value)) { timeClipBegin = new Time(); try { timeClipBegin = new Time(audioAttrClipBegin.Value); } catch (Exception ex) { string str = "CLIP BEGIN TIME PARSE FAIL: " + audioAttrClipBegin.Value; Console.WriteLine(str); Debug.Fail(str); } exmedia.ClipBegin = timeClipBegin; } if (audioAttrClipEnd != null && !string.IsNullOrEmpty(audioAttrClipEnd.Value)) { Time timeClipEnd = null; try { timeClipEnd = new Time(audioAttrClipEnd.Value); } catch (Exception ex) { string str = "CLIP END TIME PARSE FAIL: " + audioAttrClipEnd.Value; Console.WriteLine(str); Debug.Fail(str); } if (timeClipEnd != null) { try { exmedia.ClipEnd = timeClipEnd; } catch (Exception ex) { string str = "CLIP TIME ERROR (end < begin): " + timeClipBegin + " (" + (audioAttrClipBegin != null ? audioAttrClipBegin.Value : "N/A") + ") / " + timeClipEnd + " (" + audioAttrClipEnd.Value + ")"; Console.WriteLine(str); //Debug.Fail(str); } } } } if (RequestCancellation) { return; } if (media != null) { ChannelsProperty chProp = treeNode.GetChannelsProperty(); if (chProp == null) { chProp = presentation.PropertyFactory.CreateChannelsProperty(); treeNode.AddProperty(chProp); } if (isSequence) { #if ENABLE_SEQ_MEDIA SequenceMedia mediaSeq = chProp.GetMedia(m_audioChannel) as SequenceMedia; if (mediaSeq == null) { mediaSeq = presentation.MediaFactory.CreateSequenceMedia(); mediaSeq.AllowMultipleTypes = false; chProp.SetMedia(m_audioChannel, mediaSeq); } mediaSeq.ChildMedias.Insert(mediaSeq.ChildMedias.Count, media); #else ManagedAudioMedia existingMedia = chProp.GetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel()) as ManagedAudioMedia; if (existingMedia == null) { chProp.SetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel(), media); } else { // 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 ! existingMedia.AudioMediaData.MergeWith(media.AudioMediaData); //Stream stream = seqManMedia.AudioMediaData.OpenPcmInputStream(); //try //{ // mediaData.AppendPcmData(stream, null); //} //finally //{ // stream.Close(); //} } #endif //ENABLE_SEQ_MEDIA } else { //#if DEBUG // ((WavAudioMediaData) media.AudioMediaData).checkWavClips(); //#endif //DEBUG chProp.SetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel(), media); } } else { Debug.Fail("Media could not be created !"); } }
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; } } } }
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); }
public static string GetDescriptionLabel(TreeNode treeNode, int limit) { //if (qname != null) //{ // str = "[" + qname.LocalName + "] "; //} StringBuilder strBuilder = null; int length = 0; TreeNode.StringChunkRange range = treeNode.GetTextFlattened_(); if (range != null && range.First != null && !string.IsNullOrEmpty(range.First.Str)) { strBuilder = new StringBuilder(range.GetLength()); TreeNode.ConcatStringChunks(range, -1, strBuilder); length = strBuilder.Length; if (length > limit) { //string str = strBuilder.ToString(0, 40); //#if NET40 // stringBuilder.Clear(); //#else // stringBuilder.Length = 0; //#endif //NET40 //strBuilder.Append(str); //strBuilder.Append("(...)"); string addon = "(...)"; strBuilder.Insert(limit, addon); length = limit + addon.Length; } } if (treeNode.HasXmlProperty) { string localName = treeNode.GetXmlElementLocalName(); if (localName.Equals("img", StringComparison.OrdinalIgnoreCase) //|| localName.Equals("video", StringComparison.OrdinalIgnoreCase) ) { XmlAttribute xmlAttr = treeNode.GetXmlProperty().GetAttribute("src"); if (xmlAttr != null && !String.IsNullOrEmpty(xmlAttr.Value)) { if (strBuilder == null) { strBuilder = new StringBuilder(); } int l1 = strBuilder.Length; strBuilder.Append(" --> ["); string strAttr = xmlAttr.Value.TrimEnd('/'); strAttr = FileDataProvider.UriDecode(strAttr); int index = strAttr.LastIndexOf('/'); if (index >= 0) { strBuilder.Append(strAttr.Substring(index + 1)); } else { strBuilder.Append(strAttr); } strBuilder.Append("] "); int l2 = strBuilder.Length; int added = l2 - l1; length += added; } } } if (strBuilder == null) { return(""); } return(strBuilder.ToString(0, Math.Min(length, strBuilder.Length))); }
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); //} } }
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 parseHeadLinks(string rootFilePath, Project project, XmlDocument contentDoc) { XmlNode headXmlNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(contentDoc.DocumentElement, true, "head", null); if (headXmlNode == null) { return; } Presentation presentation = project.Presentations.Get(0); List <string> externalFileRelativePaths = new List <string>(); foreach (ExternalFiles.ExternalFileData extData in presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(extData.OriginalRelativePath)) { string fullPath = Path.Combine(Path.GetDirectoryName(rootFilePath), extData.OriginalRelativePath); string relPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); if (!externalFileRelativePaths.Contains(relPath)) { externalFileRelativePaths.Add(relPath); } } } List <XmlNode> externalFilesLinks = new List <XmlNode>(); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "link", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "script", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "style", headXmlNode.NamespaceURI, false)); externalFilesLinks.AddRange(XmlDocumentHelper.GetChildrenElementsOrSelfWithName(headXmlNode, true, "title", headXmlNode.NamespaceURI, false)); foreach (XmlNode linkNode in externalFilesLinks) { TreeNode treeNode = presentation.TreeNodeFactory.Create(); presentation.HeadNode.AppendChild(treeNode); XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); treeNode.AddProperty(xmlProp); xmlProp.SetQName(linkNode.LocalName, headXmlNode.NamespaceURI == linkNode.NamespaceURI ? "" : linkNode.NamespaceURI); //Console.WriteLine("XmlProperty: " + xmlProp.LocalName); foreach (System.Xml.XmlAttribute xAttr in linkNode.Attributes) { if ( //xAttr.LocalName.Equals(XmlReaderWriterHelper.NS_PREFIX_XMLNS, StringComparison.OrdinalIgnoreCase) //|| xAttr.LocalName.Equals("xsi", StringComparison.OrdinalIgnoreCase) xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XMLNS, StringComparison.OrdinalIgnoreCase) || xAttr.LocalName.Equals("space", StringComparison.OrdinalIgnoreCase) && xAttr.NamespaceURI.Equals(XmlReaderWriterHelper.NS_URL_XML, StringComparison.OrdinalIgnoreCase) ) { continue; } xmlProp.SetAttribute(xAttr.Name, linkNode.NamespaceURI == xAttr.NamespaceURI ? "" : xAttr.NamespaceURI, xAttr.Value); if ((xAttr.Name.Equals("href", StringComparison.OrdinalIgnoreCase) || xAttr.Name.Equals("src", StringComparison.OrdinalIgnoreCase)) && !string.IsNullOrEmpty(xAttr.Value) && !FileDataProvider.isHTTPFile(xAttr.Value)) { string urlDecoded = FileDataProvider.UriDecode(xAttr.Value); string fullPath = Path.Combine(Path.GetDirectoryName(rootFilePath), urlDecoded); string pathFromAttr = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); if (!externalFileRelativePaths.Contains(pathFromAttr)) { if (File.Exists(pathFromAttr)) { ExternalFiles.ExternalFileData efd = presentation.ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); try { efd.InitializeWithData(pathFromAttr, urlDecoded, true, null); externalFileRelativePaths.Add(pathFromAttr); addOPF_GlobalAssetPath(pathFromAttr); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } #if DEBUG else { Debugger.Break(); } #endif } } } string innerText = linkNode.InnerText; // includes CDATA sections! (merges "//" javascript comment markers too) if (!string.IsNullOrEmpty(innerText)) { urakawa.media.TextMedia textMedia = presentation.MediaFactory.CreateTextMedia(); textMedia.Text = innerText; ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty(); cProp.SetMedia(presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia); treeNode.AddProperty(cProp); //Console.WriteLine("Link inner text: " + textMedia.Text); } } }
private void handleAdditionalManifestItems(string opfPath, XmlDocument opfXmlDoc) { XmlNode manifNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "manifest", null); if (manifNodeRoot == null) { return; } XmlNodeList listOfManifestItemNodes = manifNodeRoot.ChildNodes; foreach (XmlNode manifItemNode in listOfManifestItemNodes) { if (RequestCancellation) { return; } if (manifItemNode.NodeType != XmlNodeType.Element || manifItemNode.LocalName != "item") { continue; } XmlAttributeCollection manifItemAttributes = manifItemNode.Attributes; if (manifItemAttributes == null) { continue; } XmlNode attrHref = manifItemAttributes.GetNamedItem("href"); XmlNode attrMediaType = manifItemAttributes.GetNamedItem("media-type"); if (attrHref == null || String.IsNullOrEmpty(attrHref.Value) || attrMediaType == null || String.IsNullOrEmpty(attrMediaType.Value)) { continue; } if (FileDataProvider.isHTTPFile(attrHref.Value)) { continue; } if (attrHref.Value.EndsWith(@".opf")) { continue; } if (attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE || attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE_ || attrMediaType.Value == DataProviderFactory.DTBOOK_MIME_TYPE || attrMediaType.Value == DataProviderFactory.DTB_RES_MIME_TYPE || attrMediaType.Value == DataProviderFactory.NCX_MIME_TYPE ) { continue; } string href = FileDataProvider.UriDecode(attrHref.Value); string fullPath = Path.Combine(Path.GetDirectoryName(opfPath), href); fullPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); bool alreadyPreserved = false; foreach ( //ExternalFiles.ExternalFileData exfiledata in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable string path in m_OPF_GlobalAssetPaths ) { if (path == fullPath) { alreadyPreserved = true; break; } //if (!string.IsNullOrEmpty(exfiledata_OriginalRelativePath)) //{ // string fp = Path.Combine(opfPath, exfiledata_OriginalRelativePath); // fp = FileDataProvider.NormaliseFullFilePath(fp).Replace('/', '\\'); //} } if (alreadyPreserved) { continue; } if (!File.Exists(fullPath)) { #if DEBUG Debugger.Break(); #endif continue; } string optionalInfo = null; XmlNode attrProperties = manifItemAttributes.GetNamedItem("properties"); if (attrProperties != null) { optionalInfo = attrProperties.Value; } ExternalFiles.ExternalFileData efd = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); try { efd.InitializeWithData(fullPath, href, true, optionalInfo); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); #if DEBUG Debugger.Break(); #endif } } }
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 parseOpfManifest(XmlDocument opfXmlDoc, out List <string> spine, out Dictionary <string, string> spineAttributes, out List <Dictionary <string, string> > spineItemsAttributes, out string spineMimeType, out string dtbookPath, out string ncxPath, out string navDocPath, out string coverImagePath, string idCoverImageFromMetadata) { spine = new List <string>(); spineAttributes = new Dictionary <string, string>(); spineItemsAttributes = new List <Dictionary <string, string> >(); spineMimeType = null; ncxPath = null; dtbookPath = null; navDocPath = null; coverImagePath = null; XmlNode spineNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "spine", null); if (spineNodeRoot != null) { XmlAttributeCollection spineAttrs = spineNodeRoot.Attributes; if (spineAttrs != null && spineAttrs.Count > 0) { foreach (XmlAttribute spineAttr in spineAttrs) { if (spineAttr.LocalName != "id" && spineAttr.LocalName != "toc") { spineAttributes.Add(spineAttr.Name, spineAttr.Value); } } } XmlNodeList listOfSpineItemNodes = spineNodeRoot.ChildNodes; foreach (XmlNode spineItemNode in listOfSpineItemNodes) { if (RequestCancellation) { return; } if (spineItemNode.NodeType != XmlNodeType.Element || spineItemNode.LocalName != "itemref") { continue; } XmlAttributeCollection spineItemAttributes = spineItemNode.Attributes; if (spineItemAttributes == null || spineItemAttributes.Count <= 0) { continue; } XmlNode attrIdRef = spineItemAttributes.GetNamedItem("idref"); if (attrIdRef != null && !string.IsNullOrEmpty(attrIdRef.Value)) { spine.Add(attrIdRef.Value); Dictionary <string, string> dict = new Dictionary <string, string>(); spineItemsAttributes.Add(dict); foreach (XmlAttribute spineItemAttr in spineItemAttributes) { if (spineItemAttr.LocalName != "id" && spineItemAttr.LocalName != "idref") { if (spineItemAttr.Name == @"properties") { dict.Add(@"properties_spine", spineItemAttr.Value); } else { dict.Add(spineItemAttr.Name, spineItemAttr.Value); } } } } } } XmlNode manifNodeRoot = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(opfXmlDoc, true, "manifest", null); if (manifNodeRoot == null) { return; } XmlNodeList listOfManifestItemNodes = manifNodeRoot.ChildNodes; foreach (XmlNode manifItemNode in listOfManifestItemNodes) { if (RequestCancellation) { return; } if (manifItemNode.NodeType != XmlNodeType.Element || manifItemNode.LocalName != "item") { continue; } XmlAttributeCollection manifItemAttributes = manifItemNode.Attributes; if (manifItemAttributes == null) { continue; } XmlNode attrHref = manifItemAttributes.GetNamedItem("href"); XmlNode attrMediaType = manifItemAttributes.GetNamedItem("media-type"); if (attrHref == null || String.IsNullOrEmpty(attrHref.Value) || attrMediaType == null || String.IsNullOrEmpty(attrMediaType.Value)) { continue; } string href = FileDataProvider.UriDecode(attrHref.Value); XmlNode attrProperties = manifItemAttributes.GetNamedItem("properties"); if (attrProperties != null && attrProperties.Value.Contains("cover-image")) { DebugFix.Assert(attrMediaType.Value == DataProviderFactory.IMAGE_SVG_MIME_TYPE || attrMediaType.Value == DataProviderFactory.IMAGE_JPG_MIME_TYPE || attrMediaType.Value == DataProviderFactory.IMAGE_BMP_MIME_TYPE || attrMediaType.Value == DataProviderFactory.IMAGE_PNG_MIME_TYPE || attrMediaType.Value == DataProviderFactory.IMAGE_GIF_MIME_TYPE ); coverImagePath = href; } XmlNode attrId = manifItemAttributes.GetNamedItem("id"); if (string.IsNullOrEmpty(coverImagePath) && attrId != null && attrId.Value == idCoverImageFromMetadata) { coverImagePath = href; } if (attrMediaType.Value != DataProviderFactory.SMIL_MIME_TYPE // yep! (EPUB3) && (attrMediaType.Value == DataProviderFactory.SMIL_MIME_TYPE_ || attrMediaType.Value == DataProviderFactory.XHTML_MIME_TYPE || attrMediaType.Value == DataProviderFactory.IMAGE_SVG_MIME_TYPE)) { if (attrProperties != null && attrProperties.Value.Contains("nav")) { DebugFix.Assert(attrMediaType.Value == DataProviderFactory.XHTML_MIME_TYPE); navDocPath = href; } if (attrId != null) { int i = spine.IndexOf(attrId.Value); if (i >= 0) { spine[i] = href; //if (!string.IsNullOrEmpty(spineMimeType) // && spineMimeType != attrMediaType.Value) //{ // System.Diagnostics.Debug.Fail(String.Format("Spine contains different mime-types ?! {0} vs {1}", attrMediaType.Value, spineMimeType)); //} spineMimeType = attrMediaType.Value; if (attrProperties != null) { Dictionary <string, string> dict = spineItemsAttributes[i]; dict.Add( @"properties_manifest" //attrProperties.Name , attrProperties.Value); //string val; //dict.TryGetValue(attrProperties.Name, out val); //if (!string.IsNullOrEmpty(val)) //{ // dict.Remove(attrProperties.Name); // dict.Add(attrProperties.Name, val + @" " + attrProperties.Value); //} //else //{ // dict.Add(attrProperties.Name, attrProperties.Value); //} } XmlNode attrMediaOverlay = manifItemAttributes.GetNamedItem("media-overlay"); if (attrMediaOverlay != null && !String.IsNullOrEmpty(attrMediaOverlay.Value)) { foreach (XmlNode manifItemNode2 in listOfManifestItemNodes) { XmlAttributeCollection manifItemAttributes2 = manifItemNode2.Attributes; if (manifItemAttributes2 == null) { continue; } XmlNode attrId2 = manifItemAttributes2.GetNamedItem("id"); XmlNode attrHref2 = manifItemAttributes2.GetNamedItem("href"); if (attrId2 != null && attrId2.Value == attrMediaOverlay.Value && attrHref2 != null && !string.IsNullOrEmpty(attrHref2.Value)) { Dictionary <string, string> dict = spineItemsAttributes[i]; dict.Add(attrMediaOverlay.Name, FileDataProvider.UriDecode(attrHref2.Value)); } } } } } } else if (attrMediaType.Value == DataProviderFactory.DTBOOK_MIME_TYPE || attrMediaType.Value == DataProviderFactory.XML_MIME_TYPE && href.EndsWith(DataProviderFactory.XML_EXTENSION)) { dtbookPath = href; } else if (attrMediaType.Value == DataProviderFactory.NCX_MIME_TYPE || attrMediaType.Value == DataProviderFactory.XML_MIME_TYPE && href.EndsWith(DataProviderFactory.NCX_EXTENSION)) { ncxPath = href; } //else if (attrMediaType.Value == DataProviderFactory.STYLE_CSS_MIME_TYPE // || attrMediaType.Value == DataProviderFactory.STYLE_PLS_MIME_TYPE) //{ // AddExternalFilesToXuk(m_Project.Presentations.Get(0), attrHref.Value); //} //else if (attrMediaType.Value == "image/jpeg" //|| attrMediaType.Value == "audio/mpeg" //|| attrMediaType.Value == DataProviderFactory.XML_TEXT_MIME_TYPE //|| attrMediaType.Value == "application/vnd.adobe.page-template+xml" //|| attrMediaType.Value == "application/oebps-page-map+xml" //|| attrMediaType.Value == DataProviderFactory.DTB_RES_MIME_TYPE) //{ // // Ignore //} } }
private TextElement walkBookTreeAndGenerateFlowDocument_audio_video(TreeNode node, TextElement parent, string textMedia) { // if (node.Children.Count != 0 || textMedia != null && !String.IsNullOrEmpty(textMedia)) // { //#if DEBUG // Debugger.Break(); //#endif // throw new Exception("Node has children or text exists when processing video ??"); // } XmlProperty xmlProp = node.GetXmlProperty(); bool isSource = "source".Equals(xmlProp.LocalName, StringComparison.OrdinalIgnoreCase); XmlProperty xmlProp_ = xmlProp; if (isSource && node.Parent != null) { xmlProp_ = node.Parent.GetXmlProperty(); } AbstractVideoMedia videoMedia = node.GetVideoMedia(); var videoMedia_ext = videoMedia as ExternalVideoMedia; var videoMedia_man = videoMedia as ManagedVideoMedia; Media audioMedia = node.GetMediaInChannel <AudioXChannel>(); // as AbstractAudioMedia; var audioMedia_ext = audioMedia as ExternalAudioMedia; var audioMedia_man = audioMedia as ManagedAudioMedia; string dirPath = Path.GetDirectoryName(m_TreeNode.Presentation.RootUri.LocalPath); string videoPath = null; if (videoMedia_ext != null) { #if DEBUG Debugger.Break(); #endif //DEBUG videoPath = Path.Combine(dirPath, videoMedia_ext.Src); } else if (videoMedia_man != null) { #if DEBUG XmlAttribute srcAttr = xmlProp.GetAttribute("src"); DebugFix.Assert(videoMedia_man.VideoMediaData.OriginalRelativePath == FileDataProvider.UriDecode(srcAttr.Value)); #endif //DEBUG var fileDataProv = videoMedia_man.VideoMediaData.DataProvider as FileDataProvider; if (fileDataProv != null) { videoPath = fileDataProv.DataFileFullPath; } } string audioPath = null; if (audioMedia_ext != null) { #if DEBUG Debugger.Break(); #endif //DEBUG audioPath = Path.Combine(dirPath, audioMedia_ext.Src); } else if (audioMedia_man != null) { #if DEBUG XmlAttribute srcAttr = xmlProp.GetAttribute("src"); DebugFix.Assert(audioMedia_man.AudioMediaData.OriginalRelativePath == FileDataProvider.UriDecode(srcAttr.Value)); #endif //DEBUG var fileDataProv = audioMedia_man.AudioMediaData.DataProvider as FileDataProvider; if (fileDataProv != null) { audioPath = fileDataProv.DataFileFullPath; } } if ( (videoPath == null || FileDataProvider.isHTTPFile(videoPath)) && (audioPath == null || FileDataProvider.isHTTPFile(audioPath)) ) { #if DEBUG Debugger.Break(); #endif //DEBUG return(walkBookTreeAndGenerateFlowDocument_Section(node, parent, textMedia, null)); } string path = string.IsNullOrEmpty(videoPath) ? audioPath : videoPath; var uri = new Uri(path, UriKind.Absolute); string videoAudioAlt = null; XmlAttribute altAttr = xmlProp_.GetAttribute("alt"); if (altAttr != null) { videoAudioAlt = altAttr.Value; } bool parentHasBlocks = parent is TableCell || parent is Section || parent is Floater || parent is Figure || parent is ListItem; var videoAudioPanel = new StackPanel(); videoAudioPanel.Orientation = Orientation.Vertical; //videoPanel.LastChildFill = true; if (!string.IsNullOrEmpty(videoAudioAlt)) { var tb = new TextBlock(new Run(videoAudioAlt)) { HorizontalAlignment = HorizontalAlignment.Center, TextWrapping = TextWrapping.Wrap }; videoAudioPanel.Children.Add(tb); } //videoPanel.Children.Add(mediaElement); var slider = new Slider(); slider.Focusable = false; slider.TickPlacement = TickPlacement.None; slider.IsMoveToPointEnabled = true; slider.Minimum = 0; slider.Maximum = 100; slider.Visibility = Visibility.Hidden; videoAudioPanel.Children.Add(slider); var timeLabel = new TextBlock(); timeLabel.Focusable = false; //timeLabel.IsEnabled = false; timeLabel.TextWrapping = TextWrapping.NoWrap; //timeLabel.TextTrimming = TextTrimming.None; timeLabel.HorizontalAlignment = HorizontalAlignment.Stretch; timeLabel.TextAlignment = TextAlignment.Center; timeLabel.Visibility = Visibility.Hidden; videoAudioPanel.Children.Add(timeLabel); var playPause = new Button() { HorizontalAlignment = HorizontalAlignment.Center, FontWeight = FontWeights.Heavy, Content = new Run("Play / Pause") }; //var border_ = new Border() // { // BorderThickness = new Thickness(2.0), // BorderBrush = ColorBrushCache.Get(Settings.Default.Document_Color_Font_NoAudio), // Padding = new Thickness(4), // Child = playPause // }; videoAudioPanel.Children.Add(playPause); videoAudioPanel.HorizontalAlignment = HorizontalAlignment.Stretch; videoAudioPanel.VerticalAlignment = VerticalAlignment.Top; var panelBorder = new Border(); panelBorder.HorizontalAlignment = HorizontalAlignment.Stretch; panelBorder.VerticalAlignment = VerticalAlignment.Top; panelBorder.Child = videoAudioPanel; panelBorder.Padding = new Thickness(4); panelBorder.BorderBrush = ColorBrushCache.Get(Settings.Default.Document_Color_Font_Audio); panelBorder.BorderThickness = new Thickness(2.0); if (parentHasBlocks) { Block vidContainer = new BlockUIContainer(panelBorder); vidContainer.TextAlignment = TextAlignment.Center; setTag(vidContainer, node); addBlock(parent, vidContainer); } else { Inline vidContainer = new InlineUIContainer(panelBorder); setTag(vidContainer, node); addInline(parent, vidContainer); } MediaElement medElement_WINDOWS_MEDIA_PLAYER = null; #if ENABLE_WPF_MEDIAKIT MediaUriElement medElement_MEDIAKIT_DIRECTSHOW = null; #endif //ENABLE_WPF_MEDIAKIT var reh = (Action <object, RoutedEventArgs>)( (object obj, RoutedEventArgs rev) => { #if ENABLE_WPF_MEDIAKIT if (Common.Settings.Default.EnableMediaKit) { medElement_MEDIAKIT_DIRECTSHOW = new MediaUriElement(); } else #endif //ENABLE_WPF_MEDIAKIT { medElement_WINDOWS_MEDIA_PLAYER = new MediaElement(); } #if ENABLE_WPF_MEDIAKIT DebugFix.Assert((medElement_WINDOWS_MEDIA_PLAYER == null) == (medElement_MEDIAKIT_DIRECTSHOW != null)); #else // DISABLE_WPF_MEDIAKIT DebugFix.Assert(medElement_WINDOWS_MEDIA_PLAYER != null); #endif //ENABLE_WPF_MEDIAKIT if (medElement_WINDOWS_MEDIA_PLAYER != null) { medElement_WINDOWS_MEDIA_PLAYER.Stretch = Stretch.Uniform; medElement_WINDOWS_MEDIA_PLAYER.StretchDirection = StretchDirection.DownOnly; } #if ENABLE_WPF_MEDIAKIT if (medElement_MEDIAKIT_DIRECTSHOW != null) { medElement_MEDIAKIT_DIRECTSHOW.Stretch = Stretch.Uniform; medElement_MEDIAKIT_DIRECTSHOW.StretchDirection = StretchDirection.DownOnly; } #endif //ENABLE_WPF_MEDIAKIT FrameworkElement mediaElement = null; if (medElement_WINDOWS_MEDIA_PLAYER != null) { mediaElement = medElement_WINDOWS_MEDIA_PLAYER; } else { mediaElement = medElement_MEDIAKIT_DIRECTSHOW; } mediaElement.Focusable = false; XmlAttribute srcW = xmlProp_.GetAttribute("width"); if (srcW != null) { var d = parseWidthHeight(srcW.Value); if (d > 0) { mediaElement.Width = d; } } XmlAttribute srcH = xmlProp_.GetAttribute("height"); if (srcH != null) { var d = parseWidthHeight(srcH.Value); if (d > 0) { mediaElement.Height = d; } } mediaElement.HorizontalAlignment = HorizontalAlignment.Center; mediaElement.VerticalAlignment = VerticalAlignment.Top; if (!string.IsNullOrEmpty(videoAudioAlt)) { mediaElement.ToolTip = videoAudioAlt; } videoAudioPanel.Children.Insert(0, mediaElement); var actionMediaFailed = new Action <string>( (str) => { m_DocumentPaneView.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { var label = new TextBlock(new Run(str)); label.TextWrapping = TextWrapping.Wrap; //label.Height = 150; var border = new Border(); border.Child = label; border.BorderBrush = ColorBrushCache.Get(Colors.Red); border.BorderThickness = new Thickness(2.0); videoAudioPanel.Children.Insert(0, border); slider.Visibility = Visibility.Hidden; timeLabel.Visibility = Visibility.Hidden; } )); } ); Action actionUpdateSliderFromVideoTime = null; DispatcherTimer _timer = new DispatcherTimer(); _timer.Interval = new TimeSpan(0, 0, 0, 0, 500); _timer.Stop(); _timer.Tick += (object oo, EventArgs ee) => { actionUpdateSliderFromVideoTime.Invoke(); }; if (medElement_WINDOWS_MEDIA_PLAYER != null) { medElement_WINDOWS_MEDIA_PLAYER.ScrubbingEnabled = true; medElement_WINDOWS_MEDIA_PLAYER.LoadedBehavior = MediaState.Manual; medElement_WINDOWS_MEDIA_PLAYER.UnloadedBehavior = MediaState.Stop; bool doNotUpdateVideoTimeWhenSliderChanges = false; actionUpdateSliderFromVideoTime = new Action(() => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } TimeSpan?timeSpan = medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentTime; double timeMS = timeSpan != null ? timeSpan.Value.TotalMilliseconds : 0; //Console.WriteLine("UPDATE: " + timeMS); //if (medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.HasTimeSpan // && timeMS >= medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan.TotalMilliseconds - 50) //{ // medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Stop(); //} doNotUpdateVideoTimeWhenSliderChanges = true; slider.Value = timeMS; }); medElement_WINDOWS_MEDIA_PLAYER.MediaFailed += new EventHandler <ExceptionRoutedEventArgs>( (oo, ee) => { //#if DEBUG // Debugger.Break(); //#endif //DEBUG //medElement_WINDOWS_MEDIA_PLAYER.Source actionMediaFailed.Invoke(uri.ToString() + " \n(" + (ee.ErrorException != null ? ee.ErrorException.Message : "ERROR!") + ")"); } ); medElement_WINDOWS_MEDIA_PLAYER.MediaOpened += new RoutedEventHandler( (oo, ee) => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } slider.Visibility = Visibility.Visible; timeLabel.Visibility = Visibility.Visible; double durationMS = medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan.TotalMilliseconds; timeLabel.Text = Time.Format_Standard(medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan); slider.Maximum = durationMS; // freeze frame (poster) if (medElement_WINDOWS_MEDIA_PLAYER.LoadedBehavior == MediaState.Manual) { medElement_WINDOWS_MEDIA_PLAYER.IsMuted = true; medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); medElement_WINDOWS_MEDIA_PLAYER.IsMuted = false; slider.Value = 0.10; } } ); medElement_WINDOWS_MEDIA_PLAYER.MediaEnded += new RoutedEventHandler( (oo, ee) => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } _timer.Stop(); medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Stop(); actionUpdateSliderFromVideoTime.Invoke(); } ); var mouseButtonEventHandler_WINDOWS_MEDIA_PLAYER = new Action( () => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } if (medElement_WINDOWS_MEDIA_PLAYER.LoadedBehavior != MediaState.Manual) { return; } bool wasPlaying = false; bool wasStopped = false; //Is Active if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Active) { //Is Paused if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentGlobalSpeed == 0.0) { } else //Is Playing { wasPlaying = true; medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } } else if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Stopped) { wasStopped = true; //medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); //medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } double durationMS = medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan.TotalMilliseconds; double timeMS = medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentTime == null || !medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentTime.HasValue ? -1.0 : medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentTime.Value.TotalMilliseconds; if (timeMS == -1.0 || timeMS >= durationMS) { slider.Value = 0.100; } if (!wasPlaying) { _timer.Start(); if (wasStopped) { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); } else { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Resume(); } } else { _timer.Stop(); medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); actionUpdateSliderFromVideoTime.Invoke(); } //if (ee.ChangedButton == MouseButton.Left) //{ //} //else if (ee.ChangedButton == MouseButton.Right) //{ // _timer.Stop(); // //Is Active // if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Active) // { // //Is Paused // if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentGlobalSpeed == 0.0) // { // } // else //Is Playing // { // medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); // } // } // else if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Stopped) // { // medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); // medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); // } // //actionRefreshTime.Invoke(); // slider.Value = 0; //} } ); medElement_WINDOWS_MEDIA_PLAYER.MouseDown += new MouseButtonEventHandler((oo, ee) => mouseButtonEventHandler_WINDOWS_MEDIA_PLAYER()); playPause.Click += new RoutedEventHandler((object sender, RoutedEventArgs e) => mouseButtonEventHandler_WINDOWS_MEDIA_PLAYER()); slider.ValueChanged += new RoutedPropertyChangedEventHandler <double>( (oo, ee) => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } var timeSpan = new TimeSpan(0, 0, 0, 0, (int)Math.Round(slider.Value)); if (doNotUpdateVideoTimeWhenSliderChanges || !_timer.IsEnabled) { double durationMS = medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan.TotalMilliseconds; timeLabel.Text = String.Format( "{0} / {1}", Time.Format_Standard(timeSpan), Time.Format_Standard(medElement_WINDOWS_MEDIA_PLAYER.NaturalDuration.TimeSpan) ); } if (doNotUpdateVideoTimeWhenSliderChanges) { doNotUpdateVideoTimeWhenSliderChanges = false; return; } bool wasPlaying = false; //Is Active if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Active) { //Is Paused if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentGlobalSpeed == 0.0) { } else //Is Playing { wasPlaying = true; medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } } else if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Stopped) { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Seek(timeSpan, TimeSeekOrigin.BeginTime); if (wasPlaying) { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Resume(); } }); bool wasPlayingBeforeDrag = false; slider.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler( (Action <object, DragStartedEventArgs>)( (oo, ee) => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } wasPlayingBeforeDrag = false; //Is Active if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Active) { //Is Paused if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentGlobalSpeed == 0.0) { } else //Is Playing { wasPlayingBeforeDrag = true; medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } } else if (medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentState == ClockState.Stopped) { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Begin(); medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Pause(); } }))); slider.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler( (Action <object, DragCompletedEventArgs>)( (oo, ee) => { if (medElement_WINDOWS_MEDIA_PLAYER == null) { #if DEBUG Debugger.Break(); #endif return; } if (wasPlayingBeforeDrag) { medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Resume(); } wasPlayingBeforeDrag = false; }))); } #if ENABLE_WPF_MEDIAKIT if (medElement_MEDIAKIT_DIRECTSHOW != null) { bool doNotUpdateVideoTimeWhenSliderChanges = false; actionUpdateSliderFromVideoTime = new Action(() => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } long timeVideo = medElement_MEDIAKIT_DIRECTSHOW.MediaPosition; //if (timeMS >= medElement_MEDIAKIT_DIRECTSHOW.MediaDuration - 50 * 10000.0) //{ // medElement_MEDIAKIT_DIRECTSHOW.Stop(); //} double timeMS = timeVideo / 10000.0; //Console.WriteLine("UPDATE: " + timeMS); doNotUpdateVideoTimeWhenSliderChanges = true; slider.Value = timeMS; }); medElement_MEDIAKIT_DIRECTSHOW.MediaFailed += new EventHandler <WPFMediaKit.DirectShow.MediaPlayers.MediaFailedEventArgs>( (oo, ee) => { //#if DEBUG // Debugger.Break(); //#endif //DEBUG //medElement_MEDIAKIT_DIRECTSHOW.Source actionMediaFailed.Invoke(uri.ToString() + " \n(" + (ee.Exception != null ? ee.Exception.Message : ee.Message) + ")"); } ); medElement_MEDIAKIT_DIRECTSHOW.MediaOpened += new RoutedEventHandler( (oo, ee) => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } long durationVideo = medElement_MEDIAKIT_DIRECTSHOW.MediaDuration; if (durationVideo == 0) { return; } //MediaPositionFormat mpf = medElement.CurrentPositionFormat; //MediaPositionFormat.MediaTime double durationMS = durationVideo / 10000.0; slider.Visibility = Visibility.Visible; timeLabel.Visibility = Visibility.Visible; slider.Maximum = durationMS; var durationTimeSpan = new TimeSpan(0, 0, 0, 0, (int)Math.Round(durationMS)); timeLabel.Text = Time.Format_Standard(durationTimeSpan); // freeze frame (poster) if (medElement_MEDIAKIT_DIRECTSHOW.LoadedBehavior == WPFMediaKit.DirectShow.MediaPlayers.MediaState.Manual) { if (false) { double volume = medElement_MEDIAKIT_DIRECTSHOW.Volume; medElement_MEDIAKIT_DIRECTSHOW.Volume = 0; medElement_MEDIAKIT_DIRECTSHOW.Play(); slider.Value = 0.10; medElement_MEDIAKIT_DIRECTSHOW.Pause(); medElement_MEDIAKIT_DIRECTSHOW.Volume = volume; } else { medElement_MEDIAKIT_DIRECTSHOW.Pause(); slider.Value = 0.10; } } } ); medElement_MEDIAKIT_DIRECTSHOW.MediaEnded += new RoutedEventHandler( (oo, ee) => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } _timer.Stop(); medElement_MEDIAKIT_DIRECTSHOW.Pause(); actionUpdateSliderFromVideoTime.Invoke(); // TODO: BaseClasses.cs in WPF Media Kit, // MediaPlayerBase.OnMediaEvent // ==> remove StopGraphPollTimer(); // in case EventCode.Complete. //m_DocumentPaneView.Dispatcher.BeginInvoke( // DispatcherPriority.Background, // (Action)(() => // { // //medElement_MEDIAKIT_DIRECTSHOW.BeginInit(); // medElement_MEDIAKIT_DIRECTSHOW.Source = uri; // //medElement_MEDIAKIT_DIRECTSHOW.EndInit(); // }) // ); } ); medElement_MEDIAKIT_DIRECTSHOW.MediaClosed += new RoutedEventHandler( (oo, ee) => { int debug = 1; } ); var mouseButtonEventHandler_MEDIAKIT_DIRECTSHOW = new Action( () => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } if (medElement_MEDIAKIT_DIRECTSHOW.LoadedBehavior != WPFMediaKit.DirectShow.MediaPlayers.MediaState.Manual) { return; } if (medElement_MEDIAKIT_DIRECTSHOW.IsPlaying) { _timer.Stop(); medElement_MEDIAKIT_DIRECTSHOW.Pause(); actionUpdateSliderFromVideoTime.Invoke(); } else { _timer.Start(); medElement_MEDIAKIT_DIRECTSHOW.Play(); } double durationMS = medElement_MEDIAKIT_DIRECTSHOW.MediaDuration / 10000.0; double timeMS = medElement_MEDIAKIT_DIRECTSHOW.MediaPosition / 10000.0; if (timeMS >= durationMS) { slider.Value = 0.100; } //if (ee.ChangedButton == MouseButton.Left) //{ //} //else if (ee.ChangedButton == MouseButton.Right) //{ // _timer.Stop(); // medElement_MEDIAKIT_DIRECTSHOW.Pause(); // //actionRefreshTime.Invoke(); // slider.Value = 0; //} } ); medElement_MEDIAKIT_DIRECTSHOW.MouseDown += new MouseButtonEventHandler((oo, ee) => mouseButtonEventHandler_MEDIAKIT_DIRECTSHOW()); playPause.Click += new RoutedEventHandler((object sender, RoutedEventArgs e) => mouseButtonEventHandler_MEDIAKIT_DIRECTSHOW()); slider.ValueChanged += new RoutedPropertyChangedEventHandler <double>( (oo, ee) => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } double timeMs = slider.Value; if (doNotUpdateVideoTimeWhenSliderChanges || !_timer.IsEnabled) { var timeSpan = new TimeSpan(0, 0, 0, 0, (int)Math.Round(timeMs)); double durationMS = medElement_MEDIAKIT_DIRECTSHOW.MediaDuration / 10000.0; //MediaPositionFormat.MediaTime //MediaPositionFormat mpf = medElement.CurrentPositionFormat; timeLabel.Text = String.Format( "{0} / {1}", Time.Format_Standard(timeSpan), Time.Format_Standard(new TimeSpan(0, 0, 0, 0, (int)Math.Round(durationMS))) ); } if (doNotUpdateVideoTimeWhenSliderChanges) { doNotUpdateVideoTimeWhenSliderChanges = false; return; } bool wasPlaying = medElement_MEDIAKIT_DIRECTSHOW.IsPlaying; if (wasPlaying) { medElement_MEDIAKIT_DIRECTSHOW.Pause(); } long timeVideo = (long)Math.Round(timeMs * 10000.0); medElement_MEDIAKIT_DIRECTSHOW.MediaPosition = timeVideo; DebugFix.Assert(medElement_MEDIAKIT_DIRECTSHOW.MediaPosition == timeVideo); if (wasPlaying) { medElement_MEDIAKIT_DIRECTSHOW.Play(); } }); bool wasPlayingBeforeDrag = false; slider.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler( (Action <object, DragStartedEventArgs>)( (oo, ee) => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } wasPlayingBeforeDrag = medElement_MEDIAKIT_DIRECTSHOW.IsPlaying; if (wasPlayingBeforeDrag) { medElement_MEDIAKIT_DIRECTSHOW.Pause(); } }))); slider.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler( (Action <object, DragCompletedEventArgs>)( (oo, ee) => { if (medElement_MEDIAKIT_DIRECTSHOW == null) { #if DEBUG Debugger.Break(); #endif return; } if (wasPlayingBeforeDrag) { medElement_MEDIAKIT_DIRECTSHOW.Play(); } wasPlayingBeforeDrag = false; }))); //DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty( // MediaSeekingElement.MediaPositionProperty, // typeof(MediaSeekingElement)); //if (dpd != null) //{ // dpd.AddValueChanged(medElement_MEDIAKIT_DIRECTSHOW, new EventHandler((o, e) => // { // //actionRefreshTime.Invoke(); // //if (!_timer.IsEnabled) // //{ // // _timer.Start(); // //} // })); //} } #endif //ENABLE_WPF_MEDIAKIT if (medElement_WINDOWS_MEDIA_PLAYER != null) { var timeline = new MediaTimeline(); timeline.Source = uri; medElement_WINDOWS_MEDIA_PLAYER.Clock = timeline.CreateClock(true) as MediaClock; medElement_WINDOWS_MEDIA_PLAYER.Clock.Controller.Stop(); //medElement_WINDOWS_MEDIA_PLAYER.Clock.CurrentTimeInvalidated += new EventHandler( //(o, e) => //{ // //actionRefreshTime.Invoke(); // //if (!_timer.IsEnabled) // //{ // // _timer.Start(); // //} //}); } #if ENABLE_WPF_MEDIAKIT if (medElement_MEDIAKIT_DIRECTSHOW != null) { medElement_MEDIAKIT_DIRECTSHOW.BeginInit(); medElement_MEDIAKIT_DIRECTSHOW.Loop = false; medElement_MEDIAKIT_DIRECTSHOW.VideoRenderer = VideoRendererType.VideoMixingRenderer9; // seems to be a multiplicator of 10,000 to get milliseconds medElement_MEDIAKIT_DIRECTSHOW.PreferedPositionFormat = MediaPositionFormat.MediaTime; medElement_MEDIAKIT_DIRECTSHOW.LoadedBehavior = WPFMediaKit.DirectShow.MediaPlayers.MediaState.Manual; medElement_MEDIAKIT_DIRECTSHOW.UnloadedBehavior = WPFMediaKit.DirectShow.MediaPlayers.MediaState.Stop; try { medElement_MEDIAKIT_DIRECTSHOW.Source = uri; medElement_MEDIAKIT_DIRECTSHOW.EndInit(); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif //DEBUG ; // swallow (reported in MediaFailed) } } #endif //ENABLE_WPF_MEDIAKIT }); FlowDocumentLoadedEvents.Add(reh); m_FlowDoc.Loaded += new RoutedEventHandler(reh); var reh2 = (Action <object, RoutedEventArgs>)( (object o, RoutedEventArgs e) => { bool thereWasOne = false; if (medElement_WINDOWS_MEDIA_PLAYER != null) { thereWasOne = true; medElement_WINDOWS_MEDIA_PLAYER.Close(); medElement_WINDOWS_MEDIA_PLAYER = null; } #if ENABLE_WPF_MEDIAKIT if (medElement_MEDIAKIT_DIRECTSHOW != null) { thereWasOne = true; medElement_MEDIAKIT_DIRECTSHOW.Close(); medElement_MEDIAKIT_DIRECTSHOW = null; } #endif //ENABLE_WPF_MEDIAKIT if (thereWasOne) { videoAudioPanel.Children.RemoveAt(0); } }); FlowDocumentUnLoadedEvents.Add(reh2); m_FlowDoc.Unloaded += new RoutedEventHandler(reh2); return(parent); }