Exemplo n.º 1
0
		public SimpleDataParser(IFwMetaDataCache mdc, IVwCacheDa cda)
		{
			m_mdc = mdc;
			m_cda = cda;
			m_sda = cda as ISilDataAccess;
			m_wsf = m_sda.WritingSystemFactory;
		}
Exemplo n.º 2
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:SimpleMatchDlg"/> class.
		/// </summary>
		/// <param name="wsf">The WSF.</param>
		/// <param name="ws">The ws.</param>
		/// <param name="ss">The ss.</param>
		/// ------------------------------------------------------------------------------------
		public SimpleMatchDlg(ILgWritingSystemFactory wsf, int ws, IVwStylesheet ss)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// We do this outside the designer-controlled code because it does funny things
			// to FwTextBoxes, owing to the need for a writing system factory, and some
			// properties it should not persist but I can't persuade it not to.
			this.m_textBox = new FwTextBox();
			this.m_textBox.WritingSystemFactory = wsf; // set ASAP.
			this.m_textBox.WritingSystemCode = ws;
			this.m_textBox.StyleSheet = ss; // before setting text, otherwise it gets confused about height needed.
			this.m_textBox.Location = new System.Drawing.Point(8, 24);
			this.m_textBox.Name = "m_textBox";
			this.m_textBox.Size = new System.Drawing.Size(450, 32);
			this.m_textBox.TabIndex = 0;
			this.m_textBox.Text = "";
			this.Controls.Add(this.m_textBox);

			regexContextMenu = new RegexHelperMenu(m_textBox, FwApp.App);

			m_ivwpattern = VwPatternClass.Create();

			helpProvider = new System.Windows.Forms.HelpProvider();
			helpProvider.HelpNamespace = FwApp.App.HelpFile;
			helpProvider.SetHelpKeyword(this, FwApp.App.GetHelpString(s_helpTopic, 0));
			helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic);
		}
Exemplo n.º 3
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="XmlNotePara"/> class based on the given
		/// StTxtPara.
		/// </summary>
		/// <param name="stTxtPara">The FDO paragraph.</param>
		/// <param name="wsDefault">The default (analysis) writing system.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// ------------------------------------------------------------------------------------
		public XmlNotePara(IStTxtPara stTxtPara, int wsDefault, ILgWritingSystemFactory lgwsf)
		{
			// REVIEW: Ask TomB about this. The only paragraph style allowed in
			// TE for notes is "Remark" so is it necessary to write it to the XML?
			// It causes a problem for the OXES validator.
			//StyleName = stTxtPara.StyleName;

			ITsString tssParaContents = stTxtPara.Contents;
			if (tssParaContents.RunCount == 0)
				return;

			int dummy;
			int wsFirstRun = tssParaContents.get_Properties(0).GetIntPropValues(
				(int)FwTextPropType.ktptWs, out dummy);

			//if (wsFirstRun != wsDefault)
			IcuLocale = lgwsf.GetStrFromWs(wsFirstRun);

			for (int iRun = 0; iRun < tssParaContents.RunCount; iRun++)
			{
				ITsTextProps props = tssParaContents.get_Properties(iRun);
				string text = tssParaContents.get_RunText(iRun);
				if (TsStringUtils.IsHyperlink(props))
					Runs.Add(new XmlHyperlinkRun(wsFirstRun, lgwsf, text, props));
				else
					Runs.Add(new XmlTextRun(wsFirstRun, lgwsf, text, props));
			}
		}
Exemplo n.º 4
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="XmlNoteCategory"/> class based on the
		/// specified category.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public XmlNoteCategory(ICmPossibility category, ILgWritingSystemFactory lgwsf)
		{
			List<CategoryNode> categoryList = GetCategoryHierarchyList(category);
			m_categoryPath = category.NameHierarchyString;

			InitializeCategory(categoryList, lgwsf);
		}
Exemplo n.º 5
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds the bullet font information to the specified props builder.
		/// </summary>
		/// <param name="bldr">The props builder.</param>
		/// <param name="bulFontInfo">The bullet font information XML.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// ------------------------------------------------------------------------------------
		private static void AddBulletFontInfoToBldr(ITsPropsBldr bldr, XElement bulFontInfo,
			ILgWritingSystemFactory lgwsf)
		{
			int intValue, type, var;
			string strValue;
			ITsPropsBldr fontProps = GetPropAttributesForElement(bulFontInfo, lgwsf);

			// Add the integer properties to the bullet props string
			StringBuilder bulletProps = new StringBuilder(fontProps.IntPropCount * 3 + fontProps.StrPropCount * 20);
			for (int i = 0; i < fontProps.IntPropCount; i++)
			{
				fontProps.GetIntProp(i, out type, out var, out intValue);
				bulletProps.Append((char)type);
				WriteIntToStrBuilder(bulletProps, intValue);
			}

			// Add the string properties to the bullet props string
			for (int i = 0; i < fontProps.StrPropCount; i++)
			{
				fontProps.GetStrProp(i, out type, out strValue);
				bulletProps.Append((char)type);
				bulletProps.Append(strValue);
				bulletProps.Append('\u0000');
			}

			bldr.SetStrPropValue((int)FwTextPropType.ktptBulNumFontInfo, bulletProps.ToString());
		}
Exemplo n.º 6
0
		/// <summary>
		/// Clear out test data.
		/// </summary>
		public override void FixtureTeardown()
		{
			m_wsf = null;
			m_styleSheet = null;

			base.FixtureTeardown();
		}
Exemplo n.º 7
0
 /// <summary>
 /// Make an LfParagraph object from an FDO StTxtPara.
 /// </summary>
 /// <returns>The LFParagraph.</returns>
 /// <param name="fdoPara">FDO StTxtPara object to convert.</param>
 public static LfParagraph FdoParaToLfPara(IStTxtPara fdoPara, ILgWritingSystemFactory wsf)
 {
     var lfPara = new LfParagraph();
     lfPara.Guid = fdoPara.Guid;
     lfPara.StyleName = fdoPara.StyleName;
     lfPara.Content = ConvertFdoToMongoTsStrings.TextFromTsString(fdoPara.Contents, wsf);
     return lfPara;
 }
		public override void FixtureSetup()
		{
			base.FixtureSetup();

			m_flidContainingTexts = ScrBookTags.kflidFootnotes;
			m_wsf = Cache.WritingSystemFactory;
			m_wsEng = m_wsf.GetWsFromStr("en");
		}
Exemplo n.º 9
0
		public void TestFixtureSetup()
		{
			// This needs to be set for ICU
			RegistryHelper.CompanyName = "SIL";
			Icu.InitIcuDataDir();
			m_wsf = new PalasoWritingSystemManager();
			m_DebugProcs = new DebugProcs();
		}
Exemplo n.º 10
0
		/// -------------------------------------------------------------------------------------
		/// <summary>
		/// Make sure that all runs of the given ts string will fit within the given height.
		/// </summary>
		/// <param name="tss">(Potentially) unadjusted TsString -- may have some pre-existing
		/// adjustments, but if it does, we (probably) ignore those and recheck every run</param>
		/// <param name="dympMaxHeight">The maximum height (in millipoints) of the Ts String.</param>
		/// <param name="styleSheet"></param>
		/// <param name="writingSystemFactory"></param>
		/// -------------------------------------------------------------------------------------
		public static ITsString GetAdjustedTsString(ITsString tss, int dympMaxHeight,
			IVwStylesheet styleSheet, ILgWritingSystemFactory writingSystemFactory)
		{
			if (dympMaxHeight == 0)
				return tss;

			ITsStrBldr bldr = null;

			int runCount = tss.RunCount;
			for (int irun = 0; irun < runCount; irun++)
			{
				ITsTextProps props = tss.get_Properties(irun);
				int var;
				int wsTmp = props.GetIntPropValues((int)FwTextPropType.ktptWs,
					out var);
				string styleName =
					props.GetStrPropValue((int)FwTextStringProp.kstpNamedStyle);

				int height;
				string name;
				float sizeInPoints;
				using (Font f = GetFontForStyle(styleName, styleSheet, wsTmp, writingSystemFactory))
				{
					height = GetFontHeight(f);
					name = f.Name;
					sizeInPoints = f.SizeInPoints;
				}
				int curHeight = height;
				// incrementally reduce the size of the font until the text can fit
				while (curHeight > dympMaxHeight)
				{
					using (var f = new Font(name, sizeInPoints - 0.25f))
					{
						curHeight = GetFontHeight(f);
						name = f.Name;
						sizeInPoints = f.SizeInPoints;
					}
				}

				if (curHeight != height)
				{
					// apply formatting to the problem run
					if (bldr == null)
						bldr = tss.GetBldr();

					int iStart = tss.get_MinOfRun(irun);
					int iEnd = tss.get_LimOfRun(irun);
					bldr.SetIntPropValues(iStart, iEnd,
						(int)FwTextPropType.ktptFontSize,
						(int)FwTextPropVar.ktpvMilliPoint, (int)(sizeInPoints * 1000.0f));
				}
			}

			if (bldr != null)
				return bldr.GetString();
			else
				return tss;
		}
Exemplo n.º 11
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get an XML representation of the given ITsTextProps.
		/// </summary>
		/// <param name="ttp">The TTP.</param>
		/// <param name="wsf">The WSF.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		public static string GetXmlRep(ITsTextProps ttp, ILgWritingSystemFactory wsf)
		{
			using (var writer = new StringWriter())
			{
				var stream = new TextWriterStream(writer);
				ttp.WriteAsXml(stream, wsf, 0);
				return writer.ToString();
			}
		}
Exemplo n.º 12
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates the test data.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_servLoc = Cache.ServiceLocator;
			m_wsf = Cache.WritingSystemFactory;
			m_ws_en = m_wsf.GetWsFromStr("en");
			m_ws_fr = m_wsf.GetWsFromStr("fr");

			CreateTestText();
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="LfMerge.DataConverters.ConvertFdoToMongoOptionList"/> class.
 /// </summary>
 /// <param name="lfOptionList">Lf option list.</param>
 /// <param name="wsForKeys">Ws for keys.</param>
 /// <param name="listCode">List code.</param>
 /// <param name="logger">Logger.</param>
 public ConvertFdoToMongoOptionList(LfOptionList lfOptionList, int wsForKeys, string listCode, ILogger logger, ILgWritingSystemFactory wsf)
 {
     _logger = logger;
     _wsf = wsf;
     _wsForKeys = wsForKeys;
     if (lfOptionList == null)
         lfOptionList = MakeEmptyOptionList(listCode);
     _lfOptionList = lfOptionList;
     UpdateOptionListItemDictionaries(_lfOptionList);
 }
Exemplo n.º 14
0
		public void Setup()
		{
			tsf = TsStrFactoryClass.Create();
			wsf = new MockWsf();
			wsEn = wsf.GetWsFromStr("en");
			wsFrn = wsf.GetWsFromStr("fr");
			ITsPropsBldr propBldr = TsPropsBldrClass.Create();
			propBldr.SetIntPropValues((int)FwTextPropType.ktptWs, (int)FwTextPropVar.ktpvDefault, wsFrn);
			ttpFrn = propBldr.GetTextProps();
		}
Exemplo n.º 15
0
		public void Setup()
		{
			m_wsf = LgWritingSystemFactoryClass.Create();
			// This is typically run during the build process before InstallLanguage.exe has
			// been built, so we want to disable InstallLanguage for this test.
			m_wsf.BypassInstall = true;

			m_wsEn = m_wsf.get_Engine("en");
			m_wsIdEn = m_wsf.GetWsFromStr("en");
			m_wsEn.set_Name(m_wsIdEn, "English");
			m_wsEn.set_Abbr(m_wsIdEn, "ENG");
		}
Exemplo n.º 16
0
		public override void FixtureSetup()
		{
			CheckDisposed();
			base.FixtureSetup();

			m_fdoCache = FdoCache.Create("TestLangProj");
			m_scr = m_fdoCache.LangProject.TranslatedScriptureOA;
			// For these tests we don't need to run InstallLanguage.
			m_wsf = m_fdoCache.LanguageWritingSystemFactoryAccessor;
			m_wsf.BypassInstall = true;

		}
Exemplo n.º 17
0
		public WordMaker(ITsString tss, ILgWritingSystemFactory encf)
		{
			m_tss = tss;
			m_ich = 0;
			m_st = tss.get_Text();
			if (m_st == null)
				m_st = "";
			m_cch = m_st.Length;
			// Get a character property engine from the wsf.
			m_cpe = encf.get_UnicodeCharProps();
			Debug.Assert(m_cpe != null, "encf.get_UnicodeCharProps() returned null");
		}
Exemplo n.º 18
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public override void FixtureSetup()
		{
			base.FixtureSetup();

			// For these tests we don't need to run InstallLanguage.
			m_wsf = Cache.WritingSystemFactory;

			// Done by MemoryOnlyBackendProviderTestBase FixtureSetup.
//			// The GetFontFaceNameFromStyle needs a vern WS.
//			var frenchWs = Cache.WritingSystemFactory.GetWsFromStr("fr");
//			var french = Cache.ServiceLocator.GetInstance<ILgWritingSystemRepository>().GetObject(frenchWs);
//			Cache.LanguageProject.VernWssRC.Add(french);
//			Cache.LanguageProject.CurVernWssRS.Add(french);
		}
Exemplo n.º 19
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Import a file (encapsulated by a TextReader) containing translations for one or more lists.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public bool ImportTranslatedLists(TextReader reader, FdoCache cache, IProgress progress)
		{
			m_cache = cache;
			m_mdc = cache.ServiceLocator.GetInstance<IFwMetaDataCacheManaged>();
			m_rgItemClasses = m_mdc.GetAllSubclasses(CmPossibilityTags.kClassId);
			m_wsf = cache.WritingSystemFactory;
			m_wsEn = GetWsFromStr("en");
			Debug.Assert(m_wsEn != 0);
			m_progress = progress;

			using (var xreader = XmlReader.Create(reader))
				Import(xreader);

			return true;
		}
Exemplo n.º 20
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Deserializes a TsString from the XML node.
		/// </summary>
		/// <param name="xml">The XML node.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// <returns>The created TsString. Will never be <c>null</c> because an exception is
		/// thrown if anything is invalid.</returns>
		/// ------------------------------------------------------------------------------------
		public static ITsString DeserializeTsStringFromXml(XElement xml, ILgWritingSystemFactory lgwsf)
		{
			if (xml != null)
			{
				switch (xml.Name.LocalName)
				{
					case "AStr":
					case "Str":
						return HandleSimpleString(xml, lgwsf) ?? HandleComplexString(xml, lgwsf);
					default:
						throw new XmlSchemaException("TsString XML must contain a <Str> or <AStr> root element");
				}
			}
			return null;
		}
Exemplo n.º 21
0
		public void SetupStyles()
		{
			m_stylesheet = new TestFwStylesheet();
			m_wsf = LgWritingSystemFactoryClass.Create();
			m_wsf.BypassInstall = true;

			// German
			IWritingSystem wsGerman = m_wsf.get_Engine("de");
			m_hvoGermanWs = wsGerman.WritingSystem;
			Assert.IsTrue(m_hvoGermanWs > 0, "Should have gotten an hvo for the German WS");
			// English
			IWritingSystem wsEnglish = m_wsf.get_Engine("en");
			m_hvoEnglishWs = wsEnglish.WritingSystem;
			Assert.IsTrue(m_hvoEnglishWs > 0, "Should have gotten an hvo for the English WS");
			Assert.IsTrue(m_hvoEnglishWs != m_hvoGermanWs, "Writing systems should have different IDs");

			// Create a couple of styles
			int hvoStyle = m_stylesheet.MakeNewStyle();
			ITsPropsBldr propsBldr = TsPropsBldrClass.Create();
			propsBldr.SetStrPropValue((int)FwTextStringProp.kstpFontFamily, "Arial");
			m_stylesheet.PutStyle("StyleA", "bla", hvoStyle, 0, hvoStyle, 1, false, false,
				propsBldr.GetTextProps());

			hvoStyle = m_stylesheet.MakeNewStyle();
			propsBldr.SetStrPropValue((int)FwTextStringProp.kstpFontFamily, "Times New Roman");
			m_stylesheet.PutStyle("StyleB", "bla", hvoStyle, 0, hvoStyle, 1, false, false,
				propsBldr.GetTextProps());

			// Override the font size for each writing system and each style.
			List<FontOverride> fontOverrides = new List<FontOverride>(2);
			FontOverride fo;
			fo.writingSystem = m_hvoGermanWs;
			fo.fontSize = 13;
			fontOverrides.Add(fo);
			fo.writingSystem = m_hvoEnglishWs;
			fo.fontSize = 21;
			fontOverrides.Add(fo);
			m_stylesheet.OverrideFontsForWritingSystems("StyleA", fontOverrides);

			fontOverrides.Clear();
			fo.writingSystem = m_hvoGermanWs;
			fo.fontSize = 56;
			fontOverrides.Add(fo);
			fo.writingSystem = m_hvoEnglishWs;
			fo.fontSize = 20;
			fontOverrides.Add(fo);
			m_stylesheet.OverrideFontsForWritingSystems("StyleB", fontOverrides);
		}
Exemplo n.º 22
0
		/// <summary>
		/// Constructor. Called by service locator factory (by reflection).
		/// </summary>
		/// <remarks>
		/// The hvo values are true 'handles' in that they are valid for one session,
		/// but may not be the same integer for another session for the 'same' object.
		/// Therefore, one should not use them for multi-session identity.
		/// CmObject identity can only be guaranteed by using their Guids (or using '==' in code).
		/// </remarks>
		internal DomainDataByFlid(ICmObjectRepository cmObjectRepository, IStTextRepository stTxtRepository,
			IFwMetaDataCacheManaged mdc, ISilDataAccessHelperInternal uowService,
			ITsStrFactory tsf, ILgWritingSystemFactory wsf)
		{
			if (cmObjectRepository == null) throw new ArgumentNullException("cmObjectRepository");
			if (stTxtRepository == null) throw new ArgumentNullException("stTxtRepository");
			if (mdc == null) throw new ArgumentNullException("mdc");
			if (uowService == null) throw new ArgumentNullException("uowService");
			if (tsf == null) throw new ArgumentNullException("tsf");
			if (wsf == null) throw new ArgumentNullException("wsf");

			m_cmObjectRepository = cmObjectRepository;
			m_stTxtRepository = stTxtRepository;
			m_mdc = mdc;
			m_uowService = uowService;
			m_tsf = tsf;
			m_wsf = wsf;
		}
Exemplo n.º 23
0
        internal static int ReadAstrElementOfMultiString(XElement aStrNode, ILgWritingSystemFactory wsf, out ITsString tss)
        {
            var wsHvo  = 0;
            var wsAttr = aStrNode.Attribute("ws");

            if (wsAttr != null)
            {
                wsHvo = wsf.GetWsFromStr(wsAttr.Value);
            }
            tss = TsStringSerializer.DeserializeTsStringFromXml(aStrNode, wsf);
            if (wsHvo == 0)
            {
                // THIS SHOULD NEVER HAPPEN but we live in a fallen world!
                var ttp = tss.get_PropertiesAt(0);
                int nVar;
                wsHvo = ttp.GetIntPropValues((int)FwTextPropType.ktptWs, out nVar);
            }
            return(wsHvo);
        }
Exemplo n.º 24
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes the specified font info.
        /// </summary>
        /// <param name="fontInfo">The font info.</param>
        /// <param name="fAllowSubscript"><c>true</c> to allow super/subscripts, <c>false</c>
        /// to disable the controls (used when called from Borders and Bullets tab)</param>
        /// <param name="ws">The default writing system (usually UI ws)</param>
        /// <param name="wsf">The writing system factory</param>
        /// <param name="styleSheet">The style sheet.</param>
        /// <param name="fAlwaysDisableFontFeatures"><c>true</c> to disable the Font Features
        /// button even when a Graphite font is selected.</param>
        /// ------------------------------------------------------------------------------------
        void IFontDialog.Initialize(FontInfo fontInfo, bool fAllowSubscript, int ws,
                                    ILgWritingSystemFactory wsf, LcmStyleSheet styleSheet, bool fAlwaysDisableFontFeatures)
        {
            m_DefaultWs = ws;

            m_preview.WritingSystemFactory = wsf;
            m_preview.WritingSystemCode    = ws;
            m_preview.StyleSheet           = styleSheet;

            m_tbFontName.Text = fontInfo.UIFontName();
            FontSize          = fontInfo.m_fontSize.Value / 1000;
            m_tbFontSize.Text = FontSize.ToString(CultureInfo.InvariantCulture);

            m_FontAttributes.UpdateForStyle(fontInfo);
            m_FontAttributes.AllowSuperSubScript = fAllowSubscript;

            m_FontAttributes.AlwaysDisableFontFeatures = fAlwaysDisableFontFeatures;
            UpdatePreview();
        }
Exemplo n.º 25
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_wsf = null;

            base.Dispose(disposing);
        }
Exemplo n.º 26
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="T:KeyTermRenderingsControl"/> class.
        /// </summary>
        /// <param name="cache">The cache.</param>
        /// <param name="mainWnd">the FwMainWnd that owns this control.</param>
        /// ------------------------------------------------------------------------------------
        public KeyTermRenderingsControl(FdoCache cache, FwMainWnd mainWnd) : base(cache, mainWnd)
        {
            InitializeComponent();
            DataGridView = m_dataGridView;

            // Setup columns
            m_Rendering.Cache             = m_cache;
            m_Rendering.WritingSystemCode = m_cache.DefaultVernWs;
            m_OriginalTerm.Cache          = m_cache;

            ILgWritingSystemFactory wsf = m_cache.LanguageWritingSystemFactoryAccessor;

            m_wsGreek = wsf.GetWsFromStr("grc");
            if (m_wsGreek <= 0)
            {
                throw new Exception("The Greek writing system is not defined.");
            }
            m_wsHebrew = wsf.GetWsFromStr("hbo");
            if (m_wsHebrew <= 0)
            {
                throw new Exception("The Hebrew writing system is not defined.");
            }

            if (mainWnd != null)
            {
                Parent           = mainWnd;
                m_stylesheet     = mainWnd.StyleSheet;
                m_Rendering.Font = new Font(
                    m_stylesheet.GetNormalFontFaceName(cache, cache.DefaultVernWs),
                    FontInfo.kDefaultFontSize / 1000);
            }

            m_list       = new List <ICheckGridRowObject>();
            m_gridSorter = new CheckGridListSorter(m_list);
            m_gridSorter.AddComparer(m_Rendering.DataPropertyName, m_tsStrComparer);
            m_gridSorter.AddComparer(m_OriginalTerm.DataPropertyName, m_tsStrComparer);
            m_gridSorter.AddComparer(m_Status.DataPropertyName, new RenderingStatusComparer());
            m_gridSorter.AddComparer(m_Reference.DataPropertyName,
                                     new ScriptureReferenceComparer((Scripture)m_cache.LangProject.TranslatedScriptureOA));

            m_dataGridView.Cache = m_cache;
            m_dataGridView.ColumnHeaderMouseClick += m_dataGridView_ColumnHeaderMouseClick;
        }
Exemplo n.º 27
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles a complex string that contains multiple runs with optional multiple
		/// text props applied.
		/// </summary>
		/// <param name="xml">The XML.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// <returns>The created TsString</returns>
		/// ------------------------------------------------------------------------------------
		private static ITsString HandleComplexString(XElement xml, ILgWritingSystemFactory lgwsf)
		{
			var runs = xml.Elements("Run");
			if (runs.Count() == 0)
			{
				if (xml.Name.LocalName == "AStr" && xml.Attributes().Count() == 1)
				{
					// This duplicates a little bit of code from HandleSimpleRun, but I wanted to keep that really simple
					// and fast, and this case hardly ever happens...maybe not at all in real life.
					XAttribute wsAttribute = xml.Attributes().First();
					if (wsAttribute.Name.LocalName != "ws")
						return null; // we handle only single runs with only the ws attribute.
					// Make sure the text is in the decomposed form (FWR-148)
					string runText = Icu.Normalize(xml.Value, Icu.UNormalizationMode.UNORM_NFD);
					return s_strFactory.MakeString(runText, GetWsForId(wsAttribute.Value, lgwsf));
				}
				return null;	// If we don't have any runs, we don't have a string!
			}

			var strBldr = TsIncStrBldrClass.Create();

			foreach (XElement runElement in runs)
			{
				if (runElement == null)
					throw new XmlSchemaException("TsString XML must contain a <Run> element contained in a <" + xml.Name.LocalName + "> element");
				string runText = runElement.Value;
				if (runElement.Attribute("ws") == null && (runText.Length == 0 || runText[0] > 13))
					throw new XmlSchemaException("Run element must contain a ws attribute. Run text: " + runElement.Value);

				// Make sure the text is in the decomposed form (FWR-148)
				runText = Icu.Normalize(runText, Icu.UNormalizationMode.UNORM_NFD);
				bool isOrcNeeded = TsPropsSerializer.GetPropAttributesForElement(runElement, lgwsf, strBldr);

				// Add an ORC character, if needed, for the run
				if (runText.Length == 0 && isOrcNeeded)
					runText = StringUtils.kszObject;

				// Add the text with the properties to the builder
				strBldr.Append(runText);
			}

			return strBldr.GetString();
		}
Exemplo n.º 28
0
        public static LfMultiText FromSingleITsString(ITsString value, ILgWritingSystemFactory wsManager)
        {
            if (value == null || value.Text == null)
            {
                return(null);
            }
            int           wsId  = value.get_WritingSystem(0);
            string        wsStr = wsManager.GetStrFromWs(wsId);
            string        text  = LfMerge.Core.DataConverters.ConvertLcmToMongoTsStrings.TextFromTsString(value, wsManager);
            LfStringField field = LfStringField.FromString(text);

            if (field == null)
            {
                return(null);
            }
            return(new LfMultiText {
                { wsStr, field }
            });
        }
Exemplo n.º 29
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets a collection of suggestions for what to do when a "word" consists of multiple
        /// writing systems
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private ICollection <SpellCorrectMenuItem> MakeWssSuggestions(ITsString tssWord,
                                                                      List <int> wss, IVwRootBox rootb, int hvoObj, int tag, int wsAlt,
                                                                      int ichMin, int ichLim)
        {
            List <SpellCorrectMenuItem> result = new List <SpellCorrectMenuItem>(wss.Count + 1);

            // Make an item with inserted spaces.
            ITsStrBldr bldr    = tssWord.GetBldr();
            int        wsFirst = TsStringUtils.GetWsOfRun(tssWord, 0);
            int        offset  = 0;

            for (int irun = 1; irun < tssWord.RunCount; irun++)
            {
                int wsNew = TsStringUtils.GetWsOfRun(tssWord, irun);
                if (wsNew != wsFirst)
                {
                    int ichInsert = tssWord.get_MinOfRun(irun) + offset;
                    bldr.Replace(ichInsert, ichInsert, " ", null);
                    wsFirst = wsNew;
                    offset++;
                }
            }
            ITsString suggest      = bldr.GetString();
            string    menuItemText = suggest.Text;

            result.Add(new SpellCorrectMenuItem(rootb, hvoObj, tag, wsAlt, ichMin, ichLim, menuItemText, suggest));

            // And items for each writing system.
            foreach (int ws in wss)
            {
                bldr = tssWord.GetBldr();
                bldr.SetIntPropValues(0, bldr.Length, (int)FwTextPropType.ktptWs, (int)FwTextPropVar.ktpvDefault, ws);
                suggest = bldr.GetString();
                ILgWritingSystemFactory wsf    = rootb.DataAccess.WritingSystemFactory;
                ILgWritingSystem        engine = wsf.get_EngineOrNull(ws);
                string wsName   = engine.LanguageName;
                string itemText = string.Format(RootSiteStrings.ksMlStringIsMono, tssWord.Text, wsName);
                result.Add(new SpellCorrectMenuItem(rootb, hvoObj, tag, wsAlt, ichMin, ichLim, itemText, suggest));
            }

            return(result);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Find the font that is used for the given style name and writing system.
        /// </summary>
        /// <param name="styleName">The style name.</param>
        /// <param name="styleSheet">The stylesheet.</param>
        /// <param name="hvoWs">The HVO of the WS.</param>
        /// <param name="writingSystemFactory">The writing system factory.</param>
        /// <returns>The font.</returns>
        public static Font GetFontForStyle(string styleName, IVwStylesheet styleSheet,
                                           int hvoWs, ILgWritingSystemFactory writingSystemFactory)
        {
            LgCharRenderProps chrps = GetChrpForStyle(styleName, styleSheet, hvoWs, writingSystemFactory);

            int           dympHeight = chrps.dympHeight;
            StringBuilder bldr       = new StringBuilder(chrps.szFaceName.Length);

            for (int i = 0; i < chrps.szFaceName.Length; i++)
            {
                ushort ch = chrps.szFaceName[i];
                if (ch == 0)
                {
                    break;                     // null termination
                }
                bldr.Append(Convert.ToChar(ch));
            }

            return(new Font(bldr.ToString(), (float)(dympHeight / 1000.0f)));
        }
Exemplo n.º 31
0
        private static ILgWritingSystem SafelyGetWritingSystem(FdoCache cache, ILgWritingSystemFactory wsFactory,
                                                               Language lang, out bool fIsVernacular)
        {
            fIsVernacular = lang.vernacularSpecified && lang.vernacular;
            ILgWritingSystem writingSystem = null;

            try
            {
                writingSystem = wsFactory.get_Engine(lang.lang);
            }
            catch (ArgumentException e)
            {
                IWritingSystem ws;
                WritingSystemServices.FindOrCreateSomeWritingSystem(cache, FwDirectoryFinder.TemplateDirectory, lang.lang,
                                                                    !fIsVernacular, fIsVernacular, out ws);
                writingSystem = ws;
                s_wsMapper.Add(lang.lang, writingSystem);                 // old id string -> new langWs mapping
            }
            return(writingSystem);
        }
Exemplo n.º 32
0
        // The raw id that should be used to create a dictionary for the given WS, if none exists.
        private static string RawDictionaryId(int ws, ILgWritingSystemFactory wsf)
        {
            ILgWritingSystem wsEngine = wsf.get_EngineOrNull(ws);

            if (wsEngine == null)
            {
                return(null);
            }
            string wsId = wsEngine.SpellCheckingId;

            if (String.IsNullOrEmpty(wsId))
            {
                return(wsEngine.Id.Replace('-', '_'));                // Enchant does not allow hyphen; that is OK since lang ID does not allow underscore.
            }
            if (wsId == "<None>")
            {
                return(null);
            }
            return(wsId);
        }
Exemplo n.º 33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes categories in the hierarchy.
		/// </summary>
		/// <param name="categoryList">The list of categories for a Scripture note.</param>
		/// <param name="lgwsf">The language writing system factory.</param>
		/// <exception cref="ArgumentOutOfRangeException">thrown when the category list is empty.
		/// </exception>
		/// ------------------------------------------------------------------------------------
		private void InitializeCategory(List<CategoryNode> categoryList, ILgWritingSystemFactory lgwsf)
		{
			XmlNoteCategory curCategory = this;
			CategoryNode node = null;
			for (int i = 0; i < categoryList.Count; i++)
			{
				node = categoryList[i];
				curCategory.CategoryName = node.CategoryName;
				curCategory.IcuLocale = lgwsf.GetStrFromWs(node.Ws);
				if (categoryList.Count > i + 1)
				{
					curCategory.SubCategory = new XmlNoteCategory();
					curCategory = curCategory.SubCategory;
				}
				else
				{
					curCategory.SubCategory = null;
				}
			}
		}
Exemplo n.º 34
0
        /// <summary>
        /// Write Text Prop property.
        /// </summary>
        internal static void WriteTextPropBinary(XmlWriter writer, ILgWritingSystemFactory wsf, string elementName, ITsTextProps propertyData)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (string.IsNullOrEmpty(elementName))
            {
                throw new ArgumentNullException("elementName");
            }

            if (propertyData == null)
            {
                return;
            }

            writer.WriteStartElement(elementName); // Open prop. element.
            writer.WriteRaw(TsStringUtils.GetXmlRep(propertyData, wsf));
            writer.WriteEndElement();              // Close prop. element.
        }
Exemplo n.º 35
0
        public static ITsString SpanStrToTsString(string source, int mainWs, ILgWritingSystemFactory wsf)
        {
            // How to build up an ITsString via an ITsIncStrBldr -
            // 1. Use SetIntPropValues or SetStrPropValues to set a property "to be applied to any subsequent append operations".
            // 2. THEN use Append(string s) to add a string, which will "pick up" the properties set in step 1.
            // See ScrFootnoteFactory.CreateRunFromStringRep() in LcmFactoryAdditions.cs for a good example.
            if (source == null)
            {
                return(null);
            }
            List <Run> runs    = GetSpanRuns(source);
            var        builder = TsStringUtils.MakeIncStrBldr();

            // Will become: ITsIncStrBldr builder = TsStringUtils.MakeIncStrBldr();  // Add "using SIL.CoreImpl;" when this line is uncommented.
            foreach (Run run in runs)
            {
                builder.ClearProps();                 // Make sure there aren't leftover properties from previous run
                // To remove a string property, you set it to null, so we can just use StyleName directly whether or not it's null.
                builder.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, run.StyleName);
                int runWs = (run.Lang == null) ? mainWs : wsf.GetWsFromStr(run.Lang);
                builder.SetIntPropValues((int)FwTextPropType.ktptWs, (int)FwTextPropVar.ktpvDefault, runWs);
                // We don't care about Guids in this function, so run.Guid is ignored
                // But we do need to set any other int or string properties that were in the original
                if (run.IntProperties != null)
                {
                    foreach (KeyValuePair <int, IntProperty> prop in run.IntProperties)
                    {
                        builder.SetIntPropValues(prop.Key, prop.Value.Variation, prop.Value.Value);
                    }
                }
                if (run.StringProperties != null)
                {
                    foreach (KeyValuePair <int, string> prop in run.StringProperties)
                    {
                        builder.SetStrPropValue(prop.Key, prop.Value);
                    }
                }
                builder.Append(run.Content);
            }
            return(builder.GetString());
        }
Exemplo n.º 36
0
        public void Init()
        {
            m_inMemoryCache = ScrInMemoryFdoCache.Create(this);
            m_inMemoryCache.InitializeLangProject();
            m_inMemoryCache.InitializeScripture();
            m_inMemoryCache.AddBookToMockedScripture(1, "Genesis");
            m_inMemoryCache.AddBookToMockedScripture(2, "Exodus");
            m_inMemoryCache.AddBookToMockedScripture(5, "Deuteronomy");
            m_James = m_inMemoryCache.AddBookToMockedScripture(59, "James");
            m_inMemoryCache.AddBookToMockedScripture(66, "Revelation");
            m_fdoCache = m_inMemoryCache.Cache;

            m_scr = (Scripture)m_fdoCache.LangProject.TranslatedScriptureOA;

            m_ctrlOwner = new Form();

            ILgWritingSystemFactory wsf = m_fdoCache.LanguageWritingSystemFactoryAccessor;

            m_scp   = new DummyScrPassageControl(null, m_scr, false);
            m_dbScp = new DummyScrPassageControl(null, m_scr, true);

            m_ctrlOwner.Controls.Add(m_scp);
            m_ctrlOwner.Controls.Add(m_dbScp);
            m_ctrlOwner.CreateControl();

            if (m_scp.DropDownWindow != null)
            {
                m_scp.DropDownWindow.Close();
            }

            if (m_dbScp.DropDownWindow != null)
            {
                m_dbScp.DropDownWindow.Close();
            }

            // Forcing the reference to this should reset the ScrReference object for us
            // which, we hope will cause some strange errors to occur when running in
            // console mode. The tests seem to always work in gui mode but not console mode.
            m_scp.ScReference   = new ScrReference(01001001, m_scr.Versification);
            m_dbScp.ScReference = new ScrReference(01001001, m_scr.Versification);
        }
Exemplo n.º 37
0
        /// <summary>
        /// The user abbreviation we'd like to see typically for this writing system.
        /// Currently this is the user writing system of the Abbr field, or if that
        /// is empty, the ICU code.
        /// We will probably change this (when everything is using it) to try
        /// the analysis writing systems in order, then the user ws.
        /// </summary>
        public static ITsString UserAbbr(FdoCache cache, int hvo)
        {
            ITsString result = cache.MainCacheAccessor.get_MultiStringAlt(hvo,
                                                                          (int)LgWritingSystem.LgWritingSystemTags.kflidAbbr, cache.DefaultUserWs);

            if (result != null && result.Length != 0)
            {
                return(result);
            }
            ILgWritingSystemFactory wsf = cache.LanguageWritingSystemFactoryAccessor;
            IWritingSystem          ws  = wsf.get_EngineOrNull(hvo);

            if (ws == null)
            {
                return(cache.MakeUserTss(Strings.ksStars));
            }
            else
            {
                return(cache.MakeUserTss(ws.get_UiName(cache.DefaultUserWs)));
            }
        }
Exemplo n.º 38
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Deserializes text properties from the specified XML node.
		/// </summary>
		/// <param name="xml">The XML node.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// <returns>The created TsTextProps. Will never be <c>null</c> because an exception is
		/// thrown if anything is invalid.</returns>
		/// ------------------------------------------------------------------------------------
		public static ITsTextProps DeserializePropsFromXml(XElement xml, ILgWritingSystemFactory lgwsf)
		{
			ITsPropsBldr propsBldr = GetPropAttributesForElement(xml, lgwsf);

			foreach (XElement element in xml.Elements())
			{
				switch (element.Name.LocalName)
				{
					case "BulNumFontInfo":
						AddBulletFontInfoToBldr(propsBldr, element, lgwsf);
						break;
					case "WsStyles9999":
						AddWsStyleInfoToBldr(propsBldr, element, lgwsf);
						break;
					default:
						throw new XmlSchemaException("Illegal element in <Props> element: " + element.Name.LocalName);
				}
			}

			return propsBldr.GetTextProps();
		}
Exemplo n.º 39
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes the data source combo.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void CheckForScrProject()
        {
            if (m_cache == null || m_langDef == null)
            {
                return;
            }

            m_scrChecksDllFile = DirectoryFinder.BasicEditorialChecksDll;

            ILgWritingSystemFactory lgwsf = m_cache.LanguageWritingSystemFactoryAccessor;
            string strLocale = m_langDef.HasChangedIcuLocale ? m_langDef.LocaleAbbr :
                               m_langDef.IcuLocaleOriginal;
            bool modifyingVernWs =
                lgwsf.GetWsFromStr(strLocale) == m_cache.DefaultVernWs;

            // If TE isn't installed, we can't support creating an inventory
            // based on Scripture data.
            cmnuScanScripture.Visible = (MiscUtils.IsTEInstalled &&
                                         File.Exists(m_scrChecksDllFile) &&
                                         m_cache.LangProject.TranslatedScriptureOA != null && modifyingVernWs);
        }
Exemplo n.º 40
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes categories in the hierarchy.
        /// </summary>
        /// <param name="categoryList">The list of categories for a Scripture note.</param>
        /// <param name="lgwsf">The language writing system factory.</param>
        /// <exception cref="ArgumentOutOfRangeException">thrown when the category list is empty.
        /// </exception>
        /// ------------------------------------------------------------------------------------
        private void InitializeCategory(List <CategoryNode> categoryList, ILgWritingSystemFactory lgwsf)
        {
            XmlNoteCategory curCategory = this;
            CategoryNode    node        = null;

            for (int i = 0; i < categoryList.Count; i++)
            {
                node = categoryList[i];
                curCategory.CategoryName = node.CategoryName;
                curCategory.IcuLocale    = lgwsf.GetStrFromWs(node.Ws);
                if (categoryList.Count > i + 1)
                {
                    curCategory.SubCategory = new XmlNoteCategory();
                    curCategory             = curCategory.SubCategory;
                }
                else
                {
                    curCategory.SubCategory = null;
                }
            }
        }
        /// <summary>
        /// Reload the vector in the root box, presumably after it's been modified by a chooser.
        /// </summary>
        public override void ReloadVector()
        {
            CheckDisposed();
            ITsStrFactory tsf = m_fdoCache.TsStrFactory;
            int           ws  = 0;

            if (m_rootObj != null && m_rootObj.IsValidObject)
            {
                ILgWritingSystemFactory wsf = m_fdoCache.WritingSystemFactory;
                int count = m_sda.get_VecSize(m_rootObj.Hvo, m_rootFlid);
                // This loop is mostly redundant now that the decorator will generate labels itself as needed.
                // It still serves the purpose of figuring out the WS that should be used for the 'fake' item where the user
                // is typing to select.
                for (int i = 0; i < count; ++i)
                {
                    int hvo = m_sda.get_VecItem(m_rootObj.Hvo, m_rootFlid, i);
                    Debug.Assert(hvo != 0);
                    ws = m_sda.GetLabelFor(hvo).get_WritingSystem(0);
                }

                if (ws == 0)
                {
                    var list = (ICmPossibilityList)m_rootObj.ReferenceTargetOwner(m_rootFlid);
                    ws = list.IsVernacular ? m_fdoCache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem.Handle
                                                 : m_fdoCache.ServiceLocator.WritingSystems.DefaultAnalysisWritingSystem.Handle;
                    if (list.PossibilitiesOS.Count > 0)
                    {
                        ObjectLabel label = ObjectLabel.CreateObjectLabel(m_fdoCache, list.PossibilitiesOS[0], m_displayNameProperty, m_displayWs);
                        ws = label.AsTss.get_WritingSystem(0);
                    }
                }
            }

            if (ws == 0)
            {
                ws = m_fdoCache.ServiceLocator.WritingSystems.DefaultAnalysisWritingSystem.Handle;
            }
            m_sda.Strings[khvoFake] = tsf.EmptyString(ws);
            base.ReloadVector();
        }
Exemplo n.º 42
0
        /// <summary>
        /// This method will update the phraseText ref item with the contents of the item entries under the word
        /// </summary>
        /// <param name="wsFactory"></param>
        /// <param name="tsStrFactory"></param>
        /// <param name="phraseText"></param>
        /// <param name="word"></param>
        /// <param name="lastWasWord"></param>
        /// <param name="space"></param>
        private static void UpdatePhraseTextForWordItems(ILgWritingSystemFactory wsFactory, ITsStrFactory tsStrFactory, ref ITsString phraseText, Word word, ref bool lastWasWord, char space)
        {
            bool isWord = false;

            foreach (var item in word.Items)
            {
                switch (item.type)
                {
                case "txt":                         //intentional fallthrough
                    isWord = true;
                    goto case "punct";

                case "punct":
                    ITsString wordString = tsStrFactory.MakeString(item.Value,
                                                                   GetWsEngine(wsFactory, item.lang).Handle);
                    if (phraseText == null)
                    {
                        phraseText = wordString;
                    }
                    else
                    {
                        var phraseBldr = phraseText.GetBldr();
                        if (lastWasWord && isWord)                                 //two words next to each other deserve a space between
                        {
                            phraseBldr.ReplaceTsString(phraseText.Length, phraseText.Length,
                                                       tsStrFactory.MakeString("" + space, GetWsEngine(wsFactory, item.lang).Handle));
                        }
                        else if (!isWord)                                 //handle punctuation
                        {
                            wordString = GetSpaceAdjustedPunctString(wsFactory, tsStrFactory,
                                                                     item, wordString, space, lastWasWord);
                        }
                        phraseBldr.ReplaceTsString(phraseBldr.Length, phraseBldr.Length, wordString);
                        phraseText = phraseBldr.GetString();
                    }
                    lastWasWord = isWord;
                    return;                             // only handle the baseline "txt" or "punct" once per "word" bundle, especially don't want extra writing system content in the baseline.
                }
            }
        }
Exemplo n.º 43
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlScrNote"/> class based on
        /// the given Scripture note.
        /// </summary>
        /// <param name="ann">The Scripture annotation.</param>
        /// <param name="wsDefault">The default (analysis) writing system.</param>
        /// <param name="lgwsf">The writing system factory.</param>
        /// ------------------------------------------------------------------------------------
        public XmlScrNote(IScrScriptureNote ann, int wsDefault, ILgWritingSystemFactory lgwsf)
            : this()
        {
            m_wsDefault      = wsDefault;
            m_lgwsf          = lgwsf;
            ResolutionStatus = ann.ResolutionStatus;
            m_typeName       = ann.AnnotationTypeRA.Name.get_String(WritingSystemServices.FallbackUserWs(ann.Cache)).Text;
            m_guidType       = ann.AnnotationTypeRA.Guid;
            SetNoteType(ann);

            m_startRef = ann.BeginRef;
            if (ann.BeginRef != ann.EndRef)
            {
                m_endRef = ann.EndRef;
            }

            if (ann.BeginObjectRA != null)
            {
                m_guidBegObj = ann.BeginObjectRA.Guid;
            }

            if (ann.BeginObjectRA != ann.EndObjectRA && ann.EndObjectRA != null)
            {
                m_guidEndObj = ann.EndObjectRA.Guid;
            }

            BeginOffset = ann.BeginOffset;
            EndOffset   = ann.EndOffset;

            m_createdDate  = ann.DateCreated;
            m_modifiedDate = ann.DateModified;
            m_resolvedDate = ann.DateResolved;

            Quote      = XmlNotePara.GetParagraphList(ann.QuoteOA, m_wsDefault, m_lgwsf);
            Discussion = XmlNotePara.GetParagraphList(ann.DiscussionOA, m_wsDefault, m_lgwsf);
            Suggestion = XmlNotePara.GetParagraphList(ann.RecommendationOA, m_wsDefault, m_lgwsf);
            Resolution = XmlNotePara.GetParagraphList(ann.ResolutionOA, m_wsDefault, m_lgwsf);
            Categories = XmlNoteCategory.GetCategoryList(ann, m_lgwsf);
            Responses  = XmlNoteResponse.GetResponsesList(ann, m_wsDefault, m_lgwsf);
        }
Exemplo n.º 44
0
        /// <summary>
        /// LT-11603 was traced in part to calls to Dictionary.Exists which never return, possibly because
        /// the OS has become confused and thinks the file is locked. To guard against this we run the test in a background
        /// thread with a timeout. Not sure whether this is enough protection, other calls may be at risk also, but if
        /// we can confirm the dictionary exists at least it isn't spuriously locked when we first consider it.
        /// </summary>
        private static bool DictionaryExists(string wsId, int ws, ILgWritingSystemFactory wsf)
        {
            bool result;

            if (s_existingDictionaries.TryGetValue(wsId, out result))
            {
                return(result);
            }
            if (!ValidEnchantId(wsId))
            {
                var wsName = wsf.GetStrFromWs(ws);
                var form   = Form.ActiveForm;
                var msg    = string.Format(FwUtilsStrings.kstidInvalidDictId, wsName, wsId);
                MessageBox.Show(form, msg, FwUtilsStrings.kstidCantDoDictExistsCaption,
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            var tester = new ExistsTester()
            {
                WsId = wsId
            };
            var newThread = new Thread(tester.Test);

            newThread.Start();
            if (newThread.Join(4000))
            {
                result = tester.Result;
            }
            else
            {
                result = false;

                var form = Form.ActiveForm;
                MessageBox.Show(form, String.Format(FwUtilsStrings.kstIdCantDoDictExists, wsId), FwUtilsStrings.kstidCantDoDictExistsCaption,
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            s_existingDictionaries[wsId] = result;
            return(result);
        }
Exemplo n.º 45
0
        public override void Display(IVwEnv vwenv, int hvo, int frag)
        {
            CheckDisposed();

            switch (frag)
            {
            case AudioVisualView.kfragPathname:
                // Display the filename.
                ILgWritingSystemFactory wsf =
                    m_cache.LanguageWritingSystemFactoryAccessor;
                vwenv.set_IntProperty((int)FwTextPropType.ktptEditable,
                                      (int)FwTextPropVar.ktpvDefault,
                                      (int)TptEditable.ktptNotEditable);
                ITsString tss;
                Debug.Assert(hvo != 0);
                Debug.Assert(m_cache != null);
                ICmFile file = CmFile.CreateFromDBObject(m_cache, hvo);
                Debug.Assert(file != null);
                string path;
                if (Path.IsPathRooted(file.InternalPath))
                {
                    path = file.InternalPath;
                }
                else
                {
                    path = Path.Combine(m_cache.LangProject.ExternalLinkRootDir,
                                        file.InternalPath);
                }
                tss = m_cache.MakeUserTss(path);
                vwenv.OpenParagraph();
                vwenv.AddString(tss);
                vwenv.CloseParagraph();
                break;

            default:
                throw new ArgumentException(
                          "Don't know what to do with the given frag.", "frag");
            }
        }
Exemplo n.º 46
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Import a file (encapsulated by a TextReader) containing translations for one or more lists.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public bool ImportTranslatedLists(TextReader reader, FdoCache cache, IProgress progress)
        {
            m_cache         = cache;
            m_mdc           = cache.ServiceLocator.GetInstance <IFwMetaDataCacheManaged>();
            m_rgItemClasses = m_mdc.GetAllSubclasses(CmPossibilityTags.kClassId);
            m_wsf           = cache.WritingSystemFactory;
            m_wsEn          = GetWsFromStr("en");
            Debug.Assert(m_wsEn != 0);
            m_progress = progress;

            try
            {
                using (var xreader = XmlReader.Create(reader))
                    Import(xreader);
            }
            catch (Exception e)
            {
                MessageBoxUtils.Show(e.Message, "Import Error");
                return(false);
            }
            return(true);
        }
Exemplo n.º 47
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="T:SimpleMatchDlg"/> class.
        /// </summary>
        /// <param name="wsf">The WSF.</param>
        /// <param name="helpTopicProvider">The help topic provider.</param>
        /// <param name="ws">The ws.</param>
        /// <param name="ss">The ss.</param>
        /// <param name="cache"></param>
        /// ------------------------------------------------------------------------------------
        public SimpleMatchDlg(ILgWritingSystemFactory wsf, IHelpTopicProvider helpTopicProvider,
                              int ws, IVwStylesheet ss, FdoCache cache)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            m_cache = cache;

            // We do this outside the designer-controlled code because it does funny things
            // to FwTextBoxes, owing to the need for a writing system factory, and some
            // properties it should not persist but I can't persuade it not to.
            this.m_textBox = new FwTextBox();
            this.m_textBox.WritingSystemFactory = wsf;  // set ASAP.
            this.m_textBox.WritingSystemCode    = ws;
            this.m_textBox.StyleSheet           = ss;   // before setting text, otherwise it gets confused about height needed.
            this.m_textBox.Location             = new System.Drawing.Point(8, 24);
            this.m_textBox.Name     = "m_textBox";
            this.m_textBox.Size     = new System.Drawing.Size(450, 32);
            this.m_textBox.TabIndex = 0;
            this.m_textBox.Text     = "";
            this.Controls.Add(this.m_textBox);
            AccessibleName      = "SimpleMatchDlg";
            m_helpTopicProvider = helpTopicProvider;

            regexContextMenu = new RegexHelperMenu(m_textBox, m_helpTopicProvider);

            m_ivwpattern = VwPatternClass.Create();

            helpProvider = new HelpProvider();
            helpProvider.HelpNamespace = m_helpTopicProvider.HelpFile;
            helpProvider.SetHelpKeyword(this, m_helpTopicProvider.GetHelpString(s_helpTopic));
            helpProvider.SetHelpNavigator(this, HelpNavigator.Topic);
            foreach (Control control in Controls)
            {
                control.Click += new EventHandler(control_Click);
            }
        }
Exemplo n.º 48
0
        public void AddingWritingSystems()
        {
            Assert.AreEqual(1, Cache.LangProject.CurrentVernacularWritingSystems.Count, "Only one current vernacular WS");
            Assert.AreEqual(1, Cache.LangProject.VernacularWritingSystems.Count, "Only one vernacular WS");
            Assert.IsFalse(Cache.LangProject.VernWss.Contains("es"), "Vernacular WSs do not include Spanish");
            Assert.IsFalse(Cache.LangProject.CurVernWss.Contains("es"), "Current Vernacular WSs do not include Spanish");
            Assert.IsFalse(Cache.LangProject.AnalysisWss.Contains("es"), "Analysis WSs do not include Spanish");
            Assert.IsFalse(Cache.LangProject.CurAnalysisWss.Contains("es"), "Current Analysis WSs do not include Spanish");

            Assert.AreEqual(1, Cache.LangProject.CurrentAnalysisWritingSystems.Count, "Only one current analysis WS");
            Assert.AreEqual(1, Cache.LangProject.AnalysisWritingSystems.Count, "Only one analysis WS");
            Assert.IsFalse(Cache.LangProject.VernWss.Contains("de"), "Vernacular WSs do not include German");
            Assert.IsFalse(Cache.LangProject.CurVernWss.Contains("de"), "Current Vernacular WSs do not include German");
            Assert.IsFalse(Cache.LangProject.AnalysisWss.Contains("de"), "Analysis WSs do not include German");
            Assert.IsFalse(Cache.LangProject.CurAnalysisWss.Contains("de"), "Current Analysis WSs do not include German");

            ILgWritingSystemFactory factWs = Cache.ServiceLocator.GetInstance <ILgWritingSystemFactory>();
            int wsEs = factWs.GetWsFromStr("es");

            if (wsEs != 0)
            {
                Cache.LangProject.VernWss    = Cache.LangProject.VernWss + " es";
                Cache.LangProject.CurVernWss = Cache.LangProject.CurVernWss + " es";
                Assert.AreEqual(2, Cache.LangProject.CurrentVernacularWritingSystems.Count, "Now two current vernacular WS");
                Assert.AreEqual(2, Cache.LangProject.VernacularWritingSystems.Count, "Now two vernacular WS");
            }
            int wsDe = factWs.GetWsFromStr("de");

            if (wsDe != 0)
            {
                IWritingSystem german = factWs.get_EngineOrNull(wsDe) as IWritingSystem;
                Assert.IsNotNull(german, "IWritingSystem and ILgWritingSystem are the same now");
                Cache.LangProject.AnalysisWritingSystems.Add(german);
                Cache.LangProject.CurrentAnalysisWritingSystems.Add(german);
                Assert.IsTrue(Cache.LangProject.AnalysisWss.Contains("de"), "Analysis WSs now include German");
                Assert.IsTrue(Cache.LangProject.CurAnalysisWss.Contains("de"), "Current Analysis WSs now include German");
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// Adds the default word-forming character overrides to the list of valid
        /// characters for each vernacular writing system that is using the old
        /// valid characters representation.
        /// </summary>
        /// <param name="cache">The cache.</param>
        void AddDefaultWordformingOverridesIfNeeded(FdoCache cache)
        {
            ILgWritingSystemFactory lgwsf = cache.LanguageWritingSystemFactoryAccessor;

            foreach (ILgWritingSystem wsObj in cache.LangProject.VernWssRC)
            {
                IWritingSystem ws            = lgwsf.get_EngineOrNull(wsObj.Hvo);
                string         validCharsSrc = ws.ValidChars;
                if (!ValidCharacters.IsNewValidCharsString(validCharsSrc))
                {
                    LanguageDefinition langDef  = new LanguageDefinition(ws);
                    ValidCharacters    valChars = ValidCharacters.Load(langDef);
                    valChars.AddDefaultWordformingCharOverrides();

                    ws.ValidChars = langDef.ValidChars = valChars.XmlString;
                    using (new SuppressSubTasks(cache))
                    {
                        ws.SaveIfDirty(cache.DatabaseAccessor);
                    }
                    langDef.Serialize();
                }
            }
        }
Exemplo n.º 50
0
        // The raw id that should be used to create a dictionary for the given WS, if none exists.
        private static string RawDictionaryId(int ws, ILgWritingSystemFactory wsf)
        {
            ILgWritingSystem wsEngine = wsf.get_EngineOrNull(ws);

            if (wsEngine == null)
            {
                return(null);
            }
            string wsId = wsEngine.SpellCheckingId;

            if (String.IsNullOrEmpty(wsId))
            {
                // Our old spelling engine, Enchant, did not allow hyphen;
                // keeping that rule in case we switch again or there is some other good reason for it that we don't know.
                // Changing to underscore is OK since lang ID does not allow underscore.
                return(wsEngine.Id.Replace('-', '_'));
            }
            if (wsId == "<None>")
            {
                return(null);
            }
            return(wsId);
        }
Exemplo n.º 51
0
            public void AddToDatabase(FdoCache cache, ICmPossibilityList posList, MasterCategory parent, IPartOfSpeech subItemOwner)
            {
                CheckDisposed();

                if (m_pos != null)
                {
                    return;                     // It's already in the database, so nothing more can be done.
                }
                cache.BeginUndoTask(LexTextControls.ksUndoCreateCategory,
                                    LexTextControls.ksRedoCreateCategory);
                int newOwningFlid;
                int insertLocation;
                int newOwner =
                    DeterminePOSLocationInfo(subItemOwner, parent, posList, out newOwningFlid, out insertLocation);
                ILgWritingSystemFactory wsf = cache.LanguageWritingSystemFactoryAccessor;

                Debug.Assert(m_pos != null);

                if (m_node == null)
                {                 // should not happen, but just in case... we still get something useful
                    m_pos.Name.SetAlternative(m_term, wsf.GetWsFromStr(m_termWs));
                    m_pos.Abbreviation.SetAlternative(m_abbrev, wsf.GetWsFromStr(m_abbrevWs));
                    m_pos.Description.SetAlternative(m_def, wsf.GetWsFromStr(m_defWs));
                }
                else
                {
                    SetContentFromNode(cache, "abbrev", false, m_pos.Abbreviation);
                    SetContentFromNode(cache, "term", true, m_pos.Name);
                    SetContentFromNode(cache, "def", false, m_pos.Description);
                }

                m_pos.CatalogSourceId = m_id;
                // Need a PropChanged, since it isn't done in the 'Append' for some reason.
                cache.PropChanged(null, PropChangeType.kpctNotifyAll,
                                  newOwner, newOwningFlid, insertLocation, 1, 0);
                cache.EndUndoTask();
            }
Exemplo n.º 52
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the valid characters list.
        /// </summary>
        /// <param name="key">The valid characters parameter key.</param>
        /// <param name="ws">The default vernacular writing system.</param>
        /// ------------------------------------------------------------------------------------
        private string GetValidCharactersList(string key, IWritingSystem ws)
        {
            if (key.StartsWith("ValidCharacters_"))
            {
                // If the key contains a locale ID, then don't use the default vernacular
                // writing system, build one from the locale.
                ILgWritingSystemFactory lgwsf = m_cache.LanguageWritingSystemFactoryAccessor;
                string icuLocale = key.Substring(key.IndexOf("_") + 1);
                int    hvoWs     = lgwsf.GetWsFromStr(icuLocale);
                ws = lgwsf.get_EngineOrNull(hvoWs);
            }
            else if (key == "AlwaysValidCharacters")
            {
                StringBuilder bldr = new StringBuilder(13);

                // Add the vernacular digits 0 through 9.
                for (int i = 0; i < 10; i++)
                {
                    bldr.Append(m_scr.ConvertToString(i));
                }

                if (ws.RightToLeft)
                {
                    // Add the LTR and RTL marks.
                    bldr.Append('\u202A');
                    bldr.Append('\u202B');
                }

                // Add the line separator.
                bldr.Append('\u2028');
                return(bldr.ToString());
            }

            ValidCharacters validChars = ValidCharacters.Load(ws);

            return(validChars != null ? validChars.SpaceDelimitedList : string.Empty);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Gets the character render properties for the given style name and writing system.
        /// </summary>
        /// <param name="styleName">The style name.</param>
        /// <param name="styleSheet">The stylesheet.</param>
        /// <param name="hvoWs">The HVO of the WS.</param>
        /// <param name="writingSystemFactory">The writing system factory.</param>
        /// <returns>The character render properties.</returns>
        public static LgCharRenderProps GetChrpForStyle(string styleName, IVwStylesheet styleSheet,
                                                        int hvoWs, ILgWritingSystemFactory writingSystemFactory)
        {
            if (string.IsNullOrEmpty(writingSystemFactory.GetStrFromWs(hvoWs)))
            {
                try
                {
                    //You may have forgotten to set the WritingSystemFactory in a recently added custom control?
                    throw new ArgumentException("This is a hard-to-reproduce scenario (TE-6891) where writing system (" + hvoWs + ") and factory are inconsistent.");
                }
                catch (ArgumentException e)
                {
                    Logger.WriteError(e);
                    var msg = e.Message + " If we aren't called from a Widget, "
                              + "call an expert (JohnT) while you have this Assert active!";
                    Debug.Fail(msg);
                    hvoWs = writingSystemFactory.UserWs;
                }
            }

            IVwPropertyStore vwps = VwPropertyStoreClass.Create();

            vwps.Stylesheet           = styleSheet;
            vwps.WritingSystemFactory = writingSystemFactory;

            ITsPropsBldr ttpBldr = TsPropsBldrClass.Create();

            ttpBldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, styleName);
            ttpBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, hvoWs);
            ITsTextProps ttp = ttpBldr.GetTextProps();

            LgCharRenderProps chrps = vwps.get_ChrpFor(ttp);
            ILgWritingSystem  ws    = writingSystemFactory.get_EngineOrNull(hvoWs);

            ws.InterpretChrp(ref chrps);
            return(chrps);
        }
Exemplo n.º 54
0
        static internal int ReadMultiUnicodeAlternative(XElement aUniNode, ILgWritingSystemFactory wsf, ITsStrFactory tsf, out ITsString tss)
        {
            tss = null;
            var sValue = aUniNode.Value;

            if (String.IsNullOrEmpty(sValue))
            {
                return(0);
            }
            var wsVal = aUniNode.Attribute("ws");

            if (wsVal == null || String.IsNullOrEmpty(wsVal.Value))
            {
                return(0);
            }
            var wsHvo = wsf.GetWsFromStr(wsVal.Value);

            // Throwing out a string without a ws is probably better than crashing
            // and preventing a db from being opened.
            // This code currently accepts this data, only storing en__IPA and fr strings.
            // <Form>
            // <AUni ws="en" />
            // <AUni ws="en__IPA">problematic</AUni>
            // <AUni>missing</AUni>
            // <AUni></AUni>
            // <AUni ws="fr">french</AUni>
            // <AUni/>
            // </Form>
            if (wsHvo == 0)
            {
                return(0);
            }
            var text = Icu.Normalize(sValue, Icu.UNormalizationMode.UNORM_NFD);

            tss = tsf.MakeString(text, wsHvo);
            return(wsHvo);
        }
        protected override void PopulatePossibilityFromExtraData(ICmPossibility poss)
        {
            ICmSemanticDomain semdom = poss as ICmSemanticDomain;

            if (semdom == null)
            {
                return;
            }
            ILgWritingSystemFactory wsf = semdom.Cache.WritingSystemFactory;
            var questionFactory         = semdom.Cache.ServiceLocator.GetInstance <ICmDomainQFactory>();
            Dictionary <string, List <SemDomQuestion> > questionsByWs = GetExtraDataWsDict <SemDomQuestion>("Questions");
            // This dict looks like {"en": (question 1, question 2...)} but each question object wants to get data that
            // looks more or less like {"en": "the question in English", "fr": "la question en francais"}...
            // So first we ensure that there are enough question objects available, and then we'll access them by index
            // as we step through the writing systems.
            int numQuestions = questionsByWs.Values.Select(questionList => questionList.Count).Max();

            while (semdom.QuestionsOS.Count < numQuestions)
            {
                semdom.QuestionsOS.Add(questionFactory.Create());
            }
            foreach (string ws in questionsByWs.Keys)
            {
                int wsId = wsf.GetWsFromStr(ws);
                int i    = 0;
                foreach (SemDomQuestion qStruct in questionsByWs[ws])
                {
                    // TODO: Find out what set_String() would do with a null value. Would it remove the string?
                    // If it would *remove* it, then we might be able to replace string.Empty with nulls in the code below
                    // Right now, just be extra-cautious and ensure we never put nulls into set_String().
                    semdom.QuestionsOS[i].Question.set_String(wsId, qStruct.Question ?? string.Empty);
                    semdom.QuestionsOS[i].ExampleSentences.set_String(wsId, qStruct.ExampleSentences ?? string.Empty);
                    semdom.QuestionsOS[i].ExampleWords.set_String(wsId, qStruct.ExampleWords ?? string.Empty);
                    i++;
                }
            }
        }
Exemplo n.º 56
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get an XML representation of the given ITsString.
		/// </summary>
		/// <param name="tss">The ITsString object</param>
		/// <param name="wsf">Writing system factory so that we can convert writing system
		/// integer codes (which are database object ids) to the corresponding strings.</param>
		/// <param name="ws">If nonzero, the writing system for a multilingual string (&lt;AStr&gt;).
		/// If zero, then this is a monolingual string (&lt;Str&gt;).</param>
		/// <returns>
		/// The XML representation of <paramref name="tss"/>.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		public static string GetXmlRep(ITsString tss, ILgWritingSystemFactory wsf, int ws)
		{
			return GetXmlRep(tss, wsf, ws, true);
		}
Exemplo n.º 57
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get an XML representation of the given ITsString.
		/// </summary>
		/// <param name="tss">The ITsString object</param>
		/// <param name="wsf">Writing system factory so that we can convert writing system
		/// integer codes (which are database object ids) to the corresponding strings.</param>
		/// <param name="ws">If nonzero, the writing system for a multilingual string (&lt;AStr&gt;).
		/// If zero, then this is a monolingual string (&lt;Str&gt;).</param>
		/// <param name="fWriteObjData"> If true, then write out embedded pictures and links.  If false, ignore
		///	any runs that contain such objects. </param>
		/// <returns>
		/// The XML representation of <paramref name="tss"/>.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		public static string GetXmlRep(ITsString tss, ILgWritingSystemFactory wsf, int ws, bool fWriteObjData)
		{
			return tss.GetXmlString(wsf, 0, ws, fWriteObjData);
		}
Exemplo n.º 58
0
		/// <summary>
		/// make the compiler happy.
		/// </summary>
		public CpeTracker(ILgWritingSystemFactory wsf, ITsString tss)
		{
			m_wsf = wsf;
			m_tssText = tss;
			m_ichLimCpe = 0;
			// ensures first request will fail.
		}
Exemplo n.º 59
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determine if the specified text exists in the string
		/// </summary>
		/// <param name="wordFormTss">text to look for</param>
		/// <param name="sourceTss">text to search in</param>
		/// <param name="wsf">source of char prop engines</param>
		/// <param name="fMatchWholeWord">True to match a whole word, false otherwise</param>
		/// <param name="ichMin">The start of the string where the text was found (undefined if
		/// this method returns false)</param>
		/// <param name="ichLim">The limit (one character position past the end) of the string
		/// where the text was found (undefined if this method returns false)</param>
		/// <returns><c>true</c> if the text is matched exactly (matching case)
		/// </returns>
		/// <remarks>
		/// TODO: Add a parameter to make it possible to do a case-insensitive match?</remarks>
		/// ------------------------------------------------------------------------------------
		public static bool FindTextInString(ITsString wordFormTss, ITsString sourceTss, ILgWritingSystemFactory wsf, bool fMatchWholeWord, out int ichMin, out int ichLim)
		{
			ichMin = ichLim = 0;

			if (wordFormTss == null || sourceTss == null || wordFormTss.Length == 0 || sourceTss.Length == 0)
			{
				// Nothing we can really do
				return false;
			}

			int ichWordForm = 0;
			bool fMatchInProgress = false;
			CpeTracker sourceTracker = new CpeTracker(wsf, sourceTss);
			CpeTracker wordTracker = new CpeTracker(wsf, wordFormTss);
			string wordForm = wordFormTss.Text;
			string sourceText = sourceTss.Text;
			bool fWordFormAndSrcAreBothNormalized = wordForm.IsNormalized() && sourceText.IsNormalized();
			bool fPrevCharWasWordForming = false;
			// Must use local temp variable because some callers pass same variable as both
			// ichMin and ichLim.
			int ichLimT;
			for (int ichSrc = 0; ichSrc < sourceText.Length; ichSrc = ichLimT)
			{
				ichLimT = ichSrc + 1;
				bool fWordForming = sourceTracker.CharPropEngine(ichSrc).get_IsWordForming(sourceText[ichSrc]);
				if (!fMatchInProgress && fPrevCharWasWordForming && fWordForming && fMatchWholeWord)
					continue;

				fPrevCharWasWordForming = fWordForming;
				if (!fMatchInProgress && !fWordForming)
					continue;

				bool fMatch = (wordForm[ichWordForm] == sourceText[ichSrc]);

				if (fMatch)
				{
					ichWordForm++;
				}

				else
				{
					if (sourceText[ichSrc] == StringUtils.kChObject)
						fMatch = true;
					else if (!fWordFormAndSrcAreBothNormalized)
					{
						int ichWfCharLim = ichWordForm + 1;

						while (ichWfCharLim < wordForm.Length && !wordTracker.CharPropEngine(ichWfCharLim).get_IsLetter(wordForm[ichWfCharLim]) && wordTracker.CharPropEngine(ichWfCharLim).get_IsWordForming(wordForm[ichWfCharLim]))
						{
							ichWfCharLim++;
						}

						while (ichLimT < sourceText.Length && !sourceTracker.CharPropEngine(ichLimT).get_IsLetter(sourceText[ichLimT]) && sourceTracker.CharPropEngine(ichLimT).get_IsWordForming(sourceText[ichLimT]))
						{
							ichLimT++;
						}

						if (wordForm.Substring(ichWordForm, ichWfCharLim - ichWordForm).Normalize() == sourceText.Substring(ichSrc, ichLimT - ichSrc).Normalize())
						{
							ichWordForm = ichWfCharLim;
							fMatch = true;
						}
					}
				}

				if (fMatch)
				{
					// If this character is the start of a match but the previous character was
					// word-forming, then this is a bogus match, so we keep looking.
					if (!fMatchInProgress)
					{
						if (ichSrc == 0 || !sourceTracker.CharPropEngine(ichSrc - 1).get_IsWordForming(sourceText[ichSrc - 1]) || !fMatchWholeWord)
						{
							ichMin = ichSrc;
							fMatchInProgress = true;
						}

						else
							ichWordForm = 0;
					}

					if (fMatchInProgress && ichWordForm == wordForm.Length)
					{
						if (++ichSrc < sourceText.Length && sourceTracker.CharPropEngine(ichSrc).get_IsWordForming(sourceText[ichSrc]) && fMatchWholeWord)
						{
							ichWordForm = 0;
							fMatchInProgress = false;
						}

						else
						{
							ichLim = ichLimT;
							return true;
						}
					}
				}

				else
				{
					ichWordForm = 0;
					fMatchInProgress = false;
				}
			}
			return false;
		}
Exemplo n.º 60
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determine if the word form exists in the string, matching the whole word or
		/// sequence of words.
		/// </summary>
		/// <param name="wordFormTss">text of word form to look for</param>
		/// <param name="sourceTss">text to search in</param>
		/// <param name="wsf">source of char prop engines</param>
		/// <param name="ichMin">The start of the string where the text was found (undefined if
		/// this method returns false)</param>
		/// <param name="ichLim">The limit (one character position past the end) of the string
		/// where the text was found (undefined if this method returns false)</param>
		/// <returns><c>true</c> if word form is matched exactly (whole word found and matching
		/// case)
		/// </returns>
		/// <remarks>
		/// TODO: Add a parameter to make it possible to do a case-insensitive match?</remarks>
		/// ------------------------------------------------------------------------------------
		public static bool FindWordFormInString(ITsString wordFormTss, ITsString sourceTss, ILgWritingSystemFactory wsf, out int ichMin, out int ichLim)
		{
			return FindTextInString(wordFormTss, sourceTss, wsf, true, out ichMin, out ichLim);
		}