/// ------------------------------------------------------------------------------------ /// <summary> /// Initializes a new instance of the <see cref="T:TeScrNoteCategoriesInit"/> class. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="scr">The scripture object.</param> /// <param name="categories">The categories.</param> /// ------------------------------------------------------------------------------------ protected TeScrNoteCategoriesInit(IAdvInd4 progressDlg, IScripture scr, XmlNode categories) { m_scr = scr; m_progressDlg = progressDlg; m_categories = categories; m_userLocale = scr.Cache.LanguageWritingSystemFactoryAccessor.GetStrFromWs(scr.Cache.DefaultUserWs); m_fallbackUserLocale = scr.Cache.FallbackUserLocale; }
private void m_btnMerge_Click(object sender, EventArgs e) { using (new SIL.FieldWorks.Common.Utils.WaitCursor(this)) { using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this)) { progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous; m_progressDlg = progressDlg as IAdvInd4; try { progressDlg.Title = "Chorus Merge Process"; // 1. export lexicon string outPath = Path.GetTempFileName(); outPath = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportLexicon), outPath); if (outPath == null) { // TODO: some sort of error report? return; } // 2. merge via chorus string inPath = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ChorusMerge), outPath); if (inPath == null) { // TODO: some sort of error report? return; } // 3. re-import lexicon, overwriting current contents. string logFile = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ImportLexicon), inPath); if (logFile == null) { // TODO: some sort of error report? return; } else { } } catch { } finally { } } } DialogResult = DialogResult.OK; Close(); }
private object ExportLift(IAdvInd4 progressDialog, params object[] parameters) { Debug.Assert(parameters.Length == 1); string p = Path.Combine(SIL.FieldWorks.Common.Utils.DirectoryFinder.FWCodeDirectory, @"Language Explorer\Export Templates"); Debug.Assert(Directory.Exists(p)); string fxtPath = Path.Combine(p, "LIFT.fxt.xml"); using (TextWriter w = new StreamWriter((string)parameters[0])) { m_dumper.Go(m_cache.LangProject as CmObject, fxtPath, w); } return(null); }
/// <summary> /// Do the modifications/merging/whatever to the LIFT file given by the first (and only) /// parameter. /// </summary> /// <returns>the name of the modified file (may be the same as the input), or null if an error occurs.</returns> protected object ChorusMerge(IAdvInd4 progressDialog, params object[] parameters) { // TODO: implement this! if (m_progressDlg == null) { m_progressDlg = progressDialog; } progressDialog.Message = "Merging via Chorus"; progressDialog.SetRange(0, 100); progressDialog.Position = 0; string outPath = parameters[0].ToString(); progressDialog.Position = 100; return(outPath); }
/// ------------------------------------------------------------------------------------ /// <summary> /// If <paramref name="progressDlg"/> is not <c>null</c> we run the background task /// with that progress dialog (without creating a separate thread). Otherwise we display /// a new progress dialog as a modal dialog and start the background task in a separate /// thread. /// </summary> /// <param name="progressDlg">The existing progress dialog, or <c>null</c>.</param> /// <param name="fDisplayUi">set to <c>true</c> to display the progress dialog, /// <c>false</c> to run without UI.</param> /// <param name="backgroundTask">The background task.</param> /// <param name="parameters">The paramters that will be passed to the background task</param> /// <returns>The return value from the background thread.</returns> /// ------------------------------------------------------------------------------------ public object RunTask(IAdvInd4 progressDlg, bool fDisplayUi, BackgroundTaskInvoker backgroundTask, params object[] parameters) { if (progressDlg != null) { int nMin; int nMax = 0; progressDlg.GetRange(out nMin, out nMax); progressDlg.Position = nMin; object ret = backgroundTask(progressDlg, parameters); progressDlg.SetRange(nMin, nMax); progressDlg.Position = nMax; return(ret); } return(RunTask(fDisplayUi, backgroundTask, parameters)); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Performs any needed tasks to ensure that the project is valid and has any objects /// required by this version of the application. /// </summary> /// <param name="cache"></param> /// <param name="existingProgressDlg">The existing progress dialog, if any.</param> /// ------------------------------------------------------------------------------------ public static void EnsureProjectValid(FdoCache cache, IAdvInd4 existingProgressDlg) { TeScrInitializer scrInitializer = new TeScrInitializer(cache); scrInitializer.RemoveRtlMarksFromScrProperties(); scrInitializer.EnsureScriptureTextsValid(); List <string> issuesToReport = scrInitializer.FixOrcsWithoutProps(); if (issuesToReport != null) { using (FixedOrphanFootnoteReportDlg dlg = new FixedOrphanFootnoteReportDlg( issuesToReport, cache.ProjectName(), FwApp.App)) { dlg.ShowDialog(); } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Exports as FXT. /// </summary> /// <param name="progressDialog">The progress dialog.</param> /// <param name="parameters">The parameters: 1) output file, 2) template file path. /// </param> /// <returns>Always null.</returns> /// ------------------------------------------------------------------------------------ private object ExportFxt(IAdvInd4 progressDialog, params object[] parameters) { Debug.Assert(parameters.Length == 3); m_progressDlg = progressDialog; string outPath = (string)parameters[0]; string fxtPath = (string)parameters[1]; bool fLiftOutput = (bool)parameters[2]; MapFlidsInDumperAsNeeded(fxtPath); #if DEBUG DateTime dtStart = DateTime.Now; #endif using (TextWriter w = new StreamWriter(outPath)) { m_dumper.ExportPicturesAndMedia = m_fExportPicturesAndMedia; m_dumper.Go(m_cache.LangProject as CmObject, fxtPath, w); } #if DEBUG DateTime dtExport = DateTime.Now; #endif if (fLiftOutput) { try { progressDialog.Message = String.Format(xWorksStrings.ksValidatingOutputFile, Path.GetFileName(outPath)); ValidationProgress prog = new ValidationProgress(progressDialog); LiftIO.Validation.Validator.CheckLiftWithPossibleThrow(outPath, prog); } catch (LiftIO.LiftFormatException lfe) { // Show the pretty yellow semi-crash dialog box, with instructions for the // user to report the bug. SIL.Utils.ErrorReporter.ReportException( new Exception(xWorksStrings.ksLiftExportBugReport, lfe), this, false); } } #if DEBUG DateTime dtValidate = DateTime.Now; TimeSpan exportDelta = new TimeSpan(dtExport.Ticks - dtStart.Ticks); TimeSpan validateDelta = new TimeSpan(dtValidate.Ticks - dtExport.Ticks); Debug.WriteLine(String.Format("Export time = {0}, Validation time = {1}", exportDelta, validateDelta)); #endif return(null); }
/// ------------------------------------------------------------------------------------- /// <summary> /// Perform one-time initialization of a new Scripture project /// </summary> /// <returns>true if data loaded successfully; false, otherwise</returns> /// ------------------------------------------------------------------------------------- protected bool Initialize(IFwSplashScreen splashScreen) { ILangProject lp = m_cache.LangProject; if (m_scr != null) { // Preload all book, section and paragraphs if we already have Scripture PreloadData(m_cache, splashScreen); if (m_scr.BookAnnotationsOS.Count != 0 && m_cache.ScriptureReferenceSystem.BooksOS.Count != 0 && m_scr.PublicationsOC.Count != 0 && lp.KeyTermsList.PossibilitiesOS.Count >= 1 && m_scr.NoteCategoriesOA != null && m_scr.NoteCategoriesOA.PossibilitiesOS.Count > 0) { return(true); } } IAdvInd4 existingProgressDlg = null; if (splashScreen != null) { existingProgressDlg = splashScreen.ProgressBar as IAdvInd4; } using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(Form.ActiveForm)) { try { dlg.RunTask(existingProgressDlg, true, new BackgroundTaskInvoker(InitializeScriptureProject)); } catch (WorkerThreadException e) { UndoResult ures; while (m_cache.Undo(out ures)) { ; // Enhance JohnT: make use of ures? } MessageBox.Show(Form.ActiveForm, e.InnerException.Message, TeResourceHelper.GetResourceString("kstidApplicationName"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } return(true); }
/// ------------------------------------------------------------------------------------ /// <summary> /// The task to do in the background. We just increment the progress and sleep in /// between. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters. Not used.</param> /// <returns>Current progress</returns> /// ------------------------------------------------------------------------------------ private object BackgroundTask(IAdvInd4 progressDlg, object[] parameters) { int i = 0; for (; i < 10; i++) { if (m_fGotCancel) { break; } progressDlg.Step(1); Thread.Sleep(1000); } return(i); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Load the NewLangProj.xml file into the new database /// </summary> /// ------------------------------------------------------------------------------------ protected virtual void LoadNewLangProj(IAdvInd4 progressDlg) { try { // Load the NewLangProj.xml into the new database. IFwXmlData xmlDataLoader = FwXmlDataClass.Create(); xmlDataLoader.Open(m_serverName, m_dbName); xmlDataLoader.LoadXml(DirectoryFinder.TemplateDirectory + @"\NewLangProj.xml", progressDlg); xmlDataLoader.Close(); } catch (Exception) { // TODO: Handle any XML loading errors throw; } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Ensures all of the project components are valid. /// </summary> /// <param name="cache">The cache.</param> /// <param name="existingProgressDlg">The existing progress dialog.</param> /// ------------------------------------------------------------------------------------ public static void EnsureProjectComponentsValid(FdoCache cache, IAdvInd4 existingProgressDlg) { EnsureProjectValid(cache, existingProgressDlg); // TE-8621: Don't try to upgrade the database unless we're the project server and no one is connected if (!MiscUtils.IsServerLocal(cache.ServerName) || cache.GetNumberOfRemoteClients() > 0) { return; } ILangProject lp = cache.LangProject; TePublicationsInit.EnsureFactoryPublications(lp, existingProgressDlg); TeStylesXmlAccessor.EnsureCurrentStylesheet(lp, existingProgressDlg); TeScrNoteCategoriesInit.EnsureCurrentScrNoteCategories(lp, existingProgressDlg); TeKeyTermsInit.EnsureCurrentKeyTerms(lp, existingProgressDlg); cache.Save(); }
private object ImportLift(IAdvInd4 progressDlg, params object[] parameters) { Debug.Assert(parameters.Length == 1); m_progressDlg.Message = LexTextControls.ksLoadingVariousLists; m_progressDlg.Value = 0; FlexLiftMerger flexImporter = new FlexLiftMerger(m_cache, FlexLiftMerger.MergeStyle.msKeepNew, true); LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> parser = new LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample>(flexImporter); parser.SetTotalNumberSteps += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .StepsArgs>(parser_SetTotalNumberSteps); parser.SetStepsCompleted += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .ProgressEventArgs>(parser_SetStepsCompleted); parser.SetProgressMessage += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .MessageArgs>(parser_SetProgressMessage); flexImporter.LiftFile = (string)parameters[0]; int cEntries = parser.ReadLiftFile((string)parameters[0]); m_progressDlg.Message = LexTextControls.ksFixingRelationLinks; flexImporter.ProcessPendingRelations(); return(flexImporter.DisplayNewListItems((string)parameters[0], cEntries)); }
/// <summary> /// Export the contents of the lexicon to the given file (first and only parameter). /// </summary> /// <returns>the name of the exported LIFT file if successful, or null if an error occurs.</returns> protected object ExportLexicon(IAdvInd4 progressDialog, params object[] parameters) { try { if (m_progressDlg == null) { m_progressDlg = progressDialog; } string outPath = (string)parameters[0]; progressDialog.Message = String.Format(FlexChorusStrings.ksExportingEntries, m_cache.LangProject.LexDbOA.EntriesOC.Count); using (XDumper dumper = new XDumper(m_cache)) { dumper.UpdateProgress += new XDumper.ProgressHandler(OnDumperUpdateProgress); dumper.SetProgressMessage += new EventHandler <XDumper.MessageArgs>(OnDumperSetProgressMessage); // Don't bother writing out the range information in the export. dumper.SetTestVariable("SkipRanges", true); dumper.SkipAuxFileOutput = true; progressDialog.SetRange(0, dumper.GetProgressMaximum()); progressDialog.Position = 0; // TODO: get better output/input filename? string p = Path.Combine(DirectoryFinder.FWCodeDirectory, @"Language Explorer\Export Templates"); string fxtPath = Path.Combine(p, "LIFT.fxt.xml"); using (TextWriter w = new StreamWriter(outPath)) { dumper.ExportPicturesAndMedia = true; // useless without Pictures directory... dumper.Go(m_cache.LangProject as CmObject, fxtPath, w); } // TODO: validate output? return(outPath); } } catch { return(null); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// If the current Scripture Note categories list version in the Db doesn't match that of /// the current XML file, update the DB. /// </summary> /// <param name="lp">The language project</param> /// <param name="existingProgressDlg">The existing progress dialog, if any.</param> /// ------------------------------------------------------------------------------------ public static void EnsureCurrentScrNoteCategories(ILangProject lp, IAdvInd4 existingProgressDlg) { XmlNode scrNoteCategories = LoadScrNoteCategoriesDoc(); IScripture scr = lp.TranslatedScriptureOA; Guid newVersion = Guid.Empty; try { XmlNode version = scrNoteCategories.Attributes.GetNamedItem("version"); newVersion = new Guid(version.Value); } catch (Exception e) { ReportInvalidInstallation("List version attribute invalid in TeScrNoteCategories.xml", e); } if (scr.NoteCategoriesOA == null || newVersion != scr.NoteCategoriesOA.ListVersion) { using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(Form.ActiveForm)) { dlg.RunTask(existingProgressDlg, true, new BackgroundTaskInvoker(CreateScrNoteCategories), scrNoteCategories, scr); } } }
private void ExportBook(IScrBook book, IAdvInd4 progressDlg) { m_writer.WriteLine("<div class=\"scrBook\">"); m_xhtml.MapCssToLang("scrBook", LanguageCode(m_cache.DefaultVernWs)); ExportBookTitle(book); int iFirst = 0; int iLim = book.SectionsOS.Count; if (m_what == ExportWhat.SingleBook) { iFirst = m_iFirstSection; iLim = m_iLastSection + 1; } bool fColumnOutput = false; for (int i = iFirst; i < iLim; ++i) { if (!book.SectionsOS[i].IsIntro && !fColumnOutput) { m_writer.WriteLine("<div class=\"columns\">"); m_xhtml.MapCssToLang("columns", LanguageCode(m_cache.DefaultVernWs)); fColumnOutput = true; } ExportBookSection(book.SectionsOS[i]); if (m_cancel) { break; } progressDlg.Step(0); } if (fColumnOutput) { m_writer.WriteLine("</div>"); // matches <div class="columns"> } m_writer.WriteLine("</div>"); // matches <div class="scrBook"> }
/// <summary> /// Constructor. /// </summary> public ValidationProgress(IAdvInd4 progress) { m_progress = progress; }
/// <summary> /// Do the modifications/merging/whatever to the LIFT file given by the first (and only) /// parameter. /// </summary> /// <returns>the name of the modified file (may be the same as the input), or null if an error occurs.</returns> protected object ChorusMerge(IAdvInd4 progressDialog, params object[] parameters) { // TODO: implement this! if (m_progressDlg == null) m_progressDlg = progressDialog; progressDialog.Message = "Merging via Chorus"; progressDialog.SetRange(0, 100); progressDialog.Position = 0; string outPath = parameters[0].ToString(); progressDialog.Position = 100; return outPath; }
protected DummyTeScrNoteCategoriesInit(IAdvInd4 progressDlg, Scripture scr, XmlNode categories) : base(progressDlg, scr, categories) { }
/// ------------------------------------------------------------------------------------ /// <summary> /// Exports the configured doc view. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters.</param> /// <returns>Always null.</returns> /// ------------------------------------------------------------------------------------ private object ExportConfiguredDocView(IAdvInd4 progressDlg, params object[] parameters) { Debug.Assert(parameters.Length == 3); m_progressDlg = progressDlg; if (m_xvc == null) return null; string outPath = (string)parameters[0]; string fxtPath = (string)parameters[1]; FxtType ft = (FxtType)parameters[2]; try { m_cache.EnableBulkLoadingIfPossible(true); using (TextWriter w = new StreamWriter(outPath)) { FileInfo outFile = new FileInfo(outPath); #if DEBUG string dirPath = Path.GetTempPath(); int copyCount = 1; string s = string.Format("Starting Configured Export at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif m_ce = new ConfiguredExport(null, m_cache.MainCacheAccessor, m_hvoRootObj); m_ce.Initialize(m_cache, w, ft.m_sDataType, ft.m_sFormat, outPath); m_ce.UpdateProgress += new SIL.FieldWorks.Common.Controls.ConfiguredExport.ProgressHandler(ce_UpdateProgress); m_xvc.Display(m_ce, m_hvoRootObj, m_seqView.RootFrag); m_ce.Finish(ft.m_sDataType); w.Close(); #if DEBUG s = string.Format("Finished Configured Export Dump at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif if (ft.m_sXsltFiles != null && ft.m_sXsltFiles.Length != 0) { string[] rgsXslts = ft.m_sXsltFiles.Split(new char[] { ';' }); int cXslts = rgsXslts.GetLength(0); progressDlg.Position = 0; progressDlg.SetRange(0, cXslts); progressDlg.Message = xWorksStrings.ProcessingIntoFinalForm; int idx = fxtPath.LastIndexOfAny(new char[] { '/', '\\' }); if (idx < 0) idx = 0; else ++idx; string basePath = fxtPath.Substring(0, idx); for (int ix = 0; ix <= cXslts; ++ix) { #if DEBUG File.Copy(outPath, Path.Combine(dirPath, "DebugOnlyExportStage" + copyCount + ".txt"), true); copyCount++; if (ix < cXslts) s = String.Format("Starting Configured Export XSLT file {0} at {1}", rgsXslts[ix], System.DateTime.Now.ToLongTimeString()); else s = String.Format("Starting final postprocess phase at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif if (ix < cXslts) { string sXsltPath = basePath + rgsXslts[ix]; m_ce.PostProcess(sXsltPath, outPath, ix + 1); } else { m_ce.PostProcess(null, outPath, ix + 1); } progressDlg.Step(0); } } if (ft.m_sFormat.ToLowerInvariant() == "xhtml") { IVwStylesheet vss = null; if (m_seqView.RootBox != null) vss = m_seqView.RootBox.Stylesheet; m_ce.WriteCssFile(Path.ChangeExtension(outPath, ".css"), vss); } m_ce = null; #if DEBUG File.Copy(outPath, Path.Combine(dirPath, "DebugOnlyExportStage" + copyCount + ".txt"), true); s = string.Format("Totally Finished Configured Export at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif } } finally { m_cache.EnableBulkLoadingIfPossible(false); } return null; }
/// <summary> /// Import from a LIFT file. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters: 1) filename</param> /// <returns></returns> private object ImportLIFT(IAdvInd4 progressDlg, params object[] parameters) { m_progressDlg = progressDlg; Debug.Assert(parameters.Length == 1); string sOrigFile = (string)parameters[0]; string sLogFile = null; PropChangedHandling oldPropChg = m_cache.PropChangedHandling; try { m_cache.PropChangedHandling = PropChangedHandling.SuppressAll; string sFilename; bool fMigrationNeeded = LiftIO.Migration.Migrator.IsMigrationNeeded(sOrigFile); if (fMigrationNeeded) { string sOldVersion = LiftIO.Validation.Validator.GetLiftVersion(sOrigFile); m_progressDlg.Message = String.Format(LexTextControls.ksMigratingLiftFile, sOldVersion, LiftIO.Validation.Validator.LiftVersion); sFilename = LiftIO.Migration.Migrator.MigrateToLatestVersion(sOrigFile); } else { sFilename = sOrigFile; } if (!Validate(sFilename, sOrigFile)) return sLogFile; m_progressDlg.Message = LexTextControls.ksLoadingVariousLists; FlexLiftMerger flexImporter = new FlexLiftMerger(m_cache, m_msImport, m_chkTrustModTimes.Checked); LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample> parser = new LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>(flexImporter); parser.SetTotalNumberSteps += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>.StepsArgs>(parser_SetTotalNumberSteps); parser.SetStepsCompleted += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>.ProgressEventArgs>(parser_SetStepsCompleted); parser.SetProgressMessage += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>.MessageArgs>(parser_SetProgressMessage); flexImporter.LiftFile = sOrigFile; int cEntries = parser.ReadLiftFile(sFilename); if (fMigrationNeeded) { // Try to move the migrated file to the temp directory, even if a copy of it // already exists there. string sTempMigrated = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetFileName(sFilename), "." + LiftIO.Validation.Validator.LiftVersion + ".lift")); if (File.Exists(sTempMigrated)) File.Delete(sTempMigrated); File.Move(sFilename, sTempMigrated); } m_progressDlg.Message = LexTextControls.ksFixingRelationLinks; flexImporter.ProcessPendingRelations(); sLogFile = flexImporter.DisplayNewListItems(sOrigFile, cEntries); } catch (Exception error) { string sMsg = String.Format(LexTextControls.ksLIFTImportProblem, sOrigFile, error.Message); try { StringBuilder bldr = new StringBuilder(); // leave in English for programmer's sake... bldr.AppendFormat("Something went wrong while FieldWorks was attempting to import {0}.", sOrigFile); bldr.AppendLine(); bldr.AppendLine(error.Message); bldr.AppendLine(); bldr.AppendLine(error.StackTrace); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) Clipboard.SetDataObject(bldr.ToString(), true); else SIL.Utils.Logger.WriteEvent(bldr.ToString()); } catch { } MessageBox.Show(sMsg, LexTextControls.ksProblemImporting, MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { m_cache.PropChangedHandling = oldPropChg; } return sLogFile; }
protected void DoExport(string outPath, bool fLiftOutput) { string fxtPath = (string)m_exportList.SelectedItems[0].Tag; FxtType ft = m_rgFxtTypes[FxtIndex(fxtPath)]; using (new SIL.FieldWorks.Common.Utils.WaitCursor(this)) { using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this)) { try { progressDlg.Title = String.Format(xWorksStrings.Exporting0, m_exportList.SelectedItems[0].SubItems[0].Text); progressDlg.Message = xWorksStrings.Exporting_; switch (ft.m_ft) { case FxtTypes.kftFxt: using (m_dumper = new XDumper(m_cache)) { m_dumper.UpdateProgress += new XDumper.ProgressHandler(OnDumperUpdateProgress); m_dumper.SetProgressMessage += new EventHandler <XDumper.MessageArgs>(OnDumperSetProgressMessage); progressDlg.SetRange(0, m_dumper.GetProgressMaximum()); progressDlg.CancelButtonVisible = true; progressDlg.Restartable = true; progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous; progressDlg.Cancel += new CancelHandler(Onm_progressDlg_Cancel); progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportFxt), outPath, fxtPath, fLiftOutput); } break; case FxtTypes.kftConfigured: case FxtTypes.kftReversal: progressDlg.SetRange(0, m_seqView.ObjectCount); progressDlg.CancelButtonVisible = true; progressDlg.Cancel += new CancelHandler(ce_Cancel); progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportConfiguredDocView), outPath, fxtPath, ft); break; } } catch (WorkerThreadException e) { if (e.InnerException is CancelException) { MessageBox.Show(this, e.InnerException.Message); m_ce = null; } else { string msg = xWorksStrings.ErrorExporting_ProbablyBug + "\n" + e.InnerException.Message; MessageBox.Show(this, msg); } } finally { m_progressDlg = null; m_dumper = null; this.Close(); } } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Initializes the scripture project. /// </summary> /// <param name="progressDialog">The progress dialog.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> /// ------------------------------------------------------------------------------------ private object InitializeScriptureProject(IAdvInd4 progressDialog, params object[] parameters) { ILangProject lp = m_cache.LangProject; if (m_scr == null) { m_scr = lp.TranslatedScriptureOA = new Scripture(); //Initialize factory styles TeStylesXmlAccessor.CreateFactoryScrStyles(progressDialog, m_scr); // Initialize the separator and bridge strings. m_scr.ChapterVerseSepr = ":"; m_scr.Bridge = "-"; m_scr.RefSepr = ";"; m_scr.VerseSepr = ","; //Initialize misc m_scr.RestartFootnoteSequence = true; m_scr.CrossRefsCombinedWithFootnotes = false; m_scr.FootnoteMarkerType = FootnoteMarkerTypes.AutoFootnoteMarker; m_scr.FootnoteMarkerSymbol = Scripture.kDefaultFootnoteMarkerSymbol; m_scr.DisplayFootnoteReference = false; m_scr.CrossRefMarkerType = FootnoteMarkerTypes.NoFootnoteMarker; m_scr.CrossRefMarkerSymbol = Scripture.kDefaultFootnoteMarkerSymbol; m_scr.DisplayCrossRefReference = true; } // Initialize Scripture book annotations if (m_scr.BookAnnotationsOS.Count == 0) { CreateScrBookAnnotations(); } //Initialize Scripture Book Ref info if (m_cache.ScriptureReferenceSystem.BooksOS.Count == 0) { CreateScrBookRefs(progressDialog); } //Initialize factory publications if (m_scr.PublicationsOC.Count == 0) { TePublicationsInit.CreatePublicationInfo(progressDialog, m_scr); } //Initialize the key terms ICmPossibilityList keyTermsList = lp.KeyTermsList; if (keyTermsList.PossibilitiesOS.Count < 1) { TeKeyTermsInit.CreateKeyTerms(progressDialog, keyTermsList); } //Initialize the note categories if (m_scr.NoteCategoriesOA == null || m_scr.NoteCategoriesOA.PossibilitiesOS.Count == 0) { TeScrNoteCategoriesInit.CreateFactoryScrNoteCategories(progressDialog, m_scr); } m_cache.Save(); // For good measure, on the off-chance the user notices. int nMin, nMax; progressDialog.GetRange(out nMin, out nMax); progressDialog.Position = nMax; return(null); }
/// -------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <param name="progressDlg"></param> /// -------------------------------------------------------------------------------- new public void DetectDifferences(IAdvInd4 progressDlg) { base.DetectDifferences(null); //PrintDiffSummary(); }
/// ------------------------------------------------------------------------------------ /// <summary> /// does the import /// </summary> /// <param name="dlg">The progress dialog.</param> /// <param name="parameters">The parameters: 1) runToCompletion, 2) last step, /// 3) start phase, 4) database file name, 5) number of entries, 6) true to display /// the import report, 7) name of phase 1 HTML report file, 8) name of phase 1 file. /// </param> /// <returns><c>true</c> if import was successful, otherwise <c>false</c>.</returns> /// ------------------------------------------------------------------------------------ public object Import(IAdvInd4 dlg, params object[] parameters) { Debug.Assert(parameters.Length == 8); bool runToCompletion = (bool)parameters[0]; int lastStep = (int)parameters[1]; int startPhase = (int)parameters[2]; string databaseFileName = (string)parameters[3]; int cEntries = (int)parameters[4]; m_fDisplayImportReport = (bool)parameters[5]; m_sPhase1HtmlReport = (string)parameters[6]; m_sPhase1FileName = (string)parameters[7]; string sErrorMsg = LexTextControls.ksTransformProblem_X; bool fAttemptedXml = false; bool fXmlOk = false; string processedInputFile = databaseFileName; string sPhase1Output = Path.Combine(m_sTempDir, s_sPhase1FileName); string sPhase2Output = Path.Combine(m_sTempDir, s_sPhase2FileName); string sPhase3Output = Path.Combine(m_sTempDir, s_sPhase3FileName); m_sPhase4Output = Path.Combine(m_sTempDir, s_sPhase4FileName); try { // if starting with a phase file, rename the phase file with the input file switch (startPhase) { case 1: sPhase1Output = databaseFileName; break; case 2: sPhase2Output = databaseFileName; break; case 3: sPhase3Output = databaseFileName; break; case 4: m_sPhase4Output = databaseFileName; break; default: break; // no renaming needed } IAdvInd ai = dlg as IAdvInd; if (startPhase < 2) { dlg.Title = String.Format(LexTextControls.ksImportingXEntriesFromY, cEntries, processedInputFile); dlg.Message = String.Format(LexTextControls.ksPhase1ofX_Preview, lastStep); sErrorMsg = LexTextControls.ksTransformProblemPhase1_X; DoTransform(m_sBuildPhase2XSLT, sPhase1Output, m_sPhase2XSLT); } ai.Step(10); if (m_fCancel) return false; sErrorMsg = LexTextControls.ksTransformProblemPhase2_X; dlg.Message = String.Format(LexTextControls.ksPhase2ofX, lastStep); if (startPhase < 2) DoTransform(m_sPhase2XSLT, sPhase1Output, sPhase2Output); ai.Step(10); if (m_fCancel) return false; sErrorMsg = LexTextControls.ksTransformProblemPhase3_X; dlg.Message = String.Format(LexTextControls.ksPhase3ofX, lastStep); if (startPhase < 3) DoTransform(m_sPhase3XSLT, sPhase2Output, sPhase3Output); ai.Step(10); if (m_fCancel) return false; sErrorMsg = LexTextControls.ksTransformProblemPhase4_X; dlg.Message = String.Format(LexTextControls.ksPhase4ofX, lastStep); if (startPhase < 4) DoTransform(m_sPhase4XSLT, sPhase3Output, m_sPhase4Output); ai.Step(20); if (m_fCancel) return false; if (runToCompletion) { sErrorMsg = LexTextControls.ksXmlParsingProblem5_X; dlg.Message = LexTextControls.ksPhase5of5_LoadingData; IFwXmlData2 fxd = FwXmlDataClass.Create(); fxd.Open(m_cache.ServerName, m_cache.DatabaseName); int hvoOwner = m_cache.LangProject.LexDbOA.Hvo; int flid = (int)LexDb.LexDbTags. kflidEntries; if (m_fCancel) return false; ai.Step(1); // There's no way to cancel from here on out. if (dlg is ProgressDialogWithTask) ((ProgressDialogWithTask)dlg).CancelButtonVisible = false; fAttemptedXml = true; if (startPhase == 4 && processedInputFile.Length == 0) processedInputFile = m_sPhase4Output; fxd.put_BaseImportDirectory(processedInputFile.Substring(0, processedInputFile.LastIndexOfAny(new char[2] { '\\', '/' }))); fxd.ImportXmlObject(m_sPhase4Output, hvoOwner, flid, ai); fXmlOk = true; sErrorMsg = LexTextControls.ksLogFileProblem5_X; ProcessLogFile(processedInputFile, startPhase); return true; } } catch (Exception ex) { Debug.WriteLine("Error: " + ex.Message); ReportError(string.Format(sErrorMsg, ex.Message), LexTextControls.ksUnhandledError); if (fAttemptedXml && !fXmlOk) { // We want to see the log file even (especially) if the Xml blows up. ProcessLogFile(processedInputFile, startPhase); } } return false; }
/// ------------------------------------------------------------------------------------- /// <summary> /// Create all of the ScrBookRef objects for each book of Scripture /// </summary> /// <param name="progressDlg">Progress dialog so the user can cancel</param> /// ------------------------------------------------------------------------------------- protected void CreateScrBookRefs(IAdvInd4 progressDlg) { IScrRefSystem scr = m_cache.ScriptureReferenceSystem; // If there are books existing, then delete them first. for (int i = scr.BooksOS.Count - 1; i >= 0; i--) { scr.BooksOS.RemoveAt(i); } XmlDocument doc = new XmlDocument(); doc.Load(DirectoryFinder.FWCodeDirectory + @"\Translation Editor\ScrBookRef.xml"); ILgWritingSystemFactory wsf = m_cache.LanguageWritingSystemFactoryAccessor; //Select and display the value of all the ISBN attributes. XmlNodeList tagList = doc.SelectNodes("/ScrBookRef/writingsystem"); progressDlg.SetRange(0, tagList.Count * ScrReference.LastBook); progressDlg.Position = 0; progressDlg.Title = TeResourceHelper.GetResourceString("kstidCreatingBookNames"); foreach (XmlNode writingSystem in tagList) { XmlAttributeCollection attributes = writingSystem.Attributes; string sLocale = attributes.GetNamedItem("iculocale").Value; int ws = m_cache.LanguageEncodings.GetWsFromIcuLocale(sLocale); if (ws == 0) { // It is possible that the XML file contains more languages than the // database. If so, just ignore this writing system. continue; } short iBook = 0; XmlNodeList WSBooks = writingSystem.SelectNodes("book"); foreach (XmlNode book in WSBooks) { XmlAttributeCollection bookAttributes = book.Attributes; string sSilBookId = bookAttributes.GetNamedItem("SILBookId").Value; Debug.Assert(sSilBookId != null); // Make sure books are coming in canonical order. Debug.Assert(ScrReference.BookToNumber(sSilBookId) == iBook + 1); string sName = bookAttributes.GetNamedItem("Name").Value; string sAbbrev = bookAttributes.GetNamedItem("Abbreviation").Value; string sAltName = bookAttributes.GetNamedItem("AlternateName").Value; progressDlg.Message = string.Format( TeResourceHelper.GetResourceString("kstidCreatingBookNamesStatusMsg"), sName); progressDlg.Step(0); // check for the book id ScrBookRef bookRef = null; if (scr.BooksOS.Count > iBook) { bookRef = (ScrBookRef)scr.BooksOS[iBook]; Debug.Assert(bookRef != null); } else { // add this book to the list bookRef = new ScrBookRef(); scr.BooksOS.Append(bookRef); } if (sName != null) { bookRef.BookName.SetAlternative(sName, ws); } if (sAbbrev != null) { bookRef.BookAbbrev.SetAlternative(sAbbrev, ws); } if (sAltName != null) { bookRef.BookNameAlt.SetAlternative(sAltName, ws); } iBook++; } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Export a single book /// </summary> /// <param name="sCanon">The current section of the Bible ("ot" or "nt")</param> /// <param name="book">The book.</param> /// <param name="progressDlg">The progress dialog.</param> /// ------------------------------------------------------------------------------------ private void ExportBook(ref string sCanon, IScrBook book, IAdvInd4 progressDlg) { // If we're using segmented backtranslations, load the segment information into the cache. if (Options.UseInterlinearBackTranslation) { foreach (int ws in m_cache.LangProject.AnalysisWssRC.HvoArray) { if (book.TitleOA != null) StTxtPara.LoadSegmentFreeTranslations(book.TitleOA.ParagraphsOS.HvoArray, m_cache, ws); foreach (IStFootnote fn in book.FootnotesOS) StTxtPara.LoadSegmentFreeTranslations(fn.ParagraphsOS.HvoArray, m_cache, ws); } } //m_writer.WriteComment(String.Format( // "Book has {0} title paragraphs and {1} sections", // book.TitleOA.ParagraphsOS.Count, book.SectionsOS.Count)); if (book.CanonicalNum < 40) // First 39 books are in the Old Testament. { if (String.IsNullOrEmpty(sCanon)) { sCanon = "ot"; m_writer.WriteStartElement("canon"); m_writer.WriteAttributeString("ID", sCanon); } } else { if (sCanon != "nt") { if (!String.IsNullOrEmpty(sCanon)) m_writer.WriteEndElement(); sCanon = "nt"; m_writer.WriteStartElement("canon"); m_writer.WriteAttributeString("ID", sCanon); } } if (progressDlg != null) { progressDlg.Message = string.Format(DlgResources.ResourceString( "kstidExportBookStatus"), book.Name.UserDefaultWritingSystem); } m_iCurrentBook = book.CanonicalNum; m_sCurrentBookId = book.BookId.Normalize(); m_sCurrentBookName = GetProperBookName(book.Name.BestVernacularAlternative); m_iCurrentChapter = 0; m_sCurrentChapterNumber = String.Empty; m_iCurrentVerse = 0; m_sCurrentVerseNumber = String.Empty; m_writer.WriteStartElement("book"); m_writer.WriteAttributeString("ID", m_sCurrentBookId); ExportBookTitle(book); m_fInIntroduction = false; int iFirst = 0; int iLim = book.SectionsOS.Count; if (m_what == ExportWhat.SingleBook) { iFirst = m_iFirstSection; iLim = m_iLastSection + 1; } for (int i = iFirst; i < iLim; ++i) { IScrSection section = book.SectionsOS[i]; IScrSection nextSection = (i + 1) < book.SectionsOS.Count ? book.SectionsOS[i + 1] : null; ExportBookSection(section, nextSection); if (m_cancel) break; if (progressDlg != null) progressDlg.Step(0); } if (m_fInIntroduction) m_writer.WriteEndElement(); // </introduction> FlushSectionElementStack(SectionLevel.Major); m_writer.WriteEndElement(); // </book> }
/// ------------------------------------------------------------------------------------ /// <summary> /// Create a new language project for the new language name /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters: first parameter is resources, second is /// name of the project (string), analysis and vernacular writing system /// (NamedWritingSystem).</param> /// <returns>Always null.</returns> /// <remarks>Override DisplayUi to prevent progress dialog from showing.</remarks> /// ------------------------------------------------------------------------------------ protected internal object CreateNewLangProj(IAdvInd4 progressDlg, params object[] parameters) { Debug.Assert(parameters.Length == 4); ResourceManager resources = (ResourceManager)parameters[0]; string projectName = (string)parameters[1]; m_analWrtSys = (NamedWritingSystem)parameters[2]; m_vernWrtSys = (NamedWritingSystem)parameters[3]; string dbFileName; string logFileName; // Loading the new language project (LoadNewLangProj) took 120 steps. To be safe // we calculate with 140. Loading newlangproj took 94% of the time, so the total is // 150. int nMax = 150; progressDlg.SetRange(0, nMax); if (resources != null) { progressDlg.Message = resources.GetString("kstidCreatingDB"); } CreateNewDbFiles(projectName, out dbFileName, out logFileName); progressDlg.Step(0); m_dbName = AttachDatabase(dbFileName, logFileName); progressDlg.Step(0); if (resources != null) { progressDlg.Message = resources.GetString("kstidInitializingDB"); } LoadNewLangProj(progressDlg); // Create the FDO cache and writing systems. progressDlg.Position = (int)(nMax * 0.95); if (resources != null) { progressDlg.Message = resources.GetString("kstidCreatingWS"); } int hvoLp = 0; using (FdoCache cache = FdoCache.Create(m_dbName)) { progressDlg.Step(0); CreateAnalysisWritingSystem(cache); progressDlg.Step(0); CreateVernacularWritingSystem(cache); // Fix sort methods that should use the vernacular writing system. progressDlg.Step(0); progressDlg.Step(0); FixVernacularWritingSystemReferences(cache); progressDlg.Step(0); // set defaults so can access them now cache.LangProject.CacheDefaultWritingSystems(); progressDlg.Step(0); AssignVernacularWritingSystemToDefaultPhPhonemes(cache); progressDlg.Step(0); // Create a reversal index for the original default analysis writing system. (LT-4480) IReversalIndex newIdx = cache.LangProject.LexDbOA.ReversalIndexesOC.Add( new ReversalIndex()); ILgWritingSystem wsAnalysis = cache.LangProject.CurAnalysisWssRS[0]; newIdx.WritingSystemRA = wsAnalysis; newIdx.Name.AnalysisDefaultWritingSystem = wsAnalysis.Name.AnalysisDefaultWritingSystem; progressDlg.Step(0); // Give the language project a default name. Later this can be modified by the // user by changing it on the project properties dialog. cache.LangProject.Name.UserDefaultWritingSystem = projectName; hvoLp = cache.LangProject.Hvo; cache.Save(); progressDlg.Position = nMax; } return(new NewLangProjReturnData(hvoLp, m_serverName, m_dbName)); }
/// ------------------------------------------------------------------------------------- /// <summary> /// Create factory styles from the TE Styles XML file. /// </summary> /// <param name="progressDlg">Progress dialog so the user can cancel</param> /// <param name="scr">The Scripture</param> /// ------------------------------------------------------------------------------------- public static void CreateFactoryScrStyles(IAdvInd4 progressDlg, IScripture scr) { TeStylesXmlAccessor acc = new TeStylesXmlAccessor(scr); acc.CreateStyles(progressDlg, scr.StylesOC, acc.LoadDoc()); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Exports the configured doc view. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters.</param> /// <returns>Always null.</returns> /// ------------------------------------------------------------------------------------ private object ExportConfiguredDocView(IAdvInd4 progressDlg, params object[] parameters) { Debug.Assert(parameters.Length == 3); m_progressDlg = progressDlg; if (m_xvc == null) { return(null); } string outPath = (string)parameters[0]; string fxtPath = (string)parameters[1]; FxtType ft = (FxtType)parameters[2]; try { m_cache.EnableBulkLoadingIfPossible(true); using (TextWriter w = new StreamWriter(outPath)) { FileInfo outFile = new FileInfo(outPath); #if DEBUG string dirPath = Path.GetTempPath(); int copyCount = 1; string s = string.Format("Starting Configured Export at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif m_ce = new ConfiguredExport(null, m_cache.MainCacheAccessor, m_hvoRootObj); m_ce.Initialize(m_cache, w, ft.m_sDataType, ft.m_sFormat, outPath); m_ce.UpdateProgress += new SIL.FieldWorks.Common.Controls.ConfiguredExport.ProgressHandler(ce_UpdateProgress); m_xvc.Display(m_ce, m_hvoRootObj, m_seqView.RootFrag); m_ce.Finish(ft.m_sDataType); w.Close(); #if DEBUG s = string.Format("Finished Configured Export Dump at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif if (ft.m_sXsltFiles != null && ft.m_sXsltFiles.Length != 0) { string[] rgsXslts = ft.m_sXsltFiles.Split(new char[] { ';' }); int cXslts = rgsXslts.GetLength(0); progressDlg.Position = 0; progressDlg.SetRange(0, cXslts); progressDlg.Message = xWorksStrings.ProcessingIntoFinalForm; int idx = fxtPath.LastIndexOfAny(new char[] { '/', '\\' }); if (idx < 0) { idx = 0; } else { ++idx; } string basePath = fxtPath.Substring(0, idx); for (int ix = 0; ix <= cXslts; ++ix) { #if DEBUG File.Copy(outPath, Path.Combine(dirPath, "DebugOnlyExportStage" + copyCount + ".txt"), true); copyCount++; if (ix < cXslts) { s = String.Format("Starting Configured Export XSLT file {0} at {1}", rgsXslts[ix], System.DateTime.Now.ToLongTimeString()); } else { s = String.Format("Starting final postprocess phase at {0}", System.DateTime.Now.ToLongTimeString()); } Debug.WriteLine(s); #endif if (ix < cXslts) { string sXsltPath = basePath + rgsXslts[ix]; m_ce.PostProcess(sXsltPath, outPath, ix + 1); } else { m_ce.PostProcess(null, outPath, ix + 1); } progressDlg.Step(0); } } if (ft.m_sFormat.ToLowerInvariant() == "xhtml") { IVwStylesheet vss = null; if (m_seqView.RootBox != null) { vss = m_seqView.RootBox.Stylesheet; } m_ce.WriteCssFile(Path.ChangeExtension(outPath, ".css"), vss); } m_ce = null; #if DEBUG File.Copy(outPath, Path.Combine(dirPath, "DebugOnlyExportStage" + copyCount + ".txt"), true); s = string.Format("Totally Finished Configured Export at {0}", System.DateTime.Now.ToLongTimeString()); Debug.WriteLine(s); #endif } } finally { m_cache.EnableBulkLoadingIfPossible(false); } return(null); }
protected void DoExport(string outPath, bool fLiftOutput) { string fxtPath = (string)m_exportList.SelectedItems[0].Tag; FxtType ft = m_rgFxtTypes[FxtIndex(fxtPath)]; using (new SIL.FieldWorks.Common.Utils.WaitCursor(this)) { using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this)) { try { progressDlg.Title = String.Format(xWorksStrings.Exporting0, m_exportList.SelectedItems[0].SubItems[0].Text); progressDlg.Message = xWorksStrings.Exporting_; switch (ft.m_ft) { case FxtTypes.kftFxt: using (m_dumper = new XDumper(m_cache)) { m_dumper.UpdateProgress += new XDumper.ProgressHandler(OnDumperUpdateProgress); m_dumper.SetProgressMessage += new EventHandler<XDumper.MessageArgs>(OnDumperSetProgressMessage); progressDlg.SetRange(0, m_dumper.GetProgressMaximum()); progressDlg.CancelButtonVisible = true; progressDlg.Restartable = true; progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous; progressDlg.Cancel += new CancelHandler(Onm_progressDlg_Cancel); progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportFxt), outPath, fxtPath, fLiftOutput); } break; case FxtTypes.kftConfigured: case FxtTypes.kftReversal: progressDlg.SetRange(0, m_seqView.ObjectCount); progressDlg.CancelButtonVisible = true; progressDlg.Cancel += new CancelHandler(ce_Cancel); progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportConfiguredDocView), outPath, fxtPath, ft); break; } } catch (WorkerThreadException e) { if (e.InnerException is CancelException) { MessageBox.Show(this, e.InnerException.Message); m_ce = null; } else { string msg = xWorksStrings.ErrorExporting_ProbablyBug + "\n" + e.InnerException.Message; MessageBox.Show(this, msg); } } finally { m_progressDlg = null; m_dumper = null; this.Close(); } } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Creates the scripture note categories. /// </summary> /// <param name="dlg">The progress dialog.</param> /// <param name="parameters">The parameters: first parameter is a XmlNode with the /// notes categories, second parameter is the scripture object.</param> /// <returns>Always <c>null</c>.</returns> /// ------------------------------------------------------------------------------------ private static object CreateScrNoteCategories(IAdvInd4 dlg, params object[] parameters) { Debug.Assert(parameters.Length == 2); XmlNode scrNoteCategories = (XmlNode)parameters[0]; IScripture scr = (IScripture)parameters[1]; TeScrNoteCategoriesInit noteCategoriesInitializer = new TeScrNoteCategoriesInit(dlg, scr, scrNoteCategories); noteCategoriesInitializer.CreateScrNoteCategories(); return null; }
/// <summary> /// Import a file which looks like a FieldWorks interlinear XML export. /// </summary> /// <param name="dlg"></param> /// <param name="parameters"></param> /// <returns></returns> public object ImportInterlinear(IAdvInd4 dlg, params object[] parameters) { Debug.Assert(parameters.Length == 1); m_nextInput = (string)parameters[0]; DoTransform(m_sRootDir + "FWExport2FWDump.xsl", m_nextInput, m_sTempDir + "IIPhaseOneOutput.xml"); if (m_fCancel) return false; m_nextInput = m_sTempDir + "IIPhaseOneOutput.xml"; m_sErrorMsg = ITextStrings.ksInterlinImportErrorPhase1; dlg.Message = ITextStrings.ksInterlinImportPhase1of2; if (Convert4()) { m_sErrorMsg = ITextStrings.ksInterlinImportErrorPhase2; dlg.Message = ITextStrings.ksInterlinImportPhase2of2; m_shownProgress = dlg.Position; m_phaseProgressEnd = 500; Convert5(); return true; } return false; }
/// ------------------------------------------------------------------------------------- /// <summary> /// Create factory note categories from the TE ScrNoteCategories XML file. /// </summary> /// <param name="progressDlg">Progress dialog so the user can cancel</param> /// <param name="scr">The Scripture</param> /// ------------------------------------------------------------------------------------- public static void CreateFactoryScrNoteCategories(IAdvInd4 progressDlg, IScripture scr) { TeScrNoteCategoriesInit noteCategoriesInitializer = new TeScrNoteCategoriesInit(progressDlg, scr, LoadScrNoteCategoriesDoc()); noteCategoriesInitializer.CreateScrNoteCategories(); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Performs any needed tasks to ensure that the project is valid and has any objects /// required by this version of the application. /// </summary> /// <param name="cache"></param> /// <param name="existingProgressDlg">The existing progress dialog, if any.</param> /// ------------------------------------------------------------------------------------ public static void EnsureProjectValid(FdoCache cache, IAdvInd4 existingProgressDlg) { TeScrInitializer scrInitializer = new TeScrInitializer(cache); scrInitializer.RemoveRtlMarksFromScrProperties(); scrInitializer.EnsureScriptureTextsValid(); List<string> issuesToReport = scrInitializer.FixOrcsWithoutProps(); if (issuesToReport != null) { using (FixedOrphanFootnoteReportDlg dlg = new FixedOrphanFootnoteReportDlg( issuesToReport, cache.ProjectName(), FwApp.App)) { dlg.ShowDialog(); } } }
/// <summary> /// Import the modified LIFT file given by the first (and only) parameter. /// </summary> /// <returns>the name of the log file for the import, or null if a major error occurs.</returns> protected object ImportLexicon(IAdvInd4 progressDialog, params object[] parameters) { if (m_progressDlg == null) { m_progressDlg = progressDialog; } progressDialog.SetRange(0, 100); progressDialog.Position = 0; string inPath = parameters[0].ToString(); string sLogFile = null; PropChangedHandling oldPropChg = m_cache.PropChangedHandling; try { m_cache.PropChangedHandling = PropChangedHandling.SuppressAll; string sFilename; bool fMigrationNeeded = LiftIO.Migration.Migrator.IsMigrationNeeded(inPath); if (fMigrationNeeded) { string sOldVersion = LiftIO.Validation.Validator.GetLiftVersion(inPath); progressDialog.Message = String.Format("Migrating from LIFT version {0} to version {1}", sOldVersion, LiftIO.Validation.Validator.LiftVersion); sFilename = LiftIO.Migration.Migrator.MigrateToLatestVersion(inPath); } else { sFilename = inPath; } // TODO: validate input file? progressDialog.Message = "Loading various lists for lookup during import"; FlexLiftMerger flexImporter = new FlexLiftMerger(m_cache, FlexLiftMerger.MergeStyle.msKeepOnlyNew, true); LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> parser = new LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample>(flexImporter); parser.SetTotalNumberSteps += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .StepsArgs>(parser_SetTotalNumberSteps); parser.SetStepsCompleted += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .ProgressEventArgs>(parser_SetStepsCompleted); parser.SetProgressMessage += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .MessageArgs>(parser_SetProgressMessage); flexImporter.LiftFile = inPath; int cEntries = parser.ReadLiftFile(sFilename); if (fMigrationNeeded) { // Try to move the migrated file to the temp directory, even if a copy of it // already exists there. string sTempMigrated = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetFileName(sFilename), "." + LiftIO.Validation.Validator.LiftVersion + ".lift")); if (File.Exists(sTempMigrated)) { File.Delete(sTempMigrated); } File.Move(sFilename, sTempMigrated); } progressDialog.Message = "Fixing relation links between imported entries"; flexImporter.ProcessPendingRelations(); sLogFile = flexImporter.DisplayNewListItems(inPath, cEntries); } catch (Exception error) { string sMsg = String.Format("Something went wrong trying to import {0} while merging...", inPath, error.Message); try { StringBuilder bldr = new StringBuilder(); // leave in English for programmer's sake... bldr.AppendFormat("Something went wrong while FieldWorks was attempting to import {0}.", inPath); bldr.AppendLine(); bldr.AppendLine(error.Message); bldr.AppendLine(); bldr.AppendLine(error.StackTrace); if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { Clipboard.SetDataObject(bldr.ToString(), true); } } catch { } MessageBox.Show(sMsg, "Problem Merging", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { m_cache.PropChangedHandling = oldPropChg; } return(sLogFile); }
/// <summary> /// Import the modified LIFT file given by the first (and only) parameter. /// </summary> /// <returns>the name of the log file for the import, or null if a major error occurs.</returns> protected object ImportLexicon(IAdvInd4 progressDialog, params object[] parameters) { if (m_progressDlg == null) m_progressDlg = progressDialog; progressDialog.SetRange(0, 100); progressDialog.Position = 0; string inPath = parameters[0].ToString(); string sLogFile = null; PropChangedHandling oldPropChg = m_cache.PropChangedHandling; try { m_cache.PropChangedHandling = PropChangedHandling.SuppressAll; string sFilename; bool fMigrationNeeded = LiftIO.Migration.Migrator.IsMigrationNeeded(inPath); if (fMigrationNeeded) { string sOldVersion = LiftIO.Validation.Validator.GetLiftVersion(inPath); progressDialog.Message = String.Format("Migrating from LIFT version {0} to version {1}", sOldVersion, LiftIO.Validation.Validator.LiftVersion); sFilename = LiftIO.Migration.Migrator.MigrateToLatestVersion(inPath); } else { sFilename = inPath; } // TODO: validate input file? progressDialog.Message = "Loading various lists for lookup during import"; FlexLiftMerger flexImporter = new FlexLiftMerger(m_cache, FlexLiftMerger.MergeStyle.msKeepOnlyNew, true); LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample> parser = new LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>(flexImporter); parser.SetTotalNumberSteps += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>.StepsArgs>(parser_SetTotalNumberSteps); parser.SetStepsCompleted += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject,LiftEntry,LiftSense,LiftExample>.ProgressEventArgs>(parser_SetStepsCompleted); parser.SetProgressMessage += new EventHandler<LiftIO.Parsing.LiftParser<LiftObject, LiftEntry, LiftSense, LiftExample>.MessageArgs>(parser_SetProgressMessage); flexImporter.LiftFile = inPath; int cEntries = parser.ReadLiftFile(sFilename); if (fMigrationNeeded) { // Try to move the migrated file to the temp directory, even if a copy of it // already exists there. string sTempMigrated = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetFileName(sFilename), "." + LiftIO.Validation.Validator.LiftVersion + ".lift")); if (File.Exists(sTempMigrated)) File.Delete(sTempMigrated); File.Move(sFilename, sTempMigrated); } progressDialog.Message = "Fixing relation links between imported entries"; flexImporter.ProcessPendingRelations(); sLogFile = flexImporter.DisplayNewListItems(inPath, cEntries); } catch (Exception error) { string sMsg = String.Format("Something went wrong trying to import {0} while merging...", inPath, error.Message); try { StringBuilder bldr = new StringBuilder(); // leave in English for programmer's sake... bldr.AppendFormat("Something went wrong while FieldWorks was attempting to import {0}.", inPath); bldr.AppendLine(); bldr.AppendLine(error.Message); bldr.AppendLine(); bldr.AppendLine(error.StackTrace); if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) Clipboard.SetDataObject(bldr.ToString(), true); } catch { } MessageBox.Show(sMsg, "Problem Merging", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { m_cache.PropChangedHandling = oldPropChg; } return sLogFile; }
/// <summary> /// Import from a LIFT file. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters: 1) filename</param> /// <returns></returns> private object ImportLIFT(IAdvInd4 progressDlg, params object[] parameters) { m_progressDlg = progressDlg; Debug.Assert(parameters.Length == 1); string sOrigFile = (string)parameters[0]; string sLogFile = null; PropChangedHandling oldPropChg = m_cache.PropChangedHandling; try { m_cache.PropChangedHandling = PropChangedHandling.SuppressAll; string sFilename; bool fMigrationNeeded = LiftIO.Migration.Migrator.IsMigrationNeeded(sOrigFile); if (fMigrationNeeded) { string sOldVersion = LiftIO.Validation.Validator.GetLiftVersion(sOrigFile); m_progressDlg.Message = String.Format(LexTextControls.ksMigratingLiftFile, sOldVersion, LiftIO.Validation.Validator.LiftVersion); sFilename = LiftIO.Migration.Migrator.MigrateToLatestVersion(sOrigFile); } else { sFilename = sOrigFile; } if (!Validate(sFilename, sOrigFile)) { return(sLogFile); } m_progressDlg.Message = LexTextControls.ksLoadingVariousLists; FlexLiftMerger flexImporter = new FlexLiftMerger(m_cache, m_msImport, m_chkTrustModTimes.Checked); LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> parser = new LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample>(flexImporter); parser.SetTotalNumberSteps += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .StepsArgs>(parser_SetTotalNumberSteps); parser.SetStepsCompleted += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .ProgressEventArgs>(parser_SetStepsCompleted); parser.SetProgressMessage += new EventHandler <LiftIO.Parsing.LiftParser <LiftObject, LiftEntry, LiftSense, LiftExample> .MessageArgs>(parser_SetProgressMessage); flexImporter.LiftFile = sOrigFile; int cEntries = parser.ReadLiftFile(sFilename); if (fMigrationNeeded) { // Try to move the migrated file to the temp directory, even if a copy of it // already exists there. string sTempMigrated = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetFileName(sFilename), "." + LiftIO.Validation.Validator.LiftVersion + ".lift")); if (File.Exists(sTempMigrated)) { File.Delete(sTempMigrated); } File.Move(sFilename, sTempMigrated); } m_progressDlg.Message = LexTextControls.ksFixingRelationLinks; flexImporter.ProcessPendingRelations(); sLogFile = flexImporter.DisplayNewListItems(sOrigFile, cEntries); } catch (Exception error) { string sMsg = String.Format(LexTextControls.ksLIFTImportProblem, sOrigFile, error.Message); try { StringBuilder bldr = new StringBuilder(); // leave in English for programmer's sake... bldr.AppendFormat("Something went wrong while FieldWorks was attempting to import {0}.", sOrigFile); bldr.AppendLine(); bldr.AppendLine(error.Message); bldr.AppendLine(); bldr.AppendLine(error.StackTrace); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { Clipboard.SetDataObject(bldr.ToString(), true); } else { SIL.Utils.Logger.WriteEvent(bldr.ToString()); } } catch { } MessageBox.Show(sMsg, LexTextControls.ksProblemImporting, MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { m_cache.PropChangedHandling = oldPropChg; } return(sLogFile); }
/// <summary> /// Export the contents of the lexicon to the given file (first and only parameter). /// </summary> /// <returns>the name of the exported LIFT file if successful, or null if an error occurs.</returns> protected object ExportLexicon(IAdvInd4 progressDialog, params object[] parameters) { try { if (m_progressDlg == null) m_progressDlg = progressDialog; string outPath = (string)parameters[0]; progressDialog.Message = String.Format(FlexChorusStrings.ksExportingEntries, m_cache.LangProject.LexDbOA.EntriesOC.Count); using (XDumper dumper = new XDumper(m_cache)) { dumper.UpdateProgress += new XDumper.ProgressHandler(OnDumperUpdateProgress); dumper.SetProgressMessage += new EventHandler<XDumper.MessageArgs>(OnDumperSetProgressMessage); // Don't bother writing out the range information in the export. dumper.SetTestVariable("SkipRanges", true); dumper.SkipAuxFileOutput = true; progressDialog.SetRange(0, dumper.GetProgressMaximum()); progressDialog.Position = 0; // TODO: get better output/input filename? string p = Path.Combine(DirectoryFinder.FWCodeDirectory, @"Language Explorer\Export Templates"); string fxtPath = Path.Combine(p, "LIFT.fxt.xml"); using (TextWriter w = new StreamWriter(outPath)) { dumper.ExportPicturesAndMedia = true; // useless without Pictures directory... dumper.Go(m_cache.LangProject as CmObject, fxtPath, w); } // TODO: validate output? return outPath; } } catch { return null; } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Exports the scripture. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The parameters. (ignored)</param> /// <returns>always <c>null</c></returns> /// ------------------------------------------------------------------------------------ private object ExportScripture(IAdvInd4 progressDlg, params object[] parameters) { switch (m_what) { case ExportWhat.AllBooks: // Export all of the Scripture books in the project. for (int i = 0; i < m_scr.ScriptureBooksOS.Count && !m_cancel; ++i) ExportBook(m_scr.ScriptureBooksOS[i], progressDlg); break; case ExportWhat.FilteredBooks: // Export all of the Scripture books in the filter for (int bookIndex = 0; bookIndex < m_bookFilter.BookCount && !m_cancel; bookIndex++) ExportBook(m_bookFilter.GetBook(bookIndex), progressDlg); break; case ExportWhat.SingleBook: // Export a single book. ExportBook(m_scr.FindBook(m_nBookSingle), progressDlg); break; } return null; }
/// ------------------------------------------------------------------------------------ /// <summary> /// If <paramref name="progressDlg"/> is not <c>null</c> we run the background task /// with that progress dialog (without creating a separate thread). Otherwise we display /// a new progress dialog as a modal dialog and start the background task in a separate /// thread. /// </summary> /// <param name="progressDlg">The existing progress dialog, or <c>null</c>.</param> /// <param name="fDisplayUi">set to <c>true</c> to display the progress dialog, /// <c>false</c> to run without UI.</param> /// <param name="backgroundTask">The background task.</param> /// <param name="parameters">The paramters that will be passed to the background task</param> /// <returns>The return value from the background thread.</returns> /// ------------------------------------------------------------------------------------ public object RunTask(IAdvInd4 progressDlg, bool fDisplayUi, BackgroundTaskInvoker backgroundTask, params object[] parameters) { if (progressDlg != null) { int nMin; int nMax = 0; progressDlg.GetRange(out nMin, out nMax); progressDlg.Position = nMin; object ret = backgroundTask(progressDlg, parameters); progressDlg.SetRange(nMin, nMax); progressDlg.Position = nMax; return ret; } return RunTask(fDisplayUi, backgroundTask, parameters); }
private void ExportBook(IScrBook book, IAdvInd4 progressDlg) { m_writer.WriteLine("<div class=\"scrBook\">"); m_xhtml.MapCssToLang("scrBook", LanguageCode(m_cache.DefaultVernWs)); ExportBookTitle(book); int iFirst = 0; int iLim = book.SectionsOS.Count; if (m_what == ExportWhat.SingleBook) { iFirst = m_iFirstSection; iLim = m_iLastSection + 1; } bool fColumnOutput = false; for (int i = iFirst; i < iLim; ++i) { if (!book.SectionsOS[i].IsIntro && !fColumnOutput) { m_writer.WriteLine("<div class=\"columns\">"); m_xhtml.MapCssToLang("columns", LanguageCode(m_cache.DefaultVernWs)); fColumnOutput = true; } ExportBookSection(book.SectionsOS[i]); if (m_cancel) break; progressDlg.Step(0); } if (fColumnOutput) m_writer.WriteLine("</div>"); // matches <div class="columns"> m_writer.WriteLine("</div>"); // matches <div class="scrBook"> }
/// ------------------------------------------------------------------------------------ /// <summary> /// Imports using the specified import settings. /// </summary> /// <param name="progressDlg">The progress dialog.</param> /// <param name="parameters">The paramaters: import settings, undo action, and book /// merger, TeImportUi.</param> /// <returns>The Scripture reference of the first thing imported</returns> /// ------------------------------------------------------------------------------------ protected override object ImportSf(IAdvInd4 progressDlg, object[] parameters) { Debug.Assert(parameters.Length == 3); IScrImportSet importSettings = (IScrImportSet)parameters[0]; UndoImportManager undoManager = (UndoImportManager)parameters[1]; TeImportUi importUi = (TeImportUi)parameters[2]; MockTeImporter.Import(importSettings, m_cache, m_styleSheet, undoManager, importUi, m_segmentList); return ScrReference.Empty; }
/// ------------------------------------------------------------------------------------- /// <summary> /// If the current stylesheet version in the Db doesn't match that of the current XML /// file, update the DB. /// </summary> /// <param name="lp">The language project</param> /// <param name="progressDlg">The progress dialog from the splash screen</param> /// ------------------------------------------------------------------------------------- public static void EnsureCurrentStylesheet(ILangProject lp, IAdvInd4 progressDlg) { TeStylesXmlAccessor acc = new TeStylesXmlAccessor(lp.TranslatedScriptureOA); acc.EnsureCurrentResource(progressDlg); if (acc.UserModifiedStyles.Count > 0) { using (FwStylesModifiedDlg dlg = new FwStylesModifiedDlg(acc.UserModifiedStyles, lp.Cache.ProjectName(), FwApp.App)) { dlg.ShowDialog(); } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// does the import /// </summary> /// <param name="dlg">The progress dialog.</param> /// <param name="parameters">The parameters: 1) runToCompletion, 2) last step, /// 3) start phase, 4) database file name, 5) number of entries, 6) true to display /// the import report, 7) name of phase 1 HTML report file, 8) name of phase 1 file. /// </param> /// <returns><c>true</c> if import was successful, otherwise <c>false</c>.</returns> /// ------------------------------------------------------------------------------------ public object Import(IAdvInd4 dlg, params object[] parameters) { Debug.Assert(parameters.Length == 8); bool runToCompletion = (bool)parameters[0]; int lastStep = (int)parameters[1]; int startPhase = (int)parameters[2]; string databaseFileName = (string)parameters[3]; int cEntries = (int)parameters[4]; m_fDisplayImportReport = (bool)parameters[5]; m_sPhase1HtmlReport = (string)parameters[6]; m_sPhase1FileName = (string)parameters[7]; string sErrorMsg = LexTextControls.ksTransformProblem_X; bool fAttemptedXml = false; bool fXmlOk = false; string processedInputFile = databaseFileName; string sPhase1Output = Path.Combine(m_sTempDir, s_sPhase1FileName); string sPhase2Output = Path.Combine(m_sTempDir, s_sPhase2FileName); string sPhase3Output = Path.Combine(m_sTempDir, s_sPhase3FileName); m_sPhase4Output = Path.Combine(m_sTempDir, s_sPhase4FileName); try { // if starting with a phase file, rename the phase file with the input file switch (startPhase) { case 1: sPhase1Output = databaseFileName; break; case 2: sPhase2Output = databaseFileName; break; case 3: sPhase3Output = databaseFileName; break; case 4: m_sPhase4Output = databaseFileName; break; default: break; // no renaming needed } IAdvInd ai = dlg as IAdvInd; if (startPhase < 2) { dlg.Title = String.Format(LexTextControls.ksImportingXEntriesFromY, cEntries, processedInputFile); dlg.Message = String.Format(LexTextControls.ksPhase1ofX_Preview, lastStep); sErrorMsg = LexTextControls.ksTransformProblemPhase1_X; DoTransform(m_sBuildPhase2XSLT, sPhase1Output, m_sPhase2XSLT); } ai.Step(10); if (m_fCancel) { return(false); } sErrorMsg = LexTextControls.ksTransformProblemPhase2_X; dlg.Message = String.Format(LexTextControls.ksPhase2ofX, lastStep); if (startPhase < 2) { DoTransform(m_sPhase2XSLT, sPhase1Output, sPhase2Output); } ai.Step(10); if (m_fCancel) { return(false); } sErrorMsg = LexTextControls.ksTransformProblemPhase3_X; dlg.Message = String.Format(LexTextControls.ksPhase3ofX, lastStep); if (startPhase < 3) { DoTransform(m_sPhase3XSLT, sPhase2Output, sPhase3Output); } ai.Step(10); if (m_fCancel) { return(false); } sErrorMsg = LexTextControls.ksTransformProblemPhase4_X; dlg.Message = String.Format(LexTextControls.ksPhase4ofX, lastStep); if (startPhase < 4) { DoTransform(m_sPhase4XSLT, sPhase3Output, m_sPhase4Output); } ai.Step(20); if (m_fCancel) { return(false); } if (runToCompletion) { sErrorMsg = LexTextControls.ksXmlParsingProblem5_X; dlg.Message = LexTextControls.ksPhase5of5_LoadingData; IFwXmlData2 fxd = FwXmlDataClass.Create(); fxd.Open(m_cache.ServerName, m_cache.DatabaseName); int hvoOwner = m_cache.LangProject.LexDbOA.Hvo; int flid = (int)LexDb.LexDbTags. kflidEntries; if (m_fCancel) { return(false); } ai.Step(1); // There's no way to cancel from here on out. if (dlg is ProgressDialogWithTask) { ((ProgressDialogWithTask)dlg).CancelButtonVisible = false; } fAttemptedXml = true; if (startPhase == 4 && processedInputFile.Length == 0) { processedInputFile = m_sPhase4Output; } fxd.put_BaseImportDirectory(processedInputFile.Substring(0, processedInputFile.LastIndexOfAny(new char[2] { '\\', '/' }))); fxd.ImportXmlObject(m_sPhase4Output, hvoOwner, flid, ai); fXmlOk = true; sErrorMsg = LexTextControls.ksLogFileProblem5_X; ProcessLogFile(processedInputFile, startPhase); return(true); } } catch (Exception ex) { Debug.WriteLine("Error: " + ex.Message); ReportError(string.Format(sErrorMsg, ex.Message), LexTextControls.ksUnhandledError); if (fAttemptedXml && !fXmlOk) { // We want to see the log file even (especially) if the Xml blows up. ProcessLogFile(processedInputFile, startPhase); } } return(false); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Process the resources (e.g., create styles or add publication info). /// </summary> /// <param name="dlg">The progress dialog manager.</param> /// <param name="progressDlg">The progress dialog box itself.</param> /// <param name="doc">The loaded document that has the settings.</param> /// ------------------------------------------------------------------------------------ protected abstract void ProcessResources(ProgressDialogWithTask dlg, IAdvInd4 progressDlg, T doc);
/// ------------------------------------------------------------------------------------ /// <summary> /// Ensures all of the project components are valid. /// </summary> /// <param name="cache">The cache.</param> /// <param name="existingProgressDlg">The existing progress dialog.</param> /// ------------------------------------------------------------------------------------ public static void EnsureProjectComponentsValid(FdoCache cache, IAdvInd4 existingProgressDlg) { EnsureProjectValid(cache, existingProgressDlg); // TE-8621: Don't try to upgrade the database unless we're the project server and no one is connected if (!MiscUtils.IsServerLocal(cache.ServerName) || cache.GetNumberOfRemoteClients() > 0) return; ILangProject lp = cache.LangProject; TePublicationsInit.EnsureFactoryPublications(lp, existingProgressDlg); TeStylesXmlAccessor.EnsureCurrentStylesheet(lp, existingProgressDlg); TeScrNoteCategoriesInit.EnsureCurrentScrNoteCategories(lp, existingProgressDlg); TeKeyTermsInit.EnsureCurrentKeyTerms(lp, existingProgressDlg); cache.Save(); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Exports as FXT. /// </summary> /// <param name="progressDialog">The progress dialog.</param> /// <param name="parameters">The parameters: 1) output file, 2) template file path. /// </param> /// <returns>Always null.</returns> /// ------------------------------------------------------------------------------------ private object ExportFxt(IAdvInd4 progressDialog, params object[] parameters) { Debug.Assert(parameters.Length == 3); m_progressDlg = progressDialog; string outPath = (string)parameters[0]; string fxtPath = (string)parameters[1]; bool fLiftOutput = (bool)parameters[2]; MapFlidsInDumperAsNeeded(fxtPath); #if DEBUG DateTime dtStart = DateTime.Now; #endif using (TextWriter w = new StreamWriter(outPath)) { m_dumper.ExportPicturesAndMedia = m_fExportPicturesAndMedia; m_dumper.Go(m_cache.LangProject as CmObject, fxtPath, w); } #if DEBUG DateTime dtExport = DateTime.Now; #endif if (fLiftOutput) { try { progressDialog.Message = String.Format(xWorksStrings.ksValidatingOutputFile, Path.GetFileName(outPath)); ValidationProgress prog = new ValidationProgress(progressDialog); LiftIO.Validation.Validator.CheckLiftWithPossibleThrow(outPath, prog); } catch (LiftIO.LiftFormatException lfe) { // Show the pretty yellow semi-crash dialog box, with instructions for the // user to report the bug. SIL.Utils.ErrorReporter.ReportException( new Exception(xWorksStrings.ksLiftExportBugReport, lfe), this, false); } } #if DEBUG DateTime dtValidate = DateTime.Now; TimeSpan exportDelta = new TimeSpan(dtExport.Ticks - dtStart.Ticks); TimeSpan validateDelta = new TimeSpan(dtValidate.Ticks - dtExport.Ticks); Debug.WriteLine(String.Format("Export time = {0}, Validation time = {1}", exportDelta, validateDelta)); #endif return null; }
/// ------------------------------------------------------------------------------------ /// <summary> /// Initializes the scripture project. /// </summary> /// <param name="progressDialog">The progress dialog.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> /// ------------------------------------------------------------------------------------ private object InitializeScriptureProject(IAdvInd4 progressDialog, params object[] parameters) { ILangProject lp = m_cache.LangProject; if (m_scr == null) { m_scr = lp.TranslatedScriptureOA = new Scripture(); //Initialize factory styles TeStylesXmlAccessor.CreateFactoryScrStyles(progressDialog, m_scr); // Initialize the separator and bridge strings. m_scr.ChapterVerseSepr = ":"; m_scr.Bridge = "-"; m_scr.RefSepr = ";"; m_scr.VerseSepr = ","; //Initialize misc m_scr.RestartFootnoteSequence = true; m_scr.CrossRefsCombinedWithFootnotes = false; m_scr.FootnoteMarkerType = FootnoteMarkerTypes.AutoFootnoteMarker; m_scr.FootnoteMarkerSymbol = Scripture.kDefaultFootnoteMarkerSymbol; m_scr.DisplayFootnoteReference = false; m_scr.CrossRefMarkerType = FootnoteMarkerTypes.NoFootnoteMarker; m_scr.CrossRefMarkerSymbol = Scripture.kDefaultFootnoteMarkerSymbol; m_scr.DisplayCrossRefReference = true; } // Initialize Scripture book annotations if (m_scr.BookAnnotationsOS.Count == 0) CreateScrBookAnnotations(); //Initialize Scripture Book Ref info if (m_cache.ScriptureReferenceSystem.BooksOS.Count == 0) CreateScrBookRefs(progressDialog); //Initialize factory publications if (m_scr.PublicationsOC.Count == 0) TePublicationsInit.CreatePublicationInfo(progressDialog, m_scr); //Initialize the key terms ICmPossibilityList keyTermsList = lp.KeyTermsList; if (keyTermsList.PossibilitiesOS.Count < 1) TeKeyTermsInit.CreateKeyTerms(progressDialog, keyTermsList); //Initialize the note categories if (m_scr.NoteCategoriesOA == null || m_scr.NoteCategoriesOA.PossibilitiesOS.Count == 0) TeScrNoteCategoriesInit.CreateFactoryScrNoteCategories(progressDialog, m_scr); m_cache.Save(); // For good measure, on the off-chance the user notices. int nMin, nMax; progressDialog.GetRange(out nMin, out nMax); progressDialog.Position = nMax; return null; }
/// ------------------------------------------------------------------------------------ /// <summary> /// Does the import. /// </summary> /// <param name="dlg">The progress dialog.</param> /// <param name="parameters">The parameters: 1) runToCompletion flag, 2) array of /// LanguageMappings, 3) start phase.</param> /// <returns>Returns <c>true</c> if we did the complete import, false if we /// quit early.</returns> /// ------------------------------------------------------------------------------------ public object Import(IAdvInd4 dlg, params object[] parameters) { Debug.Assert(parameters.Length == 3); bool runToCompletion = (bool)parameters[0]; m_languageMappings = (LanguageMapping[])parameters[1]; int startPhase = (int)parameters[2]; m_ai = dlg as IAdvInd; m_LinguaLinksXmlFileName = m_nextInput; m_sErrorMsg = ITextStrings.ksTransformProblem; m_shownProgress = m_phaseProgressStart = 0; m_phaseProgressEnd = 150; if (startPhase < 2) { dlg.Title = ITextStrings.ksLLImportProgress; dlg.Message = ITextStrings.ksLLImportPhase1; m_sErrorMsg = ITextStrings.ksTransformProblem1; if (!Convert1()) return false; } else { m_ai.Step(150); } if (m_fCancel) return false; if (startPhase < 3) { m_sErrorMsg = ITextStrings.ksTransformProblem2; dlg.Message = ITextStrings.ksLLImportPhase2; Convert2(); } m_ai.Step(75); if (m_fCancel) return false; if (startPhase < 4) { m_sErrorMsg = ITextStrings.ksTransformProblem3; dlg.Message = ITextStrings.ksLLImportPhase3; Convert3(); } m_ai.Step(75); if (m_fCancel) return false; // There should be some contents in the phase 3 file if // the process is valid and is using a valid file. // Make sure the file isn't empty and show msg if it is. FileInfo fi = new FileInfo(m_sTempDir + "LLPhase3Output.xml"); if (fi.Length == 0) { ReportError(String.Format(ITextStrings.ksInvalidLLFile, m_LinguaLinksXmlFileName), ITextStrings.ksLLImport); throw new InvalidDataException(); } // There's no way to cancel from here on out. if (dlg is ProgressDialogWithTask) ((ProgressDialogWithTask)dlg).CancelButtonVisible = false; if (runToCompletion) { m_sErrorMsg = ITextStrings.ksXMLParsingProblem4; dlg.Message = ITextStrings.ksLLImportPhase4; if (Convert4()) { m_sErrorMsg = ITextStrings.ksFinishLLTextsProblem5; dlg.Message = ITextStrings.ksLLImportPhase5; m_shownProgress = m_phaseProgressStart = dlg.Position; m_phaseProgressEnd = 500; Convert5(); return true; } } return false; }
/// ------------------------------------------------------------------------------------- /// <summary> /// Create all of the ScrBookRef objects for each book of Scripture /// </summary> /// <param name="progressDlg">Progress dialog so the user can cancel</param> /// ------------------------------------------------------------------------------------- protected void CreateScrBookRefs(IAdvInd4 progressDlg) { IScrRefSystem scr = m_cache.ScriptureReferenceSystem; // If there are books existing, then delete them first. for (int i = scr.BooksOS.Count - 1; i >= 0; i--) scr.BooksOS.RemoveAt(i); XmlDocument doc = new XmlDocument(); doc.Load(DirectoryFinder.FWCodeDirectory + @"\Translation Editor\ScrBookRef.xml"); ILgWritingSystemFactory wsf = m_cache.LanguageWritingSystemFactoryAccessor; //Select and display the value of all the ISBN attributes. XmlNodeList tagList = doc.SelectNodes("/ScrBookRef/writingsystem"); progressDlg.SetRange(0, tagList.Count * ScrReference.LastBook); progressDlg.Position = 0; progressDlg.Title = TeResourceHelper.GetResourceString("kstidCreatingBookNames"); foreach (XmlNode writingSystem in tagList) { XmlAttributeCollection attributes = writingSystem.Attributes; string sLocale = attributes.GetNamedItem("iculocale").Value; int ws = m_cache.LanguageEncodings.GetWsFromIcuLocale(sLocale); if (ws == 0) { // It is possible that the XML file contains more languages than the // database. If so, just ignore this writing system. continue; } short iBook = 0; XmlNodeList WSBooks = writingSystem.SelectNodes("book"); foreach (XmlNode book in WSBooks) { XmlAttributeCollection bookAttributes = book.Attributes; string sSilBookId = bookAttributes.GetNamedItem("SILBookId").Value; Debug.Assert(sSilBookId != null); // Make sure books are coming in canonical order. Debug.Assert(ScrReference.BookToNumber(sSilBookId) == iBook + 1); string sName = bookAttributes.GetNamedItem("Name").Value; string sAbbrev = bookAttributes.GetNamedItem("Abbreviation").Value; string sAltName = bookAttributes.GetNamedItem("AlternateName").Value; progressDlg.Message = string.Format( TeResourceHelper.GetResourceString("kstidCreatingBookNamesStatusMsg"), sName); progressDlg.Step(0); // check for the book id ScrBookRef bookRef = null; if (scr.BooksOS.Count > iBook) { bookRef = (ScrBookRef)scr.BooksOS[iBook]; Debug.Assert(bookRef != null); } else { // add this book to the list bookRef = new ScrBookRef(); scr.BooksOS.Append(bookRef); } if (sName != null) bookRef.BookName.SetAlternative(sName, ws); if (sAbbrev != null) bookRef.BookAbbrev.SetAlternative(sAbbrev, ws); if (sAltName != null) bookRef.BookNameAlt.SetAlternative(sAltName, ws); iBook++; } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Updates the key term equivalents. /// </summary> /// <param name="progressDlg">The progress dialog box.</param> /// <param name="parameters">Not used</param> /// <returns></returns> /// ------------------------------------------------------------------------------------ private object UpdateKeyTermEquivalents(IAdvInd4 progressDlg, params object[] parameters) { m_cache.EnableBulkLoadingIfPossible(true); List<InvalidRendering> invalidRenderings = new List<InvalidRendering>(); try { // first build a map from verses to the keyterms that should have renderings. Set<int> chkTermIds = m_ktTree.ChkTermsWithRefs; if (progressDlg != null) { progressDlg.Message = TeResourceHelper.GetResourceString("kstidUpdateKeyTermEquivalentsProgressLoading"); progressDlg.SetRange(0, chkTermIds.Count); } Dictionary<int, List<KeyTermRef>> bcvToChkRefs = new Dictionary<int, List<KeyTermRef>>(); foreach (int keyTermHvo in chkTermIds) { AddChkRefsToBCVmap(keyTermHvo, ref bcvToChkRefs); if (progressDlg != null) progressDlg.Step(0); } // set progress bar to the number of verses to step through. if (progressDlg != null) progressDlg.SetRange(0, bcvToChkRefs.Count); // for each keyterm occurrences in each verse, make sure renderings are up to date. List<int> sortedKeys = new List<int>(bcvToChkRefs.Keys); sortedKeys.Sort(); foreach (int bcv in sortedKeys) { // REVIEW (TE-6532): For now, all Key Term Refs in the DB use the Original // versisifcation. Should we support other versifications? ScrReference currentVerse = new ScrReference(bcv, Paratext.ScrVers.Original, m_scr.Versification); if (progressDlg != null) { progressDlg.Message = String.Format(TeResourceHelper.GetResourceString("kstidUpdateKeyTermEquivalentsProgressMessage"), currentVerse.AsString); } List<KeyTermRef> chkRefsForVerse = bcvToChkRefs[bcv]; foreach (KeyTermRef chkRef in chkRefsForVerse) { Dictionary<int, bool> renderingActuallyExistsInVerse = new Dictionary<int, bool>(); // skip doing anything about references that have been marked as "Ignore" if (chkRef.Status == KeyTermRenderingStatus.Ignored) continue; if (chkRef.RenderingRAHvo != 0) { if (CanFindTextInVerse(chkRef.RenderingRA, currentVerse)) { if (chkRef.RenderingStatus == KeyTermRenderingStatus.Missing) chkRef.RenderingStatus = KeyTermRenderingStatus.Assigned; continue; } } // if an expected rendering is not found (or there was no previous assignment) // see if we can find an alternative rendering to AutoAssign. IChkTerm parentKeyTerm = chkRef.Owner as IChkTerm; bool fFound = false; foreach (IChkRendering rendering in parentKeyTerm.RenderingsOC) { if (rendering.SurfaceFormRA == null) { // We found a surface form that is not defined. Later we'll need to // remove this rendering, but for now we'll continue to the next one. invalidRenderings.Add(new InvalidRendering(parentKeyTerm, rendering)); continue; } if (CanFindTextInVerse(rendering.SurfaceFormRA, currentVerse)) { try { chkRef.RenderingRA = rendering.SurfaceFormRA; if (chkRef.RenderingStatus != KeyTermRenderingStatus.AutoAssigned) chkRef.RenderingStatus = KeyTermRenderingStatus.AutoAssigned; fFound = true; break; } catch { // Unable to set rendering because it is invalid. invalidRenderings.Add(new InvalidRendering(parentKeyTerm, rendering)); continue; } } } if (!fFound) { if (chkRef.RenderingStatus == KeyTermRenderingStatus.Assigned) { // keep RenderingsRA info, so we know what is missing. chkRef.RenderingStatus = KeyTermRenderingStatus.Missing; } else { if (chkRef.RenderingRA != null) chkRef.RenderingRA = null; if (chkRef.RenderingStatus != KeyTermRenderingStatus.Unassigned) chkRef.RenderingStatus = KeyTermRenderingStatus.Unassigned; } } } if (progressDlg != null) progressDlg.Step(0); } return null; } finally { if (invalidRenderings.Count > 0) { // We found at least one invalid surface form, so we need to search through our // renderings and remove any that are invalid. foreach (InvalidRendering rendering in invalidRenderings) rendering.m_parentKeyTerm.RenderingsOC.Remove(rendering.m_rendering); } m_cache.EnableBulkLoadingIfPossible(false); } }