/// ------------------------------------------------------------------------------------
        /// <summary>
        /// Determine where in the annotation list to insert a new annotation having the
        /// specified startRef, beginning object and beginning offset.
        /// </summary>
        /// <param name="startRef">The start ref.</param>
        /// <param name="beginObject">The begin object.</param>
        /// <param name="begOffset">The beg offset.</param>
        /// ------------------------------------------------------------------------------------
        private int GetNewNotesInsertIndex(BCVRef startRef, ICmObject beginObject, int begOffset)
        {
            // Get the index within the book of the section containing the paragraph
            // containing the reference to which the new annotation corresponds.
            int iNewNoteSection;
            int iNewNotePara;

            GetLocationInfoForObj(beginObject, out iNewNoteSection, out iNewNotePara);

            FdoOwningSequence <IScrScriptureNote> notes = NotesOS;
            int insertIndex = notes.Count;

            // Go backward through the list of existing annotations.
            for (int i = notes.Count - 1; i >= 0; i--)
            {
                IScrScriptureNote note = notes[i];
                int iSect, iPara;
                GetLocationInfoForObj(note.BeginObjectRA, out iSect, out iPara);

                // If the annotation is for text that follows the text associated
                // with the new annotation we're adding, then decrement the index
                // of where to insert the new annotation.
                if (note.BeginRef > startRef || iSect > iNewNoteSection ||
                    (iSect == iNewNoteSection && iPara > iNewNotePara) ||
                    (iSect == iNewNoteSection && iPara == iNewNotePara && note.BeginOffset > begOffset))
                {
                    insertIndex--;
                }
            }

            return(insertIndex);
        }
Exemple #2
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Writes this category to the the specified annotation, creating a new category if
        /// needed.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        internal void WriteToCache(IScrScriptureNote ann)
        {
            int ws = (string.IsNullOrEmpty(IcuLocale) ? ann.Cache.DefaultAnalWs :
                      ScrNoteImportManager.GetWsForLocale(IcuLocale));

            ICmPossibility category;

            if (CategoryPath.IndexOf(StringUtils.kChObject) != -1)
            {
                // The category specified the full path of the category possibility.
                category = ann.Cache.LangProject.TranslatedScriptureOA.NoteCategoriesOA.FindOrCreatePossibility(
                    CategoryPath, ws);
            }
            else
            {
                // The category does not contain a delimiter, so we may need to search
                // the entire possibility tree for a matching category in case it is a
                // sub-possibility.
                category = ann.Cache.LangProject.TranslatedScriptureOA.NoteCategoriesOA.FindOrCreatePossibility(
                    CategoryPath, ws, false);
            }

            IFdoReferenceSequence <ICmPossibility> categoryList = ann.CategoriesRS;

            if (!categoryList.Contains(category))
            {
                categoryList.Add(category);
            }
        }
Exemple #3
0
        public void ExportNotationParagraphs_WritingSystems()
        {
            IScrSection section = m_scrInMemoryCache.AddSectionToMockedBook(m_book.Hvo);
            StTxtPara   para    = m_scrInMemoryCache.AddParaToMockedSectionContent(section.Hvo,
                                                                                   ScrStyleNames.NormalParagraph);
            IScrScriptureNote note = m_scrInMemoryCache.AddAnnotation(para, new BCVRef(01001001),
                                                                      NoteType.Translator, "This is some text with espa\u00F1ol.");
            TsStringAccessor tssaDisc = ((StTxtPara)note.DiscussionOA.ParagraphsOS[0]).Contents;
            ITsStrBldr       bldr     = tssaDisc.UnderlyingTsString.GetBldr();

            bldr.SetProperties(bldr.Length - 8, bldr.Length - 1,
                               StyleUtils.CharStyleTextProps(null, InMemoryFdoCache.s_wsHvos.Es));
            tssaDisc.UnderlyingTsString = bldr.GetString();

            StringWriter  stream = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stream);

            m_exporter = new ExportXml(null, Cache, null, ExportWhat.AllBooks, 0, 0, 0,
                                       "ExportNotationParagraphs_WritingSystems");

            ReflectionHelper.SetField(m_exporter, "m_writer", writer);
            ReflectionHelper.CallMethod(m_exporter, "ExportNotationParagraphs", note.DiscussionOA,
                                        "notationDiscussion");
            Assert.AreEqual("<notationDiscussion><para xml:lang=\"en\">" +
                            "<span>This is some text with </span>" +
                            "<span xml:lang=\"es\">espa\u00F1ol</span>" +
                            "<span>.</span>" +
                            "</para></notationDiscussion>", stream.ToString());
        }
Exemple #4
0
        public void ExportNotationParagraphs_Hyperlink()
        {
            IScrSection section = m_scrInMemoryCache.AddSectionToMockedBook(m_book.Hvo);
            StTxtPara   para    = m_scrInMemoryCache.AddParaToMockedSectionContent(section.Hvo,
                                                                                   ScrStyleNames.NormalParagraph);
            IScrScriptureNote note = m_scrInMemoryCache.AddAnnotation(para, new BCVRef(01001001),
                                                                      NoteType.Translator, "This is some text with a hyperlink!");
            TsStringAccessor tssaDisc = ((StTxtPara)note.DiscussionOA.ParagraphsOS[0]).Contents;

            tssaDisc.MarkTextAsHyperlink(tssaDisc.Length - 10, tssaDisc.Length - 1,
                                         "http://www.myspace.com", m_stylesheet);

            StringWriter  stream = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stream);

            m_exporter = new ExportXml(null, Cache, null, ExportWhat.AllBooks, 0, 0, 0,
                                       "ExportNotationParagraphs_Hyperlink");

            ReflectionHelper.SetField(m_exporter, "m_writer", writer);
            ReflectionHelper.CallMethod(m_exporter, "ExportNotationParagraphs", note.DiscussionOA,
                                        "notationDiscussion");
            Assert.AreEqual("<notationDiscussion><para xml:lang=\"en\">" +
                            "<span>This is some text with a </span>" +
                            "<a href=\"http://www.myspace.com\">hyperlink</a>" +
                            "<span>!</span>" +
                            "</para></notationDiscussion>", stream.ToString());
        }
Exemple #5
0
        public static bool Serialize(XmlTextWriter writer, IScrScriptureNote ann,
                                     string languageInFocus)
        {
            if (writer == null || ann == null)
            {
                return(false);
            }

            try
            {
                FdoCache cache = ann.Cache;
                ILgWritingSystemFactory lgwsf = cache.LanguageWritingSystemFactoryAccessor;
                XmlScrNote xmlNote            = new XmlScrNote(ann, cache.DefaultAnalWs, lgwsf);

                if (!string.IsNullOrEmpty(xmlNote.Type))
                {
                    if (!string.IsNullOrEmpty(languageInFocus))
                    {
                        xmlNote.LanguageInFocus = languageInFocus;
                    }

                    xmlNote.m_serializingForOxes = true;
                    return(XmlSerializationHelper.SerializeDataAndWriteAsNode(writer, xmlNote));
                }
            }
            catch
            {
                // TODO: Report something useful.
            }

            return(false);
        }
        public void ExistingAnnotation_WithResponses()
        {
            IScrScriptureNote existingAnn =
                AddAnnotation(null, 02002008, NoteType.Translator, "This is my discussion");

            existingAnn.ResolutionStatus = NoteStatus.Open;

            IStJournalText exisingResponse1 = Cache.ServiceLocator.GetInstance <IStJournalTextFactory>().Create();

            existingAnn.ResponsesOS.Add(exisingResponse1);
            AddParasTo(exisingResponse1, "This is my first response");

            IStJournalText exisingResponse2 = Cache.ServiceLocator.GetInstance <IStJournalTextFactory>().Create();

            existingAnn.ResponsesOS.Add(exisingResponse2);
            AddParasTo(exisingResponse2, "This is my second response");

            DateTime now    = DateTime.Now;
            DateTime utcNow = now.ToUniversalTime();

            XmlScrNote ann = CreateNote();

            ann.BeginScrRef        = "EXO 2:8";
            ann.ResolutionStatus   = NoteStatus.Open;
            ann.AnnotationTypeGuid = CmAnnotationDefnTags.kguidAnnTranslatorNote.ToString();
            ann.DateTimeCreated    = utcNow.ToString();
            ann.DateTimeModified   = utcNow.AddDays(1).ToString();
            AddParasTo(ann.Discussion, "This is my discussion");
            XmlNoteResponse firstResponse = new XmlNoteResponse();

            AddParasTo(firstResponse.Paragraphs, "This is my first response");
            ann.Responses.Add(firstResponse);
            XmlNoteResponse secondResponse = new XmlNoteResponse();

            AddParasTo(secondResponse.Paragraphs, "This is my second response");
            ann.Responses.Add(secondResponse);

            DummyXmlScrAnnotationsList list = new DummyXmlScrAnnotationsList();

            list.Annotations.Add(ann);

            list.CallWriteToCache(Cache, m_stylesheet);

            IScrBookAnnotations annotations = m_scr.BookAnnotationsOS[1];

            Assert.AreEqual(1, annotations.NotesOS.Count);

            IScrScriptureNote note = annotations.NotesOS[0];

            Assert.AreEqual(NoteType.Translator, note.AnnotationType);
            Assert.IsTrue(AreDateTimesClose(now, note.DateCreated));
            Assert.IsTrue(AreDatesClose(now.AddDays(1), note.DateModified));
            Assert.AreEqual(DateTime.MinValue, note.DateResolved);

            IFdoOwningSequence <IStJournalText> responses = note.ResponsesOS;

            Assert.AreEqual(2, responses.Count);
            TestAnnotationField(responses[0], "This is my first response");
            TestAnnotationField(responses[1], "This is my second response");
        }
Exemple #7
0
        private IScrScriptureNote FindOrCreateAnnotation(FwStyleSheet styleSheet)
        {
            FdoCache cache = styleSheet.Cache;

            ParagraphCollection parasQuote          = new ParagraphCollection(Quote, styleSheet, cache.DefaultVernWs);
            ParagraphCollection parasDiscussion     = new ParagraphCollection(Discussion, styleSheet);
            ParagraphCollection parasRecommendation = new ParagraphCollection(Suggestion, styleSheet);
            ParagraphCollection parasResolution     = new ParagraphCollection(Resolution, styleSheet);

            if (m_guidType == Guid.Empty)
            {
                m_guidType = CmAnnotationDefnTags.kguidAnnConsultantNote;
            }
            ScrAnnotationInfo info = new ScrAnnotationInfo(m_guidType, parasDiscussion,
                                                           parasQuote, parasRecommendation, parasResolution, BeginOffset,
                                                           BeginScrBCVRef, EndScrBCVRef, m_createdDate);

            IScrScriptureNote scrNote =
                ScrNoteImportManager.FindOrCreateAnnotation(info, m_guidBegObj);

            parasQuote.WriteToCache(scrNote.QuoteOA);
            parasDiscussion.WriteToCache(scrNote.DiscussionOA);
            parasRecommendation.WriteToCache(scrNote.RecommendationOA);
            parasResolution.WriteToCache(scrNote.ResolutionOA);

            return(scrNote);
        }
Exemple #8
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Attaches the annotated objects to the specifed annotation.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private static void AttachAnnotatedObjects(IScripture scr, int bookNum,
                                                   IScrScriptureNote scrNote)
        {
            int          iSection, iPara, ichStart, ichEnd;
            ScrReference scrRef = new ScrReference(scrNote.BeginRef, scr.Versification);

            if (TeEditingHelper.FindTextInVerse(scr, scrNote.CitedTextTss,
                                                scrRef, true, out iSection, out iPara, out ichStart, out ichEnd))
            {
                IScrBook book = scr.FindBook(bookNum);
                Debug.Assert(book != null);
                scrNote.BeginOffset = ichStart;
                scrNote.EndOffset   = ichEnd;

                if (iSection == -1)
                {
                    scrNote.BeginObjectRA = scrNote.EndObjectRA = book.TitleOA.ParagraphsOS[iPara];
                }
                else
                {
                    scrNote.BeginObjectRA = scrNote.EndObjectRA =
                        book.SectionsOS[iSection].ContentOA.ParagraphsOS[iPara];
                }
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Shows the category chooser dialog to let the user set the category for the
        /// specified annotation.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private void SetAnnotationCategory(IScrScriptureNote ann)
        {
            if (ann == null)
            {
                return;                 // Not much we can do
            }
            m_rootb.DestroySelection();
            string sUndo, sRedo;

            TeResourceHelper.MakeUndoRedoLabels("kstidSetAnnotationCategory", out sUndo, out sRedo);

            using (new WaitCursor(this))
                using (CategoryChooserDlg dlg = new CategoryChooserDlg(m_scr.NoteCategoriesOA,
                                                                       ann.CategoriesRS.ToHvoArray(), m_helpTopicProvider, TheMainWnd.App))
                {
                    if (dlg.ShowDialog(ParentForm) == DialogResult.OK)
                    {
                        using (UndoTaskHelper undoHelper = new UndoTaskHelper(this, sUndo, sRedo))
                        {
                            dlg.GetPossibilities(ann.CategoriesRS);
                            ann.DateModified    = DateTime.Now;
                            undoHelper.RollBack = false;
                        }
                    }
                }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the Scripture reference of the specified annotation as string.
        /// </summary>
        /// <param name="ann">The specified annotation.</param>
        /// ------------------------------------------------------------------------------------
        private string GetRefAsString(IScrScriptureNote ann)
        {
            BCVRef   startRef = new BCVRef(ann.BeginRef);
            IScrBook book     = m_scr.FindBook(startRef.Book);
            string   bookName;

            // Book for note may not be in the project.
            if (book != null)
            {
                bookName = book.BestUIName;
            }
            else
            {
                IScrBookRef bookRef = Cache.ServiceLocator.GetInstance <IScrRefSystemRepository>().Singleton.BooksOS[startRef.Book - 1];
                ITsString   tsName  = bookRef.BookName.get_String(Cache.DefaultUserWs);
                if (tsName.Length == 0)
                {
                    tsName = bookRef.BookName.BestAnalysisAlternative;
                }
                bookName = tsName.Text;
            }

            string titleText = ResourceHelper.GetResourceString("kstidScriptureTitle");
            string introText = ResourceHelper.GetResourceString("kstidScriptureIntro");

            return(BCVRef.MakeReferenceString(bookName, startRef, new BCVRef(ann.EndRef),
                                              m_scr.ChapterVerseSepr, m_scr.Bridge, titleText, introText));
        }
Exemple #11
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Writes this response to the the specified annotation
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void WriteToCache(IScrScriptureNote ann, FwStyleSheet styleSheet)
        {
            ParagraphCollection parasResponse = new ParagraphCollection(Paragraphs, styleSheet);

            ParagraphCollection.ParaMatchType type;
            int matchIndex = FindMatchingResponse(parasResponse, ann.ResponsesOS, out type);

            switch (type)
            {
            case ParagraphCollection.ParaMatchType.Exact:
            case ParagraphCollection.ParaMatchType.Contains:
                break;                         // we can ignore the new response -- it's a subset of the old.

            case ParagraphCollection.ParaMatchType.IsContained:
                IStJournalText oldText = ann.ResponsesOS[matchIndex];
                oldText.ParagraphsOS.Clear();
                parasResponse.WriteToCache(oldText);
                break;

            case ParagraphCollection.ParaMatchType.None:
                IStJournalText newText = ann.Cache.ServiceLocator.GetInstance <IStJournalTextFactory>().Create();
                ann.ResponsesOS.Add(newText);
                parasResponse.WriteToCache(newText);
                break;
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Create and Check an Annotation
        /// </summary>
        /// <param name="hvoParaStart">The hvo para start.</param>
        /// <param name="hvoParaEnd">The hvo para end.</param>
        /// <param name="startRef">The start ref.</param>
        /// <param name="endRef">The end ref.</param>
        /// <param name="startOffset">The start offset.</param>
        /// <param name="endOffset">The end offset.</param>
        /// <param name="tssQuote">The text in the quote.</param>
        /// <param name="sel">selection in main window</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        private IScrScriptureNote CreateAndCheckAnnotation(int hvoObjStart, int hvoObjEnd,
                                                           int startRef, int endRef, int startOffset, int endOffset, string strQuote)
        {
            ILangProject     lp = Cache.LangProject;
            CmAnnotationDefn transNoteAnnDefn = new CmAnnotationDefn(Cache,
                                                                     LangProject.kguidAnnTranslatorNote);

            // Get information from the selection about the location of the annotation.
            CmObject   topObj       = (CmObject)CmObject.CreateFromDBObject(m_inMemoryCache.Cache, hvoObjStart);
            CmObject   bottomObj    = (CmObject)CmObject.CreateFromDBObject(m_inMemoryCache.Cache, hvoObjEnd);
            int        wsSelector   = -1;
            ITsStrBldr tssBldrQuote = TsStrBldrClass.Create();

            tssBldrQuote.Replace(0, 0, strQuote, StyleUtils.ParaStyleTextProps(ScrStyleNames.Remark));

            IScrScriptureNote ann =
                m_notesEditingHelper.InsertNote(transNoteAnnDefn, startRef, endRef,
                                                topObj, bottomObj, wsSelector, startOffset, endOffset, tssBldrQuote.GetString());

            Assert.IsNotNull(ann);
            Assert.AreEqual(transNoteAnnDefn.Hvo, ann.AnnotationTypeRAHvo, "Wrong type of note created");
            Assert.AreEqual(hvoObjStart, ann.BeginObjectRAHvo, "Wrong paragraph annotated");
            Assert.AreEqual(hvoObjEnd, ann.EndObjectRAHvo, "Wrong paragraph annotated");
            Assert.AreEqual(startRef, ann.BeginRef, "Should have the correct start para reference");
            Assert.AreEqual(endRef, ann.EndRef, "Should have the correct end para reference");
            Assert.AreEqual(startOffset, ann.BeginOffset, "Should have the correct starting char offset");
            Assert.AreEqual(endOffset, ann.EndOffset, "Should have the correct ending char offset");
            Assert.AreEqual(lp.DefaultUserAgent.Hvo, ann.SourceRAHvo, "Wrong agent");
            VerifyInitializedText(ann.DiscussionOA, "Discussion");
            Assert.AreEqual(tssBldrQuote.Text, ((StTxtPara)ann.QuoteOA.ParagraphsOS[0]).Contents.Text);
            VerifyInitializedText(ann.RecommendationOA, "Recommendation");
            VerifyInitializedText(ann.ResolutionOA, "Resolution");
            return(ann);
        }
Exemple #13
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Create and Check an Annotation
        /// </summary>
        /// <param name="hvoParaStart">The hvo para start.</param>
        /// <param name="hvoParaEnd">The hvo para end.</param>
        /// <param name="startRef">The start ref.</param>
        /// <param name="endRef">The end ref.</param>
        /// <param name="startOffset">The start offset.</param>
        /// <param name="endOffset">The end offset.</param>
        /// <param name="tssQuote">The text in the quote.</param>
        /// <param name="sel">selection in main window</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        private IScrScriptureNote CreateAndCheckAnnotation(ICmObject topObj, ICmObject bottomObj,
                                                           int startRef, int endRef, int startOffset, int endOffset, string strQuote)
        {
            ILangProject      lp = Cache.LangProject;
            ICmAnnotationDefn transNoteAnnDefn =
                Cache.ServiceLocator.GetInstance <ICmAnnotationDefnRepository>().TranslatorAnnotationDefn;

            // Get information from the selection about the location of the annotation.
            ITsStrBldr tssBldrQuote = TsStrBldrClass.Create();

            tssBldrQuote.Replace(0, 0, strQuote, StyleUtils.CharStyleTextProps(null, Cache.DefaultVernWs));

            IScrScriptureNote ann =
                m_notesEditingHelper.InsertNote(transNoteAnnDefn, startRef, endRef,
                                                topObj, bottomObj, startOffset, endOffset, tssBldrQuote.GetString());

            Assert.IsNotNull(ann);
            Assert.AreEqual(transNoteAnnDefn, ann.AnnotationTypeRA, "Wrong type of note created");
            Assert.AreEqual(topObj, ann.BeginObjectRA, "Wrong paragraph annotated");
            Assert.AreEqual(bottomObj, ann.EndObjectRA, "Wrong paragraph annotated");
            Assert.AreEqual(startRef, ann.BeginRef, "Should have the correct start para reference");
            Assert.AreEqual(endRef, ann.EndRef, "Should have the correct end para reference");
            Assert.AreEqual(startOffset, ann.BeginOffset, "Should have the correct starting char offset");
            Assert.AreEqual(endOffset, ann.EndOffset, "Should have the correct ending char offset");
            Assert.AreEqual(lp.DefaultUserAgent, ann.SourceRA, "Wrong agent");
            VerifyInitializedText(ann.DiscussionOA, "Discussion");
            Assert.AreEqual(tssBldrQuote.Text, ((IStTxtPara)ann.QuoteOA.ParagraphsOS[0]).Contents.Text);
            VerifyInitializedText(ann.RecommendationOA, "Recommendation");
            VerifyInitializedText(ann.ResolutionOA, "Resolution");
            return(ann);
        }
        public void MakeLabelFromText_AnnotationOnFootnote()
        {
            IScrScriptureNote note = Cache.ServiceLocator.GetInstance <IScrScriptureNoteFactory>().Create();

            m_scr.BookAnnotationsOS[0].NotesOS.Add(note);
            note.BeginRef = 01001011;
            note.EndRef   = 01001011;
            IStFootnote footnote = AddFootnote(m_gen,
                                               (IStTxtPara)m_gen.SectionsOS[1].ContentOA.ParagraphsOS[0], 0);

            note.BeginObjectRA = AddParaToMockedText(footnote, "Whatever");
            ITsString tss = m_vc.CallMakeLabelFromText("GEN 1:11", "WhoCares", note);

            Assert.AreEqual(3, tss.RunCount);
#if __MonoCS__
            const string fontname = "OpenSymbol";
            const string symbol   = "\u2042";
#else
            const string fontname = "Marlett";
            const string symbol   = "\u0032";
#endif
            Assert.AreEqual(symbol, tss.get_RunText(0));
            Assert.AreEqual("GEN 1:11", tss.get_RunText(1));
            Assert.AreEqual(fontname,
                            tss.get_Properties(0).GetStrPropValue((int)FwTextPropType.ktptFontFamily));
            Assert.AreEqual("WhoCares",
                            tss.get_Properties(1).GetStrPropValue((int)FwTextPropType.ktptNamedStyle));
            CheckFinalSpaceInReferenceLabel(tss);
        }
Exemple #15
0
        public void ExportBookSection_IntroWithNotes()
        {
            IScrSection introSection = m_scrInMemoryCache.AddIntroSectionToMockedBook(m_book.Hvo);

            m_scrInMemoryCache.AddSectionHeadParaToSection(introSection.Hvo, "Introduction",
                                                           ScrStyleNames.IntroSectionHead);
            StTxtPara introPara = AddPara(introSection, ScrStyleNames.NormalParagraph);

            AddVerse(introPara, 0, 0, "Some intro text");
            IScrScriptureNote note = m_scrInMemoryCache.AddAnnotation(introPara, new BCVRef(01001000),
                                                                      NoteType.Consultant, "This is a basic note about the intro.");

            note.ResolutionStatus = NoteStatus.Open;
            note.BeginOffset      = 5;
            note.EndOffset        = 10;

            DateTime now    = DateTime.Now;
            string   strNow = now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss.ff");

            note.DateCreated  = now;
            note.DateModified = now;

            StringWriter  stream = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stream);

            writer.Formatting = Formatting.None;
            m_exporter        = new ExportXml(null, Cache, null, ExportWhat.AllBooks, 0, 0, 0,
                                              "ExportBookSection_IntroWithNotes");

            ReflectionHelper.SetField(m_exporter, "m_writer", writer);
            string sCanon = "ot";

            ReflectionHelper.CallMethod(m_exporter, "ExportBook", sCanon, m_book, null);


            XmlDocument actual = new XmlDocument();

            actual.Load(new StringReader(stream.ToString()));
            string strExpected = "<book ID=\"GEN\"><titleGroup short=\"Genesis\"><title type=\"main\">" +
                                 "<trGroup><tr>Genesis</tr></trGroup></title></titleGroup>" +
                                 "<introduction><section><sectionHead><trGroup><tr>Introduction</tr></trGroup></sectionHead>" +
                                 "<p><annotation type=\"consultantNote\" status=\"0\" oxesRef=\"GEN.1.0\" beginOffset=\"5\" endOffset=\"10\">" +
                                 "<created>" + strNow + "</created><modified>" + strNow + "</modified>" +
                                 "<resolved /><notationDiscussion><para xml:lang=\"en\">" +
                                 "<run>This is a basic note about the intro.</run></para></notationDiscussion></annotation>" +
                                 "<trGroup><tr><userCS type=\"Paragraph\">Some intro text</userCS></tr></trGroup>" +
                                 "<chapterEnd ID=\"GEN.0\"/></p></section></introduction></book>";

            XmlDocument expected = new XmlDocument();

            expected.Load(new StringReader(strExpected));

            string strDifference;

            if (!XmlHelper.CompareXmlNodes(expected.ChildNodes, actual.ChildNodes, out strDifference))
            {
                Assert.Fail(strDifference);
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Inserts a Scriture annotation for the book currently being imported.
        /// </summary>
        /// <param name="bcvStartReference">The starting BCV reference.</param>
        /// <param name="bcvEndReference">The ending BCV reference.</param>
        /// <param name="obj">The object being annotated (either a paragraph or a ScrBook)</param>
        /// <param name="bldr">The paragraph builder containing the guts of the annotation
        /// description</param>
        /// <param name="guidNoteType">The GUID representing the CmAnnotationDefn to use for
        /// the type</param>
        /// <returns>The newly created annotation</returns>
        /// ------------------------------------------------------------------------------------
        public IScrScriptureNote InsertNote(int bcvStartReference, int bcvEndReference,
                                            ICmObject obj, StTxtParaBldr bldr, Guid guidNoteType)
        {
            IScrScriptureNote note = m_annotations.InsertImportedNote(
                bcvStartReference, bcvEndReference, obj, obj, guidNoteType, bldr);

            return(note);
        }
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Creates an instance of a CheckingError object if the hvo is for an annotation
 /// that really is a CheckingError.
 /// </summary>
 /// ------------------------------------------------------------------------------------
 internal static CheckingError Create(IScrScriptureNote error)
 {
     if (error == null)
     {
         throw new ArgumentNullException("Null note cannot be used");
     }
     return(error.AnnotationType != NoteType.CheckingError ? null : new CheckingError(error));
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Attempts to scroll to an annotation whose BeginObjectRAHvo is the same as the hvo
        /// of the paragraph where the anchor is in the specified editing helper's selection.
        /// </summary>
        /// <param name="editingHelper">The TE editing helper with information about the
        /// selection in the Scripture pane.</param>
        /// <param name="selectedText">The selected text or the word containing the IP if the
        /// selection is not a range.</param>
        /// <param name="fExactMatchOnly">if set to <c>true</c> then only scroll to a found
        /// note if the cited text is an exact match.</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        private bool ScrollToAnnotationByPara(TeEditingHelper editingHelper,
                                              string selectedText, bool fExactMatchOnly)
        {
            if (editingHelper == null || editingHelper.CurrentSelection == null)
            {
                return(false);
            }

            ScrReference scrRef = editingHelper.CurrentStartRef;

            SelLevInfo[] info = editingHelper.CurrentSelection.GetLevelInfo(
                SelectionHelper.SelLimitType.Anchor);

            if (info.Length == 0)
            {
                return(false);
            }

            int bookHvo = m_scr.BookAnnotationsOS[scrRef.Book - 1].Hvo;

            int[] annHvos = ((ISilDataAccessManaged)m_rootb.DataAccess).VecProp(bookHvo,
                                                                                kCurrentNotesTag);

            if (annHvos.Length == 0)
            {
                return(false);
            }

            int ich = editingHelper.CurrentSelection.IchAnchor;

            // Go through the annotations for the book and find the one whose
            // begin object is in the same as the selection's paragraph.
            for (int i = 0; i < annHvos.Length; i++)
            {
                IScrScriptureNote ann = Cache.ServiceLocator.GetInstance <IScrScriptureNoteRepository>().GetObject(annHvos[i]);
                if (ann.BeginObjectRA != null && ann.BeginObjectRA.Hvo == info[0].hvo)
                {
                    // When matching on the cited text, allow for the possibility that the
                    // begin offset is off by a little bit since leading spaces and/or ORCs
                    // may have been trimmed and subsequent editing may have messed up the
                    // offsets a little.
                    int adjustedBeginOffset = ann.BeginOffset -
                                              (string.IsNullOrEmpty(ann.CitedText) ? 1 : ann.CitedText.Length);

                    if ((!fExactMatchOnly && ich >= ann.BeginOffset && ich <= ann.EndOffset) ||
                        (ich >= adjustedBeginOffset && selectedText == ann.CitedText))
                    {
                        m_vc.SelectedNoteHvo = ann.Hvo;
                        NotesEditingHelper.MakeSelectionInNote(m_vc, scrRef.Book - 1, i, this,
                                                               m_vc.IsExpanded(ann.Hvo));
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemple #19
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Writes this annotation to the specified cache.
        /// </summary>
        /// <param name="scr">The scripture.</param>
        /// <param name="styleSheet">The style sheet.</param>
        /// <returns>The created annotation</returns>
        /// ------------------------------------------------------------------------------------
        internal IScrScriptureNote WriteToCache(IScripture scr, FwStyleSheet styleSheet)
        {
            if (AnnotationTypeGuid == Guid.Empty.ToString())
            {
                return(null);
            }

            Debug.Assert(scr.Cache == styleSheet.Cache, "This can't end well");
            int bookNum             = BeginScrBCVRef.Book;
            IScrBookAnnotations sba = scr.BookAnnotationsOS[bookNum - 1];

            if (sba == null)
            {
                sba = scr.Cache.ServiceLocator.GetInstance <IScrBookAnnotationsFactory>().Create();
                scr.BookAnnotationsOS.Insert(bookNum - 1, sba);
            }

            IScrScriptureNote scrNote = FindOrCreateAnnotation(styleSheet);

            scrNote.BeginOffset      = BeginOffset;
            scrNote.EndOffset        = EndOffset;
            scrNote.ResolutionStatus = ResolutionStatus;

            if (m_createdDate > DateTime.MinValue)
            {
                scrNote.DateCreated = m_createdDate;
            }

            if (m_modifiedDate > DateTime.MinValue)
            {
                scrNote.DateModified = m_modifiedDate;
            }

            if (m_resolvedDate > DateTime.MinValue)
            {
                scrNote.DateResolved = m_resolvedDate;
            }

            foreach (XmlNoteCategory category in Categories)
            {
                category.WriteToCache(scrNote);
            }

            foreach (XmlNoteResponse response in Responses)
            {
                response.WriteToCache(scrNote, styleSheet);
            }

            //((Scripture)scr).AttachAnnotatedObjects(bookNum, scrNote);
            if (scrNote.BeginObjectRA == null && scrNote.CitedTextTss != null)
            {
                AttachAnnotatedObjects(scr, bookNum, scrNote);
            }

            return(scrNote);
        }
        public void ExcludeUnignoredErrors()
        {
            Assert.AreEqual(string.Empty, m_filter.Name);
            IScrScriptureNote note = m_scrInMemoryCache.AddAnnotation(
                (StTxtPara)m_genesis.SectionsOS[0].ContentOA.ParagraphsOS[0], 01001001,
                NoteType.CheckingError);

            note.ResolutionStatus = NoteStatus.Open;
            Assert.IsFalse(m_filter.MatchesCriteria(note.Hvo));
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Looks for any annotations in the curtrently filtered set whose reference range
        /// covers the given Scripture reference. Any such annotations are expanded and the
        /// first on is scrolled to near the top of the view.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        internal void ScrollRefIntoView(ScrReference reference, string quotedText)
        {
            CheckDisposed();
            if (reference.Book <= 0)
            {
                return;
            }

            bool fSaveSendSyncScrollMsg = m_fSendSyncScrollMsg;

            try
            {
                m_fSendSyncScrollMsg = false;
                int   bookHvo = m_scr.BookAnnotationsOS[reference.Book - 1].Hvo;
                int[] annHvos = ((ISilDataAccessManaged)m_rootb.DataAccess).VecProp(bookHvo,
                                                                                    kCurrentNotesTag);

                int exactMatchingAnnotation = -1;
                int firstMatchingAnnotation = -1;

                for (int i = 0; i < annHvos.Length; i++)
                {
                    IScrScriptureNote ann =
                        Cache.ServiceLocator.GetInstance <IScrScriptureNoteRepository>().GetObject(annHvos[i]);
                    if (ann.BeginRef <= reference && ann.EndRef >= reference)
                    {
                        if (firstMatchingAnnotation < 0)
                        {
                            firstMatchingAnnotation = i;
                        }

                        string qtext = ((IStTxtPara)ann.QuoteOA[0]).Contents.Text;
                        if (!string.IsNullOrEmpty(qtext) && !string.IsNullOrEmpty(quotedText) &&
                            qtext == quotedText && exactMatchingAnnotation < 0)
                        {
                            exactMatchingAnnotation = i;
                        }
                    }
                    else if (firstMatchingAnnotation >= 0)
                    {
                        break;
                    }
                }

                int idx = Math.Max(exactMatchingAnnotation, firstMatchingAnnotation);
                if (idx >= 0)
                {
                    NotesEditingHelper.MakeSelectionInNote(m_vc, reference.Book - 1, idx, this, m_vc.IsExpanded(annHvos[idx]));
                }
            }
            finally
            {
                m_fSendSyncScrollMsg = fSaveSendSyncScrollMsg;
            }
        }
        public void IncludeNormalNotes()
        {
            IScrScriptureNote note1 = m_scrInMemoryCache.AddAnnotation(
                (StTxtPara)m_genesis.SectionsOS[0].ContentOA.ParagraphsOS[0], 01001001,
                NoteType.Consultant);
            IScrScriptureNote note2 = m_scrInMemoryCache.AddAnnotation(
                (StTxtPara)m_genesis.SectionsOS[0].ContentOA.ParagraphsOS[0], 01001002,
                NoteType.Translator);

            Assert.IsTrue(m_filter.MatchesCriteria(note1.Hvo));
            Assert.IsTrue(m_filter.MatchesCriteria(note2.Hvo));
        }
Exemple #23
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets a list of all the categories assigned to the specified annotation.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public static List <XmlNoteCategory> GetCategoryList(IScrScriptureNote ann,
                                                             ILgWritingSystemFactory lgwsf)
        {
            List <XmlNoteCategory> list = new List <XmlNoteCategory>();

            foreach (ICmPossibility category in ann.CategoriesRS)
            {
                list.Add(new XmlNoteCategory(category, lgwsf));
            }

            return(list.Count == 0 ? null : list);
        }
        public void SavingDeserializedAnnotationsToCache_WithResponses()
        {
            DateTime now    = DateTime.Now;
            DateTime utcNow = now.ToUniversalTime();

            XmlScrNote ann = CreateNote();

            ann.BeginScrRef        = "EXO 2:8";
            ann.ResolutionStatus   = NoteStatus.Open;
            ann.AnnotationTypeGuid = LangProject.kguidAnnTranslatorNote.ToString();
            ann.DateTimeCreated    = utcNow.ToString();
            ann.DateTimeModified   = utcNow.AddDays(1).ToString();
            AddParasTo(ann.Discussion, "This is my discussion");
            AddParasTo(ann.Resolution, "This is my resolution for the note");
            AddParasTo(ann.Quote, "This is the quoted text");
            AddParasTo(ann.Suggestion, "This is my suggestion");
            XmlNoteResponse firstResponse = new XmlNoteResponse();

            AddParasTo(firstResponse.Paragraphs, "This is", "my", "first", "response");
            ann.Responses.Add(firstResponse);
            XmlNoteResponse secondResponse = new XmlNoteResponse();

            AddParasTo(secondResponse.Paragraphs, "This is", "my second response");
            ann.Responses.Add(secondResponse);

            DummyXmlScrAnnotationsList list = new DummyXmlScrAnnotationsList();

            list.Annotations.Add(ann);

            list.CallWriteToCache(Cache, m_stylesheet);

            IScrBookAnnotations annotations = m_scr.BookAnnotationsOS[1];

            Assert.AreEqual(1, annotations.NotesOS.Count);

            IScrScriptureNote note = annotations.NotesOS[0];

            Assert.AreEqual(NoteType.Translator, note.AnnotationType);
            Assert.IsTrue(AreDateTimesClose(now, note.DateCreated));
            Assert.IsTrue(AreDateTimesClose(now.AddDays(1), note.DateModified));
            Assert.AreEqual(DateTime.MinValue, note.DateResolved);

            TestAnnotationField(note.QuoteOA, "This is the quoted text");
            TestAnnotationField(note.DiscussionOA, "This is my discussion");
            TestAnnotationField(note.ResolutionOA, "This is my resolution for the note");
            TestAnnotationField(note.RecommendationOA, "This is my suggestion");

            FdoOwningSequence <IStJournalText> responses = note.ResponsesOS;

            Assert.AreEqual(2, responses.Count);
            TestAnnotationField(responses[0], "This is", "my", "first", "response");
            TestAnnotationField(responses[1], "This is", "my second response");
        }
Exemple #25
0
        public void ExportScriptureNote_IgnoredCheckingError()
        {
            IScrSection       section = m_scrInMemoryCache.AddSectionToMockedBook(m_book.Hvo);
            StTxtPara         para    = AddPara(section, ScrStyleNames.NormalParagraph);
            IScrScriptureNote note    = m_scrInMemoryCache.AddAnnotation(para, new BCVRef(01001001),
                                                                         NoteType.CheckingError, "This is some basic text.");

            note.AnnotationTypeRA.Name.SetAlternative("Repeated Words", Cache.DefaultAnalWs);
            note.AnnotationTypeRA.Guid = new Guid(StandardCheckIds.kguidRepeatedWords.ToString());
            note.ResolutionStatus      = NoteStatus.Closed;
            DateTime now    = DateTime.Now;
            string   strNow = now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss.ff");

            note.DateCreated  = now;
            note.DateModified = now;
            note.DateResolved = now;

            StringWriter  stream = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stream);

            m_exporter = new ExportXml(null, Cache, null, ExportWhat.AllBooks, 0, 0, 0,
                                       "ExportScriptureNote_Resolved");

            ReflectionHelper.SetField(m_exporter, "m_writer", writer);
            ReflectionHelper.CallMethod(m_exporter, "ExportScriptureNote", note);
            string strExpected = "<annotation subType=\"repeatedWordsCheck\" status=\"1\" oxesRef=\"GEN.1.1\" " +
                                 "beginOffset=\"0\" endOffset=\"0\" type=\"pre-typesettingCheck\">" +
                                 "<created>" + strNow + "</created>" +
                                 "<modified>" + strNow + "</modified>" +
                                 "<resolved>" + strNow + "</resolved>" +
                                 "<notationDiscussion>" +
                                 "<para xml:lang=\"en\">" +
                                 "<span>This is some basic text.</span>" +
                                 "</para>" +
                                 "</notationDiscussion>" +
                                 "</annotation>";

            XmlDocument actual = new XmlDocument();

            actual.Load(new StringReader(stream.ToString()));

            XmlDocument expected = new XmlDocument();

            expected.Load(new StringReader(strExpected));

            string strDifference;

            if (!XmlHelper.CompareXmlNodes(expected.ChildNodes, actual.ChildNodes, out strDifference))
            {
                Assert.Fail(strDifference);
            }
        }
Exemple #26
0
        public void FindOrCreateAnnotation_GuidNotFound()
        {
            StTxtParaBldr     bldr    = new StTxtParaBldr(Cache);
            ScrAnnotationInfo annInfo = new ScrAnnotationInfo(CmAnnotationDefnTags.kguidAnnConsultantNote,
                                                              bldr, 0, 01001001, 01001002);
            IScrScriptureNote newNote = ScrNoteImportManager.FindOrCreateAnnotation(annInfo, Guid.NewGuid());

            Assert.IsNotNull(newNote);
            Assert.IsNull(newNote.BeginObjectRA);
            Assert.IsNull(newNote.EndObjectRA);
            Assert.AreEqual(01001001, newNote.BeginRef);
            Assert.AreEqual(01001002, newNote.EndRef);
        }
Exemple #27
0
        public void SavingDeserializedAnnotationsToCache_WithHyperlink()
        {
            DateTime now    = DateTime.Now;
            DateTime utcNow = now.ToUniversalTime();

            XmlScrNote ann = CreateNote();

            ann.BeginScrRef        = "GEN 2:8";
            ann.ResolutionStatus   = NoteStatus.Closed;
            ann.AnnotationTypeGuid = CmAnnotationDefnTags.kguidAnnTranslatorNote.ToString();
            ann.DateTimeCreated    = utcNow.ToString(CultureInfo.InvariantCulture);
            ann.DateTimeModified   = utcNow.AddDays(1).ToString(CultureInfo.InvariantCulture);
            ann.DateTimeResolved   = utcNow.AddDays(2).ToString(CultureInfo.InvariantCulture);
            AddParasTo(ann.Discussion, "This is my", "discussion");
            AddParasTo(ann.Resolution, "This is my", "resolution for", "the note");
            AddParasTo(ann.Quote, "This is the", "quoted text");
            AddParasTo(ann.Suggestion, "This is", "my", "suggestion");
            AddHyperTo(ann.Suggestion[1], "http://www.tim.david.com/cooldudes.html");

            DummyXmlScrAnnotationsList list = new DummyXmlScrAnnotationsList();

            list.Annotations.Add(ann);

            list.CallWriteToCache(Cache, m_stylesheet);

            IScrBookAnnotations annotations = m_scr.BookAnnotationsOS[0];

            Assert.AreEqual(1, annotations.NotesOS.Count);

            IScrScriptureNote note = annotations.NotesOS[0];

            Assert.AreEqual(NoteType.Translator, note.AnnotationType);
            Assert.IsTrue(AreDateTimesClose(now, note.DateCreated));
            Assert.IsTrue(AreDatesClose(now.AddDays(1), note.DateModified));
            Assert.IsTrue(AreDatesClose(now.AddDays(2), note.DateResolved));

            TestAnnotationField(note.QuoteOA, "This is the", "quoted text");
            TestAnnotationField(note.DiscussionOA, "This is my", "discussion");
            TestAnnotationField(note.ResolutionOA, "This is my", "resolution for", "the note");
            TestAnnotationField(note.RecommendationOA, "This is", "mymy link", "suggestion");

            // Check the hyperlink location
            ITsTextProps props = ((IStTxtPara)note.RecommendationOA.ParagraphsOS[1]).Contents.get_Properties(1);
            string       href  = TsStringUtils.GetURL(props.GetStrPropValue((int)FwTextPropType.ktptObjData));

            Assert.AreEqual("http://www.tim.david.com/cooldudes.html", href);

            Assert.AreEqual(0, note.ResponsesOS.Count);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the insert index where a new annotation is inserted when the annotation's
        /// reference is that specified. The index will be at the end of those for the
        /// specified reference.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private int GetInsertIndexForRef(BCVRef startRef)
        {
            IFdoOwningSequence <IScrScriptureNote> notes = NotesOS;

            for (int i = notes.Count - 1; i >= 0; i--)
            {
                IScrScriptureNote note = notes[i];
                if (note.BeginRef <= startRef)
                {
                    return(i + 1);
                }
            }

            return(0);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Connects the notes to new categories using a map created before the new categories
        /// were loaded. If the note category does not already exist, it will create the
        /// category.
        /// </summary>
        /// <param name="map">The map (for each writing system) from the note id to the
        /// full string path of the category name.</param>
        /// <remarks>Limitation: If any category is renamed, any notes that used the previous
        /// name will continue to use the old category. To fix this problem, we would need to
        /// specify in the category file (for each category with a changed name) how the old
        /// category maps to its renamed/relocated category).</remarks>
        /// ------------------------------------------------------------------------------------
        private void ConnectNotesToNewCategories(Dictionary <int, List <string> > map)
        {
            foreach (int noteHvo in map.Keys)
            {
                IScrScriptureNote note = m_scr.Cache.ServiceLocator.GetInstance <IScrScriptureNoteRepository>().GetObject(noteHvo);
                note.CategoriesRS.Clear();                 // Just in case

                List <string> strCategories = map[noteHvo];
                foreach (string strCategory in strCategories)
                {
                    note.CategoriesRS.Add(m_scr.NoteCategoriesOA.FindOrCreatePossibility(
                                              strCategory, m_scr.Cache.DefaultAnalWs));
                }
            }
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Scroll new note into view.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="fromUndoRedo">True if the event was fired from an undo (or rollback) or
        /// redo, false otherwise.</param>
        /// ------------------------------------------------------------------------------------
        private void ScrollAfterPropChangedCompleted(object sender, bool fromUndoRedo)
        {
            // In test teardown, cache may already have been cleared
            if (Cache == null)
            {
                return;
            }
            ((IActionHandlerExtensions)Cache.ActionHandlerAccessor).PropChangedCompleted -= ScrollAfterPropChangedCompleted;
            IScrBookAnnotations annotations = m_scr.BookAnnotationsOS[m_bookNewNote - 1];
            IScrScriptureNote   annotation  = annotations.NotesOS[m_indexNewNote];
            TeNotesVc           notesVc     = CurrentNotesVc;

            if (notesVc != null)
            {
                // tell the VC that the newly inserted item should be expanded. That will cause
                // the view to be updated to show the new note.
                notesVc.ExpandItem(annotation.Hvo, EditedRootBox);
                notesVc.ExpandItem(annotation.DiscussionOA.Hvo, EditedRootBox);
            }

            if (Control != null)
            {
                Control.Focus();
            }

            // Make a selection in the discussion so the user can start to type
            int iPos = m_indexNewNote;

            if (notesVc != null)
            {
                // Get the corresponding index in the virtual property.
                iPos = ((FilteredDomainDataByFlidDecorator)EditedRootBox.DataAccess).
                       GetFilteredIndexOfItem(annotations.Hvo, iPos);
                // New note doesn't match current filter - need to turn it off
                if (iPos < 0)
                {
                    // Turn off the filter so the new note will show
                    ((NotesDataEntryView)Control).OnChangeFilter(null);
                    iPos = ((FilteredDomainDataByFlidDecorator)EditedRootBox.DataAccess).
                           GetFilteredIndexOfItem(annotations.Hvo, m_indexNewNote);
                    Debug.Assert(iPos >= 0);
                }
            }

            IVwRootSite rootSite = Control as IVwRootSite;

            MakeSelectionInNote(notesVc, m_bookNewNote - 1, iPos, rootSite, true);
        }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Implement CreateTestData, called by InMemoryFdoTestBase set up.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			m_mockedChooserDlg = new DynamicMock(typeof(ICmPossibilitySupplier));
			m_mockedDataAccess = new DynamicMock(typeof(IVwCacheDa));

			m_scrInMemoryCache.InitializeAnnotationDefs();
			m_scrInMemoryCache.InitializeScrAnnotationCategories();
			CreateTestUserView();

			// Create some Scripture annotations
			m_annotationsGen = (ScrBookAnnotations)m_scr.BookAnnotationsOS[0];
			ScrReference ref1 = new ScrReference(1, 1, 1, Paratext.ScrVers.English);
			ScrReference ref2 = new ScrReference(1, 1, 2, Paratext.ScrVers.English);
			ScrReference ref3 = new ScrReference(1, 1, 3, Paratext.ScrVers.English);

			// Insert notes for Genesis 1:1, 1:2, and 1:3
			m_note1 = m_annotationsGen.InsertNote(ref1, ref1, null, null, LangProject.kguidAnnConsultantNote);
			m_note2a = m_annotationsGen.InsertNote(ref2, ref2, null, null, LangProject.kguidAnnConsultantNote);
			m_note2b = m_annotationsGen.InsertNote(ref2, ref2, null, null, LangProject.kguidAnnConsultantNote);
			m_note3 = m_annotationsGen.InsertNote(ref3, ref3, null, null, LangProject.kguidAnnConsultantNote);

			m_note1.AnnotationTypeRA = m_inMemoryCache.m_consultantNoteDefn;
			m_note2a.AnnotationTypeRA = m_inMemoryCache.m_consultantNoteDefn;
			m_note2b.AnnotationTypeRA = m_inMemoryCache.m_translatorNoteDefn;
			m_note3.AnnotationTypeRA = m_inMemoryCache.m_translatorNoteDefn;

			m_note1.ResolutionStatus = NoteStatus.Open;
			m_note2a.ResolutionStatus = NoteStatus.Closed;
			m_note2b.ResolutionStatus = NoteStatus.Open;
			m_note3.ResolutionStatus = NoteStatus.Closed;

			m_note1.CategoriesRS.Append(m_inMemoryCache.m_categoryDiscourse);
			m_note2a.CategoriesRS.Append(m_inMemoryCache.m_categoryGrammar);
			m_note2b.CategoriesRS.Append(m_inMemoryCache.m_categoryGrammar_PronominalRef);
			m_note3.CategoriesRS.Append(m_inMemoryCache.m_categoryGrammar_PronominalRef_ExtendedUse);
			m_note3.CategoriesRS.Append(m_inMemoryCache.m_categoryDiscourse); // This note has 2 categories
		}
Exemple #32
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Writes this response to the the specified annotation
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void WriteToCache(IScrScriptureNote ann, FwStyleSheet styleSheet)
		{
			ParagraphCollection parasResponse = new ParagraphCollection(Paragraphs, styleSheet);

			ParagraphCollection.ParaMatchType type;
			int matchIndex = FindMatchingResponse(parasResponse, ann.ResponsesOS, out type);

			switch (type)
			{
				case ParagraphCollection.ParaMatchType.Exact:
				case ParagraphCollection.ParaMatchType.Contains:
					break; // we can ignore the new response -- it's a subset of the old.
				case ParagraphCollection.ParaMatchType.IsContained:
					IStJournalText oldText = ann.ResponsesOS[matchIndex];
					oldText.ParagraphsOS.RemoveAll();
					parasResponse.WriteToCache(oldText);
					break;
				case ParagraphCollection.ParaMatchType.None:
					IStJournalText newText = new StJournalText();
					ann.ResponsesOS.Append(newText);
					parasResponse.WriteToCache(newText);
					break;
			}
		}
Exemple #33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Searches given StText for quoted text.
		/// </summary>
		/// <param name="text">Text to be searche</param>
		/// <param name="note">Note containing quote</param>
		/// <param name="quote">Quote</param>
		/// <returns>
		/// Paragraph that contains quote if quote is found; otherwise <c>null</c> will be returned.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private ICmObject SearchStTextForQuote(IStText text, IScrScriptureNote note, string quote)
		{
			foreach (IStTxtPara para in text.ParagraphsOS)
			{
				if (para.Contents.Length == 0)
					continue;
				// Remove chapter/verse numbers and footnotes from paragraph contents - this is done when
				// quote is created for the note.
				ITsString tssQuote = TsStringUtils.GetCleanTsString(para.Contents, ScrStyleNames.ChapterAndVerse);

				if (tssQuote == null || tssQuote.Length == 0)
					return null;

				string paraContent = tssQuote.Text;
				int offset = paraContent.IndexOf(quote);
				if (offset >= 0)
				{
					// offsets may be off slightly because of removed characters
					note.BeginOffset = offset;
					note.EndOffset = offset + quote.Length;
					return para;
				}
			}

			return null;
		}
Exemple #34
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Finds replacement reference in current book for missing object reference.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void FindMissingReference(IScrBook book, IScrScriptureNote note)
		{
			if (!note.QuoteOA.IsEmpty)
				note.BeginObjectRA = note.EndObjectRA = FindQuoteInTitleOrIntro(book, note);

			if (note.BeginObjectRA == null)
				note.BeginObjectRA = note.EndObjectRA = book.FirstSection.IsIntro ? book.FirstSection.FirstContentParagraph : null;

			if (note.BeginObjectRA == null)
				note.BeginObjectRA = note.EndObjectRA = (IStTxtPara)book.TitleOA.ParagraphsOS[0];
		}
Exemple #35
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Attaches the annotated objects, if they're not already attached.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void AttachAnnotatedObjects(int bookNum, IScrScriptureNote note)
		{
			IScrBook book = FindBook(bookNum);
			if (book != null)
				AttachAnnotatedObjects(book, note);
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Updates the highlighted note to be the specified note.
		/// </summary>
		/// <param name="ann">The note to highlight.</param>
		/// ------------------------------------------------------------------------------------
		private void UpdateNoteHighlight(IScrScriptureNote ann)
		{
			if (ann == null || m_prevHightlightedNote == ann || m_suspendHighlightChange)
				return;

			SelectionHelper sel = EditingHelper.CurrentSelection;

			// Only selection that can get updated is a re-install of a previous selection so
			// don't bother with any selection update handling.
			m_ignoreSelChanged = true;
			try
			{
				// Need to user real object index when doing a prop change - the GetDisplayIndex method on the filter will change
				// this to the filtered index.
				m_vc.SelectedNoteHvo = ann.Hvo;
				if (m_prevHightlightedNote != null && m_prevHightlightedNote.IsValidObject)
				{
					int ownerHvo = m_prevHightlightedNote.Owner.Hvo;
					RootBox.PropChanged(ownerHvo, ScrBookAnnotationsTags.kflidNotes, m_prevHightlightedNote.IndexInOwner, 1, 1);
				}

				RootBox.PropChanged(ann.Owner.Hvo, ScrBookAnnotationsTags.kflidNotes, ann.IndexInOwner, 1, 1);

				m_prevHightlightedNote = ann;

				if (sel != null)
					sel.SetSelection(false); // restore selection taken from PropChange
			}
			finally
			{
				m_ignoreSelChanged = false;
			}
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Shows the category chooser dialog to let the user set the category for the
		/// specified annotation.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void SetAnnotationCategory(IScrScriptureNote ann)
		{
			if (ann == null)
				return; // Not much we can do

			m_rootb.DestroySelection();
			string sUndo, sRedo;
			TeResourceHelper.MakeUndoRedoLabels("kstidSetAnnotationCategory", out sUndo, out sRedo);

			using (new WaitCursor(this))
			using (CategoryChooserDlg dlg = new CategoryChooserDlg(m_scr.NoteCategoriesOA,
				ann.CategoriesRS.ToHvoArray(), m_helpTopicProvider, TheMainWnd.App))
			{
				if (dlg.ShowDialog(ParentForm) == DialogResult.OK)
				{
					using (UndoTaskHelper undoHelper = new UndoTaskHelper(this, sUndo, sRedo))
					{
						dlg.GetPossibilities(ann.CategoriesRS);
						ann.DateModified = DateTime.Now;
						undoHelper.RollBack = false;
					}
				}
			}
		}
Exemple #38
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Selects the given note's cited text in a picture caption.
		/// </summary>
		/// <param name="iBook">The index of the book in the filter (this is passed as a
		/// convenience -- it could be recalculated).</param>
		/// <param name="note">The note.</param>
		/// ------------------------------------------------------------------------------------
		private void SelectCitedTextInPictureCaption(int iBook, IScrScriptureNote note)
		{
			try
			{
				CmPicture picture = new CmPicture(Cache, note.BeginObjectRAHvo);
				int iSection, iPara, ichOrcPos;
				ITsString citedText = note.CitedTextTss;
				if (!FindPictureInVerse(new ScrReference(note.BeginRef, m_scr.Versification),
					picture.Hvo, out iSection, out iPara, out ichOrcPos))
				{
					throw new Exception("Picture ORC not found in verse"); // See catch
				}
				int ichStart, ichEnd;
				ITsString sCaptionText = picture.Caption.VernacularDefaultWritingSystem.UnderlyingTsString;
				if (sCaptionText.Length >= note.EndOffset &&
					StringUtils.Substring(sCaptionText, note.BeginOffset,
					note.EndOffset - note.BeginOffset) == citedText)
				{
					ichStart = note.BeginOffset;
					ichEnd = note.EndOffset;
				}
				else
				{
					// Search for word form in caption
					if (!StringUtils.FindWordFormInString(citedText, sCaptionText,
						m_cache.LanguageWritingSystemFactoryAccessor, out ichStart, out ichEnd))
					{
						ichStart = ichEnd = 0;
					}
				}
				MakeSelectionInPictureCaption(iBook, iSection,
					(int)ScrSection.ScrSectionTags.kflidContent, iPara,
					ichOrcPos, ichStart, ichEnd);
			}
			catch
			{
				// Picture or caption no longer exists. Go to the start of the specified verse.
				GotoVerse(new ScrReference(note.BeginRef, m_scr.Versification));
				return;
			}
		}
Exemple #39
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Displays an annotation expanded or contracted
		/// </summary>
		/// <param name="vwenv"></param>
		/// <param name="ann"></param>
		/// <param name="expanded"></param>
		/// ------------------------------------------------------------------------------------
		private void DisplayAnnotation(IVwEnv vwenv, IScrScriptureNote ann, bool expanded)
		{
			#region First row has status, ref, category, & quote
			SetBackgroundColorForNote(ann, vwenv);

			OpenTableRow(vwenv, ann);

			// Display expand box (+/-) in the first cell
			//InsertNoteSeparator(vwenv);
			vwenv.OpenTableCell(1, 1);
			vwenv.AddObj(ann.Hvo, this, (int)NotesFrags.kfrExpansion);
			vwenv.CloseTableCell();

			// Display status in the second cell
			vwenv.OpenTableCell(1, 1);
			vwenv.set_IntProperty((int)FwTextPropType.ktptPadTop,
				(int)FwTextPropVar.ktpvMilliPoint, 1000);

			if (ann.AnnotationType == NoteType.CheckingError)
			{
				// When the annotation is a checking error, we don't want clicking on the status
				// to change the status. Therefore, make the min and max the same.
				vwenv.AddIntPropPic((int)ScrScriptureNoteTags.kflidResolutionStatus,
					this, (int)NotesFrags.kfrStatus, 0, 0);
			}
			else
			{
				vwenv.AddIntPropPic((int)ScrScriptureNoteTags.kflidResolutionStatus,
					this, (int)NotesFrags.kfrStatus, (int)NoteStatus.Open, (int)NoteStatus.Closed);
			}
			vwenv.CloseTableCell();

			// Display reference in the third cell and make it readonly.
			vwenv.OpenTableCell(1, 1);
			vwenv.set_IntProperty((int)FwTextPropType.ktptEditable, (int)FwTextPropVar.ktpvDefault, 0);
			vwenv.OpenParagraph();
			vwenv.AddProp((int)CmBaseAnnotationTags.kflidBeginRef, this, (int)NotesFrags.kfrScrRef);
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			// Display CONNOT category in the fourth (and possibly fifth and sixth) cell(s)
			vwenv.OpenTableCell(1, expanded ? 3 : 1);
			IStTxtPara quotePara = ann.QuoteOA[0];
			bool fQuoteParaRtoL = IsParaRightToLeft(quotePara);

			// Conc paragraphs don't work well for R-to-L: If the text doesn't fit, it will
			// show the trailing text rather than the leading text.
			if (fQuoteParaRtoL || expanded)
				vwenv.OpenParagraph();
			else
				vwenv.OpenConcPara(0, 0, 0, 0);
			vwenv.AddObjVec((int)ScrScriptureNoteTags.kflidCategories, this,
				(int)NotesFrags.kfrConnotCategory);
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			// Display CONNOT category chooser button in the penultimate or last cell
			vwenv.OpenTableCell(1, 1);
			vwenv.set_IntProperty((int)FwTextPropType.ktptPadTop,
				(int)FwTextPropVar.ktpvMilliPoint, 1000);
			vwenv.set_IntProperty((int)FwTextPropType.ktptPadLeading,
				(int)FwTextPropVar.ktpvMilliPoint, 2000);

			vwenv.AddPicture(m_picChooser, -(int)NotesFrags.kfrConnotCategory, 0, 0);
			vwenv.CloseTableCell();

			// If not expanded, display the quote in the last cell
			if (!expanded)
			{
				vwenv.OpenTableCell(1, 1);
				SetupWsAndDirectionForPara(vwenv, quotePara.Hvo);
				if (fQuoteParaRtoL)
					vwenv.OpenParagraph(); // Conc paragraphs don't work well for R-to-L
				else
					vwenv.OpenConcPara(0, 0, 0, 0);
				vwenv.AddString(quotePara.Contents);
				vwenv.CloseParagraph();
				vwenv.CloseTableCell();
			}

			CloseTableRow(vwenv, ann);
			#endregion

			if (!expanded)
				return;

			#region Second through fifth rows
			bool fRegularAnnotation = ann.AnnotationType != NoteType.CheckingError;
			//Second row has quote
			DisplayExpandableAnnotation(vwenv, ann,
				(int)ScrScriptureNoteTags.kflidQuote,
				ann.QuoteOA.Hvo, ann.QuoteOA,
				fRegularAnnotation ? m_quoteLabel : m_detailsLabel, !fRegularAnnotation);

			// Third row has discussion
			DisplayExpandableAnnotation(vwenv, ann,
				ScrScriptureNoteTags.kflidDiscussion,
				ann.DiscussionOA.Hvo, ann.DiscussionOA,
				fRegularAnnotation ? m_discussionLabel : m_messageLabel, !fRegularAnnotation);

			// Fourth row has recommendation (i.e. suggestion)
			DisplayExpandableAnnotation(vwenv, ann,
				ScrScriptureNoteTags.kflidRecommendation,
				ann.RecommendationOA.Hvo, ann.RecommendationOA, m_suggestionLabel);

			// Fifth row has resolution
			DisplayExpandableAnnotation(vwenv, ann,
				ScrScriptureNoteTags.kflidResolution,
				ann.ResolutionOA.Hvo, ann.ResolutionOA, m_resolutionLabel);

			#endregion

			#region Sixth row has author
			SetBackgroundColorForNote(ann, vwenv);
			OpenTableRow(vwenv, ann);

			// Display empty first and second cell
			vwenv.OpenTableCell(1, 2);
			vwenv.CloseTableCell();

			// Display author in third cell
			vwenv.OpenTableCell(1, 3);
			vwenv.OpenParagraph();
			SetDisabledColorForNote(vwenv);
			vwenv.AddString(m_authorLabel);
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			CloseTableRow(vwenv, ann);
			#endregion

			#region Seventh row has dates
			SetBackgroundColorForNote(ann, vwenv);
			OpenTableRow(vwenv, ann);

			// Display empty first and second cell
			vwenv.OpenTableCell(1, 2);
			vwenv.CloseTableCell();

			// Display date created in third cell
			vwenv.OpenTableCell(1, 1);
			vwenv.OpenParagraph();
			vwenv.AddString(m_createdLabel);
			vwenv.AddTimeProp(CmAnnotationTags.kflidDateCreated, 0);
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			// Display date modified in fourth/fifth cells
			vwenv.OpenTableCell(1, 2);
			vwenv.OpenParagraph();
			vwenv.AddString(m_modifiedLabel);
			vwenv.AddTimeProp(CmAnnotationTags.kflidDateModified, 0);
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			// Display date resolved in last two cells
			vwenv.OpenTableCell(1, 2);
			vwenv.OpenParagraph();
			if (ann.ResolutionStatus == NoteStatus.Closed)
			{
				SetDisabledColorForNote(vwenv);
				vwenv.AddString(m_resolvedLabel);
				// TODO (TE-4039) This date is incorrect
				//vwenv.AddTimeProp(ScrScriptureNote.ScrScriptureNoteTags.kflidDateResolved, 0);
			}
			vwenv.CloseParagraph();
			vwenv.CloseTableCell();

			CloseTableRow(vwenv, ann);
			#endregion
		}
Exemple #40
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Displays an expandable annotation of the specified type.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void DisplayExpandableAnnotation(IVwEnv vwenv, IScrScriptureNote ann,
			int tag, int hvo, IStJournalText paras, ITsString label)
		{
			DisplayExpandableAnnotation(vwenv, ann, tag, hvo, paras, label, false);
		}
Exemple #41
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Displays an expandable annotation of the specified type.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void DisplayExpandableAnnotation(IVwEnv vwenv, IScrScriptureNote ann,
			int tag, int hvo, IStJournalText paras, ITsString label, bool readOnly)
		{
			vwenv.NoteDependency(new int[] { hvo }, new int[] { m_expansionTag }, 1);
			SetBackgroundColorForNote(ann, vwenv);
			OpenTableRow(vwenv, ann);

			// Display empty first cell
			vwenv.OpenTableCell(1, 1);
			vwenv.CloseTableCell();

			// Display +/- in the second cell, unless this is read-only
			vwenv.OpenTableCell(1, 1);
			if (!readOnly)
				vwenv.AddObjProp(tag, this, (int)NotesFrags.kfrExpansion);
			vwenv.CloseTableCell();

			// Display text in the remaining cells
			vwenv.OpenTableCell(1, 5);
			vwenv.OpenConcPara(0, 0, 0, 0);
			vwenv.AddString(label);

			if (!m_expandTable.ContainsKey(hvo))
				vwenv.AddString(paras[0].Contents);

			vwenv.CloseParagraph();
			vwenv.CloseTableCell();
			CloseTableRow(vwenv, ann);

			if (!m_expandTable.ContainsKey(hvo))
				return;

			SetBackgroundColorForNote(ann, vwenv);
			OpenTableRow(vwenv, ann);

			// Display empty first and second cell
			vwenv.OpenTableCell(1, 2);
			vwenv.CloseTableCell();

			// Display text in cells 3-7
			vwenv.OpenTableCell(1, 5);
			if (!readOnly)
				SetEditBackground(vwenv);
			vwenv.AddObjProp(tag, this, (int)StTextFrags.kfrText);
			vwenv.CloseTableCell();
			CloseTableRow(vwenv, ann);
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Notifies anyone who cares to synchronize to the specified annotation's begin
		/// reference.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="annotation">The annotation.</param>
		/// <param name="scr">The IScrScripture to which the annotation belongs.</param>
		/// ------------------------------------------------------------------------------------
		public void SyncToAnnotation(object sender, IScrScriptureNote annotation, IScripture scr)
		{
			Debug.Assert(annotation != null);

			if (m_fIgnoreAnySyncMessages || m_fProcessingSyncMessage)
				return;

			if (AnnotationChanged != null)
				AnnotationChanged(sender, annotation);

			ScrReference scrRef = new ScrReference(annotation.BeginRef, scr.Versification);
			if (scrRef.Valid || scrRef.IsBookTitle)
			{
				SyncUsfmBrowser(new ScrReference(scrRef));
				SendExternalSyncMessage(scrRef);
			}
		}
Exemple #43
0
		//        /// ------------------------------------------------------------------------------------
		//        /// <summary>
		//        /// Find out how this text matches up to the paragraph strings in bldrs.
		//        /// </summary>
		//        /// <param name="text">The journal text.</param>
		//        /// <param name="paragraphs">The list of paragraphs.</param>
		//        /// <returns></returns>
		//        /// <remarks>THIS NEEDS SOME THOROUGH TESTING, INCLUDING A UNIT TEST!!</remarks>
		//        /// ------------------------------------------------------------------------------------
		//        private static ParaMatchType DoesTextMatch(IStJournalText text, ParagraphCollection paragraphs)
		//        {
		//            ParaMatchType bestType = ParaMatchType.None;
		//#if MATCHTEXTS
		//            ParaMatchType type = ParaMatchType.None;
		//            if (text.ParagraphsOS.Count >= bldrs.Count)
		//            {
		//                if (text.ParagraphsOS.Count == 0 && rgtss.Count == 0)
		//                    return ParaMatchType.Exact;
		//                int iPrevMatch = -1;
		//                for (int i = 0; i < text.ParagraphsOS.Count; ++i)
		//                {
		//                    int iMatch = FindMatchingParagraph(text.ParagraphsOS[i] as IStTxtPara, rgtss, out type);
		//                    switch (type)
		//                    {
		//                        case ParaMatchType.None:
		//                            return type;
		//                        case ParaMatchType.Exact:
		//                            if (iMatch == i)
		//                            {
		//                                if (bestType != ParaMatchType.Exact)
		//                                {
		//                                    if (bestType == ParaMatchType.None)
		//                                        bestType = type;
		//                                    // else it stays the same. Exact is subsumed by both Contains and IsContained
		//                                }
		//                            }
		//                            else if (iMatch > iPrevMatch)
		//                            {
		//                                if (bestType == ParaMatchType.Contains)
		//                                    return ParaMatchType.None;
		//                                else
		//                                    bestType = ParaMatchType.IsContained;
		//                            }
		//                            else
		//                            {
		//                                return ParaMatchType.None;
		//                            }
		//                            break;
		//                        case ParaMatchType.Contains:
		//                            if (iMatch == i)
		//                            {
		//                                if (bestType != ParaMatchType.IsContained)
		//                                    bestType = type;
		//                                else
		//                                    return ParaMatchType.None;
		//                            }
		//                            else
		//                            {
		//                                return ParaMatchType.None;
		//                            }
		//                            break;
		//                        case ParaMatchType.IsContained:
		//                            if (iMatch == i || iMatch > iPrevMatch)
		//                            {
		//                                if (bestType != ParaMatchType.Contains)
		//                                    bestType = type;
		//                                else
		//                                    return ParaMatchType.None;
		//                            }
		//                            else
		//                            {
		//                                return ParaMatchType.None;
		//                            }
		//                            break;
		//                    }
		//                    iPrevMatch = iMatch;
		//                }
		//            }
		//            else
		//            {

		//            }
		//#endif
		//            return bestType;
		//        }
		#endregion

		#region static methods
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="XmlNoteResponse"/> class based on the
		/// specified category.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public static List<XmlNoteResponse> GetResponsesList(IScrScriptureNote ann, int wsDefault,
			ILgWritingSystemFactory lgwsf)
		{
			if (ann == null)
				return null;

			List<XmlNoteResponse> responses = new List<XmlNoteResponse>();
			foreach (IStJournalText txt in ann.ResponsesOS)
				responses.Add(new XmlNoteResponse(txt, wsDefault, lgwsf));

			return (responses.Count == 0 ? null : responses);
		}
Exemple #44
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Set the background color based on the type of annotation
		/// </summary>
		/// <param name="ann">annotation</param>
		/// <param name="vwenv"></param>
		/// ------------------------------------------------------------------------------------
		private void SetBackgroundColorForNote(IScrScriptureNote ann, IVwEnv vwenv)
		{
			int color = (int)ColorUtil.ConvertColorToBGR(GetNoteBackgroundColor(ann));

			switch (ann.AnnotationType)
			{
				case NoteType.Consultant:
					vwenv.set_IntProperty((int)FwTextPropType.ktptBackColor,
						(int)FwTextPropVar.ktpvDefault, color);
					break;

				case NoteType.Translator:
					vwenv.set_IntProperty((int)FwTextPropType.ktptBackColor,
						(int)FwTextPropVar.ktpvDefault, color);
					break;

				case NoteType.CheckingError:
					vwenv.set_IntProperty((int)FwTextPropType.ktptBackColor,
						(int)FwTextPropVar.ktpvDefault, color);
					break;

				default:
					throw new Exception("Unexpected annotation type");
			}
		}
Exemple #45
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Goes to the text referenced in the ScrScriptureNote. If it does not find the text,
		/// it makes the closest selection to the referenced text that it can.
		/// </summary>
		/// <param name="note">the note containing the Scripture reference to find</param>
		/// <param name="sendSyncMsg"><c>true</c> to not send a focus sychronization message
		/// when the selection is changed by going to the scripture ref.</param>
		/// ------------------------------------------------------------------------------------
		public void GoToScrScriptureNoteRef(IScrScriptureNote note, bool sendSyncMsg)
		{
			// TODO (TE-1729): Use this method correctly from Annotations view.

			ScrReference scrRef = new ScrReference(note.BeginRef, m_scr.Versification);
			ScrBook book = BookFilter.GetBookByOrd(scrRef.Book);
			if (book == null)
				return;

			int iBook = BookFilter.GetBookIndex(book.Hvo);
			bool fOrigIgnoreAnySyncMessages = false;
			if (m_syncHandler != null)
			{
				fOrigIgnoreAnySyncMessages = m_syncHandler.IgnoreAnySyncMessages;
				m_syncHandler.IgnoreAnySyncMessages = true;
			}

			try
			{
				if (note.Flid == (int)CmPicture.CmPictureTags.kflidCaption)
				{
					SelectCitedTextInPictureCaption(iBook, note);
					return;
				}

				int ichStart, ichEnd;
				string citedText = note.CitedText;
				ITsString citedTextTss = note.CitedTextTss;
				StTxtPara para = note.BeginObjectRA as StTxtPara;
				if (para != null && m_cache.GetOwnerOfObjectOfClass(para.Hvo, ScrDraft.kClassId) == 0)
				{
					if (para.Owner is StFootnote)
					{
						// Make selection in footnote.
						if (TextAtExpectedLoc(para.Contents.Text, citedText, note.BeginOffset, note.EndOffset))
						{
							// Select text in footnote.
							StFootnote footnote = para.Owner as StFootnote;
							if (footnote == null)
								return;

							SelectionHelper selHelper = new SelectionHelper();
							selHelper.AssocPrev = false;
							selHelper.NumberOfLevels = 3;
							selHelper.LevelInfo[2].tag = BookFilter.Tag;
							selHelper.LevelInfo[2].ihvo = iBook;
							selHelper.LevelInfo[1].tag = (int)ScrBook.ScrBookTags.kflidFootnotes;
							selHelper.LevelInfo[1].ihvo = footnote.IndexInOwner;
							selHelper.LevelInfo[0].ihvo = 0;

							// Prepare to move the IP to the specified character in the paragraph.
							selHelper.IchAnchor = note.BeginOffset;
							selHelper.IchEnd = note.EndOffset;

							// Now that all the preparation to set the IP is done, set it.
							selHelper.SetSelection(Callbacks.EditedRootBox.Site, true, true);
						}
						return;
					}

					// Make selection in Scripture text
					if (TextAtExpectedLoc(para.Contents.Text, citedText, note.BeginOffset, note.EndOffset))
					{
						SelectRangeOfChars(iBook, para, note.BeginOffset, note.EndOffset);
						return;
					}

					if (scrRef.Verse == 0)
					{
						// Either a missing chapter number or something in intro material.
						// Not much chance of finding it by reference (even if the chapter number
						// has been added, we never find the 0th verse, and 99% of the time that
						// chapter number would have been added to the same paragraph where it
						// was missing in the first place), so just try to find the text in the
						// paragraph, if it still exists.
						if (string.IsNullOrEmpty(citedText))
						{
							SelectRangeOfChars(iBook, para, note.BeginOffset, note.BeginOffset);
							return;
						}

						// The text may be null if the paragraph only contains the prompt. TE-8315
						if (para.Contents.Text != null)
						{
							int i = para.Contents.Text.IndexOf(citedText);
							if (i >= 0)
							{
								SelectRangeOfChars(iBook, para, i, i + citedText.Length);
								return;
							}
						}
					}
				}


				// A selection could not be made at the specified location. Attempt to go to
				// the specified verse and then try to find the text.

				// REVIEW (TimS): Why do we call GotoVerse here when we select the characters
				// down below? We might consider doing this only if we fail down below.
				if (sendSyncMsg)
					GotoVerse(scrRef);
				else
					GotoVerse_WithoutSynchMsg(scrRef);

				int iSection, iPara;
				if (citedText != null && FindTextInVerse(m_scr, citedTextTss, scrRef, false, out iSection,
					out iPara, out ichStart, out ichEnd))
				{
					// We found the text in the verse at a different character offset.
					SelectRangeOfChars(iBook, iSection, iPara, ichStart, ichEnd);
				}
				else if (note.BeginOffset > 0 && para != null &&
					IsOffsetValidLoc(para.Contents.Text, note.BeginOffset))
				{
					// We couldn't find the cited text at the specified offset, nor anywhere
					// in the paragraph. Therefore, just set the IP at the begin offset.
					SelectRangeOfChars(iBook, para, note.BeginOffset, note.BeginOffset);
				}
			}
			finally
			{
				if (m_syncHandler != null)
					m_syncHandler.IgnoreAnySyncMessages = fOrigIgnoreAnySyncMessages;
			}
		}
Exemple #46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Closes the table row.
		/// </summary>
		/// <param name="vwenv">The view environment.</param>
		/// <param name="ann">The annotation being displayed.</param>
		/// ------------------------------------------------------------------------------------
		private void CloseTableRow(IVwEnv vwenv, IScrScriptureNote ann)
		{
			if (ann.Hvo != SelectedNoteHvo)
			{
				// Display cell used for padding (to right-indent unselected annotations by
				// the width of the frame used to highlight the selected annotation).
				vwenv.OpenTableCell(1, 1);
				vwenv.AddString(m_tssEmpty);
				vwenv.CloseTableCell();
			}

			vwenv.CloseTableRow();
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// We override this method to make a selection in all of the views that are in a
		/// snynced group. This fixes problems where the user changes the selection in one of
		/// the slaves, but the master is not updated. Thus the view is not scrolled as the
		/// groups scroll position only scrolls the master's selection into view. (TE-3380)
		/// </summary>
		/// <param name="prootb"></param>
		/// <param name="vwselNew"></param>
		/// ------------------------------------------------------------------------------------
		protected override void HandleSelectionChange(IVwRootBox prootb, IVwSelection vwselNew)
		{
			CheckDisposed();
			base.HandleSelectionChange(prootb, vwselNew);

			if (m_ignoreSelChanged || EditingHelper.CurrentSelection == null)
				return;

			SelLevInfo noteInfo = EditingHelper.CurrentSelection.GetLevelInfoForTag(kCurrentNotesTag);
			if (m_prevNote != null && noteInfo.hvo == m_prevNote.Hvo)
				return;

			// Set text of caption to indicate which annotation is selected
			IScrScriptureNote ann = Cache.ServiceLocator.GetInstance<IScrScriptureNoteRepository>().GetObject(noteInfo.hvo);
			// Remove highlighting on previously selected annotation, and add highlighting to selected annotation.
			UpdateNoteHighlight(ann);

			m_notesMainWnd.InformationBarText = BaseInfoBarCaption + " - " + GetRefAsString(ann) + "     " +
				GetQuotedText(ann.QuoteOA, 30);

			m_prevNote = ann;

			if (!m_fSendSyncScrollMsg)
				return;

			NotesMainWnd notesMainWnd = TheMainWnd as NotesMainWnd;
			if (notesMainWnd != null && notesMainWnd.SyncHandler != null)
			{
				Trace.WriteLine("Calling SyncToAnnotation from NotesDataEntryView: " + ann.CitedText);
				notesMainWnd.SyncHandler.SyncToAnnotation(this, ann, m_scr);
			}
		}
Exemple #48
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:CheckingError"/> class.
		/// </summary>
		/// <param name="note">The note being decorated</param>
		/// ------------------------------------------------------------------------------------
		private CheckingError(IScrScriptureNote note)
		{
			m_note = note;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets the Scripture reference of the specified annotation as string.
		/// </summary>
		/// <param name="ann">The specified annotation.</param>
		/// ------------------------------------------------------------------------------------
		private string GetRefAsString(IScrScriptureNote ann)
		{
			BCVRef startRef = new BCVRef(ann.BeginRef);
			IScrBook book = m_scr.FindBook(startRef.Book);
			string bookName;
			// Book for note may not be in the project.
			if (book != null)
				bookName = book.BestUIName;
			else
			{
				IScrBookRef bookRef = Cache.ServiceLocator.GetInstance<IScrRefSystemRepository>().Singleton.BooksOS[startRef.Book - 1];
				ITsString tsName = bookRef.BookName.get_String(Cache.DefaultUserWs);
				if (tsName.Length == 0)
					tsName = bookRef.BookName.BestAnalysisAlternative;
				bookName = tsName.Text;
			}

			string titleText = ResourceHelper.GetResourceString("kstidScriptureTitle");
			string introText = ResourceHelper.GetResourceString("kstidScriptureIntro");
			return BCVRef.MakeReferenceString(bookName, startRef, new BCVRef(ann.EndRef),
				m_scr.ChapterVerseSepr, m_scr.Bridge, titleText, introText);
		}
Exemple #50
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Provides access to the "MakeLabelFromText" method.
		/// </summary>
		/// <param name="labelText">text to put in the label</param>
		/// <param name="styleName">style name to use for the character style on the text</param>
		/// <param name="ann">The annotation.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		public ITsString CallMakeLabelFromText(string labelText, string styleName,
			IScrScriptureNote ann)
		{
			return base.MakeLabelFromText(labelText, styleName, ann);
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Resets the prev note hvo.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void ResetPrevNoteHvo()
		{
			CheckDisposed();
			m_prevNote = null;
		}
Exemple #52
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Make a label string to use in the view.
		/// </summary>
		/// <param name="labelText">text to put in the label</param>
		/// <param name="styleName">style name to use for the character style on the text</param>
		/// <param name="ann">The annotation</param>
		/// <returns>An ITsString</returns>
		/// ------------------------------------------------------------------------------------
		protected ITsString MakeLabelFromText(string labelText, string styleName,
			IScrScriptureNote ann)
		{
			ITsTextProps ttpLabel = StyleUtils.CharStyleTextProps(styleName,
				m_cache.WritingSystemFactory.UserWs);
			ITsStrBldr bldr = TsStrBldrClass.Create();
			if (ann != null && ann.BeginObjectRA != null && ann.BeginObjectRA.IsValidObject)
			{
				IStTxtPara startPara = ann.BeginObjectRA as IStTxtPara;
				if (startPara != null)
				{
					int ownerOwnFlid = startPara.Owner.OwningFlid;
					if (ownerOwnFlid == ScrBookTags.kflidFootnotes)
					{
#if __MonoCS__
			const string fontname = "OpenSymbol";
			const string symbol = "\u2042";
#else
			const string fontname = "Marlett";
			const string symbol = "\u0032";
#endif
						ITsPropsBldr propsBldr = TsPropsBldrClass.Create();
						propsBldr.SetStrPropValue((int)FwTextPropType.ktptFontFamily, fontname);
						propsBldr.SetIntPropValues((int)FwTextPropType.ktptWs, 0, m_cache.WritingSystemFactory.UserWs);
						bldr.Replace(0, 0, symbol, propsBldr.GetTextProps());
					}
				}
			}
			bldr.Replace(bldr.Length, bldr.Length, labelText, ttpLabel);

			// Add a space with default paragraph characters. This prevents style bleed-through
			// from the label when the user types in the text with (part of) the label selected.
			bldr.Replace(bldr.Length, bldr.Length, " ", StyleUtils.CharStyleTextProps(null,
				m_cache.WritingSystemFactory.UserWs));
			return bldr.GetString();
		}
Exemple #53
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Attaches the annotated objects, if they're not already attached.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void AttachAnnotatedObjects(IScrBook book, IScrScriptureNote note)
		{
			if (note.BeginObjectRA == null)
				FindMissingReference(book, note);
			else if (note.BeginObjectRA.OwnerOfClass<IScrBook>() != book)
			{
				note.BeginObjectRA = note.EndObjectRA = FindCorrespondingParagraph(book, note.BeginObjectRA);
				if (note.BeginObjectRA == null)
					FindMissingReference(book, note);
			}
		}
Exemple #54
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Make a label string to use in the view.
		/// </summary>
		/// <param name="labelText">text to put in the label</param>
		/// <param name="ann">The annotation</param>
		/// <returns>An ITsString</returns>
		/// ------------------------------------------------------------------------------------
		private ITsString MakeLabelFromText(string labelText, IScrScriptureNote ann)
		{
			return MakeLabelFromText(labelText, ScrStyleNames.NotationTag, ann);
		}
Exemple #55
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Finds paragraph int the title or introduction of the passed book that contains the
		/// passed quote.
		/// </summary>
		/// <param name="book">Current version of book</param>
		/// <param name="note">Note containing quote</param>
		/// <returns>
		/// Paragraph in title or intro that contains quote if quote is found;
		/// otherwise <c>null</c> will be returned.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private ICmObject FindQuoteInTitleOrIntro(IScrBook book, IScrScriptureNote note)
		{
			string quote = note.QuoteOA[0].Contents.Text;
			ICmObject result = SearchStTextForQuote(book.TitleOA, note, quote);
			if (result == null)
			{
				IScrSection section = book.SectionsOS[0];
				int sectionIndex = 0;
				while (section.IsIntro)
				{
					result = SearchStTextForQuote(section.HeadingOA, note, quote);
					if (result != null)
						break;
					result = SearchStTextForQuote(section.ContentOA, note, quote);
					if (result != null)
						break;
					sectionIndex++;
					if (sectionIndex >= book.SectionsOS.Count)
						break;
					section = book.SectionsOS[sectionIndex];
				}
			}
			return result;
		}
Exemple #56
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets the color of the note background.
		/// </summary>
		/// <param name="ann">The ann.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private Color GetNoteBackgroundColor(IScrScriptureNote ann)
		{
			switch (ann.AnnotationType)
			{
				case NoteType.Consultant: return Color.PaleGoldenrod;
				case NoteType.Translator: return Color.LightBlue;
				case NoteType.CheckingError: return Color.PaleGreen;
				default: return Color.Red;
			}
		}
Exemple #57
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="XmlScrNote"/> class based on
		/// the given Scripture note.
		/// </summary>
		/// <param name="ann">The Scripture annotation.</param>
		/// <param name="wsDefault">The default (analysis) writing system.</param>
		/// <param name="lgwsf">The writing system factory.</param>
		/// ------------------------------------------------------------------------------------
		public XmlScrNote(IScrScriptureNote ann, int wsDefault, ILgWritingSystemFactory lgwsf)
			: this()
		{
			m_wsDefault = wsDefault;
			m_lgwsf = lgwsf;
			ResolutionStatus = ann.ResolutionStatus;
			m_typeName = ann.AnnotationTypeRA.Name.get_String(WritingSystemServices.FallbackUserWs(ann.Cache)).Text;
			m_guidType = ann.AnnotationTypeRA.Guid;
			SetNoteType(ann);

			m_startRef = ann.BeginRef;
			if (ann.BeginRef != ann.EndRef)
				m_endRef = ann.EndRef;

			if (ann.BeginObjectRA != null)
				m_guidBegObj = ann.BeginObjectRA.Guid;

			if (ann.BeginObjectRA != ann.EndObjectRA && ann.EndObjectRA != null)
				m_guidEndObj = ann.EndObjectRA.Guid;

			BeginOffset = ann.BeginOffset;
			EndOffset = ann.EndOffset;

			m_createdDate = ann.DateCreated;
			m_modifiedDate = ann.DateModified;
			m_resolvedDate = ann.DateResolved;

			Quote = XmlNotePara.GetParagraphList(ann.QuoteOA, m_wsDefault, m_lgwsf);
			Discussion = XmlNotePara.GetParagraphList(ann.DiscussionOA, m_wsDefault, m_lgwsf);
			Suggestion = XmlNotePara.GetParagraphList(ann.RecommendationOA, m_wsDefault, m_lgwsf);
			Resolution = XmlNotePara.GetParagraphList(ann.ResolutionOA, m_wsDefault, m_lgwsf);
			Categories = XmlNoteCategory.GetCategoryList(ann, m_lgwsf);
			Responses = XmlNoteResponse.GetResponsesList(ann, m_wsDefault, m_lgwsf);
		}
Exemple #58
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Scrolls to cited text.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="annotation">The annotation whose reference and cited text we should
		/// sync. to.</param>
		/// ------------------------------------------------------------------------------------
		void ScrollToCitedText(object sender, IScrScriptureNote annotation)
		{
			CheckDisposed();
			if (sender != this && annotation != null)
				GoToScrScriptureNoteRef(annotation, false);
		}
Exemple #59
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates an instance of a CheckingError object if the hvo is for an annotation
		/// that really is a CheckingError.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		internal static CheckingError Create(IScrScriptureNote error)
		{
			if (error == null)
				throw new ArgumentNullException("Null note cannot be used");
			return (error.AnnotationType != NoteType.CheckingError ? null : new CheckingError(error));
		}
Exemple #60
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Goes to the text referenced in the ScrScriptureNote. If it does not find the text,
		/// it makes the closest selection to the referenced text that it can.
		/// </summary>
		/// <param name="note">the note containing the Scripture reference to find</param>
		/// ------------------------------------------------------------------------------------
		public void GoToScrScriptureNoteRef(IScrScriptureNote note)
		{
			GoToScrScriptureNoteRef(note, true);
		}