Ejemplo n.º 1
0
        private static void CreateAnalysisForWord(string word, ISegment segment, int ws,
                                                  bool fCreateGlosses)
        {
            FdoCache               cache              = segment.Cache;
            IWfiWordformFactory    wfFactory          = cache.ServiceLocator.GetInstance <IWfiWordformFactory>();
            IWfiWordformRepository wfRepo             = cache.ServiceLocator.GetInstance <IWfiWordformRepository>();
            IWfiGlossFactory       glossFactory       = cache.ServiceLocator.GetInstance <IWfiGlossFactory>();
            IWfiAnalysisFactory    wfiAnalysisFactory = cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>();

            ITsString    tssForm = cache.TsStrFactory.MakeString(word, cache.DefaultVernWs);
            IWfiWordform form;
            IAnalysis    analysis;

            if (wfRepo.TryGetObject(tssForm, out form))
            {
                analysis = (fCreateGlosses) ? (IAnalysis)form.AnalysesOC.First().MeaningsOC.First() : form;
            }
            else
            {
                analysis = form = wfFactory.Create(tssForm);
                IWfiAnalysis actualWfiAnalysis = wfiAnalysisFactory.Create();
                form.AnalysesOC.Add(actualWfiAnalysis);
                if (fCreateGlosses)
                {
                    IWfiGloss gloss = glossFactory.Create();
                    actualWfiAnalysis.MeaningsOC.Add(gloss);
                    gloss.Form.set_String(ws, "G" + word + "g");
                    analysis = gloss;
                }
            }
            segment.AnalysesRS.Add(analysis);
        }
Ejemplo n.º 2
0
        // Generate a suitable string representation of a WfiGloss.
        // Todo: finish implementing (add the gloss!)
        static internal ITsString MakeGlossStringRep(IWfiGloss wg, LcmCache fdoCache, bool fUseStyleSheet)
        {
            ITsStrBldr tsb = TsStringUtils.MakeStrBldr();
            var        wa  = wg.Owner as IWfiAnalysis;

            var category = wa.CategoryRA;

            if (category != null)
            {
                ITsString tssPos = category.Abbreviation.get_String(fdoCache.DefaultAnalWs);
                tsb.Replace(0, 0, tssPos.Text,
                            PartOfSpeechTextProperties(fdoCache, false, fUseStyleSheet));
            }
            else
            {
                tsb.Replace(0, 0, ksMissingString,
                            PartOfSpeechTextProperties(fdoCache, false, fUseStyleSheet));
            }
            tsb.Replace(tsb.Length, tsb.Length, " ", null);
            tsb.Replace(tsb.Length, tsb.Length,
                        wg.Form.get_String(fdoCache.DefaultAnalWs).Text,
                        GlossTextProperties(fdoCache, false, fUseStyleSheet));

            //indent
            tsb.Replace(0, 0, "    ", null);
            return(tsb.GetString());
        }
Ejemplo n.º 3
0
        private void ValidateSenseWithAnalysis(ILexSense sense, IWfiGloss wfiGloss, int hvoSbWordPos, bool fMatchMainPossibility, IMoStemAllomorph allomorph)
        {
            IWfiAnalysis wfiAnalysis = wfiGloss.Owner as IWfiAnalysis;

            CompareTss(sense.Gloss.get_String(Cache.DefaultAnalWs),
                       wfiGloss.Form.get_String(Cache.DefaultAnalWs));

            // make sure the morph is linked to the lexicon sense, msa, and part of speech.
            IWfiMorphBundle morphBundle = wfiAnalysis.MorphBundlesOS[0];

            Assert.AreEqual(sense, morphBundle.SenseRA);
            Assert.AreEqual(sense.MorphoSyntaxAnalysisRA, morphBundle.MsaRA);
            if (!fMatchMainPossibility)
            {
                // expect exact possibility
                Assert.AreEqual(hvoSbWordPos, (sense.MorphoSyntaxAnalysisRA as IMoStemMsa).PartOfSpeechRA.Hvo);
            }
            else
            {
                IPartOfSpeech posTarget = Cache.ServiceLocator.GetInstance <IPartOfSpeechRepository>().GetObject(hvoSbWordPos);
                Assert.AreEqual(posTarget.MainPossibility, (sense.MorphoSyntaxAnalysisRA as IMoStemMsa).PartOfSpeechRA.MainPossibility);
            }
            Assert.AreEqual(allomorph, morphBundle.MorphRA);
            Assert.AreEqual(hvoSbWordPos, wfiAnalysis.CategoryRA.Hvo);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="argument">The xCore Command object.</param>
        /// <returns>true</returns>
        public bool OnShowWordGlossConc(object argument)
        {
            IWfiGloss gloss = Gloss;

            Debug.Assert(gloss != null, "Could not find gloss object.");

            ShowConcDlg(gloss);

            return(true);
        }
Ejemplo n.º 5
0
        public LexiconSense AddSense()
        {
            LexiconSense sense       = null;
            bool         lexemeAdded = false;

            using (m_lexicon.ActivationContext.Activate())
            {
                NonUndoableUnitOfWorkHelper.Do(m_lexicon.Cache.ActionHandlerAccessor, () =>
                {
                    IWfiWordform wordform;
                    if (!m_lexicon.TryGetWordform(m_key.LexicalForm, out wordform))
                    {
                        wordform    = m_lexicon.CreateWordform(m_key.LexicalForm);
                        lexemeAdded = true;
                    }
                    // For wordforms, our "senses" could be new meanings of an analysis for the word
                    // or it could be a brand new analysis. Because we have no idea what the user actually
                    // wanted, we just assume the worst (they want to create a new analysis for the word
                    // with a new meaning).
                    IWfiAnalysis analysis = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>().Create();
                    wordform.AnalysesOC.Add(analysis);
                    analysis.ApprovalStatusIcon = (int)Opinions.approves;                              // Assume the analysis from the external application is user approved
                    IMoStemAllomorph morph      = m_lexicon.Cache.ServiceLocator.GetInstance <IMoStemAllomorphRepository>().AllInstances().FirstOrDefault(allo =>
                    {
                        ITsString tss = allo.Form.StringOrNull(m_lexicon.DefaultVernWs);
                        if (tss != null)
                        {
                            return(tss.Text == LexicalForm.Normalize(NormalizationForm.FormD));
                        }
                        return(false);
                    });
                    if (morph != null)
                    {
                        IWfiMorphBundle mb = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>().Create();
                        analysis.MorphBundlesOS.Add(mb);
                        mb.MorphRA = morph;
                        var entry  = morph.OwnerOfClass <ILexEntry>();
                        mb.SenseRA = entry.SensesOS[0];
                        mb.MsaRA   = entry.SensesOS[0].MorphoSyntaxAnalysisRA;
                    }
                    IWfiGloss gloss = m_lexicon.Cache.ServiceLocator.GetInstance <IWfiGlossFactory>().Create();
                    analysis.MeaningsOC.Add(gloss);
                    sense = new WfiGlossLexiconSense(m_lexicon, m_key, gloss);
                });
            }
            if (lexemeAdded)
            {
                m_lexicon.OnLexemeAdded(this);
            }
            m_lexicon.OnLexiconSenseAdded(this, sense);
            return(sense);
        }
Ejemplo n.º 6
0
        private IWfiAnalysis SetupAnalysisForEntry(int hvoCba0_0, string gloss, ILexSense lexEntry1_Sense1, out WfiWordform wf)
        {
            int hvoWf = WfiWordform.GetWfiWordformFromInstanceOf(Cache, hvoCba0_0);

            wf = new WfiWordform(Cache, hvoWf);
            IWfiAnalysis analysis = wf.AnalysesOC.Add(new WfiAnalysis());

            analysis.CategoryRA = (lexEntry1_Sense1.MorphoSyntaxAnalysisRA as MoStemMsa).PartOfSpeechRA;
            IWfiGloss wfigloss = analysis.MeaningsOC.Add(new WfiGloss());

            wfigloss.Form.SetAlternative(gloss, Cache.DefaultAnalWs);
            return(analysis);
        }
Ejemplo n.º 7
0
        public void NewGlossNewLexEntryNewLexSense()
        {
            // load sandbox for first 'xxxa'
            var cba0_0 = GetNewAnalysisOccurence(m_text1, 0, 0, 0);

            m_sandbox.SwitchWord(cba0_0);

            // verify that the word gloss is empty
            ITsString tssEmpty     = TsStringUtils.MakeString("", Cache.DefaultAnalWs);
            ITsString tssWordGloss = m_sandbox.GetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                               Cache.DefaultAnalWs);

            CompareTss(tssEmpty, tssWordGloss);
            // add a new word gloss and confirm the analysis.
            ITsString tssWordGlossInSandbox = m_sandbox.SetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                                        Cache.DefaultAnalWs, "0.0.xxxa");
            // mark the count of LexEntries
            int cEntriesOrig = Cache.LangProject.LexDbOA.Entries.Count();
            // verify no analyses exist for this wordform;
            IWfiWordform wf = cba0_0.Analysis.Wordform;

            Assert.AreEqual(0, wf.AnalysesOC.Count);

            // set word pos, to first possibility (e.g. 'adjunct')
            int hvoSbWordPos = m_sandbox.SelectIndexInCombo(InterlinLineChoices.kflidWordPos, 0, 0);

            Assert.IsFalse(hvoSbWordPos == 0);             // select nonzero pos

            // confirm the analysis (making a real analysis and a LexSense)
            var wag          = m_sandbox.ConfirmAnalysis();
            var glossFactory = Cache.ServiceLocator.GetInstance <IWfiGlossFactory>();

            IWfiGloss wfiGloss = wag.Gloss;

            CompareTss(tssWordGlossInSandbox, wfiGloss.Form.get_String(Cache.DefaultAnalWs));
            // confirm we have only one analysis and that it is monomorphemic
            IWfiAnalysis wfiAnalysis = wag.WfiAnalysis;

            Assert.AreEqual(wf, wag.Wordform, "Expected confirmed analysis to be owned by the original wordform.");
            Assert.AreEqual(1, wf.AnalysesOC.Count);
            Assert.AreEqual(1, wfiAnalysis.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis.MeaningsOC.Count);

            // make sure the strings of the wfi gloss matches the strings of the lex gloss.
            ValidateSenseWithAnalysis(m_sandbox.GetLexSenseForWord(), wfiGloss, hvoSbWordPos);

            // make sure a new entry is in the Lexicon.
            int cEntriesAfter = Cache.LangProject.LexDbOA.Entries.Count();

            Assert.AreEqual(cEntriesOrig + 1, cEntriesAfter);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// For the given sequence of correspondences, generate analyses.
        /// </summary>
        private void GenerateEntryGuesses(IDictionary <IWfiWordform, EmptyWwfInfo> map)
        {
            var waFactory     = Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>();
            var wgFactory     = Cache.ServiceLocator.GetInstance <IWfiGlossFactory>();
            var wmbFactory    = Cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>();
            var computerAgent = Cache.LangProject.DefaultComputerAgent;

            foreach (var keyPair in map)
            {
                var ww   = keyPair.Key;
                var info = keyPair.Value;
                if (!HasAnalysis(ww))
                {
                    NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUowOrSkip(Cache.ActionHandlerAccessor,
                                                                             "Trying to generate guesses during PropChanged when we can't save them.",
                                                                             () =>
                    {
                        var newAnalysis        = waFactory.Create(ww, wgFactory);
                        newAnalysis.CategoryRA = info.Pos;
                        // Not all entries have senses.
                        if (info.Sense != null)
                        {
                            // copy all the gloss alternatives from the sense into the word gloss.
                            IWfiGloss wg = newAnalysis.MeaningsOC.First();
                            wg.Form.MergeAlternatives(info.Sense.Gloss);
                        }
                        var wmb = wmbFactory.Create();
                        newAnalysis.MorphBundlesOS.Add(wmb);
                        if (info.Form != null)
                        {
                            wmb.MorphRA = info.Form;
                        }
                        if (info.Msa != null)
                        {
                            wmb.MsaRA = info.Msa;
                        }
                        if (info.Sense != null)
                        {
                            wmb.SenseRA = info.Sense;
                        }

                        // Now, set up an approved "Computer" evaluation of this generated analysis
                        computerAgent.SetEvaluation(newAnalysis, Opinions.approves);
                    });
                }
            }
        }
Ejemplo n.º 9
0
        public void PickLexGlossCreatingNewAnalysis()
        {
            var cba0_0 = GetNewAnalysisOccurence(m_text1, 0, 0, 0);

            m_sandbox.SwitchWord(cba0_0);
            ILexEntry lexEntry1_Entry;
            ILexSense lexEntry1_Sense1;

            SetupLexEntryAndSense("xxxa", "0.0.xxxa", out lexEntry1_Entry, out lexEntry1_Sense1);

            // mark the count of LexEntries
            int cEntriesOrig = Cache.LangProject.LexDbOA.Entries.Count();

            // add a new word gloss
            m_sandbox.SetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                      Cache.DefaultAnalWs, "0.0.xxxa");
            IWfiWordform wf = cba0_0.Analysis.Wordform;
            // set word pos, to first possibility (e.g. 'adjunct')
            int hvoSbWordPos = m_sandbox.SelectIndexInCombo(InterlinLineChoices.kflidWordPos, 0, 0);

            // confirm the analysis (making a real analysis and a LexSense)
            var       wag      = m_sandbox.ConfirmAnalysis();
            IWfiGloss wfiGloss = wag.Gloss;

            // make sure we didn't add entries or senses to the Lexicon.
            int cEntriesAfter = Cache.LangProject.LexDbOA.Entries.Count();

            Assert.AreEqual(cEntriesOrig, cEntriesAfter);
            Assert.AreEqual(1, lexEntry1_Entry.SensesOS.Count);

            // make sure the sense matches the existing one.
            ILexSense sense = m_sandbox.GetLexSenseForWord();

            Assert.AreEqual(lexEntry1_Sense1.Hvo, sense.Hvo);
            // make sure the morph is linked to our lexicon sense, msa, and part of speech.
            ValidateSenseWithAnalysis(sense, wfiGloss, hvoSbWordPos);

            // confirm we have created a new analysis and that it is monomorphemic
            IWfiAnalysis wfiAnalysis = wag.WfiAnalysis;

            Assert.AreEqual(wf, wag.Wordform, "Expected confirmed analysis to be owned by the original wordform.");
            Assert.AreEqual(1, wf.AnalysesOC.Count);
            Assert.AreEqual(1, wfiAnalysis.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis.MeaningsOC.Count);
        }
			public GetRealAnalysisMethod(IHelpTopicProvider helpTopicProvider, SandboxBase owner,
				CachePair caches, int hvoSbWord, AnalysisTree oldAnalysis, IWfiAnalysis wa,
				IWfiGloss gloss, InterlinLineChoices choices, ITsString tssForm,
				bool fWantOnlyWfiAnalysis) : this()
			{
				m_helpTopicProvider = helpTopicProvider;
				m_sandbox = owner;
				m_caches = caches;
				m_hvoSbWord = hvoSbWord;
				m_oldAnalysis = oldAnalysis;
				m_wf = oldAnalysis.Wordform;
				m_wa = wa;
				m_wg = gloss;
				m_sda = m_caches.DataAccess;
				m_sdaMain = m_caches.MainCache.MainCacheAccessor;
				m_cmorphs = m_sda.get_VecSize(m_hvoSbWord, ktagSbWordMorphs);
				m_choices = choices;
				m_tssForm = tssForm;
				m_fWantOnlyWfiAnalysis = fWantOnlyWfiAnalysis;
			}
Ejemplo n.º 11
0
        public void NewGlossExistingLexEntryNewLexSense()
        {
            var cba0_0 = GetCba(0, 0, 0);

            m_sandbox.SwitchWord(cba0_0);
            ILexEntry lexEntry1_Entry;
            ILexSense lexEntry1_Sense1;

            SetupLexEntryAndSense("xxxa", "xxxa.existingsense1", out lexEntry1_Entry, out lexEntry1_Sense1);

            // mark the count of LexEntries
            int cEntriesOrig = Cache.LangProject.LexDbOA.Entries.Count();

            // add a new word gloss
            m_sandbox.SetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                      Cache.DefaultAnalWs, "0.0.xxxa");
            IWfiWordform wf = cba0_0.Analysis.Wordform;
            // set word pos, to first possibility (e.g. 'adjunct')
            int hvoSbWordPos = m_sandbox.SelectIndexInCombo(InterlinLineChoices.kflidWordPos, 0, 0);

            // confirm the analysis (making a real analysis and a LexSense)
            var       wag      = m_sandbox.ConfirmAnalysis();
            IWfiGloss wfiGloss = wag.Gloss;

            // make sure we didn't add entries to the Lexicon.
            int cEntriesAfter = Cache.LangProject.LexDbOA.Entries.Count();

            Assert.AreEqual(cEntriesOrig, cEntriesAfter);

            // confirm we have only one analysis and that it is monomorphemic
            IWfiAnalysis wfiAnalysis = wag.WfiAnalysis;

            Assert.AreEqual(wf, wag.Wordform, "Expected confirmed analysis to be owned by the original wordform.");
            Assert.AreEqual(1, wf.AnalysesOC.Count);
            Assert.AreEqual(1, wfiAnalysis.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis.MeaningsOC.Count);

            // make sure the strings of the wfi gloss matches the strings of the lex gloss.
            ValidateSenseWithAnalysis(m_sandbox.GetLexSenseForWord(), wfiGloss, hvoSbWordPos);
        }
        /// ------------------------------------------------------------------------------------
        /// <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);
            }));
        }
Ejemplo n.º 13
0
        private void SetUpGlosses(ISegment seg, params string[] glosses)
        {
            var servloc = Cache.ServiceLocator;
            IWfiAnalysisFactory analFactory  = servloc.GetInstance <IWfiAnalysisFactory>();
            IWfiGlossFactory    glossFactory = servloc.GetInstance <IWfiGlossFactory>();

            UndoableUnitOfWorkHelper.Do("Undo add glosses", "Redo add glosses", Cache.ActionHandlerAccessor,
                                        () =>
            {
                for (int i = 0; i < glosses.Length; i++)
                {
                    if (glosses[i] == null)
                    {
                        continue;
                    }
                    IWfiWordform wfiWordform = (IWfiWordform)seg.AnalysesRS[i];
                    IWfiAnalysis analysis    = analFactory.Create(wfiWordform, glossFactory);
                    IWfiGloss gloss          = analysis.MeaningsOC.First();
                    seg.AnalysesRS[i]        = gloss;
                    gloss.Form.SetAnalysisDefaultWritingSystem(glosses[i]);
                }
            });
        }
Ejemplo n.º 14
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Checks that the specified analysis of the given segment is a gloss for the given word.
 /// </summary>
 /// <param name="seg">The segment.</param>
 /// <param name="iForm">The index of the word (or punctuation) form.</param>
 /// <param name="word">The (vernacular) word.</param>
 /// <param name="iAnalysis">The index into the collection of analyses.</param>
 /// <param name="expectedFormsWithoutAnalyses">List of indices of wordforms which are
 /// not expected to have any analyses.</param>
 /// <param name="expectedWordforms">List of indices of analyses that are expected to be
 /// word forms, rather than glosses (these should correspond to whole words that did not
 /// survive the resegmentation)</param>
 /// ------------------------------------------------------------------------------------
 private static bool VerifyWfi(ISegment seg, int iForm, string word, int iAnalysis,
                               IEnumerable <int> expectedFormsWithoutAnalyses, IEnumerable <int> expectedWordforms)
 {
     if (expectedFormsWithoutAnalyses.Contains(iForm))
     {
         Assert.AreNotEqual(word, seg.AnalysesRS[iAnalysis].GetForm(seg.Cache.DefaultVernWs).Text,
                            "Did not expect to find an analysis for form " + iForm + " (" + word + ") at position " + iAnalysis +
                            " in the collection of analyses for this segment.");
         return(false);
     }
     if (expectedWordforms.Contains(iAnalysis))
     {
         IWfiWordform wordform = seg.AnalysesRS[iAnalysis] as IWfiWordform;
         Assert.IsNotNull(wordform, "Expected form " + iForm + " (" + word + ") to have an analysis, which is a wordform.");
         Assert.AreEqual(word, wordform.Form.VernacularDefaultWritingSystem.Text);
     }
     else
     {
         IWfiGloss gloss = seg.AnalysesRS[iAnalysis] as IWfiGloss;
         Assert.IsNotNull(gloss, "Expected form " + iForm + " (" + word + ") to have an analysis, which is a gloss.");
         Assert.AreEqual("G" + word + "g", gloss.Form.AnalysisDefaultWritingSystem.Text);
     }
     return(true);
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Removes the gloss with the specified language form the sense with the specified information
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void RemoveGloss(LexemeType type, string lexicalForm, int homograph,
                                string senseId, string language)
        {
            LexicalProviderManager.ResetLexicalProviderTimer();
            Logger.WriteEvent("Removing gloss from lexeme '" + lexicalForm + "' from an external application");

            NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
            {
                IMultiUnicode dbGlosses;
                Guid guid;
                if (senseId.StartsWith(kAnalysisPrefix))
                {
                    // The "sense" is actually an analysis for a wordform and the gloss
                    // we want to delete is a meaning for that analysis.
                    guid = new Guid(senseId.Substring(kAnalysisPrefix.Length));
                    IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance <IWfiAnalysisRepository>().GetObject(guid);
                    IWfiGloss dbGloss       = dbAnalysis.MeaningsOC.First();
                    dbGlosses = dbGloss.Form;
                }
                else
                {
                    guid = new Guid(senseId);
                    ILexSense dbSense = m_cache.ServiceLocator.GetInstance <ILexSenseRepository>().GetObject(guid);
                    dbGlosses         = dbSense.Gloss;
                }
                // Remove the gloss from the list of glosses for the sense
                int wsId = m_cache.WritingSystemFactory.GetWsFromStr(language);
                dbGlosses.set_String(wsId, (ITsString)null);

                // Delete the sense if there are no more glosses for it
                if (dbGlosses.StringCount == 0)
                {
                    RemoveSense(senseId, guid);
                }
            });
        }
Ejemplo n.º 16
0
		private void ValidateSenseWithAnalysis(ILexSense sense, IWfiGloss wfiGloss, int hvoSbWordPos, bool fMatchMainPossibility, IMoStemAllomorph allomorph)
		{
			IWfiAnalysis wfiAnalysis = wfiGloss.Owner as IWfiAnalysis;
			CompareTss(sense.Gloss.get_String(Cache.DefaultAnalWs),
				wfiGloss.Form.get_String(Cache.DefaultAnalWs));

			// make sure the morph is linked to the lexicon sense, msa, and part of speech.
			IWfiMorphBundle morphBundle = wfiAnalysis.MorphBundlesOS[0];
			Assert.AreEqual(sense, morphBundle.SenseRA);
			Assert.AreEqual(sense.MorphoSyntaxAnalysisRA, morphBundle.MsaRA);
			if (!fMatchMainPossibility)
			{
				// expect exact possibility
				Assert.AreEqual(hvoSbWordPos, (sense.MorphoSyntaxAnalysisRA as IMoStemMsa).PartOfSpeechRA.Hvo);
			}
			else
			{
				IPartOfSpeech posTarget = Cache.ServiceLocator.GetInstance<IPartOfSpeechRepository>().GetObject(hvoSbWordPos);
				Assert.AreEqual(posTarget.MainPossibility, (sense.MorphoSyntaxAnalysisRA as IMoStemMsa).PartOfSpeechRA.MainPossibility);
			}
			Assert.AreEqual(allomorph, morphBundle.MorphRA);
			Assert.AreEqual(hvoSbWordPos, wfiAnalysis.CategoryRA.Hvo);
		}
Ejemplo n.º 17
0
		// Generate a suitable string representation of a WfiGloss.
		// Todo: finish implementing (add the gloss!)
		static internal ITsString MakeGlossStringRep(IWfiGloss wg, FdoCache fdoCache, bool fUseStyleSheet)
		{
			ITsStrBldr tsb = TsStrBldrClass.Create();
			var wa = wg.Owner as IWfiAnalysis;

			var category = wa.CategoryRA;
			if (category != null)
			{
				ITsString tssPos = category.Abbreviation.get_String( fdoCache.DefaultAnalWs);
				tsb.Replace(0, 0, tssPos.Text,
					PartOfSpeechTextProperties(fdoCache,false, fUseStyleSheet));
			}
			else
			{
				tsb.Replace(0, 0, ksMissingString,
					PartOfSpeechTextProperties(fdoCache,false, fUseStyleSheet));
			}
			tsb.Replace(tsb.Length, tsb.Length, " ", null);
			tsb.Replace(tsb.Length, tsb.Length,
						wg.Form.get_String(fdoCache.DefaultAnalWs).Text,
				GlossTextProperties(fdoCache, false, fUseStyleSheet));

			//indent
			tsb.Replace(0,0, "    ", null);
			return tsb.GetString();
		}
Ejemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="word"></param>
        /// <param name="analysis">the new analysis Gloss. If multiple glosses, returns the last one created.</param>
        private static void UpgradeToWordGloss(Word word, ref IAnalysis analysis)
        {
            FdoCache cache        = analysis.Cache;
            var      tsStrFactory = cache.ServiceLocator.GetInstance <ITsStrFactory>();
            var      wsFact       = cache.WritingSystemFactory;

            if (s_importOptions.AnalysesLevel == ImportAnalysesLevel.WordGloss)
            {
                // test for adding multiple glosses in the same language. If so, create separate analyses with separate glosses.
                bool fHasMultipleGlossesInSameLanguage = false;
                var  dictMapLangToGloss = new Dictionary <string, string>();
                foreach (var wordGlossItem in word.Items.Select(i => i).Where(i => i.type == "gls"))
                {
                    string gloss;
                    if (!dictMapLangToGloss.TryGetValue(wordGlossItem.lang, out gloss))
                    {
                        dictMapLangToGloss.Add(wordGlossItem.lang, wordGlossItem.Value);
                        continue;
                    }
                    if (wordGlossItem.Value == gloss)
                    {
                        continue;
                    }
                    fHasMultipleGlossesInSameLanguage = true;
                    break;
                }

                AnalysisTree analysisTree = null;
                foreach (var wordGlossItem in word.Items.Select(i => i).Where(i => i.type == "gls"))
                {
                    if (wordGlossItem == null)
                    {
                        continue;
                    }
                    if (wordGlossItem.analysisStatusSpecified &&
                        wordGlossItem.analysisStatus != analysisStatusTypes.humanApproved)
                    {
                        continue;
                    }
                    // first make sure that an existing gloss does not already exist. (i.e. don't add duplicate glosses)
                    int       wsNewGloss  = GetWsEngine(wsFact, wordGlossItem.lang).Handle;
                    ITsString newGlossTss = tsStrFactory.MakeString(wordGlossItem.Value,
                                                                    wsNewGloss);
                    var       wfiWord       = analysis.Wordform;
                    bool      hasGlosses    = wfiWord.AnalysesOC.Any(wfia => wfia.MeaningsOC.Any());
                    IWfiGloss matchingGloss = null;
                    if (hasGlosses)
                    {
                        foreach (var wfa in wfiWord.AnalysesOC)
                        {
                            matchingGloss = wfa.MeaningsOC.FirstOrDefault(wfg => wfg.Form.get_String(wsNewGloss).Equals(newGlossTss));
                            if (matchingGloss != null)
                            {
                                break;
                            }
                        }
                    }

                    if (matchingGloss != null)
                    {
                        analysis = matchingGloss;
                    }
                    else
                    {
                        // TODO: merge with analysis having same morpheme breakdown (or at least the same stem)

                        if (analysisTree == null || dictMapLangToGloss.Count == 1 || fHasMultipleGlossesInSameLanguage)
                        {
                            // create a new WfiAnalysis to store a new gloss
                            analysisTree = WordAnalysisOrGlossServices.CreateNewAnalysisTreeGloss(wfiWord);
                        }
                        else
                        {
                            // reuse the same analysisTree for setting a gloss alternative
                        }
                        analysisTree.Gloss.Form.set_String(wsNewGloss, wordGlossItem.Value);
                        // Make sure this analysis is marked as user-approved (green check mark)
                        cache.LangProject.DefaultUserAgent.SetEvaluation(analysisTree.WfiAnalysis, Opinions.approves);
                        // Create a morpheme form that matches the wordform.
                        var morphemeBundle = cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>().Create();
                        var wordItem       = word.Items.Select(i => i).Where(i => i.type == "txt").First();
                        int wsWord         = GetWsEngine(wsFact, wordItem.lang).Handle;
                        analysisTree.WfiAnalysis.MorphBundlesOS.Add(morphemeBundle);
                        morphemeBundle.Form.set_String(wsWord, wordItem.Value);

                        analysis = analysisTree.Gloss;
                    }
                }
            }
        }
Ejemplo n.º 19
0
		private IWfiAnalysis MakeCompleteAnalysis(IWfiWordform wf, out IPartOfSpeech pos, out ICmAgent human, out IWfiGloss wg)
		{
			var wa = MakeAnalysis(wf);
			var bundle = MakeCompleteBundle(wa);
			wg = MakeCompleteGloss(wa);
			pos = MakePartOfSpeech();
			wa.CategoryRA = pos;
			human = Cache.LangProject.DefaultUserAgent;
			wa.SetAgentOpinion(human, Opinions.approves);
			Assert.IsTrue(wa.IsComplete);
			return wa;
		}
Ejemplo n.º 20
0
			public WfiGlossLexiconSense(FdoLexicon lexicon, LexemeKey lexemeKey, IWfiGloss gloss)
			{
				m_lexicon = lexicon;
				m_lexemeKey = lexemeKey;
				m_gloss = gloss;
			}
Ejemplo n.º 21
0
 private void ValidateSenseWithAnalysis(ILexSense sense, IWfiGloss wfiGloss, int hvoSbWordPos)
 {
     ValidateSenseWithAnalysis(sense, wfiGloss, hvoSbWordPos, false, sense.Entry.LexemeFormOA as IMoStemAllomorph);
 }
Ejemplo n.º 22
0
 public WfiGlossLexiconSense(FdoLexicon lexicon, LexemeKey lexemeKey, IWfiGloss gloss)
 {
     m_lexicon   = lexicon;
     m_lexemeKey = lexemeKey;
     m_gloss     = gloss;
 }
			private IAnalysis FinishItOff()
			{
				FdoCache fdoCache = m_caches.MainCache;
				var wfRepository = fdoCache.ServiceLocator.GetInstance<IWfiWordformRepository>();
				if (m_wf == null)
				{
					IWfiWordform wf;
					// first see if we can find a matching form
					if (wfRepository.TryGetObject(m_tssForm, false, out wf))
						m_wf = wf;
					else
					{
						// The user selected a case form that did not previously have a WfiWordform.
						// Since he is confirming this analysis, we now need to create one.
						// Note: if in context of the wordforms DummyRecordList, the RecordList is
						// smart enough to handle inserting one object without having to Reload the whole list.
						m_wf = fdoCache.ServiceLocator.GetInstance<IWfiWordformFactory>().Create(m_tssForm);
					}
				}
				// If sandbox contains only an empty morpheme string, don't consider this to be a true analysis.
				// Assume that the user was not finished with his analysis (cf. LT-1621).
				if (m_sandbox.IsAnalysisEmpty)
				{
					return m_wf;
				}

				// Update the wordform with any additional wss.
				List<int> wordformWss = m_choices.OtherWritingSystemsForFlid(InterlinLineChoices.kflidWord, 0);
				// we need another way to detect the static ws for kflidWord.
				foreach (int wsId in wordformWss)
				{
					UpdateMlaIfDifferent(m_hvoSbWord, ktagSbWordForm, wsId, m_wf.Hvo, WfiWordformTags.kflidForm);
				}

				// (LT-7807 later refined by FWR-3536)
				// if we're in a special mode for adding monomorphemic words to lexicon and the user's proposed analysis is monomorphemic,
				// if there is an existing possible analysis that matches on form, gloss, and POS, use it.
				// else if there is an existing possible analysis that matches on form and gloss and has no POS,
				//	update the POS and use it.
				// else if the occurrence is currently analyzed as a particular sense and there are no other occurrences
				//  of that sense, update the gloss and/or POS of the sense to match what we want (and use it)
				// else if there is a matching entry with the right form, add a suitable sense to use
				// else make a new entry and sense to use.
				if (m_sandbox.ShouldAddWordGlossToLexicon)
				{
					IhMorphEntry.MorphItem matchingMorphItem = new IhMissingEntry.MorphItem(0, null);
					ITsString tssWf = m_wf.Form.get_String(m_sandbox.RawWordformWs);
					// go through the combo options for lex entries / senses to see if we can find any existing matches.
					using (IhMorphEntry handler = InterlinComboHandler.MakeCombo(m_helpTopicProvider, ktagWordGlossIcon, m_sandbox, 0) as SandboxBase.IhMorphEntry)
					{
						List<IhMorphEntry.MorphItem> morphItems = handler.MorphItems;
						// see if we can use an existing Sense, if it matches the word gloss and word MSA
						foreach (IhMorphEntry.MorphItem morphItem in morphItems)
						{
							// skip lex senses that do not match word gloss and pos in the Sandbox
							if (!SbWordGlossMatchesSenseGloss(morphItem))
								continue;
							if (!SbWordPosMatchesSenseMsaPos(morphItem))
								continue;
							// found a LexSense matching our Word Gloss and MSA POS
							matchingMorphItem = morphItem;
							break;
						}
						if (matchingMorphItem.m_hvoSense == 0)
						{
							// Next see if we can find an existing analysis where the gloss matches and POS is null.
							foreach (IhMorphEntry.MorphItem morphItem in morphItems)
							{
								// skip lex senses that do not match word gloss and pos in the Sandbox
								if (!SbWordGlossMatchesSenseGloss(morphItem))
									continue;
								// found a LexSense matching our Word Gloss and that has no POS.
								var pos = m_caches.RealObject(m_sda.get_ObjectProp(m_hvoSbWord, ktagSbWordPos)) as IPartOfSpeech;
								var sense = m_caches.MainCache.ServiceLocator.GetObject(morphItem.m_hvoSense) as ILexSense;
								if (sense == null)
									continue; // don't think this can happen but play safe.
								var msa = sense.MorphoSyntaxAnalysisRA as IMoStemMsa;
								if (msa == null || msa.PartOfSpeechRA != null)
									continue; // for this case we can only use one that doesn't already have a POS.
								msa.PartOfSpeechRA = pos; // adjust it
								if (m_oldAnalysis.WfiAnalysis != null) // always?
								{
									if (m_oldAnalysis.WfiAnalysis.CategoryRA != pos)
										m_oldAnalysis.WfiAnalysis.CategoryRA = pos;
								}
								matchingMorphItem = morphItem; // and use it.
								break;
							}
						}
						if (matchingMorphItem.m_hvoSense == 0 && m_oldAnalysis != null && m_oldAnalysis.WfiAnalysis != null)
						{
							// still don't have one we can use; see whether it is legitimate to modify the current
							// analysis.
							var oldAnalysis = m_oldAnalysis.WfiAnalysis;
							if (oldAnalysis.MorphBundlesOS.Count == 1
								&& oldAnalysis.MorphBundlesOS[0].SenseRA != null
								&& oldAnalysis.MorphBundlesOS[0].SenseRA.MorphoSyntaxAnalysisRA is IMoStemMsa
								&& OnlyUsedThisOnce(oldAnalysis)
								&& OnlyUsedThisOnce(oldAnalysis.MorphBundlesOS[0].SenseRA))
							{
								// We're allowed to change the existing sense and analysis! A side effect of updating the sense
								// is updating the MSA of the morph bundle of the oldAnalysis.
								var pos = m_caches.RealObject(m_sda.get_ObjectProp(m_hvoSbWord, ktagSbWordPos)) as IPartOfSpeech;
								UpdateSense(oldAnalysis.MorphBundlesOS[0].SenseRA, pos);
								if (oldAnalysis.CategoryRA != pos)
									oldAnalysis.CategoryRA = pos;
								if (m_oldAnalysis.Gloss != null)
								{
									// if the old analysis is a gloss, update it also.
									CopyGlossesToWfiGloss(m_oldAnalysis.Gloss);
									return m_oldAnalysis.Gloss;
								}
								// Don't have an old gloss, create one.
								var newGloss = oldAnalysis.Services.GetInstance<IWfiGlossFactory>().Create();
								oldAnalysis.MeaningsOC.Add(newGloss);
								CopyGlossesToWfiGloss(newGloss);
								return newGloss;
							}
						}
						// If we get here we could not use an existing analysis with any safe modification.
						// if we couldn't use an existing sense but we match a LexEntry form,
						// add a new sense to an existing entry.
						ILexEntry bestEntry = null;
						if (morphItems.Count > 0 && matchingMorphItem.m_hvoSense == 0)
						{
							// Tried using FindBestLexEntryAmongstHomographs() but it matches
							// only CitationForm which MorphItems doesn't know anything about,
							// and doesn't match against Allomorphs which MorphItems do track
							// so this could lead to a crash (LT-9430).
							//
							// Solution: if the user specified a category, see if we can find an entry
							// with a sense using that same category
							// otherwise just add the new sense to the first entry in MorphItems.
							IhMorphEntry.MorphItem bestMorphItem = morphItems[0];
							foreach (IhMorphEntry.MorphItem morphItem in morphItems)
							{
								// skip items that do not match word main pos in the Sandbox
								if (!SbWordMainPosMatchesSenseMsaMainPos(morphItem))
									continue;
								bestMorphItem = morphItem;
								break;
							}

							bestEntry = bestMorphItem.GetPrimaryOrOwningEntry(m_caches.MainCache);
							// lookup this entry;
							matchingMorphItem = FindLexEntryMorphItem(morphItems, bestEntry);
						}

						if (matchingMorphItem.m_hvoMorph == 0)
						{
							// we didn't find a matching lex entry, so create a new entry
							ILexEntry newEntry;
							ILexSense newSense;
							IMoForm allomorph;
							handler.CreateNewEntry(true, out newEntry, out allomorph, out newSense);
						}
						else if (bestEntry != null)
						{
							// we found matching lex entry, so create a new sense for it
							var senseFactory = fdoCache.ServiceLocator.GetInstance<ILexSenseFactory>();
							ILexSense newSense = senseFactory.Create(bestEntry, new SandboxGenericMSA(), "");
							// copy over any word glosses we're showing.
							CopyGlossesToSense(newSense);
							// copy over the Word POS
							var pos = m_caches.RealObject(m_sda.get_ObjectProp(m_hvoSbWord, ktagSbWordPos)) as IPartOfSpeech;
							(newSense.MorphoSyntaxAnalysisRA as IMoStemMsa).PartOfSpeechRA = pos;
							var morph = fdoCache.ServiceLocator.GetInstance<IMoFormRepository>().GetObject(matchingMorphItem.m_hvoMorph);
							handler.UpdateMorphEntry(morph, bestEntry, newSense);
						}
						else
						{
							// we found a matching lex entry and sense, so select it.
							int iMorphItem = morphItems.IndexOf(matchingMorphItem);
							handler.HandleSelect(iMorphItem);
						}
					}
				}

				BuildMorphLists(); // Used later on in the code.
				m_hvoCategoryReal = m_caches.RealHvo(m_sda.get_ObjectProp(m_hvoSbWord, ktagSbWordPos));

				// We may need to create a new WfiAnalysis based on whether we have any sandbox gloss content.
				bool fNeedGloss = false;
				bool fWordGlossLineIsShowing = false; // Set to 'true' if the wrod gloss line is included in the m_choices fields.
				foreach (InterlinLineSpec ilc in m_choices)
				{
					if (ilc.Flid == InterlinLineChoices.kflidWordGloss)
					{
						fWordGlossLineIsShowing = true;
						break;
					}
				}
				if (fWordGlossLineIsShowing)
				{
					// flag that we need to create wfi gloss information if any configured word gloss lines have content.
					foreach (int wsId in m_choices.WritingSystemsForFlid(InterlinLineChoices.kflidWordGloss))
					{
						if (m_sda.get_MultiStringAlt(m_hvoSbWord, ktagSbWordGloss, wsId).Length > 0)
						{
							fNeedGloss = true;
							break;
						}
					}
				}

				// We decided to take this logic out (see LT-1653) because it is annoying when
				// deliberately removing a wrong morpheme breakdown guess.
				//				// We need to create (or find an existing) WfiAnalysis if we have any morphemes,
				//				// a word gloss, or a word category.
				//				bool fNeedAnalysis = fNeedGloss || m_cmorphs > 1 || m_hvoCategoryReal != 0;
				//
				//				// If we have exactly one morpheme, see if it has some non-trivial information
				//				// associated. If not, don't make an analysis.
				//				if (!fNeedGloss && m_cmorphs == 1 && m_hvoCategoryReal == 0 && m_analysisMsas[0] == 0
				//					&& m_analysisSenses[0] == 0 && m_analysisMorphs[0] == 0)
				//				{
				//					fNeedAnalysis = false;
				//				}
				//				// If there's no information at all, the 'analysis' is just the original wordform.
				//				if (!fNeedAnalysis)
				//					return m_hvoWordform;
				// OK, we have some information that corresponds to an analysis. Find or create
				// an analysis that matches.
				int wsVern = m_sandbox.RawWordformWs;
				m_wa = FindMatchingAnalysis(true);
				bool fFoundAnalysis = m_wa != null;
				if (!fFoundAnalysis)
				{
					// Clear the checksum on the wordform. This allows the parser filer to re-evaluate it and
					// delete the old analysis if it is just a simpler, parser-generated form of the one we're now making.
					m_wf.Checksum = 0;
					// Check whether there's a parser-generated analysis that the current settings
					// subsume.  If so, reuse that analysis by filling in the missing data (word gloss,
					// word category, and senses).
					// Another option is that there is an existing 'analysis' that is a trivial one,
					// created by word-only glossing. We can re-use that, filling in the other details
					// now supplied.
					var partialWa = FindMatchingAnalysis(false);
					bool fNewAnal = partialWa == null;
					if (fNewAnal)
					{
						foreach (var ana in m_wf.AnalysesOC)
						{
							if (m_oldAnalysis != null &&
								ana == m_oldAnalysis.WfiAnalysis &&
								OnlyUsedThisOnce(ana) &&
								IsAnalysisHumanApproved(m_caches.MainCache, ana))
							{
								ObsoleteAnalysis = ana;
								break;
							}
						}
						// Create one.
						var waFactory = fdoCache.ServiceLocator.GetInstance<IWfiAnalysisFactory>();
						var waNew = waFactory.Create();
						m_wf.AnalysesOC.Add(waNew);
						m_wa = waNew;
					}
					else
					{
						m_wa = partialWa;
						// For setting word glosses, we should treat this as a 'found' not new analysis
						// if it has any glosses, so we will search for and find any existing ones that match.
						fFoundAnalysis = m_wa.MeaningsOC.Count > 0;
					}
					IPartOfSpeech pos = null;
					if (m_hvoCategoryReal != 0)
						pos = fdoCache.ServiceLocator.GetInstance<IPartOfSpeechRepository>().GetObject(m_hvoCategoryReal);
					m_wa.CategoryRA = pos;
					var mbFactory = fdoCache.ServiceLocator.GetInstance<IWfiMorphBundleFactory>();
					var msaRepository = fdoCache.ServiceLocator.GetInstance<IMoMorphSynAnalysisRepository>();
					var mfRepository = fdoCache.ServiceLocator.GetInstance<IMoFormRepository>();
					var senseRepository = fdoCache.ServiceLocator.GetInstance<ILexSenseRepository>();
					var inflTypeRepository = fdoCache.ServiceLocator.GetInstance<ILexEntryInflTypeRepository>();
					for (int imorph = 0; imorph < m_cmorphs; imorph++)
					{
						IWfiMorphBundle mb;
						if (imorph >= m_wa.MorphBundlesOS.Count)
						{
							mb = mbFactory.Create();
							m_wa.MorphBundlesOS.Insert(imorph, mb);
						}
						else
						{
							mb = m_wa.MorphBundlesOS[imorph];
						}
						// An undo operation can leave stale information in the sandbox.  If
						// that happens, the stored database id values are invalid.  Set them
						// all to zero if the morph is invalid.  (See LT-3824 for a crash
						// scenario.)  This fix prevents a crash, but doesn't do anything for
						// restoring the original values before the operation that is undone.
						if (m_analysisMorphs[imorph] != 0 &&
							!m_sdaMain.get_IsValidObject(m_analysisMorphs[imorph]))
						{
							m_analysisMorphs[imorph] = 0;
							m_analysisMsas[imorph] = 0;
							m_analysisSenses[imorph] = 0;
						}
						// Set the Morph of the bundle if we know a real one; otherwise, just set its Form
						if (m_analysisMorphs[imorph] == 0)
						{
							int hvoSbMorph = m_sda.get_VecItem(m_hvoSbWord, ktagSbWordMorphs, imorph);
							mb.Form.set_String(wsVern, m_sandbox.GetFullMorphForm(hvoSbMorph));
							// Copy any other wss over, without any funny business about morpheme breaks
							// Per LT-14891, we don't allow editing of the other morph lines, so no need to set them.
							//foreach (int ws in m_choices.OtherWritingSystemsForFlid(InterlinLineChoices.kflidMorphemes, 0))
							//{
							//    mb.Form.set_String(ws,
							//        m_caches.DataAccess.get_MultiStringAlt(hvoSbMorph, ktagSbNamedObjName, ws));
							//}
						}
						else
						{
							mb.MorphRA = mfRepository.GetObject(m_analysisMorphs[imorph]);
						}
						// Set the MSA if we have one. Note that it is (pathologically) possible that the user has done
						// something in another window to destroy the MSA we remember, so don't try to set it if so.
						if (m_analysisMsas[imorph] != 0 && m_sdaMain.get_IsValidObject(m_analysisMsas[imorph]))
						{
							mb.MsaRA = msaRepository.GetObject(m_analysisMsas[imorph]);
						}
						// Likewise the Sense
						if (m_analysisSenses[imorph] != 0)
						{
							mb.SenseRA = senseRepository.GetObject(m_analysisSenses[imorph]);
							// set the InflType if we have one.
							var hvoSbInflType = GetRealHvoFromSbWmbInflType(imorph);
							mb.InflTypeRA = hvoSbInflType != 0 ? inflTypeRepository.GetObject(hvoSbInflType) : null;
						}

					}
				}
				else if (fWordGlossLineIsShowing) // If the line is not showing at all, don't bother.
				{
					// (LT-1428) Since we're using an existing WfiAnalysis,
					// We will find or create a new WfiGloss (even for blank lines)
					// if WfiAnalysis already has WfiGlosses
					//	or m_hvoWordGloss is nonzero
					//	or Sandbox has gloss content.
					bool fSbGlossContent = fNeedGloss;
					int cGloss = m_wa.MeaningsOC.Count;
					fNeedGloss = cGloss > 0 || m_wg != null || fSbGlossContent;
				}

				if (m_wa != null)
					EnsureCorrectMorphForms();

				if (!fNeedGloss || m_fWantOnlyWfiAnalysis)
				{
					return m_wa;
				}
				if (m_wg != null)
				{
					// We may consider editing it instead of making a new one.
					// But ONLY if it belongs to the right analysis!!
					if (m_wg.Owner != m_wa)
						m_wg = null;
				}
				/* These are the types of things we are trying to accomplish here.
				Problem 1 -- Correcting a spelling mistake.
					Gloss1: mn <-
				User corrects spelling to men
				Desired:
					Gloss1: men <-
				Bad result:
					Gloss1: mn
					Gloss2: men <-

				Problem 2 -- Switching to a different gloss via typing.
					Gloss1: he <-
					Gloss2: she
				User types in she rather than using dropdown box to select it
				Desired:
					Gloss1: he
					Gloss2: she <-
				Bad result:
					Gloss1: she <-
					Gloss2: she

				Problem 2A
							Gloss1: he <-
				User types in she without first using dropdown box to select "add new gloss"
				Desired:
							Gloss1: he (still used for N other occurrences)
							Gloss2: she <-
				Bad (at least dubious) result:
							Gloss1: she <- (used for this and all other occurrences)

				Problem 3 -- Adding a missing alternative when there are not duplications.
					Gloss1: en=green <-
				User adds the French equivalent
				Desired:
					Gloss1: en=green, fr=vert <-
				Bad result:
					Gloss1: en=green
					Gloss2: en=green, fr=vert <-

				The logic used to be to look for glosses with all alternatives matching or else it
				creates a new one. So 2 would actually work, but 1 and 3 were both bad.

				New logic: keep track of the starting WfiAnalysis and WfiGloss.
				Assuming we haven't changed to a new WfiAnalysis based on other changes, if there
				is a WfiGloss that matches any of the existing alternatives, we switch to that.
				Otherwise we set the alternatives of the starting WfiGloss to whatever the user
				entered. This logic would work for all three examples above, but has problems
				with the following.

				Problem -- add a missing gloss where there are identical glosses in another ws.
					Gloss1: en=them <-
				User adds Spanish gloss
				Desired:
					Gloss1: en=them, es=ellas <-
				This works ok with above logic. But now in another location the user needs to
				use the masculine them in Spanish, so changes ellas to ellos
				Desired:
					Gloss1: en=them, es=ellas
					Gloss2: en=them, es=ellos <-
				Bad result:
					Gloss1: en=them, es=ellos <-

				Eventually, we'll probably want to display a dialog box to ask users what they really want.
				"There are 15 places where "XXX" analyzed as 3pp is currently glossed
				en->"them".  Would you like to
				<radio button, selected> change them all to en->"them" sp->"ellas"?
				<radio button> leave the others glossed en->"them" and let just this one
				be en->"them" sp->"ellas"?
				<radio button> see a concordance and choose which ones to change to
				en->"them" sp->"ellas"?
				*/

				// (LT-1428, LT-12472)
				// -----------------------------
				// When the user edits a gloss,
				// (1) If there is an existing gloss matching what they just changed it to
				//		then switch this instance to point to that one.
				// (2) Else if the gloss is used only in this instance, or if it matches on all WSs that are not blank in the gloss,
				//		then apply the edits directly to the gloss.
				// (3) Else, create a new gloss.
				//-------------------------------
				var gloss = fFoundAnalysis ? FindMatchingGloss() : null;

				if (gloss == null && m_sandbox.WordGlossReferenceCount == 1)
				{
					gloss = m_wg; // update the existing gloss.
				}

				if (gloss == null)
				{
					// Create one.
					var wgFactory = fdoCache.ServiceLocator.GetInstance<IWfiGlossFactory>();
					gloss = wgFactory.Create();
					m_wa.MeaningsOC.Add(gloss);
				}
				foreach (int wsId in m_choices.WritingSystemsForFlid(InterlinLineChoices.kflidWordGloss))
				{
					ITsString tssGloss = m_sda.get_MultiStringAlt(m_hvoSbWord, ktagSbWordGloss, wsId);
					if (!tssGloss.Equals(gloss.Form.get_String(wsId)))
					{
						gloss.Form.set_String(wsId, tssGloss);
					}
				}
				return gloss;
			}
Ejemplo n.º 24
0
		private void ValidateSenseWithAnalysis(ILexSense sense, IWfiGloss wfiGloss, int hvoSbWordPos)
		{
			ValidateSenseWithAnalysis(sense, wfiGloss, hvoSbWordPos, false, sense.Entry.LexemeFormOA as IMoStemAllomorph);
		}
Ejemplo n.º 25
0
        public void PickLexGlossUsingExistingAnalysis()
        {
            var cba0_0 = GetNewAnalysisOccurence(m_text1, 0, 0, 0);

            m_sandbox.SwitchWord(cba0_0);
            ILexEntry    lexEntry1_Entry;
            ILexSense    lexEntry1_Sense1;
            ILexEntry    lexEntry2_Entry;
            ILexSense    lexEntry2_Sense1;
            IWfiWordform wf;

            SetupLexEntryAndSense("xxxa", "0.0.xxxa", out lexEntry1_Entry, out lexEntry1_Sense1);
            SetupLexEntryAndSense("xxxa", "xxxa.AlternativeGloss", out lexEntry2_Entry, out lexEntry2_Sense1);
            // setup an existing analysis and gloss to match existing entry
            var morphBundle1 = SetupMorphBundleForEntry(cba0_0, "0.0.xxxa", lexEntry1_Entry, lexEntry1_Sense1, out wf);
            var morphBundle2 = SetupMorphBundleForEntry(cba0_0, "xxxa.AlternativeGloss", lexEntry2_Entry, lexEntry2_Sense1, out wf);

            // load sandbox with a guess.
            m_sandbox.SwitchWord(cba0_0);
#if WANTTESTPORT
            Assert.IsTrue(m_sandbox.UsingGuess);
#endif

            // mark the count of LexEntries
            int cEntriesOrig = Cache.LangProject.LexDbOA.Entries.Count();

            // first select 'unknown' to clear the guess for the word gloss/pos
            m_sandbox.SelectItemInCombo(InterlinLineChoices.kflidWordGloss, 0, "Unknown");
            // confirm Sandbox is in the expected state.
            ITsString tssWordGlossInSandbox = m_sandbox.GetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                                        Cache.DefaultAnalWs);
            Assert.AreEqual(null, tssWordGlossInSandbox.Text);
            int hvoPos = m_sandbox.GetRealHvoInSandbox(InterlinLineChoices.kflidWordPos, 0);
            Assert.AreEqual(0, hvoPos);

            // simulate selecting a lex gloss '0.0.xxxa'
            m_sandbox.SelectItemInCombo(InterlinLineChoices.kflidWordGloss, 0, lexEntry1_Sense1.Hvo);
            // confirm Sandbox is in the expected state.
            tssWordGlossInSandbox = m_sandbox.GetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                              Cache.DefaultAnalWs);
            Assert.AreEqual("0.0.xxxa", tssWordGlossInSandbox.Text);
            int hvoPos2 = m_sandbox.GetRealHvoInSandbox(InterlinLineChoices.kflidWordPos, 0);
            Assert.AreNotEqual(0, hvoPos2);

            // simulate selecting the other lex gloss 'xxxa.AlternativeGloss'
            m_sandbox.SelectItemInCombo(InterlinLineChoices.kflidWordGloss, 0, lexEntry2_Sense1.Hvo);
            // confirm Sandbox is in the expected state.
            tssWordGlossInSandbox = m_sandbox.GetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                              Cache.DefaultAnalWs);
            Assert.AreEqual("xxxa.AlternativeGloss", tssWordGlossInSandbox.Text);
            int hvoPos3 = m_sandbox.GetRealHvoInSandbox(InterlinLineChoices.kflidWordPos, 0);
            Assert.AreNotEqual(0, hvoPos3);

            // Next simulate picking an existing word gloss/pos by typing/selecting
            tssWordGlossInSandbox = m_sandbox.SetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                              Cache.DefaultAnalWs, "0.0.xxxa");
            // set word pos, to first possibility (e.g. 'adjunct')
            int hvoSbWordPos = m_sandbox.SelectIndexInCombo(InterlinLineChoices.kflidWordPos, 0, 0);

            // confirm the analysis (using existing analysis and a LexSense)
            var       wag      = m_sandbox.ConfirmAnalysis();
            IWfiGloss wfiGloss = wag.Gloss;

            // make sure we didn't add entries or senses to the Lexicon.
            int cEntriesAfter = Cache.LangProject.LexDbOA.Entries.Count();
            Assert.AreEqual(cEntriesOrig, cEntriesAfter);
            Assert.AreEqual(1, lexEntry1_Entry.SensesOS.Count);

            // make sure the sense matches the existing one.
            ILexSense sense = m_sandbox.GetLexSenseForWord();
            Assert.AreEqual(lexEntry1_Sense1.Hvo, sense.Hvo);
            // make sure the strings of the wfi gloss matches the strings of the lex gloss.
            ValidateSenseWithAnalysis(sense, wfiGloss, hvoSbWordPos);

            // confirm we have not created a new analysis and that it is monomorphemic
            IWfiAnalysis wfiAnalysis = wag.WfiAnalysis;
            Assert.AreEqual(wf, wag.Wordform, "Expected confirmed analysis to be owned by the original wordform.");
            Assert.AreEqual(hvoSbWordPos, wfiAnalysis.CategoryRA.Hvo);
            Assert.AreEqual(2, wf.AnalysesOC.Count);
            Assert.AreEqual(1, wfiAnalysis.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis.MeaningsOC.Count);
            IWfiAnalysis wfiAnalysis2 = (morphBundle2 as IWfiMorphBundle).Owner as IWfiAnalysis;
            Assert.AreEqual(1, wfiAnalysis2.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis2.MeaningsOC.Count);

            // make sure the morph is linked to our lexicon sense, msa, and part of speech.
            IWfiMorphBundle wfiMorphBundle = wfiAnalysis.MorphBundlesOS[0];
            Assert.AreEqual(morphBundle1.Hvo, wfiMorphBundle.Hvo);
        }
Ejemplo n.º 26
0
        public void NewGlossExistingLexEntryAllomorphNewLexSense()
        {
            var cba0_0 = GetNewAnalysisOccurence(m_text1, 0, 0, 0);

            m_sandbox.SwitchWord(cba0_0);
            string    formLexEntry     = "xxxab";
            ITsString tssLexEntryForm  = TsStringUtils.MakeString(formLexEntry, Cache.DefaultVernWs);
            string    formAllomorph    = "xxxa";
            ITsString tssAllomorphForm = TsStringUtils.MakeString(formAllomorph, Cache.DefaultVernWs);

            // first create an entry with a matching allomorph that doesn't match 'verb' POS we will be selecting in the sandbox
            ILexEntry lexEntry_NounPos;
            ILexSense lexSense_NounPos;

            SetupLexEntryAndSense("xxxab", "0.0.xxxab_NounPos", "noun", out lexEntry_NounPos, out lexSense_NounPos);
            var stemFactory = Cache.ServiceLocator.GetInstance <IMoStemAllomorphFactory>();
            var allomorph0  = stemFactory.Create();

            lexEntry_NounPos.AlternateFormsOS.Add(allomorph0);
            allomorph0.Form.set_String(TsStringUtils.GetWsAtOffset(tssAllomorphForm, 0), tssAllomorphForm);

            // now create the entry we want to match, that has a 'verb' POS.
            ILexEntry lexEntry1_Entry;
            ILexSense lexEntry1_Sense1;

            SetupLexEntryAndSense("xxxab", "0.0.xxxab_VerbPos", "verb", out lexEntry1_Entry, out lexEntry1_Sense1);
            IMoStemAllomorph allomorph = stemFactory.Create();

            lexEntry1_Entry.AlternateFormsOS.Add(allomorph);
            allomorph.MorphTypeRA = lexEntry1_Entry.LexemeFormOA.MorphTypeRA;
            allomorph.Form.set_String(TsStringUtils.GetWsAtOffset(tssAllomorphForm, 0), tssAllomorphForm);
            // mark the count of LexEntries
            int cEntriesOrig = Cache.LangProject.LexDbOA.Entries.Count();

            // add a new word gloss
            ITsString tssWordGlossInSandbox = m_sandbox.SetTssInSandbox(InterlinLineChoices.kflidWordGloss,
                                                                        Cache.DefaultAnalWs, "0.0.xxxa");
            IWfiWordform wf = cba0_0.Analysis.Wordform;
            // set word pos to verb
            int hvoSbWordPos = m_sandbox.GetComboItemHvo(InterlinLineChoices.kflidWordPos, 0, "transitive verb");

            m_sandbox.SelectItemInCombo(InterlinLineChoices.kflidWordPos, 0, hvoSbWordPos);

            // confirm the analysis (making a real analysis and a LexSense)
            var       wag      = m_sandbox.ConfirmAnalysis();
            IWfiGloss wfiGloss = wag.Gloss;

            // make sure we didn't add entries to the Lexicon.
            int cEntriesAfter = Cache.LangProject.LexDbOA.Entries.Count();

            Assert.AreEqual(cEntriesOrig, cEntriesAfter);

            // confirm we have only one analysis and that it is monomorphemic
            IWfiAnalysis wfiAnalysis = wag.WfiAnalysis;

            Assert.AreEqual(wf, wag.Wordform, "Expected confirmed analysis to be owned by the original wordform.");
            Assert.AreEqual(1, wf.AnalysesOC.Count);
            Assert.AreEqual(1, wfiAnalysis.MorphBundlesOS.Count);
            Assert.AreEqual(1, wfiAnalysis.MeaningsOC.Count);

            // make sure the strings of the wfi gloss matches the strings of the lex gloss.
            ValidateSenseWithAnalysis(m_sandbox.GetLexSenseForWord(), wfiGloss, hvoSbWordPos, true, allomorph);
        }
			private void CopyGlossesToWfiGloss(IWfiGloss gloss)
			{
				foreach (int wsId in m_choices.WritingSystemsForFlid(InterlinLineChoices.kflidWordGloss))
				{
					UpdateMlaIfDifferent(m_hvoSbWord, ktagSbWordGloss, wsId, gloss.Hvo, WfiGlossTags.kflidForm);
				}
			}
Ejemplo n.º 28
0
 private static bool DuplicateGlosses(IWfiGloss wg1, IWfiGloss wg2)
 {
     return
         (wg1.Form.AvailableWritingSystemIds.Union(wg2.Form.AvailableWritingSystemIds)
          .All(ws => wg1.Form.get_String(ws).Equals(wg2.Form.get_String(ws))));
 }
Ejemplo n.º 29
0
		/// <summary>
		/// Obtain the HVO of the most desirable default annotation to use for a particular
		/// wordform.
		/// </summary>
		private void GetDefaults(IWfiWordform wordform, out IWfiAnalysis analysis, out IWfiGloss gloss, bool fAdjustCase)
		{
			analysis = null; // default
			gloss = null;
			if (wordform == null || !wordform.IsValidObject)
				return;

			if (InterlinDoc == null) //when running some tests this is null
				return;
			ISilDataAccess sda = InterlinDoc.RootBox.DataAccess;

			// If we're calling from the context of SetWordform(), we may be trying to establish
			// an alternative wordform/form/analysis. In that case, or if we don't have a default cached,
			// try to get one. Otherwise, if we've already cached a default, use it...it's surprising for the
			// user if we move the focus box to something and the default changes. (LT-4643 etc.)
			int hvoDefault = 0;
			if (m_occurrenceSelected != null && m_occurrenceSelected.Analysis == wordform)
			{
				// Try to establish a default based on the current occurrence.
				if (m_fSetWordformInProgress ||
					!sda.get_IsPropInCache(HvoAnnotation, InterlinViewDataCache.AnalysisMostApprovedFlid,
						(int) CellarPropertyType.ReferenceAtomic, 0))
				{
					InterlinDoc.RecordGuessIfNotKnown(m_occurrenceSelected);
				}
				hvoDefault = sda.get_ObjectProp(HvoAnnotation, InterlinViewDataCache.AnalysisMostApprovedFlid);
				// In certain cases like during an undo the Decorator data might be stale, so validate the result before we continue
				// to prevent using data that does not exist anymore
				if(!Cache.ServiceLocator.IsValidObjectId(hvoDefault))
					hvoDefault = 0;
			}
			else
			{
				// Try to establish a default based on the wordform itself.
				int ws = wordform.Cache.DefaultVernWs;
				if (m_occurrenceSelected != null)
					ws = m_occurrenceSelected.BaselineWs;
				var analysisDefault = InterlinDoc.GetGuessForWordform(wordform, ws);
				if (analysisDefault != null)
					hvoDefault = analysisDefault.Hvo;
			}

			if (hvoDefault != 0)
			{
				var obj = m_caches.MainCache.ServiceLocator.GetObject(hvoDefault);
				switch (obj.ClassID)
				{
					case WfiAnalysisTags.kClassId:
						analysis = (IWfiAnalysis) obj;
						gloss = null;
						return;
					case WfiGlossTags.kClassId:
						gloss = (IWfiGloss) obj;
						analysis = obj.OwnerOfClass<IWfiAnalysis>();
						return;
				}
			}
		}
			/// <summary>
			/// Count how many non-blank alternatives tss has that are not listed in wsIds.
			/// </summary>
			/// <param name="tss"></param>
			/// <param name="wsIds"></param>
			/// <returns></returns>
			static int AdditionalAlternatives(IWfiGloss wg, List<int> wsIds)
			{
				int result = 0;
				foreach (var ws in wg.Form.AvailableWritingSystemIds)
				{
					if (wsIds.Contains(ws))
						continue;
					if (wg.Form.get_String(ws).Length > 0)
						result++;
				}
				return result;
			}
			private bool MatchesCurrentGlosses(IWfiGloss gloss)
			{
				foreach (int wsId in m_choices.WritingSystemsForFlid(InterlinLineChoices.kflidWordGloss))
				{
					ITsString tssGloss = m_sda.get_MultiStringAlt(m_hvoSbWord, ktagSbWordGloss, wsId);
					if (!tssGloss.Equals(gloss.Form.get_String(wsId)))
						return false;
				}
				return true;
			}
Ejemplo n.º 32
0
        private IWfiAnalysis MakeCompleteAnalysis(IWfiWordform wf, out IPartOfSpeech pos, out ICmAgent human, out IWfiGloss wg)
        {
            var wa     = MakeAnalysis(wf);
            var bundle = MakeCompleteBundle(wa);

            wg            = MakeCompleteGloss(wa);
            pos           = MakePartOfSpeech();
            wa.CategoryRA = pos;
            human         = Cache.LangProject.DefaultUserAgent;
            wa.SetAgentOpinion(human, Opinions.approves);
            Assert.IsTrue(wa.IsComplete);
            return(wa);
        }
Ejemplo n.º 33
0
		private static bool DuplicateGlosses(IWfiGloss wg1, IWfiGloss wg2)
		{
			return
				wg1.Form.AvailableWritingSystemIds.Union(wg2.Form.AvailableWritingSystemIds)
				   .All(ws => wg1.Form.get_String(ws).Equals(wg2.Form.get_String(ws)));
		}