Example #1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Imports the specified book.
        /// </summary>
        /// <param name="owningForm">Form that can be used as the owner of progress dialogs and
        /// message boxes.</param>
        /// <param name="bookNum">The canonical book number.</param>
        /// <returns>
        /// The ScrBook created to hold the imported data
        /// </returns>
        /// ------------------------------------------------------------------------------------
        private IScrBook ImportBook(Form owningForm, int bookNum)
        {
            IScrImportSet importSettings        = null;
            var           haveSomethingToImport = NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
            {
                importSettings = m_scr.FindOrCreateDefaultImportSettings(TypeOfImport.Paratext6, m_scriptureStylesheet, FwDirectoryFinder.FlexStylesPath);
                importSettings.RevertToSaved();
                importSettings.ParatextScrProj = m_associatedPtText.Name;
                importSettings.StartRef        = new BCVRef(bookNum, 0, 0);
                var chapter                          = m_associatedPtText.Versification.LastChapter(bookNum);
                importSettings.EndRef                = new BCVRef(bookNum, chapter, m_associatedPtText.Versification.LastVerse(bookNum, chapter));
                importSettings.ImportTranslation     = true;
                importSettings.ImportBackTranslation = false;
                ParatextHelper.LoadProjectMappings(importSettings);
                var importMap  = importSettings.GetMappingListForDomain(ImportDomain.Main);
                var figureInfo = importMap[@"\fig"];
                if (figureInfo != null)
                {
                    figureInfo.IsExcluded = true;
                }
                importSettings.SaveSettings();
                return(true);
            });

            if (haveSomethingToImport && ReflectionHelper.GetBoolResult(ReflectionHelper.GetType("ParatextImport.dll", "ParatextImport.ParatextImportManager"), "ImportParatext", owningForm, m_cache, importSettings, m_scriptureStylesheet, App))
            {
                return(m_scr.FindBook(bookNum));
            }
            return(null);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Loads the texts for each Scripture book title, section, footnote, etc.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void LoadScriptureTexts(FdoCache cache, IBookImporter bookImporter)
        {
            m_bookImporter     = bookImporter;
            m_associatedPtText = bookImporter != null?ParatextHelper.GetAssociatedProject(cache.ProjectId) : null;

            m_scr = cache.LanguageProject.TranslatedScriptureOA;
            if (m_scr == null)
            {
                return;
            }
            List <TreeNode> otBooks = new List <TreeNode>();
            List <TreeNode> ntBooks = new List <TreeNode>();

            for (int bookNum = 1; bookNum <= BCVRef.LastBook; bookNum++)
            {
                var    bookName = cache.ServiceLocator.GetInstance <IScrRefSystemRepository>().Singleton.BooksOS[bookNum - 1].UIBookName;
                object book     = m_scr.FindBook(bookNum);
                if (book == null)
                {
                    if (m_associatedPtText != null && m_associatedPtText.BookPresent(bookNum))
                    {
                        book = bookNum;
                    }
                    else
                    {
                        continue;
                    }
                }

                TreeNode node = new TreeNode(bookName);
                node.Tag  = book;
                node.Name = "Book";                 // help us query for books.
                if (bookNum < ScriptureTags.kiNtMin)
                {
                    otBooks.Add(node);
                }
                else
                {
                    ntBooks.Add(node);
                }
            }

            TreeNode bibleNode = new TreeNode(FwControls.kstidBibleNode);

            bibleNode.Name = "Bible";
            if (otBooks.Count > 0)
            {
                TreeNode testamentNode = new TreeNode(FwControls.kstidOtNode, otBooks.ToArray());
                testamentNode.Name = "Testament";                 // help us query for Testaments
                bibleNode.Nodes.Add(testamentNode);
            }

            if (ntBooks.Count > 0)
            {
                TreeNode testamentNode = new TreeNode(FwControls.kstidNtNode, ntBooks.ToArray());
                testamentNode.Name = "Testament";                 // help us query for Testaments
                bibleNode.Nodes.Add(testamentNode);
            }
            Nodes.Add(bibleNode);
        }
        /// <summary>
        /// This class creates text, it must delete it here when UNDO is commanded
        /// so it can update InterestingTexts.
        /// </summary>

/*		public override void PropChanged(int hvo, int tag, int ivMin, int cvIns, int cvDel)
 *              {
 *                      if (cvDel != 1)
 *                              return;
 *                      SaveOnChangeRecord();
 *                      SuppressSaveOnChangeRecord = true;
 *                      try
 *                      {
 *                              m_list.DeleteCurrentObject();
 *                      }
 *                      finally
 *                      {
 *                              SuppressSaveOnChangeRecord = false;
 *                      }
 *                      GetInterestingTextList().UpdateInterestingTexts();
 *              } */

        #region IBookImporter Members
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Imports the specified book.
        /// </summary>
        /// <param name="bookNum">The canonical book number.</param>
        /// <param name="owningForm">Form that can be used as the owner of progress dialogs and
        /// message boxes.</param>
        /// <param name="importBt">True to import only the back translation, false to import
        /// only the main translation</param>
        /// <returns>
        /// The ScrBook created to hold the imported data
        /// </returns>
        /// ------------------------------------------------------------------------------------
        public IScrBook Import(int bookNum, Form owningForm, bool importBt)
        {
            IScripture scr = Cache.LangProject.TranslatedScriptureOA;
            bool       haveSomethingToImport = NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                IScrImportSet importSettings   = scr.FindOrCreateDefaultImportSettings(TypeOfImport.Paratext6);
                importSettings.StyleSheet      = ScriptureStylesheet;
                IScrText paratextProj          = ParatextHelper.GetAssociatedProject(Cache.ProjectId);
                importSettings.ParatextScrProj = paratextProj.Name;
                importSettings.StartRef        = new BCVRef(bookNum, 0, 0);
                int chapter           = paratextProj.Versification.LastChapter(bookNum);
                importSettings.EndRef = new BCVRef(bookNum, chapter, paratextProj.Versification.LastVerse(bookNum, chapter));
                if (!importBt)
                {
                    importSettings.ImportTranslation     = true;
                    importSettings.ImportBackTranslation = false;
                }
                else
                {
                    List <IScrText> btProjects = ParatextHelper.GetBtsForProject(paratextProj).ToList();
                    if (btProjects.Count > 0 && (string.IsNullOrEmpty(importSettings.ParatextBTProj) ||
                                                 !btProjects.Any(st => st.Name == importSettings.ParatextBTProj)))
                    {
                        importSettings.ParatextBTProj = btProjects[0].Name;
                    }
                    if (string.IsNullOrEmpty(importSettings.ParatextBTProj))
                    {
                        return(false);
                    }
                    importSettings.ImportTranslation     = false;
                    importSettings.ImportBackTranslation = true;
                }
                ParatextHelper.LoadProjectMappings(importSettings);
                ScrMappingList importMap     = importSettings.GetMappingListForDomain(ImportDomain.Main);
                ImportMappingInfo figureInfo = importMap[@"\fig"];
                if (figureInfo != null)
                {
                    figureInfo.IsExcluded = true;
                }
                importSettings.SaveSettings();
                return(true);
            });

            if (haveSomethingToImport && ReflectionHelper.GetBoolResult(ReflectionHelper.GetType("TeImportExport.dll",
                                                                                                 "SIL.FieldWorks.TE.TeImportManager"), "ImportParatext", owningForm, ScriptureStylesheet,
                                                                        (FwApp)m_mediator.PropertyTable.GetValue("App")))
            {
                return(scr.FindBook(bookNum));
            }
            return(null);
        }
Example #4
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets a list of books that exist for all of the files in this project.
        /// </summary>
        /// <returns>A List of integers representing 1-based canonical book numbers that exist
        /// in any source represented by these import settings</returns>
        /// <exception cref="NotSupportedException">If project is not a supported type</exception>
        /// ------------------------------------------------------------------------------------
        public static List <int> BooksForProject(this IScrImportSet importSettings)
        {
            Debug.Assert(importSettings.BasicSettingsExist, "Vernacular Scripture project not defined.");
            switch (importSettings.ImportTypeEnum)
            {
            case TypeOfImport.Paratext6:
                // TODO (TE-5903): Check BT and Notes projects as well.
                return(ParatextHelper.GetProjectBooks(importSettings.ParatextScrProj).ToList());

            case TypeOfImport.Paratext5:
            case TypeOfImport.Other:
                List <int> booksPresent = new List <int>();
                foreach (IScrImportFileInfo file in importSettings.GetImportFiles(ImportDomain.Main))
                {
                    foreach (int iBook in file.BooksInFile)
                    {
                        if (!booksPresent.Contains(iBook))
                        {
                            booksPresent.Add(iBook);
                        }
                    }
                }

                foreach (IScrImportFileInfo file in importSettings.GetImportFiles(ImportDomain.BackTrans))
                {
                    foreach (int iBook in file.BooksInFile)
                    {
                        if (!booksPresent.Contains(iBook))
                        {
                            booksPresent.Add(iBook);
                        }
                    }
                }

                foreach (IScrImportFileInfo file in importSettings.GetImportFiles(ImportDomain.Annotations))
                {
                    foreach (int iBook in file.BooksInFile)
                    {
                        if (!booksPresent.Contains(iBook))
                        {
                            booksPresent.Add(iBook);
                        }
                    }
                }
                booksPresent.Sort();
                return(booksPresent);

            default:
                throw new NotSupportedException("Unexpected type of Import Project");
            }
        }
Example #5
0
        /// <summary>
        /// Imports the specified book's back translation.
        /// </summary>
        /// <param name="owningForm">Form that can be used as the owner of progress dialogs and
        /// message boxes.</param>
        /// <param name="bookNum">The canonical book number.</param>
        /// <param name="btProject">The BT project to import</param>
        private void ImportBackTranslation(Form owningForm, int bookNum, IScrText btProject)
        {
            if (string.IsNullOrEmpty(btProject.Name))
            {
                return;
            }
            IScrImportSet importSettings = null;

            NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
            {
                importSettings = m_scr.FindOrCreateDefaultImportSettings(TypeOfImport.Paratext6, m_scriptureStylesheet, FwDirectoryFinder.FlexStylesPath);
                importSettings.ParatextScrProj       = m_associatedPtText.Name;
                importSettings.StartRef              = new BCVRef(bookNum, 0, 0);
                importSettings.EndRef                = new BCVRef(bookNum, 0, 0);
                importSettings.ParatextBTProj        = btProject.Name;
                importSettings.ImportTranslation     = false;
                importSettings.ImportBackTranslation = true;

                ParatextHelper.LoadProjectMappings(importSettings);
                var importMap = importSettings.GetMappingListForDomain(ImportDomain.Main);
                // Check for corrupted import settings, clear them out if they are bad.
                if (importMap == null)
                {
                    m_scr.DefaultImportSettings = null;
                    m_scr.ImportSettingsOC.Clear();
                    importSettings = null;
                }
                else
                {
                    var figureInfo = importMap[@"\fig"];
                    if (figureInfo != null)
                    {
                        figureInfo.IsExcluded = true;
                    }
                    importSettings.SaveSettings();
                }
            });

            if (importSettings != null)
            {
                ReflectionHelper.GetBoolResult(ReflectionHelper.GetType("ParatextImport.dll", "ParatextImport.ParatextImportManager"), "ImportParatext", owningForm, m_cache, importSettings, m_scriptureStylesheet, App);
            }
        }
Example #6
0
        private static bool ParatextProjectsAccessible(IScrImportSet importSettings, out StringCollection projectsNotFound)
        {
            projectsNotFound = new StringCollection();

            if (importSettings.ParatextScrProj == null)
            {
                return(false);
            }

            // Paratext seems to want to have write access to do an import...
            string filename = Path.Combine(ScriptureProvider.SettingsDirectory, importSettings.ParatextScrProj + ".ssf");

            if (!FileUtils.IsFileReadableAndWritable(filename) ||
                !ParatextHelper.GetProjectBooks(importSettings.ParatextScrProj).Any())
            {
                projectsNotFound.Add(importSettings.ParatextScrProj);
            }

            if (importSettings.ParatextBTProj != null)
            {
                filename = Path.Combine(ScriptureProvider.SettingsDirectory, importSettings.ParatextBTProj + ".ssf");
                if (!FileUtils.IsFileReadableAndWritable(filename) ||
                    !ParatextHelper.GetProjectBooks(importSettings.ParatextBTProj).Any())
                {
                    projectsNotFound.Add(importSettings.ParatextBTProj);
                }
            }

            if (importSettings.ParatextNotesProj != null)
            {
                filename = Path.Combine(ScriptureProvider.SettingsDirectory, importSettings.ParatextNotesProj + ".ssf");
                if (!FileUtils.IsFileReadableAndWritable(filename) ||
                    !ParatextHelper.GetProjectBooks(importSettings.ParatextNotesProj).Any())
                {
                    projectsNotFound.Add(importSettings.ParatextNotesProj);
                }
            }

            return(projectsNotFound.Count == 0);
        }
Example #7
0
        /// <summary>
        /// This class creates text, it must delete it here when UNDO is commanded
        /// so it can update InterestingTexts.
        /// </summary>

/*		public override void PropChanged(int hvo, int tag, int ivMin, int cvIns, int cvDel)
 *              {
 *                      if (cvDel != 1)
 *                              return;
 *                      SaveOnChangeRecord();
 *                      SuppressSaveOnChangeRecord = true;
 *                      try
 *                      {
 *                              m_list.DeleteCurrentObject();
 *                      }
 *                      finally
 *                      {
 *                              SuppressSaveOnChangeRecord = false;
 *                      }
 *                      GetInterestingTextList().UpdateInterestingTexts();
 *              } */

        #region IBookImporter Members
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Imports the specified book.
        /// </summary>
        /// <param name="bookNum">The canonical book number.</param>
        /// <param name="owningForm">Form that can be used as the owner of progress dialogs and
        /// message boxes.</param>
        /// <param name="importBt">True to import only the back translation, false to import
        /// only the main translation</param>
        /// <returns>
        /// The ScrBook created to hold the imported data
        /// </returns>
        /// ------------------------------------------------------------------------------------
        public IScrBook Import(int bookNum, Form owningForm, bool importBt)
        {
            IScripture scr = Cache.LangProject.TranslatedScriptureOA;
            bool       haveSomethingToImport = NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                IScrImportSet importSettings   = scr.FindOrCreateDefaultImportSettings(TypeOfImport.Paratext6);
                ScrText paratextProj           = ParatextHelper.GetAssociatedProject(Cache.ProjectId);
                importSettings.ParatextScrProj = paratextProj.Name;
                importSettings.IncludeBooks(bookNum, bookNum, paratextProj.Versification);
                if (!importBt)
                {
                    importSettings.ImportTranslation     = true;
                    importSettings.ImportBackTranslation = false;
                }
                else
                {
                    List <ScrText> btProjects = ParatextHelper.GetBtsForProject(paratextProj).ToList();
                    if (btProjects.Count > 0 && (string.IsNullOrEmpty(importSettings.ParatextBTProj) ||
                                                 !btProjects.Any(st => st.Name == importSettings.ParatextBTProj)))
                    {
                        importSettings.ParatextBTProj = btProjects[0].Name;
                    }
                    if (string.IsNullOrEmpty(importSettings.ParatextBTProj))
                    {
                        return(false);
                    }
                    importSettings.ImportTranslation     = false;
                    importSettings.ImportBackTranslation = true;
                }
                return(true);
            });

            if (haveSomethingToImport && ReflectionHelper.GetBoolResult(ReflectionHelper.GetType("TeImportExport.dll",
                                                                                                 "SIL.FieldWorks.TE.TeImportManager"), "ImportParatext", owningForm, ScriptureStylesheet,
                                                                        (FwApp)m_mediator.PropertyTable.GetValue("App")))
            {
                return(scr.FindBook(bookNum));
            }
            return(null);
        }
Example #8
0
        private bool FillInBookChildren(TreeNode bookNode)
        {
            IScrBook book    = bookNode.Tag as IScrBook;
            int      bookNum = (book == null) ? (int)bookNode.Tag : book.CanonicalNum;
            Form     owner   = FindForm();

            while (owner != null && !owner.Visible)
            {
                owner = owner.Owner;
            }
            if (owner == null)
            {
                owner = Form.ActiveForm ?? Application.OpenForms[0];
            }

            if (book == null || (m_associatedPtText != null && m_associatedPtText.BookPresent(book.CanonicalNum) &&
                                 !m_associatedPtText.IsCheckSumCurrent(book.CanonicalNum, book.ImportedCheckSum)))
            {
                // The book for this node is out-of-date with the Paratext book data
                IScrBook importedBook = m_bookImporter.Import(bookNum, owner, false);
                if (importedBook != null)
                {
                    bookNode.Tag = book = importedBook;
                }
                if (book == null)
                {
                    return(false);
                }
            }

            if (m_associatedPtText != null)
            {
                ScrText btProject = ParatextHelper.GetBtsForProject(m_associatedPtText).FirstOrDefault();
                if (btProject != null && !btProject.IsCheckSumCurrent(book.CanonicalNum,
                                                                      book.ImportedBtCheckSum.get_String(book.Cache.DefaultAnalWs).Text))
                {
                    // The BT for this book node is out-of-date with the Paratext BT data
                    m_bookImporter.Import(bookNum, owner, true);
                }
            }

            bookNode.Nodes.Clear();             // Gets rid of dummy.
            //IScrBook book = (IScrBook)bookNode.Tag;
            // Add Title node.
            if (book.TitleOA != null)
            {
                TreeNode titleNode =
                    new TreeNode(ResourceHelper.GetResourceString("kstidScriptureTitle"));
                titleNode.Name = book.TitleOA.ToString();
                titleNode.Tag  = book.TitleOA;
                bookNode.Nodes.Add(titleNode);
            }

            // Add Sections.
            foreach (IScrSection section in book.SectionsOS)
            {
                string chapterVerseBridge = m_scr.ChapterVerseBridgeAsString(section);
                if (section.HeadingOA != null)
                {
                    // Include the heading text if it's not empty.  See LT-8764.
                    int cTotal = 0;
                    foreach (IScrTxtPara para in section.HeadingOA.ParagraphsOS)
                    {
                        cTotal += para.Contents.Length;
                    }
                    if (cTotal > 0)
                    {
                        string   sFmt = ResourceHelper.GetResourceString("kstidSectionHeading");
                        TreeNode node = new TreeNode(String.Format(sFmt, chapterVerseBridge));
                        node.Name = String.Format(sFmt, section);
                        node.Tag  = section.HeadingOA;                        // expect an StText
                        bookNode.Nodes.Add(node);
                    }
                }
                TreeNode sectionNode = new TreeNode(chapterVerseBridge);
                sectionNode.Name = section.ToString();
                sectionNode.Tag  = section.ContentOA;                // expect an StText
                bookNode.Nodes.Add(sectionNode);
            }

            // Add Footnotes in reverse order, so we can insert them in the proper order.
            List <IScrFootnote> footnotes = new List <IScrFootnote>(book.FootnotesOS);

            footnotes.Reverse();
            foreach (IScrFootnote scrFootnote in footnotes)
            {
                // insert under the relevant section, if any (LTB-408)
                IScrSection containingSection;
                IStText     containingTitle = null;
                if (scrFootnote.TryGetContainingSection(out containingSection) ||
                    scrFootnote.TryGetContainingTitle(out containingTitle))
                {
                    string   nodeName     = m_scr.ContainingRefAsString(scrFootnote);
                    TreeNode footnoteNode = new TreeNode(nodeName);
                    footnoteNode.Tag  = scrFootnote;
                    footnoteNode.Name = "Footnote";

                    // see if we can lookup the node of this section.
                    int nodeIndex = bookNode.Nodes.IndexOfKey(
                        containingSection != null ? containingSection.ToString() : containingTitle.ToString());
                    //TreeNode[] sectionNodes = bookNode.Nodes.Find(hvoSection.ToString(), false);
                    //if (sectionNodes != null && sectionNodes.Length > 0)
                    if (nodeIndex >= 0)
                    {
                        bookNode.Nodes.Insert(nodeIndex + 1, footnoteNode);
                    }
                    else
                    {
                        bookNode.Nodes.Add(footnoteNode);                               // insert at end.
                    }
                }
            }
            return(true);
        }
Example #9
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Handles the Load event of the ExportPtxDialog control.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event
        /// data.</param>
        /// ------------------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            // set up default short name
            ScrImportSet importSet =
                (ScrImportSet)m_cache.LangProject.TranslatedScriptureOA.DefaultImportSettings;

            m_shortName = (importSet != null) ? importSet.ParatextScrProj : null;

            if (m_shortName == null)
            {
                LgWritingSystem wsVern = ((LgWritingSystem)m_cache.LangProject.CurVernWssRS[0]);
                string          abbr   = wsVern.Abbr.UserDefaultWritingSystem;
                if (abbr != null)
                {
                    m_shortName = abbr.Trim();
                }
                else
                {
                    m_shortName = wsVern.Abbreviation.Trim();
                }
            }
            else
            {
                m_shortName = m_shortName.Trim();
            }

            // Paratext 6 requires short name to be between 3 and 5 characters in length.
            if (m_shortName.Length < 3)
            {
                m_shortName = m_shortName.PadRight(3, '_');
            }
            if (m_shortName.Length > 5)
            {
                m_shortName = m_shortName.Substring(0, 5);
            }

            m_BTshortName = (importSet != null && !string.IsNullOrEmpty(importSet.ParatextBTProj)) ?
                            importSet.ParatextBTProj : (m_shortName.Substring(0, 3) + "BT");

            // Set values for what to export for one domain export (Paratext).
            switch (m_regGroup.GetIntValue("ParatextOneDomainExportWhat", 0))
            {
            case 0:
            default:
                // Temporarily load the BT settings, so when we "switch" to Scripture,
                // the BT settings will be saved in our internal object.
                LoadFileNameSchemeControl(base.RegistrySettingType + "BT", m_BTshortName);
                m_BTfileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                rdoScripture.Select();

                base.OnLoad(e);
                m_fileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                break;

            case 1:
                // Temporarily load the regular (vern) settings, so when we "switch" to
                // back translation, the vern settings will be saved in our internal object.
                LoadFileNameSchemeControl(base.RegistrySettingType, m_shortName);
                m_fileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                rdoBackTranslation.Select();

                base.OnLoad(e);
                m_BTfileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                break;
            }

            // Get the output file or folder specification.
            SCRIPTUREOBJECTSLib.ISCScriptureText3 paraTextSO = null;
            try
            {
                paraTextSO = new SCRIPTUREOBJECTSLib.SCScriptureTextClass();
            }
            catch
            {
                // Ignore: Paratext not installed
            }
            if (paraTextSO != null)
            {
                m_paratextProjFolder = paraTextSO.SettingsDirectory;
                if (m_paratextProjFolder != null)
                {
                    m_paratextProjFolder = m_paratextProjFolder.Trim(Path.DirectorySeparatorChar,
                                                                     Path.AltDirectorySeparatorChar);
                }
                string[] shortNames = ParatextHelper.GetParatextShortNames(paraTextSO);
                if (shortNames != null)
                {
                    foreach (string shortName in shortNames)
                    {
                        bool fIsEditable = true;
                        try
                        {
                            paraTextSO.Load(shortName);
                            fIsEditable = (paraTextSO.Editable != 0);
                        }
                        catch
                        {
                            // Paratext settings file is probably bogus, so we regard it as editable (i.e., we can overwrite it).
                        }
                        if (fIsEditable)
                        {
                            cboShortName.Items.Add(shortName);
                        }
                        else
                        {
                            m_nonEditableP6Projects.Add(shortName);
                        }
                    }
                }

                // The following is an attempt to keep us from looking like idiots by making
                // the default project name a non-editable project.
                int i = 1;
                while (m_nonEditableP6Projects.Contains(m_shortName) && i < 1000)
                {
                    m_shortName = "MP" + i++;
                }
                i = 1;
                while (m_nonEditableP6Projects.Contains(m_BTshortName) && i < 1000)
                {
                    m_BTshortName = "BT" + i++;
                }
            }
            else
            {
                // Paratext is not installed or Paratext directory does not exist.
                // We default the output path to "C:\My Paratext Projects". However, this directory
                // might not exist and/or we might have no permissions to write there. We attempt to
                // create this folder now. If we fail, then we disable the Short Name control and
                // won't bother writing the Paratext settings files.
                m_paratextProjFolder = kDefaultParatextPath;
            }

            cboShortName.Text = ShortName;
            m_OutputFolder    = m_regGroup.GetStringValue("ParatextOutputSpec", m_paratextProjFolder);
            m_BTOutputFolder  = m_regGroup.GetStringValue("ParatextBTOutputSpec", m_paratextProjFolder);

            UpdateDisplay();
        }
Example #10
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Fill in the children for a particular book. This is typically done when it gets
        /// expanded or when we need a list including the children. Separating it from the
        /// initial load saves a lot of time when we have a long list of books.
        /// </summary>
        /// <param name="bookNode">The book node.</param>
        /// <returns><c>true</c> if the dummy node was replaced by real child node(s)</returns>
        /// <remarks>protected virtual for unit tests</remarks>
        /// ------------------------------------------------------------------------------------
        protected virtual bool FillInBookChildren(TreeNode bookNode)
        {
            var book       = bookNode.Tag as IScrBook;
            var bookNum    = book?.CanonicalNum ?? (int)bookNode.Tag;
            var owningForm = FindForm();

            while (owningForm != null && !owningForm.Visible)
            {
                owningForm = owningForm.Owner;
            }
            if (owningForm == null)
            {
                owningForm = Form.ActiveForm ?? Application.OpenForms[0];
            }

            if (m_associatedPtText != null)
            {
                // Update main text, if possible/needed.
                if (m_associatedPtText.BookPresent(bookNum))
                {
                    // PT has it.
                    // If we don't have it, OR if our copy is stale, then get updated copy.
                    if (book == null || !m_associatedPtText.IsCheckSumCurrent(bookNum, book.ImportedCheckSum))
                    {
                        // Get new/fresh version from PT.
                        var importedBook = ImportBook(owningForm, bookNum);
                        if (importedBook != null)
                        {
                            book         = importedBook;
                            bookNode.Tag = importedBook;
                        }
                    }
                }
                if (book == null)
                {
                    // No book, so don't fret about a back translation
                    return(false);
                }

                // Update back translation
                IScrText btProject = ParatextHelper.GetBtsForProject(m_associatedPtText).FirstOrDefault();
                if (btProject != null && btProject.BookPresent(book.CanonicalNum) && !btProject.IsCheckSumCurrent(book.CanonicalNum, book.ImportedBtCheckSum.get_String(book.Cache.DefaultAnalWs).Text))
                {
                    // The BT for this book node is out-of-date with the Paratext BT data
                    ImportBackTranslation(owningForm, bookNum, btProject);
                }
            }

            bookNode.Nodes.Clear();             // Gets rid of dummy.
            // Add Title node.
            if (book.TitleOA != null)
            {
                var titleNode = new TreeNode(ResourceHelper.GetResourceString("kstidScriptureTitle"))
                {
                    Name = book.TitleOA.ToString(),
                    Tag  = book.TitleOA
                };
                bookNode.Nodes.Add(titleNode);
            }

            // Add Sections.
            foreach (var section in book.SectionsOS)
            {
                var chapterVerseBridge = m_scr.ChapterVerseBridgeAsString(section);
                // Include the heading text if it's not empty.  See LT-8764.
                var cTotal = section.HeadingOA?.ParagraphsOS.Cast <IScrTxtPara>().Sum(para => para.Contents.Length);
                if (cTotal > 0)
                {
                    var sFmt = ResourceHelper.GetResourceString("kstidSectionHeading");
                    var node = new TreeNode(string.Format(sFmt, chapterVerseBridge))
                    {
                        Name = string.Format(sFmt, section),
                        Tag  = section.HeadingOA                        // expect an StText
                    };
                    bookNode.Nodes.Add(node);
                }
                var sectionNode = new TreeNode(chapterVerseBridge)
                {
                    Name = section.ToString(),
                    Tag  = section.ContentOA                    // expect an StText
                };
                bookNode.Nodes.Add(sectionNode);
            }

            // Add Footnotes in reverse order, so we can insert them in the proper order.
            var footnotes = new List <IScrFootnote>(book.FootnotesOS);

            footnotes.Reverse();
            foreach (var scrFootnote in footnotes)
            {
                // insert under the relevant section, if any (LTB-408)
                IScrSection containingSection;
                IStText     containingTitle = null;
                if (!scrFootnote.TryGetContainingSection(out containingSection) && !scrFootnote.TryGetContainingTitle(out containingTitle))
                {
                    continue;
                }
                var nodeName     = m_scr.ContainingRefAsString(scrFootnote);
                var footnoteNode = new TreeNode(nodeName)
                {
                    Tag  = scrFootnote,
                    Name = "Footnote"
                };

                // see if we can lookup the node of this section.
                var nodeIndex = bookNode.Nodes.IndexOfKey(containingSection?.ToString() ?? containingTitle.ToString());
                if (nodeIndex >= 0)
                {
                    bookNode.Nodes.Insert(nodeIndex + 1, footnoteNode);
                }
                else
                {
                    bookNode.Nodes.Add(footnoteNode);                           // insert at end.
                }
            }
            return(true);
        }
Example #11
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Handles the Load event of the ExportPtxDialog control.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event
        /// data.</param>
        /// ------------------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            // set up default short name
            m_shortName   = m_regGroup.GetStringValue(base.RegistrySettingType + "ShortName", null);
            m_BTshortName = m_regGroup.GetStringValue(base.RegistrySettingType + "BT" + "ShortName", null);
            if (string.IsNullOrEmpty(m_shortName) || string.IsNullOrEmpty(m_BTshortName))
            {
                foreach (IScrImportSet importSet in m_cache.LangProject.TranslatedScriptureOA.ImportSettingsOC)
                {
                    if (!string.IsNullOrEmpty(importSet.ParatextScrProj))
                    {
                        if (string.IsNullOrEmpty(m_shortName))
                        {
                            m_shortName = importSet.ParatextScrProj;
                        }
                        if (string.IsNullOrEmpty(m_BTshortName))
                        {
                            m_BTshortName = importSet.ParatextBTProj;
                        }
                        if (importSet.Name.UserDefaultWritingSystem.Text == ScriptureTags.kDefaultImportSettingsName)
                        {
                            break;
                        }
                    }
                }
            }
            if (m_shortName == null)
            {
                IWritingSystem wsVern = m_cache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem;
                string         abbr   = wsVern.Abbreviation;
                if (abbr != null && !abbr.Contains("***"))
                {
                    m_shortName = abbr.Trim();
                }
                else
                {
                    m_shortName = wsVern.Abbreviation.Trim();
                }
            }
            else
            {
                m_shortName = m_shortName.Trim();
            }

            // Paratext 6 requires short name to be between 3 and 5 characters in length.
            if (m_shortName.Length < 3)
            {
                m_shortName = m_shortName.PadRight(3, '_');
            }
            if (m_shortName.Length > 5)
            {
                m_shortName = m_shortName.Substring(0, 5);
            }

            if (string.IsNullOrEmpty(m_BTshortName))
            {
                m_BTshortName = m_shortName.Substring(0, 3) + "BT";
            }

            // Set values for what to export for one domain export (Paratext).
            switch (m_regGroup.GetIntValue("ParatextOneDomainExportWhat", 0))
            {
            case 0:
            default:
                // Temporarily load the BT settings, so when we "switch" to Scripture,
                // the BT settings will be saved in our internal object.
                LoadFileNameSchemeControl(base.RegistrySettingType + "BT", m_BTshortName);
                m_BTfileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                rdoScripture.Select();

                base.OnLoad(e);
                m_fileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                break;

            case 1:
                // Temporarily load the regular (vern) settings, so when we "switch" to
                // back translation, the vern settings will be saved in our internal object.
                LoadFileNameSchemeControl(base.RegistrySettingType, m_shortName);
                m_fileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                rdoBackTranslation.Select();

                base.OnLoad(e);
                m_BTfileNameScheme = fileNameSchemeCtrl.FileNameFormat;
                break;
            }

            // Get the output file or folder specification.
            try
            {
                m_paratextProjFolder = ScrTextCollection.SettingsDirectory;
            }
            catch
            {
                // Ignore: Paratext not installed
            }

            if (m_paratextProjFolder != null)
            {
                m_paratextProjFolder = m_paratextProjFolder.Trim(Path.DirectorySeparatorChar,
                                                                 Path.AltDirectorySeparatorChar);

                cboShortName.Items.AddRange(ParatextHelper.WritableShortNames.ToArray());

                // The following is an attempt to keep us from looking like idiots by making
                // the default project name a non-editable project.
                int i = 1;
                while (!ParatextHelper.IsProjectWritable(m_shortName) && i < 1000)
                {
                    m_shortName = "MP" + i++;
                }
                i = 1;
                while (!ParatextHelper.IsProjectWritable(m_BTshortName) && i < 1000)
                {
                    m_BTshortName = "BT" + i++;
                }
            }
            else
            {
                // Paratext is not installed or Paratext directory does not exist.
                // We default the output path to "C:\My Paratext Projects". However, this directory
                // might not exist and/or we might have no permissions to write there. We attempt to
                // create this folder now. If we fail, then we disable the Short Name control and
                // won't bother writing the Paratext settings files.
                // REVIEW: this comment seems to be out of date. We might crash if we have an
                // invalid directory (see FWNX-828).
                m_paratextProjFolder = ParatextHelper.ProjectsDirectory;
            }

            cboShortName.Text = ShortName;
            m_OutputFolder    = m_regGroup.GetStringValue("ParatextOutputSpec", m_paratextProjFolder);
            m_BTOutputFolder  = m_regGroup.GetStringValue("ParatextBTOutputSpec", m_paratextProjFolder);

            UpdateDisplay();
        }