예제 #1
0
		/// -----------------------------------------------------------------------------------
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// -----------------------------------------------------------------------------------
		protected override void Dispose(bool disposing)
		{
			//Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
			// Must not be run more than once.
			if (IsDisposed)
				return;

			base.Dispose(disposing);

			if (disposing)
			{
				//RightMouseClickedEvent -= new FwRightMouseClickEventHandler(InterlinDocChild_RightMouseClickedEvent);
				if (m_tryAWordSandbox != null)
				{
					if (!Controls.Contains(m_tryAWordSandbox))
						m_tryAWordSandbox.Dispose();
				}
				if (m_vc != null)
					m_vc.Dispose();
			}
			m_tryAWordSandbox = null;
			m_vc = null;
			m_wordform = null;
			m_msaHvoList = null;
			m_sWordForm = null;
		}
예제 #2
0
        private IWfiAnalysis MakeCompleteAnalysis(IWfiWordform wf, out IPartOfSpeech pos, out ICmAgent human, out IWfiGloss wg)
        {
            var wa = MakeAnalysis(wf);

            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);
        }
예제 #3
0
        public override bool Accept(IManyOnePathSortItem item)
        {
            int OccurrenceCount = m_sda.get_IntProp(item.RootObjectHvo, m_flid);

            if (OccurrenceCount != 0)
            {
                return(true);                // occurs in our corpus, we want to show it.
            }
            IWfiWordform wf = (IWfiWordform)item.RootObjectUsing(m_cache);

            // Otherwise we want it only if it does NOT occur somewhere else.
            return(wf.FullConcordanceCount == 0);
        }
예제 #4
0
		/// <summary>
		/// Make one. Everything interesting happens when it is given a root object, however.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="analysis"></param>
		/// <param name="configurationNode"></param>
		/// <param name="stringTable"></param>
		public AnalysisInterlinearRs(FdoCache cache, IWfiAnalysis analysis,
			XmlNode configurationNode, StringTable stringTable) : base(cache)
		{
			if (analysis == null)
				throw new ArgumentNullException("analysis");
			if (configurationNode == null)
				throw new ArgumentNullException("configurationNode");

			m_configurationNode = configurationNode;
			m_wfiAnalysis = analysis;
			m_wordform = m_wfiAnalysis.Wordform;
			//			RightMouseClickedEvent += new FwRightMouseClickEventHandler(InterlinDocChild_RightMouseClickedEvent);
		}
예제 #5
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);
        }
예제 #6
0
        private void VerifyDoneStateApplyTwoAndCopyAnalyses()
        {
            VerifyDoneStateApplyTwo();
            IWfiWordform wf = WfiWordform.CreateFromDBObject(Cache,
                                                             WfiWordform.FindOrCreateWordform(Cache, "ayyy", Cache.DefaultVernWs, false));

            VerifyAnalysis(wf, "axe", 0, "axx", "axe", "first mono");
            VerifyAnalysis(wf, "chopper", -1, null, null, "second gloss");
            VerifyAnalysis(wf, "cut", 0, "axx", "cut", "second mono");
            VerifyAnalysis(wf, "cut.it", 0, "ax", "cut", "first morph cut.it");
            VerifyAnalysis(wf, "cut.it", 1, "x", "it", "2nd morph cut.it");
            VerifyAnalysis(wf, "not.rude", 0, "a", "not", "first morph not.rude");
            VerifyAnalysis(wf, "not.rude", 1, "xx", "rude", "2nd morph not.rude");
        }
예제 #7
0
        private void btnTrace_Click(object sender, System.EventArgs e)
        {
            FdoOwningCollection <IWfiWordform> words = m_selectedFdoCache.LangProject.WordformInventoryOA.WordformsOC;

            if (words.Count == 0)
            {
                MessageBox.Show("Can't do that, because there are no wordforms in this project.");
                return;
            }

            IWfiWordform word = WfiWordform.CreateFromDBObject(m_selectedFdoCache, words.HvoArray[0]);

            m_selectedParserConnection.TryAWordAsynchronously(word.Form.VernacularDefaultWritingSystem, true);
        }
예제 #8
0
        protected IWfiWordform CheckAnnotationSize(string form, int expectedSize, bool isStarting)
        {
            IFdoServiceLocator servLoc = Cache.ServiceLocator;
            IWfiWordform       wf      = FindOrCreateWordform(form);
            int actualSize             =
                (from ann in servLoc.GetInstance <ICmBaseAnnotationRepository>().AllInstances()
                 where ann.BeginObjectRA == wf
                 select ann).Count();
            // wf.RefsFrom_CmBaseAnnotation_BeginObject.Count;
            string msg = String.Format("Wrong number of {0} annotations for: {1}", isStarting ? "starting" : "ending", form);

            Assert.AreEqual(expectedSize, actualSize, msg);
            return(wf);
        }
        IWfiWordform Survivor(params IWfiWordform[] inputs)
        {
            IWfiWordform result = null;

            foreach (var wf in inputs)
            {
                if (wf.IsValidObject)
                {
                    Assert.That(result, Is.Null, "only one wordform should have survived");
                    result = wf;
                }
            }
            Assert.That(result, Is.Not.Null, "One wordform should have survived");
            return(result);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Looks up an lexeme
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public LexicalEntry GetLexeme(LexemeType type, string lexicalForm, int homograph)
        {
            LexicalProviderManager.ResetLexicalProviderTimer();

            switch (type)
            {
            case LexemeType.Word:
                IWfiWordform wf = GetDbWordform(lexicalForm);
                return((wf != null) ? CreateEntryFromDbWordform(wf) : null);

            default:
                ILexEntry dbEntry = GetDbLexeme(type, lexicalForm, homograph);
                return((dbEntry != null) ? CreateEntryFromDbEntry(type, dbEntry) : null);
            }
        }
예제 #11
0
        public void UpdateConcordanceForCustomField_FindsMatches()
        {
            // build pre-existing data
            var sl  = Cache.ServiceLocator;
            var wsf = Cache.WritingSystemFactory;
            var mdc = Cache.ServiceLocator.GetInstance <IFwMetaDataCacheManaged>();

            IWfiWordform word            = null;
            ITsString    para1_1Contents = null;
            Guid         segGuid         = new Guid();

            NonUndoableUnitOfWorkHelper.Do(Cache.ActionHandlerAccessor, () =>
            {
                mdc.AddCustomField("Segment", "test1", CellarPropertyType.String, 0,
                                   "just testing", Cache.DefaultAnalWs, Guid.Empty);
                var text1 = MakeText("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA",
                                     "Sentence one. Sentence 2.");
                var sttext1      = text1.ContentsOA;
                var para1_1      = sttext1.ParagraphsOS[0] as IStTxtPara;
                var segment1_1_1 = para1_1.SegmentsOS[0];
                var testFlid     = mdc.GetFieldId("Segment", "test1", false);
                Cache.MainCacheAccessor.SetString(segment1_1_1.Hvo, testFlid,
                                                  TsStringUtils.MakeString("the big bad wolf", Cache.DefaultAnalWs));

                var text2 = MakeText("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAB",
                                     "Another Sentence one. Another Sentence 2.");
                var sttext2      = text2.ContentsOA;
                var para2_1      = sttext2.ParagraphsOS[0] as IStTxtPara;
                var segment2_1_2 = para2_1.SegmentsOS[1];
                Cache.MainCacheAccessor.SetString(segment2_1_2.Hvo, testFlid,
                                                  TsStringUtils.MakeString("the nice big dog", Cache.DefaultAnalWs));
                var segment2_1_1 = para2_1.SegmentsOS[0];
                Cache.MainCacheAccessor.SetString(segment2_1_1.Hvo, testFlid,
                                                  TsStringUtils.MakeString("the small furry cat", Cache.DefaultAnalWs));

                var paragraphs = new HashSet <IStTxtPara>();
                paragraphs.Add(para1_1);
                paragraphs.Add(para2_1);
                var vwPattern     = VwPatternClass.Create();
                vwPattern.Pattern = TsStringUtils.MakeString("big", Cache.DefaultAnalWs);
                var matcher       = new RegExpMatcher(vwPattern);
                var result        = ConcordanceControl.GetOccurrencesInCustomField(testFlid, paragraphs,
                                                                                   Cache.MainCacheAccessor, matcher);
                Assert.That(result, Has.Count.EqualTo(2));
                Assert.That(result.Any(pf => pf.Segment == segment1_1_1));
                Assert.That(result.Any(pf => pf.Segment == segment2_1_2));
            });
        }
        // Caller must create UOW
        private void ApplyAnalysisToInstancesOfWordform(IAnalysis newAnalysis, IWfiWordform oldWordform, IWfiWordform newWordform)
        {
            var navigator = new SegmentServices.StTextAnnotationNavigator(SelectedOccurrence);

            foreach (var occ in navigator.GetAnalysisOccurrencesAdvancingInStText().ToList())
            {
                // We certainly want to update any occurrence that exactly matches the wordform of the analysis we are confirming.
                // If oldWordform is different, we are confirming a different case form from what occurred in the text,
                // and we only confirm these if SelectedOccurrence and occ are both sentence-initial.
                // We want to do that only for sentence-initial occurrences.
                if (occ.Analysis == newWordform || (occ.Analysis == oldWordform && occ.Index == 0 && SelectedOccurrence.Index == 0))
                {
                    occ.Segment.AnalysesRS[occ.Index] = newAnalysis;
                }
            }
        }
예제 #13
0
        private void CreateTryAWordSandbox()
        {
            // skip if it's before we've set the word
            if (m_sWordForm == null)
            {
                return;
            }
            // skip if it's before we've set up the rootsite control
            if (m_rootb == null)
            {
                return;
            }
            // skip if we're not visible
            if (!Visible)
            {
                return;
            }
            //Debug.WriteLine("TryAWordRootSite:WordForm - creating sandbox for " + m_sWordForm.Text);
            int hvoWordform = WfiWordform.FindOrCreateWordform(m_fdoCache, m_sWordForm, false);

            //if (m_fdoCache.IsDummyObject(hvo))
            //	m_wordform = new WfiWordform();

            m_wordform = WfiWordform.CreateFromDBObject(m_fdoCache, hvoWordform);
            m_rootb.SetRootObject(hvoWordform, m_vc, m_kfragSingleInterlinearAnalysisWithLabels, m_styleSheet);

            //Debug.Assert(m_tryAWordSandbox == null);
            m_tryAWordSandbox = new TryAWordSandbox(m_fdoCache,
                                                    Mediator,
                                                    StyleSheet,
                                                    m_vc.LineChoices,
                                                    hvoWordform);
            m_tryAWordSandbox.Visible = false;
            Controls.Add(m_tryAWordSandbox);
            SetSandboxSize();
            SetSandboxLocation();
            m_tryAWordSandbox.Visible = true;
            SetBackgroundColor();
            int height = Math.Max(ScrollRange.Height, m_tryAWordSandbox.Height) + SystemInformation.HorizontalScrollBarHeight;

            if (Height != height)
            {
                Height = height;
            }
            m_tryAWordSandbox.SizeChanged += new EventHandler(m_tryAWordSandbox_SizeChanged);
            //m_tryAWordSandbox.Focus();
        }
        /// <summary>
        /// Make one. Everything interesting happens when it is given a root object, however.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="analysis"></param>
        /// <param name="configurationNode"></param>
        /// <param name="stringTable"></param>
        public AnalysisInterlinearRs(FdoCache cache, IWfiAnalysis analysis,
                                     XmlNode configurationNode, StringTable stringTable) : base(cache)
        {
            if (analysis == null)
            {
                throw new ArgumentNullException("analysis");
            }
            if (configurationNode == null)
            {
                throw new ArgumentNullException("configurationNode");
            }

            m_configurationNode = configurationNode;
            m_wfiAnalysis       = analysis;
            m_wordform          = m_wfiAnalysis.Wordform;
            //			RightMouseClickedEvent += new FwRightMouseClickEventHandler(InterlinDocChild_RightMouseClickedEvent);
        }
예제 #15
0
        public void TestFDOAnalysisAddRemove()
        {
            CheckDisposed();

            const string kWordForm = "ak";
            ILangProject lp        = m_fdoCache.LangProject;
            IWfiWordform word      = WfiWordform.FindOrCreateWordform(m_fdoCache, kWordForm, lp.DefaultVernacularWritingSystem);

            word.AnalysesOC.Add(new WfiAnalysis());

            int[] hvos = word.AnalysesOC.HvoArray;
            foreach (int hvo in hvos)
            {
                word.AnalysesOC.Remove(hvo);
            }
            Assert.AreEqual(0, word.AnalysesOC.Count, "Analyses removal failed.");
        }
예제 #16
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);
        }
예제 #17
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Writes this rendering to the specified cache.
        /// </summary>
        /// <param name="term">The term to which this rendering belongs.</param>
        /// <param name="ResolveConflict">The delegate to call to resolve a conflict when a
        /// different rendering already exists.</param>
        /// ------------------------------------------------------------------------------------
        internal void WriteToCache(IChkTerm term, Func <IChkRef, string, string, bool> ResolveConflict)
        {
            IChkRef occ = term.OccurrencesOS.FirstOrDefault(o => o.Ref == Reference && o.Location == Location);

            if (occ == null)
            {
                MessageBox.Show(string.Format("Couldn't find occurrence {0} in {1} for imported rendering of term: {2}.",
                                              Location, (new BCVRef(Reference)), term.Name.AnalysisDefaultWritingSystem), "Unable to Import");
                return;
            }

            if (string.IsNullOrEmpty(VernRendering))
            {
                if (occ.Status != KeyTermRenderingStatus.Ignored)
                {
                    occ.Status      = KeyTermRenderingStatus.Ignored;
                    occ.RenderingRA = null;
                }
                return;
            }

            string existingRendering = occ.RenderingRA == null ? null :
                                       occ.RenderingRA.Form.VernacularDefaultWritingSystem.Text;

            if (existingRendering == VernRendering)
            {
                return;                 // already set. Nothing to do.
            }
            if (!string.IsNullOrEmpty(existingRendering))
            {
                if (!ResolveConflict(occ, existingRendering, VernRendering))
                {
                    return;                     // Leave existing rendering
                }
            }

            // See if the word form already exists
            IWfiWordform wordForm = WfiWordformServices.FindOrCreateWordform(term.Cache,
                                                                             VernRendering, term.Services.WritingSystems.DefaultVernacularWritingSystem);

            KeyTermRef ktRef = new KeyTermRef(occ);

            // Change the reference's status and attach the word form to the ChkRef
            ktRef.AssignRendering(wordForm);
        }
예제 #18
0
        public void SetDlgInfo(Mediator mediator, PropertyTable propertyTable, IWfiWordform wordform, ParserListener parserListener)
        {
            Mediator          = mediator;
            PropTable         = propertyTable;
            m_persistProvider = new PersistenceProvider(Mediator, propertyTable, PersistProviderID);
            m_cache           = PropTable.GetValue <LcmCache>("cache");
            m_parserListener  = parserListener;

            Text = m_cache.ProjectId.UiName + " - " + Text;
            SetRootSite();
            SetFontInfo();
            // restore window location and size after setting up the form textbox, because it might adjust size of
            // window causing the window to grow every time it is opened
            m_persistProvider.RestoreWindowSettings(PersistProviderID, this);
            if (wordform == null)
            {
                GetLastWordUsed();
            }
            else
            {
                SetWordToUse(wordform.Form.VernacularDefaultWritingSystem.Text);
            }

            m_webPageInteractor = new WebPageInteractor(m_htmlControl, Mediator, m_cache, m_wordformTextBox);

            // No such thing as FwApp.App now: if(FwApp.App != null) // Could be null during testing
            var helpTopicProvider = PropTable.GetValue <IHelpTopicProvider>("HelpTopicProvider");

            if (helpTopicProvider != null)             // trying this
            {
                m_helpProvider.HelpNamespace = helpTopicProvider.HelpFile;
                m_helpProvider.SetHelpKeyword(this, helpTopicProvider.GetHelpString(HelpTopicID));
                m_helpProvider.SetHelpNavigator(this, HelpNavigator.Topic);
            }

            if (m_parserListener.Connection != null)
            {
                m_parserListener.Connection.TryAWordDialogIsRunning = true;
                m_statusLabel.Text = GetString("ParserStatusPrefix") + ParserUIStrings.ksIdle_ + GetString("ParserStatusSuffix");
            }
            else
            {
                m_statusLabel.Text = ParserStoppedMessage();
            }
        }
예제 #19
0
        /// <summary>
        /// Given a wf provide the best guess based on the user-approved analyses (in or outside of texts).
        /// If we don't already have a guess, this will try to create one from the lexicon, based on the
        /// form in the specified WS.
        /// </summary>
        public IAnalysis GetBestGuess(IWfiWordform wf, int ws)
        {
            IAnalysis wag;

            if (GuessTable.TryGetValue(wf, out wag))
            {
                return(wag);
            }
            if (wf.AnalysesOC.Count == 0)
            {
                GenerateEntryGuesses(wf, ws);
                if (GuessTable.TryGetValue(wf, out wag))
                {
                    return(wag);
                }
            }
            return(new NullWAG());
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates a new LexicalEntry from the specified word form in the DB
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private LexicalEntry CreateEntryFromDbWordform(IWfiWordform wordform)
        {
            const int    homograph = 1;
            LexicalEntry entry     = new LexicalEntry(LexemeType.Word, wordform.Form.VernacularDefaultWritingSystem.Text, homograph);

            foreach (IWfiAnalysis dbAnalysis in wordform.AnalysesOC)
            {
                // Since our "sense" is really an analysis for a wordform, assume that any meanings
                // for that analysis are glosses for the same "sense".
                LexSense sense = new LexSense(kAnalysisPrefix + dbAnalysis.Guid.ToString());
                foreach (IWfiGloss gloss in dbAnalysis.MeaningsOC)
                {
                    AddDbGlossesToSense(sense, gloss.Form);
                }
                entry.Senses.Add(sense);
            }
            return(entry);
        }
예제 #21
0
        protected override FdoObjectSet <ICmObject> GetObjectSet()
        {
            IVwVirtualHandler handler = BaseVirtualHandler.GetInstalledHandler(m_cache, "WfiWordform", "OccurrencesInTexts");

            Debug.Assert(handler != null);

            IWfiWordform wf          = m_owningObject as IWfiWordform;
            List <int>   occurrences = wf.OccurrencesInTexts;

            IVwVirtualHandler vh = m_cache.VwCacheDaAccessor.GetVirtualHandlerName("WfiWordform", "OccurrencesInCaptions");

            if (vh != null)
            {
                occurrences.AddRange(m_cache.GetVectorProperty(wf.Hvo, vh.Tag, true));
            }

            return(new FdoObjectSet <ICmObject>(m_cache, occurrences.ToArray(), true));
        }
예제 #22
0
        /// <summary>
        /// Verify everything any test cares about concerning the initial state.
        /// Used after various Undo operations to verify success.
        /// </summary>
        private void VerifyStartingState()
        {
            string text = m_para1.Contents.Text;

            Assert.AreEqual(text, "Axx simplexx testxx withxx axx lotxx ofxx wordsxx endingxx inxx xx", "para 1 changes should be undone");
            text = m_para2.Contents.Text;
            Assert.AreEqual(text, "axx sentencexx axx havingxx axx lotxx ofxx axx", "para 2 changes should be undone");
            VerifyTwfic(m_cba2.Hvo, "axx sentencexx axx havingxx axx ".Length, "axx sentencexx axx havingxx axx lotxx".Length,
                        "following Twfic");
            VerifyTwfic(m_para1Occurrences[0], 0, "Axx".Length,
                        "first para 1 Twfic changed");
            VerifyTwfic(m_para1Occurrences[1], "Axx simplexx testxx withxx ".Length, "Axx simplexx testxx withxx axx".Length,
                        "first para 1 Twfic changed");
            VerifyTwfic(m_para2Occurrences[0], 0, "axx".Length,
                        "first Twfic changed");
            VerifyTwfic(m_para2Occurrences[1], "axx sentencexx ".Length, "axx sentencexx axx".Length,
                        "first Twfic changed");
            VerifyTwfic(m_para2Occurrences[2], "axx sentencexx axx havingxx ".Length, "axx sentencexx axx havingxx axx".Length,
                        "second Twfic changed");
            VerifyTwfic(m_para2Occurrences[3], "axx sentencexx axx havingxx axx lotxx ofxx ".Length, "axx sentencexx axx havingxx axx lotxx ofxx axx".Length,
                        "final (unchanged) Twfic");
            IWfiWordform wf = WfiWordform.CreateFromDBObject(Cache,
                                                             WfiWordform.FindOrCreateWordform(Cache, "ayyy", Cache.DefaultVernWs, false));

            //the wordform becomes real, and that is not undoable.
            //Assert.IsTrue(wf.IsDummyObject, "should have deleted the WF");
            Assert.AreEqual(0, Cache.GetVectorSize(wf.Hvo, (int)WfiWordform.WfiWordformTags.kflidAnalyses),
                            "when undone ayyy should have no analyses");

            IWfiWordform wfOld = WfiWordform.CreateFromDBObject(Cache,
                                                                WfiWordform.FindOrCreateWordform(Cache, "axx", Cache.DefaultVernWs, false));

            Assert.AreEqual((int)SpellingStatusStates.undecided, wf.SpellingStatus);

            if (m_wfaAxe != null)
            {
                Assert.AreEqual("axx", m_wfaAxe.MorphBundlesOS[0].MorphRA.Form.VernacularDefaultWritingSystem,
                                "lexicon should be restored(axe)");
                Assert.AreEqual("axx", m_wfaCut.MorphBundlesOS[0].MorphRA.Form.VernacularDefaultWritingSystem,
                                "lexicon should be restored(cut)");
            }

            Assert.AreEqual(m_cAnalyses, wfOld.AnalysesOC.Count, "original analyes restored");
        }
예제 #23
0
        public void TwoWordforms()
        {
            IWfiWordform snake = CheckAnalysisSize("snakeTEST", 0, true);
            IWfiWordform bull  = CheckAnalysisSize("bullTEST", 0, true);
            ILexDb       ldb   = Cache.LanguageProject.LexDbOA;

            ParseResult result = null;

            UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () =>
            {
                // Snake
                ILexEntry snakeN            = m_entryFactory.Create();
                IMoStemAllomorph snakeNForm = m_stemAlloFactory.Create();
                snakeN.AlternateFormsOS.Add(snakeNForm);
                snakeNForm.Form.VernacularDefaultWritingSystem = Cache.TsStrFactory.MakeString("snakeNTEST", m_vernacularWS.Handle);
                IMoStemMsa snakeNMsa = m_stemMsaFactory.Create();
                snakeN.MorphoSyntaxAnalysesOC.Add(snakeNMsa);

                // Bull
                ILexEntry bullN            = m_entryFactory.Create();
                IMoStemAllomorph bullNForm = m_stemAlloFactory.Create();
                bullN.AlternateFormsOS.Add(bullNForm);
                bullNForm.Form.VernacularDefaultWritingSystem = Cache.TsStrFactory.MakeString("bullNTEST", m_vernacularWS.Handle);
                IMoStemMsa bullNMsa = m_stemMsaFactory.Create();
                bullN.MorphoSyntaxAnalysesOC.Add(bullNMsa);

                result = new ParseResult(new[]
                {
                    new ParseAnalysis(new[]
                    {
                        new ParseMorph(snakeNForm, snakeNMsa)
                    }),
                    new ParseAnalysis(new[]
                    {
                        new ParseMorph(bullNForm, bullNMsa)
                    })
                });
            });

            m_filer.ProcessParse(snake, ParserPriority.Low, result);
            ExecuteIdleQueue();
            CheckAnalysisSize("snakeTEST", 1, false);
            CheckAnalysisSize("bullTEST", 1, false);
        }
예제 #24
0
        private void FinishWordForm(IWfiWordform wordform)
        {
            // the following is a port of the SP RemoveUnusedAnalyses

            // Delete stale evaluations on analyses. The only non-stale analyses are new, positive ones, so this
            // makes all analyses that are not known to be correct no-opinion. Later any of them that survive at all
            // will be changed to failed (if there was no error in parsing the wordform).
            var analysesNotUpdated = from analysis in wordform.AnalysesOC where m_analysesWithOldEvaluation.Contains(analysis) select analysis;

            foreach (var analysis in analysesNotUpdated)
            {
                analysis.SetAgentOpinion(m_parserAgent, Opinions.noopinion);
            }

            // Make sure all analyses have human evaluations, if they,
            // or glosses they own, are referred to by an ISegment.
            //var annLookup = m_baseAnnotationRepository.AllInstances()
            //	.Where(ann => ann.AnnotationTypeRA != null && ann.AnnotationTypeRA.Guid == CmAnnotationDefnTags.kguidAnnWordformInContext)
            //	.ToLookup(ann => ann.InstanceOfRA);
            var segmentAnalyses = new HashSet <IAnalysis>();

            foreach (var seg in wordform.OccurrencesBag)
            {
                segmentAnalyses.UnionWith(seg.AnalysesRS.ToArray());
            }
            var analyses = from anal in wordform.AnalysesOC
                           where segmentAnalyses.Contains(anal) || anal.MeaningsOC.Any(segmentAnalyses.Contains)
                           select anal;

            foreach (var analysis in analyses)
            {
                m_userAgent.SetEvaluation(analysis, Opinions.approves);
            }

            // Delete orphan analyses, which have no evaluations (Review JohnT: should we also check for no owned WfiGlosses?)
            var orphanedAnalyses = from anal in wordform.AnalysesOC
                                   where anal.EvaluationsRC.Count == 0
                                   select anal;

            foreach (var analysis in orphanedAnalyses)
            {
                m_cache.DomainDataByFlid.DeleteObj(analysis.Hvo);
            }
        }
예제 #25
0
        /// <summary>
        /// Have the utility do what it does.
        /// </summary>
        public void Process()
        {
            Debug.Assert(m_dlg != null);
            var cache = (FdoCache)m_dlg.Mediator.PropertyTable.GetValue("cache");

            IWfiAnalysis[] analyses = cache.ServiceLocator.GetInstance <IWfiAnalysisRepository>().AllInstances().ToArray();
            if (analyses.Length == 0)
            {
                return;
            }

            // Set up progress bar.
            m_dlg.ProgressBar.Minimum = 0;
            m_dlg.ProgressBar.Maximum = analyses.Length;
            m_dlg.ProgressBar.Step    = 1;

            // stop parser if it's running.
            m_dlg.Mediator.SendMessage("StopParser", null);

            NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
            {
                foreach (IWfiAnalysis analysis in analyses)
                {
                    ICmAgentEvaluation[] parserEvals = analysis.EvaluationsRC.Where(evaluation => !evaluation.Human).ToArray();
                    foreach (ICmAgentEvaluation parserEval in parserEvals)
                    {
                        analysis.EvaluationsRC.Remove(parserEval);
                    }

                    IWfiWordform wordform = analysis.Wordform;
                    if (analysis.EvaluationsRC.Count == 0)
                    {
                        wordform.AnalysesOC.Remove(analysis);
                    }

                    if (parserEvals.Length > 0)
                    {
                        wordform.Checksum = 0;
                    }

                    m_dlg.ProgressBar.PerformStep();
                }
            });
        }
예제 #26
0
        private void VerifyDoneStateApplyAllAndUpdateLexicon()
        {
            string text = m_para1.Contents.Text;

            Assert.AreEqual(text, "Ay simplexx testxx withxx ay lotxx ofxx wordsxx endingxx inxx xx", "expected text changes para 1");
            text = m_para2.Contents.Text;
            Assert.AreEqual(text, "ay sentencexx ay havingxx ay lotxx ofxx ay", "expected text changes para 2");
            VerifyTwfic(m_cba2.Hvo, "ay sentencexx ay havingxx ay ".Length, "ay sentencexx ay havingxx ay lotxx".Length,
                        "following Twfic");
            VerifyTwfic(m_para1Occurrences[0], 0, "Ay".Length,
                        "first para 1 Twfic changed");
            VerifyTwfic(m_para1Occurrences[1], "Ay simplexx testxx withxx ".Length, "Ay simplexx testxx withxx ay".Length,
                        "first para 1 Twfic changed");
            VerifyTwfic(m_para2Occurrences[0], 0, "ay".Length,
                        "first Twfic changed");
            VerifyTwfic(m_para2Occurrences[1], "ay sentencexx ".Length, "ay sentencexx ay".Length,
                        "first Twfic changed");
            VerifyTwfic(m_para2Occurrences[2], "ay sentencexx ay havingxx ".Length, "ay sentencexx ay havingxx ay".Length,
                        "second Twfic changed");
            VerifyTwfic(m_para2Occurrences[3], "ay sentencexx ay havingxx ay lotxx ofxx ".Length, "ay sentencexx ay havingxx ay lotxx ofxx ay".Length,
                        "final (unchanged) Twfic");
            IWfiWordform wf = WfiWordform.CreateFromDBObject(Cache,
                                                             WfiWordform.FindOrCreateWordform(Cache, "ay", Cache.DefaultVernWs, false));

            Assert.IsFalse(wf.IsDummyObject, "should have a real WF to hold spelling status");
            Assert.AreEqual((int)SpellingStatusStates.correct, wf.SpellingStatus);

            IWfiWordform wfOld = WfiWordform.CreateFromDBObject(Cache,
                                                                WfiWordform.FindOrCreateWordform(Cache, "axx", Cache.DefaultVernWs, false));

            Assert.IsFalse(wfOld.IsDummyObject, "should have a real WF to hold old spelling status");
            Assert.AreEqual((int)SpellingStatusStates.incorrect, wfOld.SpellingStatus);

            Assert.AreEqual("ay", m_wfaAxe.MorphBundlesOS[0].MorphRA.Form.VernacularDefaultWritingSystem, "lexicon should be updated(axe)");
            Assert.AreEqual("ay", m_wfaCut.MorphBundlesOS[0].MorphRA.Form.VernacularDefaultWritingSystem, "lexicon should be updated(cut)");

            Assert.AreEqual(0, wfOld.AnalysesOC.Count, "old wordform has no analyses");
            Assert.AreEqual(2, wf.AnalysesOC.Count, "two analyses survived");
            foreach (WfiAnalysis wa in wf.AnalysesOC)
            {
                Assert.AreEqual(1, wa.MorphBundlesOS.Count, "only monomorphemic analyses survived");
            }
        }
예제 #27
0
        public void SetAgentOpinion()
        {
            ICmAgent     agent = Cache.LangProject.DefaultComputerAgent;
            IWfiWordform wf    = WfiWordformServices.FindOrCreateWordform(Cache,
                                                                          TsStringUtils.MakeTss("xxxyyyzzz12234", Cache.DefaultVernWs));
            IWfiAnalysis wa = Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>().Create();

            wf.AnalysesOC.Add(wa);
            Assert.AreEqual(Opinions.noopinion, wa.GetAgentOpinion(agent));

            wa.SetAgentOpinion(agent, Opinions.approves);
            Assert.AreEqual(Opinions.approves, wa.GetAgentOpinion(agent));

            wa.SetAgentOpinion(agent, Opinions.disapproves);
            Assert.AreEqual(Opinions.disapproves, wa.GetAgentOpinion(agent));

            wa.SetAgentOpinion(agent, Opinions.noopinion);
            Assert.AreEqual(Opinions.noopinion, wa.GetAgentOpinion(agent));
        }
예제 #28
0
        public void HumanApprovedParserPreviouslyApprovedButNowRejectedAnalysisSurvives()
        {
            IWfiWordform theThreeLittlePigs = CheckAnalysisSize("theThreeLittlePigsTEST", 0, true);

            ParseResult  result = null;
            IWfiAnalysis anal   = null;

            UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () =>
            {
                // Pig entry
                ILexEntry pigN            = m_entryFactory.Create();
                IMoStemAllomorph pigNForm = m_stemAlloFactory.Create();
                pigN.AlternateFormsOS.Add(pigNForm);
                pigNForm.Form.VernacularDefaultWritingSystem = Cache.TsStrFactory.MakeString("pigNTEST", m_vernacularWS.Handle);
                IMoStemMsa pigNMsa = m_stemMsaFactory.Create();
                pigN.MorphoSyntaxAnalysesOC.Add(pigNMsa);
                ILexSense pigNSense = Cache.ServiceLocator.GetInstance <ILexSenseFactory>().Create();
                pigN.SensesOS.Add(pigNSense);

                // Human approved anal. Start with parser approved, but then it failed.
                var analFactory = Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>();
                var mbFactory   = Cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>();
                // Only analysis: human approved, previously parser approved but no longer produced.
                anal = analFactory.Create();
                theThreeLittlePigs.AnalysesOC.Add(anal);
                IWfiMorphBundle mb = mbFactory.Create();
                anal.MorphBundlesOS.Add(mb);
                mb.MorphRA = pigNForm;
                mb.MsaRA   = pigNMsa;
                HumanAgent.SetEvaluation(anal, Opinions.approves);
                ParserAgent.SetEvaluation(anal, Opinions.approves);
                CheckEvaluationSize(anal, 2, true, "anal");
                CheckAnalysisSize("theThreeLittlePigsTEST", 1, true);

                result = new ParseResult(Enumerable.Empty <ParseAnalysis>());
            });

            m_filer.ProcessParse(theThreeLittlePigs, ParserPriority.Low, result);
            ExecuteIdleQueue();
            CheckEvaluationSize(anal, 2, false, "analHvo");
            Assert.IsTrue(anal.IsValidObject, "analysis should end up with one evaluation and not be deleted");
        }
			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;
			}
예제 #30
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>
        /// This is the port of the SetParseFailureEvals SP.
        /// </remarks>
        private void MarkAnalysisParseFailures(IWfiWordform wordform)
        {
            // Solves LT-1842.

            /*
             *      Get all the IDs for Analyses that belong to the wordform, but which don't have an
             *      evaluation belonging to the given agent.  These will all be set to FAILED.
             */

            var failures = from anal in wordform.AnalysesOC
                           where anal.GetAgentOpinion(m_parserAgent) == Opinions.noopinion
                           select anal;

            foreach (var failure in failures)
            {
                m_parserAgent.SetEvaluation(failure,
                                            Opinions.disapproves);
                m_analysesWithOldEvaluation.Remove(failure);
            }
        }
예제 #31
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Assigns a rendering for this check reference.
        /// </summary>
        /// <param name="wordForm">The word form.</param>
        /// ------------------------------------------------------------------------------------
        internal void AssignRendering(IWfiWordform wordForm)
        {
            if (wordForm == null)
            {
                throw new ArgumentNullException("wordForm", "Cannot assign a rendering to a null word form.");
            }
            RenderingStatus      = KeyTermRenderingStatus.Assigned;
            m_chkRef.RenderingRA = wordForm;

            IChkTerm owningChkTerm = (IChkTerm)m_chkRef.Owner;
            bool     fChkTermRenderingAlreadySet =
                owningChkTerm.RenderingsOC.Any(rendering => rendering.SurfaceFormRA == wordForm);

            if (!fChkTermRenderingAlreadySet)
            {
                IChkRendering newRendering = m_cache.ServiceLocator.GetInstance <IChkRenderingFactory>().Create();
                owningChkTerm.RenderingsOC.Add(newRendering);
                newRendering.SurfaceFormRA = wordForm;
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Removes the sense with the specified ID and guid from the DB.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void RemoveSense(string senseId, Guid guid)
        {
            if (senseId.StartsWith(kAnalysisPrefix))
            {
                IWfiAnalysis dbAnalysis = m_cache.ServiceLocator.GetInstance <IWfiAnalysisRepository>().GetObject(guid);
                IWfiWordform dbWordform = (IWfiWordform)dbAnalysis.Owner;
                dbWordform.AnalysesOC.Remove(dbAnalysis);
            }
            else
            {
                ILexSense dbSense = m_cache.ServiceLocator.GetInstance <ILexSenseRepository>().GetObject(guid);
                ILexEntry dbEntry = (ILexEntry)dbSense.Owner;

                // Make sure we keep at least one sense around. This seems to be required.
                if (dbEntry.SensesOS.Count > 1)
                {
                    dbEntry.SensesOS.Remove(dbSense);
                }
            }
        }
예제 #33
0
        public void HumanHasNoopinionParserHadApprovedButNoLongerApprovesRemovesAnalysis()
        {
            IWfiWordform threeLittlePigs = CheckAnalysisSize("threeLittlePigsTEST", 0, true);

            ParseResult  result = null;
            IWfiAnalysis anal   = null;

            UndoableUnitOfWorkHelper.Do("Undo stuff", "Redo stuff", m_actionHandler, () =>
            {
                // Pig entry
                ILexEntry pigN            = m_entryFactory.Create();
                IMoStemAllomorph pigNForm = m_stemAlloFactory.Create();
                pigN.AlternateFormsOS.Add(pigNForm);
                pigNForm.Form.VernacularDefaultWritingSystem = TsStringUtils.MakeString("pigNTEST", m_vernacularWS.Handle);
                IMoStemMsa pigNMsa = m_stemMsaFactory.Create();
                pigN.MorphoSyntaxAnalysesOC.Add(pigNMsa);
                ILexSense pigNSense = Cache.ServiceLocator.GetInstance <ILexSenseFactory>().Create();
                pigN.SensesOS.Add(pigNSense);

                // Human no-opinion anal. Parser had approved, but then it failed to produce it.
                var analFactory = Cache.ServiceLocator.GetInstance <IWfiAnalysisFactory>();
                var mbFactory   = Cache.ServiceLocator.GetInstance <IWfiMorphBundleFactory>();
                // Human no-opinion anal. Parser had approved, but then it failed to produce it.
                anal = analFactory.Create();
                threeLittlePigs.AnalysesOC.Add(anal);
                IWfiMorphBundle mb = mbFactory.Create();
                anal.MorphBundlesOS.Add(mb);
                mb.MorphRA = pigNForm;
                mb.MsaRA   = pigNMsa;
                HumanAgent.SetEvaluation(anal, Opinions.noopinion);
                ParserAgent.SetEvaluation(anal, Opinions.approves);
                CheckEvaluationSize(anal, 1, true, "anal");
                CheckAnalysisSize("threeLittlePigsTEST", 1, true);

                result = new ParseResult(Enumerable.Empty <ParseAnalysis>());
            });

            m_filer.ProcessParse(threeLittlePigs, ParserPriority.Low, result);
            ExecuteIdleQueue();
            Assert.IsFalse(anal.IsValidObject, "analysis should end up with no evaluations and be deleted.");
        }
예제 #34
0
			public UpdateWordformWork(ParserScheduler scheduler, ParserPriority priority, IWfiWordform wordform)
				: base(scheduler, priority)
			{
				m_wordform = wordform;
			}
예제 #35
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Assigns a rendering for this check reference.
		/// </summary>
		/// <param name="wordForm">The word form.</param>
		/// ------------------------------------------------------------------------------------
		internal void AssignRendering(IWfiWordform wordForm)
		{
			RenderingStatus = KeyTermRenderingStatus.Assigned;
			RenderingRA = wordForm;

			ChkTerm owningChkTerm = new ChkTerm(Cache, OwnerHVO);
			bool fChkTermRenderingAlreadySet = false;
			foreach (IChkRendering rendering in owningChkTerm.RenderingsOC)
			{
				if (rendering.SurfaceFormRAHvo == wordForm.Hvo)
				{
					fChkTermRenderingAlreadySet = true;
					break;
				}
			}
			if (!fChkTermRenderingAlreadySet)
			{
				ChkRendering newRendering = new ChkRendering();
				owningChkTerm.RenderingsOC.Add(newRendering);
				newRendering.SurfaceFormRAHvo = wordForm.Hvo;
			}
		}
예제 #36
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds an occurrence to and old-style sense.
		/// </summary>
		/// <param name="term">The ChkTerm (a sense or subsense).</param>
		/// <param name="reference">The Scripture reference.</param>
		/// <param name="wordform">The wordform.</param>
		/// <param name="keyword">The keyword (transliterated from Greek)</param>
		/// <param name="status">The rendering status.</param>
		/// <returns>The newly added ChkRef</returns>
		/// ------------------------------------------------------------------------------------
		protected ChkRef AddOccurrenceToOldStyleSense(ChkTerm term, int reference,
			IWfiWordform wordform, string keyword, KeyTermRenderingStatus status)
		{
			ChkRef occurrence = new ChkRef();
			term.OccurrencesOS.Append(occurrence);
			occurrence.KeyWord.UnderlyingTsString = m_factory.MakeString(keyword, m_wsEn);
			occurrence.Ref = reference;
			// If wordform is null, status must either be unassigned or ignored
			// If wordform is not null, status must either be assigned or auto-assigned
			Debug.Assert(((wordform == null) && (status == KeyTermRenderingStatus.Unassigned ||
				status == KeyTermRenderingStatus.Ignored)) ||
				((wordform != null) && (status == KeyTermRenderingStatus.Assigned ||
				status == KeyTermRenderingStatus.AutoAssigned)));
			occurrence.Status = status;
			occurrence.RenderingRA = wordform;

			return occurrence;
		}
예제 #37
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds an occurrence to and old-style sense.
		/// </summary>
		/// <param name="term">The ChkTerm (a sense or subsense).</param>
		/// <param name="reference">The Scripture reference.</param>
		/// <param name="wordform">The wordform.</param>
		/// <param name="keyword">The keyword (transliterated from Greek)</param>
		/// <param name="status">The rendering status.</param>
		/// <returns>The newly added ChkRef</returns>
		/// ------------------------------------------------------------------------------------
		protected IChkRef AddOccurrenceToOldStyleSense(IChkTerm term, int reference,
			IWfiWordform wordform, string keyword, KeyTermRenderingStatus status)
		{
			IChkRef occurrence = Cache.ServiceLocator.GetInstance<IChkRefFactory>().Create();
			term.OccurrencesOS.Add(occurrence);
			occurrence.KeyWord = m_factory.MakeString(keyword, m_wsEn);
			occurrence.Ref = reference;
			// If wordform is null, status must either be unassigned or ignored
			// If wordform is not null, status must either be assigned or auto-assigned
			Debug.Assert(((wordform == null) && (status == KeyTermRenderingStatus.Unassigned ||
				status == KeyTermRenderingStatus.Ignored)) ||
				((wordform != null) && (status == KeyTermRenderingStatus.Assigned ||
				status == KeyTermRenderingStatus.AutoAssigned)));
			occurrence.Status = status;
			occurrence.RenderingRA = wordform;

			return occurrence;
		}
예제 #38
0
			private void GetRealWordformInfo(IAnalysis actualAnalysis, out int hvoActualInstanceOf, out IWfiWordform realWordform)
			{
				hvoActualInstanceOf = actualAnalysis.Hvo;
				realWordform = actualAnalysis.Wordform;
			}
예제 #39
0
		/// <summary>
		/// This version is used inside FLEx when the friendly tool is not active. So, we need to
		/// build the concordance, but on FLEx's list, and we can assume all the parts and layouts
		/// are loaded.
		/// </summary>
		public bool SetDlgInfo(IWfiWordform wf, Mediator mediator, XmlNode configurationParams)
		{
			using (var dlg = new ProgressDialogWorkingOn())
			{
				dlg.Owner = ActiveForm;
				if (dlg.Owner != null) // I think it's only null when debugging? But play safe.
					dlg.Icon = dlg.Owner.Icon;
				dlg.Text = MEStrings.ksFindingOccurrences;
				dlg.WorkingOnText = MEStrings.ksSearchingOccurrences;
				dlg.ProgressLabel = MEStrings.ksProgress;
				dlg.Show(ActiveForm);
				dlg.Update();
				dlg.BringToFront();
				try
				{
					var cache = wf.Cache;
					m_srcwfiWordform = wf;
					m_cache = cache;
					if (m_fDisposeMediator && m_mediator != null)
						m_mediator.Dispose();

					m_fDisposeMediator = false;
					return SetDlgInfoPrivate(mediator, configurationParams);
				}
				finally
				{
					dlg.Close();
				}
			}
		}
예제 #40
0
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if (IsDisposed)
				return;

			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
				foreach (RecordClerk clerk in m_recordClerks.Values)
				{
					// Take it out of the Mediator and Dispose it.
					m_mediator.PropertyTable.RemoveProperty("RecordClerk-" + clerk.Id);
					clerk.Dispose();
				}
				m_recordClerks.Clear();
				m_configurationNodes.Clear();
			}
			base.Dispose( disposing );

			m_wordform = null;
			m_sourceObject = null;
			m_cache = null;
			if (m_mediator != null)
				m_mediator.PropertyTable.RemoveProperty("IgnoreStatusPanel");
			m_mediator = null;
			m_configurationNode = null;
			m_currentBrowseView = null;
		}
예제 #41
0
		/// <summary>
		/// Initilize the gui control.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="mediator"></param>
		/// <param name="configurationNode">NB: In this case it is the main 'window' element node,
		/// se we have to drill down to find the control definition node(s).</param>
		/// <param name="sourceObject"></param>
		public void Init(Mediator mediator, XmlNode configurationNode, ICmObject sourceObject)
		{
			CheckDisposed();

			Debug.Assert(mediator != null);
			Debug.Assert(configurationNode != null);
			Debug.Assert(sourceObject != null && (sourceObject is IWfiWordform || sourceObject is IWfiAnalysis || sourceObject is IWfiGloss));

			m_cache = sourceObject.Cache;
			m_mediator = mediator;
			m_configurationNode = configurationNode;
			m_sourceObject = sourceObject;
			if (sourceObject is IWfiWordform)
			{
				m_wordform = sourceObject as IWfiWordform;
			}
			else
			{
				IWfiAnalysis anal = null;
				if (sourceObject is IWfiAnalysis)
					anal = sourceObject as IWfiAnalysis;
				else
					anal = WfiAnalysis.CreateFromDBObject(m_cache, sourceObject.OwnerHVO);
				m_wordform = WfiWordform.CreateFromDBObject(m_cache, anal.OwnerHVO);
			}

			m_mediator.PropertyTable.SetProperty("IgnoreStatusPanel", true);
			m_mediator.PropertyTable.SetPropertyPersistence("IgnoreStatusPanel", false);
			m_progAdvInd = new ProgressReporting(m_toolStripProgressBar);

			// Gather up the nodes.
			string xpathBase = "/window/controls/parameters[@id='guicontrols']/guicontrol[@id='{0}']/parameters[@id='{1}']";
			string xpath = String.Format(xpathBase, "WordformConcordanceBrowseView", "WordformInTwficsOccurrenceList");
			XmlNode configNode = m_configurationNode.SelectSingleNode(xpath);
			// And create the RecordClerks.
			RecordClerk clerk = RecordClerkFactory.CreateClerk(m_mediator, configNode);
			clerk.ProgressReporter = m_progAdvInd;
			m_recordClerks[WfiWordform.kclsidWfiWordform] = clerk;
			m_configurationNodes[WfiWordform.kclsidWfiWordform] = configNode;

			xpath = String.Format(xpathBase, "AnalysisConcordanceBrowseView", "AnalysisInTwficsOccurrenceList");
			configNode = m_configurationNode.SelectSingleNode(xpath);
			clerk = RecordClerkFactory.CreateClerk(m_mediator, configNode);
			clerk.ProgressReporter = m_progAdvInd;
			m_recordClerks[WfiAnalysis.kclsidWfiAnalysis] = clerk;
			m_configurationNodes[WfiAnalysis.kclsidWfiAnalysis] = configNode;

			xpath = String.Format(xpathBase, "GlossConcordanceBrowseView", "GlossInTwficsOccurrenceList");
			configNode = m_configurationNode.SelectSingleNode(xpath);
			clerk = RecordClerkFactory.CreateClerk(m_mediator, configNode);
			clerk.ProgressReporter = m_progAdvInd;
			m_recordClerks[WfiGloss.kclsidWfiGloss] = clerk;
			m_configurationNodes[WfiGloss.kclsidWfiGloss] = configNode;

			int concordOnHvo = sourceObject.Hvo;

			Debug.Assert(m_wordform != null);
			Debug.Assert(concordOnHvo > 0);

			tvSource.Font = new Font("Arial", 9);
			tvTarget.Font = new Font("Arial", 9);

			TreeNode srcTnWf = new TreeNode();
			TreeNode tarTnWf = new TreeNode();
			StringUtils.InitIcuDataDir();	// used for normalizing strings to NFC
			tarTnWf.Text = srcTnWf.Text = StringUtils.NormalizeToNFC(MEStrings.ksNoAnalysis);
			tarTnWf.Tag = srcTnWf.Tag = m_wordform.Hvo;
			tvSource.Nodes.Add(srcTnWf);
			tvTarget.Nodes.Add(tarTnWf);
			if ((int)srcTnWf.Tag == concordOnHvo)
				tvSource.SelectedNode = srcTnWf;
			int cnt = 0;
			// Note: the left side source tree only has human approved analyses,
			// since only those can have instances from text-land pointing at them.
			foreach (int humanApprovedAnalId in m_wordform.HumanApprovedAnalyses)
			{
				IWfiAnalysis anal = WfiAnalysis.CreateFromDBObject(m_wordform.Cache, humanApprovedAnalId);
				TreeNode srcTnAnal = new TreeNode();
				TreeNode tarTnAnal = new TreeNode();
				tarTnAnal.Text = srcTnAnal.Text = StringUtils.NormalizeToNFC(
					String.Format(MEStrings.ksAnalysisX, (++cnt).ToString()));
				tarTnAnal.Tag = srcTnAnal.Tag = anal.Hvo;
				srcTnWf.Nodes.Add(srcTnAnal);
				tarTnWf.Nodes.Add(tarTnAnal);
				if ((int)srcTnAnal.Tag == concordOnHvo)
					tvSource.SelectedNode = srcTnAnal;
				foreach (WfiGloss gloss in anal.MeaningsOC)
				{
					TreeNode srcTnGloss = new TreeNode();
					TreeNode tarTnGloss = new TreeNode();
					ITsString tss = gloss.Form.BestAnalysisAlternative;
					ITsTextProps props = tss.get_PropertiesAt(0);
					int nVar;
					int ws = props.GetIntPropValues((int)FwTextPropType.ktptWs, out nVar);
					string fontname = m_wordform.Cache.LanguageWritingSystemFactoryAccessor.get_EngineOrNull(ws).DefaultMonospace;
					tarTnGloss.NodeFont = new Font(fontname, 9);
					srcTnGloss.NodeFont = new Font(fontname, 9);
					tarTnGloss.Text = srcTnGloss.Text = StringUtils.NormalizeToNFC(tss.Text);
					tarTnGloss.Tag = srcTnGloss.Tag = gloss.Hvo;
					srcTnAnal.Nodes.Add(srcTnGloss);
					tarTnAnal.Nodes.Add(tarTnGloss);
					if ((int)srcTnGloss.Tag == concordOnHvo)
						tvSource.SelectedNode = srcTnGloss;
				}
			}
			tvSource.ExpandAll();
			tvSource.SelectedNode.EnsureVisible();
			tvTarget.ExpandAll();
		}
예제 #42
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a new LexicalEntry from the specified word form in the DB
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private LexicalEntry CreateEntryFromDbWordform(IWfiWordform wordform)
		{
			const int homograph = 1;
			LexicalEntry entry = new LexicalEntry(LexemeType.Word, wordform.Form.VernacularDefaultWritingSystem.Text, homograph);
			foreach (IWfiAnalysis dbAnalysis in wordform.AnalysesOC)
			{
				// Since our "sense" is really an analysis for a wordform, assume that any meanings
				// for that analysis are glosses for the same "sense".
				LexSense sense = new LexSense(kAnalysisPrefix + dbAnalysis.Guid.ToString());
				foreach (IWfiGloss gloss in dbAnalysis.MeaningsOC)
					AddDbGlossesToSense(sense, gloss.Form);
				entry.Senses.Add(sense);
			}
			return entry;
		}
		private IWfiAnalysis MakeAnalysis(IWfiWordform wf)
		{
			// Enhance JohnT: could make at least one bundle, or a gloss...but given the implementation this doesn't add much.
			var result = Cache.ServiceLocator.GetInstance<IWfiAnalysisFactory>().Create();
			wf.AnalysesOC.Add(result);
			return result;
		}
			/// <summary>
			/// Add to the combo the analyses of the specified wordform (that don't already occur).
			/// REFACTOR : possibly could refactor with SandboxEditMonitor.BuildCurrentMorphsString
			/// </summary>
			private void AddAnalysesOf(IWfiWordform wordform, bool fBaseWordIsPhrase)
			{
				if (wordform == null)
					return; // no real wordform, can't have analyses.
				ITsStrBldr builder = TsStrBldrClass.Create();
				ITsString space = TsStrFactoryClass.Create().
					MakeString(fBaseWordIsPhrase ? "  " : " ", m_wsVern);
				foreach (IWfiAnalysis wa in wordform.AnalysesOC)
				{
					Opinions o = wa.GetAgentOpinion(
						m_caches.MainCache.LangProject.DefaultUserAgent);
					if (o == Opinions.disapproves)
						continue;	// skip any analysis the user has disapproved.
					int cmorphs = wa.MorphBundlesOS.Count;
					if (cmorphs == 0)
						continue;
					builder.Clear();
					for (int imorph = 0; imorph < cmorphs; ++imorph)
					{
						if (imorph != 0)
							builder.ReplaceTsString(builder.Length, builder.Length, space);
						IWfiMorphBundle mb = wa.MorphBundlesOS[imorph];
						IMoForm morph = mb.MorphRA;
						if (morph != null)
						{
							ITsString tss = morph.Form.get_String(m_sandbox.RawWordformWs);
							var morphType = morph.MorphTypeRA;
							string sPrefix = morphType.Prefix;
							string sPostfix = morphType.Postfix;
							int ich = builder.Length;
							builder.ReplaceTsString(ich, ich, tss);
							if (sPrefix != null && sPrefix.Length != 0)
								builder.Replace(ich, ich, sPrefix, null);
							if (sPostfix != null && sPostfix.Length != 0)
								builder.Replace(builder.Length, builder.Length,
									sPostfix, null);
						}
						else
						{
							// No MoMorph object?  must be the Form string.
							ITsString tss = mb.Form.get_String(m_sandbox.RawWordformWs);
							builder.ReplaceTsString(builder.Length, builder.Length, tss);
						}
					}
					ITsString tssAnal = builder.GetString();
					// Add only non-whitespace morpheme breakdowns.
					if (tssAnal.Length > 0 && tssAnal.Text.Trim().Length > 0)
						AddIfNotPresent(tssAnal, wa);
				}
			}
예제 #45
0
		private bool GetSelectedWordform(IVwSelection sel, out IWfiWordform wordform)
		{
			wordform = null;
			int ichMin, ichLim, hvo, tag, ws;
			if (!GetSelectedWordPos(sel, out hvo, out tag, out ws, out ichMin, out ichLim))
				return false;

			if (tag != StTxtParaTags.kflidContents)
				return false;

			var para = m_fdoCache.ServiceLocator.GetInstance<IStTxtParaRepository>().GetObject(hvo);
			if (!para.ParseIsCurrent)
			{
				ReparseParaInUowIfNeeded(para);
			}
			var anal = FindClosestWagParsed(para, ichMin, ichLim);
			if (!para.ParseIsCurrent)
			{
				// Something is wrong! The attempt to find the word detected an inconsistency.
				// Fix the paragraph and try again.
				ReparseParaInUowIfNeeded(para);
				anal = FindClosestWagParsed(para, ichMin, ichLim);
			}
			if (anal != null && anal.HasWordform)
			{
				wordform = anal.Wordform;
				return true;
			}
			return false;
		}
예제 #46
0
		private void CopyAnalysesToNewWordform(ICollection<ISegment> originalOccurencesInTexts, IWfiWordform wfOld, IWfiWordform wfNew)
		{
			var shiftedSegments = new List<ISegment>(originalOccurencesInTexts.Count);
			foreach (IWfiAnalysis oldAnalysis in wfOld.AnalysesOC)
			{
				// Only copy approved analyses.
				if (oldAnalysis.GetAgentOpinion(m_cache.LangProject.DefaultUserAgent) != Opinions.approves)
					continue;

				IWfiAnalysis newAnalysis = FactWfiAnal.Create();
				wfNew.AnalysesOC.Add(newAnalysis);
				foreach (var segment in originalOccurencesInTexts)
				{
					if (!m_changedParas.ContainsKey(segment.Owner.Hvo))
						continue; // Skip shifting it for items that were not checked

					var analysisIdx = segment.AnalysesRS.IndexOf(oldAnalysis);
					while (analysisIdx > -1)
					{
						shiftedSegments.Add(segment);
						segment.AnalysesRS.RemoveAt(analysisIdx);
						segment.AnalysesRS.Insert(analysisIdx, newAnalysis);
						analysisIdx = segment.AnalysesRS.IndexOf(oldAnalysis);
					}
				}
				foreach (var shiftedSegment in shiftedSegments)
				{
					originalOccurencesInTexts.Remove(shiftedSegment);
				}
				shiftedSegments.Clear();
				foreach (IWfiGloss oldGloss in oldAnalysis.MeaningsOC)
				{
					IWfiGloss newGloss = FactWfiGloss.Create();
					newAnalysis.MeaningsOC.Add(newGloss);
					newGloss.Form.CopyAlternatives(oldGloss.Form);
					foreach (var segment in originalOccurencesInTexts)
					{
						if (!m_changedParas.ContainsKey(segment.Owner.Hvo))
							continue; // Skip shifting it for items that were not checked

						var glossIdx = segment.AnalysesRS.IndexOf(oldGloss);
						while (glossIdx > -1)
						{
							shiftedSegments.Add(segment);
							segment.AnalysesRS.RemoveAt(glossIdx);
							segment.AnalysesRS.Insert(glossIdx, newGloss);
							glossIdx = segment.AnalysesRS.IndexOf(oldGloss);
						}
					}
				}
				foreach (var shiftedSegment in shiftedSegments)
				{
					originalOccurencesInTexts.Remove(shiftedSegment);
				}
				foreach (IWfiMorphBundle bundle in oldAnalysis.MorphBundlesOS)
				{
					IWfiMorphBundle newBundle = FactWfiMB.Create();
					newAnalysis.MorphBundlesOS.Add(newBundle);
					newBundle.Form.CopyAlternatives(bundle.Form);
					newBundle.SenseRA = bundle.SenseRA;
					newBundle.MorphRA = bundle.MorphRA;
					newBundle.MsaRA = bundle.MsaRA;
				}
			}
		}
예제 #47
0
		private void ProcessAnalysesAndLexEntries(ProgressDialogWorkingOn progress, IWfiWordform wfOld, IWfiWordform wfNew)
		{
			wfOld.SpellingStatus = (int)SpellingStatusStates.incorrect;

			//if (UpdateLexicalEntries)
			//{
			//    foreach (IWfiAnalysis wa in wfOld.AnalysesOC)
			//    {
			//        if (wa.MorphBundlesOS.Count == 1)
			//        {
			//        }
			//    }
			//}
			if (!KeepAnalyses)
			{
				// Remove multi-morpheme anals in src wf.
				List<IWfiAnalysis> goners = new List<IWfiAnalysis>();
				foreach (IWfiAnalysis goner in wfOld.AnalysesOC)
				{
					if (goner.MorphBundlesOS.Count > 1)
					{
						goners.Add(goner);
				}
				}
				foreach (IWfiAnalysis goner in goners)
				{
					IWfiWordform wf = goner.OwnerOfClass<IWfiWordform>();
					wf.AnalysesOC.Remove(goner);
				}
				goners.Clear();
			}
			if (UpdateLexicalEntries)
			{
				// Change LE allo on single morpheme anals.
				foreach (IWfiAnalysis update in wfOld.AnalysesOC)
				{
					if (update.MorphBundlesOS.Count != 1)
						continue; // Skip any with zero or more than one.

					IWfiMorphBundle mb = update.MorphBundlesOS[0];
					ITsString tss = mb.Form.get_String(m_vernWs);
					string srcForm = tss.Text;
					if (srcForm != null)
					{
						// Change morph bundle form.
						mb.Form.set_String(m_vernWs, NewSpelling);
					}
					IMoForm mf = mb.MorphRA;
					if (mf != null)
					{
						mf.Form.set_String(m_vernWs, NewSpelling);
					}
				}
			}

			// Move remaining anals from src wf to new wf.
			// This changes the owners of the remaining ones,
			// since it is an owning property.
			var analyses = new List<IWfiAnalysis>();
			analyses.AddRange(wfOld.AnalysesOC);
			foreach (var anal in analyses)
				wfNew.AnalysesOC.Add(anal);
		}
예제 #48
0
		public IAnalysis GetGuessForWordform(IWfiWordform wf, int ws)
		{
			return GuessServices.GetBestGuess(wf, ws);
		}
예제 #49
0
		internal bool SetDlgInfo(Mediator mediator, XmlNode configurationParameters)
		{
			m_wfClerk = (RecordClerk)mediator.PropertyTable.GetValue("RecordClerk-concordanceWords");
			m_wfClerk.SuppressSaveOnChangeRecord = true; // various things trigger change record and would prevent Undo

			//We need to re-parse the interesting texts so that the rows in the dialog show all the occurrences (make sure it is up to date)
			if(m_wfClerk is InterlinearTextsRecordClerk)
			{
				//Unsuppress to allow for the list to be reloaded during ParseInterstingTextsIfNeeded()
				//(this clerk and its list are not visible in this dialog, so there will be no future reload)
				m_wfClerk.ListLoadingSuppressed = false;
				(m_wfClerk as InterlinearTextsRecordClerk).ParseInterstingTextsIfNeeded(); //Trigger the parsing
			}
			m_srcwfiWordform = (IWfiWordform)m_wfClerk.CurrentObject;
			if (m_fDisposeMediator && m_mediator != null)
				m_mediator.Dispose();

			m_fDisposeMediator = false;
			return SetDlgInfoPrivate(mediator, configurationParameters);
		}
예제 #50
0
		public IAnalysis GetGuessForWordform(IWfiWordform wf, int ws)
		{
			EnsureLoader();
			return m_loader.GetGuessForWordform(wf, ws);
		}
예제 #51
0
		public void SetDlgInfo(Mediator mediator, IWfiWordform wordform, ParserListener parserListener)
		{
			m_mediator = mediator;
			m_persistProvider = new PersistenceProvider(PersistProviderID, m_mediator.PropertyTable);
			m_cache = (FdoCache) m_mediator.PropertyTable.GetValue("cache");
			m_parserListener = parserListener;

			Text = m_cache.ProjectId.UiName + " - " + Text;
			SetRootSite();
			SetFontInfo();
			// restore window location and size after setting up the form textbox, because it might adjust size of
			// window causing the window to grow every time it is opened
			m_persistProvider.RestoreWindowSettings(PersistProviderID, this);
			if (wordform == null)
				GetLastWordUsed();
			else
				SetWordToUse(wordform.Form.VernacularDefaultWritingSystem.Text);

			m_webPageInteractor = new WebPageInteractor(m_htmlControl, m_mediator, m_wordformTextBox);
#if !__MonoCS__
			m_htmlControl.Browser.ObjectForScripting = m_webPageInteractor;
#endif

			// HermitCrab does not currently support selected tracing
			/*if (m_cache.LangProject.MorphologicalDataOA.ActiveParser == "HC")
			{
				m_parserCanDoSelectMorphs = false;
				m_doSelectMorphsCheckBox.Enabled = false;
			}
*/
			// No such thing as FwApp.App now: if(FwApp.App != null) // Could be null during testing
			if (m_mediator.HelpTopicProvider != null) // trying this
			{
				m_helpProvider.HelpNamespace = m_mediator.HelpTopicProvider.HelpFile;
				m_helpProvider.SetHelpKeyword(this, m_mediator.HelpTopicProvider.GetHelpString(HelpTopicID));
				m_helpProvider.SetHelpNavigator(this, HelpNavigator.Topic);
			}

			if (m_parserListener.Connection != null)
			{
				m_parserListener.Connection.TryAWordDialogIsRunning = true;
				m_statusLabel.Text = GetString("ParserStatusPrefix") + ParserUIStrings.ksIdle_ + GetString("ParserStatusSuffix");
			}
			else
			{
				m_statusLabel.Text = ParserStoppedMessage();
			}
		}
			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;
			}
예제 #53
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds an occurrence to and old-style sense.
		/// </summary>
		/// <param name="term">The ChkTerm (a sense or subsense).</param>
		/// <param name="reference">The Scripture reference.</param>
		/// <param name="wordform">The wordform.</param>
		/// <param name="keyword">The keyword (transliterated from Greek)</param>
		/// <returns>The newly added ChkRef</returns>
		/// ------------------------------------------------------------------------------------
		protected ChkRef AddOccurrenceToOldStyleSense(ChkTerm term, int reference,
			IWfiWordform wordform, string keyword)
		{
			return AddOccurrenceToOldStyleSense(term, reference, wordform, keyword,
				(wordform == null) ? KeyTermRenderingStatus.Unassigned : KeyTermRenderingStatus.Assigned);
		}
예제 #54
0
		/// <summary>
		/// Despite being public where the other SetDlgInfo is internal, this is a "special-case"
		/// initialization method not used in Flex, but in TE, where there is not a pre-existing mediator
		/// for each main window. This initializer obtains the configuration parameters and sets up a
		/// suitable mediator. In doing so it duplicates knowledge from various places:
		/// 1. Along with the code that initializes xWindow and various other places, it 'knows' where
		/// to find the configuration node for the respeller dialog.
		/// 2. It duplicates some of the logic in FwXWindow.InitMediatorValues and RestoreProperties,
		/// knowing the LocalSettingsId and how to use it to restore mediator properties, and what items
		/// must be in the mediator. Also logic in xWindow for restoring global settings.
		/// 3. It knows how to initialize a number of virtual properties normally created as part of
		/// FLEx's startup code.
		/// 4. It knows how to set up the string table that Flex uses.
		/// 5. It knows how to initialize the Flex part inventories.
		/// </summary>
		public bool SetDlgInfo(IWfiWordform wf, Form parent, IApp app)
		{
			if (wf == null)
				throw new ArgumentNullException("wf");
			if (parent == null)
				throw new ArgumentNullException("parent");
			if (app == null)
				throw new ArgumentNullException("app");

			using (var dlg = new ProgressDialogWorkingOn())
			{
				dlg.Owner = parent;
				dlg.Text = MEStrings.ksFindingOccurrences;
				dlg.WorkingOnText = MEStrings.ksSearchingOccurrences;
				dlg.ProgressLabel = MEStrings.ksProgress;
				dlg.Show(ActiveForm);
				dlg.Update();
				dlg.BringToFront();
				//var progressState = new MilestoneProgressState(dlg.ProgressDisplayer);
				try
				{
					m_cache = wf.Cache;
					m_srcwfiWordform = wf;
					// Get the parameter node.
					var path = Path.Combine(FwDirectoryFinder.GetCodeSubDirectory(
						Path.Combine(FwUtils.ksFlexAppName, Path.Combine("Configuration", "Words"))), "areaConfiguration.xml");
					var doc = XWindow.LoadConfigurationWithIncludes(path, true);
					var paramNode = doc.DocumentElement.SelectSingleNode("listeners/listener[@class=\"SIL.FieldWorks.XWorks.MorphologyEditor.RespellerDlgListener\"]/parameters");
					Debug.Assert(paramNode != null);
					// Initialize a mediator.
					var mediator = new Mediator();
					m_fDisposeMediator = true;
					// Copied from FwXWindow.InitMediatorValues
					mediator.PropertyTable.LocalSettingsId = "local";
					mediator.PropertyTable.SetProperty("cache", m_cache);
					mediator.PropertyTable.SetPropertyPersistence("cache", false);

					string userPath = DirectoryFinder.UserAppDataFolder(app.ApplicationName);
					Directory.CreateDirectory(userPath);
					mediator.PropertyTable.UserSettingDirectory = userPath;

					//// Enhance JohnT: possibly these three lines (also copied) are not needed.
					//mediator.PropertyTable.SetProperty("DocumentName", GetMainWindowCaption(cache));
					//mediator.PropertyTable.SetPropertyPersistence("DocumentName", false);
					mediator.PathVariables["{DISTFILES}"] = FwDirectoryFinder.CodeDirectory;
					mediator.PropertyTable.RestoreFromFile(mediator.PropertyTable.GlobalSettingsId);
					mediator.PropertyTable.RestoreFromFile(mediator.PropertyTable.LocalSettingsId);
					//progressState.SetMilestone();
					// Set this AFTER the restore! Otherwise it goes away!
					mediator.PropertyTable.SetProperty("window", dlg.Owner);
					mediator.PropertyTable.SetPropertyPersistence("window", false);

					string directoryContainingConfiguration = Path.Combine(FwDirectoryFinder.FlexFolder, "Configuration");
					StringTable table = new StringTable(directoryContainingConfiguration);
					mediator.StringTbl = table;
					mediator.FeedbackInfoProvider = (IFeedbackInfoProvider)app;
					//progressState.SetMilestone();
					//progressState.SetMilestone();

					LayoutCache.InitializePartInventories(m_cache.ProjectId.Name, app, m_cache.ProjectId.ProjectFolder);
					//progressState.SetMilestone();

					// Get all the scripture texts.
					// Review: should we include IText ones too?
					// NB: The ownership check is designed to exclude archived drafts.
					// The second half collects footnotes and the title of the book.
					var stTextRepos = m_cache.ServiceLocator.GetInstance<IStTextRepository>();
					var unarchivedScriptureTexts = m_cache.LangProject.TranslatedScriptureOA.StTexts.ToList();
					//progressState.SetMilestone();

					// Build concordance info, including the occurrence list for our wordform.
					ProgressState state = new ProgressState(dlg.ProgressDisplayer);
					// This is an ugly way of getting the state to the RespellingSda method
					mediator.PropertyTable.SetProperty("SpellingPrepState", state);
					mediator.PropertyTable.SetPropertyPersistence("SpellingPrepState", false);
					NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor,
						() =>
							{
								int done = 0;
								int total = unarchivedScriptureTexts.Count;
								foreach (var txt in unarchivedScriptureTexts)
								{
									done++;
									foreach (IStTxtPara para in txt.ParagraphsOS)
									{
										if (para.ParseIsCurrent)
											continue;
										ParagraphParser.ParseParagraph(para, true);
									}
									state.PercentDone = 50*done/total;
									state.Breath();
								}
							});
					// Make sure we will include all of Scripture in the occurrences list.
					InterestingTextList.SetScriptureTextsInPropertyTable(mediator.PropertyTable, unarchivedScriptureTexts);

					return SetDlgInfoPrivate(mediator, paramNode);
				}
				finally
				{
					dlg.Close();
				}
			}
		}
예제 #55
0
		/// <summary>
		///
		/// </summary>
		/// <param name="owner"></param>
		/// <param name="glossFactory">For creating a gloss for the first in analysis.Meanings</param>
		/// <returns></returns>
		public IWfiAnalysis Create(IWfiWordform owner, IWfiGlossFactory glossFactory)
		{
			var waNew = Create();
			owner.AnalysesOC.Add(waNew);
			var newGloss = glossFactory.Create();
			waNew.MeaningsOC.Add(newGloss);
			return waNew;
		}
예제 #56
0
		private void SetOldOccurrencesOfWordforms(int flidOccurrences, IWfiWordform wfOld, IWfiWordform wfNew)
		{
			OldWordform = wfOld.Hvo;
			m_oldOccurrencesOldWf = m_specialSda.VecProp(wfOld.Hvo, flidOccurrences);
			m_fWasOldSpellingCorrect = wfOld.SpellingStatus == (int)SpellingStatusStates.correct;

			NewWordform = wfNew.Hvo;
			m_oldOccurrencesNewWf = m_specialSda.VecProp(wfNew.Hvo, flidOccurrences);
			m_fWasNewSpellingCorrect = wfNew.SpellingStatus == (int)SpellingStatusStates.correct;
		}
예제 #57
0
		private void DeleteWordformIfPossible(IWfiWordform oldWordform)
		{
			if (oldWordform.CanDelete)
				((ICmObjectInternal)oldWordform).DeleteObject();
		}
예제 #58
0
		private void SetSpellingStatus(IWfiWordform wfNew)
		{
			wfNew.SpellingStatus = (int)SpellingStatusStates.correct;
			SpellingHelper.SetSpellingStatus(NewSpelling, m_vernWs,
				m_cache.LanguageWritingSystemFactoryAccessor, true);
		}
예제 #59
0
		internal IAnalysis GetGuessForWordform(IWfiWordform wf, int ws)
		{
			if (m_vc != null)
				return m_vc.GetGuessForWordform(wf, ws);
			return null;
		}
예제 #60
0
		public void ScheduleOneWordformForUpdate(IWfiWordform wordform, ParserPriority priority)
		{
			CheckDisposed();

			m_thread.EnqueueWork(priority, new UpdateWordformWork(this, priority, wordform));
		}