Esempio n. 1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Adds paragraphs to the database
        /// </summary>
        /// <param name="ws"></param>
        /// <param name="firstPara"></param>
        /// <param name="secondPara"></param>
        /// ------------------------------------------------------------------------------------
        private void AddParagraphs(int ws, string firstPara, string secondPara)
        {
            int           hvoPara1 = m_hvoPara++;
            int           hvoPara2 = m_hvoPara++;
            int           hvoText1 = m_hvoText++;
            int           hvoText2 = m_hvoText++;
            ITsStrFactory tsf      = TsStrFactoryClass.Create();
            ITsString     tsString = tsf.MakeString(firstPara, ws);
            IVwCacheDa    cda      = Cache.VwCacheDaAccessor;

            cda.CacheStringProp(hvoPara1, (int)StTxtPara.StTxtParaTags.kflidContents,
                                tsString);
            tsString = tsf.MakeString(secondPara, ws);
            cda.CacheStringProp(hvoPara2, (int)StTxtPara.StTxtParaTags.kflidContents,
                                tsString);

            // Now make each of them the paragraphs of an StText.
            int[] hvoParas = { hvoPara1 };
            cda.CacheVecProp(hvoText1, (int)StText.StTextTags.kflidParagraphs, hvoParas,
                             1);
            hvoParas[0] = hvoPara2;
            cda.CacheVecProp(hvoText2, (int)StText.StTextTags.kflidParagraphs, hvoParas,
                             1);

            // And the StTexts to the contents of a dummy property.
            AddVecProp(new int[] { hvoText1, hvoText2 });
        }
Esempio n. 2
0
            private void SetContentFromNode(FdoCache cache, string sNodeName, bool fFixName, MultiAccessor item)
            {
                ILgWritingSystemFactory wsf = cache.LanguageWritingSystemFactoryAccessor;
                ITsStrFactory           tsf = TsStrFactoryClass.Create();
                int     iWS;
                XmlNode nd;
                bool    fContentFound = false;              // be pessimistic

                foreach (ILgWritingSystem ws in cache.LangProject.CurAnalysisWssRS)
                {
                    string sWS = ws.ICULocale;
                    nd = m_node.SelectSingleNode(sNodeName + "[@ws='" + sWS + "']");
                    if (nd == null || nd.InnerText.Length == 0)
                    {
                        continue;
                    }
                    fContentFound = true;
                    string sNodeContent;
                    if (fFixName)
                    {
                        sNodeContent = NameFixer(nd.InnerText);
                    }
                    else
                    {
                        sNodeContent = nd.InnerText;
                    }
                    iWS = wsf.GetWsFromStr(sWS);
                    item.SetAlternative(tsf.MakeString(sNodeContent, iWS), iWS);
                }
                if (!fContentFound)
                {
                    iWS = cache.LangProject.DefaultAnalysisWritingSystem;
                    item.SetAlternative(tsf.MakeString("", iWS), iWS);
                }
            }
        public void LongMaxValueTest()
        {
            RangeIntMatcher rangeIntMatch = new RangeIntMatcher(0, long.MaxValue);
            var             tssLabel      = m_tsf.MakeString("9223372036854775807", WsDummy);

            Assert.IsTrue(rangeIntMatch.Matches(tssLabel));
        }
Esempio n. 4
0
        public void SetAndAccessMultiStrings()
        {
            ITsStrFactory tsf = TsStrFactoryClass.Create();

            int kflid   = XMLViewsDataCache.ktagEditColumnBase;
            int hvoRoot = 10578;
            int wsEng   = Cache.WritingSystemFactory.GetWsFromStr("en");
            XMLViewsDataCache xmlCache = new XMLViewsDataCache(Cache.MainCacheAccessor as ISilDataAccessManaged, true, new Dictionary <int, int>());
            Notifiee          recorder = new Notifiee();

            xmlCache.AddNotification(recorder);
            Assert.AreEqual(0, xmlCache.get_MultiStringAlt(hvoRoot, kflid, wsEng).Length);
            Assert.AreEqual(0, recorder.Changes.Count);
            ITsString test1 = tsf.MakeString("test1", wsEng);

            xmlCache.CacheMultiString(hvoRoot, kflid, wsEng, test1);
            Assert.AreEqual(0, recorder.Changes.Count);
            Assert.AreEqual(test1, xmlCache.get_MultiStringAlt(hvoRoot, kflid, wsEng));
            ITsString test2 = tsf.MakeString("blah", wsEng);

            xmlCache.SetMultiStringAlt(hvoRoot, kflid, wsEng, test2);
            Assert.AreEqual(test2, xmlCache.get_MultiStringAlt(hvoRoot, kflid, wsEng));


            recorder.CheckChanges(new ChangeInformationTest[] { new ChangeInformationTest(hvoRoot, kflid, wsEng, 0, 0) },
                                  "expected PropChanged from setting string");
            xmlCache.RemoveNotification(recorder);

            // Enhance JohnT: a better test would verify that it doesn't intefere with other multistrings,
            // and that it can store stuff independently for different HVOs, tags, and WSs.
        }
Esempio n. 5
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the RelatedWordsVc class.
        /// </summary>
        /// <param name="wsUser">The ws user.</param>
        /// <param name="headword">Headword of the target lexical entry.</param>
        /// ------------------------------------------------------------------------------------
        public RelatedWordsVc(int wsUser, ITsString headword)
        {
            m_wsDefault = wsUser;
            ITsStrFactory tsf = TsStrFactoryClass.Create();

            m_tssColon       = tsf.MakeString(": ", wsUser);
            m_tssComma       = tsf.MakeString(", ", wsUser);
            m_tssSdRelation  = tsf.MakeString(FdoUiStrings.ksWordsRelatedBySemanticDomain, wsUser);
            m_tssLexRelation = tsf.MakeString(FdoUiStrings.ksLexicallyRelatedWords, wsUser);

            var semanticDomainStrBuilder = m_tssSdRelation.GetBldr();
            var index = semanticDomainStrBuilder.Text.IndexOf("{0}");

            if (index > 0)
            {
                semanticDomainStrBuilder.ReplaceTsString(index, index + "{0}".Length, headword);
            }
            m_tssSdRelation = semanticDomainStrBuilder.GetString();

            var lexStrBuilder = m_tssLexRelation.GetBldr();

            index = lexStrBuilder.Text.IndexOf("{0}");
            if (index > 0)
            {
                lexStrBuilder.ReplaceTsString(index, index + "{0}".Length, headword);
            }
            m_tssLexRelation = lexStrBuilder.GetString();
        }
Esempio n. 6
0
        public void HookupMlString()
        {
            MockData1 data1 = new MockData1(m_wsFrn, m_wsEng);

            data1.MlSimpleOne.VernacularDefaultWritingSystem = m_tsf.MakeString("foo", m_wsFrn);

            MockParaBox mockPara = new MockParaBox();
            MlsHookup   mlHook   = new MlsHookup(data1, data1.MlSimpleOne, m_wsFrn, MockData1Props.MlSimpleOne(data1), mockPara);

            mlHook.ClientRunIndex = 7;

            data1.MlSimpleOne.SetVernacularDefaultWritingSystem("bar");

            data1.RaiseMlSimpleOneChanged(m_wsFrn);
            Assert.AreEqual(7, mockPara.TheIndex, "Should have fired the event and passed the string index");
            Assert.AreEqual("bar", mockPara.TheMlString.get_String(((MultiAccessor)data1.MlSimpleOne).VernWs).Text, "Should have informed para of new string");

            mockPara.TheTsString = m_tsf.MakeString("foo", m_wsFrn);

            data1.MlSimpleOne.SetAnalysisDefaultWritingSystem("eng");

            data1.RaiseMlSimpleOneChanged(m_wsEng);
            Assert.AreEqual("foo", mockPara.TheTsString.Text, "Should not have informed para of new string, since we are monitoring French and mocking English event");
            mlHook.Dispose();
        }
Esempio n. 7
0
        /// <summary>
        /// Add all the data from items in the FLExText file into their proper spots in the segment.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="wsFactory"></param>
        /// <param name="phrase"></param>
        /// <param name="newSegment"></param>
        /// <param name="tsStrFactory"></param>
        /// <param name="textInFile">This reference boolean indicates if there was a text item in the phrase</param>
        /// <param name="phraseText">This reference string will be filled with the contents of the "txt" item in the phrase if it is there</param>
        private static void AddSegmentItemData(FdoCache cache, ILgWritingSystemFactory wsFactory, Phrase phrase, ISegment newSegment, ITsStrFactory tsStrFactory, ref bool textInFile, ref ITsString phraseText)
        {
            if (phrase.Items != null)
            {
                foreach (var item in phrase.Items)
                {
                    switch (item.type)
                    {
                    case "reference-label":
                        newSegment.Reference = tsStrFactory.MakeString(item.Value,
                                                                       GetWsEngine(wsFactory, item.lang).Handle);
                        break;

                    case "gls":
                        newSegment.FreeTranslation.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
                        break;

                    case "lit":
                        newSegment.LiteralTranslation.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
                        break;

                    case "note":
                        INote note = cache.ServiceLocator.GetInstance <INoteFactory>().Create();
                        newSegment.NotesOS.Add(note);
                        note.Content.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
                        break;

                    case "txt":
                        phraseText = tsStrFactory.MakeString(item.Value, GetWsEngine(wsFactory, item.lang).Handle);
                        textInFile = true;
                        break;
                    }
                }
            }
        }
Esempio n. 8
0
        public override void Initialize()
        {
            CheckDisposed();
            base.Initialize();

            // This is a bit odd, but because of the unpredictable timing of garbage collection,
            // it's possible for the junk file to be deleted by the GC from a previous test,
            // resulting in a FileNotFoundException in the CmPicture constructor. So we
            // just give it a few shots at it to make it more reliable.
            bool fSucceeded = false;

            for (int i = 0; i < 5 && !fSucceeded; i++)
            {
                try
                {
                    using (DummyFileMaker filemaker = new DummyFileMaker("junk.jpg", true))
                    {
                        m_pict = new CmPicture(Cache, filemaker.Filename,
                                               m_factory.MakeString("Test picture", Cache.DefaultVernWs),
                                               StringUtils.LocalPictures);
                        fSucceeded = true;
                    }
                }
                catch (FileNotFoundException)
                {
                }
            }
            Assert.IsNotNull(m_pict);
            m_internalPath = m_pict.PictureFileRA.InternalPath;
            Assert.IsNotNull(m_internalPath, "Internal path not set correctly");
            Assert.IsTrue(m_pict.PictureFileRA.AbsoluteInternalPath == m_internalPath, "Files outside LangProject.ExtLinkRootDir are stored as absolute paths");
            m_internalFilesToDelete.Add(m_pict.PictureFileRA.AbsoluteInternalPath);
        }
Esempio n. 9
0
        public RegRuleFormulaVc(FdoCache cache, Mediator mediator)
            : base(cache, mediator)
        {
            ITsPropsBldr tpb = TsPropsBldrClass.Create();

            tpb.SetIntPropValues((int)FwTextPropType.ktptBorderBottom, (int)FwTextPropVar.ktpvMilliPoint, 1000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptBorderColor, (int)FwTextPropVar.ktpvDefault,
                                 (int)ColorUtil.ConvertColorToBGR(Color.Gray));
            tpb.SetIntPropValues((int)FwTextPropType.ktptAlign, (int)FwTextPropVar.ktpvEnum, (int)FwTextAlign.ktalCenter);
            m_ctxtProps = tpb.GetTextProps();

            tpb = TsPropsBldrClass.Create();
            tpb.SetIntPropValues((int)FwTextPropType.ktptFontSize, (int)FwTextPropVar.ktpvMilliPoint, 20000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptForeColor, (int)FwTextPropVar.ktpvDefault,
                                 (int)ColorUtil.ConvertColorToBGR(Color.Gray));
            tpb.SetIntPropValues((int)FwTextPropType.ktptAlign, (int)FwTextPropVar.ktpvEnum, (int)FwTextAlign.ktalCenter);
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadLeading, (int)FwTextPropVar.ktpvMilliPoint, 2000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadTrailing, (int)FwTextPropVar.ktpvMilliPoint, 2000);
            tpb.SetStrPropValue((int)FwTextPropType.ktptFontFamily, MiscUtils.StandardSansSerif);
            tpb.SetIntPropValues((int)FwTextPropType.ktptEditable, (int)FwTextPropVar.ktpvEnum, (int)TptEditable.ktptNotEditable);
            m_charProps = tpb.GetTextProps();

            ITsStrFactory tsf    = m_cache.TsStrFactory;
            int           userWs = m_cache.DefaultUserWs;

            m_arrow      = tsf.MakeString("\u2192", userWs);
            m_slash      = tsf.MakeString("/", userWs);
            m_underscore = tsf.MakeString("__", userWs);
        }
        public void HardLineBreaks()
        {
            ITsStrFactory tsf = TsStrFactoryClass.Create();
            // String with embedded ORC.
            string    test1     = "This is a simple sentence";
            string    lineBreak = StringUtils.kChHardLB.ToString();
            string    test3     = "with a hard break.";
            ITsString tss       = tsf.MakeString(test1 + lineBreak + test3, m_wsEn);

            m_para.Contents = tss;
            List <int> results;
            var        segments = m_pp.CollectSegments(tss, out results);

            VerifyBreaks(new int[] { test1.Length, test1.Length + 1, tss.Length - 1 },
                         results, "simple string with hard break");
            Assert.AreEqual(3, segments.Count);
            // The segments break around the ORC.
            VerifySegment(segments[0], 0, test1.Length, m_para, "simple string with hard break");
            VerifySegment(segments[1], test1.Length, test1.Length + 1, m_para, "simple string with hard break");
            VerifySegment(segments[2], test1.Length + 1, tss.Length, m_para, "simple string with hard break");

            // Now try with an EOS before the hard break.
            string test1a = "This is a proper sentence?!";

            tss             = tsf.MakeString(test1a + lineBreak + test3, m_wsEn);
            m_para.Contents = tss;
            segments        = m_pp.CollectSegments(tss, out results);
            VerifyBreaks(new int[] { test1a.Length - 2, test1a.Length + 1, tss.Length - 1 },
                         results, "EOS before hard break");
            Assert.AreEqual(3, segments.Count);
            // The segments break around the ORC.
            VerifySegment(segments[0], 0, test1a.Length, m_para, "EOS before hard break");
            VerifySegment(segments[1], test1a.Length, test1a.Length + 1, m_para, "EOS before hard break");
            VerifySegment(segments[2], test1a.Length + 1, tss.Length, m_para, "EOS before hard break");
        }
Esempio n. 11
0
            private void SetContentFromNode(FdoCache cache, string sNodeName, bool fFixName, ITsMultiString item)
            {
                ILgWritingSystemFactory wsf = cache.WritingSystemFactory;
                ITsStrFactory           tsf = cache.TsStrFactory;
                int     iWS;
                XmlNode nd;
                bool    fContentFound = false;              // be pessimistic

                foreach (IWritingSystem ws in cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems)
                {
                    string sWS = ws.Id;
                    nd = m_node.SelectSingleNode(sNodeName + "[@ws='" + sWS + "']");
                    if (nd == null || nd.InnerText.Length == 0)
                    {
                        continue;
                    }
                    fContentFound = true;
                    string sNodeContent;
                    if (fFixName)
                    {
                        sNodeContent = NameFixer(nd.InnerText);
                    }
                    else
                    {
                        sNodeContent = nd.InnerText;
                    }
                    iWS = wsf.GetWsFromStr(sWS);
                    item.set_String(iWS, (tsf.MakeString(sNodeContent, iWS)));
                }
                if (!fContentFound)
                {
                    iWS = cache.ServiceLocator.WritingSystems.DefaultAnalysisWritingSystem.Handle;
                    item.set_String(iWS, tsf.MakeString("", iWS));
                }
            }
Esempio n. 12
0
        public void EllipsesAndRefs()
        {
            ITsStrFactory   tsf   = TsStrFactoryClass.Create();
            ParagraphParser pp    = new ParagraphParser(m_para);
            string          test1 = "This is...not ... a simple sentence; it discusses Scripture (Gen 1.2 and Rom 1.2-4.5) and has ellipses.";
            ITsString       tss   = tsf.MakeString(test1, 1);

            m_para.Contents.UnderlyingTsString = tss;
            List <int> results;
            List <int> segments = pp.CollectSegmentAnnotations(tss, out results);

            VerifyBreaks(new int[] { test1.Length - 1 }, results, "ellipses verse period string");
            Assert.AreEqual(1, segments.Count);
            VerifySegment(segments[0], 0, test1.Length, m_para.Hvo, "ellipses verse period");

            string test2a  = "Here we have";
            string twoDots = "..";
            string test2b  = "just two periods, and at the end, another two";

            tss = tsf.MakeString(test2a + twoDots + test2b + twoDots, 1);
            m_para.Contents.UnderlyingTsString = tss;
            segments = pp.CollectSegmentAnnotations(tss, out results);
            VerifyBreaks(new int[] { test2a.Length, test2a.Length + 2 + test2b.Length }, results, "string with double dots");
            Assert.AreEqual(2, segments.Count);
            VerifySegment(segments[0], 0, test2a.Length + 2, m_para.Hvo, "string with double dots(1)");
            VerifySegment(segments[1], test2a.Length + 2, tss.Length, m_para.Hvo, "string with double dots(2)");

            string test3 = "This sentence ends with an ellipsis...";

            tss = tsf.MakeString(test3, 1);
            m_para.Contents.UnderlyingTsString = tss;
            segments = pp.CollectSegmentAnnotations(tss, out results);
            VerifyBreaks(new int[] {  }, results, "string with final ellipsis");
            Assert.AreEqual(1, segments.Count);
            VerifySegment(segments[0], 0, test3.Length, m_para.Hvo, "string with final ellipsis");

            string fourDots = "....";

            tss = tsf.MakeString(test2a + fourDots + test2b + fourDots, 1);
            m_para.Contents.UnderlyingTsString = tss;
            segments = pp.CollectSegmentAnnotations(tss, out results);
            VerifyBreaks(new int[] { test2a.Length, test2a.Length + 4 + test2b.Length }, results, "string with four dots");
            Assert.AreEqual(2, segments.Count);
            VerifySegment(segments[0], 0, test2a.Length + 4, m_para.Hvo, "string with four dots(1)");
            VerifySegment(segments[1], test2a.Length + 4, tss.Length, m_para.Hvo, "string with four dots(2)");
            // Case 2 periods with surrounding numbers

            string test5a = "Here is a number and two dots: 5";
            string test5b = "2 and another number, and the final dot has a number before it: 2.";

            tss = tsf.MakeString(test5a + twoDots + test5b, 1);
            m_para.Contents.UnderlyingTsString = tss;
            segments = pp.CollectSegmentAnnotations(tss, out results);
            VerifyBreaks(new int[] { test5a.Length, test5a.Length + 2 + test5b.Length - 1 }, results, "string with numbers and double dots");
            Assert.AreEqual(2, segments.Count);
            // One plus 2 for the two dots, but the following digit and space go in the previous segment, too.
            VerifySegment(segments[0], 0, test5a.Length + 2 + 2, m_para.Hvo, "string with numbers and double dots(1)");
            VerifySegment(segments[1], test5a.Length + 2 + 2, tss.Length, m_para.Hvo, "string with numbers and double dots(2)");
        }
Esempio n. 13
0
        public override void MakeRoot(IVwGraphics vg, ILgEncodingFactory encfParam, out IVwRootBox rootbParam)
        {
            rootbParam = null;

            // JohnT: this is a convenient though somewhat unconventional place to create and partly
            // initialize the combo box. We can't set its position yet, as that depends on what the user
            // clicks. Nor do we yet add it to our list of windows, nor make it visible.
            typeComboBox = new System.Windows.Forms.ComboBox();
            typeComboBox.Items.AddRange(new object[] { "sal", "noun", "verb", "det", "adj", "adv" });
            typeComboBox.DropDownWidth         = 280;     // Todo JohnT: make right for showing all options
            typeComboBox.SelectedValueChanged += new EventHandler(this.HandleComboSelChange);

            base.MakeRoot(vg, encfParam, out rootbParam);

            if (m_fdoCache == null || DesignMode)
            {
                return;
            }

            IVwRootBox rootb = (IVwRootBox) new FwViews.VwRootBoxClass();

            rootb.SetSite(this);

            int hvoRoot = khvoText;

            // Set up sample data (not in the database for now)
            ITsStrFactory tsf    = (ITsStrFactory) new FwKernelLib.TsStrFactoryClass();
            int           encEng = 0;   // TODO: Implement StrUtil::ParseEnc

            string[] words      = { "Hello", "world!", "This", "is", "an", "interlinear", "view" };
            string[] wordtypes  = { "sal", "noun", "det", "verb", "det", "adj", "noun" };
            int[]    rghvoWords = new int[(words.Length)];
            for (int i = 0; i < words.Length; ++i)
            {
                ITsString tss = tsf.MakeString(words[i], encEng);
                // Use i+1 as the HVO for the word objects. Avoid using 0 as an HVO
                m_fdoCache.VwCacheDaAccessor.CacheStringProp(i + 1, ktagWord_Form, tss);
                tss = tsf.MakeString(wordtypes[i], encEng);
                // Use i+1 as the HVO for the word objects. Avoid using 0 as an HVO
                m_fdoCache.VwCacheDaAccessor.CacheStringProp(i + 1, ktagWord_Type, tss);
                rghvoWords[i] = i + 1;
            }
            m_fdoCache.VwCacheDaAccessor.CacheVecProp(khvoText, ktagText_Words, rghvoWords, rghvoWords.Length);

            int frag = kfrText;

            m_iVc = new InterlinearVc();

            if (encfParam != null)
            {
                m_fdoCache.MainCacheAccessor.set_EncodingFactory(encfParam);
            }

            rootb.set_DataAccess(m_fdoCache.MainCacheAccessor);

            rootb.SetRootObject(hvoRoot, m_iVc, frag, null);
            rootbParam = rootb;
        }
Esempio n. 14
0
        protected RuleFormulaVcBase(FdoCache cache, XCore.Mediator mediator)
            : base(cache, mediator)
        {
            ITsStrFactory tsf    = m_cache.TsStrFactory;
            int           userWs = m_cache.DefaultUserWs;

            m_infinity = tsf.MakeString("\u221e", userWs);
            m_x        = tsf.MakeString("X", userWs);
        }
Esempio n. 15
0
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            SetupTestModel(Resources.TextCacheModel_xml);

            m_sda = new RealDataCache();
            m_sda.MetaDataCache = MetaDataCache.CreateMetaDataCache("TestModel.xml");
            //m_cache.ParaContentsFlid = kflidParaContents;
            //m_cache.ParaPropertiesFlid = kflidParaProperties;
            //m_cache.TextParagraphsFlid = kflidTextParas;

            Debug.Assert(m_wsManager == null);
            m_wsManager = Cache.ServiceLocator.GetInstance <IWritingSystemManager>();
            m_sda.WritingSystemFactory = m_wsManager;

            m_wsAnal = Cache.DefaultAnalWs;

            m_wsVern = Cache.DefaultVernWs;

            //IWritingSystem deWs;
            //m_wsManager.GetOrSet("de", out deWs);
            //m_wsDeu = deWs.Handle;

            //m_wsManager.UserWs = m_wsEng;
            //m_wsUser = m_wsManager.UserWs;

            m_tsf = TsStrFactoryClass.Create();

            m_hvoLexDb = m_sda.MakeNewObject(kclsidLexDb, 0, -1, -1);

            kflidLexDb_Entries = m_sda.MetaDataCache.GetFieldId("LexDb", "Entries", false);
            kflidEntry_Form    = m_sda.MetaDataCache.GetFieldId("Entry", "Form", false);
            kflidEntry_Summary = m_sda.MetaDataCache.GetFieldId("Entry", "Summary", false);

            m_hvoKick = m_sda.MakeNewObject(kclsidEntry, m_hvoLexDb, kflidLexDb_Entries, 0);
            m_sda.SetMultiStringAlt(m_hvoKick, kflidEntry_Form, m_wsVern, m_tsf.MakeString("kick", m_wsVern));
            m_sda.SetString(m_hvoKick, kflidEntry_Summary, m_tsf.MakeString("strike with foot", m_wsAnal));

            var keyAttrs = new Dictionary <string, string[]>();

            keyAttrs["layout"] = new[] { "class", "type", "name", "choiceGuid" };
            keyAttrs["group"]  = new[] { "label" };
            keyAttrs["part"]   = new[] { "ref" };
            var layoutInventory = new Inventory("*.fwlayout", "/LayoutInventory/*", keyAttrs, "test", "nowhere");

            layoutInventory.LoadElements(Resources.Layouts_xml, 1);

            keyAttrs         = new Dictionary <string, string[]>();
            keyAttrs["part"] = new[] { "id" };

            var partInventory = new Inventory("*Parts.xml", "/PartInventory/bin/*", keyAttrs, "test", "nowhere");

            partInventory.LoadElements(Resources.Parts_xml, 1);

            m_layouts = new LayoutCache(m_sda.MetaDataCache, layoutInventory, partInventory);
        }
        /// -------------------------------------------------------------------------------------
        /// <summary>
        /// Create publications and header/footer sets (in the DB) from the given XML document.
        /// </summary>
        /// <remarks>tests are able to call this method</remarks>
        /// <param name="progressDlg">Progress dialog</param>
        /// <param name="rootNode">The XmlNode from which to read the publication info</param>
        /// -------------------------------------------------------------------------------------
        protected void SetNamesAndAbbreviations(IProgress progressDlg, XmlNode rootNode)
        {
            IScrRefSystem srs = m_cache.ServiceLocator.GetInstance <IScrRefSystemRepository>().Singleton;

            Debug.Assert(srs != null && srs.BooksOS.Count == BCVRef.LastBook);

            XmlNodeList tagList = rootNode.SelectNodes("/ScrBookRef/writingsystem");

            progressDlg.Minimum  = 0;
            progressDlg.Maximum  = tagList.Count * BCVRef.LastBook;
            progressDlg.Position = 0;
            progressDlg.Title    = TeResourceHelper.GetResourceString("kstidCreatingBookNames");
            ITsStrFactory  tsf = m_cache.TsStrFactory;
            IWritingSystem ws;

            foreach (XmlNode writingSystem in tagList)
            {
                XmlAttributeCollection attributes = writingSystem.Attributes;
                string sWsTag = attributes.GetNamedItem("xml:lang").Value;
                m_cache.ServiceLocator.WritingSystemManager.GetOrSet(sWsTag, out ws);

                XmlNodeList WSBooks = writingSystem.SelectNodes("book");
                foreach (XmlNode book in WSBooks)
                {
                    XmlAttributeCollection bookAttributes = book.Attributes;
                    string sSilBookId = bookAttributes.GetNamedItem("SILBookId").Value;
                    Debug.Assert(sSilBookId != null);
                    int    nCanonicalBookNum = BCVRef.BookToNumber(sSilBookId);
                    string sName             = bookAttributes.GetNamedItem("Name").Value;
                    string sAbbrev           = bookAttributes.GetNamedItem("Abbreviation").Value;
                    string sAltName          = bookAttributes.GetNamedItem("AlternateName").Value;
                    progressDlg.Message = string.Format(
                        TeResourceHelper.GetResourceString("kstidCreatingBookNamesStatusMsg"), sName);
                    progressDlg.Step(0);

                    // check for the book id
                    IScrBookRef bookRef = srs.BooksOS[nCanonicalBookNum - 1];

                    int wsHandle = ws.Handle;
                    if (sName != null)
                    {
                        bookRef.BookName.set_String(wsHandle, tsf.MakeString(sName, wsHandle));
                    }
                    if (sAbbrev != null)
                    {
                        bookRef.BookAbbrev.set_String(wsHandle, tsf.MakeString(sAbbrev, wsHandle));
                    }
                    if (sAltName != null)
                    {
                        bookRef.BookNameAlt.set_String(wsHandle, tsf.MakeString(sAltName, wsHandle));
                    }
                }
            }
            // Finally, update resource version in database.
            SetNewResourceVersion(GetVersion(rootNode));
        }
Esempio n. 17
0
        public ComplexConcPatternVc(FdoCache cache, Mediator mediator)
            : base(cache, mediator)
        {
            ITsStrFactory tsf    = m_cache.TsStrFactory;
            int           userWs = m_cache.DefaultUserWs;

            m_infinity = tsf.MakeString("\u221e", userWs);
            m_or       = tsf.MakeString("OR", userWs);
            m_hash     = tsf.MakeString("#", userWs);
        }
Esempio n. 18
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="T:RelatedWordsVc"/> class.
        /// </summary>
        /// <param name="wsUser">The ws user.</param>
        /// ------------------------------------------------------------------------------------
        public RelatedWordsVc(int wsUser)
        {
            m_wsDefault = wsUser;
            ITsStrFactory tsf = TsStrFactoryClass.Create();

            m_tssColon       = tsf.MakeString(": ", wsUser);
            m_tssComma       = tsf.MakeString(", ", wsUser);
            m_tssSdRelation  = tsf.MakeString(FdoUiStrings.ksWordsRelatedBySemanticDomain, wsUser);
            m_tssLexRelation = tsf.MakeString(FdoUiStrings.ksLexicallyRelatedWords, wsUser);
        }
Esempio n. 19
0
        public void GetTextRepresentation_withBrackets()
        {
            CheckDisposed();

            m_footnotePara.Contents.UnderlyingTsString =
                m_strFact.MakeString("Text in <brackets>", m_vernWs);

            string result = m_footnote.GetTextRepresentation();

            Assert.AreEqual(@"<FN><M>o</M><ShowMarker/><P><PS>Note General Paragraph</PS>" +
                            "<RUN WS='fr'>Text in &lt;brackets&gt;</RUN></P></FN>", result);
        }
Esempio n. 20
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());
        }
        public void DecoratorDoesNothingWhenTurnedOff()
        {
            var mockDa          = new MockDa();
            var underlyingValue = "hello" + zws + "world";

            mockDa.StringValues[new Tuple <int, int>(27, StTxtParaTags.kflidContents)] = m_tsf.MakeString(underlyingValue, 77);
            var decorator = new ShowSpaceDecorator(mockDa);

            var tss = decorator.get_StringProp(27, StTxtParaTags.kflidContents);

            Assert.That(tss.Text, Is.EqualTo(underlyingValue));
            VerifyNoBackColor(tss);
        }
Esempio n. 22
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Adds a footnote with a single paragraph to the cache
        /// </summary>
        /// <returns>HVO of the new paragraph</returns>
        /// ------------------------------------------------------------------------------------
        protected int AddFootnoteAndParagraph()
        {
            int           cTexts       = m_cache.get_VecSize(m_hvoRoot, SimpleRootsiteTestsConstants.kflidDocFootnotes);
            int           hvoFootnote  = m_cache.MakeNewObject(SimpleRootsiteTestsConstants.kclsidStFootnote, m_hvoRoot, SimpleRootsiteTestsConstants.kflidDocFootnotes, cTexts);
            int           hvoPara      = m_cache.MakeNewObject(SimpleRootsiteTestsConstants.kclsidStTxtPara, hvoFootnote, SimpleRootsiteTestsConstants.kflidTextParas, 0);
            ITsStrFactory tsStrFactory = TsStrFactoryClass.Create();

            m_cache.CacheStringProp(hvoFootnote, SimpleRootsiteTestsConstants.kflidFootnoteMarker,
                                    tsStrFactory.MakeString("a", m_wsFrn));
            m_cache.CacheStringProp(hvoPara, SimpleRootsiteTestsConstants.kflidParaContents,
                                    tsStrFactory.MakeString(string.Empty, m_wsFrn));
            return(hvoPara);
        }
Esempio n. 23
0
        public void PasteParagraphsWithSameStyle()
        {
            // Add a title to the root object
            int           hvoTitle      = m_cache.MakeNewObject(SimpleRootsiteTestsConstants.kclsidStText, m_hvoRoot, SimpleRootsiteTestsConstants.kflidDocTitle, -2);
            int           hvoTitlePara1 = m_cache.MakeNewObject(SimpleRootsiteTestsConstants.kclsidStTxtPara, hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 0);
            ITsStrFactory tsStrFactory  = TsStrFactoryClass.Create();

            m_cache.CacheStringProp(hvoTitlePara1, SimpleRootsiteTestsConstants.kflidParaContents,
                                    tsStrFactory.MakeString("The First Book of the Law given by Moses", m_wsEng));
            ITsPropsFactory fact = TsPropsFactoryClass.Create();

            m_cache.SetUnknown(hvoTitlePara1, SimpleRootsiteTestsConstants.kflidParaProperties, fact.MakeProps("Title", m_wsEng, 0));

            int    hvoTitlePara2      = m_cache.MakeNewObject(SimpleRootsiteTestsConstants.kclsidStTxtPara, hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 1);
            string secondParaContents = "and Aaron";

            m_cache.CacheStringProp(hvoTitlePara2, SimpleRootsiteTestsConstants.kflidParaContents,
                                    tsStrFactory.MakeString(secondParaContents, m_wsEng));
            m_cache.SetUnknown(hvoTitlePara2, SimpleRootsiteTestsConstants.kflidParaProperties, fact.MakeProps("Title", m_wsEng, 0));

            ShowForm(SimpleViewVc.DisplayType.kTitle |
                     SimpleViewVc.DisplayType.kUseParaProperties |
                     SimpleViewVc.DisplayType.kOnlyDisplayContentsOnce);

            // Make a selection from the top of the view to the bottom.
            IVwSelection sel0 = m_basicView.RootBox.MakeSimpleSel(true, false, false, false);
            IVwSelection sel1 = m_basicView.RootBox.MakeSimpleSel(false, false, false, false);

            m_basicView.RootBox.MakeRangeSelection(sel0, sel1, true);

            // Copy the selection and then paste it at the start of the view.
            Assert.IsTrue(m_basicView.EditingHelper.CopySelection());
            // Install a simple selection at the start of the view.
            m_basicView.RootBox.MakeSimpleSel(true, true, false, true);

            // This is a legal paste.
            m_basicView.EditingHelper.PasteClipboard();

            // We expect the contents to change.
            Assert.AreEqual(4, m_cache.get_VecSize(hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas));
            Assert.AreEqual(hvoTitlePara2 + 1, m_cache.get_VecItem(hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 0));
            Assert.AreEqual(hvoTitlePara2 + 2, m_cache.get_VecItem(hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 1));
            Assert.AreEqual(hvoTitlePara1, m_cache.get_VecItem(hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 2));
            Assert.AreEqual(hvoTitlePara2, m_cache.get_VecItem(hvoTitle, SimpleRootsiteTestsConstants.kflidTextParas, 3));

            Assert.IsNotNull(m_basicView.RequestedSelectionAtEndOfUow);
            // WANTTESTPORT: (Common) FWR-1649 Check properties of RequestedSelectionAtEndOfUow
        }
        public TitleContentsVc(FdoCache cache)
        {
            int           wsUser = cache.DefaultUserWs;
            ITsStrFactory tsf    = TsStrFactoryClass.Create();

            m_tssTitle = tsf.MakeString(ITextStrings.ksTitle, wsUser);
            ITsPropsBldr tpb = TsPropsBldrClass.Create();

            tpb.SetIntPropValues((int)FwTextPropType.ktptBold,
                                 (int)FwTextPropVar.ktpvEnum,
                                 (int)FwTextToggleVal.kttvForceOn);
            m_ttpBold = tpb.GetTextProps();
            tpb       = TsPropsBldrClass.Create();
            // Set some padding all around.
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadTop,
                                 (int)FwTextPropVar.ktpvMilliPoint, 1000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadBottom,
                                 (int)FwTextPropVar.ktpvMilliPoint, 1000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadLeading,
                                 (int)FwTextPropVar.ktpvMilliPoint, 3000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptPadTrailing,
                                 (int)FwTextPropVar.ktpvMilliPoint, 3000);
            tpb.SetIntPropValues((int)FwTextPropType.ktptMarginTrailing,
                                 (int)FwTextPropVar.ktpvMilliPoint, 11000); // 10000 clips right border.
            m_ttpDataCellProps = tpb.GetTextProps();

            m_vtagStTextTitle = cache.MetaDataCacheAccessor.GetFieldId("StText", "Title", false);

            // Set up the array of writing systems we will display for title.
            SetupWritingSystemsForTitle(cache);
        }
Esempio n. 25
0
		int m_wsUr; // Urdu writing system (used for Foreign style)
		#endregion

		#region Test setup
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_inMemoryCache.InitializeWritingSystemEncodings();

			// create footnote
			m_footnote = new StFootnote();
			m_book = (ScrBook)m_scrInMemoryCache.AddBookToMockedScripture(1, "Genesis");
			m_book.FootnotesOS.Append(m_footnote);
			m_footnote.FootnoteMarker.Text = "o";
			m_footnote.DisplayFootnoteMarker = true;
			m_footnote.DisplayFootnoteReference = false;

			// create one empty footnote para
			StTxtPara para = new StTxtPara();
			m_footnote.ParagraphsOS.Append(para);
			para.StyleRules = StyleUtils.ParaStyleTextProps(ScrStyleNames.NormalFootnoteParagraph);

			m_strFact = TsStrFactoryClass.Create();
			m_vernWs = Cache.LangProject.DefaultVernacularWritingSystem;
			para.Contents.UnderlyingTsString = m_strFact.MakeString(string.Empty, m_vernWs);
			m_footnotePara = (StTxtPara)m_footnote.ParagraphsOS[0];

			m_wsUr = InMemoryFdoCache.s_wsHvos.Ur; // used with 'foreign' character style
			m_wsDe = InMemoryFdoCache.s_wsHvos.De; // used for back translations
			m_wsEs = InMemoryFdoCache.s_wsHvos.Es;
		}
Esempio n. 26
0
        public override void MakeRoot()
        {
            m_rootb = (IVwRootBox) new FwViews.VwRootBoxClass();
            m_rootb.SetSite(this);

            int hvoRoot = 1;

            m_sda = (ISilDataAccess) new FwViews.VwCacheDaClass();
            // Usually not here, but in some application global passed to each view.
            m_wsf = (ILgWritingSystemFactory) new FwLanguage.LgWritingSystemFactoryClass();
            m_sda.set_WritingSystemFactory(m_wsf);
            m_rootb.set_DataAccess(m_sda);

            ITsStrFactory tsf = (ITsStrFactory) new FwKernelLib.TsStrFactoryClass();
            ITsString     tss = tsf.MakeString("Hello World! This is a view", m_wsf.get_UserWs());

            IVwCacheDa cda = (IVwCacheDa)m_sda;

            cda.CacheStringProp(hvoRoot, ktagProp, tss);

            m_vVc = new HvVc();

            m_rootb.SetRootObject(hvoRoot, m_vVc, kfrText, null);
            m_fRootboxMade   = true;
            m_dxdLayoutWidth = -50000;             // Don't try to draw until we get OnSize and do layout.
        }
Esempio n. 27
0
        public void FindNextMissingBtFootnoteMarker_BtSectionHeadToNowhere()
        {
            IScrSection section = m_exodus.SectionsOS[1];

            ITsStrFactory strfact     = TsStrFactoryClass.Create();
            IStTxtPara    contentPara = section.ContentOA[0];
            ITsStrBldr    strBldr     = contentPara.Contents.GetBldr();
            IStFootnote   foot        = m_exodus.InsertFootnoteAt(0, strBldr, 7);

            contentPara.Contents = strBldr.GetString();
            IScrTxtPara footPara = Cache.ServiceLocator.GetInstance <IScrTxtParaFactory>().CreateWithStyle(
                foot, ScrStyleNames.NormalFootnoteParagraph);

            footPara.Contents = strfact.MakeString("This is footnote text for footnote", Cache.DefaultVernWs);

            ICmTranslation trans = contentPara.GetOrCreateBT();
            ITsStrBldr     bldr  = trans.Translation.get_String(Cache.DefaultAnalWs).GetBldr();

            TsStringUtils.InsertOrcIntoPara(foot.Guid, FwObjDataTypes.kodtNameGuidHot, bldr, 2, 2, Cache.DefaultAnalWs);
            trans.Translation.set_String(Cache.DefaultAnalWs, bldr.GetString());

            m_draftView.SetInsertionPoint(ScrSectionTags.kflidHeading, 0, 1, 0);

            m_draftView.CallNextMissingBtFootnoteMarker();

            SelectionHelper helper = m_draftView.EditingHelper.CurrentSelection;

            Assert.AreEqual(0, helper.IchAnchor);
            Assert.AreEqual(0, m_draftView.TeEditingHelper.BookIndex);
            Assert.AreEqual(1, m_draftView.TeEditingHelper.SectionIndex);
            Assert.AreEqual(0, m_draftView.ParagraphIndex);
            Assert.AreEqual(ScrSectionTags.kflidHeading, m_draftView.EditingHelper.CurrentSelection.LevelInfo[2].tag);
            Assert.IsTrue(m_draftView.TeEditingHelper.IsBackTranslation);
        }
Esempio n. 28
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates a blank dummy footnote. Used when a footnote object is missing.
        /// Note: This does not insert an ORC into the paragraph. The caller is fixing the ORC
        /// with a missing object.
        /// </summary>
        /// <param name="owner">The owner to which we will add a footnote.</param>
        /// <param name="iFootnote">The 0-based index where the footnote will be inserted in the
        /// owner.</param>
        /// <param name="paraContents">The paragraph string where the ORC is being fixed.</param>
        /// <param name="iRun">The 0-based index of the run from which we will get the writing
        /// system used in the footnote.</param>
        /// <returns>a blank general footnote</returns>
        /// ------------------------------------------------------------------------------------
        protected override StFootnote CreateBlankDummyFootnoteNoRecursion(ICmObject owner,
                                                                          int iFootnote, ITsString paraContents, int iRun)
        {
            if (!(owner is IScrBook))
            {
                return(base.CreateBlankDummyFootnoteNoRecursion(owner, iFootnote, paraContents, iRun));
            }

            // get the writing system of the existing ORC run
            int nDummy;
            int ws = paraContents.get_Properties(iRun).GetIntPropValues(
                (int)FwTextPropType.ktptWs, out nDummy);

            //  Make a dummy blank footnote
            IScripture scr         = m_cache.LangProject.TranslatedScriptureOA;
            string     sMarker     = scr.GeneralFootnoteMarker;
            StFootnote newFootnote = ScrFootnote.CreateFootnoteInScrBook((IScrBook)owner, iFootnote, ref sMarker,
                                                                         m_cache, ws);

            // Create an empty footnote paragraph with properties with default style and writing system.
            StTxtPara footnotePara = new StTxtPara();

            newFootnote.ParagraphsOS.Append(footnotePara);
            footnotePara.StyleRules = StyleUtils.ParaStyleTextProps(ScrStyleNames.NormalFootnoteParagraph);
            // Insert an empty run into the footnote paragraph in order to set the
            // default writing system.
            ITsStrFactory strFactory = TsStrFactoryClass.Create();

            footnotePara.Contents.UnderlyingTsString =
                strFactory.MakeString(string.Empty, m_cache.DefaultVernWs);

            return(newFootnote);
        }
Esempio n. 29
0
        public void FixOrcsWithoutProps_OrphanedFootnoteAndValidPicture()
        {
            CheckDisposed();

            IScrBook  exodus = CreateExodusData();
            StTxtPara para   = AddPara(exodus.SectionsOS[2]);

            AddVerse(para, 2, 3, "ORC is here, you see, my friend.");

            // Update the paragraph contents to include the picture
            ITsStrBldr    tsStrBldr = para.Contents.UnderlyingTsString.GetBldr();
            ITsStrFactory factory   = TsStrFactoryClass.Create();
            CmPicture     pict      = new CmPicture(Cache, "c:\\junk.jpg",
                                                    factory.MakeString("Test picture", Cache.DefaultVernWs),
                                                    StringUtils.LocalPictures);

            Assert.IsNotNull(pict);
            pict.InsertOwningORCIntoPara(tsStrBldr, 11, 0);
            para.Contents.UnderlyingTsString = tsStrBldr.GetString();

            // Update the paragraph contents to include the (orphaned) footnote marker
            CreateFootnote(exodus, 1, 0, 1, 19, ScrStyleNames.CrossRefFootnoteParagraph, true);

            TeScrInitializer scrInit = new TestTeScrInitializer(Cache);
            List <string>    report  = (List <string>)ReflectionHelper.GetResult(scrInit, "FixOrcsWithoutProps");

            VerifyNoOrphanedFootnotes();
            VerifyResourceForFixedOrphans();

            Assert.AreEqual(1, report.Count);
            Assert.AreEqual("EXO 1:2 - Deleted corrupted footnote marker or picture anchor", report[0]);

            Assert.AreEqual(0, exodus.FootnotesOS.Count);
        }
Esempio n. 30
0
        /// <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;
                }
            }
        }
Esempio n. 31
0
        public void FindNextMissingBtFootnoteMarker_BtSectionHeadToContent()
        {
            IScrSection section = m_exodus.SectionsOS[1];

            ITsStrFactory strfact     = TsStrFactoryClass.Create();
            IStTxtPara    contentPara = section.ContentOA[0];
            ITsStrBldr    strBldr     = contentPara.Contents.GetBldr();
            IStFootnote   foot        = m_exodus.InsertFootnoteAt(0, strBldr, 7);

            contentPara.Contents = strBldr.GetString();
            IScrTxtPara footPara = Cache.ServiceLocator.GetInstance <IScrTxtParaFactory>().CreateWithStyle(
                foot, ScrStyleNames.NormalFootnoteParagraph);

            footPara.Contents = strfact.MakeString("This is footnote text for footnote", Cache.DefaultVernWs);

            ICmTranslation trans = contentPara.GetOrCreateBT();

            m_draftView.SetInsertionPoint(ScrSectionTags.kflidHeading, 0, 1, 0);

            m_draftView.CallNextMissingBtFootnoteMarker();

            SelectionHelper helper = m_draftView.EditingHelper.CurrentSelection;

            Assert.AreEqual(2, helper.IchAnchor, "IP should be after chapter and verse number.");
            Assert.AreEqual(0, m_draftView.TeEditingHelper.BookIndex);
            Assert.AreEqual(1, m_draftView.TeEditingHelper.SectionIndex);
            Assert.AreEqual(0, m_draftView.ParagraphIndex);
            Assert.AreEqual(ScrSectionTags.kflidContent,
                            m_draftView.EditingHelper.CurrentSelection.LevelInfo[2].tag);
            Assert.IsTrue(m_draftView.TeEditingHelper.IsBackTranslation);
        }
Esempio n. 32
0
		private void PrintOneTemplateHeader(IVwEnv vwenv, ITsStrFactory tssFact, int analWs, int icol)
		{
			MakeCellsMethod.OpenStandardCell(vwenv, 1, m_chart.Logic.GroupEndIndices.Contains(icol));
			vwenv.AddString(tssFact.MakeString(m_chart.Logic.GetColumnLabel(icol), analWs));
			vwenv.CloseTableCell();
		}
Esempio n. 33
0
		private ITsString NameOfWs(ITsStrFactory tsf, int i)
		{
			// Don't use this, it uses the analysis default writing system which is not wanted per LT-4610.
			//tsf.MakeString(m_rgws[i].Abbreviation, m_wsUI);
			ILgWritingSystem ws = m_rgws[i];
			// Display in English if possible for now (August 2008).  See LT-8631 and LT-8574.
			ITsString result = ws.Cache.MainCacheAccessor.get_MultiStringAlt(ws.Hvo,
				(int)LgWritingSystem.LgWritingSystemTags.kflidAbbr, m_wsEn/*m_wsUI*/);

			if (result == null || result.Length == 0)
				return tsf.MakeString(m_rgws[i].Abbreviation, m_wsEn/*m_wsUI*/);
			return result;
		}
Esempio n. 34
0
		public override void FixtureSetup()
		{
			base.FixtureSetup();

			SetupTestModel(Resources.TextCacheModel_xml);

			m_sda = new RealDataCache();
			m_sda.MetaDataCache = MetaDataCache.CreateMetaDataCache("TestModel.xml");
			//m_cache.ParaContentsFlid = kflidParaContents;
			//m_cache.ParaPropertiesFlid = kflidParaProperties;
			//m_cache.TextParagraphsFlid = kflidTextParas;

			Debug.Assert(m_wsManager == null);
			m_wsManager = Cache.ServiceLocator.GetInstance<IWritingSystemManager>();
			m_sda.WritingSystemFactory = m_wsManager;

			m_wsAnal = Cache.DefaultAnalWs;

			m_wsVern = Cache.DefaultVernWs;

			//IWritingSystem deWs;
			//m_wsManager.GetOrSet("de", out deWs);
			//m_wsDeu = deWs.Handle;

			//m_wsManager.UserWs = m_wsEng;
			//m_wsUser = m_wsManager.UserWs;

			m_tsf = TsStrFactoryClass.Create();

			m_hvoLexDb = m_sda.MakeNewObject(kclsidLexDb, 0, -1, -1);

			kflidLexDb_Entries = m_sda.MetaDataCache.GetFieldId("LexDb", "Entries", false);
			kflidEntry_Form = m_sda.MetaDataCache.GetFieldId("Entry", "Form", false);
			kflidEntry_Summary = m_sda.MetaDataCache.GetFieldId("Entry", "Summary", false);

			m_hvoKick = m_sda.MakeNewObject(kclsidEntry, m_hvoLexDb, kflidLexDb_Entries, 0);
			m_sda.SetMultiStringAlt(m_hvoKick, kflidEntry_Form, m_wsVern, m_tsf.MakeString("kick", m_wsVern));
			m_sda.SetString(m_hvoKick, kflidEntry_Summary, m_tsf.MakeString("strike with foot", m_wsAnal));

			var keyAttrs = new Dictionary<string, string[]>();
			keyAttrs["layout"] = new[] { "class", "type", "name", "choiceGuid" };
			keyAttrs["group"] = new[] { "label" };
			keyAttrs["part"] = new[] { "ref" };
			var layoutInventory = new Inventory("*.fwlayout", "/LayoutInventory/*", keyAttrs, "test", "nowhere");
			layoutInventory.LoadElements(Resources.Layouts_xml, 1);

			keyAttrs = new Dictionary<string, string[]>();
			keyAttrs["part"] = new[] { "id" };

			var partInventory = new Inventory("*Parts.xml", "/PartInventory/bin/*", keyAttrs, "test", "nowhere");
			partInventory.LoadElements(Resources.Parts_xml, 1);

			m_layouts = new LayoutCache(m_sda.MetaDataCache, layoutInventory, partInventory);
		}
Esempio n. 35
0
		/// <summary>
		/// Initialize the control.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="mediator"></param>
		/// <param name="parentForm"></param>
		public void Initialize(FdoCache cache, Mediator mediator, Form parentForm, SandboxGenericMSA sandboxMSA)
		{
			CheckDisposed();

			m_parentForm = parentForm;
			m_mediator = mediator;
			m_tsf = cache.TsStrFactory;
			m_cache = cache;

			IVwStylesheet stylesheet = FontHeightAdjuster.StyleSheetFromMediator(mediator);
			int defUserWs = m_cache.ServiceLocator.WritingSystemManager.UserWs;
			IWritingSystem defAnalWs = m_cache.ServiceLocator.WritingSystems.DefaultAnalysisWritingSystem;
			string defAnalWsFont = defAnalWs.DefaultFontName;

			m_fwcbAffixTypes.WritingSystemFactory = m_cache.WritingSystemFactory;
			m_fwcbAffixTypes.WritingSystemCode = defAnalWs.Handle;
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksNotSure, defUserWs));
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksInflectional, defUserWs));
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksDerivational, defUserWs));
			m_fwcbAffixTypes.StyleSheet = stylesheet;
			m_fwcbAffixTypes.AdjustStringHeight = false;

			m_fwcbSlots.Font = new Font(defAnalWsFont, 10);
			m_fwcbSlots.WritingSystemFactory = m_cache.WritingSystemFactory;
			m_fwcbSlots.WritingSystemCode = defAnalWs.Handle;
			m_fwcbSlots.StyleSheet = stylesheet;
			m_fwcbSlots.AdjustStringHeight = false;

			m_tcMainPOS.Font = new Font(defAnalWsFont, 10);
			m_tcMainPOS.WritingSystemFactory = m_cache.WritingSystemFactory;
			m_tcMainPOS.WritingSystemCode = defAnalWs.Handle;
			m_tcMainPOS.StyleSheet = stylesheet;
			m_tcMainPOS.AdjustStringHeight = false;

			m_tcSecondaryPOS.Font = new Font(defAnalWsFont, 10);
			m_tcSecondaryPOS.WritingSystemFactory = m_cache.WritingSystemFactory;
			m_tcSecondaryPOS.WritingSystemCode = defAnalWs.Handle;
			m_tcSecondaryPOS.StyleSheet = stylesheet;
			m_tcSecondaryPOS.AdjustStringHeight = false;

			m_selectedMainPOS = sandboxMSA.MainPOS;
			m_fwcbAffixTypes.SelectedIndex = 0;
			m_fwcbAffixTypes.SelectedIndexChanged += HandleComboMSATypesChange;
			m_mainPOSPopupTreeManager = new POSPopupTreeManager(m_tcMainPOS, m_cache,
				m_cache.LanguageProject.PartsOfSpeechOA,
				defAnalWs.Handle, false, m_mediator,
				m_parentForm);
			m_mainPOSPopupTreeManager.NotSureIsAny = true;
			m_mainPOSPopupTreeManager.LoadPopupTree(m_selectedMainPOS != null ? m_selectedMainPOS.Hvo : 0);
			m_mainPOSPopupTreeManager.AfterSelect += m_mainPOSPopupTreeManager_AfterSelect;
			m_fwcbSlots.SelectedIndexChanged += HandleComboSlotChange;
			m_secPOSPopupTreeManager = new POSPopupTreeManager(m_tcSecondaryPOS, m_cache,
				m_cache.LanguageProject.PartsOfSpeechOA,
				defAnalWs.Handle, false, m_mediator,
				m_parentForm);
			m_secPOSPopupTreeManager.NotSureIsAny = true; // only used for affixes.
			m_selectedSecondaryPOS = sandboxMSA.SecondaryPOS;
			m_secPOSPopupTreeManager.LoadPopupTree(m_selectedSecondaryPOS != null ? m_selectedSecondaryPOS.Hvo : 0);
			m_secPOSPopupTreeManager.AfterSelect += m_secPOSPopupTreeManager_AfterSelect;

			// Relocate the m_tcSecondaryPOS control to overlay the m_fwcbSlots.
			// In the designer, they are offset to see them, and edit them.
			// In running code they are in the same spot, but only one is visible at a time.
			m_tcSecondaryPOS.Location = m_fwcbSlots.Location;

			if (m_selectedMainPOS != null && sandboxMSA.MsaType == MsaType.kInfl)
			{
				// This fixes LT-4677, LT-6048, and LT-6201.
				ResetSlotCombo();
			}
			MSAType = sandboxMSA.MsaType;
		}
Esempio n. 36
0
		public void MakeStringProp(int hvo, XmlNode node, string attrName, int tag, int ws, ITsStrFactory tsf,
			IVwCacheDa cda)
		{
			string val = GetAttrVal(node, attrName);
			if (val == null)
				return;
			cda.CacheStringProp(hvo, tag, tsf.MakeString(val, ws));
		}
Esempio n. 37
0
		protected virtual void SetDlgInfo(FdoCache cache, WindowParams wp, Mediator mediator, int wsVern)
		{
			CheckDisposed();

			Debug.Assert(cache != null);
			m_cache = cache;

			m_mediator = mediator;

			if (m_mediator != null)
			{
				ReplaceMatchingItemsControl();

				// Reset window location.
				// Get location to the stored values, if any.
				object locWnd = m_mediator.PropertyTable.GetValue(PersistenceLabel + "DlgLocation");
				object szWnd = m_mediator.PropertyTable.GetValue(PersistenceLabel + "DlgSize");
				if (locWnd != null && szWnd != null)
				{
					Rectangle rect = new Rectangle((Point)locWnd, (Size)szWnd);

					//grow it if it's too small.  This will happen when we add new controls to the dialog box.
					if(rect.Width < btnHelp.Left + btnHelp.Width + 30)
						rect.Width = btnHelp.Left + btnHelp.Width + 30;

					if(rect.Height < btnHelp.Top + btnHelp.Height + 50)
						rect.Height = btnHelp.Top + btnHelp.Height + 50;

					//rect.Height = 600;

					ScreenUtils.EnsureVisibleRect(ref rect);
					DesktopBounds = rect;
					StartPosition = FormStartPosition.Manual;
				}
			}

			SetupBasicTextProperties(wp);

			IVwStylesheet stylesheet = FontHeightAdjuster.StyleSheetFromMediator(mediator);
			InitializeMatchingEntries(cache, mediator);
			int hvoWs = wsVern;
			// Set font, writing system factory, and writing system code for the Lexical Form
			// edit box.  Also set an empty string with the proper writing system.
			m_tbForm.Font =
				new Font(cache.LanguageWritingSystemFactoryAccessor.get_EngineOrNull(wsVern).DefaultSerif, 10);
			m_tbForm.WritingSystemFactory = cache.LanguageWritingSystemFactoryAccessor;
			m_tbForm.WritingSystemCode = hvoWs;
			m_tsf = TsStrFactoryClass.Create();
			m_tbForm.AdjustStringHeight = false;
			m_tbForm.Tss = m_tsf.MakeString("", hvoWs);
			m_tbForm.StyleSheet = stylesheet;

			// Setup the fancy message text box.
			// Note: at 120DPI (only), it seems to be essential to set at least the WSF of the
			// bottom message even if not using it.
			SetupBottomMsg();
			SetBottomMessage();
			m_fwTextBoxBottomMsg.BorderStyle = BorderStyle.None;

			m_analHvos.AddRange(cache.LangProject.CurAnalysisWssRS.HvoArray);
			List<int> vernList = new List<int>(cache.LangProject.CurVernWssRS.HvoArray);
			m_vernHvos.AddRange(vernList);
			LoadWritingSystemCombo();
			int iWs = vernList.IndexOf(hvoWs);
			ILgWritingSystem lgwsCurrent;
			if (iWs < 0)
			{
				List<int> analList = new List<int>(cache.LangProject.CurAnalysisWssRS.HvoArray);
				iWs = analList.IndexOf(hvoWs);
				if (iWs < 0)
				{
					lgwsCurrent = LgWritingSystem.CreateFromDBObject(cache, hvoWs);
					m_cbWritingSystems.Items.Add(lgwsCurrent);
				}
				else
				{
					lgwsCurrent = cache.LangProject.CurAnalysisWssRS[iWs];
				}
			}
			else
			{
				lgwsCurrent = cache.LangProject.CurVernWssRS[iWs];
			}
			Debug.Assert(lgwsCurrent != null && lgwsCurrent.Hvo == hvoWs);

			m_skipCheck = true;
			m_cbWritingSystems.SelectedItem = lgwsCurrent;
			m_skipCheck = false;
			// Don't hook this up until AFTER we've initialized it; otherwise, it can
			// modify the contents of the form as a side effect of initialization.
			// Also, doing that triggers laying out the dialog prematurely, before
			// we've set WSF on all the controls.
			m_cbWritingSystems.SelectedIndexChanged += new System.EventHandler(this.m_cbWritingSystems_SelectedIndexChanged);


			// Adjust things if the form box needs to grow to accommodate its style.
			int oldHeight = m_tbForm.Height;
			int newHeight = Math.Max(oldHeight, m_tbForm.PreferredHeight);
			int delta = newHeight - oldHeight;
			if (delta != 0)
			{
				m_tbForm.Height = newHeight;
				panel1.Height += delta;
				GrowDialogAndAdjustControls(delta, panel1);
			}
		}
		public override void Initialize()
		{
			CheckDisposed();
			base.Initialize();

			m_vc = new StVc();
			m_vc.Cache = Cache;

			m_pattern = VwPatternClass.Create();
			m_strFactory = TsStrFactoryClass.Create();

			m_pattern.Pattern = m_strFactory.MakeString("a", Cache.DefaultVernWs);
			m_pattern.MatchOldWritingSystem = false;
			m_pattern.MatchDiacritics = false;
			m_pattern.MatchWholeWord = false;
			m_pattern.MatchCase = false;
			m_pattern.UseRegularExpressions = false;
		}
		/// <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.
				}
			}
		}
Esempio n. 40
0
		protected virtual void SetDlgInfo(FdoCache cache, WindowParams wp, Mediator mediator, int ws)
		{
			CheckDisposed();

			Debug.Assert(cache != null);
			m_cache = cache;
			m_tsf = cache.TsStrFactory; // do this very early, other initializers may depend on it.

			m_mediator = mediator;

			if (m_mediator != null)
			{
				// Reset window location.
				// Get location to the stored values, if any.
				object locWnd = m_mediator.PropertyTable.GetValue(PersistenceLabel + "DlgLocation");
				object szWnd = m_mediator.PropertyTable.GetValue(PersistenceLabel + "DlgSize");
				if (locWnd != null && szWnd != null)
				{
					var rect = new Rectangle((Point)locWnd, (Size)szWnd);

					//grow it if it's too small.  This will happen when we add new controls to the dialog box.
					if (rect.Width < m_btnHelp.Left + m_btnHelp.Width + 30)
						rect.Width = m_btnHelp.Left + m_btnHelp.Width + 30;

					if (rect.Height < m_btnHelp.Top + m_btnHelp.Height + 50)
						rect.Height = m_btnHelp.Top + m_btnHelp.Height + 50;

					//rect.Height = 600;

					ScreenUtils.EnsureVisibleRect(ref rect);
					DesktopBounds = rect;
					StartPosition = FormStartPosition.Manual;
				}

				m_helpTopicProvider = m_mediator.HelpTopicProvider;
				if (m_helpTopicProvider != null)
				{
					m_helpProvider.HelpNamespace = m_helpTopicProvider.HelpFile;
					SetHelpButtonEnabled();
				}

			}

			SetupBasicTextProperties(wp);

			IVwStylesheet stylesheet = FontHeightAdjuster.StyleSheetFromMediator(mediator);
			// Set font, writing system factory, and writing system code for the Lexical Form
			// edit box.  Also set an empty string with the proper writing system.
			m_tbForm.Font = new Font(cache.ServiceLocator.WritingSystemManager.Get(ws).DefaultFontName, 10);
			m_tbForm.WritingSystemFactory = cache.WritingSystemFactory;
			m_tbForm.WritingSystemCode = ws;
			m_tbForm.AdjustStringHeight = false;
			m_tbForm.Tss = m_tsf.MakeString("", ws);
			m_tbForm.StyleSheet = stylesheet;

			// Setup the fancy message text box.
			// Note: at 120DPI (only), it seems to be essential to set at least the WSF of the
			// bottom message even if not using it.
			SetupBottomMsg();
			SetBottomMessage();
			m_fwTextBoxBottomMsg.BorderStyle = BorderStyle.None;

			m_analHvos.UnionWith(cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems.Select(wsObj => wsObj.Handle));
			List<int> vernList = cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems.Select(wsObj => wsObj.Handle).ToList();
			m_vernHvos.UnionWith(vernList);
			LoadWritingSystemCombo();
			int iWs = vernList.IndexOf(ws);
			IWritingSystem currentWs;
			if (iWs < 0)
			{
				List<int> analList = cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems.Select(wsObj => wsObj.Handle).ToList();
				iWs = analList.IndexOf(ws);
				if (iWs < 0)
				{
					currentWs = cache.ServiceLocator.WritingSystemManager.Get(ws);
					m_cbWritingSystems.Items.Add(currentWs);
					SetCbWritingSystemsSize();
				}
				else
				{
					currentWs = cache.ServiceLocator.WritingSystems.CurrentAnalysisWritingSystems[iWs];
				}
			}
			else
			{
				currentWs = cache.ServiceLocator.WritingSystems.CurrentVernacularWritingSystems[iWs];
			}
			Debug.Assert(currentWs != null && currentWs.Handle == ws);

			m_skipCheck = true;
			m_cbWritingSystems.SelectedItem = currentWs;
			m_skipCheck = false;
			// Don't hook this up until AFTER we've initialized it; otherwise, it can
			// modify the contents of the form as a side effect of initialization.
			// Also, doing that triggers laying out the dialog prematurely, before
			// we've set WSF on all the controls.
			m_cbWritingSystems.SelectedIndexChanged += m_cbWritingSystems_SelectedIndexChanged;

			InitializeMatchingObjects(cache, mediator);

			// Adjust things if the form box needs to grow to accommodate its style.
			int oldHeight = m_tbForm.Height;
			int newHeight = Math.Max(oldHeight, m_tbForm.PreferredHeight);
			int delta = newHeight - oldHeight;
			if (delta != 0)
			{
				m_tbForm.Height = newHeight;
				m_panel1.Height += delta;
				GrowDialogAndAdjustControls(delta, m_panel1);
			}
		}
		/// <summary>
		/// Add all the data from items in the FLExText file into their proper spots in the segment.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="wsFactory"></param>
		/// <param name="phrase"></param>
		/// <param name="newSegment"></param>
		/// <param name="tsStrFactory"></param>
		/// <param name="textInFile">This reference boolean indicates if there was a text item in the phrase</param>
		/// <param name="phraseText">This reference string will be filled with the contents of the "txt" item in the phrase if it is there</param>
		private static void AddSegmentItemData(FdoCache cache, ILgWritingSystemFactory wsFactory, Phrase phrase, ISegment newSegment, ITsStrFactory tsStrFactory, ref bool textInFile, ref ITsString phraseText)
		{
			if (phrase.Items != null)
			{
				foreach (var item in phrase.Items)
				{
					switch (item.type)
					{
						case "reference-label":
							newSegment.Reference = tsStrFactory.MakeString(item.Value,
								GetWsEngine(wsFactory, item.lang).Handle);
							break;
						case "gls":
							newSegment.FreeTranslation.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
							break;
						case "lit":
							newSegment.LiteralTranslation.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
							break;
						case "note":
							INote note = cache.ServiceLocator.GetInstance<INoteFactory>().Create();
							newSegment.NotesOS.Add(note);
							note.Content.set_String(GetWsEngine(wsFactory, item.lang).Handle, item.Value);
							break;
						case "txt":
							phraseText = tsStrFactory.MakeString(item.Value, GetWsEngine(wsFactory, item.lang).Handle);
							textInFile = true;
							break;
					}
				}
			}
		}
Esempio n. 42
0
		private static ITsString AdjustPunctStringForCharacter(
			ILgWritingSystemFactory wsFactory, ITsStrFactory tsStrFactory,
			item item, ITsString wordString, char punctChar, int index,
			char space, bool followsWord)
		{
			bool spaceBefore = false;
			bool spaceAfter = false;
			bool spaceHere = false;
			char quote = '"';
			var charType = Icu.GetCharType(punctChar);
			switch (charType)
			{
				case Icu.UCharCategory.U_END_PUNCTUATION:
				case Icu.UCharCategory.U_FINAL_PUNCTUATION:
					spaceAfter = true;
					break;
				case Icu.UCharCategory.U_START_PUNCTUATION:
				case Icu.UCharCategory.U_INITIAL_PUNCTUATION:
					spaceBefore = true;
					break;
				case Icu.UCharCategory.U_OTHER_PUNCTUATION: //handle special characters
					if(wordString.Text.LastIndexOfAny(new[] {',','.',';',':','?','!',quote}) == wordString.Length - 1) //treat as ending characters
					{
						spaceAfter = punctChar != '"' || wordString.Length > 1; //quote characters are extra special, if we find them on their own
																				//it is near impossible to know what to do, but it's usually nothing.
					}
					if (punctChar == '\xA1' || punctChar == '\xBF')
					{
						spaceHere = true;
					}
					if (punctChar == quote && wordString.Length == 1)
					{
						spaceBefore = followsWord; //if we find a lonely quotation mark after a word, we'll put a space before it.
					}
					break;
			}
			var wordBuilder = wordString.GetBldr();
			if(spaceBefore) //put a space to the left of the punct
			{
				ILgWritingSystem wsEngine;
				if (TryGetWsEngine(wsFactory, item.lang, out wsEngine))
				{
					wordBuilder.ReplaceTsString(0, 0, tsStrFactory.MakeString("" + space,
						wsEngine.Handle));
				}
				wordString = wordBuilder.GetString();
			}
			if (spaceHere && followsWord && !LastCharIsSpaceOrQuote(wordString, index, space, quote))
			{
				ILgWritingSystem wsEngine;
				if (TryGetWsEngine(wsFactory, item.lang, out wsEngine))
				{
					wordBuilder.ReplaceTsString(index, index, tsStrFactory.MakeString("" + space,
						wsEngine.Handle));
				}
				wordString = wordBuilder.GetString();
			}
			if(spaceAfter) //put a space to the right of the punct
			{
				ILgWritingSystem wsEngine;
				if (TryGetWsEngine(wsFactory, item.lang, out wsEngine))
				{
					wordBuilder.ReplaceTsString(wordBuilder.Length, wordBuilder.Length,
						tsStrFactory.MakeString("" + space, wsEngine.Handle));
				}
				wordString = wordBuilder.GetString();
			}
			//otherwise punct doesn't deserve a space.
			return wordString;
		}
Esempio n. 43
0
		public ConstChartVc(ConstChartBody chart)
			: base(chart.Cache)
		{
			m_chart = chart;
			m_cache = m_chart.Cache;
			m_tssFact = m_cache.TsStrFactory;
			m_tssSpace = m_tssFact.MakeString(" ", m_cache.DefaultAnalWs);
			m_rowRepo = m_cache.ServiceLocator.GetInstance<IConstChartRowRepository>();
			m_wordGrpRepo = m_cache.ServiceLocator.GetInstance<IConstChartWordGroupRepository>();
			m_partRepo = m_cache.ServiceLocator.GetInstance<IConstituentChartCellPartRepository>();
			m_sMovedTextBefore = m_tssFact.MakeString(DiscourseStrings.ksMovedTextBefore,
													m_cache.DefaultUserWs);
			m_sMovedTextAfter = m_tssFact.MakeString(DiscourseStrings.ksMovedTextAfter,
													m_cache.DefaultUserWs);
			LoadFormatProps();
		}
Esempio n. 44
0
		/// <summary>
		/// Add the pile of labels used to identify the lines in interlinear text.
		/// </summary>
		/// <param name="vwenv"></param>
		/// <param name="tsf"></param>
		/// <param name="cache"></param>
		/// <param name="wsList">Null if don't want multiple writing systems.</param>
		/// <param name="fShowMutlilingGlosses"></param>
		public void AddLabelPile(IVwEnv vwenv, ITsStrFactory tsf, FdoCache cache,
			bool fWantMultipleSenseGloss, bool fShowMorphemes)
		{
			CheckDisposed();

			int wsUI = cache.DefaultUserWs;
			int wsAnalysis = cache.DefaultAnalWs;
			vwenv.set_IntProperty((int)FwTextPropType.ktptMarginTrailing,
				(int)FwTextPropVar.ktpvMilliPoint, 10000);
			vwenv.set_IntProperty((int)FwTextPropType.ktptBold,
				(int)FwTextPropVar.ktpvEnum,
				(int)FwTextToggleVal.kttvForceOn);
			vwenv.set_IntProperty((int)FwTextPropType.ktptMarginBottom,
				(int)FwTextPropVar.ktpvMilliPoint,
				5000); // default spacing is fine for all embedded paragraphs.
			vwenv.OpenInnerPile();
			foreach (InterlinLineSpec spec in m_lineChoices)
			{
				if (!spec.WordLevel)
					break;
				SetColor(vwenv, LabelRGBFor(spec));
				ITsString tss = tsf.MakeString(m_lineChoices.LabelFor(spec.Flid), wsUI);
				if (m_lineChoices.RepetitionsOfFlid(spec.Flid) > 1)
				{
					vwenv.OpenParagraph();
					vwenv.AddString(tss);
					vwenv.AddString(m_cache.MakeUserTss(" "));
					vwenv.AddString(spec.WsLabel(m_cache));
					vwenv.CloseParagraph();
				}
				else
				{
					vwenv.AddString(tss);
				}

			}
			vwenv.CloseInnerPile();
		}
Esempio n. 45
0
		void AddCharSummary(ITsStrFactory tsf, string sNewKey, ArrayList alSublist, int ws)
		{
			ITsString tssChar = tsf.MakeString(sNewKey, ws);
			MultiLevelConc.SummaryInfo siChar = new MultiLevelConc.SummaryInfo(
				tssChar,alSublist);
			m_alCharSummaries.Add(siChar);
		}
		private static IAnalysis CreateWordAnalysisStack(FdoCache cache, Word word, ITsStrFactory strFactory)
		{
			if (word.Items == null || word.Items.Length <= 0) return null;
			IAnalysis analysis = null;
			var wsFact = cache.WritingSystemFactory;
			ILgWritingSystem wsMainVernWs = null;
			foreach (var wordItem in word.Items)
			{
				ITsString wordForm = null;
				switch (wordItem.type)
				{
					case "txt":
						wsMainVernWs = GetWsEngine(wsFact, wordItem.lang);
						wordForm = strFactory.MakeString(wordItem.Value, wsMainVernWs.Handle);
						analysis = WfiWordformServices.FindOrCreateWordform(cache, wordForm);
						break;
					case "punct":
						wordForm = strFactory.MakeString(wordItem.Value,
														 GetWsEngine(wsFact, wordItem.lang).Handle);
						analysis = WfiWordformServices.FindOrCreatePunctuationform(cache, wordForm);
						break;
				}
				if (wordForm != null)
					break;
			}

			// now add any alternative word forms. (overwrite any existing)
			if (analysis != null && analysis.HasWordform)
			{
				AddAlternativeWssToWordform(analysis, word, wsMainVernWs, strFactory);
			}

			if (analysis != null)
			{
				UpgradeToWordGloss(word, ref analysis);
			}
			else
			{
				Debug.Assert(analysis != null, "What else could this do?");
			}
			//Add any morphemes to the thing
			if (word.morphemes != null && word.morphemes.morphs.Length > 0)
			{
				//var bundle = newSegment.Cache.ServiceLocator.GetInstance<IWfiMorphBundleFactory>().Create();
				//analysis.Analysis.MorphBundlesOS.Add(bundle);
				//foreach (var morpheme in word.morphemes)
				//{
				//    //create a morpheme
				//    foreach(item item in morpheme.items)
				//    {
				//        //fill in morpheme's stuff
				//    }
				//}
			}
			return analysis;
		}
		public override void TestSetup()
		{
			base.TestSetup();

			m_vc = new StVc();
			m_vc.Cache = Cache;

			m_pattern = VwPatternClass.Create();
			m_strFactory = TsStrFactoryClass.Create();

			m_pattern.Pattern = m_strFactory.MakeString("a", Cache.DefaultVernWs);
			m_pattern.MatchOldWritingSystem = false;
			m_pattern.MatchDiacritics = false;
			m_pattern.MatchWholeWord = false;
			m_pattern.MatchCase = false;
			m_pattern.UseRegularExpressions = false;

			IScrBook genesis = AddBookWithTwoSections(1, "Genesis");
			m_section = genesis.SectionsOS[0];
			// Add paragraphs (because we use an StVc in the test we add them all to the same section)
			m_para1 = AddParaToMockedSectionContent(m_section,
				ScrStyleNames.NormalParagraph);
			AddRunToMockedPara(m_para1,
				"This is some text so that we can test the find functionality.", null);
			m_para2 = AddParaToMockedSectionContent(m_section,
				ScrStyleNames.NormalParagraph);
			AddRunToMockedPara(m_para2,
				"Some more text so that we can test the find and replace functionality.", null);
			m_para3 = AddParaToMockedSectionContent(
				m_section, ScrStyleNames.NormalParagraph);
			AddRunToMockedPara(m_para3,
				"This purugruph doesn't contuin the first letter of the ulphubet.", null);
		}
Esempio n. 48
0
		/// <summary>
		/// Initialize the control.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="mediator"></param>
		/// <param name="parentForm"></param>
		public void Initialize(FdoCache cache, Mediator mediator, Form parentForm, DummyGenericMSA dummyMSA)
		{
			CheckDisposed();

			m_parentForm = parentForm;
			m_mediator = mediator;
			m_tsf = TsStrFactoryClass.Create();
			m_cache = cache;

			IVwStylesheet stylesheet = FontHeightAdjuster.StyleSheetFromMediator(mediator);

			m_fwcbAffixTypes.WritingSystemFactory = m_cache.LanguageWritingSystemFactoryAccessor;
			m_fwcbAffixTypes.WritingSystemCode = m_cache.LangProject.DefaultAnalysisWritingSystem;
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksNotSure,
				m_cache.LangProject.DefaultUserWritingSystem));
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksInflectional,
				m_cache.LangProject.DefaultUserWritingSystem));
			m_fwcbAffixTypes.Items.Add(m_tsf.MakeString(LexTextControls.ksDerivational,
				m_cache.LangProject.DefaultUserWritingSystem));
			m_fwcbAffixTypes.StyleSheet = stylesheet;
			m_fwcbAffixTypes.AdjustStringHeight = false;

			m_fwcbSlots.Font = new System.Drawing.Font(cache.LangProject.DefaultAnalysisWritingSystemFont, 10);
			m_fwcbSlots.WritingSystemFactory = m_cache.LanguageWritingSystemFactoryAccessor;
			m_fwcbSlots.WritingSystemCode = m_cache.LangProject.DefaultAnalysisWritingSystem;
			m_fwcbSlots.StyleSheet = stylesheet;
			m_fwcbSlots.AdjustStringHeight = false;

			m_tcMainPOS.Font = new System.Drawing.Font(cache.LangProject.DefaultAnalysisWritingSystemFont, 10);
			m_tcMainPOS.WritingSystemFactory = m_cache.LanguageWritingSystemFactoryAccessor;
			m_tcMainPOS.WritingSystemCode = m_cache.LangProject.DefaultAnalysisWritingSystem;
			m_tcMainPOS.StyleSheet = stylesheet;
			m_tcMainPOS.AdjustStringHeight = false;

			m_tcSecondaryPOS.Font = new System.Drawing.Font(cache.LangProject.DefaultAnalysisWritingSystemFont, 10);
			m_tcSecondaryPOS.WritingSystemFactory = m_cache.LanguageWritingSystemFactoryAccessor;
			m_tcSecondaryPOS.WritingSystemCode = m_cache.LangProject.DefaultAnalysisWritingSystem;
			m_tcSecondaryPOS.StyleSheet = stylesheet;
			m_tcSecondaryPOS.AdjustStringHeight = false;

			m_selectedMainPOSHvo = dummyMSA.MainPOS;
			m_fwcbAffixTypes.SelectedIndex = 0;
			m_fwcbAffixTypes.SelectedIndexChanged += new EventHandler(
				HandleComboMSATypesChange);
			m_mainPOSPopupTreeManager = new POSPopupTreeManager(m_tcMainPOS, m_cache,
				m_cache.LangProject.PartsOfSpeechOA,
				m_cache.LangProject.DefaultAnalysisWritingSystem, false, m_mediator,
				m_parentForm);
			m_mainPOSPopupTreeManager.NotSureIsAny = true;
			m_mainPOSPopupTreeManager.LoadPopupTree(m_selectedMainPOSHvo);
			m_mainPOSPopupTreeManager.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(m_mainPOSPopupTreeManager_AfterSelect);
			m_fwcbSlots.SelectedIndexChanged += new EventHandler(
				HandleComboSlotChange);
			m_secPOSPopupTreeManager = new POSPopupTreeManager(m_tcSecondaryPOS, m_cache,
				m_cache.LangProject.PartsOfSpeechOA,
				m_cache.LangProject.DefaultAnalysisWritingSystem, false, m_mediator,
				m_parentForm);
			m_secPOSPopupTreeManager.NotSureIsAny = true; // only used for affixes.
			m_selectedSecondaryPOSHvo = dummyMSA.SecondaryPOS;
			m_secPOSPopupTreeManager.LoadPopupTree(m_selectedSecondaryPOSHvo);
			m_secPOSPopupTreeManager.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(m_secPOSPopupTreeManager_AfterSelect);

			// Relocate the m_tcSecondaryPOS control to overlay the m_fwcbSlots.
			// In the designer, they are offset to see them, and edit them.
			// In running code they are in the same spot, but only one is visible at a time.
			m_tcSecondaryPOS.Location = m_fwcbSlots.Location;

			if (m_selectedMainPOSHvo > 0 && dummyMSA.MsaType == MsaType.kInfl)
			{
				// This fixes LT-4677, LT-6048, and LT-6201.
				ResetSlotCombo();
			}
			MSAType = dummyMSA.MsaType;
		}
Esempio n. 49
0
			/// <summary>
			/// Add the specified string in the specified color to the display, using the UI Writing system.
			/// </summary>
			/// <param name="vwenv"></param>
			/// <param name="color"></param>
			/// <param name="str"></param>
			protected static void AddColoredString(IVwEnv vwenv, int color, ITsStrFactory tsf, int ws, string str)
			{
				SetColor(vwenv, color);
				vwenv.AddString(tsf.MakeString(str, ws));
			}
		/// <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;
				}
			}
		}
Esempio n. 51
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create an ITsString in the given writing system.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public static ITsString MakeTss(ITsStrFactory tsf, int wsHvo, string text)
		{
			return tsf.MakeString(text, wsHvo);
		}
Esempio n. 52
0
			/// <summary>
			/// Add to the vwenv the label(s) for a gloss line.
			/// If multiple glosses are wanted, it generates a set of labels
			/// </summary>
			public void AddGlossLabels(IVwEnv vwenv, ITsStrFactory tsf, int color, string baseLabel,
				FdoCache cache, WsListManager wsList)
			{
				if (wsList != null && wsList.AnalysisWsLabels.Length > 1)
				{
					ITsString tssBase = MakeUiElementString(baseLabel, cache.DefaultUserWs, null);
					ITsString space = tsf.MakeString(" ", cache.DefaultUserWs);
					foreach (ITsString tssLabel in wsList.AnalysisWsLabels)
					{
						SetColor(vwenv, color);
						vwenv.OpenParagraph();
						vwenv.AddString(tssBase);
						vwenv.AddString(space);
						vwenv.AddString(tssLabel);
						vwenv.CloseParagraph();
					}
				}
				else
				{
					AddColoredString(vwenv, color, tsf, cache.DefaultAnalWs, baseLabel);
				}
			}
Esempio n. 53
0
		private HvoTreeNode AddTreeNodeForMsa(PopupTree popupTree, ITsStrFactory tsf, IMoMorphSynAnalysis msa)
		{
			// JohnT: as described in LT-4633, a stem can be given an allomorph that
			// is an affix. So we need some sort of way to handle this.
			//Debug.Assert(msa is MoStemMsa);
			ITsString tssLabel = msa.InterlinearNameTSS;
			if (msa is IMoStemMsa && (msa as IMoStemMsa).PartOfSpeechRA == null)
				tssLabel = tsf.MakeString(
					m_sUnknown,
					Cache.ServiceLocator.WritingSystemManager.UserWs);
			var node = new HvoTreeNode(tssLabel, msa.Hvo);
			popupTree.Nodes.Add(node);
			return node;
		}
Esempio n. 54
0
		public void SetDlgInfo(Mediator mediator, WindowParams wp, List<IReversalIndexEntry> filteredEntries)
		{
			CheckDisposed();

			Debug.Assert(filteredEntries != null && filteredEntries.Count > 0);

			m_mediator = mediator;
			m_cache = (FdoCache)m_mediator.PropertyTable.GetValue("cache");
			m_ws = (filteredEntries[0] as ReversalIndexEntry).ReversalIndex.WritingSystemRAHvo;
			m_owningIndex = (filteredEntries[0] as ReversalIndexEntry).Owner;
			// Don't bother filtering out the current entry -- we don't do it for lex entries, why
			// do it here? (SFM 4/23/2009 Why? because it causes a crash, so uncommented)
			foreach (IReversalIndexEntry rie in filteredEntries)
			{
				ExtantReversalIndexEntryInfo eriei = new ExtantReversalIndexEntryInfo();
				eriei.ID = rie.Hvo;
				m_filteredEntries.Add(eriei);
			}
			// End SFM edit

			btnOK.Text = wp.m_btnText;
			Text = wp.m_title;
			label1.Text = wp.m_label;

			m_tbForm.Font = new Font(
					m_cache.LanguageWritingSystemFactoryAccessor.get_EngineOrNull(m_ws).DefaultSerif,
					10);
			m_tbForm.WritingSystemFactory = m_cache.LanguageWritingSystemFactoryAccessor;
			m_tbForm.StyleSheet = FontHeightAdjuster.StyleSheetFromMediator(mediator);
			m_tbForm.WritingSystemCode = m_ws;
			m_tbForm.AdjustStringHeight = false;
			m_tsf = TsStrFactoryClass.Create();
			m_tbForm.Tss = m_tsf.MakeString("", m_ws);
			m_tbForm.TextChanged += new EventHandler(m_tbForm_TextChanged);

			btnInsert.Visible = false;
			btnHelp.Visible = true;

			switch(Text)
			{
				case "Find Reversal Entry":
					m_helpTopic = "khtpFindReversalEntry";
					break;
				case "Move Reversal Entry":
					m_helpTopic = "khtpMoveReversalEntry";
					break;
			}
			if(m_helpTopic != null && FwApp.App != null) // FwApp.App could be null during tests
			{
				this.helpProvider = new System.Windows.Forms.HelpProvider();
				this.helpProvider.HelpNamespace = FwApp.App.HelpFile;
				this.helpProvider.SetHelpKeyword(this, FwApp.App.GetHelpString(m_helpTopic, 0));
				this.helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic);
			}
			Debug.Assert(m_mediator != null);
			ReplaceMatchingItemsControl();

			// Adjust things if the form box needs to grow to accommodate its style.
			int oldHeight = m_tbForm.Height;
			int newHeight = Math.Max(oldHeight, m_tbForm.PreferredHeight);
			int delta = newHeight - oldHeight;
			if (delta != 0)
			{
				m_tbForm.Height = newHeight;
				FontHeightAdjuster.GrowDialogAndAdjustControls(this, delta, m_tbForm);
			}
		}