Esempio n. 1
0
        protected virtual void AddPagePropertiesToAudioNode(TreeNode audioWrapperNode, XmlNode pageTargetNode)
        {
            TextMedia textMedia = audioWrapperNode.Presentation.MediaFactory.CreateTextMedia();

            textMedia.Text = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(pageTargetNode, true, "text", pageTargetNode.NamespaceURI).InnerText;
            ChannelsProperty cProp = audioWrapperNode.Presentation.PropertyFactory.CreateChannelsProperty();

            cProp.SetMedia(audioWrapperNode.Presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia);
            audioWrapperNode.AddProperty(cProp);
            System.Xml.XmlAttributeCollection pageAttributes = pageTargetNode.Attributes;
            if (pageAttributes != null)
            {
                XmlProperty xmlProp = audioWrapperNode.GetXmlProperty();
                xmlProp.SetQName("pagenum", "");
                string nsUri = audioWrapperNode.GetXmlNamespaceUri();
                foreach (System.Xml.XmlAttribute attr in pageAttributes)
                {
                    string uri = "";
                    if (!string.IsNullOrEmpty(attr.NamespaceURI))
                    {
                        if (attr.NamespaceURI != nsUri)
                        {
                            uri = attr.NamespaceURI;
                        }
                    }

                    xmlProp.SetAttribute(attr.Name, uri, attr.Value);
                }
            }
        }
Esempio n. 2
0
        protected virtual TreeNode CheckAndAssignForHeadingAudio(TreeNode navPointTreeNode, TreeNode phraseTreeNode, XmlNode audioXmlNode)
        {
            XmlNode navLabelXmlNode = m_NavPointNode_NavLabelMap[navPointTreeNode];
            XmlNode headingAudio    = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(navLabelXmlNode, true, "audio", navLabelXmlNode.NamespaceURI);
            XmlNode textNode        = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(navLabelXmlNode, true, "text", navLabelXmlNode.NamespaceURI);

            double headingClipBegin = Math.Abs((new urakawa.media.timing.Time(headingAudio.Attributes.GetNamedItem("clipBegin").Value)).AsMilliseconds);
            double headingClipEnd   = Math.Abs((new urakawa.media.timing.Time(headingAudio.Attributes.GetNamedItem("clipEnd").Value)).AsMilliseconds);

            double audioClipBegin = Math.Abs((new urakawa.media.timing.Time(audioXmlNode.Attributes.GetNamedItem("clipBegin").Value)).AsMilliseconds);
            double audioClipEnd   = Math.Abs((new urakawa.media.timing.Time(audioXmlNode.Attributes.GetNamedItem("clipEnd").Value)).AsMilliseconds);

            if (headingAudio.Attributes.GetNamedItem("src").Value == audioXmlNode.Attributes.GetNamedItem("src").Value &&
                Math.Abs(headingClipBegin - audioClipBegin) <= 1 &&
                Math.Abs(headingClipEnd - audioClipEnd) <= 1)
            {
                TextMedia textMedia = navPointTreeNode.Presentation.MediaFactory.CreateTextMedia();
                textMedia.Text = textNode.InnerText;

                ChannelsProperty cProp = navPointTreeNode.Presentation.PropertyFactory.CreateChannelsProperty();
                cProp.SetMedia(navPointTreeNode.Presentation.ChannelsManager.GetOrCreateTextChannel(), textMedia);

                //TreeNode txtWrapperNode = parentNode.Presentation.TreeNodeFactory.Create();
                phraseTreeNode.AddProperty(cProp);
                //treeNode.AppendChild(txtWrapperNode);

                XmlProperty TextNodeXmlProp = navPointTreeNode.Presentation.PropertyFactory.CreateXmlProperty();
                phraseTreeNode.AddProperty(TextNodeXmlProp);
                TextNodeXmlProp.SetQName("hd", "");
            }

            return(phraseTreeNode);
        }
        public static TextMedia CreateTextMedia(Presentation pres, string text)
        {
            TextMedia res = pres.MediaFactory.CreateTextMedia() as TextMedia;

            Assert.IsNotNull(res, "Could not create TextMedia");
            res.Text = text;
            return(res);
        }
        public TextMediaBindableRun(TextMedia tmedia)
        {
            TextMedia = tmedia;

            TextMediaBinding binding = new TextMediaBinding();

            binding.BoundTextMedia = TextMedia;
            binding.Mode           = System.Windows.Data.BindingMode.TwoWay;
            SetBinding(TextProperty, binding);
        }
Esempio n. 5
0
        public BindableRunTextMedia(TextMedia tmedia)
        {
            TextMedia = tmedia;

            var binding = new TextMediaBinding
            {
                BoundTextMedia = TextMedia,
                Mode           = BindingMode.TwoWay
            };

            SetBinding(TextProperty, binding);
        }
Esempio n. 6
0
        public void CopyTextMediaRenameAndCheckAgain()
        {
            TextMedia text_obj = factory.Create <TextMedia>();

            text_obj.Text = "original media object";

            AbstractTextMedia copy_obj = (AbstractTextMedia)text_obj.Copy();

            copy_obj.Text = "copied media object";

            Assert.AreNotEqual(text_obj.Text, copy_obj.Text);
        }
Esempio n. 7
0
        /// <summary>
        /// Create a section node belonging to this presentation.
        /// </summary>
        public SectionNode CreateSectionNode()
        {
            SectionNode node = (SectionNode)m_ObiNodeFactory.createNode(XukAble.GetXukName(typeof(SectionNode)).z(PrettyFormat), DataModelFactory.NS); //sdk2 :local ObiNode factory used

            urakawa.property.channel.ChannelsProperty channelsProperty = PropertyFactory.CreateChannelsProperty();
            node.AddProperty(channelsProperty);
            // Create the text media object for the label with a default label
            TextMedia labelMedia = MediaFactory.CreateTextMedia();

            labelMedia.Text = Localizer.Message("default_section_label");
            channelsProperty.SetMedia(ChannelsManager.GetOrCreateTextChannel(), labelMedia);
            return(node);
        }
        protected override void XukInChild(XmlReader source, IProgressHandler handler)
        {
            bool readItem = false;

            if (source.NamespaceURI == XukAble.XUK_NS)
            {
                readItem = true;
                if (source.LocalName == XukStrings.Metadatas)
                {
                    XukInMetadata(source, handler);
                }
                else if (XukAble.GetXukName(typeof(TextMedia)).Match(source.LocalName))
                {
                    if (m_Text != null)
                    {
                        throw new exception.XukException("AlternateContent Text XukIn, already set !");
                    }
                    m_Text = Presentation.MediaFactory.CreateTextMedia();
                    m_Text.XukIn(source, handler);
                }
                else if (XukAble.GetXukName(typeof(ManagedAudioMedia)).Match(source.LocalName))
                {
                    if (m_Audio != null)
                    {
                        throw new exception.XukException("AlternateContent Audio XukIn, already set !");
                    }
                    m_Audio = Presentation.MediaFactory.CreateManagedAudioMedia();
                    m_Audio.XukIn(source, handler);
                }
                else if (XukAble.GetXukName(typeof(ManagedImageMedia)).Match(source.LocalName))
                {
                    if (m_Image != null)
                    {
                        throw new exception.XukException("AlternateContent Image XukIn, already set !");
                    }
                    m_Image = Presentation.MediaFactory.CreateManagedImageMedia();
                    m_Image.XukIn(source, handler);
                }
                else
                {
                    readItem = false;
                }
            }
            if (!(readItem || source.IsEmptyElement))
            {
                source.ReadSubtree().Close(); //Read past unknown child
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Append a new audio asset to the root.
        /// Set the location and timing of the audio node to that of the asset.
        /// Set the text in the node to the label of the asset.
        /// The phrase is added to the list of phrases in that project.
        /// </summary>
        /// <param name="asset">The asset to append.</param>
        public void AppendPhrase(AudioMediaAsset asset)
        {
            CoreNode         node  = this.getPresentation().getCoreNodeFactory().createNode();
            ChannelsProperty prop  = (ChannelsProperty)node.getProperty(PropertyType.CHANNEL);
            AudioMedia       audio = (AudioMedia)this.getPresentation().getMediaFactory().createMedia(MediaType.AUDIO);

            audio.setLocation(new MediaLocation(asset.Path));
            audio.setClipEnd(new Time((long)Math.Round(asset.LengthInMilliseconds)));
            prop.setMedia(mAudioChannel, audio);
            TextMedia text = (TextMedia)this.getPresentation().getMediaFactory().createMedia(MediaType.TEXT);

            text.setText(asset.Name);
            prop.setMedia(mTextChannel, text);
            this.getPresentation().getRootNode().appendChild(node);
            mPhrases.Add(new Phrase(node, asset));
        }
        public void SetDescriptionText(AlternateContent altContent, string txt)
        {
            Tuple <TreeNode, TreeNode> selection = m_UrakawaSession.GetTreeNodeSelection();
            TreeNode node = selection.Item2 ?? selection.Item1;

            if (node == null)
            {
                return;
            }

            var altProp = node.GetAlternateContentProperty();

            if (altProp == null)
            {
                return;
            }

            if (altProp.AlternateContents.IndexOf(altContent) < 0)
            {
                return;
            }

            if (string.IsNullOrEmpty(txt))
            {
                if (altContent.Text != null)
                {
                    AlternateContentRemoveManagedMediaCommand cmd1 =
                        node.Presentation.CommandFactory.CreateAlternateContentRemoveManagedMediaCommand(node, altContent,
                                                                                                         altContent.Text);
                    node.Presentation.UndoRedoManager.Execute(cmd1);
                }
            }
            else
            {
                TextMedia txt2 = node.Presentation.MediaFactory.CreateTextMedia();
                txt2.Text = txt;

                AlternateContentSetManagedMediaCommand cmd22 =
                    node.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(node, altContent, txt2);
                node.Presentation.UndoRedoManager.Execute(cmd22);
            }

            RaisePropertyChanged(() => Descriptions);
        }
Esempio n. 11
0
        public TextMediaTextBox(TextMedia originalText)
        {
            OriginalText = originalText;

            BorderThickness = new Thickness(2);
            Focusable       = true;

            Loaded += new RoutedEventHandler(thisLoaded);

            KeyUp += new KeyEventHandler(thisKeyUp);

            //Text = originalText.getText();

            TextMediaBinding binding = new TextMediaBinding();

            binding.BoundTextMedia      = OriginalText;
            binding.Mode                = System.Windows.Data.BindingMode.TwoWay;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
            SetBinding(TextProperty, binding);
        }
Esempio n. 12
0
        public TextMediaTextBox(TextMedia originalText)
        {
            OriginalText = originalText;

            BorderThickness = new Thickness(2);
            Focusable       = true;

            Loaded += OnLoaded;
            KeyUp  += OnKeyUp;

            //Text = originalText.getText();

            var binding = new TextMediaBinding
            {
                BoundTextMedia      = OriginalText,
                Mode                = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.Explicit
            };

            SetBinding(TextProperty, binding);
        }
Esempio n. 13
0
        public Inline GetTextInline(TreeNode node)
        {
            if (TextChannel != null)
            {
                ChannelsProperty chProp = node.GetProperty <ChannelsProperty>();
                if (chProp != null)
                {
                    TextMedia text = chProp.GetMedia(TextChannel) as TextMedia;

                    if (text != null)
                    {
                        if (USE_TEXT_BOX_UIELEMENT)
                        {
                            TextBox tb = new TextBox();

                            TextMediaBinding binding = new TextMediaBinding();
                            binding.BoundTextMedia = text;
                            binding.Mode           = System.Windows.Data.BindingMode.TwoWay;
                            tb.SetBinding(TextBox.TextProperty, binding);

                            //tb.Text = text.getText();

                            tb.BorderThickness = new Thickness(1);
                            tb.Focusable       = true;
                            InlineUIContainer res = new InlineUIContainer(tb);
                            return(res);
                        }
                        else
                        {
                            TextMediaBindableRun run = new TextMediaBindableRun(text);

                            //run.Text = text.getText();
                            return(run);
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 14
0
        private void diagramXmlParseBody_(XmlNode diagramElementNode, string xmlFilePath, TreeNode treeNode, int objectIndex)
        {
            string diagramElementName = diagramElementNode.Name;

            AlternateContent           altContent     = treeNode.Presentation.AlternateContentFactory.CreateAlternateContent();
            AlternateContentAddCommand cmd_AltContent =
                treeNode.Presentation.CommandFactory.CreateAlternateContentAddCommand(treeNode, altContent);

            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent);



            Metadata diagramElementName_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();

            diagramElementName_Metadata.NameContentAttribute              = new MetadataAttribute();
            diagramElementName_Metadata.NameContentAttribute.Name         = DiagramContentModelHelper.DiagramElementName;
            diagramElementName_Metadata.NameContentAttribute.NamespaceUri = null;
            diagramElementName_Metadata.NameContentAttribute.Value        = diagramElementName;
            AlternateContentMetadataAddCommand cmd_AltContent_diagramElementName_Metadata =
                treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                    treeNode,
                    null,
                    altContent,
                    diagramElementName_Metadata,
                    null
                    );

            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_diagramElementName_Metadata);


            if (diagramElementNode.Attributes != null)
            {
                for (int i = 0; i < diagramElementNode.Attributes.Count; i++)
                {
                    XmlAttribute attribute = diagramElementNode.Attributes[i];


                    if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":"))
                    {
                        //
                    }
                    else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS)
                    {
                        //
                    }
                    else if (attribute.Name == DiagramContentModelHelper.TOBI_Audio)
                    {
                        string fullPath = null;
                        if (FileDataProvider.isHTTPFile(attribute.Value))
                        {
                            fullPath = FileDataProvider.EnsureLocalFilePathDownloadTempDirectory(attribute.Value);
                        }
                        else
                        {
                            fullPath = Path.Combine(Path.GetDirectoryName(xmlFilePath), attribute.Value);
                        }
                        if (fullPath != null && File.Exists(fullPath))
                        {
                            string extension = Path.GetExtension(fullPath);

                            bool isWav = extension.Equals(DataProviderFactory.AUDIO_WAV_EXTENSION, StringComparison.OrdinalIgnoreCase);

                            AudioLibPCMFormat wavFormat = null;
                            if (isWav)
                            {
                                Stream fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                try
                                {
                                    uint dataLength;
                                    wavFormat = AudioLibPCMFormat.RiffHeaderParse(fileStream, out dataLength);
                                }
                                finally
                                {
                                    fileStream.Close();
                                }
                            }
                            string originalFilePath = null;

                            DebugFix.Assert(treeNode.Presentation.MediaDataManager.EnforceSinglePCMFormat);

                            bool wavNeedsConversion = false;
                            if (wavFormat != null)
                            {
                                wavNeedsConversion = !wavFormat.IsCompatibleWith(treeNode.Presentation.MediaDataManager.DefaultPCMFormat.Data);
                            }
                            if (!isWav || wavNeedsConversion)
                            {
                                originalFilePath = fullPath;

                                var audioFormatConvertorSession =
                                    new AudioFormatConvertorSession(
                                        //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY,
                                        treeNode.Presentation.DataProviderManager.DataFileDirectoryFullPath,
                                        treeNode.Presentation.MediaDataManager.DefaultPCMFormat,
                                        false,
                                        m_UrakawaSession.IsAcmCodecsDisabled);

                                //filePath = m_AudioFormatConvertorSession.ConvertAudioFileFormat(filePath);

                                bool cancelled = false;

                                var converter = new AudioClipConverter(audioFormatConvertorSession, fullPath);

                                bool error = ShellView.RunModalCancellableProgressTask(true,
                                                                                       "Converting audio...",
                                                                                       converter,
                                                                                       () =>
                                {
                                    m_Logger.Log(@"Audio conversion CANCELLED", Category.Debug, Priority.Medium);
                                    cancelled = true;
                                },
                                                                                       () =>
                                {
                                    m_Logger.Log(@"Audio conversion DONE", Category.Debug, Priority.Medium);
                                    cancelled = false;
                                });

                                if (cancelled)
                                {
                                    //DebugFix.Assert(!result);
                                    break;
                                }

                                fullPath = converter.ConvertedFilePath;
                                if (string.IsNullOrEmpty(fullPath))
                                {
                                    break;
                                }

                                m_Logger.Log(string.Format("Converted audio {0} to {1}", originalFilePath, fullPath),
                                             Category.Debug, Priority.Medium);

                                //Stream fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                                //try
                                //{
                                //    uint dataLength;
                                //    wavFormat = AudioLibPCMFormat.RiffHeaderParse(fileStream, out dataLength);
                                //}
                                //finally
                                //{
                                //    fileStream.Close();
                                //}
                            }


                            ManagedAudioMedia manAudioMedia  = treeNode.Presentation.MediaFactory.CreateManagedAudioMedia();
                            AudioMediaData    audioMediaData = treeNode.Presentation.MediaDataFactory.CreateAudioMediaData(DataProviderFactory.AUDIO_WAV_EXTENSION);
                            manAudioMedia.AudioMediaData = audioMediaData;

                            FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            dataProv.InitByCopyingExistingFile(fullPath);
                            audioMediaData.AppendPcmData(dataProv);

                            //                            Stream wavStream = null;
                            //                            try
                            //                            {
                            //                                wavStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);

                            //                                uint dataLength;
                            //                                AudioLibPCMFormat pcmInfo = AudioLibPCMFormat.RiffHeaderParse(wavStream, out dataLength);

                            //                                if (!treeNode.Presentation.MediaDataManager.DefaultPCMFormat.Data.IsCompatibleWith(pcmInfo))
                            //                                {
                            //#if DEBUG
                            //                                    Debugger.Break();
                            //#endif //DEBUG
                            //                                    wavStream.Close();
                            //                                    wavStream = null;

                            //                                    var audioFormatConvertorSession =
                            //                                        new AudioFormatConvertorSession(
                            //                                        //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY,
                            //                                        treeNode.Presentation.DataProviderManager.DataFileDirectoryFullPath,
                            //                                    treeNode.Presentation.MediaDataManager.DefaultPCMFormat, m_UrakawaSession.IsAcmCodecsDisabled);

                            //                                    string newfullWavPath = audioFormatConvertorSession.ConvertAudioFileFormat(fullPath);

                            //                                    FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            //                                    dataProv.InitByMovingExistingFile(newfullWavPath);
                            //                                    audioMediaData.AppendPcmData(dataProv);
                            //                                }
                            //                                else // use original wav file by copying it to data directory
                            //                                {
                            //                                    FileDataProvider dataProv = (FileDataProvider)treeNode.Presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                            //                                    dataProv.InitByCopyingExistingFile(fullPath);
                            //                                    audioMediaData.AppendPcmData(dataProv);
                            //                                }
                            //                            }
                            //                            finally
                            //                            {
                            //                                if (wavStream != null) wavStream.Close();
                            //                            }



                            AlternateContentSetManagedMediaCommand cmd_AltContent_diagramElement_Audio =
                                treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(treeNode, altContent, manAudioMedia);
                            treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_diagramElement_Audio);

                            //SetDescriptionAudio(altContent, audio, treeNode);
                        }
                    }
                    else
                    {
                        Metadata diagramElementAttribute_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                        diagramElementAttribute_Metadata.NameContentAttribute              = new MetadataAttribute();
                        diagramElementAttribute_Metadata.NameContentAttribute.Name         = attribute.Name;
                        diagramElementAttribute_Metadata.NameContentAttribute.NamespaceUri = attribute.NamespaceURI;
                        diagramElementAttribute_Metadata.NameContentAttribute.Value        = attribute.Value;
                        AlternateContentMetadataAddCommand cmd_AltContent_diagramElementAttribute_Metadata =
                            treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                                treeNode,
                                null,
                                altContent,
                                diagramElementAttribute_Metadata,
                                null
                                );
                        treeNode.Presentation.UndoRedoManager.Execute(
                            cmd_AltContent_diagramElementAttribute_Metadata);
                    }
                }
            }

            int nObjects = -1;

            XmlNode textNode = diagramElementNode;

            if (diagramElementName == DiagramContentModelHelper.D_SimplifiedImage ||
                diagramElementName == DiagramContentModelHelper.D_Tactile)
            {
                string  localTourName = DiagramContentModelHelper.StripNSPrefix(DiagramContentModelHelper.D_Tour);
                XmlNode tour          =
                    XmlDocumentHelper.GetFirstChildElementOrSelfWithName(diagramElementNode, false,
                                                                         localTourName,
                                                                         DiagramContentModelHelper.NS_URL_DIAGRAM);
                textNode = tour;

                IEnumerable <XmlNode> objects = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(diagramElementNode, false,
                                                                                                    DiagramContentModelHelper.
                                                                                                    Object,
                                                                                                    DiagramContentModelHelper.
                                                                                                    NS_URL_ZAI, false);
                nObjects = 0;
                foreach (XmlNode obj in objects)
                {
                    nObjects++;
                }

                int i = -1;
                foreach (XmlNode obj in objects)
                {
                    i++;
                    if (i != objectIndex)
                    {
                        continue;
                    }

                    if (obj.Attributes == null || obj.Attributes.Count <= 0)
                    {
                        break;
                    }

                    for (int j = 0; j < obj.Attributes.Count; j++)
                    {
                        XmlAttribute attribute = obj.Attributes[j];


                        if (attribute.Name.StartsWith(XmlReaderWriterHelper.NS_PREFIX_XMLNS + ":"))
                        {
                            //
                        }
                        else if (attribute.Name == XmlReaderWriterHelper.NS_PREFIX_XMLNS)
                        {
                            //
                        }
                        else if (attribute.Name == DiagramContentModelHelper.Src)
                        {
                            //
                        }
                        else if (attribute.Name == DiagramContentModelHelper.SrcType)
                        {
                            //
                        }
                        else
                        {
                            Metadata diagramElementAttribute_Metadata = treeNode.Presentation.MetadataFactory.CreateMetadata();
                            diagramElementAttribute_Metadata.NameContentAttribute              = new MetadataAttribute();
                            diagramElementAttribute_Metadata.NameContentAttribute.Name         = attribute.Name;
                            diagramElementAttribute_Metadata.NameContentAttribute.NamespaceUri = attribute.NamespaceURI;
                            diagramElementAttribute_Metadata.NameContentAttribute.Value        = attribute.Value;
                            AlternateContentMetadataAddCommand cmd_AltContent_diagramElementAttribute_Metadata =
                                treeNode.Presentation.CommandFactory.CreateAlternateContentMetadataAddCommand(
                                    treeNode,
                                    null,
                                    altContent,
                                    diagramElementAttribute_Metadata,
                                    null
                                    );
                            treeNode.Presentation.UndoRedoManager.Execute(
                                cmd_AltContent_diagramElementAttribute_Metadata);
                        }
                    }

                    XmlAttribute srcAttr = (XmlAttribute)obj.Attributes.GetNamedItem(DiagramContentModelHelper.Src);
                    if (srcAttr != null)
                    {
                        XmlAttribute srcType =
                            (XmlAttribute)obj.Attributes.GetNamedItem(DiagramContentModelHelper.SrcType);

                        ManagedImageMedia img = treeNode.Presentation.MediaFactory.CreateManagedImageMedia();

                        string imgFullPath = null;
                        if (FileDataProvider.isHTTPFile(srcAttr.Value))
                        {
                            imgFullPath = FileDataProvider.EnsureLocalFilePathDownloadTempDirectory(srcAttr.Value);
                        }
                        else
                        {
                            imgFullPath = Path.Combine(Path.GetDirectoryName(xmlFilePath), srcAttr.Value);
                        }
                        if (imgFullPath != null && File.Exists(imgFullPath))
                        {
                            string extension = Path.GetExtension(imgFullPath);

                            ImageMediaData imgData = treeNode.Presentation.MediaDataFactory.CreateImageMediaData(extension);
                            if (imgData != null)
                            {
                                imgData.InitializeImage(imgFullPath, Path.GetFileName(imgFullPath));
                                img.ImageMediaData = imgData;

                                AlternateContentSetManagedMediaCommand cmd_AltContent_Image =
                                    treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(
                                        treeNode, altContent, img);
                                treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_Image);
                            }
                        }
                    }
                }
            }

            if (textNode != null)
            {
                string strText = textNode.InnerXml;

                if (!string.IsNullOrEmpty(strText))
                {
                    strText = strText.Trim();
                    strText = Regex.Replace(strText, @"\s+", " ");
                    strText = strText.Replace("\r\n", "\n");
                }

                if (!string.IsNullOrEmpty(strText))
                {
                    TextMedia txtMedia = treeNode.Presentation.MediaFactory.CreateTextMedia();
                    txtMedia.Text = strText;
                    AlternateContentSetManagedMediaCommand cmd_AltContent_Text =
                        treeNode.Presentation.CommandFactory.CreateAlternateContentSetManagedMediaCommand(treeNode,
                                                                                                          altContent,
                                                                                                          txtMedia);
                    treeNode.Presentation.UndoRedoManager.Execute(cmd_AltContent_Text);
                }
            }

            if (nObjects > 0 && ++objectIndex <= nObjects - 1)
            {
                diagramXmlParseBody_(diagramElementNode, xmlFilePath, treeNode, objectIndex);
            }
        }
Esempio n. 15
0
        private void parseContentDocument(XmlNode xmlNode, TreeNode parentTreeNode, string filePath)
        {
            XmlNodeType xmlType = xmlNode.NodeType;

            switch (xmlType)
            {
            case XmlNodeType.Attribute:
            {
                System.Diagnostics.Debug.Fail("Calling this method with an XmlAttribute should never happen !!");
                break;
            }

            case XmlNodeType.Document:
            {
                //XmlNodeList listOfBodies = ((XmlDocument)xmlNode).GetElementsByTagName("body");
                //if (listOfBodies.Count == 0)
                //{
                //    listOfBodies = ((XmlDocument)xmlNode).GetElementsByTagName("book");
                //}
                XmlNode bodyElement = getFirstChildElementsWithName(xmlNode, true, "body", null);

                if (bodyElement == null)
                {
                    bodyElement = getFirstChildElementsWithName(xmlNode, true, "book", null);
                }

                if (bodyElement != null)
                {
                    Presentation presentation = m_Project.Presentations.Get(0);
                    presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI;

                    // preserve internal DTD if it exists in dtbook
                    string strInternalDTD = ExtractInternalDTD(((XmlDocument)xmlNode).DocumentType);
                    if (strInternalDTD != null)
                    {
                        File.WriteAllText(
                            Path.Combine(presentation.DataProviderManager.DataFileDirectoryFullPath, "DTBookLocalDTD.dtd"),
                            strInternalDTD);
                    }

                    parseContentDocument(bodyElement, parentTreeNode, filePath);
                }
                //parseContentDocument(((XmlDocument)xmlNode).DocumentElement, parentTreeNode);
                break;
            }

            case XmlNodeType.Element:
            {
                Presentation presentation = m_Project.Presentations.Get(0);

                TreeNode treeNode = presentation.TreeNodeFactory.Create();

                if (parentTreeNode == null)
                {
                    presentation.RootNode = treeNode;
                    parentTreeNode        = presentation.RootNode;
                }
                else
                {
                    parentTreeNode.AppendChild(treeNode);
                }

                XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty();
                treeNode.AddProperty(xmlProp);
                xmlProp.LocalName = xmlNode.LocalName;
                if (xmlNode.ParentNode != null && xmlNode.ParentNode.NodeType == XmlNodeType.Document)
                {
                    presentation.PropertyFactory.DefaultXmlNamespaceUri = xmlNode.NamespaceURI;
                }

                if (xmlNode.NamespaceURI != presentation.PropertyFactory.DefaultXmlNamespaceUri)
                {
                    xmlProp.NamespaceUri = xmlNode.NamespaceURI;
                }

                string updatedSRC = null;

                if (xmlNode.LocalName == "img")
                {
                    XmlNode getSRC = xmlNode.Attributes.GetNamedItem("src");
                    if (getSRC != null)
                    {
                        string relativePath = xmlNode.Attributes.GetNamedItem("src").Value;
                        if (!relativePath.StartsWith("http://"))
                        {
                            string parentPath        = Directory.GetParent(filePath).FullName;
                            string imgSourceFullpath = Path.Combine(parentPath, relativePath);
                            string datafilePath      = presentation.DataProviderManager.DataFileDirectoryFullPath;
                            string imgDestFullpath   = Path.Combine(datafilePath,
                                                                    Path.GetFileName(imgSourceFullpath));
                            if (!File.Exists(imgDestFullpath))
                            {
                                //File.Delete(imgDestFullpath);
                                File.Copy(imgSourceFullpath, imgDestFullpath);
                            }

                            updatedSRC =
                                presentation.RootUri.MakeRelativeUri(new Uri(imgDestFullpath, UriKind.Absolute))
                                .ToString();
                            //string dirPath = Path.GetDirectoryName(presentation.RootUri.LocalPath);
                            //updatedSRC = presentation.DataProviderManager.DataFileDirectory + Path.DirectorySeparatorChar + Path.GetFileName(imgDestFullpath);

                            ChannelsProperty chProp = presentation.PropertyFactory.CreateChannelsProperty();
                            treeNode.AddProperty(chProp);
                            ExternalImageMedia externalImage =
                                presentation.MediaFactory.CreateExternalImageMedia();
                            externalImage.Src = updatedSRC;
                            chProp.SetMedia(m_ImageChannel, externalImage);
                        }
                    }
                }

                XmlAttributeCollection attributeCol = xmlNode.Attributes;

                if (attributeCol != null)
                {
                    for (int i = 0; i < attributeCol.Count; i++)
                    {
                        XmlNode attr = attributeCol.Item(i);
                        if (attr.LocalName != "smilref" && attr.Name != "xmlns:xsi" && attr.Name != "xml:space")
                        {
                            if (updatedSRC != null && attr.LocalName == "src")
                            {
                                xmlProp.SetAttribute(attr.LocalName, "", updatedSRC);
                            }
                            else
                            {
                                if (attr.LocalName == "xmlns")
                                {
                                    if (attr.Value != presentation.PropertyFactory.DefaultXmlNamespaceUri)
                                    {
                                        xmlProp.SetAttribute(attr.LocalName, "", attr.Value);
                                    }
                                }
                                else if (string.IsNullOrEmpty(attr.NamespaceURI) ||
                                         attr.NamespaceURI == presentation.PropertyFactory.DefaultXmlNamespaceUri)
                                {
                                    xmlProp.SetAttribute(attr.LocalName, "", attr.Value);
                                }
                                else
                                {
                                    xmlProp.SetAttribute(attr.Name, attr.NamespaceURI, attr.Value);
                                }
                            }
                        }
                    }
                }

                foreach (XmlNode childXmlNode in xmlNode.ChildNodes)
                {
                    parseContentDocument(childXmlNode, treeNode, filePath);
                }
                break;
            }

            case XmlNodeType.Text:
            {
                Presentation presentation = m_Project.Presentations.Get(0);

                string    text      = trimXmlText(xmlNode.Value);
                TextMedia textMedia = presentation.MediaFactory.CreateTextMedia();
                textMedia.Text = text;

                ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty();
                cProp.SetMedia(m_textChannel, textMedia);

                int counter = 0;
                foreach (XmlNode childXmlNode in xmlNode.ParentNode.ChildNodes)
                {
                    XmlNodeType childXmlType = childXmlNode.NodeType;
                    if (childXmlType == XmlNodeType.Text || childXmlType == XmlNodeType.Element)
                    {
                        counter++;
                    }
                }
                if (counter == 1)
                {
                    parentTreeNode.AddProperty(cProp);
                }
                else
                {
                    TreeNode txtWrapperNode = presentation.TreeNodeFactory.Create();
                    txtWrapperNode.AddProperty(cProp);
                    parentTreeNode.AppendChild(txtWrapperNode);
                }

                break;
            }

            default:
            {
                return;
            }
            }
        }
Esempio n. 16
0
        private void parseDTBookXmlDocAndPopulateDataModel(XmlNode xmlNode, core.TreeNode parentTreeNode)
        {
            XmlNodeType xmlType = xmlNode.NodeType;

            switch (xmlType)
            {
            case XmlNodeType.Attribute:
            {
                System.Diagnostics.Debug.Fail("Calling this method with an XmlAttribute should never happen !!");
                break;
            }

            case XmlNodeType.Document:
            {
                parseDTBookXmlDocAndPopulateDataModel(((XmlDocument)xmlNode).DocumentElement, parentTreeNode);
                break;
            }

            case XmlNodeType.Element:
            {
                Presentation presentation = m_Project.GetPresentation(0);

                core.TreeNode treeNode = presentation.TreeNodeFactory.Create();

                if (parentTreeNode == null)
                {
                    presentation.RootNode = treeNode;
                    parentTreeNode        = presentation.RootNode;
                }
                else
                {
                    parentTreeNode.AppendChild(treeNode);
                }

                XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty();
                treeNode.AddProperty(xmlProp);
                xmlProp.LocalName = xmlNode.Name;
                if (xmlNode.ParentNode != null && xmlNode.ParentNode.NodeType == XmlNodeType.Document)
                {
                    presentation.PropertyFactory.DefaultXmlNamespaceUri = xmlNode.NamespaceURI;
                }

                if (xmlNode.NamespaceURI != presentation.PropertyFactory.DefaultXmlNamespaceUri)
                {
                    xmlProp.NamespaceUri = xmlNode.NamespaceURI;
                }

                XmlAttributeCollection attributeCol = xmlNode.Attributes;

                if (attributeCol != null)
                {
                    for (int i = 0; i < attributeCol.Count; i++)
                    {
                        XmlNode attr = attributeCol.Item(i);
                        if (attr.Name != "smilref")
                        {
                            xmlProp.SetAttribute(attr.Name, "", attr.Value);
                        }
                    }


                    if (xmlNode.Name == "meta")
                    {
                        XmlNode attrName    = attributeCol.GetNamedItem("name");
                        XmlNode attrContent = attributeCol.GetNamedItem("content");
                        if (attrName != null && attrContent != null && !String.IsNullOrEmpty(attrName.Value) &&
                            !String.IsNullOrEmpty(attrContent.Value))
                        {
                            Metadata md = presentation.MetadataFactory.CreateMetadata();
                            md.Name    = attrName.Value;
                            md.Content = attrContent.Value;
                            presentation.AddMetadata(md);
                        }
                    }
                }


                foreach (XmlNode childXmlNode in xmlNode.ChildNodes)
                {
                    parseDTBookXmlDocAndPopulateDataModel(childXmlNode, treeNode);
                }
                break;
            }

            case XmlNodeType.Text:
            {
                Presentation presentation = m_Project.GetPresentation(0);

                string    text      = xmlNode.Value;
                TextMedia textMedia = presentation.MediaFactory.CreateTextMedia();
                textMedia.Text = text;

                ChannelsProperty cProp = presentation.PropertyFactory.CreateChannelsProperty();
                cProp.SetMedia(m_textChannel, textMedia);

                int counter = 0;
                foreach (XmlNode childXmlNode in xmlNode.ParentNode.ChildNodes)
                {
                    XmlNodeType childXmlType = childXmlNode.NodeType;
                    if (childXmlType == XmlNodeType.Text || childXmlType == XmlNodeType.Element)
                    {
                        counter++;
                    }
                }
                if (counter == 1)
                {
                    parentTreeNode.AddProperty(cProp);
                }
                else
                {
                    core.TreeNode txtWrapperNode = presentation.TreeNodeFactory.Create();
                    txtWrapperNode.AddProperty(cProp);
                    parentTreeNode.AppendChild(txtWrapperNode);
                }

                break;
            }

            default:
            {
                return;
            }
            }
        }
Esempio n. 17
0
        protected virtual void parseContentDocuments(List <string> spineOfContentDocuments,
                                                     Dictionary <string, string> spineAttributes,
                                                     List <Dictionary <string, string> > spineItemsAttributes,
                                                     string coverImagePath, string navDocPath)
        {
            if (spineOfContentDocuments == null || spineOfContentDocuments.Count <= 0)
            {
                return;
            }

            Presentation spinePresentation = m_Project.Presentations.Get(0);

            spinePresentation.RootNode.GetOrCreateXmlProperty().SetQName("spine", "");

            if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath))
            {
                spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(OPF_ContainerRelativePath, "", m_OPF_ContainerRelativePath);
            }

            foreach (KeyValuePair <string, string> spineAttribute in spineAttributes)
            {
                spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(spineAttribute.Key, "", spineAttribute.Value);
            }

            if (m_PackagePrefixAttr != null)
            {
                spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute("prefix", "", m_PackagePrefixAttr.Value);
            }

            // Audio files may be shared between chapters of a book!
            m_OriginalAudioFile_FileDataProviderMap.Clear();

            Presentation spineItemPresentation = null;

            int index = -1;

            foreach (string docPath in spineOfContentDocuments)
            {
                index++;

                reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath));

                //DirectoryInfo opfParentDir = Directory.GetParent(m_Book_FilePath);
                //string dirPath = opfParentDir.ToString();
                string fullDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), docPath);

                fullDocPath = FileDataProvider.NormaliseFullFilePath(fullDocPath).Replace('/', '\\');

                if (!File.Exists(fullDocPath))
                {
#if DEBUG
                    Debugger.Break();
#endif //DEBUG
                    continue;
                }

                addOPF_GlobalAssetPath(fullDocPath);

                TreeNode  spineChild = spinePresentation.TreeNodeFactory.Create();
                TextMedia txt        = spinePresentation.MediaFactory.CreateTextMedia();
                txt.Text = docPath; // Path.GetFileName(fullDocPath);
                spineChild.GetOrCreateChannelsProperty().SetMedia(spinePresentation.ChannelsManager.GetOrCreateTextChannel(), txt);
                spinePresentation.RootNode.AppendChild(spineChild);

                spineChild.GetOrCreateXmlProperty().SetQName("metadata", "");

                foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index])
                {
                    spineChild.GetOrCreateXmlProperty().SetAttribute(spineItemAttribute.Key, "", spineItemAttribute.Value);
                }

                string ext = Path.GetExtension(fullDocPath);

                if (docPath == coverImagePath)
                {
                    DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase));

                    spineChild.GetOrCreateXmlProperty().SetAttribute("cover-image", "", "true");
                }

                if (docPath == navDocPath)
                {
                    DebugFix.Assert(
                        ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) ||
                        ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase));

                    spineChild.GetOrCreateXmlProperty().SetAttribute("nav", "", "true");
                }

                if (
                    !ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) &&
                    !ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase) &&
                    !ext.Equals(DataProviderFactory.DTBOOK_EXTENSION, StringComparison.OrdinalIgnoreCase) &&
                    !ext.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase)
                    )
                {
                    DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase));

                    bool notExistYet = true;
                    foreach (ExternalFiles.ExternalFileData externalFileData in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable)
                    {
                        if (!string.IsNullOrEmpty(externalFileData.OriginalRelativePath))
                        {
                            bool notExist = docPath != externalFileData.OriginalRelativePath;
                            notExistYet = notExistYet && notExist;
                            if (!notExist)
                            {
                                break;
                            }
                        }
                    }

                    DebugFix.Assert(notExistYet);

                    if (notExistYet)
                    {
                        ExternalFiles.ExternalFileData externalData = null;
                        if (docPath == coverImagePath)
                        {
                            externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create
                                           <ExternalFiles.CoverImageExternalFileData>();
                        }
                        else
                        {
                            externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create
                                           <ExternalFiles.GenericExternalFileData>();
                        }
                        if (externalData != null)
                        {
                            externalData.InitializeWithData(fullDocPath, docPath, true, null);

                            addOPF_GlobalAssetPath(fullDocPath);
                        }
                    }

                    continue;
                }

                spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true");

                XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDocPath, true, true);

                if (RequestCancellation)
                {
                    return;
                }

                m_PublicationUniqueIdentifier     = null;
                m_PublicationUniqueIdentifierNode = null;

                Project spineItemProject = new Project();
                spineItemProject.PrettyFormat = m_XukPrettyFormat;

                string dataFolderPrefix = FileDataProvider.EliminateForbiddenFileNameCharacters(docPath);
                spineItemPresentation = spineItemProject.AddNewPresentation(new Uri(m_outDirectory),
                                                                            //Path.GetFileName(fullDocPath)
                                                                            dataFolderPrefix
                                                                            );

                PCMFormatInfo pcmFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //.Copy();
                pcmFormat.Data.SampleRate       = (ushort)m_audioProjectSampleRate;
                pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1;
                spineItemPresentation.MediaDataManager.DefaultPCMFormat = pcmFormat;

                //presentation.MediaDataManager.EnforceSinglePCMFormat = true;

                //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData);

                TextChannel textChannel = spineItemPresentation.ChannelFactory.CreateTextChannel();
                textChannel.Name = "The Text Channel";
                DebugFix.Assert(textChannel == spineItemPresentation.ChannelsManager.GetOrCreateTextChannel());

                AudioChannel audioChannel = spineItemPresentation.ChannelFactory.CreateAudioChannel();
                audioChannel.Name = "The Audio Channel";
                DebugFix.Assert(audioChannel == spineItemPresentation.ChannelsManager.GetOrCreateAudioChannel());

                ImageChannel imageChannel = spineItemPresentation.ChannelFactory.CreateImageChannel();
                imageChannel.Name = "The Image Channel";
                DebugFix.Assert(imageChannel == spineItemPresentation.ChannelsManager.GetOrCreateImageChannel());

                VideoChannel videoChannel = spineItemPresentation.ChannelFactory.CreateVideoChannel();
                videoChannel.Name = "The Video Channel";
                DebugFix.Assert(videoChannel == spineItemPresentation.ChannelsManager.GetOrCreateVideoChannel());

                /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath;
                 * if (Directory.Exists(dataPath))
                 * {
                 * Directory.Delete(dataPath, true);
                 * }*/

                //AudioLibPCMFormat previousPcm = null;
                if (m_AudioConversionSession != null)
                {
                    //previousPcm = m_AudioConversionSession.FirstDiscoveredPCMFormat;
                    RemoveSubCancellable(m_AudioConversionSession);
                    m_AudioConversionSession = null;
                }

                m_AudioConversionSession = new AudioFormatConvertorSession(
                    //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY,
                    spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath,
                    spineItemPresentation.MediaDataManager.DefaultPCMFormat,
                    m_autoDetectPcmFormat,
                    m_SkipACM);

                //if (previousPcm != null)
                //{
                //    m_AudioConversionSession.FirstDiscoveredPCMFormat = previousPcm;
                //}

                AddSubCancellable(m_AudioConversionSession);

                TreenodesWithoutManagedAudioMediaData = new List <TreeNode>();

                //foreach (var key in m_OriginalAudioFile_FileDataProviderMap.Keys)
                //{
                //    FileDataProvider dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE);
                //VERSUS//
                //    FileDataProvider dataProv = new FileDataProvider();
                //    dataProv.MimeType = DataProviderFactory.AUDIO_WAV_MIME_TYPE;
                //}



                //m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable

                if (RequestCancellation)
                {
                    return;
                }

                if (parseContentDocParts(fullDocPath, spineItemProject, xmlDoc, docPath, DocumentMarkupType.NA))
                {
                    return; // user cancel
                }


                //if (RequestCancellation) return;
                //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, docPath));
                //parseMetadata(fullDocPath, project, xmlDoc);

                //if (RequestCancellation) return;
                //ParseHeadLinks(fullDocPath, project, xmlDoc);

                //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, docPath));
                //parseContentDocument(fullDocPath, project, xmlDoc, null, fullDocPath, null, DocumentMarkupType.NA);



                string title = GetTitle(spineItemPresentation);
                if (!string.IsNullOrEmpty(title))
                {
                    spineChild.GetOrCreateXmlProperty().SetAttribute("title", "", title);
                }


                if (false) // do not copy metadata from project to individual chapter
                {
                    foreach (Metadata metadata in m_Project.Presentations.Get(0).Metadatas.ContentsAs_Enumerable)
                    {
                        Metadata md = spineItemPresentation.MetadataFactory.CreateMetadata();
                        md.NameContentAttribute = metadata.NameContentAttribute.Copy();

                        foreach (MetadataAttribute metadataAttribute in metadata.OtherAttributes.ContentsAs_Enumerable)
                        {
                            MetadataAttribute mdAttr = metadataAttribute.Copy();
                            md.OtherAttributes.Insert(md.OtherAttributes.Count, mdAttr);
                        }

                        spineItemPresentation.Metadatas.Insert(spineItemPresentation.Metadatas.Count, md);
                    }
                }



                //XmlNodeList listOfBodies = xmlDoc.GetElementsByTagName("body");
                //if (listOfBodies.Count == 0)
                //{
                //    listOfBodies = xmlDoc.GetElementsByTagName("book");
                //}

                //XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "body", null);
                //if (bodyElement == null)
                //{
                //    bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null);
                //}

                //if (bodyElement == null)
                //{
                //    continue;
                //}

                // TODO: return hierarchical outline where each node points to a XUK relative path, + XukAble.Uid (TreeNode are not corrupted during XukAbleManager.RegenerateUids();


                foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index])
                {
                    if (spineItemAttribute.Key == "media-overlay")
                    {
                        string opfDirPath  = Path.GetDirectoryName(m_Book_FilePath);
                        string overlayPath = spineItemAttribute.Value;


                        reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMediaOverlay, overlayPath));


                        string fullOverlayPath = Path.Combine(opfDirPath, overlayPath);
                        if (!File.Exists(fullOverlayPath))
                        {
                            continue;
                        }

                        XmlDocument overlayXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullOverlayPath, false, false);

                        IEnumerable <XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false);
                        if (audioElements == null)
                        {
                            continue;
                        }

                        foreach (XmlNode audioNode in audioElements)
                        {
                            XmlAttributeCollection attrs = audioNode.Attributes;
                            if (attrs == null)
                            {
                                continue;
                            }

                            XmlNode attrSrc = attrs.GetNamedItem("src");
                            if (attrSrc == null)
                            {
                                continue;
                            }

                            //XmlNode attrBegin = attrs.GetNamedItem("clipBegin");
                            //XmlNode attrEnd = attrs.GetNamedItem("clipEnd");

                            //string overlayDirPath = Path.GetDirectoryName(fullOverlayPath);
                            //string fullAudioPath = Path.Combine(overlayDirPath, attrSrc.Value);

                            //if (!File.Exists(fullAudioPath))
                            //{
                            //    continue;
                            //}


                            //if (RequestCancellation) return;
                            //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullAudioPath)));


                            TreeNode textTreeNode = null;

                            XmlNodeList children = audioNode.ParentNode.ChildNodes;
                            foreach (XmlNode child in children)
                            {
                                if (child == audioNode)
                                {
                                    continue;
                                }
                                if (child.LocalName != "text")
                                {
                                    continue;
                                }

                                XmlAttributeCollection textAttrs = child.Attributes;
                                if (textAttrs == null)
                                {
                                    continue;
                                }

                                XmlNode textSrc = textAttrs.GetNamedItem("src");
                                if (textSrc == null)
                                {
                                    continue;
                                }

                                string urlDecoded = FileDataProvider.UriDecode(textSrc.Value);

                                if (urlDecoded.IndexOf('#') > 0)
                                {
                                    string[] srcParts = urlDecoded.Split('#');
                                    if (srcParts.Length != 2)
                                    {
                                        continue;
                                    }

                                    string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath),
                                                                          srcParts[0]);
                                    fullTextRefPath =
                                        FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\');

                                    if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase))
                                    {
                                        //#if DEBUG
                                        //                                Debugger.Break();
                                        //#endif //DEBUG

                                        continue;
                                    }

                                    string txtId = srcParts[1];

                                    textTreeNode = spineItemPresentation.RootNode.GetFirstDescendantWithXmlID(txtId);
                                }
                                else
                                {
                                    string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath),
                                                                          urlDecoded);
                                    fullTextRefPath =
                                        FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\');

                                    if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase))
                                    {
                                        //#if DEBUG
                                        //                                Debugger.Break();
                                        //#endif //DEBUG

                                        continue;
                                    }

                                    textTreeNode = spineItemPresentation.RootNode;
                                }
                            }

                            if (textTreeNode != null)
                            {
                                addAudio(textTreeNode, audioNode, false, fullOverlayPath);
                            }
                        }
                    }
                }


                spinePresentation.MediaDataManager.DefaultPCMFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //copied!

                string xuk_FilePath = GetXukFilePath_SpineItem(m_outDirectory, docPath, title, index);

                string xukFileName = Path.GetFileName(xuk_FilePath);
                spineChild.GetOrCreateXmlProperty().SetAttribute("xukFileName", "", xukFileName);

                //deleteDataDirectoryIfEmpty();
                string dataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath;
                spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(xuk_FilePath));

                string newDataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath;
                DebugFix.Assert(Directory.Exists(newDataFolderPath));

                if (newDataFolderPath != dataFolderPath)
                {
                    try
                    {
                        if (Directory.Exists(newDataFolderPath))
                        {
                            FileDataProvider.TryDeleteDirectory(newDataFolderPath, false);
                        }

                        Directory.Move(dataFolderPath, newDataFolderPath);
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        Debugger.Break();
#endif // DEBUG
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);

                        spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(dataFolderPrefix);
                    }
                }

                spineItemProject.PrettyFormat = m_XukPrettyFormat;

                SaveXukAction action = new SaveXukAction(spineItemProject, spineItemProject, new Uri(xuk_FilePath), true);
                action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile;
                action.LongDescription  = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile;

                action.Progress += new EventHandler <ProgressEventArgs>(
                    delegate(object sender, ProgressEventArgs e)
                {
                    double val = e.Current;
                    double max = e.Total;

                    int percent = -1;
                    if (val != max)
                    {
                        percent = (int)((val / max) * 100);
                    }

                    reportProgress_Throttle(percent, val + "/" + max);
                    //reportProgress(-1, action.LongDescription);

                    if (RequestCancellation)
                    {
                        e.Cancel();
                    }
                }
                    );


                action.Finished += new EventHandler <FinishedEventArgs>(
                    delegate(object sender, FinishedEventArgs e)
                {
                    reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved);
                }
                    );
                action.Cancelled += new EventHandler <CancelledEventArgs>(
                    delegate(object sender, CancelledEventArgs e)
                {
                    reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving);
                }
                    );

                action.DoWork();



                //if (first)
                //{
                //    Presentation presentation = m_Project.Presentations.Get(0);
                //    XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty();
                //    xmlProp.LocalName = "book";
                //    presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI;
                //    xmlProp.NamespaceUri = presentation.PropertyFactory.DefaultXmlNamespaceUri;
                //    TreeNode treeNode = presentation.TreeNodeFactory.Create();
                //    treeNode.AddProperty(xmlProp);
                //    presentation.RootNode = treeNode;

                //    first = false;
                //}

                //foreach (XmlNode childOfBody in bodyElement.ChildNodes)
                //{
                //    parseContentDocument(childOfBody, m_Project.Presentations.Get(0).RootNode, fullDocPath);
                //}
            }
        }