Example #1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Adds a dummy project to the simulated Paratext collection.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void AddProject(string shortName, string associatedProject, string baseProject,
                               bool editable, bool isResource, string booksPresent, Utilities.Enum <Paratext.ProjectType> translationType)
        {
            ScrText scrText = new ScrText();

            scrText.Name = shortName;

            if (!string.IsNullOrEmpty(associatedProject))
            {
                scrText.AssociatedLexicalProject = new AssociatedLexicalProject(LexicalAppType.FieldWorks, associatedProject);
            }
            // Don't know how to implement a test involving baseProject now that BaseTranslation is gone from the PT API.
            // However all clients I can find so far pass null.
            if (!string.IsNullOrEmpty(baseProject))
            {
                //scrText.BaseTranslation = new BaseTranslation(derivedTranslationType, baseProject, string.Empty);
                var baseProj = Projects.Select(x => x.Name == baseProject).FirstOrDefault();
                Assert.That(baseProj, Is.Not.Null);
                scrText.TranslationInfo = new TranslationInformation(translationType, baseProject, string.Empty);
                Assert.That(scrText.TranslationInfo.BaseProjectName, Is.EqualTo(baseProject));
            }
            else
            {
                scrText.TranslationInfo = new TranslationInformation(translationType);
            }

            scrText.Editable = editable;
            scrText.SetParameterValue("ResourceText", isResource ? "T" : "F");
            if (booksPresent != null)
            {
                scrText.BooksPresent = booksPresent;
            }

            Projects.Add(new PT7ScrTextWrapper(scrText));
        }
Example #2
0
        public void AddProject(string shortName, string associatedProject, string baseProject,
                               bool editable, bool isResource, string booksPresent, DerivedTranslationType derivedTranslationType)
        {
            ScrText scrText = new ScrText();

            scrText.Name = shortName;

            if (!string.IsNullOrEmpty(associatedProject))
            {
                scrText.AssociatedLexicalProject = new AssociatedLexicalProject(LexicalAppType.FieldWorks, associatedProject);
            }
            if (!string.IsNullOrEmpty(baseProject))
            {
                scrText.BaseTranslation = new BaseTranslation(derivedTranslationType, baseProject, string.Empty);
            }

            scrText.Editable = editable;
            scrText.SetParameterValue("ResourceText", isResource ? "T" : "F");
            if (booksPresent != null)
            {
                scrText.BooksPresent = booksPresent;
            }

            Projects.Add(scrText);
        }
Example #3
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Load the Paratext project and enumerator, preparing us to read the data files.
        /// </summary>
        /// <param name="paratextProjectId">3-letter Paratext project ID</param>
        /// <returns>true if the project was loaded, else false</returns>
        /// ------------------------------------------------------------------------------------
        protected virtual void LoadParatextProject(string paratextProjectId)
        {
            try
            {
                m_ptProjectText = new ScrText(paratextProjectId);
            }
            catch (Exception e)
            {
                // Can't load Paratext project if Paratext is not installed.
                throw new ParatextLoadException(
                          TeResourceHelper.GetResourceString("kstidCheckParatextInstallation"), e);
            }

            try
            {
                // create ref objs of the Paratext lib
                Logger.WriteEvent("Loading Paratext project " + paratextProjectId + " to import from " +
                                  m_settings.StartRef.AsString + " to " + m_settings.EndRef.AsString);

                // Now initialize the TextEnum with the range of Scripture text we want
                m_ptParser   = m_ptProjectText.Parser();
                m_ptCurrBook = new VerseRef(m_settings.StartRef.Book, 0, 0);
                ResetParatextState();
            }
            catch (Exception e)
            {
                string msg = string.Format(
                    TeResourceHelper.GetResourceString("kstidParatextProjectLoadFailure"),
                    paratextProjectId);
                throw new ParatextLoadException(msg, e);
            }
        }
Example #4
0
 /// --------------------------------------------------------------------------------
 /// <summary>
 /// Reloads the specified Paratext project with the latest data.
 /// </summary>
 /// --------------------------------------------------------------------------------
 public void ReloadProject(ScrText project)
 {
     if (project != null)
     {
         project.Reload();
     }
 }
        /// ------------------------------------------------------------------------------------
        /// <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);
        }
Example #6
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the Paratext project, if any, that is associated with the specified FieldWorks
        /// project.
        /// </summary>
        /// <returns>The associated project, or null if there is none.</returns>
        /// ------------------------------------------------------------------------------------
        public static ScrText GetAssociatedProject(IProjectIdentifier projectId)
        {
            ScrText assocProj = s_ptHelper.GetProjects().FirstOrDefault(scrText =>
                                                                        scrText.AssociatedLexicalProject.ToString() == projectId.PipeHandle);

            s_ptHelper.ReloadProject(assocProj);
            return(assocProj);
        }
Example #7
0
 private static void DoRead(ScrText scr, VerseRef vref, string file)
 {
     string text = scr.GetText(vref, vref.ChapterNum != 0, false);
     using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
     {
         writer.Write(text);
     }
 }
Example #8
0
 /// <summary>
 /// For unit tests only. FLEx is not responsible for disposing of IScrText objects received from ParaText
 /// </summary>
 internal void DisposePTObject()
 {
     if (pt8Object != null)
     {
         pt8Object.Dispose();
     }
     pt8Object = null;
 }
 public ParatextProjectProxy(ScrText scrText)
 {
     ScrText                  = scrText;
     Language                 = new DblMetadataLanguage();
     Language.Iso             = scrText.Settings.LanguageID.Id;
     Language.Name            = scrText.DisplayLanguageName;
     Language.Script          = scrText.Language.FontName;
     Language.ScriptDirection = scrText.RightToLeft ? "RTL" : "LTR";
 }
Example #10
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Gets any back translations of the specified base project.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 public static IEnumerable <ScrText> GetBtsForProject(ScrText baseProj)
 {
     // We're looking for projects that are back translations of baseProj. That means they have type
     // back translation, and their base project is the one we want.
     // Seems that baseProj.Equals(proj.BaseScrText) should work, but it doesn't, at least in one unit test,
     // possibly just because the mock is not simulating the real helper well enough.
     return(s_ptHelper.GetProjects().Where(proj => baseProj.Name.Equals(proj.TranslationInfo.BaseProjectName) &&
                                           proj.TranslationInfo.Type == ProjectType.BackTranslation));
 }
Example #11
0
        /// <summary> Get list of book numbers in PT project. </summary>
        public IReadOnlyList <int> GetBookList(UserSecret userSecret, string ptProjectId)
        {
            ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), ptProjectId);

            if (scrText == null)
            {
                return(Array.Empty <int>());
            }
            return(scrText.Settings.BooksPresentSet.SelectedBookNumbers.ToArray());
        }
Example #12
0
        public void GetAssociatedProject()
        {
            m_ptHelper.AddProject("MNKY", "Soup");
            m_ptHelper.AddProject("SOUP", "Monkey Soup");
            m_ptHelper.AddProject("GRK", "Levington");
            m_ptHelper.AddProject("Mony", "Money");
            ScrText found = ParatextHelper.GetAssociatedProject(new TestProjectId(FDOBackendProviderType.kXML, "Monkey Soup"));

            Assert.AreEqual("SOUP", found.Name);
        }
Example #13
0
        /// <summary> Get PT book text in USX, or throw if can't. </summary>
        public string GetBookText(UserSecret userSecret, string ptProjectId, int bookNum)
        {
            ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), ptProjectId);

            if (scrText == null)
            {
                throw new DataNotFoundException("Can't get access to cloned project.");
            }
            string usfm = scrText.GetText(bookNum);

            return(UsfmToUsx.ConvertToXmlString(scrText, bookNum, usfm, false));
        }
Example #14
0
        private static void DoWrite(ScrText scr, VerseRef vref, string file)
        {
            string text;
            using (StreamReader reader = new StreamReader(file, Encoding.UTF8))
            {
                text = reader.ReadToEnd();
            }

            string chapter = (vref.Chapter == "0") ? null : vref.Chapter;

            scr.PutText(vref.Book, chapter, false, text, null);
        }
        /// <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;
                ScrText 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 <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;
                }
                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 #16
0
        private void UpdateRightList()
        {
            // Save selected value
            ScrText scrText = uiRightList.SelectedItem as ScrText;

            uiRightList.BeginUpdate();
            uiRightList.Items.Clear();
            foreach (ScrText item in rightItems)
            {
                uiRightList.Items.Add(item);
            }
            uiRightList.EndUpdate();

            uiRightList.SelectedIndex = rightItems.IndexOf(scrText);
        }
Example #17
0
 /// <summary/>
 protected virtual void Dispose(bool fDisposing)
 {
     System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******");
     if (fDisposing && !IsDisposed)
     {
         // dispose managed and unmanaged objects
         Cleanup();
         if (m_ptProjectText != null)
         {
             m_ptProjectText.Dispose();
         }
     }
     m_ptProjectText = null;
     IsDisposed      = true;
 }
Example #18
0
        /// <summary> Get notes from the Paratext project folder. </summary>
        public string GetNotes(UserSecret userSecret, string projectId, int bookNum)
        {
            // TODO: should return some data structure instead of XML
            ScrText scrText = ScrTextCollection.FindById(GetParatextUsername(userSecret), projectId);

            if (scrText == null)
            {
                return(null);
            }

            CommentManager manager = CommentManager.Get(scrText);
            var            threads = manager.FindThreads((commentThread) => { return(commentThread.VerseRef.BookNum == bookNum); },
                                                         true);

            return(NotesFormatter.FormatNotes(threads));
        }
        public ParatextScrTextWrapper(ScrText underlyingText, bool ignoreQuotationProblemsIfRulesAreNotSet = false)
        {
            UnderlyingScrText = underlyingText;

            if (ignoreQuotationProblemsIfRulesAreNotSet && !HasQuotationRulesSet)
            {
                IgnoreQuotationsProblems();
            }
            else
            {
                GetUpdatedBookInfo();
            }
            if (m_bookInfo.SupportedBookCount == 0)
            {
                throw new NoSupportedBooksException(ProjectId, m_bookInfo);
            }
        }
Example #20
0
        private void LoadSavedSelectionItem_Click(object sender, EventArgs e)
        {
            SavedScrTextList savedList =
                (sender as ToolStripMenuItem).Tag as SavedScrTextList;

            rightItems = new List <ScrText>();
            foreach (string scrTextName in savedList.ScrTextNames)
            {
                ScrText scrText = ScrTextCollection.Get(scrTextName);
                if (scrText != null)
                {
                    rightItems.Add(scrText);
                }
            }
            UpdateRightList();
            UpdateSavedSelectionLinks();
        }
Example #21
0
        static void Main(string[] args)
        {
            if (args.Length != 5)
            {
                Console.WriteLine("Usage: rdwrtp7 -r|-w project book chapter|0 fileName");
                Environment.Exit(-1);
            }

            ScrTextCollection.Initialize();

            string operation = args[0];
            string project = args[1];
            string book = args[2];
            string chapter = args[3];
            string file = args[4];

            ScrText scr = ScrTextCollection.Get(project);
            if (scr == null)
            {
                Console.WriteLine("Error: unknown project");
                Environment.Exit(-1);
            }

            VerifyBook(book);
            VerifyChapter(chapter);

            VerseRef vref = new VerseRef(book, chapter, "1", scr.Versification);

            try
            {
                if (operation == "-r")
                    DoRead(scr, vref, file);
                else if (operation == "-w")
                    DoWrite(scr, vref, file);
                else
                {
                    Console.WriteLine("Error: unknown operation");
                    Environment.Exit(-1);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Environment.Exit(-1);
            }
        }
Example #22
0
        /// <summary>
        /// Get a scripture text for a given user for a Paratext project with the target project ID and type.
        /// </summary>
        /// <param name="ptUsername">The username of the user retrieving the ScrText.</param>
        /// <param name="projectId">The ID of the target project.</param>
        /// <returns>
        /// The scripture text.
        /// </returns>
        public ScrText?FindById(string ptUsername, string projectId)
        {
            if (projectId == null)
            {
                return(null);
            }

            string baseProjectPath = Path.Combine(SettingsDirectory, projectId);

            if (!FileSystemService.DirectoryExists(baseProjectPath))
            {
                return(null);
            }

            string fullProjectPath = Path.Combine(baseProjectPath, "source");
            string settingsFile    = Path.Combine(fullProjectPath, ProjectSettings.fileName);

            if (!FileSystemService.FileExists(settingsFile))
            {
                // If this is an older project (most likely a resource), there will be an SSF file
                settingsFile = FileSystemService.EnumerateFiles(fullProjectPath, "*.ssf").FirstOrDefault();

                // We couldn't find the xml or ssf file
                if (settingsFile == null)
                {
                    return(null);
                }
            }

            string?name = GetNameFromSettings(settingsFile);

            if (name != null)
            {
                ScrText scrText = CreateScrText(ptUsername, new ProjectName()
                {
                    ProjectPath = fullProjectPath,
                    ShortName   = name
                });

                // Return the object
                return(scrText);
            }

            return(null);
        }
Example #23
0
        public void FindById_TargetProjectExists_ReturnsProject()
        {
            string projectId       = "Project01";
            string username        = "******";
            string projectTextName = "Proj01";
            string path            = Path.Combine(_testDirectory, projectId, "target");
            string content         = $"<ScriptureText><Name>{projectTextName}</Name><guid>{projectId}</guid></ScriptureText>";

            _fileSystemService.FileReadText(Arg.Any <string>()).Returns(content);
            _fileSystemService.FileExists(Arg.Any <string>()).Returns(true);

            ScrText scrText = _lazyScrTextCollection.FindById(username, projectId);

            Assert.NotNull(scrText);
            Assert.AreEqual(projectTextName, scrText.Name);
            Assert.AreEqual(path, scrText.Directory);
            _fileSystemService.Received(1).FileExists(Path.Combine(path, ProjectSettings.fileName));
        }
Example #24
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Returns whether or not the project with the specified short name is abe to be
        /// written. Written being defined as editable and not a resource.
        /// </summary>
        /// <remarks>Returns true if the spcified project could not be found.</remarks>
        /// ------------------------------------------------------------------------------------
        private static bool IsProjectWritable(string projShortName, bool fPerformRefresh)
        {
            if (ScrTextCollection.SLTTexts.Contains(projShortName.ToLowerInvariant()))
            {
                return(false);
            }

            if (fPerformRefresh)
            {
                s_ptHelper.RefreshProjects();
            }

            ScrText existingProj = s_ptHelper.GetProjects().FirstOrDefault(
                x => x.Name.Equals(projShortName, StringComparison.InvariantCultureIgnoreCase));

            return(existingProj == null || (string.IsNullOrEmpty(existingProj.AssociatedLexicalProject.ProjectId) &&
                                            existingProj.Editable && !existingProj.IsResourceText));
        }
Example #25
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Returns a list of book IDs that exist for the given Paratext project.
        /// </summary>
        /// <returns>A List of integers representing 1-based canonical book numbers that exist
        /// in the given Paratext project</returns>
        /// <remark>The returned list will be empty if there is a problem with the Paratext
        /// installation or the specified project could not be found.</remark>
        /// ------------------------------------------------------------------------------------
        public static IEnumerable <int> GetProjectBooks(string projShortName)
        {
            try
            {
                ScrText foundText = s_ptHelper.GetProjects().FirstOrDefault(p => p.Name == projShortName);
                // Make sure we don't add books outside of our valid range
                if (foundText != null)
                {
                    return(foundText.BooksPresentSet.SelectedBookNumbers.Where(book => book <= BCVRef.LastBook));
                }
            }
            catch (Exception e)
            {
                Logger.WriteError(e);
                // ignore error - probably Paratext installation problem. Caller can check number of books present.
            }

            return(new int[0]);
        }
Example #26
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 #27
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Handles the SelectedIndexChanged event of the cboShortName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        /// ------------------------------------------------------------------------------------
        protected void cboShortName_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (!m_fUserModifiedFolder && cboShortName.SelectedIndex >= 0)
            {
                try
                {
                    using (ScrText paraTextSO = new ScrText(ShortName))
                    {
                        string folder = paraTextSO.Directory;
                        m_fAppendShortNameToFolder = (folder.EndsWith(Path.DirectorySeparatorChar + ShortName));
                        BaseOutputFolder           = folder;
                        m_fUserModifiedFolder      = false;
                        CalculateDisplayOutputFolder();

                        FileNameFormat currentFileNameScheme = ExportScriptureDomain ? m_fileNameScheme :
                                                               m_BTfileNameScheme;
                        currentFileNameScheme.m_filePrefix   = paraTextSO.FileNamePrePart;
                        currentFileNameScheme.m_schemeFormat =
                            FileNameFormat.GetSchemeFormatFromParatextForm(paraTextSO.FileNameForm);
                        m_fileNameScheme.m_fileSuffix = Path.GetFileNameWithoutExtension(paraTextSO.FileNamePostPart);
                        //if (ExportScriptureDomain)
                        //    m_BTfileNameScheme.m_fileSuffix = m_fileNameScheme.m_fileSuffix.Substring(0, 3) + "BT";
                        currentFileNameScheme.m_fileExtension = Path.GetExtension(paraTextSO.FileNamePostPart);

                        // set file name scheme control with properties that check the export domain.
                        fileNameSchemeCtrl.ClearUserModifiedNameScheme();
                        fileNameSchemeCtrl.Prefix    = FileNamePrefix;
                        fileNameSchemeCtrl.Scheme    = FileNameScheme;
                        fileNameSchemeCtrl.Suffix    = FileNameSuffix;
                        fileNameSchemeCtrl.Extension = FileNameExtension;
                    }
                }
                catch
                {
                    // Ignore Paratext Load errors. Project will be overwritten.
                }
            }
        }
Example #28
0
		private void SelectTexts()
		{
			// Create list of current items
			List<ScrText> currentItems = new List<ScrText>();
			foreach (TextCollectionItem item in m_textCollection.Items)
				currentItems.Add(item.ScrText);
			TextCollectionItem currentItem = null;
			if (m_textCollection.CurItem >= 0 && m_textCollection.CurItem < m_textCollection.Items.Count)
				currentItem = m_textCollection.Items[m_textCollection.CurItem];

			// Re-initialize, just in case.
			// We pass the directory (rather than passing no arguments, and letting the paratext dll figure
			// it out) because the figuring out goes wrong on Linux, where both programs are simulating
			// the registry.
			ScrTextCollection.Initialize(ParatextHelper.ProjectsDirectory, false);
			List<string> textNames = ScrTextCollection.ScrTextNames;

			foreach (string nameVar in textNames)
			{
				if (nameVar.Length < 1)
					continue;

				string name = nameVar.ToLower();

				// Ignore P6 source language texts.
				if (name == "lxx" || name == "grk" || name == "heb")
					continue;

				try
				{
					if (ScrTextCollection.Get(nameVar) == null)
					{
						// REVIEW: I'm not sure how/if ScrTextCollection gets disposed
						ScrText scrText = new ScrText(nameVar);
						ScrTextCollection.Add(scrText);
					}
				}
				catch (Exception)
				{
					//MessageBox.Show(name + ": " + exception.Message);
					// TODO What will happen if a text can't be loaded?
				}
			}

			// the two booleans indicate we want all the available texts, including resources (part of the Paratext distribution)
			// and non-scriptural materials (things like commentaries maybe?)
			using (ScrTextListSelectionForm selForm = new ScrTextListSelectionForm(
				ScrTextCollection.ScrTexts(true, true), currentItems))
			{
				if (selForm.ShowDialog(this) == DialogResult.OK)
				{
					// Create new list of items, keeping data from old one (to preserve zoom etc)
					List<TextCollectionItem> newItems = new List<TextCollectionItem>();
					foreach (ScrText scrText in selForm.Selections)
					{
						// Attempt to find in old list
						bool found = false;
						foreach (TextCollectionItem item in m_textCollection.Items)
						{
							if (item.ScrText == scrText)
							{
								newItems.Add(item);
								found = true;
								break;
							}
						}
						if (!found)
							newItems.Add(new TextCollectionItem(scrText, 1));
					}
					m_textCollection.Items = newItems;
					int curItemIndex = -1; // none selected
					for (int i = 0; i < newItems.Count; i++)
					{
						if (newItems[i] == currentItem)
						{
							curItemIndex = i;
							break;
						}
					}
					// select some current item if possible; out of range does not cause problem.
					// Currently it seems to cause a crash if the item is out of range for the OLD items;
					// I think this is a bug in the Paratext code.
					if (curItemIndex == -1 && m_textCollection.Items.Count > 0 && currentItems.Count > 0)
						curItemIndex = 0;
					m_textCollection.CurItem = curItemIndex;

					tryReloadTextCollection();
				}
			}
		}
Example #29
0
        private void SelectTexts()
        {
            // Create list of current items
            List <ScrText> currentItems = new List <ScrText>();

            foreach (TextCollectionItem item in m_textCollection.Items)
            {
                currentItems.Add(item.ScrText);
            }
            TextCollectionItem currentItem = null;

            if (m_textCollection.CurItem >= 0 && m_textCollection.CurItem < m_textCollection.Items.Count)
            {
                currentItem = m_textCollection.Items[m_textCollection.CurItem];
            }

            // Re-initialize, just in case.
            // We pass the directory (rather than passing no arguments, and letting the paratext dll figure
            // it out) because the figuring out goes wrong on Linux, where both programs are simulating
            // the registry.
            ScrTextCollection.Initialize(ParatextHelper.ProjectsDirectory, false);
            List <string> textNames = ScrTextCollection.ScrTextNames;

            foreach (string nameVar in textNames)
            {
                if (nameVar.Length < 1)
                {
                    continue;
                }

                string name = nameVar.ToLower();

                // Ignore P6 source language texts.
                if (name == "lxx" || name == "grk" || name == "heb")
                {
                    continue;
                }

                try
                {
                    if (ScrTextCollection.Get(nameVar) == null)
                    {
                        // REVIEW: I'm not sure how/if ScrTextCollection gets disposed
                        ScrText scrText = new ScrText(nameVar);
                        ScrTextCollection.Add(scrText);
                    }
                }
                catch (Exception)
                {
                    //MessageBox.Show(name + ": " + exception.Message);
                    // TODO What will happen if a text can't be loaded?
                }
            }

            // the two booleans indicate we want all the available texts, including resources (part of the Paratext distribution)
            // and non-scriptural materials (things like commentaries maybe?)
            using (ScrTextListSelectionForm selForm = new ScrTextListSelectionForm(
                       ScrTextCollection.ScrTexts(true, true), currentItems))
            {
                if (selForm.ShowDialog(this) == DialogResult.OK)
                {
                    // Create new list of items, keeping data from old one (to preserve zoom etc)
                    List <TextCollectionItem> newItems = new List <TextCollectionItem>();
                    foreach (ScrText scrText in selForm.Selections)
                    {
                        // Attempt to find in old list
                        bool found = false;
                        foreach (TextCollectionItem item in m_textCollection.Items)
                        {
                            if (item.ScrText == scrText)
                            {
                                newItems.Add(item);
                                found = true;
                                break;
                            }
                        }
                        if (!found)
                        {
                            newItems.Add(new TextCollectionItem(scrText, 1));
                        }
                    }
                    m_textCollection.Items = newItems;
                    int curItemIndex = -1;                     // none selected
                    for (int i = 0; i < newItems.Count; i++)
                    {
                        if (newItems[i] == currentItem)
                        {
                            curItemIndex = i;
                            break;
                        }
                    }
                    // select some current item if possible; out of range does not cause problem.
                    // Currently it seems to cause a crash if the item is out of range for the OLD items;
                    // I think this is a bug in the Paratext code.
                    if (curItemIndex == -1 && m_textCollection.Items.Count > 0 && currentItems.Count > 0)
                    {
                        curItemIndex = 0;
                    }
                    m_textCollection.CurItem = curItemIndex;

                    tryReloadTextCollection();
                }
            }
        }
Example #30
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Restore settings (currently the list of texts displayed).
        /// </summary>
        /// <param name="key">The key.</param>
        /// ------------------------------------------------------------------------------------
        public void LoadSettings(RegistryKey key)
        {
            try
            {
                m_floaty.LoadSettings(key);

                string texts = key.GetValue("UsfmTexts", "") as string;
                if (string.IsNullOrEmpty(texts))
                {
                    return;                     // foreach below does one iteration for empty string, which is bad.
                }
                List <TextCollectionItem> items = new List <TextCollectionItem>();
                foreach (string name in texts.Split(','))
                {
                    ScrText text = null;
                    try
                    {
                        foreach (ScrText st in ScrTextCollection.ScrTexts(true, true))
                        {
                            if (st.Name == name)
                            {
                                text = st;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // If we for some reason can't make that text, carry on with the others.
                        continue;
                    }
                    if (text == null)
                    {
                        continue;                         // forget any saved item that is no longer an option.
                    }
                    items.Add(new TextCollectionItem(text, 1.0));
                }
                m_textCollection.Items = items;
                string curItemName = key.GetValue("UsfmCurItem", "") as string;
                if (string.IsNullOrEmpty(curItemName))
                {
                    for (int i = 0; i < m_textCollection.Items.Count; i++)
                    {
                        if (m_textCollection.Items[i].ScrText.Name == curItemName)
                        {
                            m_textCollection.CurItem = i;
                            break;
                        }
                    }
                }

                // Paratext now requires a versification for Reload(),
                // so we'll default to English at this point.
                m_textCollection.Reference = new VerseRef("MAT 1:1", ScrVers.English);
                tryReloadTextCollection();

                VerseRef vr        = new VerseRef("MAT 1:1");          // default
                string   reference = key.GetValue("UsfmCurRef", null) as string;
                if (!string.IsNullOrEmpty(reference))
                {
                    vr = new VerseRef(reference);
                }
                m_textCollection.CurItem = (int)key.GetValue("UsfmCurSel", -1);
                SetScriptureReference(vr);
            }
            catch
            {
                // ignore any problems.
            }
        }
Example #31
0
		/// <summary/>
		protected virtual void Dispose(bool fDisposing)
		{
			System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******");
			if (fDisposing && !IsDisposed)
			{
				// dispose managed and unmanaged objects
				Cleanup();
				if (m_ptProjectText != null)
					m_ptProjectText.Dispose();
			}
			m_ptProjectText = null;
			IsDisposed = true;
		}
Example #32
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Load the Paratext project and enumerator, preparing us to read the data files.
		/// </summary>
		/// <param name="paratextProjectId">3-letter Paratext project ID</param>
		/// <returns>true if the project was loaded, else false</returns>
		/// ------------------------------------------------------------------------------------
		protected virtual void LoadParatextProject(string paratextProjectId)
		{
			try
			{
				m_ptProjectText = new ScrText(paratextProjectId);
			}
			catch (Exception e)
			{
				// Can't load Paratext project if Paratext is not installed.
				throw new ParatextLoadException(
					TeResourceHelper.GetResourceString("kstidCheckParatextInstallation"), e);
			}

			try
			{
				// create ref objs of the Paratext lib
				Logger.WriteEvent("Loading Paratext project " + paratextProjectId + " to import from " +
					m_settings.StartRef.AsString + " to " + m_settings.EndRef.AsString);

				// Now initialize the TextEnum with the range of Scripture text we want
				m_ptParser = m_ptProjectText.Parser;
				m_ptCurrBook = new VerseRef(m_settings.StartRef.Book, 0, 0);
				ResetParatextState();
			}
			catch (Exception e)
			{
				string msg = string.Format(
					TeResourceHelper.GetResourceString("kstidParatextProjectLoadFailure"),
					paratextProjectId);
				throw new ParatextLoadException(msg, e);
			}
		}
 protected override UnsupportedReason MigrateProjectIfNeeded(ScrText scrText)
 {
     throw new NotImplementedException("This method should not be used in SF context.");
 }
Example #34
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles the SelectedIndexChanged event of the cboShortName control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
		/// ------------------------------------------------------------------------------------
		protected void cboShortName_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (!m_fUserModifiedFolder && cboShortName.SelectedIndex >= 0)
			{
				try
				{
					using (ScrText paraTextSO = new ScrText(ShortName))
					{
						string folder = paraTextSO.Directory;
						m_fAppendShortNameToFolder = (folder.EndsWith(Path.DirectorySeparatorChar + ShortName));
						BaseOutputFolder = folder;
						m_fUserModifiedFolder = false;
						CalculateDisplayOutputFolder();

						FileNameFormat currentFileNameScheme = ExportScriptureDomain ? m_fileNameScheme :
						m_BTfileNameScheme;
						currentFileNameScheme.m_filePrefix = paraTextSO.FileNamePrePart;
						currentFileNameScheme.m_schemeFormat =
						FileNameFormat.GetSchemeFormatFromParatextForm(paraTextSO.FileNameForm);
						m_fileNameScheme.m_fileSuffix = Path.GetFileNameWithoutExtension(paraTextSO.FileNamePostPart);
						//if (ExportScriptureDomain)
						//    m_BTfileNameScheme.m_fileSuffix = m_fileNameScheme.m_fileSuffix.Substring(0, 3) + "BT";
						currentFileNameScheme.m_fileExtension = Path.GetExtension(paraTextSO.FileNamePostPart);

						// set file name scheme control with properties that check the export domain.
						fileNameSchemeCtrl.ClearUserModifiedNameScheme();
						fileNameSchemeCtrl.Prefix = FileNamePrefix;
						fileNameSchemeCtrl.Scheme = FileNameScheme;
						fileNameSchemeCtrl.Suffix = FileNameSuffix;
						fileNameSchemeCtrl.Extension = FileNameExtension;
					}
				}
				catch
				{
					// Ignore Paratext Load errors. Project will be overwritten.
				}
			}
		}
Example #35
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets any back translations of the specified base project.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public static IEnumerable<ScrText> GetBtsForProject(ScrText baseProj)
		{
			// We're looking for projects that are back translations of baseProj. That means they have type
			// back translation, and their base project is the one we want.
			// Seems that baseProj.Equals(proj.BaseScrText) should work, but it doesn't, at least in one unit test,
			// possibly just because the mock is not simulating the real helper well enough.
			return s_ptHelper.GetProjects().Where(proj => baseProj.Name.Equals(proj.TranslationInfo.BaseProjectName) &&
													proj.TranslationInfo.Type == ProjectType.BackTranslation);
		}
Example #36
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Method adapted from TextCollectionControl method of same name, to use our dialog.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void SelectTexts()
		{
			// Create list of current items
			List<ScrText> currentItems = new List<ScrText>();
			foreach (TextCollectionItem item in m_textCollection.Items)
				currentItems.Add(item.ScrText);
			TextCollectionItem currentItem = null;
			if (m_textCollection.CurItem >= 0 && m_textCollection.CurItem < m_textCollection.Items.Count)
				currentItem = m_textCollection.Items[m_textCollection.CurItem];

			ScrTextCollection.Initialize(); // Re-initialize, just in case
			List<string> textNames = ScrTextCollection.ScrTextNames;

			foreach (string nameVar in textNames)
			{
				if (nameVar.Length < 1)
					continue;

				string name = nameVar.ToLower();

				// Ignore P6 source language texts.
				if (name == "lxx" || name == "grk" || name == "heb")
					continue;

				try
				{
					if (ScrTextCollection.Get(nameVar) == null)
					{
						ScrText scrText = new ScrText(nameVar);
						ScrTextCollection.Add(scrText);
					}
				}
				catch (Exception)
				{
					//MessageBox.Show(name + ": " + exception.Message);
					// TODO What will happen if a text can't be loaded?
				}
			}


			ScrTextListSelectionForm selForm = new ScrTextListSelectionForm(
				ScrTextCollection.ScrTexts, currentItems);
			if (selForm.ShowDialog(this) == DialogResult.OK)
			{
				// Create new list of items, keeping data from old one (to preserve zoom etc)
				List<TextCollectionItem> newItems = new List<TextCollectionItem>();
				foreach (ScrText scrText in selForm.Selections)
				{
					// Attempt to find in old list
					bool found = false;
					foreach (TextCollectionItem item in m_textCollection.Items)
					{
						if (item.ScrText == scrText)
						{
							newItems.Add(item);
							found = true;
							break;
						}
					}
					if (!found)
						newItems.Add(new TextCollectionItem(scrText, 1));
				}
				m_textCollection.Items = newItems;
				int curItemIndex = -1; // none selected
				for (int i = 0; i < newItems.Count; i++)
				{
					if (newItems[i] == currentItem)
					{
						curItemIndex = i;
						break;
					}
				}
				// select some current item if possible; out of range does not cause problem.
				// Currently it seems to cause a crash if the item is out of range for the OLD items;
				// I think this is a bug in the Paratext code.
				if (curItemIndex == -1 && m_textCollection.Items.Count > 0 && currentItems.Count > 0)
					curItemIndex = 0;
				m_textCollection.CurItem = curItemIndex;

				tryReloadTextCollection();
			}
		}
Example #37
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes the <see cref="ImportWizard"/> class.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		static ImportWizard()
		{
			s_noneProject = new ScrText();
			s_noneProject.Name = ScrImportComponents.kstidImportWizNoProjType;
		}
Example #38
0
			/// --------------------------------------------------------------------------------
			/// <summary>
			/// Reloads the specified Paratext project with the latest data.
			/// </summary>
			/// --------------------------------------------------------------------------------
			public void ReloadProject(ScrText project)
			{
				if (project != null)
					project.Reload();
			}