示例#1
0
        /// <summary>
        /// Find an extant wordform,
        /// or create one (with nonundoable UOW), if one does not exist.
        /// </summary>
        public static IWfiWordform GetWordformForForm(LcmCache cache, ITsString form)
        {
            var          servLoc       = cache.ServiceLocator;
            var          wordformRepos = servLoc.GetInstance <IWfiWordformRepository>();
            IWfiWordform retval;

            if (!wordformRepos.TryGetObject(form, false, out retval))
            {
                // Have to make it.
                var wordformFactory = servLoc.GetInstance <IWfiWordformFactory>();
                NonUndoableUnitOfWorkHelper.Do(servLoc.GetInstance <IActionHandler>(), () =>
                {
                    retval = wordformFactory.Create(form);
                });
            }
            return(retval);
        }
示例#2
0
        public TryAWordRootSite(LcmCache cache, Mediator mediator, PropertyTable propertyTable)
        {
            m_cache         = cache;
            m_mediator      = mediator;
            m_propertyTable = propertyTable;
            VisibleChanged += OnVisibleChanged;
            var window = m_propertyTable.GetValue <FwXWindow>("window");

            if (window != null)
            {
                m_styleSheet = window.StyleSheet;
            }
            CoreWritingSystemDefinition wsObj = m_cache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem;

            RightToLeft = wsObj.RightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
            AutoScroll  = true;
        }
示例#3
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>
        public AnalysisInterlinearRs(LcmCache cache, IWfiAnalysis analysis,
                                     XmlNode configurationNode) : 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);
        }
示例#4
0
        public void Init(LcmCache cache, IFsFeatStruc fs)
        {
            CheckDisposed();

            m_fs    = fs;
            m_cache = cache;

            if (m_rootb == null)
            {
                MakeRoot();
            }
            else
            {
                m_rootb.SetRootObject(m_fs == null ? 0 : m_fs.Hvo, m_vc, (int)VcFrags.kfragName, m_rootb.Stylesheet);
                m_rootb.Reconstruct();
            }
        }
示例#5
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates dummy paras.
        /// </summary>
        /// <returns>An array of paras</returns>
        /// ------------------------------------------------------------------------------------
        public static IScrTxtPara[] CreateDummyParas(int count, LcmCache cache)
        {
            IText text = cache.ServiceLocator.GetInstance <ITextFactory>().Create();
            //cache.LangProject.TextsOC.Add(text);
            IStText stText = cache.ServiceLocator.GetInstance <IStTextFactory>().Create();

            text.ContentsOA = stText;

            IScrTxtPara[] paras = new IScrTxtPara[count];
            for (int i = 0; i < paras.Length; i++)
            {
                paras[i] = cache.ServiceLocator.GetInstance <IScrTxtParaFactory>().CreateWithStyle(
                    stText, ScrStyleNames.NormalParagraph);
            }

            return(paras);
        }
示例#6
0
 public void Init(LcmCache cache, IMoMorphSynAnalysis msa)
 {
     Debug.Assert(msa != null);
     m_msa   = msa;
     m_cache = cache;
     if (m_rootb == null)
     {
         MakeRoot();
     }
     else
     {
         m_rootb.SetRootObject(m_msa.Hvo, Vc,
                               (int)VcFrags.kfragFullMSAInterlinearname, m_rootb.Stylesheet);
         m_rootb.Reconstruct();
     }
     m_cache.DomainDataByFlid.AddNotification(this);
 }
示例#7
0
        internal void Initialize(LcmCache cache, IHelpTopicProvider helpTopicProvider, IApp app, IVwStylesheet stylesheet,
                                 NotebookImportWiz.RnSfMarker rsfm)
        {
            m_cache                     = cache;
            m_stylesheet                = stylesheet;
            m_chkForEachLine.Checked    = rsfm.m_txo.m_fStartParaNewLine;
            m_chkAfterBlankLine.Checked = rsfm.m_txo.m_fStartParaBlankLine;
            m_chkWhenIndented.Checked   = rsfm.m_txo.m_fStartParaIndented;
            m_chkAfterShortLine.Checked = rsfm.m_txo.m_fStartParaShortLine;
            m_tbShortLength.Text        = rsfm.m_txo.m_cchShortLim.ToString();
            m_tbShortLength.Enabled     = rsfm.m_txo.m_fStartParaShortLine;

            m_btnAddWritingSystem.Initialize(m_cache, helpTopicProvider, app);
            NotebookImportWiz.InitializeWritingSystemCombo(rsfm.m_txo.m_wsId, m_cache,
                                                           m_cbWritingSystem);
            InitializeStylesCombo(rsfm.m_txo.m_sStyle);
        }
示例#8
0
        public void Action_WithNoChangesFromMongo_ShouldCountZeroChanges()
        {
            // Setup
            var      lfProj = _lfProj;
            LcmCache cache  = lfProj.FieldWorksProject.Cache;

            // Exercise
            SutMongoToLcm.Run(lfProj);

            // Verify
            Assert.That(_counts.Added, Is.EqualTo(0));
            Assert.That(_counts.Modified, Is.EqualTo(0));
            Assert.That(_counts.Deleted, Is.EqualTo(0));

            Assert.That(LfMergeBridgeServices.FormatCommitMessageForLfMerge(_counts.Added, _counts.Modified, _counts.Deleted),
                        Is.EqualTo("Language Forge S/R"));
        }
示例#9
0
        public override void AddToDatabase(LcmCache cache)
        {
            if (m_fInDatabase)
            {
                return;                 // It's already in the database, so nothing more can be done.
            }
            string sType = XmlUtils.GetMandatoryAttributeValue(m_node, "type");

            if (sType == "value")
            {
                UndoableUnitOfWorkHelper.Do(MGAStrings.ksUndoCreatePhonologicalFeature, MGAStrings.ksRedoCreatePhonologicalFeature,
                                            cache.ActionHandlerAccessor, () =>
                {
                    m_featDefn = cache.LangProject.PhFeatureSystemOA.AddFeatureFromXml(m_node);
                });
            }
        }
示例#10
0
        public void Action_WithOneWellKnownItemThatHasOneParentButNoGuidInMongoGrammar_ShouldAddTwoGrammarEntriesWithCorrectNamesAndParents()
        {
            // Setup
            var          lfProj       = _lfProj;
            LcmCache     cache        = lfProj.FieldWorksProject.Cache;
            var          data         = new SampleData();
            BsonDocument grammarEntry = new BsonDocument();

            grammarEntry.Add("key", "subordconn");             // Standard abbreviation for "subordinating connector", whose parent is "connector"
            grammarEntry.Add("value", "NotTheRightName");
            grammarEntry.Add("abbreviation", "NotTheRightAbbrev");
            data.bsonOptionListData["items"] = new BsonArray(new BsonDocument[] { grammarEntry });

            _conn.UpdateMockOptionList(data.bsonOptionListData);

            // Exercise
            SutMongoToLcm.Run(lfProj);

            // Verify
            char   ORC          = '\ufffc';
            string expectedGuid = PartOfSpeechMasterList.FlatPosGuidsFromAbbrevs["subordconn"];

            string[] expectedNames        = PartOfSpeechMasterList.HierarchicalPosNames[expectedGuid].Split(ORC);
            string[] expectedAbbrevs      = PartOfSpeechMasterList.HierarchicalPosAbbrevs[expectedGuid].Split(ORC);
            string   expectedName         = expectedNames[1];
            string   expectedAbbrev       = expectedAbbrevs[1];
            string   expectedParentName   = expectedNames[0];
            string   expectedParentAbbrev = expectedAbbrevs[0];
            string   expectedParentGuid   = PartOfSpeechMasterList.FlatPosGuidsFromAbbrevs[expectedParentAbbrev];

            IPartOfSpeech newlyCreatedPos = cache.LangProject.AllPartsOfSpeech.FirstOrDefault(pos =>
                                                                                              pos.Name.BestAnalysisVernacularAlternative.Text == expectedName
                                                                                              );

            Assert.That(newlyCreatedPos, Is.Not.Null);
            Assert.That(newlyCreatedPos.Guid, Is.Not.Null);
            Assert.That(newlyCreatedPos.Guid.ToString(), Is.EqualTo(expectedGuid));
            Assert.That(newlyCreatedPos.Name.BestAnalysisVernacularAlternative.Text, Is.EqualTo(expectedName));
            Assert.That(newlyCreatedPos.Abbreviation.BestAnalysisVernacularAlternative.Text, Is.EqualTo(expectedAbbrev));
            Assert.That(newlyCreatedPos.OwningPossibility, Is.Not.Null);
            Assert.That(newlyCreatedPos.OwningPossibility, Is.InstanceOf <IPartOfSpeech>());
            Assert.That(newlyCreatedPos.OwningPossibility.Guid, Is.Not.Null);
            Assert.That(newlyCreatedPos.OwningPossibility.Guid.ToString(), Is.EqualTo(expectedParentGuid));
            Assert.That(newlyCreatedPos.OwningPossibility.Name.BestAnalysisVernacularAlternative.Text, Is.EqualTo(expectedParentName));
            Assert.That(newlyCreatedPos.OwningPossibility.Abbreviation.BestAnalysisVernacularAlternative.Text, Is.EqualTo(expectedParentAbbrev));
        }
示例#11
0
        internal static ILexEntry MakeEntry(LcmCache cache, string lf, string gloss)
        {
            ILexEntry entry = null;

            UndoableUnitOfWorkHelper.Do("undo", "redo", cache.ActionHandlerAccessor, () =>
            {
                entry              = cache.ServiceLocator.GetInstance <ILexEntryFactory>().Create();
                var form           = cache.ServiceLocator.GetInstance <IMoStemAllomorphFactory>().Create();
                entry.LexemeFormOA = form;
                form.Form.VernacularDefaultWritingSystem =
                    TsStringUtils.MakeString(lf, cache.DefaultVernWs);
                var sense = cache.ServiceLocator.GetInstance <ILexSenseFactory>().Create();
                entry.SensesOS.Add(sense);
                sense.Gloss.AnalysisDefaultWritingSystem = TsStringUtils.MakeString(gloss, cache.DefaultAnalWs);
            });
            return(entry);
        }
示例#12
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();
            }
        }
示例#13
0
        public static DictionaryNodeOptions GetFullyEnabledListOptions(LcmCache cache, DictionaryNodeListOptions.ListIds listName)
        {
            List <DictionaryNodeListOptions.DictionaryNodeOption> dnoList;
            var useParaOptions = false;

            switch (listName)
            {
            case DictionaryNodeListOptions.ListIds.Minor:
                dnoList = DictionaryDetailsControllerTests.ListOfEnabledDNOsFromStrings(
                    new[] { XmlViewsUtils.GetGuidForUnspecifiedVariantType(), XmlViewsUtils.GetGuidForUnspecifiedComplexFormType() }
                    .Select(guid => guid.ToString())
                    .Union(cache.LangProject.LexDbOA.ComplexEntryTypesOA.PossibilitiesOS
                           .Union(cache.LangProject.LexDbOA.VariantEntryTypesOA.PossibilitiesOS).Select(item => item.Guid.ToString())));
                break;

            case DictionaryNodeListOptions.ListIds.Variant:
                dnoList = DictionaryDetailsControllerTests.ListOfEnabledDNOsFromStrings(
                    new[] { XmlViewsUtils.GetGuidForUnspecifiedVariantType().ToString() }
                    .Union(cache.LangProject.LexDbOA.VariantEntryTypesOA.PossibilitiesOS.Select(item => item.Guid.ToString())));
                break;

            case DictionaryNodeListOptions.ListIds.Complex:
                useParaOptions = true;
                dnoList        = DictionaryDetailsControllerTests.ListOfEnabledDNOsFromStrings(
                    new[] { XmlViewsUtils.GetGuidForUnspecifiedComplexFormType().ToString() }
                    .Union(cache.LangProject.LexDbOA.ComplexEntryTypesOA.PossibilitiesOS.Select(item => item.Guid.ToString())));
                break;

            case DictionaryNodeListOptions.ListIds.Note:
                useParaOptions = true;
                dnoList        = DictionaryDetailsControllerTests.ListOfEnabledDNOsFromStrings(
                    new[] { XmlViewsUtils.GetGuidForUnspecifiedExtendedNoteType().ToString() }
                    .Union(cache.LangProject.LexDbOA.ExtendedNoteTypesOA.PossibilitiesOS.Select(item => item.Guid.ToString())));
                break;

            default:
                throw new NotImplementedException(string.Format("Unknown list id {0}", listName));
            }

            DictionaryNodeListOptions listOptions = useParaOptions ? new DictionaryNodeListAndParaOptions() : new DictionaryNodeListOptions();

            listOptions.ListId  = listName;
            listOptions.Options = dnoList;
            return(listOptions);
        }
示例#14
0
        internal void Initialize(LcmCache cache, IHelpTopicProvider helpTopicProvider, IApp app, NotebookImportWiz.RnSfMarker rsfm,
                                 CellarPropertyType cpt)
        {
            m_cache             = cache;
            m_helpTopicProvider = helpTopicProvider;
            m_btnAddWritingSystem.Initialize(m_cache, helpTopicProvider, app);
            NotebookImportWiz.InitializeWritingSystemCombo(rsfm.m_tlo.m_wsId, cache,
                                                           m_cbWritingSystem);

            bool fNotAtomic = (cpt != CellarPropertyType.ReferenceAtomic);

            m_tbDefaultValue.Text = rsfm.m_tlo.m_sEmptyDefault;

            m_chkDelimMultiEnable.Checked = rsfm.m_tlo.m_fHaveMulti && fNotAtomic;
            m_chkDelimMultiEnable.Enabled = fNotAtomic;
            m_tbDelimMulti.Text           = rsfm.m_tlo.m_sDelimMulti;
            m_tbDelimMulti.Enabled        = rsfm.m_tlo.m_fHaveMulti && fNotAtomic;

            m_chkDelimSubEnable.Checked = rsfm.m_tlo.m_fHaveSub;
            m_tbDelimSub.Text           = rsfm.m_tlo.m_sDelimSub;
            m_tbDelimSub.Enabled        = rsfm.m_tlo.m_fHaveSub;

            m_chkBetweenEnable.Checked = rsfm.m_tlo.m_fHaveBetween;
            m_tbBetweenBefore.Text     = rsfm.m_tlo.m_sMarkStart;
            m_tbBetweenAfter.Text      = rsfm.m_tlo.m_sMarkEnd;
            m_tbBetweenBefore.Enabled  = rsfm.m_tlo.m_fHaveBetween;
            m_tbBetweenAfter.Enabled   = rsfm.m_tlo.m_fHaveBetween;

            m_chkOnlyBeforeEnable.Checked = rsfm.m_tlo.m_fHaveBefore;
            m_tbOnlyBefore.Text           = rsfm.m_tlo.m_sBefore;
            m_tbOnlyBefore.Enabled        = rsfm.m_tlo.m_fHaveBefore;

            m_chkDiscardNewStuff.Checked = rsfm.m_tlo.m_fIgnoreNewStuff;

            m_rbMatchName.Checked = rsfm.m_tlo.m_pnt == PossNameType.kpntName;
            m_rbMatchAbbr.Checked = rsfm.m_tlo.m_pnt != PossNameType.kpntName;

            Debug.Assert(rsfm.m_tlo.m_rgsMatch.Count == rsfm.m_tlo.m_rgsReplace.Count);
            m_lvSubstitutions.Items.Clear();
            for (int i = 0; i < rsfm.m_tlo.m_rgsMatch.Count; ++i)
            {
                var lvi = new ListViewItem(new[] { rsfm.m_tlo.m_rgsMatch[i], rsfm.m_tlo.m_rgsReplace[i] });
                m_lvSubstitutions.Items.Add(lvi);
            }
        }
示例#15
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="ProjectLocationDlg"/> class.
 /// </summary>
 /// <param name="helpTopicProvider">The help topic provider.</param>
 /// <param name="cache"></param>
 /// ------------------------------------------------------------------------------------
 public ProjectLocationDlg(IHelpTopicProvider helpTopicProvider, LcmCache cache = null)
     : this()
 {
     if (cache == null)
     {
         m_tbCurrentProjectPath.Visible = false;
         m_lbCurrentProject.Visible     = false;
     }
     else
     {
         m_tbCurrentProjectPath.Text = cache.ProjectId.Path;
     }
     m_tbProjectsFolder.Text          = FwDirectoryFinder.ProjectsDirectory;
     m_tbProjectsFolder.Enabled       = true;
     m_btnBrowseProjectFolder.Enabled = true;
     m_helpTopicProvider             = helpTopicProvider;
     m_tbProjectsFolder.TextChanged += m_tbProjectsFolder_TextChanged;
 }
示例#16
0
        /// <summary>
        /// Initialize the launcher.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="obj"></param>
        /// <param name="flid"></param>
        /// <param name="fieldName"></param>
        /// <param name="persistProvider"></param>
        /// <param name="mediator"></param>
        /// <param name="propertyTable"></param>
        /// <param name="displayNameProperty"></param>
        /// <param name="displayWs"></param>
        public virtual void Initialize(LcmCache cache, ICmObject obj, int flid, string fieldName,
                                       IPersistenceProvider persistProvider, Mediator mediator, PropertyTable propertyTable, string displayNameProperty, string displayWs)
        {
            Debug.Assert(cache != null);
            Debug.Assert(flid != 0);
            Debug.Assert(!string.IsNullOrEmpty(fieldName));

            m_displayNameProperty = displayNameProperty;
            m_displayWs           = displayWs;
            m_persistProvider     = persistProvider;
            m_mediator            = mediator;
            m_propertyTable       = propertyTable;

            m_cache     = cache;
            m_obj       = obj;
            m_flid      = flid;
            m_fieldName = fieldName;
        }
示例#17
0
        private static int EnsureWritingSystemSetup(LcmCache cache, string wsStr, bool isVernacular)
        {
            var wsFact = cache.WritingSystemFactory;
            var result = wsFact.GetWsFromStr(wsStr);

            if (result < 1)
            {
                if (isVernacular)
                {
                    cache.LangProject.AddToCurrentVernacularWritingSystems(cache.WritingSystemFactory.get_Engine(wsStr) as CoreWritingSystemDefinition);
                }
                else
                {
                    cache.LangProject.AddToCurrentAnalysisWritingSystems(cache.WritingSystemFactory.get_Engine(wsStr) as CoreWritingSystemDefinition);
                }
            }
            return(wsFact.GetWsFromStr(wsStr));
        }
示例#18
0
        public void MigrateIfNeeded(SimpleLogger logger, PropertyTable propertyTable, string appVersion)
        {
            m_logger = logger;
            Cache    = propertyTable.GetValue <LcmCache>("cache");
            var foundOne = string.Format("{0}: Configuration was found in need of migration. - {1}",
                                         appVersion, DateTime.Now.ToString("yyyy MMM d h:mm:ss"));

            foreach (var config in DCM.GetConfigsNeedingMigration(Cache, VersionAlpha3))
            {
                m_logger.WriteLine(foundOne);
                m_logger.WriteLine(string.Format("Migrating {0} configuration '{1}' from version {2} to {3}.",
                                                 config.Type, config.Label, config.Version, VersionAlpha3));
                m_logger.IncreaseIndent();
                MigrateFrom83Alpha(config);
                config.Save();
                m_logger.DecreaseIndent();
            }
        }
示例#19
0
        public TwoLevelConc(LcmCache cache, IConcPolicy cp, IGetNodeInfo gni)
        {
            m_cp  = cp;
            m_gni = gni;
            InitializeBasic(cache, false);             // JT: was Initialize, that now has more args; not retested.
            InitializeComponentBasic();

            // Can't add null values to Controls,
            // now that there isn't a SliceCollection, which could hold nulls.
            //m_slices.AddRange(new Slice[cp.Count]); // adds appropriate # nulls

            // Temporary: until I figure how to be lazy, we have to make slices
            // for all nodes.
            for (int i = 0; i < cp.Count; i++)
            {
                FieldAt(i);
            }
        }
示例#20
0
        private static IStText CreateMultiParaText(string content, LcmCache cache)
        {
            var text = cache.ServiceLocator.GetInstance <ITextFactory>().Create();
            //cache.LangProject.
            var stText = cache.ServiceLocator.GetInstance <IStTextFactory>().Create();

            cache.LangProject.InterlinearTexts.Add(stText);
            text.ContentsOA = stText;
            var para = cache.ServiceLocator.GetInstance <IStTxtParaFactory>().Create();

            stText.ParagraphsOS.Add(para);
            para.Contents = MakeVernTss("First para " + content, cache);
            var para1 = cache.ServiceLocator.GetInstance <IStTxtParaFactory>().Create();

            stText.ParagraphsOS.Add(para1);
            para1.Contents = MakeVernTss("Second para " + content, cache);
            return(text.ContentsOA);
        }
示例#21
0
        protected PatternVcBase(LcmCache cache, PropertyTable propertyTable)
        {
            Cache           = cache;
            m_propertyTable = propertyTable;

            int userWs      = m_cache.DefaultUserWs;
            int maxFontSize = Cache.ServiceLocator.WritingSystems.AllWritingSystems.Select(ws => GetFontHeight(ws.Handle)).Max();

            ITsPropsBldr tpb = TsStringUtils.MakePropsBldr();

            // specify the writing system, so that font info for a specific WS in the normal style does not override these props
            tpb.SetIntPropValues((int)FwTextPropType.ktptWs, 0, userWs);
            // use Charis SIL because it supports the special characters that are needed for
            // multiline brackets
            tpb.SetStrPropValue((int)FwTextPropType.ktptFontFamily, "Charis SIL");
            // make the size of the brackets large enough so that they display properly
            tpb.SetIntPropValues((int)FwTextPropType.ktptFontSize, (int)FwTextPropVar.ktpvMilliPoint, maxFontSize);
            m_bracketProps = tpb.GetTextProps();

            tpb = TsStringUtils.MakePropsBldr();
            tpb.SetIntPropValues((int)FwTextPropType.ktptMarginLeading, (int)FwTextPropVar.ktpvMilliPoint, PileMargin);
            tpb.SetIntPropValues((int)FwTextPropType.ktptMarginTrailing, (int)FwTextPropVar.ktpvMilliPoint, PileMargin);
            m_pileProps = tpb.GetTextProps();

            m_empty               = TsStringUtils.EmptyString(userWs);
            m_leftBracketUpHook   = TsStringUtils.MakeString("\u23a1", userWs);
            m_leftBracketExt      = TsStringUtils.MakeString("\u23a2", userWs);
            m_leftBracketLowHook  = TsStringUtils.MakeString("\u23a3", userWs);
            m_rightBracketUpHook  = TsStringUtils.MakeString("\u23a4", userWs);
            m_rightBracketExt     = TsStringUtils.MakeString("\u23a5", userWs);
            m_rightBracketLowHook = TsStringUtils.MakeString("\u23a6", userWs);
            m_leftBracket         = TsStringUtils.MakeString("[", userWs);
            m_rightBracket        = TsStringUtils.MakeString("]", userWs);
            m_leftParenUpHook     = TsStringUtils.MakeString("\u239b", userWs);
            m_leftParenExt        = TsStringUtils.MakeString("\u239c", userWs);
            m_leftParenLowHook    = TsStringUtils.MakeString("\u239d", userWs);
            m_rightParenUpHook    = TsStringUtils.MakeString("\u239e", userWs);
            m_rightParenExt       = TsStringUtils.MakeString("\u239f", userWs);
            m_rightParenLowHook   = TsStringUtils.MakeString("\u23a0", userWs);
            m_leftParen           = TsStringUtils.MakeString("(", userWs);
            m_rightParen          = TsStringUtils.MakeString(")", userWs);
            m_questions           = TsStringUtils.MakeString("???", userWs);
            m_zwSpace             = TsStringUtils.MakeString("\u200b", userWs);
        }
示例#22
0
        public void Action_RunTwice_ShouldNotDuplicatePictures()
        {
            // Setup initial Mongo project has 1 picture and 2 captions
            var lfProj = _lfProj;
            var data   = new SampleData();
            int newMongoPictureCount = data.bsonTestData["senses"][0]["pictures"].AsBsonArray.Count;
            int newMongoCaptionCount = data.bsonTestData["senses"][0]["pictures"][0]["caption"].AsBsonDocument.Count();

            Assert.That(newMongoPictureCount, Is.EqualTo(2));
            Assert.That(newMongoCaptionCount, Is.EqualTo(2));

            // Initial LCM project has 63 entries, 3 internal pictures, and 1 externally linked picture
            LcmCache            cache     = _cache;
            ILexEntryRepository entryRepo = _servLoc.GetInstance <ILexEntryRepository>();
            int originalNumOfLcmPictures  = entryRepo.AllInstances().Count(
                e => (e.SensesOS.Count > 0) && (e.SensesOS[0].PicturesOS.Count > 0));

            Assert.That(entryRepo.Count, Is.EqualTo(OriginalNumOfLcmEntries));
            Assert.That(originalNumOfLcmPictures, Is.EqualTo(3 + 1));
            string expectedGuidStrBefore = data.bsonTestData["guid"].AsString;
            Guid   expectedGuidBefore    = Guid.Parse(expectedGuidStrBefore);
            var    entryBefore           = entryRepo.GetObject(expectedGuidBefore);

            Assert.That(entryBefore.SensesOS.Count, Is.GreaterThan(0));
            Assert.That(entryBefore.SensesOS.First().PicturesOS.Count, Is.EqualTo(1));

            // Exercise running Action twice
            data.bsonTestData["authorInfo"]["modifiedDate"] = DateTime.UtcNow;
            _conn.UpdateMockLfLexEntry(data.bsonTestData);
            SutMongoToLcm.Run(lfProj);
            data.bsonTestData["authorInfo"]["modifiedDate"] = DateTime.UtcNow;
            _conn.UpdateMockLfLexEntry(data.bsonTestData);
            SutMongoToLcm.Run(lfProj);

            string expectedGuidStr = data.bsonTestData["guid"].AsString;
            Guid   expectedGuid    = Guid.Parse(expectedGuidStr);
            var    entry           = entryRepo.GetObject(expectedGuid);

            Assert.IsNotNull(entry);
            Assert.That(entry.Guid, Is.EqualTo(expectedGuid));

            Assert.That(entry.SensesOS.Count, Is.GreaterThan(0));
            Assert.That(entry.SensesOS.First().PicturesOS.Count, Is.EqualTo(2));
        }
示例#23
0
        public void Action_WithOneItemInMongoGrammarThatHasNoGuidAndIsNotWellKnown_ShouldAddOneNewItemInLcmGrammar()
        {
            // Setup
            var           lfProj = _lfProj;
            LcmCache      cache  = lfProj.FieldWorksProject.Cache;
            int           grammarCountBeforeTest = cache.LangProject.AllPartsOfSpeech.Count;
            IPartOfSpeech secondPosBeforeTest    = cache.LangProject.AllPartsOfSpeech.Skip(1).FirstOrDefault();
            var           data         = new SampleData();
            BsonDocument  grammarEntry = new BsonDocument();

            grammarEntry.Add("key", "k2");
            grammarEntry.Add("value", "v2");
            grammarEntry.Add("abbreviation", "a2");
            data.bsonOptionListData["items"] = new BsonArray(new BsonDocument[] { grammarEntry });

            _conn.UpdateMockOptionList(data.bsonOptionListData);

            // Exercise
            SutMongoToLcm.Run(lfProj);

            // Verify
            int           grammarCountAfterTest = cache.LangProject.AllPartsOfSpeech.Count;
            IPartOfSpeech secondPosAfterTest    = cache.LangProject.AllPartsOfSpeech.Skip(1).FirstOrDefault();
            IPartOfSpeech newlyCreatedPos       = cache.LangProject.AllPartsOfSpeech.FirstOrDefault(pos =>
                                                                                                    pos.Abbreviation.BestAnalysisVernacularAlternative.Text == "k2" && // NOTE: k2 not a2
                                                                                                    pos.Name.BestAnalysisVernacularAlternative.Text == "v2"
                                                                                                    );

            Assert.That(grammarCountAfterTest, Is.EqualTo(grammarCountBeforeTest + 1));
            Assert.That(secondPosAfterTest, Is.Not.Null);
            Assert.That(secondPosAfterTest.Guid, Is.EqualTo(secondPosBeforeTest.Guid));
            Assert.That(secondPosAfterTest, Is.SameAs(secondPosBeforeTest));
            Assert.That(secondPosAfterTest.Name.BestAnalysisVernacularAlternative.Text, Is.Not.EqualTo("v2"));
            Assert.That(secondPosAfterTest.Abbreviation.BestAnalysisVernacularAlternative.Text, Is.Not.EqualTo("a2"));
            Assert.That(secondPosAfterTest.Abbreviation.BestAnalysisVernacularAlternative.Text, Is.Not.EqualTo("k2"));
            Assert.That(newlyCreatedPos, Is.Not.Null);
            Assert.That(newlyCreatedPos.Guid, Is.Not.Null);
            Assert.That(newlyCreatedPos.Name.BestAnalysisVernacularAlternative.Text, Is.EqualTo("v2"));
            Assert.That(newlyCreatedPos.Abbreviation.BestAnalysisVernacularAlternative.Text, Is.EqualTo("k2"));
            // The newly-created part of speech will get its abbreviation from the LF key, not the LF abbrev.
            // TODO: Consider whether or not that's a bug, and whether it should use the (user-supplied) abbrev.
            // OTOH, they should be the same... unless LF has a non-English UI language. In which case we *need*
            // the English abbrev (the "key") and we *want* the non-English abbrev.
        }
示例#24
0
        /// <summary>
        /// Load the information about the lexical relations that link to hvoEntry. Specifically, we want LexReferences
        /// that refer to the target Entry (hvoEntry) and also some other lexical entry.
        /// For each such thing, we store in cdaTemp the name (or, if appropriate, the reverse name) of the
        /// relationship that hvoEntry has to the other entry(s) in the lex reference, as property RelatedWordsVc.ktagName of
        /// the LexReference Hvo. Return through relsOut the list of LexReferences that are thus related to hvoEntry.
        /// Return true if there are any.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="hvoEntry">ID of the lexical entry we're working with</param>
        /// <param name="relsOut">an array of IDs (HVOs) for related objects</param>
        /// <param name="cdaTemp"></param>
        /// <returns>false if the entry has no associated lexical relations, or none of them are linked to any other entries.</returns>
        //
        static private bool LoadLexicalRelationInfo(LcmCache cache, int hvoEntry, out int[] relsOut, IVwCacheDa cdaTemp)
        {
            var relatedObjectIds = new List <int>();
            var entryRepository  = cache.ServiceLocator.GetInstance <ILexEntryRepository>();
            var lexEntry         = entryRepository.GetObject(hvoEntry);
            var targets          = new HashSet <ICmObject>(lexEntry.AllSenses.Cast <ICmObject>())
            {
                lexEntry
            };

            foreach (ILexRefType lexRefType in cache.LanguageProject.LexDbOA.ReferencesOA.ReallyReallyAllPossibilities)
            {
                foreach (var lexReference in lexRefType.MembersOC)
                {
                    // If at least one target is the lex entry or one of its senses.
                    if ((from target in lexReference.TargetsRS where targets.Contains(target) select target).FirstOrDefault() != null &&
                        (from target in lexReference.TargetsRS where !targets.Contains(target) select target).FirstOrDefault() != null)
                    {
                        // The name we want to use for our lex reference is either the name or the reverse name
                        // (depending on the direction of the relationship, if relevant) of the owning lex ref type.
                        var lexReferenceName = lexRefType.Name.BestVernacularAnalysisAlternative;

                        if (lexRefType.MappingType == (int)MappingTypes.kmtEntryAsymmetricPair ||
                            lexRefType.MappingType == (int)MappingTypes.kmtEntryOrSenseAsymmetricPair ||
                            lexRefType.MappingType == (int)MappingTypes.kmtSenseAsymmetricPair ||
                            lexRefType.MappingType == (int)MappingTypes.kmtEntryTree ||
                            lexRefType.MappingType == (int)MappingTypes.kmtEntryOrSenseTree ||
                            lexRefType.MappingType == (int)MappingTypes.kmtSenseTree)
                        {
                            if (lexEntry.OwnOrd == 0 && lexRefType.Name != null)                             // the original code had a check for name length as well.
                            {
                                lexReferenceName = lexRefType.ReverseName.BestVernacularAnalysisAlternative;
                            }
                        }

                        cdaTemp.CacheStringProp(lexReference.Hvo, RelatedWordsVc.ktagName, lexReferenceName);
                        relatedObjectIds.Add(lexReference.Hvo);
                    }
                }
            }

            relsOut = relatedObjectIds.ToArray();
            return(relsOut.Length > 0);
        }
示例#25
0
        /// <summary/>
        public void SetDlginfo(ICmPossibilityList posList, Mediator mediator, XCore.PropertyTable propertyTable, bool launchedFromInsertMenu, IPartOfSpeech subItemOwner)
        {
            CheckDisposed();

            m_subItemOwner           = subItemOwner;   // May be null, which is fine.
            m_posList                = posList;
            m_launchedFromInsertMenu = launchedFromInsertMenu;
            m_mediator               = mediator;
            m_propertyTable          = propertyTable;
            if (m_propertyTable != null)
            {
                // Reset window location.
                // Get location to the stored values, if any.
                if (m_propertyTable.PropertyExists("masterCatListDlgLocation") &&
                    m_propertyTable.PropertyExists("masterCatListDlgSize"))
                {
                    var       locWnd = m_propertyTable.GetValue <Point>("masterCatListDlgLocation");
                    var       szWnd  = m_propertyTable.GetValue <Size>("masterCatListDlgSize");
                    Rectangle rect   = new Rectangle(locWnd, szWnd);
                    ScreenHelper.EnsureVisibleRect(ref rect);
                    DesktopBounds = rect;
                    StartPosition = FormStartPosition.Manual;
                }
                m_helpTopicProvider = m_propertyTable.GetValue <IHelpTopicProvider>("HelpTopicProvider");
                if (m_helpTopicProvider != null)
                {
                    helpProvider = new HelpProvider();
                    helpProvider.HelpNamespace = m_helpTopicProvider.HelpFile;
                    helpProvider.SetHelpKeyword(this, m_helpTopicProvider.GetHelpString(s_helpTopic));
                    helpProvider.SetHelpNavigator(this, HelpNavigator.Topic);
                }
            }
            m_bnHelp.Enabled = (m_helpTopicProvider != null);

            Debug.Assert(posList != null);
            m_cache = posList.Cache;
            var posSet = new HashSet <IPartOfSpeech>();

            foreach (IPartOfSpeech pos in posList.ReallyReallyAllPossibilities)
            {
                posSet.Add(pos);
            }
            LoadMasterCategories(posSet);
        }
示例#26
0
        protected override void DoRun(ILfProject project)
        {
            _lfProject     = project;
            _projectRecord = _projectRecordFactory.Create(_lfProject);
            if (_projectRecord == null)
            {
                Logger.Warning("No project named {0}", _lfProject.ProjectCode);
                Logger.Warning("If we are unit testing, this may not be an error");
                return;
            }
            _lfProjectConfig = _projectRecord.Config;
            if (_lfProjectConfig == null)
            {
                return;
            }

            if (project.FieldWorksProject == null)
            {
                Logger.Error("Failed to find the corresponding FieldWorks project!");
                return;
            }
            if (project.FieldWorksProject.IsDisposed)
            {
                Logger.Warning("Project {0} is already disposed; this shouldn't happen", project.ProjectCode);
            }
            _cache = project.FieldWorksProject.Cache;
            if (_cache == null)
            {
                Logger.Error("Failed to find the LCM cache!");
                return;
            }

            _servLoc = _cache.ServiceLocator;
            if (_servLoc == null)
            {
                Logger.Error("Failed to find the service locator; giving up.");
                return;
            }

            var converter = new ConvertMongoToLcmLexicon(Settings, project, Logger, Progress, _connection, _projectRecord, EntryCounts);

            converter.RunConversion();
        }
示例#27
0
        public override void Initialize(LcmCache cache, ICmObject obj, int flid, string fieldName, IPersistenceProvider persistProvider,
                                        XCore.Mediator mediator, PropertyTable propertyTable, string displayNameProperty, string displayWs)
        {
            CheckDisposed();
            base.Initialize(cache, obj, flid, fieldName, persistProvider, mediator, propertyTable, displayNameProperty, displayWs);

            m_view.Init(mediator, propertyTable, obj.Hvo, this, new AffixRuleFormulaVc(cache, propertyTable), AffixRuleFormulaVc.kfragRule, cache.MainCacheAccessor);

            m_view.SelectionChanged += SelectionChanged;

            m_insertionControl.AddOption(new InsertOption(RuleInsertType.Phoneme), DisplayOption);
            m_insertionControl.AddOption(new InsertOption(RuleInsertType.NaturalClass), DisplayOption);
            m_insertionControl.AddOption(new InsertOption(RuleInsertType.Features), DisplayOption);
            m_insertionControl.AddOption(new InsertOption(RuleInsertType.MorphemeBoundary), DisplayOption);
            m_insertionControl.AddOption(new InsertOption(RuleInsertType.Variable), DisplayVariableOption);
            m_insertionControl.AddOption(new InsertOption(RuleInsertType.Column), DisplayColumnOption);
            m_insertionControl.AddMultiOption(new InsertOption(RuleInsertType.Index), DisplayOption, DisplayIndices);
            m_insertionControl.NoOptionsMessage = DisplayNoOptsMsg;
        }
示例#28
0
        private static void DisplayEntriesRecursive(LcmCache cache, IWin32Window owner,
                                                    Mediator mediator, PropertyTable propertyTable, IVwStylesheet stylesheet,
                                                    IHelpTopicProvider helpProvider, string helpFileKey,
                                                    List <ILexEntry> entries, ITsString tssWf)
        {
            // Loop showing the SummaryDialogForm as long as the user clicks the Other button
            // in that dialog.
            bool otherButtonClicked = false;

            do
            {
                using (var sdform = new SummaryDialogForm(new List <int>(entries.Select(le => le.Hvo)), tssWf,
                                                          helpProvider, helpFileKey,
                                                          stylesheet, cache, mediator, propertyTable))
                {
                    SetCurrentModalForm(sdform);
                    if (owner == null)
                    {
                        sdform.StartPosition = FormStartPosition.CenterScreen;
                    }
                    sdform.ShowDialog(owner);
                    if (sdform.ShouldLink)
                    {
                        sdform.LinkToLexicon();
                    }
                    otherButtonClicked = sdform.OtherButtonClicked;
                }
                if (otherButtonClicked)
                {
                    // Look for another entry to display.  (If the user doesn't select another
                    // entry, loop back and redisplay the current entry.)
                    var entry = ShowFindEntryDialog(cache, mediator, propertyTable, tssWf, owner);
                    if (entry != null)
                    {
                        // We need a list that contains the entry we found to display on the
                        // next go around of this loop.
                        entries = new List <ILexEntry>();
                        entries.Add(entry);
                        tssWf = entry.HeadWord;
                    }
                }
            } while (otherButtonClicked);
        }
示例#29
0
        /// <summary/>
        public static bool ShowNewDialog(IWin32Window parentForm, LcmCache cache, IHelpTopicProvider helpProvider, IApp app,
                                         FwWritingSystemSetupModel.ListType type, out IEnumerable <CoreWritingSystemDefinition> newWritingSystems)
        {
            newWritingSystems = new List <CoreWritingSystemDefinition>();
            var model    = new FwWritingSystemSetupModel(cache.ServiceLocator.WritingSystems, type, cache.ServiceLocator.WritingSystemManager, cache);
            var oldWsSet = new HashSet <WSListItemModel>(model.WorkingList);

            using (var dlg = new FwWritingSystemSetupDlg(model, helpProvider, app))
            {
                dlg.ShowDialog(parentForm);
                if (dlg.DialogResult == DialogResult.OK)
                {
                    newWritingSystems = model.WorkingList.Where(item => !oldWsSet.Contains(item)).Select(item => item.WorkingWs);
                    return(true);
                }
            }

            return(false);
        }
示例#30
0
        /// <summary>
        /// Set up the dlg in preparation to showing it.
        /// </summary>
        /// <param name="cache">FDO cache.</param>
        /// <param name="wp">Strings used for various items in this dialog.</param>
        /// <param name="mediator">The mediator.</param>
        /// <param name="propertyTable"></param>
        /// <param name="tssform">The form.</param>
        /// <param name="hvoType">The HVO of the type.</param>
        public void SetDlgInfo(LcmCache cache, WindowParams wp, Mediator mediator, XCore.PropertyTable propertyTable, ITsString tssform, int hvoType)
        {
            CheckDisposed();

            SetDlgInfo(cache, wp, mediator, propertyTable, tssform);

            m_formOrig = m_tbForm.Text;
            m_hvoType  = hvoType;

            // JohnT: a prior call to SetForm should have established whether this button
            // is enabled...and it should NOT be, if there are no entries selected,
            // typically because none at all match the form.
            //btnOK.Enabled = true;
            m_btnOK.Width    += 30;
            m_btnOK.Left     += 90;
            m_btnClose.Width += 30;                     // for balance...

            ShowControlsBasedOnPanel1Position();
        }