/// <summary>
 /// Step the progress bar by the given amount.
 /// </summary>
 public void Step(int n)
 {
     if (m_progress != null)
     {
         m_progress.Step(n);
     }
 }
Beispiel #2
0
        /// ------------------------------------------------------------------------------------
        /// <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);
        }
Beispiel #3
0
        void OnDumperUpdateProgress(object sender)
        {
            if (m_progressDlg == null)
            {
                return;
            }
            int nMin, nMax;

            m_progressDlg.GetRange(out nMin, out nMax);
            if (m_progressDlg.Position >= nMax)
            {
                m_progressDlg.Position = 0;
            }
            m_progressDlg.Step(1);
            if (m_progressDlg.Position > nMax)
            {
                m_progressDlg.Position = m_progressDlg.Position % nMax;
            }
        }
Beispiel #4
0
        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">
        }
Beispiel #5
0
        /// ------------------------------------------------------------------------------------
        /// <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);
        }
Beispiel #6
0
 private void OnDumperUpdateProgress(object sender)
 {
     Debug.Assert(m_progressDlg != null);
     m_progressDlg.Step(0);
 }
Beispiel #7
0
        /// ------------------------------------------------------------------------------------
        /// <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>
		/// 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);
			}
		}
Beispiel #9
0
		/// ------------------------------------------------------------------------------------
		/// <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>
		/// Updates the verse bridges.
		/// </summary>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns>Always null.</returns>
		/// ------------------------------------------------------------------------------------
		private object UpdateVerseBridges(IAdvInd4 progressDlg, params object[] parameters)
		{
			Debug.Assert(parameters.Length == 1);
			string oldBridge = (string)parameters[0];
			string newBridge = m_scr.Bridge;

			foreach (ScrBook book in m_scr.ScriptureBooksOS)
			{
				progressDlg.Message =
					string.Format(DlgResources.ResourceString("kstidUpdateVerseBridgesInBook"),
					book.Name.UserDefaultWritingSystem);

				foreach (ScrSection section in book.SectionsOS)
					foreach (StTxtPara para in section.ContentOA.ParagraphsOS)
						UpdateVerseBridgesInParagraph(para, oldBridge, newBridge);

				progressDlg.Step(0);
			}

			return null;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Converts the chapter verse numbers.
		/// </summary>
		/// <param name="progressDlg">The progress DLG.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private object ConvertChapterVerseNumbers(IAdvInd4 progressDlg, params object[] parameters)
		{
			char zeroDigit = (m_scr.UseScriptDigits ? (char)m_scr.ScriptDigitZero : '0');

			ILgCharacterPropertyEngine charEngine = m_cache.UnicodeCharProps;

			foreach (ScrBook book in m_scr.ScriptureBooksOS)
			{
				// update the status with the book name.
				progressDlg.Message =
					string.Format(DlgResources.ResourceString("kstidConvertChapterVerseNumbersMessage"),
						book.BestUIName);

				foreach (ScrSection section in book.SectionsOS)
				{
					foreach (StTxtPara para in section.ContentOA.ParagraphsOS)
						ConvertChapterVerseNumbers(para, zeroDigit, charEngine);
				}

				progressDlg.Step(0);
			}

			return null;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Redoes the footnote sequencing.
		/// </summary>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <param name="parameters">The parameters: none</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private object RedoFootnoteSequencing(IAdvInd4 progressDlg, params object[] parameters)
		{
			// for all of the books in the database...
			foreach (ScrBook book in m_scr.ScriptureBooksOS)
			{
				// update the status with the book name.
				progressDlg.Message =
					string.Format(DlgResources.ResourceString("kstidFootnoteResequenceMessage"),
					book.BestUIName);

				// if the book has 26 footnotes or less then the resequence option will
				// not matter.
				if (book.FootnotesOS.Count > 26)
					ScrFootnote.RecalculateFootnoteMarkers(book, 26);

				progressDlg.Step(0);
			}

			return null;
		}
		/// ------------------------------------------------------------------------------------
		/// <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);
		}
Beispiel #14
0
		/// -------------------------------------------------------------------------------------
		/// <summary>
		/// Create a HeaderFooterSet for each HeaderFooterSet node in the given xml node list.
		/// </summary>
		/// <param name="progressDlg">Progress dialog</param>
		/// <param name="hfSetNodes">the xml nodes to read</param>
		/// -------------------------------------------------------------------------------------
		protected void CreateHfSets(IAdvInd4 progressDlg, XmlNodeList hfSetNodes)
		{
			//create each HeaderFooterSet
			foreach (XmlNode hfSetNode in hfSetNodes)
			{
				progressDlg.Step(0);

				IPubHFSet hfSet = m_scr.FindHeaderFooterSetByName(
					GetString(hfSetNode.Attributes, "Name"));
				if (hfSet == null)
					hfSet = m_scr.HeaderFooterSetsOC.Add(new PubHFSet());
				// ENHANCE(TE-5897): If a user has modified a header/footer set, then changes
				// to it in the factory H/F set should not be applied
				ReadHeaderFooterSet(hfSet, hfSetNode, true, true);
			}
		}
Beispiel #15
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create a Publication for each publication node in the given xml node list.
		/// </summary>
		/// <param name="progressDlg">Progress dialog</param>
		/// <param name="publicationNodes">the xml nodes to read</param>
		/// <param name="hfSetNodes">The header/footer set nodes.</param>
		/// ------------------------------------------------------------------------------------
		private void CreatePublications(IAdvInd4 progressDlg, XmlNodeList publicationNodes,
			XmlNodeList hfSetNodes)
		{
			// Remove any previously-defined publications.
			m_scr.PublicationsOC.RemoveAll();

			//create each publication
			foreach (XmlNode publicationNode in publicationNodes)
			{
				progressDlg.Step(0);

				XmlAttributeCollection attributes = publicationNode.Attributes;
				string pubName = GetString(attributes, "Name");

				// Determine the measurement unit to be used for all measurements in this pub
				m_conversion = GetUnitConversion(attributes, "MeasurementUnits", kMpPerInch);

				// Create the new Publication object and set non-variable properties
				Publication pub = (Publication)m_scr.PublicationsOC.Add(new Publication());

				pub.Name = pubName;
				// This seems wrong. We don't know why the Publication.Description is a BigString,
				// but for now we'll build a TsString to populate it.
				ITsStrFactory strFactory = TsStrFactoryClass.Create();
				pub.Description.UnderlyingTsString =
					strFactory.MakeString(GetString(attributes, "Description"),
					m_scr.Cache.DefaultUserWs);
				pub.IsLandscape = GetBoolean(attributes, "IsLandscape", false);
				GetPageHeightAndWidth(attributes, pub,
					publicationNode.SelectSingleNode("SupportedPublicationSizes"));
				pub.PaperHeight = 0;
				pub.PaperWidth = 0;
				pub.GutterMargin = GetMeasurement(attributes, "GutterMargin", 0, m_conversion);
				pub.BindingEdge = GetGutterLoc(attributes, "BindingSide", BindingSide.Left);
				pub.BaseFontSize = GetMeasurement(attributes, "BaseCharSize", 0, 1000);
				// Line spacing < 0 means "exact", which is all we support currently
				pub.BaseLineSpacing = -Math.Abs(GetMeasurement(attributes, "BaseLineSize", 0, 1000));
				pub.SheetLayout = GetSheetLayout(attributes, MultiPageLayout.Simplex);

				XmlNodeList divisionNodes = publicationNode.SelectNodes("Divisions/Division");
				CreateDivisions(pub, divisionNodes, hfSetNodes);
			}
		}
Beispiel #16
0
		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">
		}
Beispiel #17
0
		/// -------------------------------------------------------------------------------------
		/// <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++;
				}
			}
		}
Beispiel #18
0
        /// -------------------------------------------------------------------------------------
        /// <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>
        /// Load the Scr notes categories from the given XML document
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected virtual void CreateScrNoteCategories()
        {
            // Save the previous categories for all of the notes.
            Dictionary <int, List <string> > notesToCategories = CreateNoteToCategoryMap();

            m_scr.NoteCategoriesOA            = new CmPossibilityList();
            m_scr.NoteCategoriesOA.ItemClsid  = CmPossibility.kClassId;
            m_scr.NoteCategoriesOA.WsSelector = LangProject.kwsAnals;
            m_scr.NoteCategoriesOA.Name.SetAlternative(
                TeResourceHelper.GetResourceString("kstidScrNoteCategoriesListName"),
                m_scr.Cache.DefaultUserWs);

            XmlNodeList scrNoteCategoriesList = m_categories.SelectNodes("category");

            string message = null;

            if (m_progressDlg != null)
            {
                m_progressDlg.Title    = TeResourceHelper.GetResourceString("kstidLoadingNoteCategoriesCaption");
                m_progressDlg.Message  = string.Empty;
                m_progressDlg.Position = 0;
                m_progressDlg.SetRange(0, scrNoteCategoriesList.Count);
                message = TeResourceHelper.GetResourceString("kstidLoadNoteCategoryInDBStatus");
            }

            string localeXpath         = "name[@iculocale='" + m_userLocale + "']";
            string fallbackLocaleXpath = "name[@iculocale='" + m_fallbackUserLocale + "']";

            // Load all of the categories from the XML document
            int index = 0;

            foreach (XmlNode noteCategoryNode in scrNoteCategoriesList)
            {
                // Update dialog message.
                if (m_progressDlg != null)
                {
                    XmlNode node = noteCategoryNode.SelectSingleNode(localeXpath);
                    if (node == null)
                    {
                        node = noteCategoryNode.SelectSingleNode(fallbackLocaleXpath);
                    }

                    if (node != null)
                    {
                        m_progressDlg.Message = string.Format(message, node.InnerText);
                    }
                }

                CreateNoteCategory(m_scr.NoteCategoriesOAHvo,
                                   (int)CmPossibilityList.CmPossibilityListTags.kflidPossibilities,
                                   index++, noteCategoryNode);

                if (m_progressDlg != null)
                {
                    m_progressDlg.Step(1);
                }
            }

            m_scr.NoteCategoriesOA.ListVersion =
                new Guid(m_categories.Attributes.GetNamedItem("version").Value);

            // Attempt to map the previous categories of any notes to the new categories.
            ConnectNotesToNewCategories(notesToCategories);
        }
Beispiel #20
0
		/// ------------------------------------------------------------------------------------
		/// <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>
		}
Beispiel #21
0
		/// ------------------------------------------------------------------------------------
		/// <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;
		}
Beispiel #22
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Export the heading and contents of the given section.
		/// </summary>
		/// <param name="progressDlg">The progress dialog.</param>
		/// <param name="section">current section in the book</param>
		/// <param name="outputImplicitChapter">if true, output implicit chapter number</param>
		/// ------------------------------------------------------------------------------------
		protected void ExportSection(IAdvInd4 progressDlg, IScrSection section,
			bool outputImplicitChapter)
		{
			m_currentSectionIsIntro = section.IsIntro;
			m_textOutputBegunInCurrentSection = false;
			BCVRef sectionRefStart = section.VerseRefStart;

			// Pre-process the first paragraph of the section. If this first paragraph begins with
			// a chapter number, we need to export the chapter marker now, before the section marker.
			RefElement runTypeFound;
			ITsString tss = ((StTxtPara)section.ContentOA.ParagraphsOS[0]).Contents.UnderlyingTsString;
			ProcessParaStart(tss, section.VerseRefStart, out runTypeFound);

			// If m_currentChapterRef was not set during ProcessParaStart
			//  (i.e. the section does not begin with a chapter number run)...
			if (m_currentChapterRef == 0)
			{
				// Set the current chapter & verse ref state from the section start ref,
				//  so the vref markers and annotation matching will be correct.
				m_currentChapterRef = sectionRefStart.Chapter;
				m_lastNumericBeginVerseNum = m_lastNumericEndVerseNum = sectionRefStart.Verse;
				m_currentVerseNumString = null;
			}

			// Handle the special output needed if there is an implicit chapter 1.
			// If the section ref start indicates chapter 1, and the section is not an introduction, and
			// the first paragraph does not begin with a chapter run and no chapter has been written ...
			if (runTypeFound != RefElement.Chapter && m_lastChapterWritten == 0 &&
				sectionRefStart.Chapter == 1 && !m_currentSectionIsIntro)
			{
				// If we are to output implicit first chapter number...
				if (outputImplicitChapter)
				{
					// output the "\c 1" and record marker.
					// also see if the chapter we just wrote out needs to get an
					//  implicit first verse marker.
					if (WriteChapterTag(1))
						m_v1NeededForImplicitFirstVerse = ParaBeginsWithImplicitFirstVerse(tss, 0);
				}
				else
				{
					// book has only one chapter; output only the record marker, not a \c.
					m_file.WriteLine(); //always start on new line
					WriteRecordMark(m_currentBookCode, 1);
					m_v1NeededForImplicitFirstVerse = ParaBeginsWithImplicitFirstVerse(tss, 0);
				}
			}

			// Write out the section heading paragraphs
			m_currentParaIsHeading = true;
			foreach (StTxtPara para in section.HeadingOA.ParagraphsOS)
				ExportParagraph(para);

			// Write out the section contents
			m_currentParaIsHeading = false;
			foreach (StTxtPara para in section.ContentOA.ParagraphsOS)
				ExportParagraph(para);

			progressDlg.Step(0);
		}