/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create minimal test data required for every test.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			base.CreateTestData();
			m_helper = new DiscourseTestHelper(Cache);
			m_firstPara = m_helper.FirstPara;
			m_stText = m_firstPara.Owner as IStText;
		}
		/// <summary>
		/// non-undoable task
		/// </summary>
		private void DoSetupFixture()
		{
			var textFactory = Cache.ServiceLocator.GetInstance<ITextFactory>();
			var stTextFactory = Cache.ServiceLocator.GetInstance<IStTextFactory>();
			m_text = textFactory.Create();
			//Cache.LangProject.TextsOC.Add(m_text);
			m_stText = stTextFactory.Create();
			m_text.ContentsOA = m_stText;
			m_para0 = m_stText.AddNewTextPara(null);
			m_para0.Contents = TsStringUtils.MakeTss("Xxxhope xxxthis xxxwill xxxdo. xxxI xxxhope.", Cache.DefaultVernWs);
			m_para1 = m_stText.AddNewTextPara(null);
			m_para1.Contents = TsStringUtils.MakeTss("Xxxcertain xxxto xxxcatch xxxa xxxfrog. xxxCertainly xxxcan. xxxOn xxxLake xxxMonroe.", Cache.DefaultVernWs);
			m_para2 = null;

			using (ParagraphParser pp = new ParagraphParser(Cache))
				foreach (IStTxtPara para in m_stText.ParagraphsOS)
					pp.Parse(para);

			m_expectedAnOcs = new List<AnalysisOccurrence>();
			foreach (IStTxtPara para in m_stText.ParagraphsOS)
				foreach (ISegment seg in para.SegmentsOS)
					for (int i = 0; i < seg.AnalysesRS.Count; i++)
						m_expectedAnOcs.Add(new AnalysisOccurrence(seg, i));

			m_expectedAnOcsPara0 = new List<AnalysisOccurrence>();
			foreach (ISegment seg in m_para0.SegmentsOS)
				for (int i = 0; i < seg.AnalysesRS.Count; i++)
					m_expectedAnOcsPara0.Add(new AnalysisOccurrence(seg, i));
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the ChooseScriptureDialog class.
		/// WARNING: this constructor is called by reflection, at least in the Interlinear
		/// Text DLL. If you change its parameters be SURE to find and fix those callers also.
		/// </summary>
		/// <param name="cache">The cache.</param>
		/// <param name="objList">A list of texts and books to check as an array of hvos</param>
		/// <param name="helpTopicProvider">The help topic provider.</param>
		/// <param name="importer">The Paratext book importer.</param>
		/// ------------------------------------------------------------------------------------
		public FilterTextsDialogTE(FdoCache cache, IStText[] objList,
			IHelpTopicProvider helpTopicProvider, IBookImporter importer)
			: base(cache, objList, helpTopicProvider)
		{
			m_bookImporter = importer;
			using (var progressDlg = new ProgressDialogWithTask(this))
			{
				// This somewhat duplicates some logic in FieldWorks.GetHelpTopicProvider, but it feels
				// wrong to reference the main exe even though I can't find an actual circular dependency.
				// As far as I can discover, the help topic provider is only used if the user has modified
				// TE styles and TE needs to display a dialog about it (possibly because it has loaded a
				// new version of the standard ones?). Anyway, I don't think it will be used at all if TE
				// is not installed, so it should be safe to use the regular FLEx one.
				IHelpTopicProvider helpProvider;
				if (FwUtils.FwUtils.IsTEInstalled)
				{
					helpProvider = (IHelpTopicProvider) DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
						"SIL.FieldWorks.TE.TeHelpTopicProvider");
				}
				else
				{
					helpProvider = (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
						"SIL.FieldWorks.XWorks.LexText.FlexHelpTopicProvider");
				}
				NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
				TeScrInitializer.EnsureMinimalScriptureInitialization(cache, progressDlg,
					helpProvider));
			}
		}
		/// <summary>non-undoable task because setting up an StText must be done in a Unit of Work</summary>
		private void DoSetupFixture()
		{
			m_application = new MockFwXApp(new MockFwManager { Cache = Cache }, null, null);
			var configFilePath = Path.Combine(FwDirectoryFinder.CodeDirectory, m_application.DefaultConfigurationPathname);
			m_window = new MockFwXWindow(m_application, configFilePath);
			((MockFwXWindow)m_window).Init(Cache); // initializes Mediator values
			m_mediator = m_window.Mediator;

			// set up default vernacular ws.
			m_wsDefaultVern = Cache.ServiceLocator.WritingSystemManager.Get("fr");
			m_wsOtherVern = Cache.ServiceLocator.WritingSystemManager.Get("es");
			m_wsEn = Cache.ServiceLocator.WritingSystemManager.Get("en");
			Cache.ServiceLocator.WritingSystems.VernacularWritingSystems.Add(m_wsOtherVern);
			Cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Add(m_wsOtherVern);
			Cache.ServiceLocator.WritingSystems.VernacularWritingSystems.Add(m_wsDefaultVern);
			Cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Insert(0, m_wsDefaultVern);

			// set up an StText with an empty paragraph with default Contents (empty English TsString)
			m_sttNoExplicitWs = Cache.ServiceLocator.GetInstance<IStTextFactory>().Create();
			Cache.ServiceLocator.GetInstance<ITextFactory>().Create().ContentsOA = m_sttNoExplicitWs;
			m_sttNoExplicitWs.AddNewTextPara(null);
			Assert.AreEqual(m_wsEn.Handle, m_sttNoExplicitWs.MainWritingSystem, "Our code counts on English being the defualt WS for very empty texts");

			// set up an StText with an empty paragraph with an empty TsString in a non-default vernacular
			m_sttEmptyButWithWs = Cache.ServiceLocator.GetInstance<IStTextFactory>().Create();
			Cache.ServiceLocator.GetInstance<ITextFactory>().Create().ContentsOA = m_sttEmptyButWithWs;
			m_sttEmptyButWithWs.AddNewTextPara(null);
			((IStTxtPara)m_sttEmptyButWithWs.ParagraphsOS[0]).Contents = TsStringUtils.MakeTss(string.Empty, m_wsOtherVern.Handle);
		}
Example #5
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Use this method to move the entire contents of one StText to an adjacent one.
		/// </summary>
		/// <param name="fromText">StText from which the contents is moved</param>
		/// <param name="toText">StText to which the contents is moved. This StText should be
		/// empty.</param>
		/// <param name="toIsPreceding">Should equal true if the toText preceeds the fromText.
		/// If true, the moved paragraphs will be appended to the toText.
		/// If false, they will be placed at the beginning of the toText.</param>
		/// ------------------------------------------------------------------------------------
		public static void MoveTextContents(IStText fromText, IStText toText, bool toIsPreceding)
		{
			int iLastFromPara = fromText.ParagraphsOS.Count -1;

			if(toIsPreceding)
				MoveWholeParas(fromText, 0, iLastFromPara, toText, toText.ParagraphsOS.Count);
			else
				MoveWholeParas(fromText, 0, iLastFromPara, toText, 0);
		}
		/// <summary>
		///
		/// </summary>
		public override void TestSetup()
		{
			base.TestSetup();

			m_wsVern = Cache.DefaultVernWs;
			m_wsTrans = Cache.DefaultAnalWs;
			m_book = Cache.ServiceLocator.GetInstance<IScrBookFactory>().Create(1);
			m_section = Cache.ServiceLocator.GetInstance<IScrSectionFactory>().Create();
			m_book.SectionsOS.Add(m_section);
			m_section.ContentOA = m_text = Cache.ServiceLocator.GetInstance<IStTextFactory>().Create(); ;
			m_para = m_text.AddNewTextPara(ScrStyleNames.NormalParagraph);
		}
		private void FixtureSetupInternal()
		{
			//IWritingSystem wsEn = Cache.WritingSystemFactory.get_Engine("en");
			// Setup default analysis ws
			//m_wsEn = Cache.ServiceLocator.GetInstance<ILgWritingSystemRepository>().GetObject(wsEn.WritingSystem);
			m_wsVern = Cache.DefaultVernWs;

			m_text = Cache.ServiceLocator.GetInstance<ITextFactory>().Create();
			//Cache.LangProject.TextsOC.Add(m_text);
			m_stText = Cache.ServiceLocator.GetInstance<IStTextFactory>().Create();
			m_text.ContentsOA = m_stText;
			m_para = Cache.ServiceLocator.GetInstance<IScrTxtParaFactory>().CreateWithStyle(m_stText, ScrStyleNames.NormalParagraph);
		}
Example #8
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public FwMultiParaTextBox(IStText stText, IVwStylesheet styleSheet)
		{
			// Because a panel only allows single borders that are black, we'll
			// set it's border to none and manage the border ourselves.
			base.BorderStyle = BorderStyle.None;

			BorderStyle = (Application.RenderWithVisualStyles ?
				BorderStyle.FixedSingle : BorderStyle.Fixed3D);

			m_textBox = new InternalFwMultiParaTextBox(stText, styleSheet);
			m_textBox.Dock = DockStyle.Fill;
			Controls.Add(m_textBox);
		}
Example #9
0
        public static LfMultiParagraph GetCustomStTextValuesAsLfMultiPara(IStText obj, int flid,
			IWritingSystemManager wsManager, IFwMetaDataCache metaDataCacheAccessor, int fallbackWs)
        {
            if (obj == null || obj.ParagraphsOS == null || obj.ParagraphsOS.Count == 0) return null;
            var result = new LfMultiParagraph();
            result.Paragraphs = obj.ParagraphsOS.OfType<IStTxtPara>().Where(para => para.Contents != null).Select(para => FdoParaToLfPara(para, wsManager)).ToList();
            // StText objects in FDO have a single primary writing system, unlike MultiString or MultiUnicode objects
            int fieldWs = metaDataCacheAccessor.GetFieldWs(flid);
            string wsStr = wsManager.GetStrFromWs(fieldWs);
            if (wsStr == null) wsStr = wsManager.GetStrFromWs(fallbackWs);
            result.InputSystem = wsStr;
            return result;
        }
Example #10
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create test data for tests.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_servloc = Cache.ServiceLocator;
			m_text = AddInterlinearTextToLangProj("My Interlinear Text");
			m_stTextPara = AddParaToInterlinearTextContents(m_text, "Here is a sentence I can chart.");
			m_stText = m_text.ContentsOA;
			m_tssFact = Cache.TsStrFactory;
			m_rowFact = m_servloc.GetInstance<IConstChartRowFactory>();
			m_wordGrpFact = m_servloc.GetInstance<IConstChartWordGroupFactory>();
			m_possFact = m_servloc.GetInstance<ICmPossibilityFactory>();
			m_wfiFact = m_servloc.GetInstance<IWfiWordformFactory>();
			m_mtMrkrFact = m_servloc.GetInstance<IConstChartMovedTextMarkerFactory>();
			m_clsMrkrFact = m_servloc.GetInstance<IConstChartClauseMarkerFactory>();
		}
Example #11
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Shows the specified comment text for the specified cell in the tooltip.
		/// </summary>
		/// <param name="comment">The comment to display in the tooltip.</param>
		/// <param name="cell">The status cell whose comment is being displayed.</param>
		/// ------------------------------------------------------------------------------------
		public void Show(IStText comment, DataGridViewCell cell)
		{
			Debug.Assert(cell != null);
			Debug.Assert(cell.DataGridView != null);

			MakeTextBox(comment);

			Rectangle rcCell = cell.DataGridView.GetCellDisplayRectangle(
				cell.ColumnIndex, cell.RowIndex, true);

			// Subtract one from the bottom so the tooltip
			// covers the grey border between grid rows.
			Point pt = new Point(rcCell.Right - Width, rcCell.Bottom - 1);
			base.Show(cell.DataGridView, pt);
		}
Example #12
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a text for testing.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void CreateTestText()
		{
			m_txt = m_servLoc.GetInstance<ITextFactory>().Create();
			//Cache.LangProject.TextsOC.Add(m_txt);
			m_stTxt = m_servLoc.GetInstance<IStTextFactory>().Create();
			m_txt.ContentsOA = m_stTxt;
			m_txtPara = m_txt.ContentsOA.AddNewTextPara(null);

			// 0         1         2         3         4
			// 0123456789012345678901234567890123456789012
			// This is a test string for CopyObject tests.

			int hvoVernWs = Cache.DefaultVernWs;
			m_txtPara.Contents = TsStringUtils.MakeTss("This is a test string for CopyObject tests.", hvoVernWs);
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a text for testing.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void CreateTestText()
		{
			m_txt = m_servLoc.GetInstance<ITextFactory>().Create();
			//Cache.LangProject.TextsOC.Add(m_txt);
			m_possTagList = Cache.LangProject.GetDefaultTextTagList();
			m_stTxt = m_servLoc.GetInstance<IStTextFactory>().Create();
			m_txt.ContentsOA = m_stTxt;
			m_txtPara = m_txt.ContentsOA.AddNewTextPara(null);

			// 0    1  2 3    4      5   6                        7    8
			// This is a test string for ReferenceAdjusterService tests.

			var hvoVernWs = Cache.DefaultVernWs;
			m_txtPara.Contents = TsStringUtils.MakeTss("This is a test string for ReferenceAdjusterService tests.", hvoVernWs);
			ParseText();
		}
Example #14
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates dummy paras.
        /// </summary>
        /// <returns>An array of paras</returns>
        /// ------------------------------------------------------------------------------------
        public static IScrTxtPara[] CreateDummyParas(int count, FdoCache cache)
        {
            IText text = cache.ServiceLocator.GetInstance <ITextFactory>().Create();
            //cache.LangProject.TextsOC.Add(text);
            IStText stText = cache.ServiceLocator.GetInstance <IStTextFactory>().Create();

            text.ContentsOA = stText;

            IScrTxtPara[] paras = new IScrTxtPara[count];
            for (int i = 0; i < paras.Length; i++)
            {
                paras[i] = cache.ServiceLocator.GetInstance <IScrTxtParaFactory>().CreateWithStyle(
                    stText, ScrStyleNames.NormalParagraph);
            }

            return(paras);
        }
Example #15
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Makes the text box containing the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// ------------------------------------------------------------------------------------
        private void MakeTextBox(IStText text)
        {
            if (m_resolutionText != null)
            {
                Controls.Remove(m_resolutionText);
                m_resolutionText.Dispose();
            }

            Size                         = new Size(175, 1);
            m_resolutionText             = new FwMultiParaTextBox(text, m_stylesheet);
            m_resolutionText.Dock        = DockStyle.Fill;
            m_resolutionText.BackColor   = SystemColors.Info;
            m_resolutionText.BorderStyle = BorderStyle.None;
            m_resolutionText.ReadOnly    = true;
            m_resolutionText.AutoScroll  = false;
            Controls.Add(m_resolutionText);
        }
Example #16
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates a test footnote in the given location.
        /// </summary>
        /// <param name="book">The Scripture book.</param>
        /// <param name="text">The StText containing iPara.</param>
        /// <param name="iPara">The index of the Content paragraph where the footnote is to be
        /// inserted.</param>
        /// <param name="iFootnote">The index of the footnote to create.</param>
        /// <param name="ichOrc">The charaacter offset in the paragraph where the ORC (marker)
        /// is to be inserted.</param>
        /// <param name="sStyle">The style name (which determines whether it is a general
        /// footnote or a cross-reference).</param>
        /// <param name="fMakeOrphan">Flag indicating whether to make this footnote into an
        /// "orphan" by clearing the properties of the ORC.</param>
        /// ------------------------------------------------------------------------------------
        private IStFootnote CreateFootnote(IScrBook book, IStText text, int iPara, int iFootnote,
                                           int ichOrc, string sStyle, bool fMakeOrphan)
        {
            IScrTxtPara scrPara  = (IScrTxtPara)text.ParagraphsOS[iPara];
            IStFootnote footnote = InsertTestFootnote(book, scrPara, iFootnote, ichOrc);
            IStTxtPara  fnPara   = AddParaToMockedText(footnote, sStyle);

            AddRunToMockedPara(fnPara, "Footnote " + Guid.NewGuid(), Cache.DefaultVernWs);

            if (fMakeOrphan)
            {
                ITsStrBldr bldr = scrPara.Contents.GetBldr();
                bldr.SetProperties(ichOrc, ichOrc + 1, TsStringUtils.PropsForWs(Cache.DefaultVernWs));
                scrPara.Contents = bldr.GetString();
            }
            return(footnote);
        }
Example #17
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Makes the text box containing the specified text.
		/// </summary>
		/// <param name="text">The text.</param>
		/// ------------------------------------------------------------------------------------
		private void MakeTextBox(IStText text)
		{
			if (m_resolutionText != null)
			{
				Controls.Remove(m_resolutionText);
				m_resolutionText.Dispose();
			}

			Size = new Size(175, 1);
			m_resolutionText = new FwMultiParaTextBox(text, m_stylesheet);
			m_resolutionText.Dock = DockStyle.Fill;
			m_resolutionText.BackColor = SystemColors.Info;
			m_resolutionText.BorderStyle = BorderStyle.None;
			m_resolutionText.ReadOnly = true;
			m_resolutionText.AutoScroll = false;
			Controls.Add(m_resolutionText);
		}
Example #18
0
        /// -----------------------------------------------------------------------------------
        /// <summary>
        /// In certain contexts, check the given paragraph to see if it is empty. If so,
        /// insert a user prompt.
        /// </summary>
        /// <param name="vwenv">view environment</param>
        /// <param name="paraHvo">HVO of the paragraph to be displayed</param>
        /// <returns>true if an empty string was substituted for missing/empty StText</returns>
        /// -----------------------------------------------------------------------------------
        protected override bool InsertParaContentsUserPrompt(IVwEnv vwenv, int paraHvo)
        {
            Debug.Assert(!DisplayTranslation);

            // No user prompt in any of these conditions
            IStTxtPara para = m_cache.ServiceLocator.GetInstance <IStTxtParaRepository>().GetObject(paraHvo);

            if (!(para is IScrTxtPara) ||
                !Options.ShowEmptyParagraphPromptsSetting ||                 // tools options setting
                m_target == LayoutViewTarget.targetPrint ||                 // any print layout view
                m_updatedPrompts.Contains(para.Hvo))                    // user interaction has updated prompt
            {
                return(false);
            }

            // User prompt is only for title & heading paras
            IStText text = (IStText)para.Owner;             // para owner

            if (text.OwningFlid != ScrBookTags.kflidTitle &&
                text.OwningFlid != ScrSectionTags.kflidHeading)
            {
                return(false);
            }

            int paraCount = text.ParagraphsOS.Count;

            Debug.Assert(paraCount != 0,
                         "We shouldn't come here if StText doesn't contain any paragraphs");
            // By design, if there is more than one para, don't display the user prompt.
            if (paraCount != 1)
            {
                return(false);
            }

            // If first para is empty, insert user prompt for paragraph content
            if (text[0].Contents.Text == null)
            {
                vwenv.NoteDependency(new int[] { para.Hvo },
                                     new int[] { StTxtParaTags.kflidContents }, 1);
                vwenv.AddProp(SimpleRootSite.kTagUserPrompt, this, text.OwningFlid);
                return(true);
            }

            return(false);
        }
Example #19
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Use this method to move part of one StText to an adjacent one when the fromText
        /// must be left with at least one empty paragraph.
        /// </summary>
        /// <param name="fromText">StText from which the contents is moved</param>
        /// <param name="toText">StText to which the contents is moved. This StText should be
        /// empty.</param>
        /// <param name="divIndex">Index of last whole paragraph to be moved</param>
        /// <param name="toIsPreceding">Should equal true if the toText preceeds the fromText.
        /// If true, the moved paragraphs will be appended to the toText.
        /// If false, they will be placed at the beginning of the toText.</param>
        /// ------------------------------------------------------------------------------------
        public static void MoveTextParagraphsAndFixEmpty(IStText fromText, IStText toText,
                                                         int divIndex, bool toIsPreceding)
        {
            // Save the paragraph props. We might need it to create an empty paragraph.
            ITsTextProps paraPropsSave =
                ((StTxtPara)fromText.ParagraphsOS[divIndex]).StyleRules;

            MoveTextParagraphs(fromText, toText, divIndex, toIsPreceding);

            // If fromText is now empty, create a new empty paragraph.
            if (fromText.ParagraphsOS.Count == 0)
            {
                string styleName =
                    paraPropsSave.GetStrPropValue((int)FwTextPropType.ktptNamedStyle);
                StTxtParaBldr.CreateEmptyPara(fromText.Cache, fromText.Hvo,
                                              styleName, fromText.Cache.DefaultVernWs);
            }
        }
Example #20
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Use this method to move part of one StText to an adjacent one.
        /// </summary>
        /// <param name="fromText">StText from which the contents is moved</param>
        /// <param name="toText">StText to which the contents is moved. This StText should be
        /// empty.</param>
        /// <param name="divIndex">Index of last whole paragraph to be moved</param>
        /// <param name="toIsPreceding">Should equal true if the toText preceeds the fromText.
        /// If true, the moved paragraphs will be appended to the toText.
        /// If false, they will be placed at the beginning of the toText.</param>
        /// ------------------------------------------------------------------------------------
        public static void MoveTextParagraphs(IStText fromText, IStText toText,
                                              int divIndex, bool toIsPreceding)
        {
            int initParaCount = fromText.ParagraphsOS.Count;

            Debug.Assert(divIndex >= 0 && divIndex <= initParaCount - 1);

            if (toIsPreceding)
            {
                //Move initial paragraphs up, appending
                MoveWholeParas(fromText, 0, divIndex, toText, toText.ParagraphsOS.Count);
            }
            else
            {
                //Move final paragraphs down, prepending
                MoveWholeParas(fromText, divIndex, initParaCount - 1, toText, 0);
            }
        }
Example #21
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Adds an empty chart on the specified text.
        /// </summary>
        /// <param name="name">Chart name.</param>
        /// <param name="stText">Chart is BasedOn this text.</param>
        /// ------------------------------------------------------------------------------------
        private IDsConstChart AddChartToLangProj(string name, IStText stText)
        {
            ILcmServiceLocator servloc = Cache.ServiceLocator;
            IDsConstChart      chart   = servloc.GetInstance <IDsConstChartFactory>().Create();

            if (Cache.LangProject.DiscourseDataOA == null)
            {
                Cache.LangProject.DiscourseDataOA = servloc.GetInstance <IDsDiscourseDataFactory>().Create();
            }

            Cache.LangProject.DiscourseDataOA.ChartsOC.Add(chart);

            // Setup the new chart
            chart.Name.AnalysisDefaultWritingSystem = TsStringUtils.MakeString(name, Cache.DefaultAnalWs);
            chart.BasedOnRA = stText;

            return(chart);            // This chart has no template or rows, so far!!
        }
Example #22
0
        /// <summary>
        /// Add a segment of text to the paragraph and return the resulting segment.
        /// Note that this depends on the code that automatically reparses the paragraph,
        /// so the strings added must really produce segments.
        /// </summary>
        private ISegment MakeSegment(IStText text, string contents)
        {
            var para   = (IStTxtPara)text.ParagraphsOS[0];
            int length = para.Contents.Length;

            if (length == 0)
            {
                para.Contents = Cache.TsStrFactory.MakeString(contents, Cache.DefaultVernWs);
            }
            else
            {
                var bldr = para.Contents.GetBldr();
                bldr.Replace(length, length, " " + contents, null);
                para.Contents = bldr.GetString();
            }
            var seg = para.SegmentsOS[para.SegmentsOS.Count - 1];

            return(seg);
        }
Example #23
0
        /// <summary>
        /// Executes in two distinct scenarios.
        ///
        /// 1. If disposing is true, the method has been called directly
        /// or indirectly by a user's code via the Dispose method.
        /// Both managed and unmanaged resources can be disposed.
        ///
        /// 2. If disposing is false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference (access)
        /// other managed objects, as they already have been garbage collected.
        /// Only unmanaged resources can be disposed.
        /// </summary>
        /// <param name="disposing"></param>
        /// <remarks>
        /// If any exceptions are thrown, that is fine.
        /// If the method is being done in a finalizer, it will be ignored.
        /// If it is thrown by client code calling Dispose,
        /// it needs to be handled by fixing the bug.
        ///
        /// If subclasses override this method, they should call the base implementation.
        /// </remarks>
        protected override void Dispose(bool disposing)
        {
            //Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
            // Must not be run more than once.
            if (IsDisposed)
            {
                return;
            }

            if (disposing)
            {
                // Dispose managed resources here.
            }

            // Dispose unmanaged resources here, whether disposing is true or false.
            m_text = null;

            base.Dispose(disposing);
        }
        public void CreateBtWhenBookTitleParagraphIsAdded()
        {
            // add title paragraphs
            IStText    title = AddTitleToMockedBook(m_book, "Genesis or whatever");
            IStTxtPara para2 = AddParaToMockedText(title, "An anthology");

            AddParaToMockedText(title, "Written by God");
            AddParaToMockedText(title, "For Israel and everyone else");

            // Make sure the back translations got created.
            ICmTranslation bt = para2.GetBT();

            Assert.IsNotNull(bt);
            Assert.IsNull(bt.Status.AnalysisDefaultWritingSystem.Text);

            bt = para2.GetBT();
            Assert.IsNotNull(bt);
            Assert.IsNull(bt.Status.AnalysisDefaultWritingSystem.Text);
        }
Example #25
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected override void CreateTestData()
        {
            m_inMemoryCache.InitializeWritingSystemEncodings();

            m_currentText = m_inMemoryCache.CreateArbitraryStText();
            StTxtPara para = m_inMemoryCache.AddParaToMockedText(m_currentText.Hvo, "Normal");

            m_inMemoryCache.AddRunToMockedPara(para, "1", "CharacterStyle1");
            m_inMemoryCache.AddRunToMockedPara(para, "1", "CharacterStyle2");
            m_inMemoryCache.AddRunToMockedPara(para, "This text has no char style.", null);
            m_currentFootnotesOS = m_inMemoryCache.CreateArbitraryFootnoteSequence(m_currentText);

            m_archivedText = m_inMemoryCache.CreateArbitraryStText();
            para           = m_inMemoryCache.AddParaToMockedText(m_archivedText.Hvo, "Normal");
            m_inMemoryCache.AddRunToMockedPara(para, "1", "CharacterStyle1");
            m_inMemoryCache.AddRunToMockedPara(para, "1", "CharacterStyle2");
            m_inMemoryCache.AddRunToMockedPara(para, "This is the previous version of the text.", null);
            m_archivedFootnotesOS = m_inMemoryCache.CreateArbitraryFootnoteSequence(m_archivedText);
        }
Example #26
0
        /// <summary>
        /// non-undoable task
        /// </summary>
        private void DoSetupFixture()
        {
            var textFactory   = Cache.ServiceLocator.GetInstance <ITextFactory>();
            var stTextFactory = Cache.ServiceLocator.GetInstance <IStTextFactory>();

            m_text = textFactory.Create();
            //Cache.LangProject.TextsOC.Add(m_text);
            m_stText          = stTextFactory.Create();
            m_text.ContentsOA = m_stText;
            m_para0           = m_stText.AddNewTextPara(null);
            m_para0.Contents  = TsStringUtils.MakeString("Xxxhope xxxthis xxxwill xxxdo. xxxI xxxhope.", Cache.DefaultVernWs);
            m_para1           = m_stText.AddNewTextPara(null);
            m_para1.Contents  = TsStringUtils.MakeString("Xxxcertain xxxto xxxcatch xxxa xxxfrog. xxxCertainly xxxcan. xxxOn xxxLake xxxMonroe.", Cache.DefaultVernWs);
            m_para2           = null;

            using (ParagraphParser pp = new ParagraphParser(Cache))
                foreach (IStTxtPara para in m_stText.ParagraphsOS)
                {
                    pp.Parse(para);
                }

            m_expectedAnOcs = new List <AnalysisOccurrence>();
            foreach (IStTxtPara para in m_stText.ParagraphsOS)
            {
                foreach (ISegment seg in para.SegmentsOS)
                {
                    for (int i = 0; i < seg.AnalysesRS.Count; i++)
                    {
                        m_expectedAnOcs.Add(new AnalysisOccurrence(seg, i));
                    }
                }
            }

            m_expectedAnOcsPara0 = new List <AnalysisOccurrence>();
            foreach (ISegment seg in m_para0.SegmentsOS)
            {
                for (int i = 0; i < seg.AnalysesRS.Count; i++)
                {
                    m_expectedAnOcsPara0.Add(new AnalysisOccurrence(seg, i));
                }
            }
        }
Example #27
0
        public void FindNextBackTrans_SectionContentToNextBook_TitleFinished()
        {
            // add new book
            IScrBook    book    = AddBookToMockedScripture(3, "Leviticus");
            IStText     text    = AddTitleToMockedBook(book, "Title for Leviticus");
            IScrSection section = AddSectionToMockedBook(book);

            AddSectionHeadParaToSection(section, "Heading", ScrStyleNames.SectionHead);
            // add BT for last para of first book
            IScrTxtPara para = (IScrTxtPara)m_exodus.SectionsOS[2].ContentOA[0];

            AddBtToMockedParagraph(para, Cache.DefaultAnalWs);

            // add BT for title para of the last book
            para = (IScrTxtPara)text[0];
            ICmTranslation trans = AddBtToMockedParagraph(para,
                                                          Cache.DefaultAnalWs);

            m_draftView.SetTransStatus(trans, BackTranslationStatus.Finished);

            // add BT for the first section head of the last book
            para = (IScrTxtPara)book.SectionsOS[0].HeadingOA[0];
            AddBtToMockedParagraph(para, Cache.DefaultAnalWs);
            m_draftView.RefreshDisplay();

            int iLastSectionInExodus = m_exodus.SectionsOS.Count - 1;

            m_draftView.SetInsertionPoint(ScrSectionTags.kflidContent,
                                          0, iLastSectionInExodus,
                                          m_exodus.SectionsOS[iLastSectionInExodus].ContentOA.ParagraphsOS.Count - 1);

            m_draftView.CallNextUnfinishedBackTrans();
            SelectionHelper helper = m_draftView.EditingHelper.CurrentSelection;

            Assert.AreEqual(0, helper.IchAnchor);
            Assert.AreEqual(1, m_draftView.TeEditingHelper.BookIndex);
            Assert.AreEqual(0, m_draftView.TeEditingHelper.SectionIndex);
            Assert.AreEqual(0, m_draftView.ParagraphIndex);
            Assert.AreEqual(ScrSectionTags.kflidHeading,
                            m_draftView.EditingHelper.CurrentSelection.LevelInfo[2].tag);
            Assert.IsFalse(m_draftView.TeEditingHelper.InBookTitle);
        }
Example #28
0
        private IStText MakeText(ITsString[] paragraphs, string[] styles)
        {
            var text = Cache.ServiceLocator.GetInstance <ITextFactory>().Create();
            //Cache.LangProject.TextsOC.Add(text);
            IStText sttext = Cache.ServiceLocator.GetInstance <IStTextFactory>().Create();

            text.ContentsOA = sttext;
            var paraFactory = Cache.ServiceLocator.GetInstance <IStTxtParaFactory>();

            for (int i = 0; i < paragraphs.Length; i++)
            {
                var para = paraFactory.Create();
                sttext.ParagraphsOS.Add(para);
                para.Contents = paragraphs[i];
                var bldr = TsStringUtils.MakePropsBldr();
                bldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, styles[i]);
                para.StyleRules = bldr.GetTextProps();
            }
            return(sttext);
        }
        private void GetTextProps()
        {
            IStText txt = CmObject.CreateFromDBObject(m_cache, m_hvoRoot) as IStText;

            if (txt != null)
            {
                int hvoOwner = txt.OwnerHVO;
                m_text = CmObject.CreateFromDBObject(m_cache, hvoOwner) as FDO.IText;
                if (m_text != null)
                {
                    m_tssTextName         = m_text.Name.BestVernacularAnalysisAlternative;
                    m_tssTextAbbreviation = m_text.Abbreviation.BestVernacularAnalysisAlternative;
                }
                else if (SIL.FieldWorks.FDO.Scripture.Scripture.IsResponsibleFor(txt as SIL.FieldWorks.FDO.Cellar.StText))
                {
                    m_tssTextName = txt.ShortNameTSS;
                    // sorry, no abbreviation...
                }
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Makes a selection from one paragraph to another paragraph.
        /// NOTE: This selects the entirety of both paragraphs.
        /// </summary>
        /// <param name="para1">The first paragraph.</param>
        /// <param name="para2">The last paragraph (could be same as first).</param>
        /// <param name="view">DraftView or FootnoteView</param>
        /// ------------------------------------------------------------------------------------
        private SelectionHelper MakeSelection(IStTxtPara para1, IStTxtPara para2, IVwRootSite view)
        {
            Debug.Assert(view != null);
            Debug.Assert(para1.OwningFlid == StTextTags.kflidParagraphs);
            Debug.Assert(para2.OwningFlid == StTextTags.kflidParagraphs);

            SelectionHelper helper = new SelectionHelper();
            IStText         text1  = (IStText)para1.Owner;
            IStText         text2  = (IStText)para2.Owner;

            // build the anchor part of the selection
            SetupSelectionFor(helper, text1, para1, SelectionHelper.SelLimitType.Anchor,
                              (FwRootSite)view);

            // build the end part of the selection
            SetupSelectionFor(helper, text2, para2, SelectionHelper.SelLimitType.End,
                              (FwRootSite)view);
            helper.IchAnchor = 0;
            helper.IchEnd    = para2.Contents.Length;

            return(helper);
        }
Example #31
0
        public static LfMultiParagraph GetCustomStTextValuesAsLfMultiPara(IStText obj, int flid,
                                                                          WritingSystemManager wsManager, IFwMetaDataCache metaDataCacheAccessor, int fallbackWs)
        {
            if (obj == null || obj.ParagraphsOS == null || obj.ParagraphsOS.Count == 0)
            {
                return(null);
            }
            var result = new LfMultiParagraph();

            // result.Guid = obj.Guid;  // TODO: See if this would break LF PHP
            result.Paragraphs = obj.ParagraphsOS.OfType <IStTxtPara>().Where(para => para.Contents != null).Select(para => LcmParaToLfPara(para, wsManager)).ToList();
            // StText objects in LCM have a single primary writing system, unlike MultiString or MultiUnicode objects
            int    fieldWs = metaDataCacheAccessor.GetFieldWs(flid);
            string wsStr   = wsManager.GetStrFromWs(fieldWs);

            if (wsStr == null)
            {
                wsStr = wsManager.GetStrFromWs(fallbackWs);
            }
            result.InputSystem = wsStr;
            return(result);
        }
Example #32
0
 public void Init(Mediator mediator, IStText text, int ws)
 {
     CheckDisposed();
     Mediator   = mediator;
     Cache      = (FdoCache)mediator.PropertyTable.GetValue("cache");
     StyleSheet = FontHeightAdjuster.StyleSheetFromMediator(m_mediator);
     m_text     = text;
     m_vc       = new StVc("Normal", ws)
     {
         Cache = m_fdoCache, Editable = true
     };
     DoSpellCheck = true;
     if (m_rootb == null)
     {
         MakeRoot();
     }
     else if (m_text != null)
     {
         m_rootb.SetRootObject(m_text.Hvo, m_vc, (int)StTextFrags.kfrText, m_styleSheet);
         m_rootb.Reconstruct();
     }
 }
Example #33
0
        /// <summary>
        /// Return an index we can use to order StTexts in Scripture.
        /// Take the book index * 10,000.
        /// if not in the title, add (section index + 1)*2.
        /// If in contents add 1.
        /// </summary>
        /// <param name="hvoText"></param>
        /// <returns></returns>
        int TextPosition(IStText text)
        {
            ICmObject owner = text.Owner;
            int       flid  = text.OwningFlid;

            if (flid != ScrSectionTags.kflidContent &&
                flid != ScrSectionTags.kflidHeading &&
                flid != ScrBookTags.kflidTitle)
            {
                return(-1);
            }
            if (flid == ScrBookTags.kflidTitle)
            {
                return(BookPosition((IScrBook)owner));
            }
            var section = (IScrSection)owner;
            var book    = (IScrBook)section.Owner;

            return(BookPosition(book)
                   + section.IndexInOwner * 2 + 2
                   + (flid == ScrSectionTags.kflidContent ? 1 : 0));
        }
		/// <summary>
		/// non-undoable task
		/// </summary>
		private void DoSetupFixture()
		{
			// setup default vernacular ws.
			IWritingSystem wsXkal = Cache.ServiceLocator.WritingSystemManager.Set("qaa-x-kal");
			wsXkal.DefaultFontName = "Times New Roman";
			Cache.ServiceLocator.WritingSystems.VernacularWritingSystems.Add(wsXkal);
			Cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Insert(0, wsXkal);
			var textFactory = Cache.ServiceLocator.GetInstance<ITextFactory>();
			var stTextFactory = Cache.ServiceLocator.GetInstance<IStTextFactory>();
			m_text0 = textFactory.Create();
			//Cache.LangProject.TextsOC.Add(m_text0);
			m_stText0 = stTextFactory.Create();
			m_text0.ContentsOA = m_stText0;
			m_para0_0 = m_stText0.AddNewTextPara(null);
			m_para0_0.Contents = TsStringUtils.MakeTss("Xxxhope xxxthis xxxwill xxxdo. xxxI xxxhope.", wsXkal.Handle);

			InterlinMaster.LoadParagraphAnnotationsAndGenerateEntryGuessesIfNeeded(m_stText0, false);
			// paragraph 0_0 simply has wordforms as analyses
			foreach (var occurence in SegmentServices.GetAnalysisOccurrences(m_para0_0))
				if (occurence.HasWordform)
					m_analysis_para0_0.Add(new AnalysisTree(occurence.Analysis));

		}
		/// <summary>
		/// Return an index we can use to order StTexts in Scripture.
		/// Take the book index * 10,000.
		/// if not in the title, add (section index + 1)*2.
		/// If in contents add 1.
		/// </summary>
		/// <param name="hvoText"></param>
		/// <returns></returns>
		int TextPosition(IStText text)
		{
			ICmObject owner = text.Owner;
			int flid = text.OwningFlid;
			if (flid != ScrSectionTags.kflidContent &&
				flid != ScrSectionTags.kflidHeading
				&& flid != ScrBookTags.kflidTitle)
			{
				return -1;
			}
			if (flid == ScrBookTags.kflidTitle)
				return BookPosition((IScrBook)owner);
			var section = (IScrSection)owner;
			var book = (IScrBook)section.Owner;
			return BookPosition(book)
				   + section.IndexInOwner * 2 + 2
				   + (flid == ScrSectionTags.kflidContent ? 1 : 0);
		}
		private int AddBefore(int index, IStText item)
		{
			if (item == null)
				return index; // nothing to add
			if (index == 0 || m_scriptureTexts[index - 1] != item)
			{
				// Not present, add it.
				m_scriptureTexts.Insert(index, item);
				return index; // no change, things moved up.
			}
			return index - 1; // next earlier item goes before one already present.
		}
		private int AddAfter(int indexAfter, IStText item)
		{
			if (item == null)
				return indexAfter; // nothing to add
			if (indexAfter >= m_scriptureTexts.Count - 1 || m_scriptureTexts[indexAfter] != item)
			{
				// Not already present, add it.
				m_scriptureTexts.Insert(indexAfter, item);
			}
			return indexAfter + 1; // in either case next text goes after this one.
		}
		public bool IsInterestingText(IStText text)
		{
			if (m_interestingTests == null)
				m_interestingTests = new HashSet<IStText>(InterestingTexts);
			return m_interestingTests.Contains(text);
		}
		/// <summary>
		/// This is invoked when TE (or some other program) invokes a link, typically to a Scripture Section text not in our filter.
		/// If possible, add it to the filter and return true. Also add any other sections in the same chapter.
		/// Also when jumping from Notebook to a text that is excluded.
		/// Todo JohnT: get it called from TE and test it; not currently used by TE (ported from parts of old InterlinearTextsVirtualHandler)
		/// </summary>
		public bool AddChapterToInterestingTexts(IStText newText)
		{
			int oldCount = m_scriptureTexts.Count;
			int targetPosition = TextPosition(newText);
			if (targetPosition < 0)
			{
				var excludedCoreTextIdList = ExcludedCoreTextIdList();
				if (newText.Owner is IText && excludedCoreTextIdList.Contains(newText.Guid))
				{
					CoreTexts.Add(newText);
					if (m_interestingTests != null)
						m_interestingTests.Add(newText);
					excludedCoreTextIdList.Remove(newText.Guid);
					UpdateExcludedCoreTexts(excludedCoreTextIdList);
					RaiseInterestingTextsChanged(CoreTexts.Count - 1, 1, 0);
					return true; // added sucessfully
				}
				return false; // not a text in current Scripture.
			}
			int index;
			for (index = 0; index < m_scriptureTexts.Count; index++)
			{
				if (TextPosition(m_scriptureTexts[index]) > targetPosition)
				{
					break;
				}
			}
			m_scriptureTexts.Insert(index, newText);
			// Also insert the other text in the same section
			var sec = newText.Owner as IScrSection;
			if (sec != null) // not a book title
			{
				if (newText == sec.ContentOA && sec.HeadingOA != null)
				{
					if (index == 0 || m_scriptureTexts[index - 1] != sec.HeadingOA)
						m_scriptureTexts.Insert(index, sec.HeadingOA);
					else
						index--; // move index to point at heading
				}
				else if (sec.ContentOA != null)
				{
					if (index >= m_scriptureTexts.Count - 1 || m_scriptureTexts[index + 1] != sec.ContentOA)
						m_scriptureTexts.Insert(index + 1, sec.ContentOA);
				}
				// At this point the heading and contents of the section for the inserted text
				// are at index. We look for adjacent sections in the same chapter and if necessary
				// add them too.
				int indexAfter = index + 1;
				if (sec.ContentOA != null && sec.HeadingOA != null)
					indexAfter++;
				// It would be nicer to use ScrReference, but not worth adding a whole project reference.
				int chapMax = sec.VerseRefMax / 1000;
				int chapMin = sec.VerseRefMin / 1000;
				var book = (IScrBook)sec.Owner;
				int csec = book.SectionsOS.Count;
				int isecCur = sec.IndexInOwner;
				for (int isec = isecCur + 1; isec < csec; isec++)
				{
					IScrSection secNext = book.SectionsOS[isec];
					if (secNext.VerseRefMin / 1000 != chapMax)
						break; // different chapter.
					indexAfter = AddAfter(indexAfter, secNext.HeadingOA);
					indexAfter = AddAfter(indexAfter, secNext.ContentOA);
				}
				for (int isec = isecCur - 1; isec >= 0; isec--)
				{
					IScrSection secPrev = book.SectionsOS[isec];
					if (secPrev.VerseRefMax / 1000 != chapMin)
						break;
					index = AddBefore(index, secPrev.ContentOA);
					index = AddBefore(index, secPrev.HeadingOA);
				}
			}
			// We could get fancy and try to figure the exact range that changed, but this is close enough.
			RaiseInterestingTextsChanged(CoreTexts.Count, m_scriptureTexts.Count, oldCount);
			return true;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a test footnote in the given location.
		/// </summary>
		/// <param name="book">The Scripture book.</param>
		/// <param name="text">The StText containing iPara.</param>
		/// <param name="iPara">The index of the Content paragraph where the footnote is to be
		/// inserted.</param>
		/// <param name="iFootnote">The index of the footnote to create.</param>
		/// <param name="ichOrc">The charaacter offset in the paragraph where the ORC (marker)
		/// is to be inserted.</param>
		/// <param name="sStyle">The style name (which determines whether it is a general
		/// footnote or a cross-reference).</param>
		/// <param name="fMakeOrphan">Flag indicating whether to make this footnote into an
		/// "orphan" by clearing the properties of the ORC.</param>
		/// ------------------------------------------------------------------------------------
		private IStFootnote CreateFootnote(IScrBook book, IStText text, int iPara, int iFootnote,
			int ichOrc, string sStyle, bool fMakeOrphan)
		{
			IScrTxtPara scrPara = (IScrTxtPara)text.ParagraphsOS[iPara];
			IStFootnote footnote = InsertTestFootnote(book, scrPara, iFootnote, ichOrc);
			IStTxtPara fnPara = AddParaToMockedText(footnote, sStyle);
			AddRunToMockedPara(fnPara, "Footnote " + Guid.NewGuid(), Cache.DefaultVernWs);

			if (fMakeOrphan)
			{
				ITsStrBldr bldr = scrPara.Contents.GetBldr();
				bldr.SetProperties(ichOrc, ichOrc + 1, TsStringUtils.PropsForWs(Cache.DefaultVernWs));
				scrPara.Contents = bldr.GetString();
			}
			return footnote;
		}
 public IScrSection SplitSectionContent_atIP(int iParaSplit, int ichSplit, IStText newHeading)
 {
     throw new NotImplementedException();
 }
Example #42
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_wsArbitrary = Cache.DefaultVernWs;
			IText itext = AddInterlinearTextToLangProj("My Interlinear Text");
			AddParaToInterlinearTextContents(itext, "Book of Genesis");
			m_text = itext.ContentsOA;
		}
Example #43
0
        private void ExportCustomFields(TextWriter writer, IRnGenericRec record)
        {
            ISilDataAccessManaged sda = m_cache.DomainDataByFlid as ISilDataAccessManaged;

            Debug.Assert(sda != null);
            foreach (int flid in m_customFlids)
            {
                string             fieldName = m_mdc.GetFieldName(flid);
                bool               fHandled  = false;
                ITsString          tss;
                string             s;
                CellarPropertyType cpt = (CellarPropertyType)m_mdc.GetFieldType(flid);
                switch (cpt)
                {
                case CellarPropertyType.Boolean:
                    break;

                case CellarPropertyType.Integer:
                    break;

                case CellarPropertyType.Numeric:
                    break;

                case CellarPropertyType.Float:
                    break;

                case CellarPropertyType.Time:
                    break;

                case CellarPropertyType.Guid:
                    break;

                case CellarPropertyType.Image:
                case CellarPropertyType.Binary:
                    break;

                case CellarPropertyType.GenDate:
                    break;

                case CellarPropertyType.String:
                    tss = sda.get_StringProp(record.Hvo, flid);
                    if (tss != null && tss.Text != null)
                    {
                        ExportString(writer, tss, fieldName);
                    }
                    fHandled = true;
                    break;

                case CellarPropertyType.MultiString:
                case CellarPropertyType.MultiUnicode:
                    ITsMultiString tms = sda.get_MultiStringProp(record.Hvo, flid);
                    int            cch = 0;
                    for (int i = 0; i < tms.StringCount; ++i)
                    {
                        int ws;
                        tss  = tms.GetStringFromIndex(i, out ws);
                        cch += tss.Length;
                        if (cch > 0)
                        {
                            break;
                        }
                    }
                    if (cch > 0)
                    {
                        writer.WriteLine("<Field name=\"{0}\" type=\"MultiString\">", fieldName);
                        for (int i = 0; i < tms.StringCount; ++i)
                        {
                            int ws;
                            tss = tms.GetStringFromIndex(i, out ws);
                            if (tss != null && tss.Length > 0)
                            {
                                if (cpt == CellarPropertyType.MultiString)
                                {
                                    writer.WriteLine(TsStringUtils.GetXmlRep(tss,
                                                                             m_cache.WritingSystemFactory, ws, true));
                                }
                                else
                                {
                                    writer.WriteLine("<AUni ws=\"{0}\">{1}</AUni>",
                                                     m_cache.WritingSystemFactory.GetStrFromWs(ws),
                                                     XmlUtils.MakeSafeXml(tss.Text));
                                }
                            }
                        }
                        writer.WriteLine("</Field>");
                    }
                    fHandled = true;
                    break;

                case CellarPropertyType.Unicode:
                    break;

                case CellarPropertyType.ReferenceAtomic:
                case CellarPropertyType.ReferenceCollection:
                case CellarPropertyType.ReferenceSequence:
                {
                    int        destClid  = m_mdc.GetDstClsId(flid);
                    List <int> rghvoDest = new List <int>();
                    if (cpt == CellarPropertyType.ReferenceAtomic)
                    {
                        int hvo = sda.get_ObjectProp(record.Hvo, flid);
                        if (hvo != 0)
                        {
                            if (destClid == CmPossibilityTags.kClassId)
                            {
                                ICmPossibility poss = PossibilityRepository.GetObject(hvo);
                                ExportAtomicReference(writer, poss, fieldName, "CmPossibility");
                                fHandled = true;
                            }
                            else
                            {
                                rghvoDest.Add(hvo);
                            }
                        }
                        else
                        {
                            fHandled = true;
                        }
                    }
                    else
                    {
                        int[] hvos = sda.VecProp(record.Hvo, flid);
                        if (hvos.Length > 0)
                        {
                            if (destClid == CmPossibilityTags.kClassId)
                            {
                                List <ICmPossibility> collection = new List <ICmPossibility>();
                                foreach (int hvo in hvos)
                                {
                                    collection.Add(PossibilityRepository.GetObject(hvo));
                                }
                                ExportReferenceList(writer, collection, fieldName, "CmPossibility", cpt);
                                fHandled = true;
                            }
                            else
                            {
                                rghvoDest.AddRange(hvos);
                            }
                        }
                        else
                        {
                            fHandled = true;
                        }
                    }
                    if (rghvoDest.Count > 0)
                    {
                    }
                }
                break;

                case CellarPropertyType.OwningAtomic:
                case CellarPropertyType.OwningCollection:
                case CellarPropertyType.OwningSequence:
                {
                    int        destClid  = m_mdc.GetDstClsId(flid);
                    List <int> rghvoDest = new List <int>();
                    if (cpt == CellarPropertyType.OwningAtomic)
                    {
                        int hvo = sda.get_ObjectProp(record.Hvo, flid);
                        if (hvo != 0)
                        {
                            if (destClid == StTextTags.kClassId)
                            {
                                IStText text = StTextRepository.GetObject(hvo);
                                ExportStText(writer, text, fieldName);
                                fHandled = true;
                            }
                            else
                            {
                                rghvoDest.Add(hvo);
                            }
                        }
                        else
                        {
                            fHandled = true;
                        }
                    }
                    else
                    {
                    }
                }
                break;
                }
                if (!fHandled)
                {
                }
            }
        }
Example #44
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates the test data.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected override void CreateTestData()
        {
            IText text = AddInterlinearTextToLangProj("My Interlinear Text");

            m_stText = text.ContentsOA;
        }
		public IEnumerable<IParaFragment> Search(IStText text)
		{
			if (IsPatternEmpty)
				return Enumerable.Empty<IParaFragment>();

			var matches = new List<IParaFragment>();
			foreach (IStTxtPara para in text.ParagraphsOS.OfType<IStTxtPara>())
			{
				IParaFragment lastFragment = null;
				var data = new ComplexConcParagraphData(m_spanFactory, m_featSys, para);
				Match<ComplexConcParagraphData, ShapeNode> match = m_matcher.Match(data);
				while (match.Success)
				{
					if (match.Span.Start == match.Span.End
						&& ((FeatureSymbol) match.Span.Start.Annotation.FeatureStruct.GetValue<SymbolicFeatureValue>("type")).ID == "bdry")
					{
						match = match.NextMatch();
						continue;
					}

					ShapeNode startNode = match.Span.Start;
					if (((FeatureSymbol) startNode.Annotation.FeatureStruct.GetValue<SymbolicFeatureValue>("type")).ID == "bdry")
						startNode = startNode.Next;

					Annotation<ShapeNode> startAnn = startNode.Annotation;
					if (((FeatureSymbol) startAnn.FeatureStruct.GetValue<SymbolicFeatureValue>("type")).ID == "morph")
						startAnn = startAnn.Parent;

					var startAnalysis = (Tuple<IAnalysis, int, int>) startAnn.Data;

					ShapeNode endNode = match.Span.End;
					if (((FeatureSymbol) endNode.Annotation.FeatureStruct.GetValue<SymbolicFeatureValue>("type")).ID == "bdry")
						endNode = endNode.Prev;

					Annotation<ShapeNode> endAnn = endNode.Annotation;
					if (((FeatureSymbol) endAnn.FeatureStruct.GetValue<SymbolicFeatureValue>("type")).ID == "morph")
						endAnn = endAnn.Parent;

					Debug.Assert(startNode.CompareTo(endNode) <= 0);

					var endAnalysis = (Tuple<IAnalysis, int, int>) endAnn.Data;

					if (lastFragment != null && lastFragment.GetMyBeginOffsetInPara() == startAnalysis.Item2 && lastFragment.GetMyEndOffsetInPara() == endAnalysis.Item3)
					{
						match = GetNextMatch(match);
						continue;
					}

					ISegment seg = para.SegmentsOS.Last(s => s.BeginOffset <= startAnalysis.Item2);
					lastFragment = new ParaFragment(seg, startAnalysis.Item2, endAnalysis.Item3, startAnalysis.Item1);
					matches.Add(lastFragment);

					match = GetNextMatch(match);
				}
			}

			return matches;
		}
Example #46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Searches given StText for quoted text.
		/// </summary>
		/// <param name="text">Text to be searche</param>
		/// <param name="note">Note containing quote</param>
		/// <param name="quote">Quote</param>
		/// <returns>
		/// Paragraph that contains quote if quote is found; otherwise <c>null</c> will be returned.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private ICmObject SearchStTextForQuote(IStText text, IScrScriptureNote note, string quote)
		{
			foreach (IStTxtPara para in text.ParagraphsOS)
			{
				if (para.Contents.Length == 0)
					continue;
				// Remove chapter/verse numbers and footnotes from paragraph contents - this is done when
				// quote is created for the note.
				ITsString tssQuote = TsStringUtils.GetCleanTsString(para.Contents, ScrStyleNames.ChapterAndVerse);

				if (tssQuote == null || tssQuote.Length == 0)
					return null;

				string paraContent = tssQuote.Text;
				int offset = paraContent.IndexOf(quote);
				if (offset >= 0)
				{
					// offsets may be off slightly because of removed characters
					note.BeginOffset = offset;
					note.EndOffset = offset + quote.Length;
					return para;
				}
			}

			return null;
		}
        public void AddAndRemoveScripture()
        {
            List <IStText>      expectedScripture;
            List <IStText>      expected;
            InterestingTextList testObj = SetupTwoMockTextsAndOneScriptureSection(true, out expectedScripture, out expected);

            MakeMockScriptureSection();
            testObj.PropChanged(m_sections[1].Hvo, ScrSectionTags.kflidContent, 0, 1, 0);
            testObj.PropChanged(m_sections[1].Hvo, ScrSectionTags.kflidHeading, 0, 1, 0);
            VerifyList(expected, testObj.InterestingTexts, "new Scripture objects are not added automatically");
            VerifyScriptureList(testObj, expectedScripture, "new Scripture objects are not added automatically to ScriptureTexts");
            Assert.IsTrue(testObj.IsInterestingText(expectedScripture[0]));
            Assert.IsTrue(testObj.IsInterestingText(expectedScripture[1]));

            var remove = ((MockStText)m_sections[0].ContentOA);

            remove.IsValidObject = false;
            expected.Remove(m_sections[0].ContentOA);   // before we clear ContentsOA!
            expectedScripture.Remove(m_sections[0].ContentOA);
            m_sections[0].ContentOA = null;             // not normally valid, but makes things somewhat more consistent for test.
            testObj.PropChanged(m_sections[0].Hvo, ScrSectionTags.kflidContent, 0, 0, 1);
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (ContentsOA)");
            VerifyScriptureList(testObj, expectedScripture, "deleted Scripture texts are removed from ScriptureTexts (ContentsOA");
            VerifyTextsChangedArgs(2, 0, 1);
            Assert.IsFalse(testObj.IsInterestingText(remove));
            Assert.IsTrue(testObj.IsInterestingText(expectedScripture[0]));

            ((MockStText)m_sections[0].HeadingOA).IsValidObject = false;
            expected.Remove(m_sections[0].HeadingOA);   // before we clear ContentsOA!
            m_sections[0].HeadingOA = null;             // not normally valid, but makes things somewhat more consistent for test.
            testObj.PropChanged(m_sections[0].Hvo, ScrSectionTags.kflidHeading, 0, 0, 1);
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (HeadingOA)");

            m_sections[0].ContentOA = new MockStText();
            var newTexts = new IStText[] { expected[0], expected[1], m_sections[0].ContentOA, m_sections[1].ContentOA, m_sections[1].HeadingOA };

            testObj.SetInterestingTexts(newTexts);
            VerifyTextsChangedArgs(2, 3, 0);
            expected.AddRange(new[] { m_sections[0].ContentOA, m_sections[1].ContentOA, m_sections[1].HeadingOA });
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (HeadingOA)");
            // Unfortunately, I don't think we actually get PropChanged on the direct owning property,
            // if the owning object (Text or ScrSection) gets deleted. We need to detect deleted objects
            // if things are deleted from any of the possible owning properties.
            // This is also a chance to verify that being owned by an ScrDraft does not count as valid.
            // It's not a very realistic test, as we aren't trying to make everything about the test data consistent.
            ((MockStText)m_sections[0].ContentOA).m_mockOwnerOfClass = new MockScrDraft();              // not allowed in list.
            testObj.PropChanged(m_sections[0].Hvo, ScrBookTags.kflidSections, 0, 0, 1);
            expected.RemoveAt(2);
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (ScrBook.SectionsOS)");
            VerifyTextsChangedArgs(2, 0, 1);

            ((MockStText)expected[3]).IsValidObject = false;
            expected.RemoveAt(3);
            testObj.PropChanged(m_sections[0].Hvo, ScriptureTags.kflidScriptureBooks, 0, 0, 1);
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (Scripture.ScriptureBooks)");
            VerifyTextsChangedArgs(3, 0, 1);

            ((MockStText)expected[2]).IsValidObject = false;
            expected.RemoveAt(2);
            testObj.PropChanged(m_sections[0].Hvo, ScrBookTags.kflidTitle, 0, 0, 1);
            VerifyList(expected, testObj.InterestingTexts, "deleted Scripture texts are removed (ScrBookTags.Title)");
            VerifyTextsChangedArgs(2, 0, 1);
            Assert.AreEqual(0, testObj.ScriptureTexts.Count(), "by now we've removed all ScriptureTexts");

            ((MockStText)expected[1]).IsValidObject = false;
            expected.RemoveAt(1);
            //testObj.PropChanged(1, LangProjectTags.kflidTexts, 0, 0, 1);
            VerifyList(expected, testObj.InterestingTexts, "deleted texts are removed (LangProject.Texts)");
            VerifyTextsChangedArgs(1, 0, 1);
        }
Example #48
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Use this method to transfer the beginning part of the first paragraph of an StText
        /// to the end of another or the ending part of the last paragraph of an StText
        /// to the beginning of another. Does nothing if there are no characters to move.
        /// </summary>
        /// <param name="source">StText from which the paragraphs are moved</param>
        /// <param name="ichDiv">Character index of point where paragraph is to be divided
        /// </param>
        /// <param name="destn">StText to which the paragraphs are moved</param>
        /// <param name="moveInitialFragment">
        /// If True, move the paragraph fragment preceding the division point in the
        /// first paragraph of the source text to the end of the destination text;
        /// else, move the paragraph fragment following the division point in the
        /// last paragraph of the source text to the beginning of the destination text.</param>
        /// ------------------------------------------------------------------------------------
        private static void DivideParaContents(IStText source, int ichDiv, IStText destn,
                                               bool moveInitialFragment)
        {
            int contentFlid = (int)StTxtPara.StTxtParaTags.kflidContents;

            // Set up paragraph indices
            int srcParaIndex, dstParaIndex;

            if (moveInitialFragment)
            {
                // the paragraph fragment to be moved is in the first part of the first paragraph
                srcParaIndex = 0;
                // the moved portion goes to the end of the destination paragraph
                dstParaIndex = destn.ParagraphsOS.Count;
            }
            else
            {
                // the paragraph fragment to be moved is the last part of the last paragraph
                srcParaIndex = source.ParagraphsOS.Count - 1;
                // the moved portion goes to the beginning of the destination paragraph
                dstParaIndex = 0;
            }

            // Set the source paragraph
            IStTxtPara curPara      = (IStTxtPara)source.ParagraphsOS[srcParaIndex];
            int        ichEndOfPara = curPara.Contents.Length;

            // Set up parameters based on which portion of the divided paragraph must move
            int ichStartMoved, ichEndMoved, ichStartRemainder, ichEndRemainder;

            if (moveInitialFragment)
            {
                ichStartMoved     = 0;
                ichEndMoved       = ichDiv;
                ichStartRemainder = ichDiv;
                ichEndRemainder   = ichEndOfPara;
            }
            else
            {
                ichStartMoved     = ichDiv;
                ichEndMoved       = ichEndOfPara;
                ichStartRemainder = 0;
                ichEndRemainder   = ichDiv;
            }

            //Move partial paragraph if there are characters to move
            if (ichStartMoved < ichEndMoved)
            {
                IStTxtPara newPara = (IStTxtPara)destn.ParagraphsOS.InsertAt(new StTxtPara(), dstParaIndex);
                newPara.StyleRules = curPara.StyleRules;
                ITsString  tss  = curPara.Contents.UnderlyingTsString;
                ITsStrBldr bldr = tss.GetBldr();
                bldr.Replace(ichStartRemainder, ichEndRemainder, "", null);
                newPara.Contents.UnderlyingTsString = bldr.GetString();
                newPara.Cache.PropChanged(null, PropChangeType.kpctNotifyAll,
                                          newPara.Hvo, contentFlid, 0, ichEndMoved - ichStartMoved, 0);
                // if an empty paragraph would be left at end of a multiple
                // paragraph text, remove it.
                if (source.ParagraphsOS.Count > 1 && ichStartRemainder == ichEndRemainder)
                {
                    source.ParagraphsOS.RemoveAt(srcParaIndex);
                }
                else
                {
                    // else remove only the moved contents from the source paragraph
                    bldr = tss.GetBldr();
                    bldr.Replace(ichStartMoved, ichEndMoved, "", null);
                    curPara.Contents.UnderlyingTsString = bldr.GetString();
                    curPara.Cache.PropChanged(null, PropChangeType.kpctNotifyAll,
                                              curPara.Hvo, contentFlid, ichStartMoved, 0, ichEndMoved - ichStartMoved);
                }
            }
        }
Example #49
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create test data for tests.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_text = AddInterlinearTextToLangProj("My Interlinear Text");
			m_stTextPara = AddParaToInterlinearTextContents(m_text, "Here is a sentence I can chart.");
			m_stText = m_text.ContentsOA;
		}
Example #50
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Look for a previous translation with a matching status in a paragraph of an StText
		/// </summary>
		/// <param name="text">StText to search through</param>
		/// <param name="searchStatus">status of the CmTranslation that we want to find</param>
		/// <param name="iParaStartSearch">Index of the paragraph where search starts</param>
		/// <returns>an index of the found paragraph in the StText or -1 if not found</returns>
		/// ------------------------------------------------------------------------------------
		private int FindPrevTranslationInText(IStText text, BackTranslationStatus searchStatus,
			int iParaStartSearch)
		{
			// Look through all of the paragraphs in the StText.
			for (int paraIndex = iParaStartSearch; paraIndex >= 0; paraIndex--)
			{
				IStTxtPara para = (IStTxtPara)text.ParagraphsOS[paraIndex];

				// Get the translation for this paragraph. If it has the desired state then
				// return it.
				ICmTranslation trans = para.GetOrCreateBT();
				if (GetBackTranslationStatus(trans) == searchStatus)
					return paraIndex;
			}

			// It was not found in this StText
			return -1;
		}
Example #51
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds an empty chart on the specified text.
		/// </summary>
		/// <param name="name">Chart name.</param>
		/// <param name="stText">Chart is BasedOn this text.</param>
		/// ------------------------------------------------------------------------------------
		private IDsConstChart AddChartToLangProj(string name, IStText stText)
		{
			IFdoServiceLocator servloc = Cache.ServiceLocator;
			IDsConstChart chart = servloc.GetInstance<IDsConstChartFactory>().Create();
			if (Cache.LangProject.DiscourseDataOA == null)
				Cache.LangProject.DiscourseDataOA = servloc.GetInstance<IDsDiscourseDataFactory>().Create();

			Cache.LangProject.DiscourseDataOA.ChartsOC.Add(chart);

			// Setup the new chart
			chart.Name.AnalysisDefaultWritingSystem = TsStringUtils.MakeTss(name, Cache.DefaultAnalWs);
			chart.BasedOnRA = stText;

			return chart; // This chart has no template or rows, so far!!
		}
Example #52
0
        private static bool MergeTextWithBIRDDoc(ref FDO.IText newText, TextCreationParams textParams)
        {
            s_importOptions = textParams.ImportOptions;
            Interlineartext   interlinText = textParams.InterlinText;
            FdoCache          cache        = textParams.Cache;
            IThreadedProgress progress     = textParams.Progress;

            if (s_importOptions.CheckAndAddLanguages == null)
            {
                s_importOptions.CheckAndAddLanguages = CheckAndAddLanguagesInternal;
            }

            ILgWritingSystemFactory wsFactory = cache.WritingSystemFactory;
            char space = ' ';

            //handle the languages(writing systems) section alerting the user if new writing systems are encountered
            if (!s_importOptions.CheckAndAddLanguages(cache, interlinText, wsFactory, progress))
            {
                return(false);
            }

            //handle the header(info or meta) information as well as any media-files sections
            SetTextMetaAndMedia(cache, interlinText, wsFactory, newText);

            IStText oldContents = newText.ContentsOA;
            IStText newContents = null;

            //create all the paragraphs NOTE: Currently the paragraph guids are being ignored, this might be wrong.
            foreach (var paragraph in interlinText.paragraphs)
            {
                if (newContents == null)
                {
                    newContents        = cache.ServiceLocator.GetInstance <IStTextFactory>().Create();
                    newText.ContentsOA = newContents;
                }
                IStTxtPara newTextPara = newContents.AddNewTextPara("");
                int        offset      = 0;
                if (paragraph.phrases == null)
                {
                    continue;
                }
                foreach (var phrase in paragraph.phrases)
                {
                    ICmObject oldSegment = null;
                    //Try and locate a segment with this Guid.
                    if (!String.IsNullOrEmpty(phrase.guid))
                    {
                        if (cache.ServiceLocator.ObjectRepository.TryGetObject(new Guid(phrase.guid), out oldSegment))
                        {
                            if (oldSegment as ISegment != null)                             //The segment matches, add it into our paragraph.
                            {
                                newTextPara.SegmentsOS.Add(oldSegment as ISegment);
                            }
                            else if (oldSegment == null)                            //The segment is identified by a Guid, but apparently we don't have it in our current document, so make one
                            {
                                oldSegment = cache.ServiceLocator.GetInstance <ISegmentFactory>().Create(newTextPara, offset, cache, new Guid(phrase.guid));
                            }
                            else                             //The Guid is in use, but not by a segment. This is bad.
                            {
                                return(false);
                            }
                        }
                    }
                    //set newSegment to the old, or create a brand new one.
                    ISegment newSegment   = oldSegment as ISegment ?? cache.ServiceLocator.GetInstance <ISegmentFactory>().Create(newTextPara, offset);
                    var      tsStrFactory = cache.ServiceLocator.GetInstance <ITsStrFactory>();
                    //Fill in the ELAN time information if it is present.
                    AddELANInfoToSegment(cache, phrase, newSegment);

                    ITsString phraseText = null;
                    bool      textInFile = false;
                    //Add all of the data from <item> elements into the segment.
                    AddSegmentItemData(cache, wsFactory, phrase, newSegment, tsStrFactory, ref textInFile, ref phraseText);

                    bool lastWasWord = false;
                    if (phrase.WordsContent != null && phrase.WordsContent.Words != null)
                    {
                        foreach (var word in phrase.WordsContent.Words)
                        {
                            //If the text of the phrase was not found in a "txt" item for this segment then build it from the words.
                            if (!textInFile)
                            {
                                UpdatePhraseTextForWordItems(wsFactory, tsStrFactory, ref phraseText, word, ref lastWasWord, space);
                            }
                            MergeWordToSegment(newSegment, word, tsStrFactory);
                        }
                    }
                    UpdateParagraphTextForPhrase(newTextPara, ref offset, phraseText);
                }
            }
            return(true);
        }
 public bool TryGetObject(int hvo, out IStText obj)
 {
     throw new NotImplementedException();
 }
Example #54
0
 /// -----------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="ScrVerse"/> class for an empty paragraph.
 /// </summary>
 /// -----------------------------------------------------------------------------------
 public ScrVerse(BCVRef start, BCVRef end, ITsString text, ParaNodeMap map,
                 IScrTxtPara para, IStText paraOwner, bool isStanzaBreak) :
     this(start, end, text, map, para, paraOwner, 0, 0, false, false, true, isStanzaBreak)
 {
 }
Example #55
0
		/// <summary>
		/// Makes more acessible the means of testing for interesting texts.
		/// </summary>
		public bool IsInterestingText(IStText text)
		{
			if (m_interestingTexts == null)
				return true;
			return m_interestingTexts.IsInterestingText(text);
		}
		internal MockInterlinDocForAnalyis(IStText testText)
		{
			Cache = testText.Cache;
			m_hvoRoot = testText.Hvo;
			m_testText = testText;
			m_vc = new InterlinVc(Cache);
			m_vc.RootSite = this;
		}
Example #57
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Look for a translation with a matching status in a paragraph of an StText
		/// </summary>
		/// <param name="text">StText to search through</param>
		/// <param name="iParaStartSearch">Index of the paragraph where search starts</param>
		/// <param name="condition">Condition the CmTranslation must fulfill</param>
		/// <returns>an index of the found paragraph in the StText or -1 if not found</returns>
		/// ------------------------------------------------------------------------------------
		private static int FindNextTranslationInText(IStText text, int iParaStartSearch,
			Func<ICmTranslation, bool> condition)
		{
			// Look through all of the paragraphs in the StText.
			for (int paraIndex = iParaStartSearch; paraIndex < text.ParagraphsOS.Count; paraIndex++)
			{
				IStTxtPara para = (IStTxtPara)text.ParagraphsOS[paraIndex];

				// Get the translation for this paragraph. If it has the desired state then
				// return it.
				ICmTranslation trans = para.GetOrCreateBT();
				if (condition(trans))
					return paraIndex;
			}

			// It was not found in this StText
			return -1;
		}
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Sets up the specifed SelectionHelper for the specified paragraph and StText.
        /// </summary>
        /// <param name="helper">The SelectionHelper.</param>
        /// <param name="text">The StText.</param>
        /// <param name="para">The para.</param>
        /// <param name="limit">The limit.</param>
        /// <param name="view">The view</param>
        /// ------------------------------------------------------------------------------------
        private void SetupSelectionFor(SelectionHelper helper, IStText text, IStTxtPara para,
                                       SelectionHelper.SelLimitType limit, FwRootSite view)
        {
            Debug.Assert((view is DraftView && ((DraftView)view).TeEditingHelper != null) ||
                         (view is FootnoteView && ((FootnoteView)view).EditingHelper != null));

            helper.SetTextPropId(limit, StTxtParaTags.kflidContents);

            if (view is DraftView)
            {
                DraftView draftView = (DraftView)view;

                if ((text.OwningFlid == ScrSectionTags.kflidContent ||
                     text.OwningFlid == ScrSectionTags.kflidHeading))
                {
                    // text belongs to section heading or contents
                    IScrSection section = (IScrSection)text.Owner;
                    Debug.Assert(section.OwningFlid == ScrBookTags.kflidSections);

                    helper.SetNumberOfLevels(limit, 4);
                    SelLevInfo[] info = helper.GetLevelInfo(limit);
                    info[0].ihvo = para.IndexInOwner;
                    info[0].tag  = StTextTags.kflidParagraphs;
                    info[1].ihvo = 0;
                    info[1].tag  = text.OwningFlid;
                    info[2].ihvo = section.IndexInOwner;
                    info[2].tag  = ScrBookTags.kflidSections;
                    info[3].ihvo = draftView.TeEditingHelper.BookFilter.GetBookIndex((IScrBook)section.Owner);
                    info[3].tag  = draftView.TeEditingHelper.BookFilter.Tag;
                }
                else
                {
                    // text belongs to a book title
                    Debug.Assert(text.OwningFlid == ScrBookTags.kflidTitle);
                    IScrBook book = (IScrBook)text.Owner;

                    helper.SetNumberOfLevels(limit, 3);
                    SelLevInfo[] info = helper.GetLevelInfo(limit);
                    info[0].ihvo = para.IndexInOwner;
                    info[0].tag  = StTextTags.kflidParagraphs;
                    info[1].ihvo = 0;
                    info[1].tag  = text.OwningFlid;
                    info[2].ihvo = draftView.TeEditingHelper.BookFilter.GetBookIndex(book);
                    info[2].tag  = draftView.TeEditingHelper.BookFilter.Tag;
                }
            }
            else if (view is FootnoteView && text.OwningFlid == ScrBookTags.kflidFootnotes)
            {
                // text belongs to a footnote
                FootnoteView footnoteView = (FootnoteView)view;
                IStFootnote  footnote     = (IStFootnote)para.Owner;
                IScrBook     book         = (IScrBook)text.Owner;

                helper.SetNumberOfLevels(limit, 3);
                SelLevInfo[] info = helper.GetLevelInfo(limit);
                info[0].hvo  = text.Hvo;
                info[0].tag  = StTextTags.kflidParagraphs;
                info[1].hvo  = footnote.Hvo;
                info[1].ihvo = footnote.IndexInOwner;
                info[1].tag  = ScrBookTags.kflidFootnotes;
                info[2].hvo  = book.Hvo;
                info[2].ihvo = footnoteView.BookFilter.GetBookIndex(book);
                info[2].tag  = footnoteView.BookFilter.Tag;
                info[0].ich  = info[1].ich = info[2].ich = -1;
            }
        }
Example #59
0
 public StTextParagraphOperations(IStText owningText)
 {
     m_owningText = owningText;
 }
        /// <summary>
        /// Establish the writing system of the new text by filling its first paragraph with
        /// an empty string in the proper writing system.
        /// </summary>
        internal void CreateFirstParagraph(IStText stText, int wsText)
        {
            var txtPara = stText.AddNewTextPara(null);

            txtPara.Contents = TsStringUtils.MakeTss(string.Empty, wsText);
        }