RunTask() public méthode

If progress dialog is already showing, we run the background task using it (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.
Wraps any exception thrown by the background /// task
public RunTask ( Func backgroundTask ) : object
backgroundTask Func The background task.
Résultat object
Exemple #1
0
		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();
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Calls the TePublicationsInit.CreateFactoryPublicationInfo method
		/// </summary>
		/// <param name="doc">The XML document containing publications and HF sets</param>
		/// ------------------------------------------------------------------------------------
		internal void CallCreatePublicationInfo(XmlDocument doc)
		{
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				progressDlg.RunTask(false, new BackgroundTaskInvoker(CreateFactoryPublicationInfo),
					doc.SelectSingleNode("PublicationDefaultsForNewProject"));
			}
		}
		private void m_btnOK_Click(object sender, EventArgs e)
		{
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = false;
				dlg.Minimum = 0;
				dlg.Maximum = 500;
				using (new WaitCursor(this, true))
				{
					var import = new LinguaLinksImport(m_cache,
						Path.Combine(Path.GetTempPath(), "LanguageExplorer" + Path.DirectorySeparatorChar),
						Path.Combine(FwDirectoryFinder.CodeDirectory, Path.Combine("Language Explorer", "Import" + Path.DirectorySeparatorChar)));
					import.NextInput = m_tbFilename.Text;
					import.Error += import_Error;
					try
					{
						var fSuccess = (bool) dlg.RunTask(true, import.ImportInterlinear, m_tbFilename.Text);
						if (fSuccess)
						{
							DialogResult = DialogResult.OK; // only 'OK' if not exception
							var firstNewText = import.FirstNewText;
							if (firstNewText != null && m_mediator != null)
							{
								m_mediator.SendMessage("JumpToRecord", firstNewText.Hvo);
							}
						}
						else
						{
							DialogResult = DialogResult.Abort; // unsuccessful import
							string message = ITextStrings.ksInterlinImportFailed + Environment.NewLine + Environment.NewLine;
							message += m_messages.ToString();
							MessageBox.Show(this, message, ITextStrings.ksImportFailed, MessageBoxButtons.OK,
								MessageBoxIcon.Warning);
						}
						Close();
					}
					catch (WorkerThreadException ex)
					{
						System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

						MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
							ITextStrings.ksUnhandledError,
							MessageBoxButtons.OK, MessageBoxIcon.Error);
						DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
						Close();
					}
				}
			}
		}
Exemple #4
0
        // I made this region to hold methods that perform particular tasks involving wrapping this dialog around
        // some work.
        #region static methods to encapsulate usages of the dialog
        /// <summary>
        /// I'd like to put all this logic into XmlTranslatedLists, because it is common to most cases of
        /// calling ImportTranslatedListsForWs, which is the point of this method. Unfortunately FDO
        /// cannot reference the DLL that has ProgressDialogWithTask. I've made it public static so that
        /// anything that references FwControls can use it at least.
        /// </summary>
        /// <param name="cache"> </param>
        /// <param name="ws"></param>
        /// <param name="parentWindow"> </param>
        public static void ImportTranslatedListsForWs(Form parentWindow, LcmCache cache, string ws)
        {
            string path = XmlTranslatedLists.TranslatedListsPathForWs(ws, FwDirectoryFinder.TemplateDirectory);

            if (!File.Exists(path))
            {
                return;
            }
            using (var dlg = new ProgressDialogWithTask(parentWindow))
            {
                dlg.AllowCancel = true;
                dlg.Maximum     = 200;
                dlg.Message     = Path.GetFileName(path);
                dlg.Title       = XmlTranslatedLists.ProgressDialogCaption;
                dlg.RunTask(true, ImportTranslatedListsForWs, ws, cache);
            }
        }
		private void m_btnOK_Click(object sender, EventArgs e)
		{
			using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(this))
			{
				dlg.CancelButtonVisible = false;
				dlg.SetRange(0, 500);
				using (new WaitCursor(this, true))
				{
					LinguaLinksImport import = new LinguaLinksImport(m_cache,
						Path.Combine(Path.GetTempPath(), "LanguageExplorer\\"),
						Path.Combine(SIL.FieldWorks.Common.Utils.DirectoryFinder.FWCodeDirectory, "Language Explorer\\Import\\"));
					import.NextInput = m_tbFilename.Text;
					import.Error += new LinguaLinksImport.ErrorHandler(import_Error);
					dlg.Cancel += new CancelHandler(import.On_ProgressDlg_Cancel);
					try
					{
						bool fSuccess = (bool)dlg.RunTask(true,
							new BackgroundTaskInvoker(import.ImportInterlinear),
							m_tbFilename.Text);
						if (fSuccess)
							this.DialogResult = DialogResult.OK;	// only 'OK' if not exception
						else
						{
							this.DialogResult = DialogResult.Abort; // unsuccessful import
							string message = ITextStrings.ksInterlinImportFailed + "\n\n";
							message += m_messages.ToString();
							MessageBox.Show(this, message, ITextStrings.ksImportFailed, MessageBoxButtons.OK,
											MessageBoxIcon.Warning);
						}
						Close();
					}
					catch (WorkerThreadException ex)
					{
						System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

						MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
							ITextStrings.ksUnhandledError,
							MessageBoxButtons.OK, MessageBoxIcon.Error);
						this.DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
						Close();
					}
				}
			}
		}
        /// <summary>
        /// Create a new Fieldworks project and import a lift file into it. Return the .fwdata path.
        /// </summary>
        private static string CreateProjectFromLift(Form parent, IHelpTopicProvider helpTopicProvider, string liftPath)
        {
            string   projectPath;
            FdoCache cache;

            var anthroListFile = CallPickAnthroList(helpTopicProvider);

            using (var progressDlg = new ProgressDialogWithTask(parent))
            {
                progressDlg.Title = FwControls.ksCreatingLiftProject;
                var cacheReceiver = new FdoCache[1];                 // a clumsy way of handling an out parameter, consistent with RunTask
                projectPath = (string)progressDlg.RunTask(true, CreateProjectTask,
                                                          new object[] { liftPath, parent, anthroListFile, cacheReceiver });
                cache = cacheReceiver[0];
            }

            CallImportObtainedLexicon(cache, liftPath, parent);

            ProjectLockingService.UnlockCurrentProject(cache);             // finish all saves and completely write the file so we can proceed to open it
            cache.Dispose();

            return(projectPath);
        }
		private void DoImport()
		{
			using (new WaitCursor(this))
			{
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Minimum = 0;
					progressDlg.Maximum = 100;
					progressDlg.AllowCancel = true;
					progressDlg.Restartable = true;
					progressDlg.Title = String.Format(LexTextControls.ksImportingFrom0, m_sSfmDataFile);
					m_sLogFile = (string)progressDlg.RunTask(true, ImportStdFmtFile,
						m_sSfmDataFile);
					if (m_chkDisplayImportReport.Checked && !String.IsNullOrEmpty(m_sLogFile))
					{
						using (Process.Start(m_sLogFile))
						{
						}
					}
				}
			}
		}
Exemple #8
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Export all of scripture
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void ExportScripture(Form dialogOwner)
		{
			int sectionCount = 0;
			for (int i = 0; i < m_bookFilter.BookCount; i++)
				sectionCount += m_bookFilter.GetBook(i).SectionsOS.Count;
			using (var progressDlg = new ProgressDialogWithTask(dialogOwner))
			{
				progressDlg.Minimum = 0;
				progressDlg.Maximum = sectionCount;
				progressDlg.Title = DlgResources.ResourceString("kstidExportXmlProgress");
				progressDlg.AllowCancel = true;

				progressDlg.RunTask(true, ExportScripture);
			}
		}
Exemple #9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Export all of scripture
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void ExportScripture()
		{
			int sectionCount = 0;
			for (int i = 0; i < m_bookFilter.BookCount; i++)
				sectionCount += m_bookFilter.GetBook(i).SectionsOS.Count;
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				progressDlg.SetRange(0, sectionCount);
				progressDlg.Title = DlgResources.ResourceString("kstidExportXmlProgress");
				progressDlg.CancelButtonVisible = true;
				progressDlg.Cancel += new CancelHandler(OnExportCancel);

				progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportScripture));
			}
		}
		protected override void OnFinishButton()
		{
			if (UsesInvalidFileNames(false))
				return;

			base.OnFinishButton();

			bool runToCompletion = true;
			int lastStep = 5;
			// if the shift key is down, then just build the phaseNoutput files
			if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
			{
				runToCompletion = false;
				lastStep = 4;
			}

			SaveSettings();

			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = true;
				dlg.Maximum = 200;
				using (new WaitCursor(this, true))
				{
					int startPhase = GetDictionaryFileAsPhaseFileNumber();	// see if starting with phase file
					// XSLT files
					string sTransformDir = Path.Combine(FwDirectoryFinder.CodeDirectory,
						String.Format("Language Explorer{0}Import{0}", Path.DirectorySeparatorChar));

					LexImport lexImport = new LexImport(m_cache, m_sTempDir, sTransformDir);
					lexImport.Error += OnImportError;
					bool fRet = (bool)dlg.RunTask(true, lexImport.Import,
						runToCompletion, lastStep, startPhase, m_DatabaseFileName.Text, m_cEntries,
						m_DisplayImportReport.Checked, m_sPhase1HtmlReport, LexImport.s_sPhase1FileName);

					if (fRet)
						DialogResult = DialogResult.OK;	// only 'OK' if not exception
				}
			}
		}
Exemple #11
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create a new language project showing a dialog progress.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected void CreateNewLangProjWithProgress()
		{
			ResourceManager resources = new ResourceManager(
				"SIL.FieldWorks.FwCoreDlgs.FwCoreDlgs", Assembly.GetExecutingAssembly());

			try
			{
				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Title = string.Format(FwCoreDlgs.kstidCreateLangProjCaption, ProjectName);


					using (new WaitCursor())
					{
						m_newProjectInfo = (NewLangProjReturnData)progressDlg.RunTask(DisplayUi,
							new BackgroundTaskInvoker(new FwNewLangProjectCreator().CreateNewLangProj),
							resources, ProjectName, m_cbAnalWrtSys.SelectedItem, m_cbVernWrtSys.SelectedItem);
					}
				}
			}
			catch (WorkerThreadException wex)
			{
				Exception e = wex.InnerException;
				if (e is PathTooLongException)
				{
					this.Show();
					m_fIgnoreClose = true;
					MessageBox.Show(FwCoreDlgs.kstidErrPathToLong);
				}
				else if (e is ApplicationException)
				{
					if (resources != null)
						MessageBox.Show(string.Format(resources.GetString("kstidErrorNewDb"), e.Message));

					m_fIgnoreClose = true;
					this.DialogResult = DialogResult.Cancel;
				}
				else
				{
					m_fIgnoreClose = true;
					this.DialogResult = DialogResult.Cancel;
					throw new Exception(FwCoreDlgs.kstidErrApp, e);
				}
			}
		}
Exemple #12
0
		private void ImportTranslatedLists(string filename)
		{
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = true;
				dlg.Maximum = 200;
				dlg.Message = filename;
				dlg.RunTask(true, FdoCache.ImportTranslatedLists, filename, Cache);
			}
		}
		/// <summary>
		/// Create a new Fieldworks project and import a lift file into it. Return the .fwdata path.
		/// </summary>
		private static string CreateProjectFromLift(Form parent, IHelpTopicProvider helpTopicProvider, string liftPath)
		{
			string projectPath;
			FdoCache cache;

			var anthroListFile = CallPickAnthroList(helpTopicProvider);

			using (var progressDlg = new ProgressDialogWithTask(parent))
			{
				progressDlg.Title = FwControls.ksCreatingLiftProject;
				var cacheReceiver = new FdoCache[1]; // a clumsy way of handling an out parameter, consistent with RunTask
				projectPath = (string)progressDlg.RunTask(true, CreateProjectTask,
					new object[] { liftPath, parent, anthroListFile, cacheReceiver });
				cache = cacheReceiver[0];
			}

			CallImportObtainedLexicon(cache, liftPath, parent);

			ProjectLockingService.UnlockCurrentProject(cache); // finish all saves and completely write the file so we can proceed to open it
			cache.Dispose();

			return projectPath;
		}
Exemple #14
0
		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();
					}
				}
			}
		}
		private void btnImport_Click(object sender, System.EventArgs e)
		{
			// if the shift key is down, then just build the phaseNoutput files
			bool runToCompletion = ((Control.ModifierKeys & Keys.Shift) != Keys.Shift);
			using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(this))
			{
				dlg.CancelButtonVisible = true;

				LanguageMapping[] languageMappings = new LanguageMapping[listViewMapping.Items.Count];
				for (int i = 0; i < listViewMapping.Items.Count; i++)
					languageMappings[i] = new LanguageMapping(listViewMapping.Items[i].SubItems);

				dlg.SetRange(0, 500);

				using (new WaitCursor(this, true))
				{
					// This needs to be reset when cancel is pressed with out clicking the
					// browse button.  This resolves a noted issue in the code where an exception
					// is processed when run a second time...
					m_nextInput = m_LinguaLinksXmlFileName.Text;

					LinguaLinksImport import = new LinguaLinksImport(m_cache, m_sTempDir, m_sRootDir);
					import.NextInput = m_nextInput;
					import.Error += new LinguaLinksImport.ErrorHandler(OnImportError);
					dlg.Cancel += new CancelHandler(import.On_ProgressDlg_Cancel);
					Debug.Assert(m_nextInput == m_LinguaLinksXmlFileName.Text);
					try
					{
						bool fSuccess = (bool)dlg.RunTask(true, new BackgroundTaskInvoker(import.Import),
							runToCompletion, languageMappings, m_startPhase);

						if (fSuccess)
						{
							string sLogFile = m_sTempDir + "LLPhase3Output-Import.log";
							MessageBox.Show(this,
								String.Format(ITextStrings.ksSuccessLoadingLL,
									Path.GetFileName(m_LinguaLinksXmlFileName.Text),
									m_cache.DatabaseName, System.Environment.NewLine, sLogFile),
								ITextStrings.ksLLImportSucceeded,
								MessageBoxButtons.OK, MessageBoxIcon.Information);
							this.DialogResult = DialogResult.OK;	// only 'OK' if not exception
						}
						else
						{
							this.DialogResult = DialogResult.Abort; // unsuccessful import
						}

						Close();
						m_nextInput = import.NextInput;
					}
					catch (WorkerThreadException ex)
					{
						if (ex.InnerException is InvalidDataException)
						{
							// Special handling for this case...
							ShowFinishLabel();
							CheckImportEnabled();
						}
						else
						{
							System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

							MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
								ITextStrings.ksUnhandledError,
								MessageBoxButtons.OK, MessageBoxIcon.Error);
							this.DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
							Close();
						}
					}
				}
			}
		}
Exemple #16
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Moves all of the projects in the specified old project folder (including any
		/// subfolders) to the specified new project folder.
		/// </summary>
		/// <param name="oldFolderForProjects">The old folder that held the projects.</param>
		/// <param name="newFolderForProjects">The new folder that will hold the projects.</param>
		/// <param name="projectPath">The project path.</param>
		/// <param name="oldProjectId">The Id of the old project (to use if it has not moved)</param>
		/// <returns>The ProjectId for the project to load after the move is completed</returns>
		/// ------------------------------------------------------------------------------------
		private static ProjectId MoveProjectFolders(string oldFolderForProjects, string newFolderForProjects,
			string projectPath, ProjectId oldProjectId)
		{
			List<string> rgErrors = new List<string>();
			bool fCopy = MustCopyFoldersAndFiles(oldFolderForProjects, newFolderForProjects);
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(s_threadHelper))
			{
				string[] subDirs = Directory.GetDirectories(oldFolderForProjects);
				progressDlg.Maximum = subDirs.Length;
				progressDlg.AllowCancel = false;
				progressDlg.Title = string.Format(Properties.Resources.ksMovingProjectsCaption, oldFolderForProjects, newFolderForProjects);
				// Move all of the files and folders
				progressDlg.RunTask(true, (progressDialog, dummy) =>
				{
					foreach (string subdir in subDirs)
					{
						try
						{
							string sub = Path.GetFileName(subdir);
							// If the project folder is not known to be ours don't move the folder.
							// This is some protection against moving vital folders if the user does something silly like
							// making C:\ the project folder. See FWR-3371.
							var destDirName = Path.Combine(newFolderForProjects, sub);
							if (!IsFieldWorksProjectFolder(subdir))
							{
								// It might still be a folder which is the name of a remote server,
								// and contains local settings for projects on that server.
								// Check each of its subfolders, and move/copy the ones that appear to be settings, if any.
								bool movedSomething = false;
								foreach (string subsubdir in Directory.GetDirectories(subdir))
								{
									if (!IsFieldWorksSettingsFolder(subsubdir))
										continue;
									// We found a project folder one level down. This ought not so to be.
									// Maybe we are doing some bizarre move into one of our own subfolders, and this
									// was already moved earlier in the main loop? Anyway don't move it, it's not just a settings folder.
									if (IsFieldWorksProjectFolder(subsubdir))
										continue;
									movedSomething = true;
									var leafName = Path.GetFileName(subsubdir);
									var subDirDest = Path.Combine(destDirName, leafName);
									Directory.CreateDirectory(destDirName); // may be redundant (will be after first time) but cheap.
									if (fCopy)
									{
										CopyDirectory(subsubdir, subDirDest);
										Directory.Delete(subsubdir, true);
									}
									else
									{
										Directory.Move(subsubdir, subDirDest);
									}
								}
								// If we moved something and left nothing behind delete the parent folder.
								// (We do a fresh GetDirectories just in case bizarrely we are moving INTO one of our own subfolders,
								// and thus even though we moved everything something is still there).
								if (movedSomething && Directory.GetDirectories(subdir).Length == 0)
									Directory.Delete(subdir);
								continue; // with more top-level directories in the projects folder.
							}
							progressDialog.Message = string.Format(Properties.Resources.ksMovingProject, sub);
							progressDialog.Step(1);
							if (fCopy)
							{
								// Recursively copy each subfolder.
								CopyDirectory(subdir, destDirName);
								Directory.Delete(subdir, true);
							}
							else
							{
								Directory.Move(subdir, destDirName);
							}
						}
						catch (Exception e)
						{
							rgErrors.Add(String.Format("{0} - {1}", Path.GetFileNameWithoutExtension(subdir), e.Message));
						}
					}
					return null;
				});
			}
			if (rgErrors.Count > 0)
			{
				// Show the user any errors that occured while doing the move
				StringBuilder bldr = new StringBuilder();
				bldr.AppendLine(Properties.Resources.ksCannotMoveProjects);
				foreach (var err in rgErrors)
					bldr.AppendLine(err);
				bldr.Append(Properties.Resources.ksYouCanTryToMoveProjects);
				MessageBox.Show(bldr.ToString(), Properties.Resources.ksProblemsMovingProjects);
			}
			if (MiscUtils.IsUnix)
			{
				if (projectPath.StartsWith(oldFolderForProjects))
				{
					// This is perhaps a temporary workaround.  On Linux, FwDirectoryFinder.ProjectsDirectory
					// isn't returning the updated value, but rather the original value.  This seems to
					// last for the duration of the program, but if you exit and restart the program, it
					// gets the correct (updated) value!?
					// (On the other hand, I somewhat prefer this code which is fairly straightforward and
					// obvious to depending on calling some static method hidden in the depths of FDO.)
					string projFileName = Path.GetFileName(projectPath);
					string projName = Path.GetFileNameWithoutExtension(projectPath);
					string path = Path.Combine(Path.Combine(newFolderForProjects, projName), projFileName);
					return new ProjectId(path, null);
				}
			}
			else
			{
				if (projectPath.StartsWith(oldFolderForProjects, StringComparison.InvariantCultureIgnoreCase))
				{
					return new ProjectId(ClientServerServices.Current.Local.IdForLocalProject(
						Path.GetFileNameWithoutExtension(projectPath)), null);
				}
			}
			return oldProjectId;
		}
Exemple #17
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// If all of the books are "new" or auto-merged or caller is asking to auto-accept
		/// changes, then don't actually show the dialog.
		/// See TE-7072, TE-2126 and FB-8847. Otherwise, show the dialog and process normally.
		/// </summary>
		/// <param name="wnd">The parent form</param>
		/// <param name="fAutoAcceptChanges">if set to <c>true</c> automatically accept all
		/// the imported stuff by applying the changes.</param>
		/// ------------------------------------------------------------------------------------
		public void ShowOrSave(IWin32Window wnd, bool fAutoAcceptChanges)
		{
			int cNewOrAutoMerged = 0;
			m_owningForm = wnd as Form;
			bool fCancelled = false;

			foreach (ListViewItem item in lstImportedBooks.Items)
			{
				BookMerger bookMerger = item.Tag as BookMerger;
				if (bookMerger == null)
				{
					++cNewOrAutoMerged;
					continue;
				}

				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(m_owningForm))
				{
					bookMerger.AttemptAutoMerge = true;
					bookMerger.BookVersionAgent = this;
					bookMerger.UseFilteredDiffList = true;
					progressDlg.Title = TeResourceHelper.GetResourceString("kstidImportProgressCaption");
					Debug.Assert(bookMerger.BookRev != null);
					progressDlg.Message = string.Format(
						DlgResources.ResourceString("kstidMergeProgress"), bookMerger.BookRev.BestUIName);
					progressDlg.CancelButtonText =
						TeResourceHelper.GetResourceString("kstidStopImporting");

					// User should not see undo tasks, so the strings don't need to be localized.
					UndoableUnitOfWorkHelper.Do("Automerge", "Automerge",
						m_cache.ServiceLocator.GetInstance<IActionHandler>(), () =>
					{
						try
						{
							progressDlg.RunTask(bookMerger.DetectDifferences);

							if (bookMerger.AutoMerged)
							{
								SetItemStatus(item, ImportedBookStatus.AutoMerged);
								cNewOrAutoMerged++;
							}
							else if (fAutoAcceptChanges)
							{
								progressDlg.Message = string.Format(
									DlgResources.ResourceString("kstidAutoAcceptMergeProgress"), bookMerger.BookRev.BestUIName);
								progressDlg.RunTask(true, bookMerger.AcceptAllChanges);
							}
						}
						catch (WorkerThreadException e)
						{
							if (e.InnerException is CancelException)
							{
								// The current version of
								fCancelled = true;
								return;
							}
							throw;
						}
					});
				}
				if (fCancelled)
					return;
			}

			if (cNewOrAutoMerged < lstImportedBooks.Items.Count && !fAutoAcceptChanges)
				ShowDialog(wnd);
			else
				OnClosed(null);
		}
Exemple #18
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Performs a partial overwrite of the book using the imported portion of the book.
		/// </summary>
		/// <param name="bookMerger">The book merger.</param>
		/// <param name="sectionsToRemove">The sections to remove as the first step (before
		/// calling the auto-merge code).</param>
		/// ------------------------------------------------------------------------------------
		protected virtual void PartialOverwrite(BookMerger bookMerger,
			List<IScrSection> sectionsToRemove)
		{
			Logger.WriteEvent("Performing partial Overwrite of book: " + bookMerger.BookCurr.BookId);
			using (ProgressDialogWithTask progress = new ProgressDialogWithTask(this))
			{
				progress.Title = DlgResources.ResourceString("kstidOverwriteCaption");
				progress.RunTask(bookMerger.DoPartialOverwrite, sectionsToRemove);
			}
		}
Exemple #19
0
		/// -------------------------------------------------------------------------------------
		/// <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;
		}
Exemple #20
0
		private void DoImport()
		{
			using (new WaitCursor(this))
			{
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Minimum = 0;
					progressDlg.Maximum = 100;
					progressDlg.AllowCancel = true;
					progressDlg.Restartable = true;
					progressDlg.Title = String.Format(LexTextControls.ksImportingFrom0, tbPath.Text);
					try
					{
						m_cache.DomainDataByFlid.BeginNonUndoableTask();
						m_sLogFile = (string)progressDlg.RunTask(true, ImportLIFT, tbPath.Text);
					}
					finally
					{
						// This can indirectly try to access Views code in all the PropChanged
						// handling.  This is why the UOW handling has been moved from ImportLIFT
						// (which executes on a different thread).  See FWR-3057.
						m_cache.DomainDataByFlid.EndNonUndoableTask();
					}
				}
			}
		}
Exemple #21
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Cleanly exits the FieldWorks process
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private static void ExitCleanly()
		{
			if (s_appServerMode)
				return; // Continue running even when all apps are shut down

			if (s_allowFinalShutdown)
				Logger.WriteEvent("Shutting down");

			// To be safe - this method might get called recursively (explicitly and from
			// Application.Exit() below again). Also could be called when the startup process
			// did not complete...we picked an app from the command line, but another process
			// was already handling that project.
			if (s_cache != null && !s_cache.IsDisposed)
			{
				DataUpdateMonitor.ClearSemaphore();

				using (var progressDlg = new ProgressDialogWithTask(s_threadHelper))
				{
					progressDlg.Title = string.Format(ResourceHelper.GetResourceString("kstidShutdownCaption"),
						s_cache.ProjectId.UiName);
					progressDlg.AllowCancel = false;
					progressDlg.IsIndeterminate = true;
					var stackMgr = s_cache.ServiceLocator.GetInstance<IUndoStackManager>();
					if (stackMgr.HasUnsavedChanges)
						progressDlg.RunTask(true, CommitAndDisposeCache);
					else
					{
						// For whatever reasons the progress dialog sometimes got closed while
						// the worker was still busy which caused a hang.
						CommitAndDisposeCache(progressDlg, null);
					}
				}
			}

			// This has to be done to zap anything in it weven during a restart triggered by S/R.
			SingletonsContainer.Release();

			if (s_allowFinalShutdown)
			{
				Logger.ShutDown();
				Application.Exit();
			}
		}
		/// ------------------------------------------------------------------------------------
		/// <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);
				}
			}
		}
		protected override void OnFinishButton()
		{
			base.OnFinishButton();
			SaveSettings();
			if (string.IsNullOrEmpty(m_fileListBox.Text))
				return;
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = false;
				dlg.Minimum = 0;
				// Allow 100 units of progress for each file for now. This allows for plenty of resolution for the LL importer
				dlg.Maximum = InputFiles.Count() * 100;

				try
				{
					dlg.RunTask(true, DoConversion);
				}
				catch (WorkerThreadException ex) // any exception on the worker thread is converted to this
				{
					// JohnT: I hate to just report and otherwise ignore all exceptions, but have not been able to find any doc of which ones,
					// if any, EncConverters may throw.
					System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);
					MessageBox.Show(this, String.Format(ITextStrings.ksSfmImportProblem, ex.InnerException.Message),
						ITextStrings.ksUnhandledError,
						MessageBoxButtons.OK, MessageBoxIcon.Error);
					DialogResult = DialogResult.Cancel;
					Close();
				}
			}
			m_mediator.SendMessage("MasterRefresh", ActiveForm);
			if (m_firstNewText != null)
			{
				// try to select it.
				var clerk = RecordClerk.FindClerk(m_mediator, "interlinearTexts");
				if (clerk != null)
					clerk.JumpToRecord(m_firstNewText.ContentsOA.Hvo);
			}
		}
Exemple #24
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// If all of the books are "new" or auto-merged, then don't actually show the dialog.
		/// See TE-7072 and TE-2126. Otherwise, show the dialog and process normally.
		/// </summary>
		/// <param name="wnd"></param>
		/// ------------------------------------------------------------------------------------
		public void ShowOrSave(IWin32Window wnd)
		{
			int cNewOrAutoMerged = 0;
			m_owningForm = wnd as Form;

			foreach (ListViewItem item in lstImportedBooks.Items)
			{
				BookMerger bookMerger = item.Tag as BookMerger;
				if (bookMerger == null)
				{
					++cNewOrAutoMerged;
					continue;
				}

				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(m_owningForm))
				{
					bookMerger.AttemptAutoMerge = true;
					bookMerger.BookVersionAgent = this;
					bookMerger.UseFilteredDiffList();
					progressDlg.Title = DlgResources.ResourceString("kstidCompareCaption");
					Debug.Assert(bookMerger.BookRev != null);
					progressDlg.Message = string.Format(
						DlgResources.ResourceString("kstidMergeProgress"), bookMerger.BookRev.BestUIName);
#if DEBUG_SINGLE_THREADED
					progressDlg.RunTask_DebuggingOnly(true, new BackgroundTaskInvoker(
						bookMerger.DetectDifferences));
#else
					progressDlg.RunTask(true, new BackgroundTaskInvoker(bookMerger.DetectDifferences));
#endif
				}
				if (bookMerger.AutoMerged)
				{
					SetItemStatus(item, ImportedBookStatus.AutoMerged);
					cNewOrAutoMerged++;
				}
			}

			if (cNewOrAutoMerged < lstImportedBooks.Items.Count)
				ShowDialog(wnd);
			else
				OnClosed(null);
		}
		protected override void DoExport(string outPath)
		{
			using (var dlg = new ProgressDialogWithTask(this) { IsIndeterminate = true, AllowCancel = false, Message = ITextStrings.ksExporting_ })
			{
				try
				{
					var fxtPath = (string)m_exportList.SelectedItems[0].Tag; // read fxtPath here to prevent access to m_exportList on another thread
					dlg.RunTask(DoExportWithProgress, outPath, fxtPath);
				}
				finally
				{
					Close();
				}
			}
		}
Exemple #26
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Performs a partial overwrite of the book using the imported portion of the book.
		/// </summary>
		/// <param name="bookMerger">The book merger.</param>
		/// <param name="sectionsToRemove">The sections to remove as the first step (before
		/// calling the auto-merge code).</param>
		/// ------------------------------------------------------------------------------------
		protected virtual void PartialOverwrite(BookMerger bookMerger,
			List<IScrSection> sectionsToRemove)
		{
			using (ProgressDialogWithTask progress = new ProgressDialogWithTask(this))
			{
				progress.Title = DlgResources.ResourceString("kstidOverwriteCaption");
				progress.RunTask(true, new BackgroundTaskInvoker(bookMerger.DoPartialOverwrite),
					sectionsToRemove);
			}
		}
		private ScrReference InternalImport(IScrImportSet importSettings, bool fDisplayUi)
		{
			ScrReference firstImported = ScrReference.Empty;
			bool fPartialBtImported = false;
			try
			{
				Logger.WriteEvent("Starting import");
				using (var progressDlg = new ProgressDialogWithTask(m_mainWnd))
				{
					progressDlg.CancelButtonText =
						TeResourceHelper.GetResourceString("kstidStopImporting");
					progressDlg.Title =
						TeResourceHelper.GetResourceString("kstidImportProgressCaption");
					progressDlg.Message =
						TeResourceHelper.GetResourceString("kstidImportInitializing");

					using (TeImportUi importUi = CreateTeImportUi(progressDlg))
					{
						firstImported = (ScrReference)progressDlg.RunTask(fDisplayUi,
							ImportTask, importSettings, m_undoImportManager, importUi);
					}
				}
			}
			catch (WorkerThreadException e)
			{
				if (e.InnerException is ScriptureUtilsException)
				{
					var se = (ScriptureUtilsException)e.InnerException;
					if (m_helpTopicProvider != null)
					{
						string sCaption = GetDialogCaption(se.ImportErrorCodeType);
						// TODO-Linux: Help is not implemented in Mono
						MessageBox.Show(m_mainWnd, se.Message, sCaption, MessageBoxButtons.OK,
							MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, m_helpTopicProvider.HelpFile,
							HelpNavigator.Topic, se.HelpTopic);
					}
					if (se.ImportErrorCodeType == ErrorCodeType.BackTransErrorCode && !se.InterleavedImport)
						fPartialBtImported = true;
				}
				else if (e.InnerException is ParatextLoadException)
				{
					if (!MiscUtils.RunningTests)
					{
						Logger.WriteError(e);
						string sCaption = ScriptureUtilsException.GetResourceString("kstidImportErrorCaption");
						Exception innerE = e.InnerException;
						var sbMsg = new StringBuilder(innerE.Message);
						while (innerE.InnerException != null)
						{
							innerE = innerE.InnerException;
							sbMsg.AppendLine();
							sbMsg.Append(innerE.Message);
						}

						MessageBoxUtils.Show(m_mainWnd, sbMsg.ToString(), sCaption, MessageBoxButtons.OK,
						MessageBoxIcon.Error);
					}
				}
				else if (!(e.InnerException is CancelException))
				{
					// User didn't just cancel import in the middle of a book -- let's die.
					throw;
				}
			}

			if (m_undoImportManager.ImportedBooks.Count == 0 && !fPartialBtImported)
			{
				Logger.WriteEvent("Nothing imported. Undoing Import.");
				// Either there was nothing in the file, or the user canceled during the first book.
				// In any case, we didn't get any books, so whatever has been done should be undone.
				m_undoImportManager.UndoEntireImport();
				return null;
			}
			return firstImported;
		}
Exemple #28
0
        protected void DoExport(string outPath, bool fLiftOutput)
        {
            string fxtPath = (string)m_exportItems[0].Tag;
            FxtType ft = m_rgFxtTypes[FxtIndex(fxtPath)];
            using (new WaitCursor(this))
            {
                using (var progressDlg = new ProgressDialogWithTask(this))
                {
                    try
                    {
                        progressDlg.Title = String.Format(xWorksStrings.Exporting0,
                            m_exportItems[0].SubItems[0].Text);
                        progressDlg.Message = xWorksStrings.Exporting_;

                        switch (ft.m_ft)
                        {
                            case FxtTypes.kftFxt:
                                m_dumper = new XDumper(m_cache);
                                m_dumper.UpdateProgress += OnDumperUpdateProgress;
                                m_dumper.SetProgressMessage += OnDumperSetProgressMessage;
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = m_dumper.GetProgressMaximum();
                                progressDlg.AllowCancel = true;
                                progressDlg.Restartable = true;

                                progressDlg.RunTask(true, ExportFxt, outPath, fxtPath, fLiftOutput);
                                break;
                            case FxtTypes.kftConfigured:
                            case FxtTypes.kftReversal:
                            case FxtTypes.kftClassifiedDict:
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = m_seqView.ObjectCount;
                                progressDlg.AllowCancel = true;

                                IVwStylesheet vss = m_seqView.RootBox == null ? null : m_seqView.RootBox.Stylesheet;
                                progressDlg.RunTask(true, ExportConfiguredDocView,
                                    outPath, fxtPath, ft, vss);
                                break;
                            case FxtTypes.kftTranslatedLists:
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = m_translatedLists.Count;
                                progressDlg.AllowCancel = true;

                                progressDlg.RunTask(true, ExportTranslatedLists, outPath);
                                break;
                            case FxtTypes.kftSemanticDomains:
                                // Potentially, we could count semantic domains and try to make the export update for each.
                                // In practice this only takes a second or two on a typical modern computer
                                // an the main export routine is borrowed from kftTranslatedLists and set up to count each
                                // list as one step. For now, claiming this export just has one step seems good enough.
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = 1;
                                progressDlg.AllowCancel = true;

                                progressDlg.RunTask(true, ExportSemanticDomains, outPath, ft, fxtPath, m_allQuestions);
                                break;
                            case FxtTypes.kftPathway:
                                break;
                            case FxtTypes.kftLift:
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = 1000;
                                progressDlg.AllowCancel = true;
                                progressDlg.Restartable = true;
                                progressDlg.RunTask(true, ExportLift, outPath, ft.m_filtered);
                                break;
                            case FxtTypes.kftGrammarSketch:
                                progressDlg.Minimum = 0;
                                progressDlg.Maximum = 1000;
                                progressDlg.AllowCancel = true;
                                progressDlg.Restartable = true;
                                progressDlg.RunTask(true, ExportGrammarSketch, outPath, ft.m_sDataType, ft.m_sXsltFiles);
                                break;
                        }
                    }
                    catch (WorkerThreadException e)
                    {
                        if (e.InnerException is CancelException)
                        {
                            MessageBox.Show(this, e.InnerException.Message);
                            m_ce = null;
                        }
                        else if (e.InnerException is LiftFormatException)
                        {
                            // Show the pretty yellow semi-crash dialog box, with instructions for the
                            // user to report the bug.
                            var app = (IApp) m_mediator.PropertyTable.GetValue("App");
                            ErrorReporter.ReportException(new Exception(xWorksStrings.ksLiftExportBugReport, e.InnerException),
                                app.SettingsKey, m_mediator.FeedbackInfoProvider.SupportEmailAddress, this, false);
                        }
                        else
                        {
                            string msg = xWorksStrings.ErrorExporting_ProbablyBug + Environment.NewLine + e.InnerException.Message;
                            MessageBox.Show(this, msg);
                        }
                    }
                    finally
                    {
                        m_progressDlg = null;
                        m_dumper = null;
                        Close();
                    }
                }
            }
        }
Exemple #29
0
		/// <summary>
		/// Run the utility on command from the main utility dialog.
		/// </summary>
		public void Process()
		{
			Debug.Assert(m_dlg != null);
			using (var dlg = new FixErrorsDlg())
			{
				try
				{
					if (dlg.ShowDialog(m_dlg) == DialogResult.OK)
					{
						string pathname = Path.Combine(
							Path.Combine(FwDirectoryFinder.ProjectsDirectory, dlg.SelectedProject),
							dlg.SelectedProject + FdoFileHelper.ksFwDataXmlFileExtension);
						if (File.Exists(pathname))
						{
							using (new WaitCursor(m_dlg))
							{
								using (var progressDlg = new ProgressDialogWithTask(m_dlg))
								{
									string fixes = (string)progressDlg.RunTask(true, FixDataFile, pathname);
									if (fixes.Length > 0)
									{
										MessageBox.Show(fixes, Strings.ksErrorsFoundOrFixed);
										File.WriteAllText(pathname.Replace(FdoFileHelper.ksFwDataXmlFileExtension, "fixes"), fixes);
									}
								}
							}
						}
					}
				}
				catch
				{
				}
			}
		}
		/// <summary>
		/// Import the lift file using the given MergeStyle:
		///		FlexLiftMerger.MergeStyle.MsKeepNew (aka 'merciful', in that all entries from lift file and those in FLEx are retained)
		///		FlexLiftMerger.MergeStyle.MsKeepOnlyNew (aka 'merciless',
		///			in that the Flex lexicon ends up with the same entries as in the lift file, even if some need to be deleted in FLEx.)
		/// </summary>
		/// <param name="mergeStyle">FlexLiftMerger.MergeStyle.MsKeepNew or FlexLiftMerger.MergeStyle.MsKeepOnlyNew</param>
		/// <returns>'true' if the import succeeded, otherwise 'false'.</returns>
		private bool ImportLiftCommon(FlexLiftMerger.MergeStyle mergeStyle)
		{
			using (new WaitCursor(_parentForm))
			{
				using (var progressDlg = new ProgressDialogWithTask(_parentForm))
				{
					_progressDlg = progressDlg;
					try
					{
						if(mergeStyle == FlexLiftMerger.MergeStyle.MsKeepBoth)
						{
							LiftImportFailureServices.RegisterBasicImportFailure(Path.GetDirectoryName(_liftPathname));
						}
						else
						{
							LiftImportFailureServices.RegisterStandardImportFailure(Path.GetDirectoryName(_liftPathname));
						}
						progressDlg.Title = ResourceHelper.GetResourceString("kstidImportLiftlexicon");
						var logFile = (string)progressDlg.RunTask(true, ImportLiftLexicon, new object[] { _liftPathname, mergeStyle });
						if(logFile != null)
						{
							LiftImportFailureServices.ClearImportFailure(Path.GetDirectoryName(_liftPathname));
							return true;
						}
						LiftImportFailureServices.DisplayLiftFailureNoticeIfNecessary(_parentForm, _liftPathname);
						return false;
					}
					catch (WorkerThreadException error)
					{
						// It appears to be an analyst issue to sort out how we should report this.
						// LT-12340 however says we must report it somehow.
						var sMsg = String.Format(LexEdStrings.kProblemImportWhileMerging, _liftPathname, error.InnerException.Message);

						MessageBoxUtils.Show(sMsg, LexEdStrings.kProblemMerging, MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return false;
					}
					finally
					{
						_progressDlg = null;
					}
				}
			}
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles paginating the whole document
		/// </summary>
		/// <param name="args">ignored</param>
		/// <returns><c>true</c> because we handled it</returns>
		/// ------------------------------------------------------------------------------------
		public virtual bool OnViewUpdatePageBreak(object args)
		{
			CheckDisposed();

			IVwRootBox focusedRootBox = FocusedRootBox;
			using (var dialog = new ProgressDialogWithTask(FindForm()))
			{
				dialog.CancelButtonText = ResourceHelper.GetResourceString("kstidUpdatePageBreakButtonText");
				dialog.Title = ResourceHelper.GetResourceString("kstidUpdatePageBreakWindowCaption");
				dialog.AllowCancel = true;
				dialog.RunTask(true, UpdatePageBreaks, DpiXPrinter, DpiYPrinter);
			}

			// make sure the selection is in view
			if (focusedRootBox != null && focusedRootBox.Selection != null &&
				focusedRootBox.Selection.IsValid)
				ScrollSelectionIntoView(focusedRootBox.Selection, VwScrollSelOpts.kssoDefault);

			return true;
		}
		/// <summary>
		/// Export the FieldWorks lexicon into the LIFT file.
		/// The file may, or may not, exist.
		/// </summary>
		/// <returns>True, if the import successful, otherwise false.</returns>
		/// <remarks>
		/// This method calls an overloaded ExportLiftLexicon, which is run in a thread.
		/// </remarks>
		public bool ExportLiftLexicon()
		{
			using (new WaitCursor(_parentForm))
			{
				using (var progressDlg = new ProgressDialogWithTask(_parentForm))
				{
					_progressDlg = progressDlg;
					try
					{
						progressDlg.Title = ResourceHelper.GetResourceString("kstidExportLiftLexicon");
						var outPath = (string)progressDlg.RunTask(true, ExportLiftLexicon, null);
						var retval = (!String.IsNullOrEmpty(outPath));
						if (!retval && CanUndoLiftExport)
						{
							UndoExport();
						}
						return retval;
					}
					catch
					{
						if (CanUndoLiftExport)
						{
							UndoExport();
						}
						return false;
					}
					finally
					{
						_progressDlg = null;
					}
				}
			}
		}