Пример #1
0
        //public event EventHandler Closed

        private void Window_Closed(object sender, EventArgs e)
        {
            if (ProjectUri != null && ProjectUri.IsFile)
            {
                string strPath          = ProjectUri.LocalPath;
                int    indexOfLastSlash = strPath.LastIndexOf('\\');
                string strFile          = strPath.Substring(indexOfLastSlash);
                Uri    projectUri       = new Uri(strPath.Remove(indexOfLastSlash) + strFile + ".out.xuk");
                //FileStream fs = new FileStream(projectUri.LocalPath, FileMode.Create, FileAccess.Write);

                SaveXukAction action = new SaveXukAction(Project, projectUri);
                bool          wasCancelled;
                ProgressWindow.ExecuteProgressAction(action, out wasCancelled);
                if (wasCancelled)
                {
                    return;
                }
            }
        }
Пример #2
0
        private bool saveAs(string filePath, bool autoSave, bool noUI)
        {
            if (DocumentProject == null)
            {
                return(false);
            }

            string saveAsDocumentFilePath = filePath;

            m_Logger.Log(String.Format(@"UrakawaSession.saveas() [{0}]", saveAsDocumentFilePath), Category.Debug, Priority.Medium);

            //var backWorker = new BackgroundWorker
            //    {
            //        WorkerSupportsCancellation = true,
            //        WorkerReportsProgress = true
            //    };

            //bool cancelFlag = false;
            //int currentPercentage = 0;

            var uri = new Uri(saveAsDocumentFilePath + SAVING_EXT, UriKind.Absolute);

            //DocumentProject.OpenXuk(uri);

            DocumentProject.PrettyFormat = Settings.Default.XUK_PrettyFormat;

            var action = new SaveXukAction(DocumentProject, DocumentProject, uri, !Settings.Default.EnableAutoSave)
            {
                ShortDescription = Tobi_Plugin_Urakawa_Lang.UrakawaSaveAction_ShortDesc,
                LongDescription  = Tobi_Plugin_Urakawa_Lang.UrakawaSaveAction_LongDesc
            };

            bool cancelled = false;
            bool error     = false;


            Action cancelledCallback =
                () =>
            {
                cancelled = true;

                RaisePropertyChanged(() => IsDirty);
                //IsDirty = true;

                //backWorker.CancelAsync();
            };

            Action finishedCallback =
                () =>
            {
                cancelled = false;

                if (DocumentFilePath == saveAsDocumentFilePath)
                {
                    DebugFix.Assert(!autoSave);

                    string saving = DocumentFilePath + SAVING_EXT;

                    if (File.Exists(saving))
                    {
                        if (Settings.Default.EnableAutoSave)
                        {
                            SaveXukAction.Backup(DocumentFilePath);
                        }
                        File.Delete(DocumentFilePath);

                        File.Move(saving, DocumentFilePath);
                        try
                        {
                            File.SetAttributes(DocumentFilePath, FileAttributes.Normal);
                        }
                        catch
                        {
                        }

                        //File.Copy(DocumentFilePath + SAVING_EXT, DocumentFilePath);
                        //File.Delete(DocumentFilePath + SAVING_EXT);

                        DocumentProject.Presentations.Get(0).UndoRedoManager.SetDirtyMarker();
                    }
                    else
                    {
#if DEBUG
                        Debugger.Break();
#endif

                        m_Logger.Log(@"UrakawaSession_Save SAVING NOT EXIST!!?? => " + saving, Category.Debug,
                                     Priority.Medium);
                    }
                }
                else
                {
                    string saving = saveAsDocumentFilePath + SAVING_EXT;

                    if (File.Exists(saving))
                    {
                        if (File.Exists(saveAsDocumentFilePath))
                        {
                            if (Settings.Default.EnableAutoSave && !autoSave)
                            {
                                SaveXukAction.Backup(saveAsDocumentFilePath);
                            }
                            File.Delete(saveAsDocumentFilePath);
                        }

                        File.Move(saving, saveAsDocumentFilePath);
                        try
                        {
                            File.SetAttributes(saveAsDocumentFilePath, FileAttributes.Normal);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
#if DEBUG
                        Debugger.Break();
#endif

                        m_Logger.Log(@"UrakawaSession_SaveAs SAVING NOT EXIST!!?? => " + saving, Category.Debug,
                                     Priority.Medium);
                    }
                }


                if (m_EventAggregator != null)
                {
                    m_EventAggregator.GetEvent <StatusBarMessageUpdateEvent>()
                    .Publish(Tobi_Plugin_Urakawa_Lang.Saved);
                }

                RaisePropertyChanged(() => IsDirty);
                //IsDirty = false;
            };

            if (autoSave || noUI)
            {
                action.Progress += new EventHandler <ProgressEventArgs>(
                    delegate(object sender, ProgressEventArgs e)
                {
                }
                    );

                action.Finished += new EventHandler <FinishedEventArgs>(
                    delegate(object sender, FinishedEventArgs e)
                {
                    finishedCallback();
                }
                    );

                action.Cancelled += new EventHandler <CancelledEventArgs>(
                    delegate(object sender, CancelledEventArgs e)
                {
                    cancelledCallback();
                }
                    );

                try
                {
                    action.DoWork();
                }
                catch (Exception ex)
                {
#if DEBUG
                    Debugger.Break();
#endif
                    //Console.WriteLine(ex.Message);
                    //Console.WriteLine(ex.StackTrace);

                    ExceptionHandler.Handle(ex, false, m_ShellView);

                    error = true;
                }
            }
            else
            {
                error = m_ShellView.RunModalCancellableProgressTask(true,
                                                                    Tobi_Plugin_Urakawa_Lang.UrakawaSaveAction_ShortDesc, action,
                                                                    cancelledCallback,
                                                                    finishedCallback
                                                                    );
            }

            string savingFile = saveAsDocumentFilePath + SAVING_EXT;
            if (File.Exists(savingFile))
            {
                if (cancelled && !error)
                {
                    File.Delete(savingFile);
                }

                if (error)
                {
                    m_ShellView.ExecuteShellProcess(Path.GetDirectoryName(savingFile));
                }
            }

            return(!cancelled);
        }
Пример #3
0
        }//btnLoad

        //Start Import button to strat the conversion process
        private void btnStartImport_Click(object sender, EventArgs e)
        {
            var            converter    = new XukImport.DaisyToXuk(m_ImportFile, m_SaveDir);
            Channel        channelText  = null;
            Channel        channelAudio = null;
            List <Channel> listCh       = converter.Project.Presentations.Get(0).ChannelsManager.ManagedObjects.ContentsAs_ListCopy;

            foreach (Channel ch in listCh)
            {
                if (ch is TextChannel)
                {
                    channelText = ch;
                }
                else if (ch is AudioChannel)
                {
                    channelAudio = ch;
                }
            }

            RenameChannelCommand.mProject = converter.Project;

            RenameChannelCommand cmd1 = null;

            if (channelText != null)
            {
                cmd1 = converter.Project.Presentations.Get(0).CommandFactory.Create <RenameChannelCommand>();
                cmd1.Init(channelText, "The new TEXT Channel Name");
            }

            RenameChannelCommand cmd2 = null;

            if (channelAudio != null)
            {
                cmd2 = converter.Project.Presentations.Get(0).CommandFactory.Create <RenameChannelCommand>();
                cmd2.Init(channelAudio, "The new AUDIO Channel Name");
            }

            RenameChannelCommand cmd3 = null;

            if (channelText != null)
            {
                cmd3 = converter.Project.Presentations.Get(0).CommandFactory.Create <RenameChannelCommand>();
                cmd3.Init(channelText, "NEW TEXT Channel Name");
            }

            /*
             * DeleteChannelCommand cmd2 = null;
             * if (channelAudio != null)
             * {
             *  cmd2 = new DeleteChannelCommand(channelAudio);
             * }
             * */


            converter.Project.Presentations.Get(0).UndoRedoManager.StartTransaction("rename transaction", null);

            if (cmd1 != null)
            {
                converter.Project.Presentations.Get(0).UndoRedoManager.Execute(cmd1);
            }

            if (cmd2 != null)
            {
                converter.Project.Presentations.Get(0).UndoRedoManager.Execute(cmd2);
            }

            converter.Project.Presentations.Get(0).UndoRedoManager.EndTransaction();


            if (cmd3 != null)
            {
                converter.Project.Presentations.Get(0).UndoRedoManager.Execute(cmd3);
            }

            converter.Project.Presentations.Get(0).UndoRedoManager.Undo();

            Uri uriComp = new Uri(m_SaveDir + ".COMPRESSED.xuk");

            converter.Project.SetPrettyFormat(false);

            {
                SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriComp);
                bool          saveWasCancelled;
                Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                if (saveWasCancelled)
                {
                    return;
                }
            }

            Uri uriPretty = new Uri(m_SaveDir + ".PRETTY.xuk");

            converter.Project.SetPrettyFormat(true);

            {
                SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriPretty);
                bool          saveWasCancelled;
                Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                if (saveWasCancelled)
                {
                    return;
                }
            }

            /////
            //// Make sure we don't create concurrent access to WAV files while opening the same XUK file in several projects.
            converter.Project.Presentations.Get(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
            /////
            Project projectPretty = new Project();

            {
                OpenXukAction actionOpen = new OpenXukAction(projectPretty, uriPretty);
                bool          openWasCancelled;
                Progress.ExecuteProgressAction(actionOpen, out openWasCancelled);
                if (openWasCancelled)
                {
                    return;
                }
            }
            projectPretty.Presentations.Get(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
            System.Diagnostics.Debug.Assert(converter.Project.ValueEquals(projectPretty));

            Project projectComp = new Project();

            {
                OpenXukAction actionOpen = new OpenXukAction(projectComp, uriComp);
                bool          openWasCancelled;
                Progress.ExecuteProgressAction(actionOpen, out openWasCancelled);
                if (openWasCancelled)
                {
                    return;
                }
            }
            projectComp.Presentations.Get(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
            System.Diagnostics.Debug.Assert(converter.Project.ValueEquals(projectComp));

            //// Make sure we don't create concurrent access to WAV files while opening the same XUK file in several projects.
            System.Diagnostics.Debug.Assert(projectComp.ValueEquals(projectPretty));

            converter.Project.Presentations.Get(0).UndoRedoManager.Redo();

            System.Diagnostics.Debug.Assert(!converter.Project.ValueEquals(projectPretty));


            //TODO: there is a bug in the Urakawa SDK due to the static sharing of the XukString !
            // In other words, the Factories will not refresh their QNames in the following call to SetPrettyFormat(),
            // because converter.Project was already set to PRETTY a while ago (see code above). Problem:
            // the "projectComp" instance created above has set the Factory QNames to COMPRESSED
            // and due to the static sharing of XukStrings, converter.Project is affected. As a result, the PRETTY2 file
            // is nicely indented but with compressed q-names.

            Uri uriPretty2 = new Uri(m_SaveDir + ".PRETTY2.xuk");

            converter.Project.SetPrettyFormat(true);

            {
                SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriPretty2);
                bool          saveWasCancelled;
                Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                if (saveWasCancelled)
                {
                    return;
                }
            }
        }//btnStartImport
Пример #4
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);
                //}
            }
        }
Пример #5
0
        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;
            }
        }
Пример #6
0
        private void btnLoad_Click_1(object sender, EventArgs e)
        {
            txtBookName.Clear();

            var open = new OpenFileDialog();

            //open.InitialDirectory = @"C:\";
            open.Filter           = "XML Files (*.xml)|*.xml|OPF Files (*.opf)|*.opf|All files(*.*)|*.*";
            open.FilterIndex      = 1;
            open.RestoreDirectory = true;
            if (open.ShowDialog(this) == DialogResult.OK)
            {
                txtBookName.Text = open.FileName;
                string pathDTBook = txtBookName.Text;
                DTBooktoXukConversion converter = new DTBooktoXukConversion(pathDTBook);
                Channel        channelText      = null;
                Channel        channelAudio     = null;
                List <Channel> listCh           = converter.Project.GetPresentation(0).ChannelsManager.ListOfChannels;
                foreach (Channel ch in listCh)
                {
                    if (ch is TextChannel)
                    {
                        channelText = ch;
                    }
                    else if (ch is AudioChannel)
                    {
                        channelAudio = ch;
                    }
                }

                RenameChannelCommand.mProject = converter.Project;

                RenameChannelCommand cmd1 = null;
                if (channelText != null)
                {
                    cmd1 = converter.Project.GetPresentation(0).CommandFactory.Create <RenameChannelCommand>();
                    cmd1.Init(channelText, "The new TEXT Channel Name");
                }

                RenameChannelCommand cmd2 = null;
                if (channelAudio != null)
                {
                    cmd2 = converter.Project.GetPresentation(0).CommandFactory.Create <RenameChannelCommand>();
                    cmd2.Init(channelAudio, "The new AUDIO Channel Name");
                }

                RenameChannelCommand cmd3 = null;
                if (channelText != null)
                {
                    cmd3 = converter.Project.GetPresentation(0).CommandFactory.Create <RenameChannelCommand>();
                    cmd3.Init(channelText, "NEW TEXT Channel Name");
                }

                /*
                 * DeleteChannelCommand cmd2 = null;
                 * if (channelAudio != null)
                 * {
                 *  cmd2 = new DeleteChannelCommand(channelAudio);
                 * }
                 * */


                converter.Project.GetPresentation(0).UndoRedoManager.StartTransaction("rename transaction", null);

                if (cmd1 != null)
                {
                    converter.Project.GetPresentation(0).UndoRedoManager.Execute(cmd1);
                }

                if (cmd2 != null)
                {
                    converter.Project.GetPresentation(0).UndoRedoManager.Execute(cmd2);
                }

                converter.Project.GetPresentation(0).UndoRedoManager.EndTransaction();


                if (cmd3 != null)
                {
                    converter.Project.GetPresentation(0).UndoRedoManager.Execute(cmd3);
                }

                converter.Project.GetPresentation(0).UndoRedoManager.Undo();

                ////
                ////
                Uri uriComp = new Uri(txtBookName.Text + ".COMPRESSED.xuk");

                converter.Project.SetPrettyFormat(false);

                {
                    SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriComp);
                    bool          saveWasCancelled;
                    Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                    if (saveWasCancelled)
                    {
                        return;
                    }
                }

                /////

                Uri uriPretty = new Uri(txtBookName.Text + ".PRETTY.xuk");

                converter.Project.SetPrettyFormat(true);

                {
                    SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriPretty);
                    bool          saveWasCancelled;
                    Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                    if (saveWasCancelled)
                    {
                        return;
                    }
                }

                /////
                //// Make sure we don't create concurrent access to WAV files while opening the same XUK file in several projects.
                converter.Project.GetPresentation(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
                /////
                Project projectPretty = new Project();
                {
                    OpenXukAction actionOpen = new OpenXukAction(projectPretty, uriPretty);
                    bool          openWasCancelled;
                    Progress.ExecuteProgressAction(actionOpen, out openWasCancelled);
                    if (openWasCancelled)
                    {
                        return;
                    }
                }
                projectPretty.GetPresentation(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
                System.Diagnostics.Debug.Assert(converter.Project.ValueEquals(projectPretty));
                /////
                /////
                Project projectComp = new Project();
                {
                    OpenXukAction actionOpen = new OpenXukAction(projectComp, uriComp);
                    bool          openWasCancelled;
                    Progress.ExecuteProgressAction(actionOpen, out openWasCancelled);
                    if (openWasCancelled)
                    {
                        return;
                    }
                }
                projectComp.GetPresentation(0).DataProviderManager.CompareByteStreamsDuringValueEqual = false;
                System.Diagnostics.Debug.Assert(converter.Project.ValueEquals(projectComp));

                //// Make sure we don't create concurrent access to WAV files while opening the same XUK file in several projects.
                System.Diagnostics.Debug.Assert(projectComp.ValueEquals(projectPretty));

                converter.Project.GetPresentation(0).UndoRedoManager.Redo();

                System.Diagnostics.Debug.Assert(!converter.Project.ValueEquals(projectPretty));

                Uri uriPretty2 = new Uri(txtBookName.Text + ".PRETTY2.xuk");

                converter.Project.SetPrettyFormat(true);

                {
                    SaveXukAction actionSave = new SaveXukAction(converter.Project, converter.Project, uriPretty2);
                    bool          saveWasCancelled;
                    Progress.ExecuteProgressAction(actionSave, out saveWasCancelled);
                    if (saveWasCancelled)
                    {
                        return;
                    }
                }
            }
        }