Exemplo n.º 1
0
            public override void Write(LoadException le)
            {
                m_xmlWriter.WriteStartElement("Error");
                switch (le.ErrorType)
                {
                case LoadException.LoadErrorType.INVALID_ENTRY_SHAPE:
                    var      entryShape = le.Data["shape"] as string;
                    var      entryId    = le.Data["entry"] as string;
                    LexEntry entry      = le.Loader.CurrentMorpher.Lexicon.GetEntry(entryId);
                    m_xmlWriter.WriteString(string.Format(ParserCoreStrings.ksHCInvalidEntryShape, entryShape, entry.Description));
                    break;

                case LoadException.LoadErrorType.INVALID_RULE_SHAPE:
                    var ruleShape          = le.Data["shape"] as string;
                    var ruleId             = le.Data["rule"] as string;
                    MorphologicalRule rule = le.Loader.CurrentMorpher.GetMorphologicalRule(ruleId);
                    m_xmlWriter.WriteString(string.Format(ParserCoreStrings.ksHCInvalidRuleShape, ruleShape, rule.Description));
                    break;

                default:
                    m_xmlWriter.WriteString(string.Format(ParserCoreStrings.ksHCDefaultErrorMsg, le.Message));
                    break;
                }
                m_xmlWriter.WriteEndElement();
            }
Exemplo n.º 2
0
        private void LoadSimpleList(string path)
        {
            using (TextReader r = File.OpenText(path))
            {
                do
                {
                    string s = r.ReadLine();
                    if (s == null)
                    {
                        break;
                    }
                    s = s.Trim();

                    if (!string.IsNullOrEmpty(s))                    //skip blank lines
                    {
                        var entry = new LexEntry();
                        entry.LexicalForm.SetAlternative(_preferredPromptingWritingSystemId, s);
                        var sense = new LexSense(entry);
                        if (_glossMeaningField)
                        {
                            sense.Gloss.SetAlternative(_preferredPromptingWritingSystemId, s);
                        }
                        else
                        {
                            sense.Definition.SetAlternative(_preferredPromptingWritingSystemId, s);
                        }
                        entry.Senses.Add(sense);
                        _words.Add(entry);
                    }
                }while (true);
            }
        }
Exemplo n.º 3
0
        public void Setup()
        {
            WeSayProjectTestHelper.InitializeForTests();

            _tempFolder         = new TemporaryFolder();
            _filePath           = _tempFolder.GetTemporaryFile();
            _lexEntryRepository = new LexEntryRepository(_filePath);

            _target = CreateEntry("one", "single item");
            _source = CreateEntry("single", "one item");

            CreateEntry("verde", "green");
            CreateEntry("amarelho", "yellow");
            CreateEntry("azul", "blue");

            _synonymsRelationField = new Field("synonyms",
                                               "LexEntry",
                                               new string[] { WritingSystemsIdsForTests.OtherIdForTest },
                                               Field.MultiplicityType.ZeroOrMore,
                                               "RelationToOneEntry");
            _synonymsRelationType = new LexRelationType("synonyms",
                                                        LexRelationType.Multiplicities.Many,
                                                        LexRelationType.TargetTypes.Sense);

            _singleSynonymRelationField = new Field("synonym",
                                                    "LexEntry",
                                                    new string[] { WritingSystemsIdsForTests.OtherIdForTest },
                                                    Field.MultiplicityType.ZeroOr1,
                                                    "RelationToOneEntry");
            _singleSynonymRelationType = new LexRelationType("synonym",
                                                             LexRelationType.Multiplicities.One,
                                                             LexRelationType.TargetTypes.Sense);
        }
Exemplo n.º 4
0
        public override void FixtureSetup()
        {
            string partDirectory = Path.Combine(SIL.FieldWorks.Common.Utils.DirectoryFinder.FwSourceDirectory,
                                                @"common\controls\detailcontrols\detailcontrolstests");
            Dictionary <string, string[]> keyAttrs = new Dictionary <string, string[]>();

            keyAttrs["layout"] = new string[] { "class", "type", "name" };
            keyAttrs["group"]  = new string[] { "label" };
            keyAttrs["part"]   = new string[] { "ref" };

            string configurationDir = Path.Combine(SIL.FieldWorks.Common.Utils.DirectoryFinder.FWCodeDirectory,
                                                   @"Language Explorer\Configuration");

            m_stringTable = new SIL.Utils.StringTable(configurationDir);

            m_layouts = new Inventory(new string[] { partDirectory },
                                      "*Layouts.xml", "/LayoutInventory/*", keyAttrs);

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

            m_parts = new Inventory(new string[] { partDirectory },
                                    "*Parts.xml", "/PartInventory/bin/*", keyAttrs);

            m_cache = FdoCache.Create("TestLangProj");

            m_entry = new LexEntry();
            m_cache.LangProject.LexDbOA.EntriesOC.Add(m_entry);
            m_entry.CitationForm.VernacularDefaultWritingSystem = "rubbish";
            // We set both alternatives because currently the default part for Bibliography uses vernacular,
            // but I think this will probably get fixed. Anyway, this way the test is robust.
            m_entry.Bibliography.SetAnalysisDefaultWritingSystem("My rubbishy bibliography");
            m_entry.Bibliography.SetVernacularDefaultWritingSystem("My rubbishy bibliography");
        }
Exemplo n.º 5
0
        /// <summary> Adds pronunciation audio of a word to be written out to lift </summary>
        private void AddAudio(LexEntry entry, Word wordEntry, string path)
        {
            foreach (var audioFile in wordEntry.Audio)
            {
                var lexPhonetic = new LexPhonetic();

                var util = new Utilities();

                var projectPath = Path.Combine(util.GenerateFilePath(
                                                   Utilities.FileType.Dir, true, "", ""), _projectId);
                projectPath = Path.Combine(projectPath, "Import", "ExtractedLocation");
                var extractedDir = Directory.GetDirectories(projectPath);
                projectPath = Path.Combine(projectPath, extractedDir.Single());
                var src = Path.Combine(util.GenerateFilePath(
                                           Utilities.FileType.Audio, true), Path.Combine(projectPath, "audio", audioFile));
                var dest = Path.Combine(path, audioFile);

                if (File.Exists(src))
                {
                    File.Copy(src, dest, true);

                    var proMultiText = new LiftMultiText {
                        { "href", dest }
                    };
                    lexPhonetic.MergeIn(MultiText.Create(proMultiText));
                    entry.Pronunciations.Add(lexPhonetic);
                }
            }
        }
Exemplo n.º 6
0
        private void OnRecordPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            VerifyNotDisposed();
            LexEntry entry = (LexEntry)sender;

            switch (e.PropertyName)
            {
            // these are changes to the list not a change that needs to clean up
            // and can actually have very detrimental effect if we do.
            case "exampleSentences":
            case "senses":
                break;

            default:
                //this is to fix WS-238. The scenario is this:
                //a paste operation starts by erasing the target... this fired off a cleanup
                //and then the new text came in so fast that we got various crashes.
                //With this, we just schedule a cleanup, as a ui event handler, for
                //a moment in the future.  The interval is chosen to allow even a quick
                //backspace followed by typing, without wiping out the sense/example.
                if (_cleanupTimer == null)
                {
                    _cleanupTimer          = new Timer();
                    _cleanupTimer.Tick    += OnCleanupTimer_Tick;
                    _cleanupTimer.Interval = 500;
                }
                _cleanupTimer.Tag = entry;
                _cleanupTimer.Stop();                        //reset it
                _cleanupTimer.Start();
                break;
            }
            _lexEntryRepository.NotifyThatLexEntryHasBeenUpdated((LexEntry)sender);
            // can't afford to do this every keystroke, with large files
        }
Exemplo n.º 7
0
        public void NotifyThatLexEntryHasBeenUpdated_LexEntryDoesNotExistInRepository_Throws()
        {
            var entryToUpdate = new LexEntry();

            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        _repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate));
        }
Exemplo n.º 8
0
        public void ExampleTranslations_FreeFollowedByUnmarked()
        {
            LexEntry e     = MakeSimpleEntry();
            LexSense sense = new LexSense();

            e.Senses.Add(sense);
            LexExampleSentence ex = new LexExampleSentence();

            sense.ExampleSentences.Add(ex);

            LiftMultiText t2 = new LiftMultiText();

            t2.Add("aa", "freestuff");
            _builder.MergeInTranslationForm(ex,
                                            "Free translation",
                                            t2,
                                            "<translation type='free'><bogus/></translation>");
            LiftMultiText translation = new LiftMultiText();

            translation.Add("aa", "unmarked translation");
            _builder.MergeInTranslationForm(ex,
                                            "",
                                            translation,
                                            "<translation><bogusUnmarked/></translation>");
            _builder.FinishEntry(e);

            _liftWriter.Add(e);
            _liftWriter.End();
            AssertHasAtLeastOneMatch("//entry/sense/example/translation[not(@type)]/bogusUnmarked");
            AssertHasAtLeastOneMatch(
                "//entry/sense/example/translation[@type='Free translation']/form/text[text()='freestuff']");
        }
Exemplo n.º 9
0
        private static void RenderSense(LexEntry entry, LexSense sense, int senseNumber, CurrentItemEventArgs currentItem, StringBuilder html)
        {
            Field glossField = WeSayWordsProject.Project.GetFieldFromDefaultViewTemplate(LexSense.WellKnownProperties.Gloss);

            if (entry.Senses.Count > 1 ||
                (currentItem != null &&
                 ((glossField.IsMeaningField && currentItem.PropertyName == LexSense.WellKnownProperties.Gloss) ||
                  (!glossField.IsMeaningField && currentItem.PropertyName == LexSense.WellKnownProperties.Definition))
                ))
            {
                html.Append(" " + senseNumber);
            }

            RenderPartOfSpeech(sense, currentItem, html);

            // Render the Gloss/Definition (meaning) field
            if (glossField.IsMeaningField)
            {
                html.Append(" " + RenderField(sense.Gloss, currentItem, 0, glossField));
            }
            else
            {
                Field dfnField = WeSayWordsProject.Project.GetFieldFromDefaultViewTemplate(LexSense.WellKnownProperties.Definition);
                html.Append(" " + RenderField(sense.Definition, currentItem, 0, dfnField));
            }

            RenderExampleSentences(currentItem, html, sense);

            html.Append(RenderGhostedField(sense, "Sentence", currentItem, null));
            html.Append(RenderGhostedField(sense, "Translation", currentItem, null));
        }
Exemplo n.º 10
0
		public static bool TryMergeEntries(LexEntry entry1, LexEntry entry2, string[] traitsWithMultiplicity, IProgress progress)
		{
			if (!entry1.LexicalForm.CanBeUnifiedWith(entry2.LexicalForm))
			{
				progress.WriteMessageWithColor("gray","Attempting to merge entries, but could not because their Lexical Forms clash in some writing system.");
				return false;
			}

			if (!SenseMerger.TryMergeProperties(entry1, entry2, traitsWithMultiplicity, "entries for "+entry1.ToString(), progress))
				return false;

			// at this point, we're committed to doing the merge

			entry1.LexicalForm.MergeIn(entry2.LexicalForm);

			var senses = entry2.Senses.ToArray();
			foreach (var sense in senses)
			{
				MergeOrAddSense(entry1, sense, traitsWithMultiplicity, progress);
			}

			if (entry2.ModificationTime > entry1.ModificationTime)
			{
				entry1.ModificationTime = entry2.ModificationTime;
			}

			entry1.IsDirty = true;
			return true;
		}
Exemplo n.º 11
0
        private static void AddTranslationToEntry(LexEntry entry, string translation)
        {
            LexSense           sense   = entry.Senses[0];
            LexExampleSentence example = sense.ExampleSentences[0];

            example.Translation[WritingSystemsIdsForTests.AnalysisIdForTest] = translation;
        }
Exemplo n.º 12
0
        private static void RenderHeadword(LexEntry entry,
                                           StringBuilder html,
                                           LexEntryRepository lexEntryRepository)
        {
            if (StartNewSpan(html, HeadWordWritingSystemId, true, false, 0))
            {
                LanguageForm headword = entry.GetHeadWord(HeadWordWritingSystemId);
                if (null != headword)
                {
                    var str = MakeSafeForHtmlAndFormat(headword.Form);
                    html.Append(str);

                    int homographNumber = lexEntryRepository.GetHomographNumber(
                        entry,
                        WeSayWordsProject.Project.DefaultViewTemplate.HeadwordWritingSystem
                        );
                    if (homographNumber > 0)
                    {
                        html.Append("<sub>" + homographNumber.ToString() + "</sub>");
                    }
                }
                else
                {
                    html.Append("??? ");
                }
                html.Append(" </span>");
            }
        }
Exemplo n.º 13
0
        public void GetOrMakeEntry_ReturnedLexEntryIsDirty()
        {
            Extensible extensibleInfo = new Extensible();
            LexEntry   entry          = _builder.GetOrMakeEntry(extensibleInfo, 0);

            Assert.IsTrue(entry.IsDirty);
        }
        public void NoExamples()
        {
            LexEntry entry = new LexEntry();

            entry.Senses.Add(new LexSense());
            Assert.AreEqual(true, _missingExampleSentenceFilter.FilteringPredicate(entry));
        }
Exemplo n.º 15
0
        public void LexicalFormWritingSystemNoVernacular()
        {
            LexEntry entry = new LexEntry();

            entry.LexicalForm["analysis"] = "filler";
            Assert.AreEqual(true, _missingLexicalFormFilter.FilteringPredicate(entry));
        }
Exemplo n.º 16
0
        private static void RenderHeadword(LexEntry entry,
                                           StringBuilder rtf,
                                           LexEntryRepository lexEntryRepository)
        {
            rtf.Append(@"{\b ");
            LanguageForm headword = entry.GetHeadWord(HeadWordWritingSystemId);

            if (null != headword)
            {
                // rtf.Append(RenderField(headword, currentItem, 2, null));

                rtf.Append(SwitchToWritingSystem(headword.WritingSystemId, 2));
                rtf.Append(headword.Form);
                //   rtf.Append(" ");

                int homographNumber = lexEntryRepository.GetHomographNumber(
                    entry,
                    WeSayWordsProject.Project.DefaultViewTemplate.HeadwordWritingSystem
                    );
                if (homographNumber > 0)
                {
                    rtf.Append(@"{\sub " + homographNumber + "}");
                }
            }
            else
            {
                rtf.Append("??? ");
            }
            rtf.Append("}");
        }
Exemplo n.º 17
0
 /// <summary> Adds vernacular of a word to be written out to lift </summary>
 private static void AddVern(LexEntry entry, Word wordEntry, string vernacularBcp47)
 {
     entry.LexicalForm.MergeIn(MultiText.Create(
                                   new LiftMultiText {
         { vernacularBcp47, wordEntry.Vernacular }
     }));
 }
Exemplo n.º 18
0
        private static void RenderSense(LexEntry entry, LexSense sense, int senseNumber, CurrentItemEventArgs currentItem, StringBuilder rtf)
        {
//rtf.Append(SwitchToWritingSystem(WritingSystems.AnalysisWritingSystemDefault.Id));
#if GlossMeaning
            if (entry.Senses.Count > 1 || (currentItem != null && currentItem.PropertyName == "Gloss"))
#else
            if (entry.Senses.Count > 1 ||
                (currentItem != null &&
                 currentItem.PropertyName == LexSense.WellKnownProperties.Definition))
#endif
            {
                rtf.Append(" " + senseNumber);
            }

            RenderPartOfSpeech(sense, currentItem, rtf);
#if GlossMeaning
            rtf.Append(" " + RenderField(sense.Gloss, currentItem));
#else
            // Render the Definition (meaning) field
            Field dfnField = WeSayWordsProject.Project.GetFieldFromDefaultViewTemplate(
                LexSense.WellKnownProperties.Definition);
            rtf.Append(" " + RenderField(sense.Definition, currentItem, 0, dfnField));
#endif
            //                rtf.Append(@"\i0 ");

            RenderExampleSentences(currentItem, rtf, sense);

            rtf.Append(RenderGhostedField(sense, "Sentence", currentItem, null));
            rtf.Append(RenderGhostedField(sense, "Translation", currentItem, null));
        }
Exemplo n.º 19
0
        public static bool TryMergeEntries(LexEntry entry1, LexEntry entry2, string[] traitsWithMultiplicity, IProgress progress)
        {
            if (!entry1.LexicalForm.CanBeUnifiedWith(entry2.LexicalForm))
            {
                progress.WriteMessageWithColor("gray", "Attempting to merge entries, but could not because their Lexical Forms clash in some writing system.");
                return(false);
            }

            if (!SenseMerger.TryMergeProperties(entry1, entry2, traitsWithMultiplicity, "entries for " + entry1.ToString(), progress))
            {
                return(false);
            }

            // at this point, we're committed to doing the merge

            entry1.LexicalForm.MergeIn(entry2.LexicalForm);

            var senses = entry2.Senses.ToArray();

            foreach (var sense in senses)
            {
                MergeOrAddSense(entry1, sense, traitsWithMultiplicity, progress);
            }

            if (entry2.ModificationTime > entry1.ModificationTime)
            {
                entry1.ModificationTime = entry2.ModificationTime;
            }

            entry1.IsDirty = true;
            return(true);
        }
Exemplo n.º 20
0
        public void Reversal_Complex()
        {
            LexEntry e   = MakeSimpleEntry();
            string   xml =
                @"  <entry id='utan'>
				<sense id='utan_'>
				  <grammatical-info value='n'/>
				  <reversal type='eng'>
					<form lang='en'>
					  <text>mushroom</text>
					</form>
					<main>
					  <form lang='en'>
						<text>vegetable</text>
					  </form>
					</main>
				  </reversal>
				</sense>
			  </entry>"            ;

            LexSense sense = new LexSense();

            e.Senses.Add(sense);
            _builder.MergeInReversal(sense, null, null, null, xml);
            _builder.FinishEntry(e);

            _liftWriter.Add(e);
            _liftWriter.End();
            AssertHasAtLeastOneMatch("//entry/sense/reversal/main/form/text[text()='vegetable']");
            AssertHasAtLeastOneMatch("//entry/sense/reversal/form/text[text()='mushroom']");
        }
        /// <summary>
        /// Given a (potentially) owning object, and the flid in which is does/will own
        /// the feature structure, find the relevant POS.
        /// </summary>
        /// <param name="cobj"></param>
        /// <param name="owningFlid"></param>
        /// <returns></returns>
        private IPartOfSpeech GetPosFromCmObjectAndFlid(ICmObject cobj, int owningFlid)
        {
            IPartOfSpeech pos = null;

            switch (cobj.ClassID)
            {
            case MoInflAffMsa.kclsidMoInflAffMsa:
                IMoInflAffMsa infl = cobj as IMoInflAffMsa;
                if (infl != null)
                {
                    pos = infl.PartOfSpeechRA;
                }
                break;

            case MoDerivAffMsa.kclsidMoDerivAffMsa:
                IMoDerivAffMsa deriv = cobj as IMoDerivAffMsa;
                if (deriv != null)
                {
                    if (owningFlid == (int)MoDerivAffMsa.MoDerivAffMsaTags.kflidFromMsFeatures)
                    {
                        pos = deriv.FromPartOfSpeechRA;
                    }
                    else if (owningFlid == (int)MoDerivAffMsa.MoDerivAffMsaTags.kflidToMsFeatures)
                    {
                        pos = deriv.ToPartOfSpeechRA;
                    }
                }
                break;

            case MoStemMsa.kclsidMoStemMsa:
                IMoStemMsa stem = cobj as IMoStemMsa;
                if (stem != null)
                {
                    pos = stem.PartOfSpeechRA;
                }
                break;

            case MoStemName.kclsidMoStemName:
                IMoStemName sn = cobj as IMoStemName;
                pos = PartOfSpeech.CreateFromDBObject(sn.Cache, sn.OwnerHVO);
                break;

            case MoAffixAllomorph.kclsidMoAffixAllomorph:
                // get entry of the allomorph and then get the msa of first sense and return its (from) POS
                ILexEntry entry = LexEntry.CreateFromDBObject(m_cache, cobj.OwnerHVO);
                if (entry == null)
                {
                    return(pos);
                }
                ILexSense sense = entry.SensesOS.FirstItem;
                if (sense == null)
                {
                    return(pos);
                }
                IMoMorphSynAnalysis msa = sense.MorphoSyntaxAnalysisRA;
                pos = GetPosFromCmObjectAndFlid(msa, (int)MoDerivAffMsa.MoDerivAffMsaTags.kflidFromMsFeatures);
                break;
            }
            return(pos);
        }
Exemplo n.º 22
0
        internal int AddWidgets(LexEntry entry, int insertAtRow)
        {
            DetailList.SuspendLayout();
            Debug.Assert(DetailList.RowCount == 0);
            Debug.Assert(DetailList.ColumnCount == 3);
            Debug.Assert(DetailList.RowStyles.Count == 0);
            FirstRow = 0;
            int   rowCount = 0;
            Field field    = ActiveViewTemplate.GetField(Field.FieldNames.EntryLexicalForm.ToString());

            if (field != null && field.GetDoShow(entry.LexicalForm, ShowNormallyHiddenFields))
            {
                Control formControl = MakeBoundControl(entry.LexicalForm, field);
                DetailList.AddWidgetRow(StringCatalog.Get(field.DisplayName),
                                        true,
                                        formControl,
                                        insertAtRow,
                                        false);
                insertAtRow = DetailList.GetRow(formControl);
                ++rowCount;
            }
            rowCount += AddCustomFields(entry, insertAtRow + rowCount);

            var rowCountBeforeSenses = rowCount;

            LastRow = insertAtRow + rowCount;
            foreach (var lexSense in entry.Senses)
            {
                var layouter = new LexSenseLayouter(
                    DetailList,
                    rowCount,
                    ActiveViewTemplate,
                    RecordListManager,
                    _serviceProvider,
                    lexSense
                    )
                {
                    ShowNormallyHiddenFields = ShowNormallyHiddenFields,
                    Deletable             = _sensesAreDeletable,
                    ShowMinorMeaningLabel = ShowMinorMeaningLabel,
                    ParentLayouter        = this
                };
                layouter.DeleteClicked += OnSenseDeleteClicked;
                rowCount += AddChildrenWidgets(layouter, lexSense, rowCount);
                ChildLayouts.Add(layouter);
            }

            //see: WS-1120 Add option to limit "add meanings" task to the ones that have a semantic domain
            //also: WS-639 ([email protected]) In Add meanings, don't show extra meaning slots just because a sense was created for the semantic domain
            var ghostingRule = ActiveViewTemplate.GetGhostingRuleForField(LexEntry.WellKnownProperties.Sense);

            if (rowCountBeforeSenses == rowCount || ghostingRule.ShowGhost)
            {
                AddSenseGhost(entry, rowCount);
                rowCount++;
            }

            DetailList.ResumeLayout(false);
            return(rowCount);
        }
Exemplo n.º 23
0
        private Guid AddEntry(string lexemeForm,
                              string meaningWritingSystemId,
                              string meaning,
                              bool includeExample)
        {
            LexEntry entry = _lexEntryRepository.CreateItem();

            entry.LexicalForm.SetAlternative("th", lexemeForm);

            LexSense sense = new LexSense();

            entry.Senses.Add(sense);
#if GlossMeaning
            sense.Gloss[
                WeSayWordsProject.Project.DefaultViewTemplate.GetField("SenseGloss").WritingSystemIds[0]] =
                meaning;
#else
            sense.Definition.SetAlternative(meaningWritingSystemId, meaning);
#endif
            if (includeExample)
            {
                LexExampleSentence ex = new LexExampleSentence();
                sense.ExampleSentences.Add(ex);
                ex.Sentence.SetAlternative("th", "hello");
            }
            _lexEntryRepository.SaveItem(entry);
            return(entry.Guid);
        }
Exemplo n.º 24
0
        public void ExampleTranslations_MultipleTypes()
        {
            LexEntry e     = MakeSimpleEntry();
            LexSense sense = new LexSense();

            e.Senses.Add(sense);
            LexExampleSentence ex = new LexExampleSentence();

            sense.ExampleSentences.Add(ex);
            LiftMultiText translation = new LiftMultiText();

            translation.Add("aa", "unmarked translation");
            _builder.MergeInTranslationForm(ex, "", translation, "bogus raw xml");
            LiftMultiText t2 = new LiftMultiText();

            t2.Add("aa", "type2translation");
            _builder.MergeInTranslationForm(ex,
                                            "type2",
                                            t2,
                                            "<translation type='type2'><bogus/></translation>");
            _builder.FinishEntry(e);

            _liftWriter.Add(e);
            _liftWriter.End();
            AssertHasAtLeastOneMatch(
                "//entry/sense/example/translation[not(@type)]/form[@lang='aa']/text[text()='unmarked translation']");
            AssertHasAtLeastOneMatch("//entry/sense/example/translation[@type='type2']/bogus");
        }
Exemplo n.º 25
0
        public void DeleteWordWhenEvenHasCleanup_Regression()
        {
            AddInitialEntries();
            ClickAddWord();
            int before = _lexEntryRepository.CountAllItems();

            EntryViewControl parentControl =
                ((DictionaryControl)_task.Control).Control_EntryDetailPanel;
            LexEntry     entry = parentControl.DataSource;
            const string form  = "xx";

            entry.LexicalForm.SetAlternative(_vernacularWritingSystem.Id, form);
            GoToLexicalEntryUseFind("Initial");        //go away
            GoToLexicalEntryUseFind(form);             //come back

            var item2 = new KeyValuePair <string, IPalasoDataObjectProperty>("test", new LexRelation("b", "bbb", entry));

            entry.Properties.Add(item2);

            GetEditControl("*EntryLexicalForm").FocusOnFirstWsAlternative();
            DeleteWord();
            Assert.AreEqual(before - 1, _lexEntryRepository.CountAllItems());
            // GoToLexicalEntryUseFind(form); should fail to find it

            AssertExistenceOfEntryInList(form, false);
        }
Exemplo n.º 26
0
        /// <summary> Adds each sense of a word to be written out to lift </summary>
        private void AddSenses(LexEntry entry, Word wordEntry)
        {
            for (var i = 0; i < wordEntry.Senses.Count; i++)
            {
                // Merge in senses
                var dict = new Dictionary <string, string>();
                foreach (var gloss in wordEntry.Senses[i].Glosses)
                {
                    dict.Add(gloss.Language, gloss.Def);
                }

                var lexSense = new LexSense();
                lexSense.Gloss.MergeIn(MultiTextBase.Create(dict));
                entry.Senses.Add(lexSense);

                // Merge in semantic domains
                foreach (var semdom in wordEntry.Senses[i].SemanticDomains)
                {
                    var orc = new OptionRefCollection();
                    orc.Add(semdom.Id + " " + semdom.Name);

                    entry.Senses[i].Properties.Add(
                        new KeyValuePair <string, IPalasoDataObjectProperty>("semantic-domain-ddp4", orc));
                }
            }
        }
Exemplo n.º 27
0
        private void EnsureHasOneEntryProperty()
        {
            LexEntry entry = GetCurrentEntry();

            entry.CleanUpAfterEditting();
            Assert.AreEqual(1, entry.Properties.Count);
        }
Exemplo n.º 28
0
        public void HiddenFields_AreNotOutput()
        {
            using (var environment = new EnvironmentForTest())
            {
                LexEntry e1 = environment.Repo.CreateItem();
                e1.LexicalForm[EnvironmentForTest.Green] = "sunset";
                e1.GetOrCreateProperty <MultiText>("color").SetAlternative(environment.WritingSystemIds[0], EnvironmentForTest.Red);
                environment.Repo.SaveItem(e1);

                var color = new Field(
                    "color",
                    "LexEntry",
                    environment.WritingSystemIds,
                    Field.MultiplicityType.ZeroOr1,
                    "MultiText"
                    );
                color.DisplayName = "color";
                environment.Template.Add(color);

                environment.DoExport();
                environment.AssertHasAtLeastOneMatch("lift/entry[@id='" + e1.Id + "']/field[@type='" + "color" + "']");

                //now make it invisible and it should disappear
                environment.Template.GetField("color").Enabled = false;

                environment.DoExport();
                environment.AssertNoMatchForXPath("lift/entry[@id='" + e1.Id + "']/field");
            }
        }
Exemplo n.º 29
0
        public void EmptyProperitesRemovedAfterEditting()
        {
            AddInitialEntries();
            EntryViewControl parentControl =
                ((DictionaryControl)_task.Control).Control_EntryDetailPanel;
            LexEntry entry = parentControl.DataSource;

            Assert.Less(0,
                        entry.Properties.Count,
                        "the setup of this test should have some custom properties");
            TextBoxTester t = new TextBoxTester(GetLexicalFormControlName(), _window);

            t.Enter("test");
            Assert.Less(0,
                        entry.Properties.Count,
                        "the setup of this test should have some custom properties");

            //cycle out this record
            parentControl.DataSource = _lexEntryRepository.CreateItem();

            Assert.AreEqual(0, entry.Properties.Count);
#if GlossMeaning
            Assert.AreEqual(0, entry.Senses[0].Properties.Count);
#else
            Assert.AreEqual(1, entry.Senses[0].Properties.Count);
            Assert.AreEqual(LexSense.WellKnownProperties.Definition,
                            entry.Senses[0].Properties[0].Key);
#endif
        }
Exemplo n.º 30
0
 /// <summary>
 /// Handle launching of the MSA editor.
 /// </summary>
 protected override void HandleChooser()
 {
     using (MsaCreatorDlg dlg = new MsaCreatorDlg())
     {
         MoMorphSynAnalysis originalMsa = m_obj as MoMorphSynAnalysis;
         ILexEntry          entry       = LexEntry.CreateFromDBObject(m_cache, originalMsa.OwnerHVO);
         dlg.SetDlgInfo(m_cache,
                        m_persistProvider,
                        m_mediator,
                        entry,
                        DummyGenericMSA.Create(originalMsa),
                        originalMsa.Hvo,
                        true,
                        String.Format(LexEdStrings.ksEditX, Slice.Label));
         if (dlg.ShowDialog(FindForm()) == DialogResult.OK)
         {
             DummyGenericMSA dummyMsa = dlg.DummyMSA;
             if (!originalMsa.EqualsMsa(dummyMsa))
             {
                 m_cache.BeginUndoTask(LexEdStrings.ksUndoEditFunction,
                                       LexEdStrings.ksRedoEditFunction);
                 // The UpdateOrReplace call may end up disposing this. So any variables we
                 // need after it must be copied to the stack.
                 FdoCache            cache  = m_cache;
                 Slice               parent = Slice;
                 IMoMorphSynAnalysis newMsa = originalMsa.UpdateOrReplace(dummyMsa);
                 cache.EndUndoTask();
             }
         }
     }
 }
Exemplo n.º 31
0
 public void CheckRelationOutput(LexEntry targetEntry, string relationName)
 {
     AssertHasAtLeastOneMatchWithArgs("lift/entry/relation/field[@type='headword-of-target']/form[@lang='{1}']/text[text() = '{2}']",
                                      relationName,
                                      HeadwordWritingSystem.Id,
                                      targetEntry.GetHeadWordForm(HeadwordWritingSystem.Id));
 }
Exemplo n.º 32
0
			public void AddSenseWithSemanticDomainToLexEntry(LexEntry entry, string semanticDomain)
			{
				entry.Senses.Add(new LexSense());
				OptionRefCollection o =
					entry.Senses[1].GetOrCreateProperty<OptionRefCollection>(
						LexSense.WellKnownProperties.SemanticDomainDdp4);
				o.Add(semanticDomain);
				_repository.SaveItem(entry);
			}
Exemplo n.º 33
0
		private static void MergeOrAddSense(LexEntry targetEntry, LexSense incomingSense, string[] traitsWithMultiplicity, IProgress progress)
		{
			if (targetEntry.Senses.Count == 0)
			{
				targetEntry.Senses.Add(incomingSense);//no problem!
			}
			else
			{
				if (targetEntry.Senses.Count == 1)
				{
					var targetSense = targetEntry.Senses[0];
					if (SenseMerger.TryMergeSenseWithSomeExistingSense(targetSense, incomingSense, traitsWithMultiplicity, progress))
					{
						//it was merged in
						return;
					}
				}
			}
			//it needs to be added
			targetEntry.Senses.Add(incomingSense);
		}
		private void CreateThreeDifferentLexEntries(GetMultiTextFromLexEntryDelegate getMultiTextFromLexEntryDelegate)
		{
			LexEntry[] lexEntriesToSort = new LexEntry[3];
			MultiText[] propertyOfLexentry = new MultiText[3];

			lexEntriesToSort[0] = _repository.CreateItem();
			propertyOfLexentry[0] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[0]);
			propertyOfLexentry[0].SetAlternative("de", "de Word2");

			lexEntriesToSort[1] = _repository.CreateItem();
			propertyOfLexentry[1] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[1]);
			propertyOfLexentry[1].SetAlternative("de", "de Word3");

			lexEntriesToSort[2] = _repository.CreateItem();
			propertyOfLexentry[2] = getMultiTextFromLexEntryDelegate(lexEntriesToSort[2]);
			propertyOfLexentry[2].SetAlternative("de", "de Word1");

			_repository.SaveItem(lexEntriesToSort[0]);
			_repository.SaveItem(lexEntriesToSort[1]);
			_repository.SaveItem(lexEntriesToSort[2]);
		}
Exemplo n.º 35
0
		public override void Setup()
		{
			base.Setup();
			this.tabbedForm = new TabbedForm();
			this.tabbedForm.Show();
			string name = new Finder().Name(this.tabbedForm);
			_mainWindowTester = new FormTester(name);


			_project = new WeSayWordsProject();
			_project.StringCatalogSelector = "en";
			_project.LoadFromProjectDirectoryPath(WeSayWordsProject.GetPretendProjectDirectory());
			_project.Tasks = new List<ITask>();
			_project.Tasks.Add(new MockTask("Dashboard", "The control center.", true));


			_lexEntryRepository = new InMemoryRecordListManager();
			LexEntry entry = new LexEntry();
			_lexEntryRepository.Get<LexEntry>().Add(entry);
			_project.Tasks.Add(new WeSay.LexicalTools.EntryDetailTask(_lexEntryRepository));

		}
Exemplo n.º 36
0
		public void Setup()
		{
			_entry = new LexEntry();
			_sense = new LexSense();
			_entry.Senses.Add(_sense);
#if GlossMeaning
			this._sense.Gloss["th"] = "sense";
#else
			_sense.Definition["th"] = "sense";
#endif
			MultiText customFieldInSense =
					_sense.GetOrCreateProperty<MultiText>("customFieldInSense");
			customFieldInSense["th"] = "custom";
			_examples = new LexExampleSentence();
			_sense.ExampleSentences.Add(_examples);
			_examples.Sentence["th"] = "example";
			_examples.Translation["en"] = "translation";
			MultiText customFieldInExample =
					_examples.GetOrCreateProperty<MultiText>("customFieldInExample");
			customFieldInExample["th"] = "custom";
			_entry.EmptyObjectsRemoved += _entry_EmptyObjectsRemoved;
			_entry.PropertyChanged += _entry_PropertyChanged;
			_removed = false;
		}
Exemplo n.º 37
0
		public void DeletedEntry()
		{
			using (var session = new LiftExportAsFragmentTestSession())
			{
				var entry = new LexEntry();
				session.LiftWriter.AddDeletedEntry(entry);
				session.LiftWriter.End();
				Assert.IsNotNull(GetStringAttributeOfTopElement("dateDeleted", session));
			}
		}
Exemplo n.º 38
0
		public void Setup()
		{
			_entry = new LexEntry();
			_entry.PropertyChanged += _entry_PropertyChanged;
			_didNotify = false;
		}
Exemplo n.º 39
0
		public void DeletedEntry()
		{
			LexEntry entry = new LexEntry();
			_exporter.AddDeletedEntry(entry);
			_exporter.End();
			Assert.IsNotNull(GetStringAttributeOfTopElement("dateDeleted"));
		}
Exemplo n.º 40
0
		public void GetHeadword_CitationFormHasAlternative_CorrectForm()
		{
			LexEntry entry = new LexEntry();
			entry.LexicalForm.SetAlternative("a", "apple");
			MultiText citation =
					entry.GetOrCreateProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
			citation.SetAlternative("b", "barter");
			citation.SetAlternative("a", "applishus");
			Assert.AreEqual("applishus", entry.GetHeadWordForm("a"));
			Assert.AreEqual("barter", entry.GetHeadWordForm("b"));
			Assert.AreEqual(string.Empty, entry.GetHeadWordForm("donthave"));
		}
		private static void CheckCompleteEntry(LexEntry entry)
		{
			Assert.AreEqual(1, entry.Senses.Count);
			LexSense sense = entry.Senses[0];
			Assert.AreEqual(1, sense.ExampleSentences.Count);
			LexExampleSentence example = sense.ExampleSentences[0];
			Assert.AreEqual("this is a sentence", example.Sentence["foo"]);
			Assert.AreEqual("aaaa", example.Translation["aa"]);
			Assert.AreEqual(entry, sense.Parent);
			Assert.AreEqual(entry, example.Parent.Parent);
		}
Exemplo n.º 42
0
		public void LexEntryChanges_IsDirtyReturnsTrue()
		{
			LexEntry entry = new LexEntry();
			entry.Clean();
			entry.Senses.Add(new LexSense());
			Assert.IsTrue(entry.IsDirty);
		}
Exemplo n.º 43
0
		public void GetHeadword_EmptyEverything_ReturnsEmptyString()
		{
			LexEntry entry = new LexEntry();
			Assert.AreEqual(string.Empty, entry.GetHeadWordForm("a"));
		}
Exemplo n.º 44
0
		public void Clean_IsDirtyReturnsFalse()
		{
			LexEntry entry = new LexEntry();
			entry.Clean();
			Assert.IsFalse(entry.IsDirty);
		}
Exemplo n.º 45
0
		public void LexEntryConstructor_IsDirtyReturnsTrue()
		{
			LexEntry entry = new LexEntry();
			Assert.IsTrue(entry.IsDirty);
		}
Exemplo n.º 46
0
		public void GetHeadword_CitationFormLacksAlternative_GetsFormFromLexemeForm()
		{
			LexEntry entry = new LexEntry();
			entry.LexicalForm.SetAlternative("a", "apple");
			MultiText citation =
					entry.GetOrCreateProperty<MultiText>(LexEntry.WellKnownProperties.Citation);
			citation.SetAlternative("b", "bater");
			Assert.AreEqual("apple", entry.GetHeadWordForm("a"));
		}
Exemplo n.º 47
0
		public void GetHumanReadableId_IdIsSpace_NoForm()
		{
			var entry = new LexEntry(" ", Guid.NewGuid());
			Assert.IsTrue(
				LiftWriter.GetHumanReadableIdWithAnyIllegalUnicodeEscaped(
					entry, new Dictionary<string, int>()
				).StartsWith("Id'dPrematurely_")
			);
		}
Exemplo n.º 48
0
 private LexEntry AddEntry(string gloss, FeatureStruct syntacticFS, Stratum stratum, params string[] forms)
 {
     var entry = new LexEntry
     {
         SyntacticFeatureStruct = syntacticFS,
         Gloss = gloss,
         IsPartial = syntacticFS.IsEmpty
     };
     foreach (string form in forms)
         entry.Allomorphs.Add(new RootAllomorph(new Segments(stratum.CharacterDefinitionTable, form)));
     stratum.Entries.Add(entry);
     Entries[gloss] = entry;
     return entry;
 }
Exemplo n.º 49
0
		private string GetResultStringFromEntry(LexEntry entry, string insideClass, string afterClass)
		{
			string templateAttributes = "requireClassTemplatesForEverything='true' doUseBaseClassTemplatesIfNeeded='true'";
			XDumper dumper = new XDumper(Cache);
			dumper.FxtDocument = new XmlDocument();
			//sadly, the current dumper code requires the first thing inside the template to be a class node
			dumper.FxtDocument.LoadXml(string.Format("<template {0}><class name=\"LexEntry\">{1}</class>{2}</template>", templateAttributes, insideClass, afterClass));
			System.Text.StringBuilder builder = new System.Text.StringBuilder();
			StringWriter writer = new StringWriter(builder);
			dumper.Go(entry as CmObject, writer, new IFilterStrategy[] { });
			return builder.ToString();
		}
Exemplo n.º 50
0
		public void GetHumanReadableId_IdIsSpace_TreatedAsThoughNonExistentId()
		{
			LexEntry entry = new LexEntry(" ", Guid.NewGuid());
			entry.LexicalForm["green"] = "string";
			Assert.IsTrue(
					LiftExporter.GetHumanReadableId(entry, new Dictionary<string, int>()).StartsWith
							("string"));
		}
		public void NotifyThatLexEntryHasBeenUpdated_LexEntryDoesNotExistInRepository_Throws()
		{
			var entryToUpdate = new LexEntry();
			Assert.Throws<ArgumentOutOfRangeException>(() =>
				_repository.NotifyThatLexEntryHasBeenUpdated(entryToUpdate));
		}
Exemplo n.º 52
0
		public void GetHumanReadableId_IdIsSpace_NoForm()
		{
			LexEntry entry = new LexEntry(" ", Guid.NewGuid());
			Assert.IsTrue(
					LiftExporter.GetHumanReadableId(entry, new Dictionary<string, int>()).StartsWith
							("Id'dPrematurely_"));
		}
Exemplo n.º 53
0
		/// <summary>
		/// Create a new entry with the given guid owned by the given owner.
		/// </summary>
		public ILexEntry Create(Guid guid, ILexDb owner)
		{
			if (owner == null) throw new ArgumentNullException("owner");

			ILexEntry le;
			if (guid == Guid.Empty)
			{
				le = Create();
			}
			else
			{
				int hvo = ((IDataReader)m_cache.ServiceLocator.GetInstance<IDataSetup>()).GetNextRealHvo();
				le = new LexEntry(m_cache, hvo, guid);
			}
			return le;
		}
Exemplo n.º 54
0
		public void GetHeadword_LexemeForm_ReturnsCorrectAlternative()
		{
			LexEntry entry = new LexEntry();
			entry.LexicalForm.SetAlternative("c", "can");
			entry.LexicalForm.SetAlternative("a", "apple");
			entry.LexicalForm.SetAlternative("b", "bart");
			Assert.AreEqual("apple", entry.GetHeadWordForm("a"));
			Assert.AreEqual("bart", entry.GetHeadWordForm("b"));
			Assert.AreEqual(string.Empty, entry.GetHeadWordForm("donthave"));
		}
Exemplo n.º 55
0
		public void GetHomographNumber_AssignesUniqueNumbers()
		{
			using (var env = new TestEnvironment())
			{
				LexEntry entryOther = env.MakeEntryWithLexemeForm("en", "blue");
				Assert.AreNotEqual("en", env.HeadwordWritingSystem.LanguageTag);
				LexEntry[] entries = new LexEntry[3];
				entries[0] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue");
				entries[1] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue");
				entries[2] = env.MakeEntryWithLexemeForm(env.HeadwordWritingSystem.LanguageTag, "blue");
				List<int> ids = new List<int>(entries.Length);
				foreach (LexEntry entry in entries)
				{
					int homographNumber = env.Repository.GetHomographNumber(entry,
						env.HeadwordWritingSystem);
					Assert.IsFalse(ids.Contains(homographNumber));
					ids.Add(homographNumber);
				}
			}
		}
		public void GetHomographNumber_AssignesUniqueNumbers()
		{
			LexEntry entryOther = MakeEntryWithLexemeForm("en", "blue");
			Assert.AreNotEqual("en", _headwordWritingSystem.Id);
			LexEntry[] entries = new LexEntry[3];
			entries[0] = MakeEntryWithLexemeForm(_headwordWritingSystem.Id, "blue");
			entries[1] = MakeEntryWithLexemeForm(_headwordWritingSystem.Id, "blue");
			entries[2] = MakeEntryWithLexemeForm(_headwordWritingSystem.Id, "blue");
			List<int> ids = new List<int>(entries.Length);
			foreach (LexEntry entry in entries)
			{
				int homographNumber = _repository.GetHomographNumber(entry,
																			 _headwordWritingSystem);
				Assert.IsFalse(ids.Contains(homographNumber));
				ids.Add(homographNumber);
			}
		}