public static XmlDocument ParseXmlDocument(string filePath, bool preserveWhiteSpace, bool validate) { XmlDocument xmldoc = null; XmlReaderSettings settings = GetDefaultXmlReaderConfiguration(true, preserveWhiteSpace, validate); XmlReader xmlReader = null; Stream stream = null; try { DebugFix.Assert(File.Exists(filePath)); stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); TextReader reader = new StreamReader(stream, Encoding.UTF8); Uri uri = new Uri(@"file:///" + filePath.Replace('\\', '/'), UriKind.Absolute); string uriStr = uri.ToString(); xmlReader = XmlReader.Create(reader, settings, uriStr); if (xmlReader is XmlTextReader) { if (preserveWhiteSpace) { ((XmlTextReader)xmlReader).WhitespaceHandling = WhitespaceHandling.All; } else { ((XmlTextReader)xmlReader).WhitespaceHandling = WhitespaceHandling.None; } } xmldoc = new XmlDocument(); xmldoc.PreserveWhitespace = preserveWhiteSpace; xmldoc.XmlResolver = null; xmldoc.Load(xmlReader); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif throw new Exception("ParseXmlFromFile", ex); } finally { if (xmlReader != null) { try { xmlReader.Close(); } catch (Exception ex) { Console.WriteLine("!! xmlReader.Close();" + ex.Message); } } if (stream != null) { try { stream.Close(); } catch (Exception ex) { Console.WriteLine("!! stream.Close();" + ex.Message); } try { stream.Dispose(); } catch (Exception ex) { Console.WriteLine("!! stream.Dispose();" + ex.Message); } } } return(xmldoc); }
public void Rename(string prefix) { if (mOpenOutputStream != null) { #if DEBUG Debugger.Break(); #endif return; } if (mOpenInputStreams.Count > 0) { #if DEBUG Debugger.Break(); #endif return; } string oldPrefix = m_NamePrefix; string oldName = DataFileRelativePath; string oldPath = DataFileFullPath; m_NamePrefix = prefix; mDataFileRelativePath = null; string newName = DataFileRelativePath; string newPath = DataFileFullPath; #if DEBUG DebugFix.Assert(!File.Exists(newPath)); #endif #if DEBUG foreach (DataProvider dp in Presentation.DataProviderManager.ManagedObjects.ContentsAs_Enumerable) { if (dp is FileDataProvider) { FileDataProvider fdp = (FileDataProvider)dp; if (fdp == this) { continue; } if (fdp.DataFileFullPath == newPath) { Debugger.Break(); } } } #endif if (!File.Exists(oldPath)) { #if DEBUG Debugger.Break(); #endif HasBeenInitialized = false; return; } try { File.Move(oldPath, DataFileFullPath); try { File.SetAttributes(DataFileFullPath, FileAttributes.Normal); } catch { } HasBeenInitialized = true; } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif m_NamePrefix = oldPrefix; mDataFileRelativePath = oldName; newName = DataFileRelativePath; newPath = DataFileFullPath; } }
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, (m_useTitleInFileName ? title : null), 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 override void DoWork() { if (RequestCancellation) { return; } initializeProject(Path.GetFileName(m_Book_FilePath)); try { transformBook(); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif throw new Exception("Import", ex); } reportProgress(-1, UrakawaSDK_daisy_Lang.SaveXUK); if (RequestCancellation) { return; } //m_Project.SaveXuk(new Uri(m_Xuk_FilePath)); if (IsRenameOfProjectFileAndDirsAllowedAfterImport && m_useTitleInFileName) { string title = GetTitle(m_Project.Presentations.Get(0)); if (!string.IsNullOrEmpty(title)) { string originalXukFilePath = m_Xuk_FilePath; m_Xuk_FilePath = GetXukFilePath(m_outDirectory, m_Book_FilePath, title, m_IsSpine); //deleteDataDirectoryIfEmpty(); //m_Project.Presentations.Get(0).DataProviderManager.SetDataFileDirectoryWithPrefix(Path.GetFileNameWithoutExtension(m_Xuk_FilePath)); Presentation presentation = m_Project.Presentations.Get(0); string dataFolderPath = presentation.DataProviderManager.DataFileDirectoryFullPath; presentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(m_Xuk_FilePath)); string newDataFolderPath = presentation.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); presentation.DataProviderManager.SetCustomDataFileDirectory(m_dataFolderPrefix); } } } }// end of rename code m_Project.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(m_Project, m_Project, new Uri(m_Xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <urakawa.events.progress.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 (RequestCancellation) { m_Xuk_FilePath = null; m_Project = null; } }
private void verifyTree(TreeNode node, bool ancestorHasAudio, string ancestorExtAudioFile) { if (TreeNodeMustBeSkipped(node)) { return; } if (TreeNodeTriggersNewAudioFile(node) && ancestorExtAudioFile == null) { ancestorExtAudioFile = ""; } Media manSeqMedia = node.GetManagedAudioMediaOrSequenceMedia(); if (ancestorHasAudio) { DebugFix.Assert(manSeqMedia == null); } if (node.HasChannelsProperty) { ChannelsProperty chProp = node.GetChannelsProperty(); Media media = chProp.GetMedia(DestinationChannel); if (ancestorHasAudio) { DebugFix.Assert(media == null); } if (media != null) { DebugFix.Assert(media is ExternalAudioMedia); DebugFix.Assert(manSeqMedia != null); if (!ancestorHasAudio) { ExternalAudioMedia extMedia = (ExternalAudioMedia)media; ancestorHasAudio = true; if (ancestorExtAudioFile != null) { if (ancestorExtAudioFile == "") { ancestorExtAudioFile = extMedia.Uri.LocalPath; } else { DebugFix.Assert(ancestorExtAudioFile == extMedia.Uri.LocalPath); } } else { ancestorExtAudioFile = extMedia.Uri.LocalPath; } string ext = Path.GetExtension(ancestorExtAudioFile); if (!DataProviderFactory.AUDIO_WAV_EXTENSION.Equals(ext, StringComparison.OrdinalIgnoreCase)) { Debug.Fail("Verification can only be done if external media points to wav file!"); } //reportProgress(-1, @"DEBUG: " + ancestorExtAudioFile); Stream extMediaStream = new FileStream(ancestorExtAudioFile, FileMode.Open, FileAccess.Read, FileShare.None); Stream manMediaStream = null; ManagedAudioMedia manMedia = node.GetManagedAudioMedia(); #if ENABLE_SEQ_MEDIA SequenceMedia seqMedia = node.GetManagedAudioSequenceMedia(); #endif //ENABLE_SEQ_MEDIA if (manMedia != null) { #if ENABLE_SEQ_MEDIA DebugFix.Assert(seqMedia == null); #endif //ENABLE_SEQ_MEDIA DebugFix.Assert(manMedia.HasActualAudioMediaData); manMediaStream = manMedia.AudioMediaData.OpenPcmInputStream(); } else { Debug.Fail("SequenceMedia is normally removed at import time...have you tried re-importing the DAISY book ?"); #if ENABLE_SEQ_MEDIA DebugFix.Assert(seqMedia != null); DebugFix.Assert(!seqMedia.AllowMultipleTypes); DebugFix.Assert(seqMedia.ChildMedias.Count > 0); DebugFix.Assert(seqMedia.ChildMedias.Get(0) is ManagedAudioMedia); manMediaStream = seqMedia.OpenPcmInputStreamOfManagedAudioMedia(); #endif //ENABLE_SEQ_MEDIA } try { uint extMediaPcmLength; AudioLibPCMFormat pcmInfo = AudioLibPCMFormat.RiffHeaderParse(extMediaStream, out extMediaPcmLength); DebugFix.Assert(extMediaPcmLength == extMediaStream.Length - extMediaStream.Position); if (manMedia != null) { DebugFix.Assert(pcmInfo.IsCompatibleWith(manMedia.AudioMediaData.PCMFormat.Data)); } #if ENABLE_SEQ_MEDIA if (seqMedia != null) { DebugFix.Assert( pcmInfo.IsCompatibleWith( ((ManagedAudioMedia)seqMedia.ChildMedias.Get(0)).AudioMediaData.PCMFormat.Data)); } #endif //ENABLE_SEQ_MEDIA extMediaStream.Position += pcmInfo.ConvertTimeToBytes(extMedia.ClipBegin.AsLocalUnits); long manMediaStreamPosBefore = manMediaStream.Position; long extMediaStreamPosBefore = extMediaStream.Position; //DebugFix.Assert(AudioLibPCMFormat.CompareStreamData(manMediaStream, extMediaStream, (int)manMediaStream.Length)); //DebugFix.Assert(manMediaStream.Position == manMediaStreamPosBefore + manMediaStream.Length); //DebugFix.Assert(extMediaStream.Position == extMediaStreamPosBefore + manMediaStream.Length); } finally { extMediaStream.Close(); manMediaStream.Close(); } } } else { DebugFix.Assert(manSeqMedia == null); } } else { DebugFix.Assert(manSeqMedia == null); } foreach (TreeNode child in node.Children.ContentsAs_Enumerable) { verifyTree(child, ancestorHasAudio, ancestorExtAudioFile); } }
private void readTypeAndQNamesFromXmlReader(TypeAndQNames tq, XmlReader rd, bool pretty) { tq.AssemblyName = new AssemblyName(ReadXukAttribute(rd, AssemblyName_NAME)); if (ReadXukAttribute(rd, AssemblyVersion_NAME) != null) { tq.AssemblyName.Version = new Version(ReadXukAttribute(rd, AssemblyVersion_NAME)); } tq.ClassName = ReadXukAttribute(rd, FullName_NAME); if (tq.AssemblyName != null && tq.ClassName != null) { try { Assembly a = Assembly.Load(tq.AssemblyName); try { tq.Type = a.GetType(tq.ClassName); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif Console.WriteLine("ClassName: " + tq.ClassName); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); tq.Type = null; } } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif Console.WriteLine("AssemblyName: " + tq.AssemblyName); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); tq.Type = null; } } else { #if DEBUG Debugger.Break(); #endif Console.WriteLine("Type XukIn error?!"); Console.WriteLine("AssemblyName: " + tq.AssemblyName); Console.WriteLine("ClassName: " + tq.ClassName); tq.Type = null; } string xukLocalName = ReadXukAttribute(rd, XukLocalName_NAME); UglyPrettyName name = null; if (tq.Type != null) { UglyPrettyName nameCheck = GetXukName(tq.Type); DebugFix.Assert(nameCheck != null); if (nameCheck != null) { if (pretty) { DebugFix.Assert(xukLocalName == nameCheck.Pretty); } else { DebugFix.Assert(xukLocalName == nameCheck.Ugly); } name = nameCheck; } } DebugFix.Assert(name != null); if (name == null) { name = new UglyPrettyName( !pretty ? xukLocalName : null, pretty ? xukLocalName : null); } tq.QName = new QualifiedName( name, ReadXukAttribute(rd, XukNamespaceUri_NAME) ?? ""); string baseXukLocalName = ReadXukAttribute(rd, BaseXukLocalName_NAME); if (!string.IsNullOrEmpty(baseXukLocalName)) { UglyPrettyName nameBase = new UglyPrettyName( !pretty ? baseXukLocalName : null, pretty ? baseXukLocalName : null); tq.BaseQName = new QualifiedName( nameBase, ReadXukAttribute(rd, BaseXukNamespaceUri_NAME) ?? ""); } else { tq.BaseQName = null; } }
public void ToString(StringBuilder strBuilder, int level) { //strBuilder.AppendLine(); strIndent(strBuilder, level); strBuilder.Append(@"<li>"); strBuilder.Append(@"<a"); string uid = (RealSectioningRootOrContent != null ? RealSectioningRootOrContent.GetXmlElementId() : null); if (Heading != null) { string headingName = Heading.GetXmlElementLocalName(); if (!string.IsNullOrEmpty(headingName) && headingName.Equals(@"hgroup", StringComparison.OrdinalIgnoreCase)) { TreeNode highestRanked = null; int highestRank = int.MaxValue; foreach (TreeNode child in Heading.Children.ContentsAs_Enumerable) { string name = child.GetXmlElementLocalName(); int rank = GetHeadingRank(name); if (rank >= 0 && rank < highestRank) { highestRank = rank; highestRanked = child; } } if (highestRanked != null) { if (string.IsNullOrEmpty(uid)) { uid = Heading.GetXmlElementId(); if (string.IsNullOrEmpty(uid)) { uid = highestRanked.GetXmlElementId(); } } if (!string.IsNullOrEmpty(uid)) { strBuilder.Append(" href=\"#" + uid + "\""); } strBuilder.Append(@">"); strBuilder.Append(highestRanked.GetTextFlattened()); } else { Debugger.Break(); if (string.IsNullOrEmpty(uid)) { uid = Heading.GetXmlElementId(); } if (!string.IsNullOrEmpty(uid)) { strBuilder.Append(" href=\"#" + uid + "\""); } strBuilder.Append(@">"); strBuilder.Append(Heading.GetTextFlattened()); } } else { if (string.IsNullOrEmpty(uid)) { uid = Heading.GetXmlElementId(); } if (!string.IsNullOrEmpty(uid)) { strBuilder.Append(" href=\"#" + uid + "\""); } strBuilder.Append(@">"); strBuilder.Append(Heading.GetTextFlattened()); } } else { if (!string.IsNullOrEmpty(uid)) { strBuilder.Append(" href=\"#" + uid + "\""); } strBuilder.Append(@">"); if (RealSectioningRootOrContent != null) { string name = RealSectioningRootOrContent.GetXmlElementPrefixedLocalName(); if (name.Equals(@"body")) { strBuilder.Append(@"Untitled document"); } else if (name.Equals(@"section")) { strBuilder.Append(@"Untitled section"); } else if (name.Equals(@"article")) { strBuilder.Append(@"Article"); } else if (name.Equals(@"aside")) { strBuilder.Append(@"Sidebar"); } else if (name.Equals(@"nav")) { strBuilder.Append(@"Navigation"); } else { strBuilder.Append(@"UNTITLED ("); strBuilder.Append(name); strBuilder.Append(@")"); } } else { strBuilder.Append(@"UNTITLED"); } } strBuilder.Append(@"</a>"); if (SubSections.Count > 0) { strBuilder.AppendLine(); strIndent(strBuilder, level + 1); strBuilder.AppendLine(@"<ol>"); foreach (Section section in SubSections) { DebugFix.Assert(section.ParentSection == this); section.ToString(strBuilder, level + 2); } //strBuilder.AppendLine(); strIndent(strBuilder, level + 1); strBuilder.AppendLine(@"</ol>"); strIndent(strBuilder, level); } strBuilder.AppendLine("</li>"); }
private void OnUndoRedoManagerChanged_AudioEditCommand(UndoRedoManagerEventArgs eventt, bool done, AudioEditCommand cmd, bool isTransactionEndEvent, bool isNoTransactionOrTrailingEdge) { #if DEBUG DebugFix.Assert(!isTransactionEndEvent || isNoTransactionOrTrailingEdge && cmd.IsInTransaction() && cmd.TopTransactionId() == AudioPaneViewModel.COMMAND_TRANSATION_ID__AUDIO_TTS); #endif if (cmd is ManagedAudioMediaInsertDataCommand) { var command = (ManagedAudioMediaInsertDataCommand)cmd; if (!done) { DebugFix.Assert(!m_OnUndoRedoManagerChanged_wasInitByRemove); } if (!done || // reverse => force scan backwards to beginning m_OnUndoRedoManagerChanged_targetNode1 == null || // not reverse, first-time init m_OnUndoRedoManagerChanged_wasInitByRemove // not reverse, not first-time init, but deletion occured before addition (e.g. select waveform audio + paste over it) ) { m_OnUndoRedoManagerChanged_wasInitByRemove = false; m_OnUndoRedoManagerChanged_wasInitByAdd = true; m_OnUndoRedoManagerChanged_targetNode1 = command.CurrentTreeNode; m_OnUndoRedoManagerChanged_targetNode2 = command.CurrentTreeNode == command.TreeNode ? null : command.TreeNode; m_OnUndoRedoManagerChanged_byteStart = command.BytePositionInsert; if (done || m_OnUndoRedoManagerChanged_targetNode1 == null) { m_OnUndoRedoManagerChanged_byteDur = 0; } m_OnUndoRedoManagerChanged_done = done; } m_OnUndoRedoManagerChanged_byteDur += command.ManagedAudioMediaSource.AudioMediaData.PCMFormat.Data.ConvertTimeToBytes( command.ManagedAudioMediaSource.Duration.AsLocalUnits); } else if (cmd is TreeNodeSetManagedAudioMediaCommand) { var command = (TreeNodeSetManagedAudioMediaCommand)cmd; if (!done) { DebugFix.Assert(!m_OnUndoRedoManagerChanged_wasInitByRemove); } if (!done || // reverse => force scan backwards to beginning m_OnUndoRedoManagerChanged_targetNode1 == null || // not reverse, first-time init m_OnUndoRedoManagerChanged_wasInitByRemove // not reverse, not first-time init, but deletion occured before addition (e.g. select waveform audio + paste over it) ) { m_OnUndoRedoManagerChanged_wasInitByRemove = false; m_OnUndoRedoManagerChanged_wasInitByAdd = true; m_OnUndoRedoManagerChanged_targetNode1 = command.CurrentTreeNode; m_OnUndoRedoManagerChanged_targetNode2 = command.CurrentTreeNode == command.TreeNode ? null : command.TreeNode; m_OnUndoRedoManagerChanged_byteStart = 0; if (done || m_OnUndoRedoManagerChanged_targetNode1 == null) { m_OnUndoRedoManagerChanged_byteDur = 0; } m_OnUndoRedoManagerChanged_done = done; } m_OnUndoRedoManagerChanged_byteDur += command.ManagedAudioMedia.AudioMediaData.PCMFormat.Data.ConvertTimeToBytes( command.ManagedAudioMedia.Duration.AsLocalUnits); } else if (cmd is TreeNodeAudioStreamDeleteCommand) { var command = (TreeNodeAudioStreamDeleteCommand)cmd; if (done) { DebugFix.Assert(!m_OnUndoRedoManagerChanged_wasInitByAdd); } if (!done || // reverse => force scan backwards to beginning m_OnUndoRedoManagerChanged_targetNode1 == null // not reverse, first-time init ) { if (done || m_OnUndoRedoManagerChanged_targetNode1 == null || m_OnUndoRedoManagerChanged_wasInitByAdd) { m_OnUndoRedoManagerChanged_byteDur = 0; } m_OnUndoRedoManagerChanged_wasInitByAdd = false; m_OnUndoRedoManagerChanged_wasInitByRemove = true; m_OnUndoRedoManagerChanged_targetNode1 = command.CurrentTreeNode; m_OnUndoRedoManagerChanged_targetNode2 = command.CurrentTreeNode == command.TreeNode ? null : command.TreeNode; m_OnUndoRedoManagerChanged_byteStart = 0; m_OnUndoRedoManagerChanged_done = !done; } long bytesBegin = 0; long bytesEnd = 0; if (command.SelectionData.m_LocalStreamLeftMark > 0) { bytesBegin = command.SelectionData.m_LocalStreamLeftMark; } if (command.SelectionData.m_LocalStreamRightMark <= 0) { bytesEnd = command.OriginalManagedAudioMedia.AudioMediaData.PCMFormat.Data.ConvertTimeToBytes(command.OriginalManagedAudioMedia.AudioMediaData.AudioDuration.AsLocalUnits); } else { bytesEnd = command.SelectionData.m_LocalStreamRightMark; } m_OnUndoRedoManagerChanged_byteStart += bytesBegin; m_OnUndoRedoManagerChanged_byteDur += (bytesEnd - bytesBegin); } }
private void updateTreeNodeAudioStatus(bool forceRemove, TreeNode node) { foreach (var childTreeNode in node.Children.ContentsAs_Enumerable) { updateTreeNodeAudioStatus(forceRemove, childTreeNode); } if (!forceRemove && node.NeedsAudio() && !node.HasOrInheritsAudio() && (!Tobi.Common.Settings.Default.ValidMissingAudioElements_Enable || !isTreeNodeValidNoAudio(node))) { bool alreadyInList = false; foreach (var vItem in ValidationItems) { var valItem = vItem as MissingAudioValidationError; DebugFix.Assert(valItem != null); if (valItem == null) { continue; } if (valItem.Target == node) { alreadyInList = true; break; } } if (!alreadyInList) { var validationItem = new MissingAudioValidationError(m_Session) { Target = node, Validator = this }; bool inserted = false; int i = -1; foreach (var vItem in ValidationItems) { i++; var valItem = vItem as MissingAudioValidationError; DebugFix.Assert(valItem != null); if (valItem == null) { continue; } if (node.IsBefore(valItem.Target)) { insertValidationItem(i, validationItem); inserted = true; break; } } if (!inserted) { addValidationItem(validationItem); } } } else { var toRemove = new List <ValidationItem>(); foreach (var vItem in ValidationItems) { var valItem = vItem as MissingAudioValidationError; DebugFix.Assert(valItem != null); if (valItem == null) { continue; } if (valItem.Target == node) { toRemove.Add(vItem); } } removeValidationItems(toRemove); } }
public void Popup() { var navView = m_Container.Resolve <DescriptionsNavigationView>(); if (navView != null) { navView.UpdateTreeNodeSelectionFromListItem(); } Tuple <TreeNode, TreeNode> selection = m_Session.GetTreeNodeSelection(); TreeNode node = selection.Item2 ?? selection.Item1; if (node == null) { return; } var navModel = m_Container.Resolve <DescriptionsNavigationViewModel>(); if (navModel.DescriptionsNavigator == null) { return; } bool found = false; foreach (DescribableTreeNode dnode in navModel.DescriptionsNavigator.DescribableTreeNodes) { found = dnode.TreeNode == node; if (found) { break; } } if (!found) { var label = new TextBlock { Text = Tobi.Plugin.Descriptions.Tobi_Plugin_Descriptions_Lang.FirstSelectImage, Margin = new Thickness(8, 0, 8, 0), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Focusable = true, TextWrapping = TextWrapping.WrapWithOverflow }; var iconProvider = new ScalableGreyableImageProvider(m_ShellView.LoadTangoIcon("dialog-warning"), m_ShellView.MagnificationLevel); var panel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch, }; panel.Children.Add(iconProvider.IconLarge); panel.Children.Add(label); //panel.Margin = new Thickness(8, 8, 8, 0); var popup = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Descriptions_Lang.CmdEditDescriptions_ShortDesc), panel, PopupModalWindow.DialogButtonsSet.Ok, PopupModalWindow.DialogButton.Ok, true, 340, 160, null, 0, null); popup.ShowModal(); return; } var windowPopup = new PopupModalWindow(m_ShellView, UserInterfaceStrings.EscapeMnemonic(Tobi_Plugin_Descriptions_Lang.CmdEditDescriptions_ShortDesc), this, PopupModalWindow.DialogButtonsSet.OkApplyCancel, PopupModalWindow.DialogButton.Apply, true, 1000, 600, null, 0, null); //this.OwnerWindow = windowPopup; DONE in ON PANEL LOADED EVENT windowPopup.IgnoreEscape = true; //var bindings = Application.Current.MainWindow.InputBindings; //foreach (var binding in bindings) //{ // if (binding is KeyBinding) // { // var keyBinding = (KeyBinding)binding; // if (keyBinding.Command == m_ShellView.ExitCommand) // { // continue; // } // windowPopup.InputBindings.Add(keyBinding); // } //} //windowPopup.InputBindings.AddRange(Application.Current.MainWindow.InputBindings); //windowPopup.KeyUp += (object sender, KeyEventArgs e) => // { // var key = (e.Key == Key.System // ? e.SystemKey // : (e.Key == Key.ImeProcessed ? e.ImeProcessedKey : e.Key)); // if (key == Key.Escape) // { // m_EventAggregator.GetEvent<EscapeEvent>().Publish(null); // } // }; //windowPopup.Closed += (sender, ev) => Dispatcher.BeginInvoke( // DispatcherPriority.Background, // (Action)(() => // { // // // })); m_Session.DocumentProject.Presentations.Get(0).UndoRedoManager.StartTransaction (Tobi_Plugin_Descriptions_Lang.CmdEditDescriptions_ShortDesc, Tobi_Plugin_Descriptions_Lang.CmdEditDescriptions_LongDesc, "EDIT_IMAGE_DESCRIPTIONS"); //Tuple<TreeNode, TreeNode> selection = m_Session.GetTreeNodeSelection(); //TreeNode node = selection.Item2 ?? selection.Item1; //if (node == null) return; bool hadAltProp = true; var altProp = node.GetAlternateContentProperty(); //node.GetAlternateContentProperty(); if (altProp == null) { hadAltProp = false; altProp = node.GetOrCreateAlternateContentProperty(); DebugFix.Assert(altProp != null); } m_DescriptionPopupModalWindow = windowPopup; windowPopup.ShowModal(); m_DescriptionPopupModalWindow = null; if (windowPopup.ClickedDialogButton == PopupModalWindow.DialogButton.Ok || windowPopup.ClickedDialogButton == PopupModalWindow.DialogButton.Apply) { altProp = node.GetAlternateContentProperty(); //node.GetAlternateContentProperty(); if (altProp != null) { removeEmptyDescriptions(altProp); } bool empty = m_Session.DocumentProject.Presentations.Get(0).UndoRedoManager.IsTransactionEmpty; m_Session.DocumentProject.Presentations.Get(0).UndoRedoManager.EndTransaction(); if (empty) { altProp = node.GetAlternateContentProperty(); //node.GetAlternateContentProperty(); if (altProp != null && !hadAltProp) { #if DEBUG DebugFix.Assert(altProp.IsEmpty); #endif //DEBUG node.RemoveProperty(altProp); } } } else { m_Session.DocumentProject.Presentations.Get(0).UndoRedoManager.CancelTransaction(); altProp = node.GetAlternateContentProperty(); //node.GetAlternateContentProperty(); if (altProp != null && !hadAltProp) { #if DEBUG DebugFix.Assert(altProp.IsEmpty); #endif //DEBUG node.RemoveProperty(altProp); } } if (windowPopup.ClickedDialogButton == PopupModalWindow.DialogButton.Apply) { Popup(); } }
private void updateTotalDuration(Command cmd, bool done) { if (cmd is ManagedAudioMediaInsertDataCommand) { var command = (ManagedAudioMediaInsertDataCommand)cmd; long dur = command.ManagedAudioMediaSource.Duration.AsLocalUnits; if (done) { TotalDocumentAudioDurationInLocalUnits += dur; TotalSessionAudioDurationInLocalUnits += dur; } else { TotalDocumentAudioDurationInLocalUnits -= dur; TotalSessionAudioDurationInLocalUnits -= dur; } } else if (cmd is TreeNodeSetManagedAudioMediaCommand) { var command = (TreeNodeSetManagedAudioMediaCommand)cmd; long dur = command.ManagedAudioMedia.Duration.AsLocalUnits; if (done) { TotalDocumentAudioDurationInLocalUnits += dur; TotalSessionAudioDurationInLocalUnits += dur; } else { TotalDocumentAudioDurationInLocalUnits -= dur; TotalSessionAudioDurationInLocalUnits -= dur; } } else if (cmd is TreeNodeAudioStreamDeleteCommand) { var command = (TreeNodeAudioStreamDeleteCommand)cmd; Time timeBegin = command.SelectionData.m_LocalStreamLeftMark == -1 ? Time.Zero : new Time(command.OriginalManagedAudioMedia.AudioMediaData.PCMFormat.Data.ConvertBytesToTime(command.SelectionData.m_LocalStreamLeftMark)); Time timeEnd = command.SelectionData.m_LocalStreamRightMark == -1 ? command.OriginalManagedAudioMedia.AudioMediaData.AudioDuration : new Time(command.OriginalManagedAudioMedia.AudioMediaData.PCMFormat.Data.ConvertBytesToTime(command.SelectionData.m_LocalStreamRightMark)); Time diff = timeEnd.GetDifference(timeBegin); ManagedAudioMedia manMedia = command.TreeNode.GetManagedAudioMedia(); if (manMedia == null) { DebugFix.Assert(done); DebugFix.Assert(diff.IsEqualTo(command.OriginalManagedAudioMedia.Duration)); DebugFix.Assert( //command.OriginalManagedAudioMedia.AudioMediaData.PCMFormat.Data. AudioLibPCMFormat.TimesAreEqualWithMillisecondsTolerance( diff.AsLocalUnits, command.OriginalManagedAudioMedia.Duration.AsLocalUnits)); } long dur = diff.AsLocalUnits; if (done) { TotalDocumentAudioDurationInLocalUnits -= dur; TotalSessionAudioDurationInLocalUnits -= dur; } else { TotalDocumentAudioDurationInLocalUnits += dur; TotalSessionAudioDurationInLocalUnits += dur; } } else if (cmd is TreeNodeRemoveCommand) { var command = (TreeNodeRemoveCommand)cmd; Time duration = command.TreeNode.GetDurationOfManagedAudioMediaFlattened(); long dur = duration == null ? 0 : duration.AsLocalUnits; if (!done) { TotalDocumentAudioDurationInLocalUnits += dur; TotalSessionAudioDurationInLocalUnits += dur; } else { TotalDocumentAudioDurationInLocalUnits -= dur; TotalSessionAudioDurationInLocalUnits -= dur; } } else if (cmd is TreeNodeInsertCommand) { var command = (TreeNodeInsertCommand)cmd; Time duration = command.TreeNode.GetDurationOfManagedAudioMediaFlattened(); long dur = duration == null ? 0 : duration.AsLocalUnits; if (done) { TotalDocumentAudioDurationInLocalUnits += dur; TotalSessionAudioDurationInLocalUnits += dur; } else { TotalDocumentAudioDurationInLocalUnits -= dur; TotalSessionAudioDurationInLocalUnits -= dur; } } }
static XukAble() { Debugger.Break(); try { PropertyInfo[] properties = typeof(XukStrings).GetProperties(BindingFlags.Public | BindingFlags.Static); DebugFix.Assert(!string.IsNullOrEmpty(XUK_NS)); List <string> list = new List <string>(); foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies()) { Console.WriteLine(ass.FullName); foreach (Type type in ass.GetTypes()) { if (type == typeof(XukAble) || typeof(XukAble).IsAssignableFrom(type)) { Console.WriteLine("-----------"); Console.WriteLine(type.FullName); Type typeConcrete = type; if (type.ContainsGenericParameters) { DebugFix.Assert(type.IsAbstract); Type[] types = type.GetGenericArguments(); DebugFix.Assert(types.Length == 1); typeConcrete = type.MakeGenericType(types[0].BaseType); } FieldInfo[] fields = typeConcrete.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo field in fields) { if (field.FieldType != typeof(UglyPrettyName)) { continue; } const string NAME = "_NAME"; bool okay = field.Name.EndsWith(NAME); DebugFix.Assert(okay); if (okay) { Console.WriteLine("....."); Console.WriteLine(field.Name); UglyPrettyName name = (UglyPrettyName)field.GetValue(typeConcrete); string fieldName = field.Name.Substring(0, field.Name.Length - NAME.Length); Console.WriteLine(fieldName); PropertyInfo found_ = null; foreach (PropertyInfo property in properties) { if (property.PropertyType == typeof(string) && property.Name == fieldName) { found_ = property; break; } } DebugFix.Assert(found_ != null); if (found_ != null) { XukStrings.IsPrettyFormat = false; string uglyCheck = (string)found_.GetValue(typeof(XukStrings), null); DebugFix.Assert(name.Ugly == uglyCheck); Console.WriteLine(uglyCheck); XukStrings.IsPrettyFormat = true; string prettyCheck = (string)found_.GetValue(typeof(XukStrings), null); DebugFix.Assert(name.Pretty == prettyCheck); Console.WriteLine(prettyCheck); } Console.WriteLine("....."); } } string ns = GetXukNamespace(type); DebugFix.Assert(!string.IsNullOrEmpty(ns)); if (type == typeof(XukAble)) { Console.WriteLine(ns); } if (type.FullName.StartsWith("Obi.")) { DebugFix.Assert(ns == "http://www.daisy.org/urakawa/obi"); } else { DebugFix.Assert(ns == "http://www.daisy.org/urakawa/xuk/2.0"); } if (type.IsAbstract) { Console.WriteLine("abstract"); continue; } if (type.FullName.StartsWith("Obi.")) { if (!type.FullName.StartsWith("Obi.Commands")) { string pretty_ = GetXukName(type, true); string ugly_ = GetXukName(type, false); DebugFix.Assert(!string.IsNullOrEmpty(pretty_)); DebugFix.Assert(!string.IsNullOrEmpty(ugly_)); DebugFix.Assert(pretty_ == ugly_); Console.WriteLine(pretty_); if (type.Name == "ObiPresentation") { DebugFix.Assert(pretty_ == type.Name); } else if (type.Name == "ObiNode") { DebugFix.Assert(pretty_ == type.Name); } else if (type.Name == "PhraseNode") { DebugFix.Assert(pretty_ == "phrase"); } else if (type.Name == "SectionNode") { DebugFix.Assert(pretty_ == "section"); } else if (type.Name == "ObiRootNode") { DebugFix.Assert(pretty_ == "root"); } else if (type.Name == "EmptyNode") { DebugFix.Assert(pretty_ == "empty"); } else { Debugger.Break(); } } continue; } if (type.Name == "DummyCommand") { continue; } string pretty = GetXukName(type, true); if (!string.IsNullOrEmpty(pretty)) { Console.WriteLine(pretty); if (list.Contains(pretty)) { Debugger.Break(); } else { list.Add(pretty); } if (type.Name == "CSSExternalFileData") { DebugFix.Assert(pretty == "CssExternalFileData"); } else if (type.Name == "XSLTExternalFileData") { DebugFix.Assert(pretty == "XsltExternalFileData"); } else if (type.Name == "ExternalFilesDataManager") { DebugFix.Assert(pretty == "ExternalFileDataManager"); } else { DebugFix.Assert(type.Name == pretty); } } else { Debugger.Break(); } string ugly = GetXukName(type, false); if (!string.IsNullOrEmpty(ugly)) { Console.WriteLine(ugly); if (list.Contains(ugly)) { Debugger.Break(); } else { list.Add(ugly); } } else { Debugger.Break(); } PropertyInfo found = null; foreach (PropertyInfo property in properties) { if (property.PropertyType == typeof(string) && (property.Name == type.Name || (type.Name == "ExternalFilesDataManager" && property.Name == "ExternalFileDataManager") )) { found = property; break; } } DebugFix.Assert(found != null); if (found != null) { XukStrings.IsPrettyFormat = false; string uglyCheck = (string)found.GetValue(typeof(XukStrings), null); DebugFix.Assert(ugly == uglyCheck); XukStrings.IsPrettyFormat = true; string prettyCheck = (string)found.GetValue(typeof(XukStrings), null); DebugFix.Assert(pretty == prettyCheck); } } } } // Make sure default is false, to at least open exising projects whilst testing. // (for as long as the refactoring goes on to remove dependency on static XukStrings) XukStrings.IsPrettyFormat = false; } catch (Exception ex) { Debugger.Break(); } Debugger.Break(); }
private static void handleMetadataGroup( XmlNode headNode, XmlDocument descriptionDocument, XmlNode descriptionNode, Dictionary <string, List <Metadata> > groupedMetadata) { foreach (string key in groupedMetadata.Keys) { List <Metadata> metadatasForKey = groupedMetadata[key]; if (metadatasForKey.Count == 1) { Metadata md = metadatasForKey[0]; string hasId = null; string hasRel = null; string hasResource = null; List <MetadataAttribute> mains = new List <MetadataAttribute>(); List <MetadataAttribute> hasOthers = new List <MetadataAttribute>(); foreach (MetadataAttribute metadataAttribute in md.OtherAttributes.ContentsAs_Enumerable) { if (metadataAttribute.Name == Metadata.PrimaryIdentifierMark) { continue; } if (metadataAttribute.Name == XmlReaderWriterHelper.XmlId) { hasId = metadataAttribute.Value; mains.Add(metadataAttribute); } else if (metadataAttribute.Name == DiagramContentModelHelper.Rel) { hasRel = metadataAttribute.Value; mains.Add(metadataAttribute); } else if (metadataAttribute.Name == DiagramContentModelHelper.Resource) { hasResource = metadataAttribute.Value; mains.Add(metadataAttribute); } else { hasOthers.Add(metadataAttribute); } } if (hasRel != null && hasResource != null && (hasOthers.Count > 0 || (md.NameContentAttribute != null && md.NameContentAttribute.Name != DiagramContentModelHelper.NA && md.NameContentAttribute.Value != DiagramContentModelHelper.NA))) { XmlNode metaNode = addFlatDiagramHeadMetadata( null, mains, headNode, descriptionDocument, descriptionNode); addFlatDiagramHeadMetadata( md.NameContentAttribute, hasOthers, metaNode, descriptionDocument, descriptionNode); } else { addFlatDiagramHeadMetadata( metadatasForKey[0].NameContentAttribute, metadatasForKey[0].OtherAttributes.ContentsAs_Enumerable, headNode, descriptionDocument, descriptionNode); } } else { bool idAdded = false; string relAdded = null; string resourceAdded = null; List <MetadataAttribute> listCommonMetaAttributes = new List <MetadataAttribute>(); Dictionary <Metadata, List <MetadataAttribute> > mapMetaUpdatedAttributes = new Dictionary <Metadata, List <MetadataAttribute> >(); foreach (Metadata md in metadatasForKey) { if (md.OtherAttributes == null || md.OtherAttributes.Count == 0) { #if DEBUG Debugger.Break(); #endif // DEBUG continue; } foreach (MetadataAttribute metadataAttribute in md.OtherAttributes.ContentsAs_Enumerable) { if (metadataAttribute.Name == Metadata.PrimaryIdentifierMark) { continue; } if (metadataAttribute.Name == XmlReaderWriterHelper.XmlId) { DebugFix.Assert(metadataAttribute.Value == key); if (!idAdded) { listCommonMetaAttributes.Add(metadataAttribute); idAdded = true; } } else if (metadataAttribute.Name == DiagramContentModelHelper.Rel) { if (relAdded == null) { listCommonMetaAttributes.Add(metadataAttribute); relAdded = metadataAttribute.Value; } else { if (metadataAttribute.Value != relAdded) { #if DEBUG Debugger.Break(); #endif addDic(mapMetaUpdatedAttributes, md, metadataAttribute); } } } else if (metadataAttribute.Name == DiagramContentModelHelper.Resource) { if (resourceAdded == null) { listCommonMetaAttributes.Add(metadataAttribute); resourceAdded = metadataAttribute.Value; } else { if (metadataAttribute.Value != resourceAdded) { #if DEBUG Debugger.Break(); #endif addDic(mapMetaUpdatedAttributes, md, metadataAttribute); } } } else { addDic(mapMetaUpdatedAttributes, md, metadataAttribute); } } } XmlNode metaNode = addFlatDiagramHeadMetadata( null, listCommonMetaAttributes, headNode, descriptionDocument, descriptionNode); foreach (Metadata md in metadatasForKey) { if (mapMetaUpdatedAttributes.ContainsKey(md)) { addFlatDiagramHeadMetadata( md.NameContentAttribute, mapMetaUpdatedAttributes[md], metaNode, descriptionDocument, descriptionNode); } else { addFlatDiagramHeadMetadata( md.NameContentAttribute, null, metaNode, descriptionDocument, descriptionNode); } } } } }
public void CreateSmilNodesForImageDescription(TreeNode levelNodeDescendant, XmlDocument smilDocument, XmlNode smilBodySeq, Time durationOfCurrentSmil, AlternateContentProperty altProperty, string smilFileName) { //try //{ int counter = 0; foreach (string diagramDescriptionElementName in m_Map_AltProperty_TO_Description[altProperty].Map_DiagramElementName_TO_AltContent.Keys) { AlternateContent altContent = m_Map_AltProperty_TO_Description[altProperty].Map_DiagramElementName_TO_AltContent[diagramDescriptionElementName]; if (altContent.Text == null) { continue; } counter++; if (m_Image_ProdNoteMap[levelNodeDescendant].Count <= counter) { break; } XmlNode seqNode = smilDocument.CreateElement("seq", smilBodySeq.NamespaceURI); smilBodySeq.AppendChild(seqNode); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, seqNode, "class", "prodnote"); string strSeqID = GetNextID(ID_SmilPrefix); //System.Windows.Forms.MessageBox.Show(counter.ToString () + " : " + m_Image_ProdNoteMap[n].Count.ToString()); string dtbookID = m_Image_ProdNoteMap[levelNodeDescendant][counter].Attributes.GetNamedItem("id").Value; string par_id = GetNextID(ID_SmilPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, seqNode, "id", strSeqID); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, seqNode, "class", "prodnote"); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, seqNode, "customTest", "prodnote"); XmlDocumentHelper.CreateAppendXmlAttribute(m_DTBDocument, m_Image_ProdNoteMap[levelNodeDescendant][counter], "smilref", FileDataProvider.UriEncode(smilFileName + "#" + strSeqID)); XmlNode parNode = smilDocument.CreateElement(null, "par", smilBodySeq.NamespaceURI); seqNode.AppendChild(parNode); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, parNode, "id", par_id); XmlNode SmilTextNode = smilDocument.CreateElement(null, "text", smilBodySeq.NamespaceURI); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, SmilTextNode, "id", GetNextID(ID_SmilPrefix)); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, SmilTextNode, "src", FileDataProvider.UriEncode(m_Filename_Content + "#" + dtbookID)); parNode.AppendChild(SmilTextNode); if (altContent.Audio != null) { media.data.audio.ManagedAudioMedia managedAudio = altContent.Audio; string srcPath = m_Map_AltContentAudio_TO_RelativeExportedFilePath[altContent]; DebugFix.Assert(!string.IsNullOrEmpty(srcPath)); XmlNode audioNode = smilDocument.CreateElement(null, "audio", smilBodySeq.NamespaceURI); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, audioNode, "clipBegin", "00:00:00"); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, audioNode, "clipEnd", FormatTimeString(managedAudio.Duration)); XmlDocumentHelper.CreateAppendXmlAttribute(smilDocument, audioNode, "src", FileDataProvider.UriEncode(srcPath)); parNode.AppendChild(audioNode); if (!m_FilesList_SmilAudio.Contains(srcPath)) { m_FilesList_SmilAudio.Add(srcPath); } // add to duration durationOfCurrentSmil.Add(managedAudio.Duration); } } //} //catch (System.Exception ex) //{ // System.Windows.Forms.MessageBox.Show(ex.ToString()); //} }
private void addAudio(TreeNode treeNode, XmlNode xmlNode, bool isSequence) { //if (RequestCancellation) return; string dirPath = m_NccBaseDirectory; 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("clip-begin"); XmlNode audioAttrClipEnd = audioAttrs.GetNamedItem("clip-end"); ObiPresentation presentation = m_Presentation; ManagedAudioMedia media = null; string fullPath = Path.Combine(dirPath, src); fullPath = FileDataProvider.NormaliseFullFilePath(fullPath).Replace('/', '\\'); //addOPF_GlobalAssetPath(fullPath); if (src.EndsWith("wav", StringComparison.OrdinalIgnoreCase)) { FileDataProvider dataProv = null; if (!File.Exists(fullPath)) { Debug.Fail("File not found: {0}", 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_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 AudioLibPCMFormat(); m_AudioConversionSession.FirstDiscoveredPCMFormat.CopyFrom(pcmInfo); } //if (RequestCancellation) return; 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); } else if (src.EndsWith("mp3", StringComparison.OrdinalIgnoreCase) || src.EndsWith("mp4", 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_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 (RequestCancellation) return; //media = addAudioWav(newfullWavPath, true, audioAttrClipBegin, audioAttrClipEnd); media = addAudioWav(dataProv, audioAttrClipBegin, audioAttrClipEnd, treeNode); if (media == null) { Debugger.Break(); } } } //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(0); 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); } #endif //ENABLE_SEQ_MEDIA } else { chProp.SetMedia(presentation.ChannelsManager.GetOrCreateAudioChannel(), media); } } else { Debug.Fail("Media could not be created !"); } }
protected string AdjustAudioFileName(ExternalAudioMedia externalAudio, TreeNode levelNode) { //#if !TOBI // // Obi should not use this, as the above AddSectionNameToAudioFileName() is used instead!! // Debugger.Break(); // return externalAudio.Src; //#endif // Obi should return below! if (!IsAdjustAudioFileNameEnabled) { return(externalAudio.Src); } if (externalAudio.Tag == null || !(externalAudio.Tag is TreeNode)) { #if DEBUG Debugger.Break(); #endif return(externalAudio.Src); } TreeNode node = externalAudio.Tag as TreeNode; // In some cases this occurs (for example with Great Painters, // or when m_audioExportDTBOOKElementNameTriggers / doesTreeNodeTriggerNewSmil() is set to level2 but not level1 // The generated SMIL and audio file structure looks okay, but the heading/section title is missing in the filename // DebugFix.Assert(node == levelNode); #if DEBUG if (node != levelNode) { bool breakpointHere = true; } // Debugger.Break(); #endif string src = null; m_adjustedExternalAudioFileNames.TryGetValue(node, out src); if (!string.IsNullOrEmpty(src)) { #if DEBUG //DebugFix.Assert(!src.Equals(externalAudio.Src, StringComparison.Ordinal)); //if (src.Equals(externalAudio.Src, StringComparison.Ordinal)) //{ // Debugger.Break(); //} #endif externalAudio.Src = src; return(src); } string strTitle = ""; bool html5_outlining = node.Presentation.RootNode.GetXmlElementLocalName() .Equals("body", StringComparison.OrdinalIgnoreCase); if (html5_outlining) { #if DEBUG Debugger.Break(); #endif //TODO? //List<Section> sections = node.Presentation.RootNode.GetOrCreateOutline() // spine item / HTML title?? } else { string localName = node.GetXmlElementLocalName(); #if DEBUG //protected virtual bool doesTreeNodeTriggerNewSmil(TreeNode node) DebugFix.Assert(node.HasXmlProperty); DebugFix.Assert(localName.StartsWith("level", StringComparison.OrdinalIgnoreCase) || localName.Equals("section", StringComparison.OrdinalIgnoreCase) || localName.Equals("book", StringComparison.OrdinalIgnoreCase) ); #endif TreeNode heading = null; if (TreeNode.IsLevel(localName)) { TreeNode level = node; if (level.Children.Count > 0) { TreeNode nd = level.Children.Get(0); if (nd != null) { localName = nd.HasXmlProperty ? nd.GetXmlElementLocalName() : null; if (localName != null && (localName == "pagenum" || localName == "img") && level.Children.Count > 1) { nd = level.Children.Get(1); if (nd != null) { localName = nd.GetXmlElementLocalName(); } } if (localName != null && (TreeNode.IsHeading(localName))) { heading = nd; } else { if (localName != null && (localName == "pagenum" || localName == "img") && level.Children.Count > 2) { nd = level.Children.Get(2); if (nd != null) { localName = nd.GetXmlElementLocalName(); } } if (localName != null && (TreeNode.IsHeading(localName))) { heading = nd; } } } } } else if (TreeNode.IsHeading(localName)) { #if DEBUG Debugger.Break(); #endif heading = node; } else if (!localName.Equals("book", StringComparison.OrdinalIgnoreCase)) { #if DEBUG Debugger.Break(); #endif } StringBuilder strBuilder = null; if (heading != null) { TreeNode.StringChunkRange range = heading.GetTextFlattened_(); if (!(range == null || range.First == null || string.IsNullOrEmpty(range.First.Str))) { strBuilder = new StringBuilder(range.GetLength()); TreeNode.ConcatStringChunks(range, -1, strBuilder); //strBuilder.Insert(0, "] "); //strBuilder.Insert(0, heading.GetXmlElementLocalName()); //strBuilder.Insert(0, "["); } } //else //{ // strBuilder = new StringBuilder(); // strBuilder.Append("["); // strBuilder.Append(level.GetXmlElementLocalName()); // strBuilder.Append("] "); // strBuilder.Append(Tobi_Plugin_NavigationPane_Lang.NoHeading); //} if (strBuilder != null) { strTitle = strBuilder.ToString().Trim(); } } if (strTitle.Length > 0) { strTitle = FileDataProvider.EliminateForbiddenFileNameCharacters(strTitle.Replace(" ", "_")); } int MAX_LENGTH = AudioFileNameCharsLimit > 0 ? AudioFileNameCharsLimit : 10; if (strTitle.Length > MAX_LENGTH) { strTitle = strTitle.Substring(0, MAX_LENGTH); } string filename = Path.GetFileName(externalAudio.Src); string source = Path.Combine(m_OutputDirectory, filename); if (File.Exists(source)) { if (strTitle.Length > 0) { string newFileName = filename; string name = Path.GetFileNameWithoutExtension(externalAudio.Src); name = name.Replace("aud", ""); string ext = Path.GetExtension(externalAudio.Src); newFileName = name + "_" + strTitle + ext; //externalAudio.Src = externalAudio.Src.Replace(filename, newFileName); externalAudio.Src = newFileName; m_adjustedExternalAudioFileNames.Add(node, externalAudio.Src); string dest = Path.Combine(m_OutputDirectory, newFileName); File.Move(source, dest); try { File.SetAttributes(dest, FileAttributes.Normal); } catch { } return(newFileName); } } return(filename); }
//public void RefreshQNames() //{ // foreach (TypeAndQNames tq in mRegisteredTypeAndQNames) // { // if (tq.Type != null) // { // tq.QName = GetXukQualifiedName(tq.Type); // if (tq.BaseQName != null // && tq.Type.BaseType != null) // { // tq.BaseQName = GetXukQualifiedName(tq.Type.BaseType); // } // } // } // { // Dictionary<string, TypeAndQNames> newDict = new Dictionary<string, TypeAndQNames>(); // Dictionary<string, TypeAndQNames>.Enumerator enu = mRegisteredTypeAndQNamesByQualifiedName.GetEnumerator(); // while (enu.MoveNext()) // { // KeyValuePair<string, TypeAndQNames> pair = enu.Current; // TypeAndQNames tq = new TypeAndQNames(); // if (pair.Value.Type != null) // { // tq.QName = GetXukQualifiedName(pair.Value.Type); // tq.Type = pair.Value.Type; // tq.ClassName = pair.Value.Type.FullName; // tq.AssemblyName = pair.Value.Type.Assembly.GetName(); // if (pair.Value.BaseQName != null) // { // tq.BaseQName = GetXukQualifiedName(pair.Value.Type.BaseType); // } // } // else // { // tq.QName = new QualifiedName(pair.Value.QName.LocalName, pair.Value.QName.NamespaceUri); // tq.Type = null; // tq.ClassName = pair.Value.ClassName; // tq.AssemblyName = pair.Value.AssemblyName; // if (pair.Value.BaseQName != null) // { // tq.BaseQName = new QualifiedName(pair.Value.BaseQName.LocalName, pair.Value.BaseQName.NamespaceUri); // } // } // newDict.Add(tq.QName.FullyQualifiedName, tq); // } // mRegisteredTypeAndQNamesByQualifiedName.Clear(); // mRegisteredTypeAndQNamesByQualifiedName = newDict; // } // { // Dictionary<Type, TypeAndQNames> newDict = new Dictionary<Type, TypeAndQNames>(); // Dictionary<Type, TypeAndQNames>.Enumerator enu = mRegisteredTypeAndQNamesByType.GetEnumerator(); // while (enu.MoveNext()) // { // KeyValuePair<Type, TypeAndQNames> pair = enu.Current; // TypeAndQNames tq = new TypeAndQNames(); // if (pair.Value.Type != null) // { // tq.QName = GetXukQualifiedName(pair.Value.Type); // tq.Type = pair.Value.Type; // tq.ClassName = pair.Value.Type.FullName; // tq.AssemblyName = pair.Value.Type.Assembly.GetName(); // if (pair.Value.BaseQName != null) // { // tq.BaseQName = GetXukQualifiedName(pair.Value.Type.BaseType); // } // newDict.Add(pair.Value.Type, tq); // } // } // mRegisteredTypeAndQNamesByType.Clear(); // mRegisteredTypeAndQNamesByType = newDict; // } //} private void RegisterType(TypeAndQNames tq) { DebugFix.Assert(tq.Type != null); bool isTypeAlreadyRegistered = false; if (tq.Type != null) { isTypeAlreadyRegistered = typeAlreadyRegistered(tq.Type) != null; } foreach (TypeAndQNames typeAndQNames in mRegisteredTypeAndQNames) { // Does this QName resolve an existing registered BaseQName? if (typeAndQNames.BaseQName != null && (string.IsNullOrEmpty(typeAndQNames.BaseQName.LocalName.Ugly) || string.IsNullOrEmpty(typeAndQNames.BaseQName.LocalName.Pretty)) && typeAndQNames.BaseQName.NamespaceUri == tq.QName.NamespaceUri && (tq.QName.LocalName.Ugly != null && typeAndQNames.BaseQName.LocalName.Ugly == tq.QName.LocalName.Ugly || tq.QName.LocalName.Pretty != null && typeAndQNames.BaseQName.LocalName.Pretty == tq.QName.LocalName.Pretty) ) { #if DEBUG Debugger.Break(); #endif string ugly = typeAndQNames.BaseQName.LocalName.Ugly ?? tq.QName.LocalName.Ugly; string pretty = typeAndQNames.BaseQName.LocalName.Pretty ?? tq.QName.LocalName.Pretty; DebugFix.Assert(!string.IsNullOrEmpty(ugly)); DebugFix.Assert(!string.IsNullOrEmpty(pretty)); typeAndQNames.BaseQName = new QualifiedName(new UglyPrettyName(ugly, pretty), typeAndQNames.BaseQName.NamespaceUri); } // Can this BaseQName be resolved by an existing registered QName? if (tq.BaseQName != null && (string.IsNullOrEmpty(tq.BaseQName.LocalName.Ugly) || string.IsNullOrEmpty(tq.BaseQName.LocalName.Pretty)) && tq.BaseQName.NamespaceUri == typeAndQNames.QName.NamespaceUri && (typeAndQNames.QName.LocalName.Ugly != null && tq.BaseQName.LocalName.Ugly == typeAndQNames.QName.LocalName.Ugly || typeAndQNames.QName.LocalName.Pretty != null && tq.BaseQName.LocalName.Pretty == typeAndQNames.QName.LocalName.Pretty) ) { #if DEBUG Debugger.Break(); #endif string ugly = tq.BaseQName.LocalName.Ugly ?? typeAndQNames.QName.LocalName.Ugly; string pretty = tq.BaseQName.LocalName.Pretty ?? typeAndQNames.QName.LocalName.Pretty; DebugFix.Assert(!string.IsNullOrEmpty(ugly)); DebugFix.Assert(!string.IsNullOrEmpty(pretty)); tq.BaseQName = new QualifiedName(new UglyPrettyName(ugly, pretty), tq.BaseQName.NamespaceUri); } } //DebugFix.Assert(!isTypeAlreadyRegistered); if (!isTypeAlreadyRegistered) { mRegisteredTypeAndQNames.Add(tq); } }
protected virtual void CreateDTBookDocument() { // check if there is preserved internal DTD //string[] dtbFilesList = Directory.GetFiles(m_Presentation.DataProviderManager.DataFileDirectoryFullPath, daisy.import.Daisy3_Import.INTERNAL_DTD_NAME, SearchOption.AllDirectories); //string strInternalDTD = null; //if (dtbFilesList.Length > 0) //{ // strInternalDTD = File.ReadAllText(dtbFilesList[0]); // if (strInternalDTD.Trim() == "") strInternalDTD = null; //} List <ExternalFileData> list_ExternalStyleSheets = new List <ExternalFileData>(); string strInternalDTD = null; foreach (ExternalFiles.ExternalFileData efd in m_Presentation.ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (RequestCancellation) { return; } if (efd is ExternalFiles.DTDExternalFileData && efd.OriginalRelativePath == daisy.import.Daisy3_Import.INTERNAL_DTD_NAME && !efd.IsPreservedForOutputFile && string.IsNullOrEmpty(strInternalDTD)) { StreamReader sr = new StreamReader(efd.OpenInputStream(), Encoding.UTF8); strInternalDTD = sr.ReadToEnd(); } else if (efd is ExternalFiles.CSSExternalFileData || efd is XSLTExternalFileData //&& !efd.OriginalRelativePath.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA) ) { list_ExternalStyleSheets.Add(efd); } } if (RequestCancellation) { return; } //m_ProgressPercentage = 0; reportProgress(-1, UrakawaSDK_daisy_Lang.CreatingXMLFile); XmlDocument DTBookDocument = XmlDocumentHelper.CreateStub_DTBDocument(m_Presentation.Language, strInternalDTD, list_ExternalStyleSheets); string mathML_XSLT = null; foreach (ExternalFileData efd in list_ExternalStyleSheets) { string filename = efd.OriginalRelativePath; if (filename.StartsWith(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA)) { filename = filename.Substring(SupportedMetadata_Z39862005.MATHML_XSLT_METADATA.Length); mathML_XSLT = filename; } filename = FileDataProvider.EliminateForbiddenFileNameCharacters(filename); if (efd.IsPreservedForOutputFile && !m_FilesList_ExternalFiles.Contains(filename)) { string filePath = Path.Combine(m_OutputDirectory, filename); efd.DataProvider.ExportDataStreamToFile(filePath, true); m_FilesList_ExternalFiles.Add(filename); } } string mathPrefix = m_Presentation.RootNode.GetXmlNamespacePrefix(DiagramContentModelHelper.NS_URL_MATHML); if (!string.IsNullOrEmpty(mathPrefix) && string.IsNullOrEmpty(mathML_XSLT)) { string appDir = System.AppDomain.CurrentDomain.BaseDirectory; string xsltFileName = FileDataProvider.EliminateForbiddenFileNameCharacters(SupportedMetadata_Z39862005._builtInMathMLXSLT); string xsltFullPath = Path.Combine(appDir, xsltFileName); if (File.Exists(xsltFullPath)) { string destFile = Path.Combine(m_OutputDirectory, xsltFileName); File.Copy(xsltFullPath, destFile, true); try { File.SetAttributes(destFile, FileAttributes.Normal); } catch { } m_FilesList_ExternalFiles.Add(xsltFileName); } } m_ListOfLevels = new List <TreeNode>(); Dictionary <string, string> old_New_IDMap = new Dictionary <string, string>(); List <XmlAttribute> referencingAttributesList = new List <XmlAttribute>(); // add metadata XmlNode headNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "head", null); //DTBookDocument.GetElementsByTagName("head")[0] Metadata mdId = AddMetadata_DtbUid(false, DTBookDocument, headNode); AddMetadata_Generator(DTBookDocument, headNode); bool hasMathML_z39_86_extension_version = false; bool hasMathML_DTBook_XSLTFallback = false; // todo: filter-out unecessary metadata for DTBOOK (e.g. dtb:multimediatype) foreach (Metadata m in m_Presentation.Metadatas.ContentsAs_Enumerable) { if (mdId == m) { continue; } XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); string name = m.NameContentAttribute.Name; if (name == SupportedMetadata_Z39862005._z39_86_extension_version) { hasMathML_z39_86_extension_version = true; } else if (name == SupportedMetadata_Z39862005.MATHML_XSLT_METADATA) { hasMathML_DTBook_XSLTFallback = true; } string prefix; string localName; urakawa.property.xml.XmlProperty.SplitLocalName(name, out prefix, out localName); if (!string.IsNullOrEmpty(prefix)) { // split the metadata name and make first alphabet upper, required for daisy 3.0 localName = localName.Substring(0, 1).ToUpper() + localName.Remove(0, 1); name = prefix + ":" + localName; } XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", name); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", m.NameContentAttribute.Value); // add metadata optional attributes if any foreach (MetadataAttribute ma in m.OtherAttributes.ContentsAs_Enumerable) { if (ma.Name == "id" || ma.Name == Metadata.PrimaryIdentifierMark) { continue; } XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, ma.Name, ma.Value); } } if (!string.IsNullOrEmpty(mathML_XSLT)) { DebugFix.Assert(hasMathML_z39_86_extension_version); DebugFix.Assert(hasMathML_DTBook_XSLTFallback); } if (!string.IsNullOrEmpty(mathPrefix) && !hasMathML_z39_86_extension_version) { XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", SupportedMetadata_Z39862005._z39_86_extension_version); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", "1.0"); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "scheme", DiagramContentModelHelper.NS_URL_MATHML); } if (!string.IsNullOrEmpty(mathPrefix) && !hasMathML_DTBook_XSLTFallback) { XmlNode metaNode = DTBookDocument.CreateElement(null, "meta", headNode.NamespaceURI); headNode.AppendChild(metaNode); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "name", SupportedMetadata_Z39862005.MATHML_XSLT_METADATA); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "content", string.IsNullOrEmpty(mathML_XSLT) ? SupportedMetadata_Z39862005._builtInMathMLXSLT : mathML_XSLT); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, metaNode, "scheme", DiagramContentModelHelper.NS_URL_MATHML); } // add elements to book body m_TreeNode_XmlNodeMap = new Dictionary <TreeNode, XmlNode>(); XmlNode bookNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "book", null); //DTBookDocument.GetElementsByTagName("book")[0]; if (bookNode == null) { bookNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "body", null); } XmlNode docRootNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "dtbook", null); if (docRootNode == null) { docRootNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(DTBookDocument, true, "html", null); } if (false && !string.IsNullOrEmpty(mathML_XSLT)) // namespace prefix attribute automatically added for each m:math element because of MathML DTD { XmlDocumentHelper.CreateAppendXmlAttribute( DTBookDocument, bookNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + "dtbook", bookNode.NamespaceURI, XmlReaderWriterHelper.NS_URL_XMLNS ); } m_ListOfLevels.Add(m_Presentation.RootNode); m_TreeNode_XmlNodeMap.Add(m_Presentation.RootNode, bookNode); XmlNode currentXmlNode = null; bool isHeadingNodeAvailable = true; m_Presentation.RootNode.AcceptDepthFirst( delegate(TreeNode n) { if (RequestCancellation) { return(false); } // add to list of levels if xml property has level string //QualifiedName qName = n.GetXmlElementQName(); //if (qName != null && // (qName.LocalName.StartsWith("level") || qName.LocalName == "doctitle" || qName.LocalName == "docauthor")) //{ // m_ListOfLevels.Add(n); //} if (doesTreeNodeTriggerNewSmil(n)) { if (!isHeadingNodeAvailable && m_ListOfLevels.Count > 1) { m_ListOfLevels.RemoveAt(m_ListOfLevels.Count - 1); //System.Windows.Forms.MessageBox.Show ( "removing :" + m_ListOfLevels.Count.ToString () ); } m_ListOfLevels.Add(n); isHeadingNodeAvailable = false; reportProgress(-1, UrakawaSDK_daisy_Lang.CreatingXMLFile); } if (IsHeadingNode(n)) { isHeadingNodeAvailable = true; } if (n.HasXmlProperty && (n.GetXmlElementLocalName() == "note" || n.GetXmlElementLocalName() == "annotation")) { m_NotesNodeList.Add(n); } property.xml.XmlProperty xmlProp = n.GetXmlProperty(); if (xmlProp == null) { string txtx = n.GetTextMedia() != null ? n.GetTextMedia().Text : null; if (txtx != null) { XmlNode textNode = DTBookDocument.CreateTextNode(txtx); ExternalAudioMedia extAudio = GetExternalAudioMedia(n); if (extAudio == null) { m_TreeNode_XmlNodeMap[n.Parent].AppendChild(textNode); m_TreeNode_XmlNodeMap.Add(n, textNode); } else { Debug.Fail("TreeNode without XmlProperty but with TextMedia cannot have Audio attached to it ! (reason: at authoring time, an XmlProperty should have been added when audio was recorded for the pure-text TreeNode) => " + txtx); //XmlNode textParent = DTBookDocument.CreateElement(null, "sent", bookNode.NamespaceURI); //textParent.AppendChild(textNode); //m_TreeNode_XmlNodeMap[n.Parent].AppendChild(textParent); //m_TreeNode_XmlNodeMap.Add(n, textParent); } } return(true); } // create sml node in dtbook document // code removed because XmlProperty stores proper namespaces, useful for inline MathML, SVG, whatever... //string name = xmlProp.LocalName; //string prefix = name.Contains(":") ? name.Split(':')[0] : null; //string elementName = name.Contains(":") ? name.Split(':')[1] : name; //currentXmlNode = DTBookDocument.CreateElement(prefix, elementName, bookNode.NamespaceURI); bool notBookRoot = !"book".Equals(xmlProp.LocalName, StringComparison.OrdinalIgnoreCase) && !"body".Equals(xmlProp.LocalName, StringComparison.OrdinalIgnoreCase); bool forceXmlNamespacePrefix = false; if ( //xmlProp.LocalName.Equals("math", StringComparison.OrdinalIgnoreCase) xmlProp.GetNamespaceUri() == DiagramContentModelHelper.NS_URL_MATHML && bookNode.LocalName.Equals("book", StringComparison.OrdinalIgnoreCase) ) { // Hack, because some MathML in DAISY is produced // with redundant (and DTD-invalid) xmlns="http://MATHML" forceXmlNamespacePrefix = true; } if (!notBookRoot) { currentXmlNode = bookNode; } else { XmlNode xmlNodeParent = m_TreeNode_XmlNodeMap[n.Parent]; string nsUri = n.GetXmlNamespaceUri(); if (string.IsNullOrEmpty(nsUri)) { nsUri = xmlNodeParent.NamespaceURI; } DebugFix.Assert(!string.IsNullOrEmpty(nsUri)); if (string.IsNullOrEmpty(nsUri)) { nsUri = bookNode.NamespaceURI; } if (string.IsNullOrEmpty(nsUri)) { nsUri = DTBookDocument.DocumentElement.NamespaceURI; } if (string.IsNullOrEmpty(nsUri)) { nsUri = DTBookDocument.NamespaceURI; } string prefix = (forceXmlNamespacePrefix || n.NeedsXmlNamespacePrefix()) ? n.GetXmlNamespacePrefix(nsUri) : null; currentXmlNode = DTBookDocument.CreateElement( prefix, xmlProp.LocalName, nsUri); xmlNodeParent.AppendChild(currentXmlNode); m_TreeNode_XmlNodeMap.Add(n, currentXmlNode); } // add attributes for (int i = 0; i < xmlProp.Attributes.Count; i++) { property.xml.XmlAttribute xmlAttr = xmlProp.Attributes.Get(i); string prefix = xmlAttr.Prefix; string nameWithoutPrefix = xmlAttr.PrefixedLocalName != null ? xmlAttr.PrefixedLocalName : xmlAttr.LocalName; if (!string.IsNullOrEmpty(prefix)) { string nsUriPrefix = xmlProp.GetNamespaceUri(prefix); if (string.IsNullOrEmpty(nsUriPrefix)) { #if DEBUG Debugger.Break(); #endif //DEBUG nsUriPrefix = currentXmlNode.GetNamespaceOfPrefix(prefix); } if (!string.IsNullOrEmpty(nsUriPrefix) && string.IsNullOrEmpty(DTBookDocument.DocumentElement.GetNamespaceOfPrefix(prefix)) && string.IsNullOrEmpty(bookNode.GetNamespaceOfPrefix(prefix))) { XmlDocumentHelper.CreateAppendXmlAttribute( DTBookDocument, docRootNode, //bookNode, XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":" + prefix, nsUriPrefix, XmlReaderWriterHelper.NS_URL_XMLNS ); } } //todo: check ID attribute, normalize with fresh new list of IDs // (warning: be careful maintaining ID REFS, such as idref attributes for annotation/annoref and prodnote/noteref // (be careful because idref contain URIs with hash character), // and also the special imgref and headers attributes which contain space-separated list of IDs, not URIs) if (nameWithoutPrefix == "id") // xmlAttr.LocalName == "id" || xmlAttr.LocalName == XmlReaderWriterHelper.XmlId) { string id_New = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "id", id_New); if (!old_New_IDMap.ContainsKey(xmlAttr.Value)) { old_New_IDMap.Add(xmlAttr.Value, id_New); } else { System.Diagnostics.Debug.Fail("Duplicate ID found in original DTBook document", "Original DTBook document has duplicate ID: " + xmlProp.Attributes.Get(i).Value); } } else { XmlNode xmlNd = null; if (currentXmlNode == bookNode && (prefix == XmlReaderWriterHelper.NS_PREFIX_XMLNS || nameWithoutPrefix == "lang")) { // Hack: to make sure DTD validation passes. xmlNd = docRootNode; } else { xmlNd = currentXmlNode; } if (forceXmlNamespacePrefix && nameWithoutPrefix == XmlReaderWriterHelper.NS_PREFIX_XMLNS && xmlAttr.Value == DiagramContentModelHelper.NS_URL_MATHML ) { bool debug = true; // skip xmlns="http://MATH" } else { XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, xmlNd, xmlAttr.LocalName, xmlAttr.Value, xmlAttr.GetNamespaceUri()); } } } // for loop ends if (!notBookRoot) { return(true); } if (xmlProp.LocalName == "imggroup") { m_TempImageId = new List <string>(1); } if (m_TempImageId != null && // !string.IsNullOrEmpty(m_TempImageId) (xmlProp.LocalName == "caption" || xmlProp.LocalName == "prodnote")) { string imgIds = ""; foreach (string imgId in m_TempImageId) { imgIds += imgId + " "; } imgIds = imgIds.Trim(); if (!string.IsNullOrEmpty(imgIds)) { XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "imgref", imgIds); } } XmlAttributeCollection currentXmlNodeAttrs = currentXmlNode.Attributes; // add id attribute in case it do not exists and it is required if (IsIDRequired(currentXmlNode.LocalName) && currentXmlNodeAttrs != null) { XmlNode idAttr = currentXmlNodeAttrs.GetNamedItem("id"); if (idAttr == null) { string id = GetNextID(ID_DTBPrefix); XmlDocumentHelper.CreateAppendXmlAttribute(DTBookDocument, currentXmlNode, "id", id); } else if (xmlProp.LocalName != null && xmlProp.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase) && m_TempImageId != null) { string id = idAttr.Value; m_TempImageId.Add(id); } } // add text from text property string txt = n.GetTextMedia() != null ? n.GetTextMedia().Text : null; if (txt != null) { XmlNode textNode = DTBookDocument.CreateTextNode(txt); currentXmlNode.AppendChild(textNode); DebugFix.Assert(n.Children.Count == 0); } // if current xmlnode is referencing node, add its referencing attribute to referencingAttributesList AddReferencingNodeToReferencedAttributesList(currentXmlNode, referencingAttributesList); if (currentXmlNodeAttrs != null && currentXmlNode.LocalName != null) { bool isHTML = @"body".Equals(m_Presentation.RootNode.GetXmlElementLocalName(), StringComparison.OrdinalIgnoreCase); //n.Presentation // TODO: special treatment of subfolders in file paths (restore full hierarchy, including OPF, XHTMLs, etc., not just referenced media assets) if (currentXmlNode.LocalName.Equals("img", StringComparison.OrdinalIgnoreCase)) { XmlAttribute imgSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); if (imgSrcAttribute != null && n.GetImageMedia() != null && n.GetImageMedia() is media.data.image.ManagedImageMedia) { media.data.image.ManagedImageMedia managedImage = (media.data.image.ManagedImageMedia)n.GetImageMedia(); //if (FileDataProvider.isHTTPFile(managedImage.ImageMediaData.OriginalRelativePath)) //exportImageName = Path.GetFileName(managedImage.ImageMediaData.OriginalRelativePath); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string destPath = Path.Combine(m_OutputDirectory, exportImageName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedImage.ImageMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } imgSrcAttribute.Value = FileDataProvider.UriEncode(exportImageName); if (!m_FilesList_Image.Contains(exportImageName)) { m_FilesList_Image.Add(exportImageName); } generateImageDescriptionInDTBook(n, currentXmlNode, exportImageName, DTBookDocument); } } else if (currentXmlNode.LocalName.Equals(DiagramContentModelHelper.Math, StringComparison.OrdinalIgnoreCase)) { XmlAttribute imgSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("altimg"); if (imgSrcAttribute != null && n.GetImageMedia() != null && n.GetImageMedia() is media.data.image.ManagedImageMedia) { media.data.image.ManagedImageMedia managedImage = (media.data.image.ManagedImageMedia)n.GetImageMedia(); //if (FileDataProvider.isHTTPFile(managedImage.ImageMediaData.OriginalRelativePath)) //exportImageName = Path.GetFileName(managedImage.ImageMediaData.OriginalRelativePath); string exportImageName = //Path.GetFileName FileDataProvider.EliminateForbiddenFileNameCharacters (managedImage.ImageMediaData.OriginalRelativePath) ; string destPath = Path.Combine(m_OutputDirectory, exportImageName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedImage.ImageMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } imgSrcAttribute.Value = FileDataProvider.UriEncode(exportImageName); if (!m_FilesList_Image.Contains(exportImageName)) { m_FilesList_Image.Add(exportImageName); } } } #if SUPPORT_AUDIO_VIDEO else if (currentXmlNode.LocalName.Equals("video", StringComparison.OrdinalIgnoreCase) || ( currentXmlNode.LocalName.Equals("source", StringComparison.OrdinalIgnoreCase) && currentXmlNode.ParentNode != null && currentXmlNode.ParentNode.LocalName.Equals("video", StringComparison.OrdinalIgnoreCase) ) ) { XmlAttribute videoSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); if (videoSrcAttribute != null && n.GetVideoMedia() != null && n.GetVideoMedia() is ManagedVideoMedia) { ManagedVideoMedia managedVideo = (ManagedVideoMedia)n.GetVideoMedia(); //if (FileDataProvider.isHTTPFile(managedVideo.VideoMediaData.OriginalRelativePath)) //exportVideoName = Path.GetFileName(managedVideo.VideoMediaData.OriginalRelativePath); string exportVideoName = FileDataProvider.EliminateForbiddenFileNameCharacters( managedVideo.VideoMediaData.OriginalRelativePath); string destPath = Path.Combine(m_OutputDirectory, exportVideoName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedVideo.VideoMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } videoSrcAttribute.Value = FileDataProvider.UriEncode(exportVideoName); if (!m_FilesList_Video.Contains(exportVideoName)) { m_FilesList_Video.Add(exportVideoName); } } } else if (currentXmlNode.LocalName.Equals("audio", StringComparison.OrdinalIgnoreCase) || ( currentXmlNode.LocalName.Equals("source", StringComparison.OrdinalIgnoreCase) && currentXmlNode.ParentNode != null && currentXmlNode.ParentNode.LocalName.Equals("audio", StringComparison.OrdinalIgnoreCase) ) ) { XmlAttribute audioSrcAttribute = (XmlAttribute)currentXmlNodeAttrs.GetNamedItem("src"); ManagedAudioMedia managedAudio = n.GetManagedAudioMedia(); if (audioSrcAttribute != null && managedAudio != null) { //if (FileDataProvider.isHTTPFile(managedAudio.AudioMediaData.OriginalRelativePath)) //exportAudioName = Path.GetFileName(managedAudio.AudioMediaData.OriginalRelativePath); string exportAudioName = FileDataProvider.EliminateForbiddenFileNameCharacters( managedAudio.AudioMediaData.OriginalRelativePath); string destPath = Path.Combine(m_OutputDirectory, exportAudioName); if (!File.Exists(destPath)) { if (RequestCancellation) { return(false); } managedAudio.AudioMediaData.DataProvider.ExportDataStreamToFile(destPath, false); } audioSrcAttribute.Value = FileDataProvider.UriEncode(exportAudioName); if (!m_FilesList_Audio.Contains(exportAudioName)) { m_FilesList_Audio.Add(exportAudioName); } } } #endif } return(true); }, delegate(urakawa.core.TreeNode n) { property.xml.XmlProperty xmlProp = n.GetXmlProperty(); //QualifiedName qName = n.GetXmlElementQName(); if (xmlProp != null && xmlProp.LocalName == "imggroup") { m_TempImageId = null; } }); if (RequestCancellation) { return; } // set references to new ids foreach (XmlAttribute attr in referencingAttributesList) { string strIDToFind = attr.Value; if (strIDToFind.IndexOf('#') >= 0) //strIDToFind.Contains("#") { strIDToFind = strIDToFind.Split('#')[1]; } string str; old_New_IDMap.TryGetValue(strIDToFind, out str); if (!string.IsNullOrEmpty(str)) //old_New_IDMap.ContainsKey(strIDToFind)) { string id_New = str; // old_New_IDMap[strIDToFind]; attr.Value = "#" + id_New; } } m_DTBDocument = DTBookDocument; //CommonFunctions.WriteXmlDocumentToFile(DTBookDocument, // Path.Combine(m_OutputDirectory, m_Filename_Content)); }
public List <Section> GetOrCreateOutline() { string localXmlName = GetXmlElementLocalName(); if (string.IsNullOrEmpty(localXmlName) || ( !IsSectioningContent(localXmlName) && !IsSectioningRoot(localXmlName) )) { Outline = null; return(null); } if (Outline != null) { return(Outline); } TreeNode currentOutlinee = null; Section currentSection = null; Stack <TreeNode> stack = new Stack <TreeNode>(); PreVisitDelegate enterNode = delegate(TreeNode node) { node.Outline = null; if (stack.Count > 0) { TreeNode top = stack.Peek(); if (IsHeading(top.GetXmlElementLocalName())) { return(true); } } string name = node.GetXmlElementLocalName(); if (IsSectioningContent(name) || IsSectioningRoot(name)) { //if (currentOutlinee != null && currentSection != null && currentSection.Heading == null) //{ // currentSection.HeadingImplied = true; //} if (currentOutlinee != null) { stack.Push(currentOutlinee); } currentOutlinee = node; currentSection = new Section(); currentSection.RealSectioningRootOrContent = currentOutlinee; currentOutlinee.Outline = new List <Section>(); currentOutlinee.Outline.Add(currentSection); return(true); } if (currentOutlinee == null) { return(true); } if (IsHeading(name)) { Section section = null; if (currentSection != null && currentSection.Heading == null) { currentSection.Heading = node; } else if ( currentOutlinee.Outline == null || ( currentOutlinee.Outline.Count > 0 && (section = currentOutlinee.Outline[currentOutlinee.Outline.Count - 1]).Heading != null && node.GetHeadingRank() <= section.Heading.GetHeadingRank() ) ) { Section newSection = new Section(); newSection.Heading = node; if (currentOutlinee.Outline == null) { currentOutlinee.Outline = new List <Section>(); } currentOutlinee.Outline.Add(newSection); currentSection = newSection; } else { Section candidate = currentSection; while (candidate != null) { if (candidate.Heading != null && node.GetHeadingRank() > candidate.Heading.GetHeadingRank()) { Section newSection = new Section(); newSection.Heading = node; candidate.SubSections.Add(newSection); newSection.ParentSection = candidate; currentSection = newSection; break; } candidate = candidate.ParentSection; } } stack.Push(node); } return(true); }; PostVisitDelegate exitNode = delegate(TreeNode node) { string name = node.GetXmlElementLocalName(); if (stack.Count > 0) { TreeNode top = stack.Peek(); if (top != null && top == node) { DebugFix.Assert(IsHeading(name)); stack.Pop(); return; } } bool isSectioningContent = IsSectioningContent(name); bool isSectioningRoot = IsSectioningRoot(name); if (isSectioningContent || isSectioningRoot) { if (stack.Count > 0) { currentOutlinee = stack.Pop(); if (currentOutlinee.Outline != null && currentOutlinee.Outline.Count > 0) { currentSection = currentOutlinee.Outline[currentOutlinee.Outline.Count - 1]; } if (isSectioningContent) { if (currentSection != null && node.Outline != null) { for (int i = 0; i < node.Outline.Count; i++) { Section section = node.Outline[i]; currentSection.SubSections.Add(section); section.ParentSection = currentSection; } } } else if (isSectioningRoot) { while (currentSection != null && currentSection.SubSections != null && currentSection.SubSections.Count > 0) { currentSection = currentSection.SubSections[currentSection.SubSections.Count - 1]; } } } else { if (currentOutlinee.Outline != null && currentOutlinee.Outline.Count > 0) { currentSection = currentOutlinee.Outline[0]; } } } }; AcceptDepthFirst(enterNode, exitNode); if (currentOutlinee != null) { DebugFix.Assert(Object.ReferenceEquals(currentOutlinee, this)); } return(currentOutlinee != null ? currentOutlinee.Outline : null); }
/// <summary> /// Gets Operating System Name, Service Pack, and Architecture using WMI with the legacy methods as a fallback /// </summary> /// <returns>String containing the name of the operating system followed by its service pack (if any) and architecture</returns> private static string getOSInfo() { var objMOS = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); //Variables to hold our return value string os = ""; int OSArch = 0; try { foreach (ManagementObject objManagement in objMOS.Get()) { // Get OS version from WMI - This also gives us the edition object osCaption = objManagement.GetPropertyValue("Caption"); if (osCaption != null) { // Remove all non-alphanumeric characters so that only letters, numbers, and spaces are left. string osC = Regex.Replace(osCaption.ToString(), "[^A-Za-z0-9 ]", ""); //string osC = osCaption.ToString(); // If the OS starts with "Microsoft," remove it. We know that already if (osC.StartsWith("Microsoft")) { osC = osC.Substring(9); } // If the OS now starts with "Windows," again... useless. Remove it. if (osC.Trim().StartsWith("Windows")) { osC = osC.Trim().Substring(7); } // Remove any remaining beginning or ending spaces. os = osC.Trim(); // Only proceed if we actually have an OS version - service pack is useless without the OS version. if (!String.IsNullOrEmpty(os)) { object osSP = null; try { // Get OS service pack from WMI osSP = objManagement.GetPropertyValue("ServicePackMajorVersion"); if (osSP != null && osSP.ToString() != "0") { os += " Service Pack " + osSP.ToString(); } else { // Service Pack not found. Try built-in Environment class. os += getOSServicePackLegacy(); } } catch (Exception) { // There was a problem getting the service pack from WMI. Try built-in Environment class. os += getOSServicePackLegacy(); } } object osA = null; try { // Get OS architecture from WMI osA = objManagement.GetPropertyValue("OSArchitecture"); if (osA != null) { string osAString = osA.ToString(); // If "64" is anywhere in there, it's a 64-bit architectore. OSArch = (osAString.Contains("64") ? 64 : 32); } } catch (Exception) { } } } } catch (Exception) { } // If WMI couldn't tell us the OS, use our legacy method. // We won't get the exact OS edition, but something is better than nothing. if (os == "") { os = getOSLegacy(); } // If WMI couldn't tell us the architecture, use our legacy method. if (OSArch == 0) { OSArch = getOSArchitectureLegacy(); } else { #if NET40 DebugFix.Assert((OSArch == 64) == Environment.Is64BitOperatingSystem); #endif } return(os + " " + OSArch.ToString() + "-bit"); }
/// <summary> /// The shell is loaded at this stage, so we load the rest of the application /// by discovering plugins and the extension points they fulfill, /// and by resolving instances through the MEF dependency graph. /// </summary> protected override void InitializeModules() { // Does nothing, as we do not use any real CAG IModule (only the dummy empty one). base.InitializeModules(); var shell = Container.TryResolve <IShellView>(); DebugFix.Assert(shell != null); // MEF will fetch DLL assemblies adjacent to the Tobi.exe executable // We could add support for a special "plugin" folder, // using something like: + Path.DirectorySeparatorChar + "addons"; string mefDir = AppDomain.CurrentDomain.BaseDirectory; // sowe can call dirCatalog.Refresh(); when needed (which triggers re-composition) //var dirCatalog = new DirectoryCatalog(mefDir, @"Tobi.Plugin.*.dll"); //Container.RegisterCatalog(dirCatalog); // Any MEF part exported from this directory will take precedence over the built-in Tobi ones. // As a result, a single Import (as opposed to ImportMany) that has several realizations // (i.e. the default/fallback Tobi implementation and the custom Extension) // will not trigger an exception (as it is normally the case), instead the Extension will be returned, and the built-in feature ignored. var directories = Directory.GetDirectories(mefDir, @"Extensions", SearchOption.TopDirectoryOnly); // @"*.*" foreach (var directory in directories) { try { // We use the direct loading below to avoid UNC network drives issues. //Container.RegisterCatalog(new DirectoryCatalog(directory)); var extensionsAggregateCatalog = new AggregateCatalog(); foreach (string file in Directory.GetFiles(directory, "*.dll")) { var assembly = Assembly.LoadFrom(file); extensionsAggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly)); } Container.RegisterCatalog(extensionsAggregateCatalog); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } } //var dirCatalog = new DirectoryCatalog(mefDir, @"Tobi.Plugin.MenuBarDebug*.dll"); //Container.RegisterCatalog(dirCatalog); var tobiModulesExtensions = MefContainer.GetExportedValues <ITobiPlugin>(); foreach (var tobiModuleEXT in tobiModulesExtensions) { DebugFix.Assert(!string.IsNullOrEmpty(tobiModuleEXT.Name) && !string.IsNullOrEmpty(tobiModuleEXT.Description)); LoggerFacade.Log(@"Loaded extension plugin: [[" + tobiModuleEXT.Name + @"]] [[" + tobiModuleEXT.Description + @"]]", Category.Debug, Priority.Low); } // NOTE: we're loading assemblies manually so that they get picked-up by ClickOnce deployment (and it means we can control the order of registration). try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(UrakawaPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(AbstractTobiPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(AudioPanePlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(ValidatorPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(MetadataValidatorPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(ContentDocumentValidatorPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(MissingAudioValidatorPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(MetadataPanePlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(StructureTrailPanePlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(DocumentPanePlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AggregateCatalog(new ComposablePartCatalog[] { //new AssemblyCatalog(Assembly.GetAssembly(typeof(HeadingNavigationPlugin))), // in the same assembly as the main Navigation Plugin, so not needed //new AssemblyCatalog(Assembly.GetAssembly(typeof(PageNavigationPlugin))), // in the same assembly as the main Navigation Plugin, so not needed //new AssemblyCatalog(Assembly.GetAssembly(typeof(MarkersNavigationPlugin))), // in the same assembly as the main Navigation Plugin, so not needed new AssemblyCatalog(Assembly.GetAssembly(typeof(NavigationPanePlugin))) })); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { //new AssemblyCatalog(Assembly.GetAssembly(typeof(DescriptionsNavigationPlugin))), // in the same assembly as the main Navigation Plugin, so not needed Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(DescriptionsPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } //MessageBox.Show(@"Urakawa session should now be resolved (window title changed)"); var tobiModules = MefContainer.GetExportedValues <ITobiPlugin>(); foreach (var tobiModule in tobiModules) { DebugFix.Assert(!string.IsNullOrEmpty(tobiModule.Name) && !string.IsNullOrEmpty(tobiModule.Description)); LoggerFacade.Log( @"Loaded plugin: [[" + tobiModule.Name + @"]] [[" + tobiModule.Version + @"]] [[" + tobiModule.Description + @"]]", Category.Debug, Priority.Low); } //MessageBox.Show(@"Urakawa module is loaded but it 'waits' for a toolbar to push its commands: press ok to get the toolbar view to load (but not to display yet)"); // This artificially emulates the dynamic loading of the Toolbar and Menubar plugin: // the container gets composed again and the modules dependent on the toolbar/menubar gets satisified try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(ToolBarsPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(MenuBarPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } try { Container.RegisterFallbackCatalog(new AssemblyCatalog(Assembly.GetAssembly(typeof(SettingsPlugin)))); } catch (Exception ex) { ExceptionHandler.Handle(ex, false, shell); } //MessageBox.Show(@"After pressing ok the toolbar module will load to integrate the view into the window"); var tobiModulesAFTER = MefContainer.GetExportedValues <ITobiPlugin>(); foreach (var tobiModuleAFTER in tobiModulesAFTER) { DebugFix.Assert(!string.IsNullOrEmpty(tobiModuleAFTER.Name) && !string.IsNullOrEmpty(tobiModuleAFTER.Description)); LoggerFacade.Log(@"Loaded plugin AFTER: [[" + tobiModuleAFTER.Name + @"]] [[" + tobiModuleAFTER.Description + @"]]", Category.Debug, Priority.Low); } // In ClickOnce application manifest: //<fileAssociation xmlns="urn:schemas-microsoft-com:clickonce.v1" extension=".text" description="Text Document (ClickOnce)" progid="Text.Document" defaultIcon="text.ico" /> // // Arguments for ClickOnce-actived application are passed here (including file path due to file extension association): //string[] args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData; //if (args != null && args.Length != 0) //{ // try // { // Uri uri = new Uri(args[0]); // if (!uri.IsFile) // throw new UriFormatException("The URI " + uri + " is not a file."); // OpenFile(uri.AbsolutePath); // } // catch (UriFormatException) // { // MessageBox.Show("Invalid file specified.", Program.Name); // } //} // The code below is totally obsolete, as we are not using CAG modules. //var name = typeof (UrakawaModule).Name; //var moduleCatalog = Container.Resolve<IModuleCatalog>(); //foreach (var module in moduleCatalog.Modules) //{ // if (module.ModuleName == name) // { // var moduleManager = Container.Resolve<IModuleManager>(); // moduleManager.LoadModule(module.ModuleName); // } //} usageReport(shell); }
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); Settings.Default.UseTitleInFileNames //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, }; checkAuto.Checked += new RoutedEventHandler((sender, ev) => { combo.IsEnabled = false; checkBox.IsEnabled = false; label_.IsEnabled = false; }); checkAuto.Unchecked += new RoutedEventHandler((sender, ev) => { combo.IsEnabled = true; checkBox.IsEnabled = true; label_.IsEnabled = true; }); 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(panel_); panel.Children.Add(combo); 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; } bool useTitleInFileName = Settings.Default.UseTitleInFileNames; var converter = new Daisy3_Import(DocumentFilePath, useTitleInFileName, 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); if (useTitleInFileName) { 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); }
private void EncodeTransientFileResample(TreeNode node) { string sourceFilePath = base.GetCurrentAudioFileUri().LocalPath; //string destinationFilePath = Path.Combine(base.DestinationDirectory.LocalPath, Path.GetFileNameWithoutExtension(sourceFilePath) + "_" + base.EncodePublishedAudioFilesSampleRate + DataProviderFactory.AUDIO_WAV_EXTENSION); //reportProgress(m_ProgressPercentage, String.Format(UrakawaSDK_daisy_Lang.ConvertingAudio,sourceFilePath)); ExternalAudioMedia extMedia = m_ExternalAudioMediaList[0]; PCMFormatInfo audioFormat = extMedia.Presentation.MediaDataManager.DefaultPCMFormat; //AudioLibPCMFormat pcmFormat = audioFormat.Data; AudioLibPCMFormat pcmFormat = new AudioLibPCMFormat(); pcmFormat.CopyFrom(audioFormat.Data); pcmFormat.SampleRate = (ushort)base.EncodePublishedAudioFilesSampleRate; pcmFormat.NumberOfChannels = (ushort)(base.EncodePublishedAudioFilesStereo ? 2 : 1); AudioLib.WavFormatConverter formatConverter = new WavFormatConverter(true, DisableAcmCodecs); AddSubCancellable(formatConverter); string destinationFilePath = null; try { AudioLibPCMFormat originalPcmFormat; destinationFilePath = formatConverter.ConvertSampleRate(sourceFilePath, base.DestinationDirectory.LocalPath, pcmFormat, out originalPcmFormat); if (originalPcmFormat != null) { DebugFix.Assert(audioFormat.Data.Equals(originalPcmFormat)); } } finally { RemoveSubCancellable(formatConverter); } //string sourceName = Path.GetFileNameWithoutExtension(sourceFilePath); //string destName = Path.GetFileNameWithoutExtension(destinationFilePath); //foreach (ExternalAudioMedia ext in m_ExternalAudioMediaList) //{ //if (ext != null) //{ //ext.Src = ext.Src.Replace(sourceName, destName); //} //} File.Delete(sourceFilePath); File.Move(destinationFilePath, sourceFilePath); try { File.SetAttributes(sourceFilePath, FileAttributes.Normal); } catch { } m_ExternalAudioMediaList.Clear(); }
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 } } }
//#endif private void initializeCommands_Recorder() { Stopwatch stopWatchRecorder = null; CommandStopRecordAndContinue = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioStopRecordAndContinue_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioStopRecordAndContinue_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadTangoIcon("start-here"), //weather-clear-night -- emblem-symbolic-link () => { Logger.Log("AudioPaneViewModel.CommandStopRecordAndContinue", Category.Debug, Priority.Medium); if (stopWatchRecorder != null) { stopWatchRecorder.Stop(); if (stopWatchRecorder.ElapsedMilliseconds <= 100) { Console.WriteLine("stopWatchRecorder.ElapsedMilliseconds<=100, skipping stop record"); stopWatchRecorder.Start(); return; } Console.WriteLine("stopWatchRecorder.ElapsedMilliseconds, elapsed record :" + stopWatchRecorder.ElapsedMilliseconds); } stopWatchRecorder = null; IsAutoPlay = false; m_RecordAndContinue = true; m_InterruptRecording = false; if (!Settings.Default.Audio_DisableSingleWavFileRecord) { m_RecordAndContinue_StopBytePos = (long)m_Recorder.CurrentDurationBytePosition_BufferLookAhead; OnAudioRecordingFinished(null, new AudioRecorder.AudioRecordingFinishEventArgs( m_Recorder.RecordedFilePath)); } else { m_Recorder.StopRecording(); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.RecordingStopped); } } //ENABLE_SINGLE_RECORD_FILE }, () => { //Tuple<TreeNode, TreeNode> treeNodeSelection = m_UrakawaSession.GetTreeNodeSelection(); return(!IsWaveFormLoading && IsRecording && m_UrakawaSession.DocumentProject != null); }, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_StopRecordAndContinue)); m_ShellView.RegisterRichCommand(CommandStopRecordAndContinue); // CommandStopRecord = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioStopRecord_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioStopRecord_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadTangoIcon("media-playback-stop"), () => { Logger.Log("AudioPaneViewModel.CommandStopRecord", Category.Debug, Priority.Medium); if (stopWatchRecorder != null) { stopWatchRecorder.Stop(); if (stopWatchRecorder.ElapsedMilliseconds <= 50) { Console.WriteLine("stopWatchRecorder.ElapsedMilliseconds<=50, skipping stop record"); stopWatchRecorder.Start(); return; } Console.WriteLine("stopWatchRecorder.ElapsedMilliseconds, elapsed record :" + stopWatchRecorder.ElapsedMilliseconds); } stopWatchRecorder = null; m_RecordAndContinue = false; m_Recorder.StopRecording(); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.RecordingStopped); } if (IsMonitoringAlways) { CommandStartMonitor.Execute(); } }, () => !IsWaveFormLoading && IsRecording, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_StartStopRecord)); m_ShellView.RegisterRichCommand(CommandStopRecord); // CommandStartRecord = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioStartRecord_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioStartRecord_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadTangoIcon("media-record"), () => { Logger.Log("AudioPaneViewModel.CommandStartRecord", Category.Debug, Priority.Medium); m_RecordAndContinue_StopBytePos = -1; if (stopWatchRecorder != null) { Console.WriteLine("stopWatchRecorder != null, skipping start record"); return; } if (IsMonitoring) { CommandStopMonitor.Execute(); } IsAutoPlay = false; bool allowPlayPreview = false; m_punchInRecordOverSelection = false; if (IsPlaying) // Punch-in recording { SetRecordAfterPlayOverwriteSelection(-1); m_punchInRecordOverSelection = true; CommandPause.Execute(); CommandSelectRight.Execute(); } else if (Settings.Default.Audio_EnableRecordOverwrite && !IsSelectionSet) { SetRecordAfterPlayOverwriteSelection(-1); m_punchInRecordOverSelection = true; if (PlayBytePosition >= 0) { allowPlayPreview = true; CommandSelectRight.Execute(); } else { CommandSelectAll.Execute(); } } if (IsWaveFormLoading && View != null) { View.CancelWaveFormLoad(true); } m_RecordAndContinue = false; if (m_UrakawaSession.DocumentProject == null) { SetRecordAfterPlayOverwriteSelection(-1); State.ResetAll(); State.Audio.PcmFormatRecordingMonitoring = new PCMFormatInfo(); } else { Tuple <TreeNode, TreeNode> treeNodeSelection = m_UrakawaSession.GetTreeNodeSelection(); if (treeNodeSelection.Item1 == null) { SetRecordAfterPlayOverwriteSelection(-1); return; } if (!m_punchInRecordOverSelection || allowPlayPreview) // let's check auto punch in/out based on audio selection { var bytesForRequiredOffsetTime = m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.DefaultPCMFormat. Data.ConvertTimeToBytes(150 * AudioLibPCMFormat.TIME_UNIT); if (State.Selection.SelectionBeginBytePosition > 0 && PlayBytePosition >= 0 && PlayBytePosition < State.Selection.SelectionBeginBytePosition - bytesForRequiredOffsetTime) { AudioPlayer_PlayFromTo(PlayBytePosition, State.Selection.SelectionBeginBytePosition); SetRecordAfterPlayOverwriteSelection(State.Selection.SelectionBeginBytePosition); return; } else if (Settings.Default.Audio_EnablePlayPreviewBeforeRecord && m_RecordAfterPlayOverwriteSelection < 0 && PlayBytePosition > 0) { var playbackStartBytePos = m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.DefaultPCMFormat. Data.ConvertTimeToBytes((long)Settings.Default.AudioWaveForm_PlayPreviewTimeStep * 2 * AudioLibPCMFormat.TIME_UNIT); playbackStartBytePos = PlayBytePosition - playbackStartBytePos; if (playbackStartBytePos < 0) { playbackStartBytePos = 0; } SetRecordAfterPlayOverwriteSelection(State.Selection.SelectionBeginBytePosition > 0 ? State.Selection.SelectionBeginBytePosition : PlayBytePosition); AudioPlayer_PlayFromTo(playbackStartBytePos, PlayBytePosition); return; } SetRecordAfterPlayOverwriteSelection(-1); } DebugFix.Assert(m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.EnforceSinglePCMFormat); State.Audio.PcmFormatRecordingMonitoring = m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.DefaultPCMFormat; } OnSettingsPropertyChanged(this, new PropertyChangedEventArgs(GetMemberName(() => Settings.Default.Audio_InputDevice))); stopWatchRecorder = Stopwatch.StartNew(); m_Recorder.StartRecording(State.Audio.PcmFormatRecordingMonitoring.Copy().Data); RaisePropertyChanged(() => State.Audio.PcmFormatRecordingMonitoring); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.Recording); } }, () => { return((!IsMonitoring || IsMonitoringAlways) && !IsRecording && !IsWaveFormLoading && //!IsPlaying && canDeleteInsertReplaceAudio()); }, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_StartStopRecord)); m_ShellView.RegisterRichCommand(CommandStartRecord); // // CommandStopMonitor = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioStopMonitor_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioStopMonitor_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadTangoIcon("media-playback-stop"), () => { Logger.Log("AudioPaneViewModel.CommandStopMonitor", Category.Debug, Priority.Medium); m_Recorder.StopRecording(); //AudioCues.PlayTockTock(); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.MonitoringStopped); } State.Audio.PcmFormatRecordingMonitoring = null; }, () => !IsWaveFormLoading && IsMonitoring, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_StartStopMonitor)); m_ShellView.RegisterRichCommand(CommandStopMonitor); // CommandStartMonitor = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioStartMonitor_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioStartMonitor_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadTangoIcon("audio-input-microphone"), () => { Logger.Log("AudioPaneViewModel.CommandStartMonitor", Category.Debug, Priority.Medium); m_RecordAndContinue_StopBytePos = -1; // to avoid display of m_RecordAndContinue time stamp IsAutoPlay = false; if (m_UrakawaSession.DocumentProject == null) { State.ResetAll(); State.Audio.PcmFormatRecordingMonitoring = new PCMFormatInfo(); //m_PcmFormatOfAudioToInsert = IsAudioLoaded ? State.Audio.PcmFormat : new PCMFormatInfo(); //m_Recorder.InputDevice.Capture.Caps.Format44KhzMono16Bit } else { DebugFix.Assert(m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.EnforceSinglePCMFormat); State.Audio.PcmFormatRecordingMonitoring = m_UrakawaSession.DocumentProject.Presentations.Get(0).MediaDataManager.DefaultPCMFormat; } OnSettingsPropertyChanged(this, new PropertyChangedEventArgs(GetMemberName(() => Settings.Default.Audio_InputDevice))); //AudioCues.PlayTock(); m_Recorder.StartMonitoring(State.Audio.PcmFormatRecordingMonitoring.Copy().Data); RaisePropertyChanged(() => State.Audio.PcmFormatRecordingMonitoring); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.Monitoring); } }, () => !IsWaveFormLoading && !IsPlaying && !IsRecording && !IsMonitoring, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_StartStopMonitor)); m_ShellView.RegisterRichCommand(CommandStartMonitor); // CommandTogglePlayPreviewBeforeRecord = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioTogglePlayPreviewBeforeRecord_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioTogglePlayPreviewBeforeRecord_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) m_ShellView.LoadGnomeGionIcon("Gion_music-player"), () => { Settings.Default.Audio_EnablePlayPreviewBeforeRecord = !Settings.Default.Audio_EnablePlayPreviewBeforeRecord; RaisePropertyChanged(() => RecordPlayPreviewString); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.AudioRecordPlayPreview + (Settings.Default.Audio_EnablePlayPreviewBeforeRecord ? " [ON]" : " [OFF]")); } }, () => true, Settings_KeyGestures.Default, PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_TogglePlayPreviewBeforeRecord)); m_ShellView.RegisterRichCommand(CommandTogglePlayPreviewBeforeRecord); // CommandToggleRecordOverwrite = new RichDelegateCommand( Tobi_Plugin_AudioPane_Lang.CmdAudioToggleRecordOverwrite_ShortDesc, Tobi_Plugin_AudioPane_Lang.CmdAudioToggleRecordOverwrite_LongDesc, null, // KeyGesture obtained from settings (see last parameters below) null, //m_ShellView.LoadGnomeGionIcon("Gion_music-player"), () => { Settings.Default.Audio_EnableRecordOverwrite = !Settings.Default.Audio_EnableRecordOverwrite; RaisePropertyChanged(() => RecordOverwriteString); if (EventAggregator != null) { EventAggregator.GetEvent <StatusBarMessageUpdateEvent>().Publish(Tobi_Plugin_AudioPane_Lang.AudioRecordOverwrite + (Settings.Default.Audio_EnableRecordOverwrite ? " [ON]" : " [OFF]")); } }, () => true, Settings_KeyGestures.Default, null //PropertyChangedNotifyBase.GetMemberName(() => Settings_KeyGestures.Default.Keyboard_Audio_TogglePlayPreviewBeforeRecord) ); m_ShellView.RegisterRichCommand(CommandToggleRecordOverwrite); }
public static string NormaliseFullFilePath(string fullPath) { bool absolute = Path.IsPathRooted(fullPath); DebugFix.Assert(absolute); if (!absolute) { return(fullPath); } char sep = Path.DirectorySeparatorChar; DebugFix.Assert(sep == '\\'); // We're on Windows! if (sep == '\\' && fullPath.IndexOf('/') >= 0) { fullPath = fullPath.Replace('/', sep); } else if (sep == '/' && fullPath.IndexOf('\\') >= 0) { fullPath = fullPath.Replace('\\', sep); } //fullPath = fullPath.TrimEnd(new char[] {sep}); //fullPath = fullPath.TrimEnd(sep); if ( fullPath.Length > 1 && fullPath[fullPath.Length - 1] == sep //fullPath.LastIndexOf(sep) == fullPath.Length - 1 ) { fullPath = fullPath.Substring(0, fullPath.Length - 1); } // Path.GetFullPath accesses the filesystem when the file exists. // fullPath = Path.GetFullPath(fullPath); //DirectoryInfo dirInfo = new DirectoryInfo(fullPath); //string str0 = dirInfo.FullName; FileInfo fileInfo = new FileInfo(fullPath); fullPath = fileInfo.FullName; // Replaces '\\' with '/' //Uri uri = new Uri(fullPath, UriKind.Absolute); //string fullPath1 = uri.AbsolutePath; // LocalPath //UriBuilder uriBuilder = new UriBuilder(); //uriBuilder.Host = String.Empty; //uriBuilder.Scheme = Uri.UriSchemeFile; //uriBuilder.Path = fullPath; //Uri fileUri = uriBuilder.Uri; //fullPath = fileUri.ToString(); if ( fullPath.Length > 1 && fullPath[fullPath.Length - 1] == sep //fullPath.LastIndexOf(sep) == fullPath.Length - 1 ) { #if DEBUG Debugger.Break(); #endif fullPath = fullPath.Substring(0, fullPath.Length - 1); } if (sep == '\\') { fullPath = fullPath.Replace(sep, '/'); } return(fullPath); }