/// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ public void SimulateVernAddingWs(ILgWritingSystem ws) { CheckDisposed(); AddWsToList(ws, m_lstVernWs); UpdateButtons(m_lstVernWs); }
/// <summary> /// Get a dictionary for the specified writing system, or null if we don't know of one. /// We ideally want a dictionary that exactly matches the specified writing system, that is, /// dict.Information.Language == the SpellCheckDictionary of the writing system. /// If we can't find such a dictionary, for major languages (those that have non-trivial base dictionary files), /// we will return a dictionary that shares a prefix, for example, 'en' when looking for 'en_US' or vice versa. /// This is not allowed for minority languages (where the dictionary is one we created ourselves that is empty, /// and all the spelling information is in the overrides kept by Enchant); we return null if we can't find /// an exact match or an approximate match that is a 'major' language dictionary. /// Note: a similar algorithm is unfortunately implemented in VwRootBox::GetDictionary /// and in WritingSystemPropertiesDialog.PopulateSpellingDictionaryComboBox. /// </summary> public static Enchant.Dictionary GetDictionary(int ws, ILgWritingSystemFactory wsf) { string dictId = DictionaryId(ws, wsf); if (dictId == null) { return(null); } Dictionary dict = GetDict(dictId); if (dict == null) { return(null); } ILgWritingSystem engine = wsf.get_EngineOrNull(ws); if (engine == null) { return(dict); // should never happen? Can't verify ID so go ahead and return it. } if (dict.Information.Language == engine.SpellCheckingId) { return(dict); // exact match } if (IsPrivateDictionary(dict.Information.Language)) { return(null); // private dictionaries may only be returned when matching exactly. } return(dict); }
private string WritingSystemId(int ws) { if (ws == 0) { return(String.Empty); } string sWs; if (m_dictWsStr.TryGetValue(ws, out sWs)) { return(sWs); } if (m_fUseRFC4646) { ILgWritingSystem lgws = LgWritingSystem.CreateFromDBObject(m_cache, ws); sWs = lgws.RFC4646bis; } else { sWs = m_cache.LanguageWritingSystemFactoryAccessor.GetStrFromWs(ws); } sWs = XmlUtils.MakeSafeXmlAttribute(sWs); m_dictWsStr.Add(ws, sWs); return(sWs); }
/// <summary> /// Convert FDO example LF example. /// </summary> /// <returns>LF example /// <param name="fdoExample">Fdo example.</param> private LfExample FdoExampleToLfExample(ILexExampleSentence fdoExample) { var lfExample = new LfExample(); ILgWritingSystem AnalysisWritingSystem = ServiceLocator.LanguageProject.DefaultAnalysisWritingSystem; ILgWritingSystem VernacularWritingSystem = ServiceLocator.LanguageProject.DefaultVernacularWritingSystem; lfExample.Guid = fdoExample.Guid; lfExample.Sentence = ToMultiText(fdoExample.Example); lfExample.Reference = LfMultiText.FromSingleITsString(fdoExample.Reference, ServiceLocator.WritingSystemFactory); // ILexExampleSentence fields we currently do not convert: // fdoExample.DoNotPublishInRC; // fdoExample.LiftResidue; // fdoExample.PublishIn; // NOTE: Currently, LanguageForge only stores one translation per example, whereas FDO can store // multiple translations with (possibly) different statuses (as freeform strings, like "old", "updated", // "needs fixing"...). Until LanguageForge acquires a data model where translations are stored in a list, // we will save only the first translation (if any) to Mongo. We also save the GUID so that the Mongo->FDO // direction will know which ICmTranslation object to update with any changes. // TODO: Once LF improves its data model for translations, persist all of them instead of just the first. foreach (ICmTranslation translation in fdoExample.TranslationsOC.Take(1)) { lfExample.Translation = ToMultiText(translation.Translation); lfExample.TranslationGuid = translation.Guid; } BsonDocument customFieldsAndGuids = _convertCustomField.GetCustomFieldsForThisCmObject(fdoExample, "examples", ListConverters); BsonDocument customFieldsBson = customFieldsAndGuids["customFields"].AsBsonDocument; BsonDocument customFieldGuids = customFieldsAndGuids["customFieldGuids"].AsBsonDocument; lfExample.CustomFields = customFieldsBson; lfExample.CustomFieldGuids = customFieldGuids; return(lfExample); }
private void ExportLanguages(TextWriter writer) { string sAnal = AnalWsTag; string sVern = m_cache.WritingSystemFactory.GetStrFromWs(m_cache.DefaultVernWs); writer.WriteLine("<Languages defaultAnal=\"{0}\" defaultVern=\"{1}\">", sAnal, sVern); IWritingSystemManager manager = m_cache.ServiceLocator.GetInstance <IWritingSystemManager>(); foreach (var wsLocal in manager.LocalWritingSystems) { string tag = LangTagUtils.ToLangTag(wsLocal.LanguageSubtag, wsLocal.ScriptSubtag, wsLocal.RegionSubtag, wsLocal.VariantSubtag); ILgWritingSystem lgws = null; int ws = m_cache.WritingSystemFactory.GetWsFromStr(tag); if (ws <= 0) { continue; } lgws = m_cache.WritingSystemFactory.get_EngineOrNull(ws); string code = wsLocal.LanguageSubtag.Code; string type = code.Length == 2 ? "ISO-639-1" : "ISO-639-3"; writer.WriteLine("<WritingSystem id=\"{0}\" language=\"{1}\" type=\"{2}\">", tag, code, type); writer.WriteLine("<Name><Uni>{0}</Uni></Name>", XmlUtils.MakeSafeXml(wsLocal.LanguageName)); writer.WriteLine("<Abbreviation><Uni>{0}</Uni></Abbreviation>", XmlUtils.MakeSafeXml(wsLocal.Abbreviation)); // We previously wrote out the LCID, but this is obsolete. It would be unreliable to output the WindowsLcid, which only // old writing systems will have. If something needs this, we need to output something new in its place. But I'm pretty sure // nothing does...Locale is not used in any of the notebook output transforms. //writer.WriteLine("<Locale><Integer val=\"{0}\"/></Locale>", ((ILegacyWritingSystemDefinition)wsLocal).WindowsLcid); writer.WriteLine("<RightToLeft><Boolean val=\"{0}\"/></RightToLeft>", wsLocal.RightToLeftScript ? "true" : "false"); if (ws == m_cache.DefaultAnalWs) { m_fRightToLeft = wsLocal.RightToLeftScript; } writer.WriteLine("<DefaultFont><Uni>{0}</Uni></DefaultFont>", XmlUtils.MakeSafeXml(wsLocal.DefaultFontName)); if (!String.IsNullOrEmpty(wsLocal.DefaultFontFeatures)) { writer.WriteLine("<DefaultFontFeatures><Uni>{0}</Uni></DefaultFontFeatures>", XmlUtils.MakeSafeXml(wsLocal.DefaultFontFeatures)); } // The following commented out data are probably never needed. //if (!String.IsNullOrEmpty(wsLocal.ValidChars)) // writer.WriteLine("<ValidChars><Uni>{0}</Uni></ValidChars>", // XmlUtils.MakeSafeXml(wsLocal.ValidChars)); //writer.WriteLine("<ICULocale><Uni>{0}</Uni></ICULocale>", // XmlUtils.MakeSafeXml(wsLocal.IcuLocale)); writer.WriteLine("<SortUsing><Uni>{0}</Uni></SortUsing>", XmlUtils.MakeSafeXml(wsLocal.SortUsing.ToString())); writer.WriteLine("<SortRules><Uni>{0}</Uni></SortRules>", XmlUtils.MakeSafeXml(wsLocal.SortRules)); writer.WriteLine("</WritingSystem>"); } writer.WriteLine("</Languages>"); }
/// <summary> /// Add a LgWritingSystem to the collection. /// </summary> /// <param name="lws">The LgWritingSystem to add.</param> public ILgWritingSystem Add(ILgWritingSystem lws) { Debug.Assert(lws != null); ILgWritingSystem leAdd = (ILgWritingSystem)ValidateObject(lws); List.Add(leAdd); return(leAdd); }
private readonly ILgWritingSystem m_ws; // only text in this language is checked. /// <summary> /// Make one /// </summary> /// <param name="tss"></param> /// <param name="dict"></param> /// <param name="ws"></param> public SpellCheckMethod(ITsString tss, ISpellEngine dict, ILgWritingSystem ws) { m_tss = tss; m_text = tss.Text ?? string.Empty; m_cch = m_text.Length; m_dict = dict; m_ws = ws; }
private void ExportLanguages(TextWriter writer) { string sAnal = AnalWsTag; string sVern = m_cache.WritingSystemFactory.GetStrFromWs(m_cache.DefaultVernWs); writer.WriteLine("<Languages defaultAnal=\"{0}\" defaultVern=\"{1}\">", sAnal, sVern); IWritingSystemManager manager = m_cache.ServiceLocator.GetInstance <IWritingSystemManager>(); foreach (var wsLocal in manager.LocalWritingSystems) { string tag = LangTagUtils.ToLangTag(wsLocal.LanguageSubtag, wsLocal.ScriptSubtag, wsLocal.RegionSubtag, wsLocal.VariantSubtag); ILgWritingSystem lgws = null; int ws = m_cache.WritingSystemFactory.GetWsFromStr(tag); if (ws <= 0) { continue; } lgws = m_cache.WritingSystemFactory.get_EngineOrNull(ws); string code = wsLocal.LanguageSubtag.Code; string type = code.Length == 2 ? "ISO-639-1" : "ISO-639-3"; writer.WriteLine("<WritingSystem id=\"{0}\" language=\"{1}\" type=\"{2}\">", tag, code, type); writer.WriteLine("<Name><Uni>{0}</Uni></Name>", XmlUtils.MakeSafeXml(wsLocal.LanguageName)); writer.WriteLine("<Abbreviation><Uni>{0}</Uni></Abbreviation>", XmlUtils.MakeSafeXml(wsLocal.Abbreviation)); writer.WriteLine("<Locale><Integer val=\"{0}\"/></Locale>", wsLocal.LCID); writer.WriteLine("<RightToLeft><Boolean val=\"{0}\"/></RightToLeft>", wsLocal.RightToLeftScript ? "true" : "false"); if (ws == m_cache.DefaultAnalWs) { m_fRightToLeft = wsLocal.RightToLeftScript; } writer.WriteLine("<DefaultFont><Uni>{0}</Uni></DefaultFont>", XmlUtils.MakeSafeXml(wsLocal.DefaultFontName)); if (!String.IsNullOrEmpty(wsLocal.DefaultFontFeatures)) { writer.WriteLine("<DefaultFontFeatures><Uni>{0}</Uni></DefaultFontFeatures>", XmlUtils.MakeSafeXml(wsLocal.DefaultFontFeatures)); } // The following commented out data are probably never needed. //if (!String.IsNullOrEmpty(wsLocal.ValidChars)) // writer.WriteLine("<ValidChars><Uni>{0}</Uni></ValidChars>", // XmlUtils.MakeSafeXml(wsLocal.ValidChars)); //writer.WriteLine("<ICULocale><Uni>{0}</Uni></ICULocale>", // XmlUtils.MakeSafeXml(wsLocal.IcuLocale)); writer.WriteLine("<SortUsing><Uni>{0}</Uni></SortUsing>", XmlUtils.MakeSafeXml(wsLocal.SortUsing.ToString())); writer.WriteLine("<SortRules><Uni>{0}</Uni></SortRules>", XmlUtils.MakeSafeXml(wsLocal.SortRules)); writer.WriteLine("</WritingSystem>"); } writer.WriteLine("</Languages>"); }
public static ITsString WsLabel(FdoCache cache, int ws) { ITsPropsFactory tpf = TsPropsFactoryClass.Create(); ITsTextProps ttp = tpf.MakeProps("Language Code", cache.DefaultUserWs, 0); ILgWritingSystem wsObj = LgWritingSystem.CreateFromDBObject(cache, ws); ITsStrFactory tsf = TsStrFactoryClass.Create(); string sAbbr = wsObj.Abbr.UserDefaultWritingSystem; return(tsf.MakeStringWithPropsRgch(sAbbr, sAbbr.Length, ttp)); }
public void GetWsFromIcuLocale() { CheckDisposed(); LgWritingSystemCollection analWritingSystems = Cache.LanguageEncodings; ILgWritingSystem lgws = analWritingSystems.Item(0); // TODO (DN-208) This needs to switch to just use the hvo. Assert.AreEqual(lgws.Hvo, analWritingSystems.GetWsFromIcuLocale(lgws.ICULocale)); Assert.AreEqual(0, analWritingSystems.GetWsFromIcuLocale("not_THERE")); }
private IRenderEngine GetUniscribeEngine(IVwGraphics vg, ILgWritingSystem ws) { IRenderEngine uniscribeEngine; uniscribeEngine = UniscribeEngineClass.Create(); uniscribeEngine.InitRenderer(vg, null); uniscribeEngine.RenderEngineFactory = this; uniscribeEngine.WritingSystemFactory = ws.WritingSystemFactory; return(uniscribeEngine); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Gets the ws handle for specified writing system identifier. /// </summary> /// <param name="wsId">The writing system identifier.</param> /// <param name="lgwsf">The writing system factory.</param> /// ------------------------------------------------------------------------------------ internal static int GetWsForId(string wsId, ILgWritingSystemFactory lgwsf) { try { ILgWritingSystem ws = lgwsf.get_Engine(wsId); return(ws.Handle); } catch (Exception e) { throw new XmlSchemaException("Unable to create writing system: " + wsId, e); } }
private int GetWsFromStr(string sWs) { int ws = m_wsf.GetWsFromStr(sWs); if (ws != 0) { return(ws); } // Add this writing system. ILgWritingSystem lgws = m_wsf.get_Engine(sWs); return(lgws.Handle); }
private static Font GetVernacularFont(ILgWritingSystemFactory wsf, int wsVern, IVwStylesheet stylesheet) { if (stylesheet == null) { ILgWritingSystem wsEngine = wsf.get_EngineOrNull(wsVern); string fontName = wsEngine.DefaultFontName; return(new Font(fontName, (float)10.0)); } else { return(FontHeightAdjuster.GetFontForNormalStyle(wsVern, stylesheet, wsf)); } }
public void GetFirstItemOfSequence() { CheckDisposed(); //first try with an empty sequence ILexEntry entry = Cache.LangProject.LexDbOA.EntriesOC.Add(new LexEntry()); Assert.IsNull(entry.AlternateFormsOS.FirstItem); //cleanup Cache.LangProject.LexDbOA.EntriesOC.Remove(entry); ILgWritingSystem x = Cache.LangProject.CurAnalysisWssRS.FirstItem; Assert.AreEqual(Cache.DefaultAnalWs, x.Hvo); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Given a start character position that is within a word, and a direction /// return the index of the first non-wordforming (and non-number) character in that direction, /// or -1 if the start of the string is reached, or string.Length if the end is reached. /// For our purposes here, ORC (0xfffc) is considered word-forming. /// </summary> /// ------------------------------------------------------------------------------------ private int AdjustWordBoundary(ILgWritingSystemFactory wsf, ITsString tss, bool forward, int ichStart, int lim) { int ich; for (ich = NextCharIndex(tss, forward, ichStart); !BeyondLim(forward, ich, lim); ich = NextCharIndex(tss, forward, ich)) { int ch = tss.CharAt(ich); ILgWritingSystem ws = wsf.get_EngineOrNull(tss.get_WritingSystemAt(ich)); if (!ws.get_IsWordForming(ch) && !Icu.Character.IsNumeric(ch) && ch != 0xfffc) { break; } } return(ich); }
/// <summary> /// Get the engine used to render text with the specified properties. At present only /// font, bold, and italic properties are significant. /// Font name may be '<default font>' which produces a renderer suitable for the default /// font. /// </summary> public IRenderEngine get_Renderer(ILgWritingSystem ws, IVwGraphics vg) { LgCharRenderProps chrp = vg.FontCharProperties; string fontName = MarshalEx.UShortToString(chrp.szFaceName); if (fontName == "<default font>") { fontName = ws.DefaultFontName; MarshalEx.StringToUShort(fontName, chrp.szFaceName); vg.SetupGraphics(ref chrp); } Dictionary <Tuple <string, bool, bool>, Tuple <bool, IRenderEngine> > wsFontEngines; if (!m_fontEngines.TryGetValue(ws, out wsFontEngines)) { wsFontEngines = new Dictionary <Tuple <string, bool, bool>, Tuple <bool, IRenderEngine> >(); m_fontEngines[ws] = wsFontEngines; } var key = Tuple.Create(fontName, chrp.ttvBold == (int)FwTextToggleVal.kttvForceOn, chrp.ttvItalic == (int)FwTextToggleVal.kttvForceOn); Tuple <bool, IRenderEngine> fontEngine; if (!wsFontEngines.TryGetValue(key, out fontEngine)) { // We don't have a font engine stored for this combination of font face with bold and italic // so we will create the engine for it here wsFontEngines[key] = GetRenderingEngine(fontName, vg, ws); } else if (fontEngine.Item1 == ws.IsGraphiteEnabled) { // We did have a font engine for this key and IsGraphiteEnabled hasn't changed so use it. return(fontEngine.Item2); } else { // We had a font engine for this key, but IsGraphiteEnabled has changed in the ws. // Destroy all the engines associated with this ws and create one for this key. ReleaseRenderEngines(wsFontEngines.Values); wsFontEngines.Clear(); var renderingEngine = GetRenderingEngine(fontName, vg, ws); wsFontEngines[key] = renderingEngine; } return(wsFontEngines[key].Item2); }
private void CreateReversalIndexDlg_FormClosing(object sender, FormClosingEventArgs e) { switch (DialogResult) { default: { Debug.Assert(false, "Unexpected DialogResult."); break; } case DialogResult.Cancel: { if (!m_btnCancel.Visible) { e.Cancel = true; MessageBox.Show(LexEdStrings.ksMustSelectOne); } break; } case DialogResult.OK: { NamedWritingSystem nws = m_cbWritingSystems.SelectedItem as NamedWritingSystem; if (nws != null) { ILgWritingSystem lgws = LgWritingSystem.CreateFromDBObject(m_cache, nws.Hvo); IReversalIndex newIdx = m_cache.LangProject.LexDbOA.ReversalIndexesOC.Add(new ReversalIndex()); newIdx.WritingSystemRA = lgws; // Copy any and all alternatives from lgws.Name to newIdx.Name // LT-4907 dies here. foreach (ILgWritingSystem lgwsLoop in m_cache.LanguageEncodings) { string lgsNameAlt = lgws.Name.GetAlternative(lgwsLoop.Hvo); if (lgsNameAlt != null && lgsNameAlt.Length > 0) { newIdx.Name.SetAlternative(lgsNameAlt, lgws.Hvo); } } m_hvoRevIdx = newIdx.Hvo; } break; } } }
public void get_Engine() { var wsManager = new PalasoWritingSystemManager(); IWritingSystem enWs = wsManager.Set("en-US"); ILgWritingSystem enLgWs = wsManager.get_Engine("en-US"); Assert.AreSame(enWs, enLgWs); Assert.IsFalse(wsManager.Exists("en-Latn-US")); // this should create a new writing system, since it doesn't exist ILgWritingSystem enUsLgWs = wsManager.get_Engine("en-Latn-US"); Assert.IsTrue(wsManager.Exists("en-Latn-US")); Assert.IsTrue(wsManager.Exists(enUsLgWs.Handle)); IWritingSystem enUsWs = wsManager.Get("en-Latn-US"); Assert.AreSame(enUsWs, enUsLgWs); wsManager.Save(); }
/// ------------------------------------------------------------------------------------ /// <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); }
// 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); }
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); }
/// <summary> /// try to create a tss based upon the state of the Find text box and WritingSystems combo. /// </summary> /// <returns></returns> private ITsString CreateVariantTss() { // only create a variant tss when we're calling the dialog up from an entry // upon which we want to add a variant. if (!m_fBackRefToVariant || m_tbForm.Text == null) { return(null); } ITsString tssNewVariantLexemeForm = null; string trimmed = m_tbForm.Text.Trim(); if (trimmed.Length > 0 && m_cbWritingSystems.SelectedItem != null) { ILgWritingSystem ws = m_cbWritingSystems.SelectedItem as ILgWritingSystem; if (m_cache.LangProject.CurVernWssRS.Contains(ws)) { tssNewVariantLexemeForm = StringUtils.MakeTss(trimmed, ws.Hvo); } } return(tssNewVariantLexemeForm); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Setup the test. /// </summary> /// ------------------------------------------------------------------------------------ public override void Initialize() { base.Initialize(); m_bookFilter = new FilteredScrBooks(Cache, 1); m_bookFilter.UpdateFilter(new int[] { m_Genesis.Hvo }); m_dummyParaDlg = new DummyParatextDialog(Cache, m_bookFilter); //ScrImportSet importSet = new ScrImportSet(); //Cache.LangProject.TranslatedScriptureOA.ImportSettingsOC.Add(importSet); //importSet.ParatextScrProj = "xyz"; //importSet.ParatextBTProj = "xyzBT"; //Cache.LangProject.TranslatedScriptureOA.DefaultImportSettings = importSet; ILgWritingSystem wsVern = ((LgWritingSystem)Cache.LangProject.CurVernWssRS[0]); wsVern.Abbr.UserDefaultWritingSystem = "xyz"; // Initialize in-memory registry settings. m_dummyParaDlg.Registry.SetIntValue("ParatextOneDomainExportWhat", 0); m_dummyParaDlg.Registry.SetStringValue("ParatextOutputSpec", @"C:\My Paratext Projects"); m_dummyParaDlg.Registry.SetStringValue("ParatextBTOutputSpec", @"C:\My Paratext Projects"); }
public void TestOverrideFontForWritingSystem_ForStyleWithNullProps() { var stylesheet = new TestFwStylesheet(); int hvoNewStyle1 = stylesheet.MakeNewStyle(); stylesheet.PutStyle("FirstStyle", "bla", hvoNewStyle1, 0, 0, 0, false, false, null); var wsf = new PalasoWritingSystemManager(); ILgWritingSystem ws = wsf.get_Engine("de"); int hvoGermanWs = ws.Handle; Assert.IsTrue(hvoGermanWs > 0, "Should have gotten an hvo for the German WS"); // Array of 1 struct, contains writing system and font size to override List <FontOverride> fontOverrides = new List <FontOverride>(1); FontOverride aFontOverride; aFontOverride.writingSystem = hvoGermanWs; aFontOverride.fontSize = 48; fontOverrides.Add(aFontOverride); stylesheet.OverrideFontsForWritingSystems("FirstStyle", fontOverrides); //check results IVwPropertyStore vwps = VwPropertyStoreClass.Create(); vwps.Stylesheet = stylesheet; vwps.WritingSystemFactory = wsf; ITsPropsBldr ttpBldr = TsPropsBldrClass.Create(); ttpBldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, "FirstStyle"); ttpBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, hvoGermanWs); ITsTextProps ttp = ttpBldr.GetTextProps(); LgCharRenderProps chrps = vwps.get_ChrpFor(ttp); ws.InterpretChrp(ref chrps); Assert.AreEqual(48, chrps.dympHeight / 1000); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Adds a new gloss to the sense with the specified information /// </summary> /// ------------------------------------------------------------------------------------ public LexGloss AddGlossToSense(LexemeType type, string lexicalForm, int homograph, string senseId, string language, string text) { LexicalProviderManager.ResetLexicalProviderTimer(); Logger.WriteEvent("Adding new gloss to lexeme '" + lexicalForm + "' from an external application"); return(NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () => { IMultiUnicode dbGlosses; if (senseId.StartsWith(kAnalysisPrefix)) { // The "sense" is actually an analysis for a wordform and our new // gloss is a new meaning for that analysis. Guid analysisGuid = new Guid(senseId.Substring(kAnalysisPrefix.Length)); IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance <IWfiAnalysisRepository>().GetObject(analysisGuid); IWfiGloss dbGloss = dbAnalysis.MeaningsOC.FirstOrDefault(); if (dbGloss == null) { dbGloss = m_cache.ServiceLocator.GetInstance <IWfiGlossFactory>().Create(); dbAnalysis.MeaningsOC.Add(dbGloss); } dbGlosses = dbGloss.Form; dbAnalysis.ApprovalStatusIcon = 1; // Assume the analysis from the external application is user approved } else { Guid senseGuid = new Guid(senseId); ILexSense dbSense = m_cache.ServiceLocator.GetInstance <ILexSenseRepository>().GetObject(senseGuid); dbGlosses = dbSense.Gloss; } // Add the new gloss to the list of glosses for the sense ILgWritingSystem writingSystem = m_cache.WritingSystemFactory.get_Engine(language); dbGlosses.set_String(writingSystem.Handle, TsStringUtils.MakeTss(text, writingSystem.Handle)); return new LexGloss(language, text); })); }
// 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); }
/// <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); }
internal static int ReversalIndexAfterDeletion(FdoCache cache, out int cobjNew) { int hvoIdxNew = 0; cobjNew = cache.LangProject.LexDbOA.ReversalIndexesOC.Count; if (cobjNew == 0) { // Big trouble ensues if we don't have any reversal indexes at all, so ... // Create a reversal index for the current default analysis writing system. IReversalIndex newIdx = cache.LangProject.LexDbOA.ReversalIndexesOC.Add(new ReversalIndex()); ILgWritingSystem wsAnalysis = cache.LangProject.CurAnalysisWssRS[0]; newIdx.WritingSystemRA = wsAnalysis; newIdx.Name.AnalysisDefaultWritingSystem = wsAnalysis.Name.AnalysisDefaultWritingSystem; hvoIdxNew = newIdx.Hvo; cobjNew = 1; } else { // Regardless, we need to change the reversal index hvo since the old one just // disappeared. hvoIdxNew = cache.LangProject.LexDbOA.ReversalIndexesOC.HvoArray[0]; } return(hvoIdxNew); }
private void WriteStringSFM(string s, string name, ILgWritingSystem ws, TextWriter contentsStream) { if (s != null && s.Trim().Length > 0) { s = Icu.Normalize(s, m_eIcuNormalizationMode); string elname = name; if (ws != null) { elname = String.Format("{0}_{1}", name, LabelString(ws)); //e.g. lxEn } WriteOpeningOfStartOfComplexElementTag(contentsStream, elname); WriteClosingOfStartOfComplexElementTag(contentsStream); contentsStream.Write(s); WriteEndOfComplexElementTag(contentsStream, elname); } }
public LabeledMultiStringViewVc(int flid, ILgWritingSystem[] rgws, int wsUser, bool editable, LabeledMultiStringView view) : base(flid, rgws, wsUser, editable, view.WritingSystemFactory.GetWsFromStr("en")) { m_view = view; Debug.Assert(m_view != null); }
/// <summary> /// Write one writing system alternative from a custom multilingual field. /// </summary> /// <param name="currentObject"></param> /// <param name="flid"></param> /// <param name="ws"></param> /// <param name="name"></param> /// <param name="contentsStream"></param> protected void writeCustomStringAlternativeToSFM(CmObject currentObject, int flid, ILgWritingSystem ws, string name, TextWriter contentsStream) { if (m_mapFlids.ContainsKey(flid)) flid = m_mapFlids[flid]; FieldType cpt = m_cache.GetFieldType(flid); switch (cpt) { case FieldType.kcptMultiUnicode: case FieldType.kcptMultiBigUnicode: case FieldType.kcptMultiString: case FieldType.kcptMultiBigString: break; default: return; // not a valid type. } ITsString tss = m_cache.GetMultiStringAlt(currentObject.Hvo, flid, ws.Hvo); WriteStringSFM(tss.Text, name, ws, contentsStream); }
private bool TryWriteStringAlternative(object orange, ILgWritingSystem ws, string name, string internalElementName, TextWriter contentsStream, bool fLeadingNewline) { ITsString tss = null; if (m_eStringFormatOutput != StringFormatOutputStyle.None) tss = GetTsStringOfProperty(orange, ws.Hvo); if (tss == null) { string s = GetStringOfProperty(orange, ws.Hvo); if (fLeadingNewline && !String.IsNullOrEmpty(s)) contentsStream.WriteLine(); WriteString(s, name, ws, internalElementName, contentsStream); return !String.IsNullOrEmpty(s); } else { Debug.Assert(m_format == "xml"); if (fLeadingNewline && tss.Length > 0) contentsStream.WriteLine(); WriteTsStringXml(tss, name, ws, internalElementName, contentsStream); return tss.Length > 0; } }
private static string GetValueOfPattern(XmlNode textNode, string sPattern, ILgWritingSystem ws) { XmlNode xn = textNode.SelectSingleNode(sPattern + "[@ws='" + ws.ICULocale + "']"); string sValue = null; if (xn != null) sValue = xn.InnerText; return sValue; }
private static List<int> HvosFromWss(ILgWritingSystem[] wss) { List<int> hvos = new List<int>(); foreach (ILgWritingSystem lws in wss) hvos.Add(lws.Hvo); return hvos; }
/// <summary> /// stores the list values in terms of icu locale /// </summary> /// <param name="display"></param> /// <param name="list"></param> private void AddWritingSystemListWithIcuLocales(UIListDisplayProperties display, ILgWritingSystem[] list) { string[] active = GetVisibleWSSPropertyValue().Split(','); foreach (ILgWritingSystem ws in list) { // generally enable all items, but if only one is checked that one is disabled; // it can't be turned off. bool enabled = (active.Length != 1 || ws.ICULocale != active[0]); display.List.Add(ws.ShortName, ws.ICULocale, null, null, enabled); } }
/// <summary> /// go through all the data tree slices, finding the slices that refer to the same part as this slice /// setting them to the same writing systems to display /// and redisplaying their views. /// </summary> /// <param name="wssToDisplay"></param> private void SetWssToDisplayForPart(ILgWritingSystem[] wssToDisplay) { XmlNode ourPart = this.PartRef(); foreach (Control c in ContainingDataTree.Controls) { Slice slice = c as Slice; XmlNode part = slice.PartRef(); if (part == ourPart) { (slice.Control as LabeledMultiStringView).WritingSystemsToDisplay = wssToDisplay; (slice.Control as LabeledMultiStringView).RefreshDisplay(); } } }
/// <summary> /// convert the given writing systems into a property containing comma-delimited icuLocales. /// </summary> /// <param name="wss"></param> /// <returns></returns> private static string EncodeWssToDisplayPropertyValue(ILgWritingSystem[] wss) { List<string> icuLocaleList = new List<string>(); foreach (ILgWritingSystem lws in wss) { icuLocaleList.Add(lws.ICULocale); } return ChoiceGroup.EncodeSinglePropertySequenceValue(icuLocaleList.ToArray()); }
private void WriteString(string s, string name, ILgWritingSystem ws, string internalElementName, TextWriter contentsStream) { if (m_format == "xml") WriteStringXml(s, name, ws, internalElementName, contentsStream); else WriteStringSFM(s, name, ws, contentsStream); }
public void AddEngine(ILgWritingSystem _wseng) { throw new NotImplementedException(); }
private void WriteStringStartElements(XmlTextWriter writer, string name, ILgWritingSystem ws, string internalElementName) { writer.WriteStartElement(name); if (ws != null) { switch (m_writingSystemAttrStyle) { case WritingSystemAttrStyles.LIFT: writer.WriteAttributeString("lang", ws.RFC4646bis); break; case WritingSystemAttrStyles.FieldWorks: writer.WriteAttributeString("ws", ws.Abbreviation); break; } } if (!String.IsNullOrEmpty(internalElementName)) writer.WriteStartElement(internalElementName); }
/// <summary> /// Add a LgWritingSystem to the collection. /// </summary> /// <param name="lws">The LgWritingSystem to add.</param> public ILgWritingSystem Add(ILgWritingSystem lws) { Debug.Assert(lws != null); ILgWritingSystem leAdd = (ILgWritingSystem)ValidateObject(lws); List.Add(leAdd); return leAdd; }
/// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="ws"></param> /// <param name="list"></param> /// ------------------------------------------------------------------------------------ static internal protected void AddWsToList(ILgWritingSystem ws, ListBox list) { if (list is CheckedListBox) (list as CheckedListBox).Items.Add(ws, true); else list.Items.Add(ws); list.SelectedItem = ws; }
private static bool TryGetWsEngine(ILgWritingSystemFactory wsFact, string langCode, out ILgWritingSystem wsEngine) { wsEngine = null; try { wsEngine = wsFact.get_Engine(langCode); } catch (ArgumentException e) { Debug.Assert(false, "We hit the non-existant ws in AdjustPunctStringForCharacter()."); return false; } return true; }
private void WriteTsStringXml(ITsString tss, string name, ILgWritingSystem ws, string internalElementName, TextWriter contentsStream) { if (tss == null || tss.Length == 0) return; XmlTextWriter writer = new XmlTextWriter(contentsStream); WriteStringStartElements(writer, name, ws, internalElementName); if (m_eStringFormatOutput == StringFormatOutputStyle.FieldWorks) { WriteFieldWorksTsStringContent(tss, writer); } else { Debug.Assert(m_eStringFormatOutput == StringFormatOutputStyle.LIFT); WriteLiftTsStringContent(tss, writer, ws.Hvo); } WriteStringEndElements(writer, internalElementName); }
/// <summary> /// /// </summary> /// <param name="lgWs"></param> /// <returns>true if lgWs shares the same Language</returns> public bool IsRelatedWs(ILgWritingSystem lgWs) { ILgWritingSystemFactory lgwsf = lgWs.Cache.LanguageWritingSystemFactoryAccessor; IWritingSystem ws = lgwsf.get_Engine(lgWs.ICULocale); return IsRelatedWs(ws); }
private void WriteStringXml(string s, string name, ILgWritingSystem ws, string internalElementName, TextWriter contentsStream) { if (s == null || s.Trim().Length == 0) return; XmlTextWriter writer = new XmlTextWriter(contentsStream); s = Icu.Normalize(s, m_eIcuNormalizationMode); WriteStringStartElements(writer, name, ws, internalElementName); writer.WriteString(s); WriteStringEndElements(writer, internalElementName); }
public LabeledMultiStringVc(int flid, ILgWritingSystem[] rgws, int wsUser, bool editable, int wsEn) { m_flid = flid; m_rgws = rgws; m_wsUI = wsUser; m_ttpLabel = LgWritingSystem.AbbreviationTextProperties; m_editable = editable; m_wsEn = wsEn == 0 ? wsUser : wsEn; // Here's the C++ code which does the same thing using styles. // StrUni stuLangCodeStyle(L"Language Code"); // ITsPropsFactoryPtr qtpf; // qtpf.CreateInstance(CLSID_TsPropsFactory); // StrUni stu; // ITsStringPtr qtss; // ITsStrFactoryPtr qtsf; // qtsf.CreateInstance(CLSID_TsStrFactory); // // Get the properties of the "Language Code" style for the writing system // // which corresponds to the user's environment. // qtpf->MakeProps(stuLangCodeStyle.Bstr(), ???->UserWs(), 0, &qttp); }
private void WriteStringXml(string s, string name, ILgWritingSystem ws, TextWriter contentsStream) { WriteStringXml(s, name, ws, null, contentsStream); }
/// <summary> /// Return an array of writing systems given an array of their HVOs. /// </summary> /// <returns></returns> public static ILgWritingSystem[] WssFromHvos(int[] hvos, FdoCache cache) { ILgWritingSystem [] result = new ILgWritingSystem[hvos.Length]; for (int i = 0; i < hvos.Length; i++) { result[i] = LgWritingSystem.CreateFromDBObject(cache, hvos[i]); } return result; }
/// <summary> /// Get the SFM tag extension for the given writing system. /// </summary> private string LabelString(ILgWritingSystem ws) { string sTagExt = null; ILgWritingSystemFactory wsf = m_cache.LanguageWritingSystemFactoryAccessor; // MDF labels are based on English, so try that first. int wsTag = wsf.GetWsFromStr("en"); sTagExt = ws.Abbr.GetAlternative(wsTag); if (sTagExt != null && sTagExt != string.Empty) return sTagExt; // If that doesn't work, try the user interface writing system. sTagExt = ws.Abbr.GetAlternative(wsf.UserWs); if (sTagExt != null && sTagExt != string.Empty) return sTagExt; // If that doesn't work, try the cache's fallback writing system. sTagExt = ws.Abbr.GetAlternative(m_cache.FallbackUserWs); if (sTagExt != null && sTagExt != string.Empty) return sTagExt; // If that doesn't work, try the first analysis writing system, or the ICU locale. return ws.Abbreviation; }
private void InvokeWritingSystemWizard(ContextMenuStrip cmnuAddWs, out ILgWritingSystem lws, FdoCache cache, IHelpTopicProvider helpTopicProvider) { lws = null; using (new WaitCursor(this)) { using (WritingSystemWizard wiz = new WritingSystemWizard()) { wiz.Init(cache.LanguageWritingSystemFactoryAccessor, helpTopicProvider); if (wiz.ShowDialog() == DialogResult.OK) { // The engine from the wizard isn't the real one, so it doesn't have an id. IWritingSystem wsEngine = wiz.WritingSystem(); string strws = wsEngine.IcuLocale; ILgWritingSystemFactory wsf = cache.LanguageWritingSystemFactoryAccessor; wsEngine = wsf.get_Engine(strws); cache.ResetLanguageEncodings(); lws = LgWritingSystem.CreateFromDBObject(cache, wsEngine.WritingSystem); } } } }
public void TestOverrideFontsForWritingSystems_ForStyleWithProps() { var stylesheet = new TestFwStylesheet(); int hvoNewStyle1 = stylesheet.MakeNewStyle(); ITsPropsBldr propsBldr = TsPropsBldrClass.Create(); propsBldr.SetStrPropValue((int)FwTextStringProp.kstpFontFamily, "Arial"); propsBldr.SetIntPropValues((int)FwTextPropType.ktptFontSize, (int)FwTextPropVar.ktpvMilliPoint, 23000); stylesheet.PutStyle("FirstStyle", "bla", hvoNewStyle1, 0, 0, 0, false, false, propsBldr.GetTextProps()); var wsf = new PalasoWritingSystemManager(); ILgWritingSystem wsIngles = wsf.get_Engine("en"); int hvoInglesWs = wsIngles.Handle; Assert.IsTrue(hvoInglesWs > 0, "Should have gotten an HVO for the English WS"); ILgWritingSystem wsFrench = wsf.get_Engine("fr"); int hvoFrenchWs = wsFrench.Handle; Assert.IsTrue(hvoFrenchWs > 0, "Should have gotten an HVO for the French WS"); ILgWritingSystem wsGerman = wsf.get_Engine("de"); int hvoGermanWs = wsGerman.Handle; Assert.IsTrue(hvoGermanWs > 0, "Should have gotten an HVO for the German WS"); Assert.IsTrue(hvoFrenchWs != hvoGermanWs, "Should have gotten different HVOs for each WS"); Assert.IsTrue(hvoInglesWs != hvoGermanWs, "Should have gotten different HVOs for each WS"); Assert.IsTrue(hvoFrenchWs != hvoInglesWs, "Should have gotten different HVOs for each WS"); // Array of structs, containing writing systems and font sizes to override. var fontOverrides = new List <FontOverride>(2); FontOverride aFontOverride; aFontOverride.writingSystem = hvoInglesWs; aFontOverride.fontSize = 34; fontOverrides.Add(aFontOverride); aFontOverride.writingSystem = hvoGermanWs; aFontOverride.fontSize = 48; fontOverrides.Add(aFontOverride); stylesheet.OverrideFontsForWritingSystems("FirstStyle", fontOverrides); //check results IVwPropertyStore vwps = VwPropertyStoreClass.Create(); vwps.Stylesheet = stylesheet; vwps.WritingSystemFactory = wsf; ITsPropsBldr ttpBldr = TsPropsBldrClass.Create(); ttpBldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, "FirstStyle"); ttpBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, hvoFrenchWs); ITsTextProps ttpFrench = ttpBldr.GetTextProps(); ttpBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, hvoGermanWs); ITsTextProps ttpGerman = ttpBldr.GetTextProps(); ttpBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, hvoInglesWs); ITsTextProps ttpIngles = ttpBldr.GetTextProps(); LgCharRenderProps chrpsFrench = vwps.get_ChrpFor(ttpFrench); LgCharRenderProps chrpsGerman = vwps.get_ChrpFor(ttpGerman); LgCharRenderProps chrpsIngles = vwps.get_ChrpFor(ttpIngles); wsFrench.InterpretChrp(ref chrpsFrench); wsGerman.InterpretChrp(ref chrpsGerman); wsIngles.InterpretChrp(ref chrpsIngles); Assert.AreEqual(23, chrpsFrench.dympHeight / 1000); Assert.AreEqual(34, chrpsIngles.dympHeight / 1000); Assert.AreEqual(48, chrpsGerman.dympHeight / 1000); }
/// <summary> /// add any alternative forms (in alternative writing systems) to the wordform. /// Overwrite any existing alternative form in a given alternative writing system. /// </summary> /// <param name="analysis"></param> /// <param name="word"></param> /// <param name="wsMainVernWs"></param> /// <param name="strFactory"></param> private static void AddAlternativeWssToWordform(IAnalysis analysis, Word word, ILgWritingSystem wsMainVernWs, ITsStrFactory strFactory) { ILgWritingSystemFactory wsFact = analysis.Cache.WritingSystemFactory; var wf = analysis.Wordform; foreach (var wordItem in word.Items) { ITsString wffAlt = null; switch (wordItem.type) { case "txt": var wsAlt = GetWsEngine(wsFact, wordItem.lang); if (wsAlt.Handle == wsMainVernWs.Handle) continue; wffAlt = strFactory.MakeString(wordItem.Value, wsAlt.Handle); if (wffAlt.Length > 0) wf.Form.set_String(wsAlt.Handle, wffAlt); break; } } }