Esempio n. 1
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the text representation of the back translations for a footnote paragraph.
        /// </summary>
        /// <param name="footnotePara">The footnote paragraph.</param>
        /// <returns>
        /// text representation of all of the back translations for the footnote paragraph
        /// </returns>
        /// ------------------------------------------------------------------------------------
        private string GetTextRepresentationOfTrans(StTxtPara footnotePara)
        {
            string        transRepresentation = string.Empty;
            CmTranslation trans = (CmTranslation)footnotePara.GetBT();

            if (trans == null)
            {
                return(transRepresentation);
            }

            List <int> transWs = m_cache.GetUsedScriptureTransWsForPara(footnotePara.Hvo);

            foreach (int ws in transWs)
            {
                ITsString tss = trans.Translation.GetAlternativeTss(ws);
                if (tss != null && tss.Length > 0)
                {
                    LgWritingSystem lgws = new LgWritingSystem(m_cache, ws);
                    transRepresentation += "<TRANS WS='" + lgws.ICULocale + "'>";
                    transRepresentation += GetTextRepresentationOfTsString(tss);
                    transRepresentation += "</TRANS>";
                }
            }

            return(transRepresentation);
        }
Esempio n. 2
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the text representation of a TsString.
        /// </summary>
        /// <param name="tss">The TsString.</param>
        /// <returns>text representation of the TsString</returns>
        /// ------------------------------------------------------------------------------------
        private string GetTextRepresentationOfTsString(ITsString tss)
        {
            string tssRepresentation = string.Empty;

            for (int iRun = 0; iRun < tss.RunCount; iRun++)
            {
                tssRepresentation += "<RUN";

                // writing system of run
                int nVar;
                int ws = tss.get_Properties(iRun).GetIntPropValues(
                    (int)FwTextPropType.ktptWs, out nVar);
                if (ws != -1)
                {
                    LgWritingSystem lgws = new LgWritingSystem(m_cache, ws);
                    tssRepresentation += " WS='" + lgws.ICULocale + "'";
                }

                // character style of run
                string charStyle = tss.get_Properties(iRun).GetStrPropValue(
                    (int)FwTextPropType.ktptNamedStyle);
                string runText = tss.get_RunText(iRun);
                // add the style tags
                if (charStyle != null)
                {
                    tssRepresentation += " CS='" + charStyle + @"'";
                }

                tssRepresentation += ">";

                // add the text for the tag
                if (runText != null && runText != string.Empty)
                {
                    StringBuilder newString = new StringBuilder(runText.Length * 2);
                    for (int i = 0; i < runText.Length; i++)
                    {
                        // remove '<' and '>' from the text
                        if (runText[i] == '<')
                        {
                            newString.Append("&lt;");
                        }
                        else if (runText[i] == '>')
                        {
                            newString.Append("&gt;");
                        }
                        else
                        {
                            newString.Append(runText[i]);
                        }
                    }
                    tssRepresentation += newString.ToString();
                }

                // add the run end tag
                tssRepresentation += "</RUN>";
            }
            return(tssRepresentation);
        }
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Computes the settings.
		/// </summary>
		/// <param name="normalStyle">The normal style.</param>
		/// <param name="ws">The HVO of the vernacular writing system.</param>
		/// ------------------------------------------------------------------------------------
		private void ComputeSettings(UsfmStyEntry normalStyle, int ws)
		{
			FontInfo fontInfo = normalStyle.FontInfoForWs(ws);
			m_fontName = normalStyle.RealFontNameForWs(ws);
			m_fontSize = (fontInfo.m_fontSize.Value / 1000).ToString();

			LgWritingSystem lgws = new LgWritingSystem(m_cache, ws);
			m_wsName = lgws.Name.UserDefaultWritingSystem;
			m_RtoL = (lgws.RightToLeft ? "T" : "F");
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Computes the settings.
		/// </summary>
		/// <param name="format">The format.</param>
		/// <param name="projPath">The proj path.</param>
		/// <param name="ws">The ws.</param>
		/// ------------------------------------------------------------------------------------
		private void ComputeSettings(FileNameFormat format, string projPath, int ws)
		{
			m_projPath = projPath.Trim();
			LgWritingSystem lgws = new LgWritingSystem(m_cache, ws);
			m_wsName = lgws.Name.UserDefaultWritingSystem;
			m_fileScheme = format.ParatextFileScheme;
			m_sPostPart = format.m_fileSuffix + "." + format.m_fileExtension;
			m_sPrePart = format.m_filePrefix;
			m_LtoR = (lgws.RightToLeft ? "F" : "T");
			m_versification =
				((int)m_cache.LangProject.TranslatedScriptureOA.Versification).ToString();
		}
		public void WriteParatextLdsFile()
		{
			if (File.Exists("test.lds"))
				File.Delete("test.lds");

			int wsHvo = Cache.DefaultVernWs;
			LgWritingSystem vernWs = new LgWritingSystem(Cache, wsHvo);
			vernWs.Name.UserDefaultWritingSystem = "French";

			DummyUsfmStyEntry normalEntry = new DummyUsfmStyEntry();
			StyleInfoTable styleTable = new StyleInfoTable("Normal",
				Cache.LanguageWritingSystemFactoryAccessor);
			styleTable.Add("Normal", normalEntry);
			normalEntry.DefaultFontInfo.m_fontSize.ExplicitValue = 14000;
			normalEntry.DefaultFontInfo.m_fontName.ExplicitValue = "Wingdings";

			ParatextLdsFileAccessor ldsAccessor = new ParatextLdsFileAccessor(Cache);
			DummyFileWriter actualLds = new DummyFileWriter();
			ReflectionHelper.CallMethod(ldsAccessor, "WriteParatextLdsFile", "test.lds",
				Cache.DefaultVernWs, normalEntry, actualLds);

			// Verify the .lds file
			string[] expectedLds =
			{
				"[General]",
				"codepage=65001",
				"RTL=F",
				"font=Wingdings",
				"name=French",
				"size=14",
				string.Empty,
				"[Checking]",
				string.Empty,
				"[Characters]",
				string.Empty,
				"[Punctuation]"
			};

			actualLds.VerifyOutput(expectedLds);
		}
Esempio n. 6
0
		public void UpdateParatextSsfFile_SameFolderAndSpec()
		{
			int wsHvo = Cache.DefaultVernWs;
			m_scr.Versification = 0; // Should default to English
			LgWritingSystem vernWs = new LgWritingSystem(Cache, wsHvo);

			// The existing file has Exodus and Matthew.
			string existingSsf =
				@"<ScriptureText>" + Environment.NewLine +
				@"<Book_EXO>Exodus</Book_EXO>"  + Environment.NewLine +
				@"<Book_MAT>Matthew</Book_MAT>"  + Environment.NewLine +
				@"<BooksPresent>010000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000</BooksPresent>"  + Environment.NewLine +
				@"<ChapterMarker>c</ChapterMarker>"  + Environment.NewLine +
				@"<Copyright></Copyright>"  + Environment.NewLine +
				@"<Directory>C:\My Paratext Projects\dummy</Directory>" + Environment.NewLine +
				@"<DotAll>No</DotAll>" + Environment.NewLine +
				@"<Editable>T</Editable>" + Environment.NewLine +
				@"<Encoding>65001</Encoding>" + Environment.NewLine +
				@"<FileNameChapterNumberForm></FileNameChapterNumberForm>" + Environment.NewLine +
				@"<FileNameForm>41MAT</FileNameForm>" + Environment.NewLine +
				@"<FileNamePostPart>suf.ext</FileNamePostPart>" + Environment.NewLine +
				@"<FileNamePrePart>pre</FileNamePrePart>" + Environment.NewLine +
				@"<FullName>My project Name</FullName>" + Environment.NewLine +
				@"<Language>Gumbasian</Language>" + Environment.NewLine +
				@"<LeftToRight>" + (vernWs.RightToLeft ? "F" : "T") + "</LeftToRight>" + Environment.NewLine +
				@"<MatchCase>No</MatchCase>" + Environment.NewLine +
				@"<Name>dummy</Name>" + Environment.NewLine +
				@"<ResourceText>F</ResourceText>" + Environment.NewLine +
				@"<RunFromCD>F</RunFromCD>" + Environment.NewLine +
				@"<ShowReferences>No</ShowReferences>" + Environment.NewLine +
				@"<StyleSheet>dontOverWriteMe.sty</StyleSheet>" + Environment.NewLine +
				@"<VerseMarker>v</VerseMarker>" + Environment.NewLine +
				@"<Versification>2</Versification>" + Environment.NewLine +
				"<Naming PrePart=\"pre\" PostPart=\"suf.ext\" BookNameForm=\"41MAT\"></Naming>" + Environment.NewLine +
				@"</ScriptureText>";

			FileNameFormat fileNameFormat = new FileNameFormat("pre",
				FileNameFormat.SchemeFormat.NNBBB, "suf", "ext");
			XmlDocument resultSSF;

			m_filter.Add(m_book.Hvo);

			using (StringReader sr = new StringReader(existingSsf))
			{
				resultSSF = m_exporter.ParatextSsfFileAccessor.UpdateSsfFile(sr, fileNameFormat, "dummy",
					"styFile.sty", @"C:\My Paratext Projects\dummy", wsHvo);
			}

			// Verify the .ssf contents
			Dictionary<string, string> expectedSsfEntries = new Dictionary<string, string>();
			expectedSsfEntries["Book_EXO"] = "Exodus";
			expectedSsfEntries["Book_MAT"] = "Matthew";
			expectedSsfEntries["BooksPresent"] = "110000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000";
			expectedSsfEntries["ChapterMarker"] = "c";
			expectedSsfEntries["Copyright"] = string.Empty;
			expectedSsfEntries["Directory"] = @"C:\My Paratext Projects\dummy";
			expectedSsfEntries["DotAll"] = "No";
			expectedSsfEntries["Editable"] = "T";
			expectedSsfEntries["Encoding"] = "65001";
			expectedSsfEntries["FileNameChapterNumberForm"] = string.Empty;
			expectedSsfEntries["FileNameForm"] = "41MAT";
			expectedSsfEntries["FileNamePostPart"] = "suf.ext";
			expectedSsfEntries["FileNamePrePart"] = "pre";
			expectedSsfEntries["FullName"] = "My project Name";
			expectedSsfEntries["Language"] = "francés";
			expectedSsfEntries["LeftToRight"] = (vernWs.RightToLeft ? "F" : "T");
			expectedSsfEntries["MatchCase"] = "No";
			expectedSsfEntries["Name"] = "dummy";
			expectedSsfEntries["ResourceText"] = "F";
			expectedSsfEntries["RunFromCD"] = "F";
			expectedSsfEntries["ShowReferences"] = "No";
			expectedSsfEntries["StyleSheet"] = "dontOverWriteMe.sty"; // Don't overwrite the .sty
			expectedSsfEntries["VerseMarker"] = "v";
			expectedSsfEntries["Versification"] = "2"; // Don't overwrite the versification.
			expectedSsfEntries["Naming"] = string.Empty;

			Assert.AreEqual(1, resultSSF.ChildNodes.Count, "Only node in document should be ScriptureText");
			XmlNode contents = resultSSF.SelectSingleNode("ScriptureText");
			Assert.AreEqual(expectedSsfEntries.Count, contents.ChildNodes.Count);
			foreach (string expectedElement in expectedSsfEntries.Keys)
			{
				XmlNode node = contents.SelectSingleNode(expectedElement);
				Assert.IsNotNull(node);
				Assert.AreEqual(expectedSsfEntries[expectedElement], node.InnerText);
			}
			// Check the Naiming node (only node that uses attributes)
			XmlNode namingNode = contents.SelectSingleNode("Naming");
			Assert.IsNotNull(namingNode);
			Assert.AreEqual("pre", namingNode.Attributes.GetNamedItem("PrePart").Value);
			Assert.AreEqual("suf.ext", namingNode.Attributes.GetNamedItem("PostPart").Value);
			Assert.AreEqual("41MAT", namingNode.Attributes.GetNamedItem("BookNameForm").Value);
		}
Esempio n. 7
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get a value determining if the new writing systems should be created as a side-effect
		/// of a paste operation.
		/// </summary>
		/// <param name="wsf">writing system factory containing the new writing systems</param>
		/// <param name="destWs">The destination writing system (writing system used at the
		/// selection).</param>
		/// <returns>
		/// 	an indication of how the paste should be handled.
		/// </returns>
		/// ------------------------------------------------------------------------------------
		public override PasteStatus DeterminePasteWs(ILgWritingSystemFactory wsf, out int destWs)
		{
			// Determine writing system at selection (destination for paste).
			destWs = 0;
			if (CurrentSelection != null)
				destWs = CurrentSelection.GetWritingSystem(SelectionHelper.SelLimitType.Anchor);
			if (destWs <= 0)
				destWs = Cache.DefaultAnalWs; // set to default analysis, if 0.

			// Get list of writing system names.
			List<string> wsMissingNames = new List<string>();
			int cws = wsf.NumberOfWs;

			using (ArrayPtr ptr = MarshalEx.ArrayToNative(cws, typeof(int)))
			{
				wsf.GetWritingSystems(ptr, cws);
				int[] vws = (int[])MarshalEx.NativeToArray(ptr, cws, typeof(int));

				IWritingSystem ws;
				for (int iws = 0; iws < cws; iws++)
				{
					if (vws[iws] == 0)
						continue;
					ws = wsf.get_EngineOrNull(vws[iws]);
					if (ws == null)
					{
						// found corrupt writing system--don't want to use any ws in this pasted string
						return PasteStatus.UseDestWs;
					}
					if (Cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr(ws.IcuLocale) == 0)
						wsMissingNames.Add(ws.LanguageName); // writing system not found in ws factory
				}
			}

			PasteStatus pasteStatus;
			if (wsMissingNames.Count > 0)
			{
				if (!Options.ShowPasteWsChoice)
					return PasteStatus.UseDestWs;

				// Ask user whether to use destination writing system or copy original writing systems.
				LgWritingSystem lgws = new LgWritingSystem(Cache, destWs);
				Debug.Assert(lgws != null);
				using (AddWsFromPastedTextDlg newWsDlg = new AddWsFromPastedTextDlg(
					m_cache.LangProject.Name.BestAnalysisAlternative.Text,
					lgws.Name.BestAnalysisAlternative.Text, wsMissingNames))
				{
					newWsDlg.ShowDialog(Control.FindForm());
					pasteStatus = newWsDlg.PasteStatus;
				}
			}
			else // no missing writing systems in TsString to paste
				pasteStatus = PasteStatus.PreserveWs;

			return pasteStatus;
		}
Esempio n. 8
0
		/// -----------------------------------------------------------------------------------
		/// <summary>
		/// Get a string that describes the Scripture passage based on the selection.
		/// </summary>
		/// <param name="tag">The flid of the selected element</param>
		/// <param name="hvoSel">The hvo of the selected element, either a ScrSection (usually)
		/// or ScrBook (if in a title)</param>
		/// <param name="fSimpleFormat">Gets a simple, standardized reference (uses SIL 3-letter
		/// codes and no verse bridges)</param>
		/// <returns>String that describes the Scripture passage or null if the selection
		/// can't be interpreted as a book and/or section reference.</returns>
		/// -----------------------------------------------------------------------------------
		public virtual string GetPassageAsString(int tag, int hvoSel, bool fSimpleFormat)
		{
			CheckDisposed();

			if (m_cache == null)
				return null;

			string sEditRef = null; // Title/reference/etc of text being edited in the draft pane
			switch (tag)
			{
				case (int)ScrSection.ScrSectionTags.kflidHeading:
				case (int)ScrSection.ScrSectionTags.kflidContent:
				{
					// ENHANCE TomB: might want to use low-level methods to get
					// cached values directly instead of creating the FDO objects
					// and having them reread the info from the DB. Also, may want
					// to cache the hvoSel in a method static variable so that when
					// the selection hasn't really changed to a new section or book,
					// we stop here.
					ScrSection section = new ScrSection(m_cache, hvoSel, false, false);
					BCVRef startRef;
					BCVRef endRef;
					section.GetDisplayRefs(out startRef, out endRef);
					if (fSimpleFormat)
						sEditRef = startRef.AsString;
					else
					{
						sEditRef = ScrReference.MakeReferenceString(section.OwningBook.BestUIName,
							startRef, endRef, m_scr.ChapterVerseSepr, m_scr.Bridge);
					}
					break;
				}
				case (int)ScrBook.ScrBookTags.kflidTitle:
				{
					ScrBook book = new ScrBook(m_cache, hvoSel, false, false);
					sEditRef = (fSimpleFormat ? (book.BookId + " 0:0") : book.BestUIName);
					break;
				}
				default:
					return null;
			}

			// Add the back translation writing system info to the output string, if needed
			if (IsBackTranslation)
			{
				LgWritingSystem ws = new LgWritingSystem(m_cache, ViewConstructorWS);
				sEditRef = string.Format(
					TeResourceHelper.GetResourceString("kstidCaptionInBackTrans"),
					sEditRef, ws.Name.UserDefaultWritingSystem);
			}

			return (sEditRef != null && sEditRef.Length != 0) ? sEditRef : null;
		}
Esempio n. 9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create test data in a right-to-left script.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected override void CreateTestData()
		{
			// Set the default writing system to a right-to-left writing system (Urdu)
			m_wsUrdu = InMemoryFdoCache.s_wsHvos.Ur;
			m_scrInMemoryCache.ChangeDefaultVernWs(m_wsUrdu);

			LgWritingSystem defWs = new LgWritingSystem(Cache, Cache.DefaultVernWs);

			// Add basic data for Genesis
			m_genesis = m_scrInMemoryCache.AddBookToMockedScripture(1, "Genesis");
			m_scrInMemoryCache.AddTitleToMockedBook(1, m_StartText);
			IScrSection section = m_scrInMemoryCache.AddSectionToMockedBook(m_genesis.Hvo);
			StTxtPara para = m_scrInMemoryCache.AddParaToMockedSectionContent(section.Hvo, null);
			m_scrInMemoryCache.AddFormatTextToMockedPara(m_genesis, para,
				@"\c12\v13-14\*" + m_WordsText, m_wsUrdu);
			section.AdjustReferences();

			// Add footnote
			ITsTextProps normalFootnoteParaProps =
				StyleUtils.ParaStyleTextProps(ScrStyleNames.NormalFootnoteParagraph);
			StFootnote footnote = m_scrInMemoryCache.AddFootnote(m_genesis, para, 10);
			StTxtPara footPara = new StTxtPara();
			footnote.ParagraphsOS.Append(footPara);
			footPara.StyleRules = normalFootnoteParaProps;
			ITsStrFactory strfact = TsStrFactoryClass.Create();
			footPara.Contents.UnderlyingTsString =
				strfact.MakeString(m_WordsText, m_wsUrdu);
		}
Esempio n. 10
0
		public void MissingEncodingConverter()
		{
			CheckDisposed();

			string encFileName = string.Empty;
			EncConverters converters = new EncConverters();

			using (TempSFFileMaker fileMaker = new TempSFFileMaker())
			{
				string fileName = fileMaker.CreateFile("ROM",
					new string[] {@"\mt 0123456789",
									 @"\c 1",
									 @"\v 1"},
					Encoding.GetEncoding(28591), false);
				m_settings.AddFile(fileName, ImportDomain.Main, null, 0);

				// Set the vernacular WS to use the MissingEncoder encoder
				LgWritingSystem wsVern =
					new LgWritingSystem(Cache, Cache.LangProject.DefaultVernacularWritingSystem);
				wsVern.LegacyMapping = "MissingEncoder";

				ISCTextEnum textEnum = GetTextEnum(ImportDomain.Main,
					new ScrReference(45, 0, 0, Paratext.ScrVers.English), new ScrReference(45, 1, 1, Paratext.ScrVers.English));

				// read the \id segment
				ISCTextSegment textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read segment");

				try
				{
					// read the \mt segment which should cause an exception
					textSeg = textEnum.Next();
				}
				catch (EncodingConverterException e)
				{
					Assert.IsTrue(e.Message.StartsWith(@"Encoding converter not found."));
					return;
				}
				Assert.Fail("Expected exception did not occur");
			}
		}
Esempio n. 11
0
		public void ConvertingTextSegments_BTImportDomain()
		{
			CheckDisposed();

			using (TempSFFileMaker fileMaker = new TempSFFileMaker())
			{
				string fileName = fileMaker.CreateFile("MAT", new string[]
					{
						@"\mt Matthew",
						@"\c 1",
						@"\v 1",
						@"\vt my \uw retronica\uw* translation",
						@"\k keywordbt"
					});
				m_settings.AddFile(fileName, ImportDomain.BackTrans, "en", 0);

				m_settings.SetMapping(MappingSet.Main, new ImportMappingInfo(@"\uw ", @"\uw*", false,
					MappingTargetType.TEStyle, MarkerDomain.BackTrans, "Untranslated Word", "es"));
				m_settings.SetMapping(MappingSet.Main, new ImportMappingInfo(@"\k", null, "Key Word"));

				// Set the vernacular WS to use the UPPERCASE encoder
				LgWritingSystem wsEnglish =
					new LgWritingSystem(Cache, Cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr("en"));
				wsEnglish.LegacyMapping = "UPPERCASE";

				// Save settings before enumerating, which will get the styles hooked up in the mapping list
				m_settings.SaveSettings();

				DummySCScriptureText text = new DummySCScriptureText(m_settings, ImportDomain.BackTrans);
				ISCTextEnum textEnum = text.TextEnum(new ScrReference(40, 0, 0, Paratext.ScrVers.English), new ScrReference(40, 1, 2, Paratext.ScrVers.English));

				ISCTextSegment textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read id segment ");
				Assert.AreEqual(@"\id", textSeg.Marker);
				Assert.AreEqual("MAT ", textSeg.Text);
				Assert.AreEqual(40, textSeg.FirstReference.Book);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read mt segment");
				Assert.AreEqual(@"\mt", textSeg.Marker);
				Assert.AreEqual(@"MATTHEW ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read c segment");
				Assert.AreEqual(@"\c", textSeg.Marker);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read v 1");
				Assert.AreEqual(@"\v", textSeg.Marker);
				Assert.AreEqual("1", textSeg.LiteralVerseNum);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read first vt segment");
				Assert.AreEqual(@"\vt", textSeg.Marker);
				Assert.AreEqual(@"MY ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read untranslated word segment (Spanish)");
				Assert.AreEqual(@"\uw ", textSeg.Marker);
				Assert.AreEqual(@"retronica", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to segment following untranslated word");
				Assert.AreEqual(@"\uw*", textSeg.Marker);
				Assert.AreEqual(@" TRANSLATION ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read keyword segment");
				Assert.AreEqual(@"\k", textSeg.Marker);
				Assert.AreEqual(@"KEYWORDBT ", textSeg.Text);

				Assert.IsNull(textEnum.Next());
			}
		}
Esempio n. 12
0
		public void ConvertingTextSegments_MainImportDomain()
		{
			CheckDisposed();

			using (TempSFFileMaker fileMaker = new TempSFFileMaker())
			{
				string fileName = fileMaker.CreateFile("MAT", new string[]
					{
						@"\mt Matthew",
						@"\c 1",
						@"\v 1",
						@"\vt This is \em my\em* verse text with a",
						@"\sp espanol",
						@"\k keyword",
						@"\f footnote text", // This tests the switch statement in GetEncodingConverterForMarkerDomain
						@"\spkwf raro", // This tests the need for & ~MarkerDomain.Footnote in ConvertSource
						@"\ft end of footnote",
						@"\btvt my \em Back\em* translation",
						@"\k keywordbt"
					});
				m_settings.AddFile(fileName, ImportDomain.Main, null, 0);

				m_settings.SetMapping(MappingSet.Main, new ImportMappingInfo(@"\em ", @"\em*", "Emphasis"));
				m_settings.SetMapping(MappingSet.Main, new ImportMappingInfo(@"\k", null, "Key Word"));

				ImportMappingInfo mapping = m_settings.MappingForMarker(@"\sp", MappingSet.Main);
				mapping.StyleName = "Default Paragraph Characters";
				mapping.IcuLocale = "es";
				mapping = m_settings.MappingForMarker(@"\f", MappingSet.Main);
				mapping.StyleName = ScrStyleNames.NormalFootnoteParagraph;

				mapping = m_settings.MappingForMarker(@"\spkwf", MappingSet.Main);
				mapping.StyleName = "Key Word";
				mapping.IcuLocale = "es";
				mapping.Domain = MarkerDomain.Default | MarkerDomain.Footnote;

				mapping = m_settings.MappingForMarker(@"\ft", MappingSet.Main);
				mapping.StyleName = "Default Paragraph Characters";
				mapping.Domain = MarkerDomain.Default | MarkerDomain.Footnote;

				mapping = m_settings.MappingForMarker(@"\btvt", MappingSet.Main);
				mapping.Domain = MarkerDomain.BackTrans;

				// Set the vernacular WS to use the UPPERCASE encoder
				LgWritingSystem wsVern =
					new LgWritingSystem(Cache, Cache.LangProject.DefaultVernacularWritingSystem);
				wsVern.LegacyMapping = "UPPERCASE";

				// Save settings before enumerating, which will get the styles hooked up in the mapping list
				m_settings.SaveSettings();

				DummySCScriptureText text = new DummySCScriptureText(m_settings, ImportDomain.Main);
				ISCTextEnum textEnum = text.TextEnum(new ScrReference(40, 0, 0, Paratext.ScrVers.English), new ScrReference(40, 1, 2, Paratext.ScrVers.English));

				ISCTextSegment textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read id segment ");
				Assert.AreEqual(@"\id", textSeg.Marker);
				Assert.AreEqual("MAT ", textSeg.Text);
				Assert.AreEqual(40, textSeg.FirstReference.Book);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read mt segment");
				Assert.AreEqual(@"\mt", textSeg.Marker);
				Assert.AreEqual(@"MATTHEW ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read c segment");
				Assert.AreEqual(@"\c", textSeg.Marker);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read v 1");
				Assert.AreEqual(@"\v", textSeg.Marker);
				Assert.AreEqual("1", textSeg.LiteralVerseNum);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read first vt segment");
				Assert.AreEqual(@"\vt", textSeg.Marker);
				Assert.AreEqual(@"THIS IS ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read emphasis segment");
				Assert.AreEqual(@"\em ", textSeg.Marker);
				Assert.AreEqual(@"MY", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read emphasis segment");
				Assert.AreEqual(@"\em*", textSeg.Marker);
				Assert.AreEqual(@" VERSE TEXT WITH A ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read Spanish segment");
				Assert.AreEqual(@"\sp", textSeg.Marker);
				Assert.AreEqual(@"espanol ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read keyword segment");
				Assert.AreEqual(@"\k", textSeg.Marker);
				Assert.AreEqual(@"KEYWORD ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read footnote text segment");
				Assert.AreEqual(@"\f", textSeg.Marker);
				Assert.AreEqual(@"FOOTNOTE TEXT ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read Spanish keyword in footnote segment");
				Assert.AreEqual(@"\spkwf", textSeg.Marker);
				Assert.AreEqual(@"raro ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read end of footnote segment");
				Assert.AreEqual(@"\ft", textSeg.Marker);
				Assert.AreEqual(@"END OF FOOTNOTE ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read btvt segment");
				Assert.AreEqual(@"\btvt", textSeg.Marker);
				Assert.AreEqual(@"my ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, @"Unable to read BT \em segment");
				Assert.AreEqual(@"\em ", textSeg.Marker);
				Assert.AreEqual(@"Back", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, @"Unable to read BT \em segment");
				Assert.AreEqual(@"\em*", textSeg.Marker);
				Assert.AreEqual(@" translation ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read BT keyword segment");
				Assert.AreEqual(@"\k", textSeg.Marker);
				Assert.AreEqual(@"keywordbt ", textSeg.Text);

				Assert.IsNull(textEnum.Next());
			}
		}
Esempio n. 13
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get an encoding converter for a mapping
		/// </summary>
		/// <param name="icuLocale">An ICU Locale</param>
		/// <param name="marker">The marker whose data is to be converted (used only for
		/// error reporting)</param>
		/// <returns>the encoding converter for the writing system of the mapping's ICU locale
		/// </returns>
		/// ------------------------------------------------------------------------------------
		private IEncConverter GetEncodingConverterForLocale(string icuLocale, string marker)
		{
			// If an entry already exists, then just look it up and return it
			if (m_icuLocaleToConverterMap.ContainsKey(icuLocale))
				return m_icuLocaleToConverterMap[icuLocale];

			// If there is no entry, then find the writing system with the ICU locale, get its
			// converter name and get a converter for that name.
			ILgWritingSystem ws = new LgWritingSystem(Cache,
				Cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr(icuLocale));
			IEncConverter converter = null;
			if (ws.LegacyMapping != null)
			{
				try
				{
					converter = (IEncConverter)m_encConverters[ws.LegacyMapping];
				}
				catch
				{
					// Something bad happened... Try to carry on.
					// This is a workaround until TE-5068 is fixed.
					converter = null;
				}
				if (converter == null)
				{
					throw new EncodingConverterException(string.Format(ScriptureUtilsException.GetResourceString(
						"kstidEncConvMissingConverter"), m_lineNumber, m_currentFile.FileName,
						ws.LegacyMapping, marker),
						"/Beginning_Tasks/Import_Standard_Format/Unable_to_Import/Encoding_converter_not_found.htm");
				}
			}
			m_icuLocaleToConverterMap[icuLocale] = converter;
			return converter;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// <param name="hvos"></param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private void AddWritingSystems(int[] hvos)
		{
			string langId = string.Empty;
			string langName = string.Empty;

			foreach (int hvo in hvos)
			{
				if (hvo == InMemoryFdoCache.s_wsHvos.En)
				{
					langId = "en";
					langName = "English";
				}
				else if (hvo == InMemoryFdoCache.s_wsHvos.Es)
				{
					langId = "es";
					langName = "Spanish";
				}
				else if (hvo == InMemoryFdoCache.s_wsHvos.Fr)
				{
					langId = "Fr";
					langName = "French";
				}
				else if (hvo == InMemoryFdoCache.s_wsHvos.Ipa)
				{
					langId = "en__IPA";
					langName = "English IPA";
				}
				LgWritingSystem ws = new LgWritingSystem(m_inMemoryCache.Cache, hvo);
				ws.ICULocale = langId;
				m_inMemoryCache.Cache.SetMultiUnicodeAlt(hvo,
					(int)LgWritingSystem.LgWritingSystemTags.kflidName, InMemoryFdoCache.s_wsHvos.En,
					langName);
			}
		}
Esempio n. 15
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Get the name of the writing system for an ICU Locale. If the ICU Locale is null
		/// then get the default analysis writing system name.
		/// </summary>
		/// <param name="icuLocale"></param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private string GetWritingSystemNameForLocale(string icuLocale)
		{
			if (icuLocale == null)
				icuLocale = m_cache.LangProject.DefaultAnalysisWritingSystemICULocale;
			ILgWritingSystem ws = new LgWritingSystem(m_cache,
				m_cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr(icuLocale));
			return ws.ShortName;
		}
Esempio n. 16
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets a string that can be used to format the given Scripture-reference punctuation
		/// for the given writing system by wrapping it in right-to-left marks if needed.
		/// </summary>
		/// <param name="punct">The Scripture-reference punctuation mark, which is usually a
		/// single character.</param>
		/// <param name="hvoWs">HVO of the writing system. If 0 or -1, the default vernacular
		/// will be used.</param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private string FormatReferencePunctForWs(string punct, int hvoWs)
		{
			if (hvoWs <= 0)
				hvoWs = Cache.DefaultVernWs;
			LgWritingSystem lgws = new LgWritingSystem(m_cache, hvoWs);
			return (lgws.RightToLeft) ? "\u200f" + punct + "\u200f" : punct;
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Adds the "invalid" character as a valid character.
		/// </summary>
		/// <param name="addedCharError">The checking error containing the character that will
		/// be added to the valid character inventory.</param>
		/// ------------------------------------------------------------------------------------
		private void AddAsValidCharacter(CheckingError addedCharError)
		{
			Debug.Assert(addedCharError.CheckId == StandardCheckIds.kguidCharacters,
				"Checking error should be from the valid characters check");

			ILgWritingSystemFactory lgwsf = m_cache.LanguageWritingSystemFactoryAccessor;
			int hvoWs = m_cache.DefaultVernWs;
			IWritingSystem ws = lgwsf.get_EngineOrNull(hvoWs);
			LanguageDefinition langDef = new LanguageDefinition(ws);
			LgWritingSystem lgWs = new LgWritingSystem(m_cache, hvoWs);
			langDef.ValidChars = ws.ValidChars;

			if (StringUtils.IsCharacterDefined(addedCharError.CitedText))
			{
				using (new WaitCursor(Parent))
				{
					// Get the valid characters from the database
					ValidCharacters validChars = ValidCharacters.Load(langDef);
					if (validChars != null)
					{
						validChars.AddCharacter(addedCharError.CitedText);
						ws.ValidChars = langDef.ValidChars = validChars.XmlString;
						StringUtils.UpdatePUACollection(langDef, validChars.AllCharacters);
						ws.SaveIfDirty(m_cache.DatabaseAccessor);
						langDef.Serialize();
					}

					// Mark all data grid view rows containing the newly-defined valid character to irrelevant.
					for (int iRow = 0; iRow < m_list.Count; iRow++)
					{
						CheckingError checkError = GetCheckingError(iRow);
						if (((StTxtPara)checkError.QuoteOA.ParagraphsOS[0]).Contents.Text ==
							addedCharError.CitedText)
						{
							// We don't want to create an undoable action, so we suppress subtasks.
							using (SuppressSubTasks supressActionHandler = new SuppressSubTasks(m_cache, true))
								checkError.Status = CheckingStatus.StatusEnum.Irrelevant;
						}
					}

					IsStale = true;

					m_dataGridView.Invalidate();
				}
			}
			else
			{
				string msg =
					ResourceHelper.GetResourceString("kstidUndefinedCharacterMsg");
				MessageBox.Show(this, msg, Application.ProductName,
					MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}
Esempio n. 18
0
		public void GetPageReference_DifferentChapter_Rtl()
		{
			ILgWritingSystem lgws = new LgWritingSystem(Cache, Cache.DefaultVernWs);
			lgws.RightToLeft = true;

			m_vc.SetDa(Cache.MainCacheAccessor);
			string sPageRefGuid = MiscUtils.GetObjDataFromGuid(HeaderFooterVc.PageReferenceGuid);
			// Set pseudo-correct level info so selection at start of page will appear be in
			// Genesis
			ScrSection section = (ScrSection)m_genesis.SectionsOS[2];

			SelLevInfo[] levInfoStart = new SelLevInfo[3];
			levInfoStart[2].hvo = section.Hvo;
			levInfoStart[2].tag = (int)ScrBook.ScrBookTags.kflidSections;
			levInfoStart[1].hvo = section.ContentOA.Hvo;
			levInfoStart[1].tag = (int)ScrSection.ScrSectionTags.kflidContent;
			levInfoStart[0].hvo = section.ContentOA.ParagraphsOS[0].Hvo;
			levInfoStart[0].tag = (int)StText.StTextTags.kflidParagraphs;

			m_pageInfo.m_topOfPage = new SelectionHelper();
			m_pageInfo.m_topOfPage.SetLevelInfo(SelectionHelper.SelLimitType.Anchor,
				levInfoStart);

			section = (ScrSection)m_genesis.SectionsOS[3];

			SelLevInfo[] levInfoEnd = new SelLevInfo[3];
			levInfoEnd[2].hvo = section.Hvo;
			levInfoEnd[2].tag = (int)ScrBook.ScrBookTags.kflidSections;
			levInfoEnd[1].hvo = section.ContentOA.Hvo;
			levInfoEnd[1].tag = (int)ScrSection.ScrSectionTags.kflidContent;
			levInfoEnd[0].hvo = section.ContentOA.ParagraphsOS[0].Hvo;
			levInfoEnd[0].tag = (int)StText.StTextTags.kflidParagraphs;

			m_pageInfo.m_bottomOfPage = new SelectionHelper();
			m_pageInfo.m_bottomOfPage.SetLevelInfo(SelectionHelper.SelLimitType.Anchor,
				levInfoEnd);

			Assert.AreEqual("Genesis 1\u200f,\u200f2", m_vc.GetStrForGuid(sPageRefGuid).Text);
		}
Esempio n. 19
0
		public void ConvertingTextSegments_InterleavedBt()
		{
			CheckDisposed();

			using (TempSFFileMaker fileMaker = new TempSFFileMaker())
			{
				string fileName = fileMaker.CreateFile("MAT", new string[]
					{
						@"\mt Matthew",
						@"\c 1",
						@"\v 1 This is my verse text",
						@"\rt my Back translation",
						@"\v 2 Second verse"
					});
				m_settings.AddFile(fileName, ImportDomain.Main, null, 0);

				ImportMappingInfo mapping = m_settings.MappingForMarker(@"\rt", MappingSet.Main);
				mapping.StyleName = "Default Paragraph Characters";
				mapping.Domain = MarkerDomain.BackTrans;

				// Set the vernacular WS to use the UPPERCASE encoder
				LgWritingSystem wsVern =
					new LgWritingSystem(Cache, Cache.LangProject.DefaultVernacularWritingSystem);
				wsVern.LegacyMapping = "UPPERCASE";

				// Save settings before enumerating, which will get the styles hooked up in the mapping list
				m_settings.SaveSettings();

				DummySCScriptureText text = new DummySCScriptureText(m_settings, ImportDomain.Main);
				ISCTextEnum textEnum = text.TextEnum(new ScrReference(40, 0, 0, Paratext.ScrVers.English), new ScrReference(40, 1, 2, Paratext.ScrVers.English));

				ISCTextSegment textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read id segment ");
				Assert.AreEqual(@"\id", textSeg.Marker);
				Assert.AreEqual("MAT ", textSeg.Text);
				Assert.AreEqual(40, textSeg.FirstReference.Book);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read mt segment");
				Assert.AreEqual(@"\mt", textSeg.Marker);
				Assert.AreEqual(@"MATTHEW ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read c segment");
				Assert.AreEqual(@"\c", textSeg.Marker);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read v 1");
				Assert.AreEqual(@"\v", textSeg.Marker);
				Assert.AreEqual("1", textSeg.LiteralVerseNum);
				Assert.AreEqual(@" THIS IS MY VERSE TEXT ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read btvt segment");
				Assert.AreEqual(@"\rt", textSeg.Marker);
				Assert.AreEqual(@"my Back translation ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read v 2");
				Assert.AreEqual(@"\v", textSeg.Marker);
				Assert.AreEqual("2", textSeg.LiteralVerseNum);
				Assert.AreEqual(@" SECOND VERSE ", textSeg.Text);

				Assert.IsNull(textEnum.Next());
			}
		}
Esempio n. 20
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Raises the visible changed event.
		/// </summary>
		/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event
		/// data.</param>
		/// ------------------------------------------------------------------------------------
		protected override void OnVisibleChanged(EventArgs e)
		{
			base.OnVisibleChanged(e);

			if (!Visible || Disposing)
				return;

			if (DesignMode)
				return;

			if (m_cache == null)
				throw new InvalidOperationException("Cache must be set before showing the FwMultilingualPropView named " + Name);
			if (m_hvoRootObject == 0)
				throw new InvalidOperationException("Root object must be set before showing the FwMultilingualPropView named " + Name);
			if (m_fieldsToDisplay.Count == 0)
				throw new InvalidOperationException("At least one field must be added to the FieldsToDisplay property before showing the FwMultilingualPropView named " + Name);
			if (m_writingSystemsToDisplay.Count == 0)
				throw new InvalidOperationException("At least one writing system must be added to the WritingSystemsToDisplay property before showing the FwMultilingualPropView named " + Name);

			// Add column headers
			foreach (ColumnInfo colInfo in m_fieldsToDisplay)
				AddColumn(colInfo.name, colInfo.widthPct);

			int iRow = 0;
			foreach (int ws in m_writingSystemsToDisplay)
			{
				Rows.Add(new FwTextBoxRow(ws));
				LgWritingSystem lgws = new LgWritingSystem(m_cache, ws);
				Rows[iRow].Cells[0].Value = lgws.Abbreviation;

				int iCol = 1;
				foreach (ColumnInfo colInfo in m_fieldsToDisplay)
					AddStringToCell(ws, colInfo.flid, iRow, iCol++);
				iRow++;
			}

			AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
			AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

			// Now set the current cell to the second column so that we skip the (read-only)
			// language name.
			CurrentCell = CurrentRow.Cells[1];
		}
Esempio n. 21
0
		public void ConvertAsciiToUnicode()
		{
			CheckDisposed();

			string encFileName = string.Empty;
			EncConverters converters = new EncConverters();
			try
			{
				// Define an encoding converter
				StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(
					"SIL.FieldWorks.FDO.Scripture.EncTest.map"));
				encFileName = Path.Combine(Path.GetTempPath(), "test.map");
				StreamWriter writer = new StreamWriter(encFileName);
				writer.Write(reader.ReadToEnd());
				reader.Close();
				writer.Close();

				converters.Add("MyConverter", encFileName, ConvType.Legacy_to_from_Unicode, string.Empty,
					string.Empty, ProcessTypeFlags.UnicodeEncodingConversion);

				using (TempSFFileMaker fileMaker = new TempSFFileMaker())
				{
					string fileName = fileMaker.CreateFile("ROM",
						new string[] {
										 @"\mt 0123456789",
										 "\\s \u0081\u009a\u0096\u00b5",
										 @"\c 1",
										 @"\v 1"},
						Encoding.GetEncoding(28591), false);
					m_settings.AddFile(fileName, ImportDomain.Main, null, 0);

					// Set the vernacular WS to use the MyConverter encoder
					LgWritingSystem wsVern =
						new LgWritingSystem(Cache, Cache.LangProject.DefaultVernacularWritingSystem);
					wsVern.LegacyMapping = "MyConverter";

					ISCTextEnum textEnum = GetTextEnum(ImportDomain.Main,
						new ScrReference(45, 0, 0, Paratext.ScrVers.English), new ScrReference(45, 1, 1, Paratext.ScrVers.English));

					ISCTextSegment textSeg = textEnum.Next();
					Assert.IsNotNull(textSeg, "Unable to read segment");
					Assert.AreEqual(@"\id", textSeg.Marker);
					Assert.AreEqual("ROM ", textSeg.Text);

					textSeg = textEnum.Next();
					Assert.IsNotNull(textSeg, "Unable to read segment");
					Assert.AreEqual(@"\mt", textSeg.Marker);
					Assert.AreEqual("\u0966\u0967\u0968\u0969\u096a\u096b\u096c\u096d\u096e\u096f ", textSeg.Text);

					textSeg = textEnum.Next();
					Assert.IsNotNull(textSeg, "Unable to read segment");
					Assert.AreEqual(@"\s", textSeg.Marker);
					Assert.AreEqual("\u0492\u043a\u2013\u04e9 ", textSeg.Text);

					textSeg = textEnum.Next();
					Assert.IsNotNull(textSeg, "Unable to read segment");
					Assert.AreEqual(@"\c", textSeg.Marker);
					Assert.AreEqual(@" ", textSeg.Text);

					textSeg = textEnum.Next();
					Assert.IsNotNull(textSeg, "Unable to read segment");
					Assert.AreEqual(@"\v", textSeg.Marker);
					Assert.AreEqual(@" ", textSeg.Text);
				}
			}
			finally
			{
				converters.Remove("MyConverter");
				try
				{
					File.Delete(encFileName);
				}
				catch {}
			}
		}
		public void GetParameterValue_VerseBridge()
		{
			ILgWritingSystem lgws = new LgWritingSystem(Cache, Cache.DefaultVernWs);

			lgws.RightToLeft = true;
			Assert.AreEqual("\u200f-\u200f", m_dataSource.GetParameterValue("Verse Bridge"));
			lgws.RightToLeft = false;
			Assert.AreEqual("-", m_dataSource.GetParameterValue("Verse Bridge"));
		}
Esempio n. 23
0
		public void DoNotCallConverterForUnicode()
		{
			CheckDisposed();

			using (TempSFFileMaker fileMaker = new TempSFFileMaker())
			{
				string filename = fileMaker.CreateFile("EPH",
					new string[] {@"\p", @"\c 1", "\\v 1 \u1234"}, Encoding.UTF8, true);
				m_settings.AddFile(filename, ImportDomain.Main, null, 0);

				// Set the vernacular WS to use the Garbagio encoder
				LgWritingSystem wsVern =
					new LgWritingSystem(Cache, Cache.LangProject.DefaultVernacularWritingSystem);
				wsVern.LegacyMapping = "Garbagio";

				ISCTextEnum textEnum = GetTextEnum(ImportDomain.Main,
					new ScrReference(49, 0, 0, Paratext.ScrVers.English), new ScrReference(49, 1, 1, Paratext.ScrVers.English));

				ISCTextSegment textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read segment 1 from file 1");
				Assert.AreEqual(@"\id", textSeg.Marker);
				Assert.AreEqual("EPH ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read segment 2 from file 1");
				Assert.AreEqual(@"\p", textSeg.Marker);
				Assert.AreEqual(@"", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read segment 3 from file 1");
				Assert.AreEqual(@"\c", textSeg.Marker);
				Assert.AreEqual(@" ", textSeg.Text);

				textSeg = textEnum.Next();
				Assert.IsNotNull(textSeg, "Unable to read segment 4 from file 1");
				Assert.AreEqual(@"\v", textSeg.Marker);
				Assert.AreEqual(" \u1234 ", textSeg.Text);
				Assert.AreEqual(49001001, textSeg.FirstReference.BBCCCVVV);
				Assert.AreEqual(49001001, textSeg.LastReference.BBCCCVVV);
			}
		}
Esempio n. 24
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Gets the language names (separated by newlines if more than one) given a list of
		/// writing systems.
		/// </summary>
		/// <param name="cache">The cache.</param>
		/// <param name="wsList">The list of writing systems.</param>
		/// ------------------------------------------------------------------------------------
		private static string GetLanguageNames(FdoCache cache, List<int> wsList)
		{
			Debug.Assert(wsList != null && wsList.Count > 0);

			StringBuilder strBldr = new StringBuilder();
			foreach (int wsHvo in wsList)
			{
				ILgWritingSystem lgws;
				try
				{
					lgws = new LgWritingSystem(cache, wsHvo);
					strBldr.Append("   " + lgws.Name.UserDefaultWritingSystem + Environment.NewLine);
				}
				catch
				{
					// invalid writing system
				}
			}
			return strBldr.ToString();
		}
Esempio n. 25
0
		private void ExportLDML(LgWritingSystem lgws, LdmlInFolderWritingSystemStore ldmlstore)
		{
			foreach (WritingSystemDefinition wsdT in ldmlstore.WritingSystemDefinitions)
			{
				// Don't bother changing an existing LDML file.
				if (wsdT.RFC4646 == lgws.RFC4646bis)
					return;
			}
			string sICU = lgws.ICULocale;
			string sLang;
			string sScript;
			string sCountry;
			string sVariant;
			Icu.UErrorCode err = Icu.UErrorCode.U_ZERO_ERROR;
			Icu.GetLanguageCode(sICU, out sLang, out err);
			if (sLang.Length > 3 && sLang.StartsWith("x"))
				sLang = sLang.Insert(1, "-");
			Icu.GetScriptCode(sICU, out sScript, out err);
			Icu.GetCountryCode(sICU, out sCountry, out err);
			Icu.GetVariantCode(sICU, out sVariant, out err);
			if (sVariant == "IPA")
				sVariant = "fonipa";
			Debug.Assert(err == Icu.UErrorCode.U_ZERO_ERROR);
			string sKeyboard;
			if (String.IsNullOrEmpty(lgws.KeymanKeyboard))
				sKeyboard = GetKeyboardName(lgws.Locale);
			else
				sKeyboard = lgws.KeymanKeyboard;
			string sSortUsing = null;
			string sSortRules = null;
			if (lgws.CollationsOS.Count > 0)
			{
				try
				{
					ILgCollation coll = lgws.CollationsOS[0];
					string sResName = coll.IcuResourceName;
					string sRules = coll.ICURules;
					int lcid = coll.WinLCID;
					if (!String.IsNullOrEmpty(sRules))
					{
						sSortUsing = "CustomICU";
						sSortRules = sRules;
					}
					else if (!String.IsNullOrEmpty(sResName))
					{
						sSortUsing = "OtherLanguage";
						sSortRules = sResName;
					}
					else if (lcid != 0)
					{
						sSortUsing = "OtherLanguage";
						System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(lcid);
						sSortRules = ci.Name;
					}
				}
				catch
				{
					// This try-catch shouldn't be needed, but as LT-9545 points out, creating
					// the collation can crash for some non-repeatable reason.  It's happened
					// twice on my machine, and once each for a couple of testers.
				}
			}
			WritingSystemDefinition wsd = new WritingSystemDefinition(sLang);
			wsd.Script = sScript;
			wsd.Region = sCountry;
			wsd.Variant = sVariant;
			wsd.LanguageName = lgws.Name.UserDefaultWritingSystem;
			wsd.Abbreviation = lgws.Abbr.UserDefaultWritingSystem;
			wsd.RightToLeftScript = lgws.RightToLeft;
			wsd.DefaultFontName = lgws.DefaultSerif;
			wsd.DefaultFontSize = 12;		// pure guesswork - we need a stylesheet or a model change!
			wsd.Keyboard = sKeyboard;
			if (!String.IsNullOrEmpty(sSortUsing))
			{
				wsd.SortUsing = sSortUsing;
				wsd.SortRules = sSortRules;
			}
			//wsd.NativeName = null;
			//wsd.SpellCheckingId = null;
			//wsd.StoreID = null;
			//wsd.VersionDescription = null;
			//wsd.VersionNumber = null;
			try
			{
				ldmlstore.SaveDefinition(wsd);
			}
			catch (Exception ex)
			{
				Debug.WriteLine(String.Format("Error writing LDML file: lgws.RFC={0}, wsd.RFC={1}; error: {2}",
					lgws.RFC4646bis, wsd.RFC4646, ex.Message));
			}
		}
Esempio n. 26
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Display the punctuation dialog box, using the specified guid to determine what
		/// tab on the dialog is initially brought to front.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void ShowPunctuationDialog(Guid initialTab)
		{
			ILgWritingSystemFactory lgwsf = m_cache.LanguageWritingSystemFactoryAccessor;
			int hvoWs = m_cache.DefaultVernWs;
			IWritingSystem ws = lgwsf.get_EngineOrNull(hvoWs);
			LanguageDefinition langDef = new LanguageDefinition(ws);
			LgWritingSystem lgWs = new LgWritingSystem(m_cache, hvoWs);

			using (PunctuationDlg dlg = new PunctuationDlg(m_cache, FwApp.App,
				langDef, lgWs.Name.UserDefaultWritingSystem, initialTab))
			{
				if (dlg.ShowDialog(this) == DialogResult.OK)
				{
					ws.SaveIfDirty(m_cache.DatabaseAccessor);
					langDef.Serialize();
				}
			}
		}
Esempio n. 27
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Save information about default analysis and vernacular writing systems for fast
		/// access. This method is called when an existing Language Project is initialized. It
		/// should also be called explicitly whenever an app changes to a different default
		/// writing systems or changes the name or ICU locale of one of the existing default
		/// writing systems.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void CacheDefaultWritingSystems()
		{
			// Preload writing systems
			CmObject.LoadObjectsIntoCache(m_cache, typeof(LgWritingSystem), null,
				LgWritingSystem.kClassId);

			if (CurAnalysisWssRS == null ||
				CurAnalysisWssRS.HvoArray.Length == 0 ||
				CurVernWssRS == null ||
				CurVernWssRS.HvoArray.Length == 0)
			{
				// The database must be in the early stages of being created because it still
				// doesn't have these writing systems set. So sad!
				return;
			}

			m_iDefaultAnalysisWritingSystem = CurAnalysisWssRS.HvoArray[0];
			//new LgWritingSystem(m_cache, CurAnalysisWssRS.HvoArray[0]).Code;

			m_sDefaultAnalysisWritingSystemICULocale =
				new LgWritingSystem(m_cache, CurAnalysisWssRS.HvoArray[0]).ICULocale;

			m_DefaultAnalysisWritingSystemName =
				new LgWritingSystem(m_cache, CurAnalysisWssRS.HvoArray[0]).Name;

			m_iDefaultVernacularWritingSystem = CurVernWssRS.HvoArray[0];
			//new LgWritingSystem(m_cache, CurVernWssRS.HvoArray[0]).Code;

			m_sDefaultVernacularWritingSystemICULocale =
				new LgWritingSystem(m_cache, CurVernWssRS.HvoArray[0]).ICULocale;

			m_DefaultVernacularWritingSystemName =
				new LgWritingSystem(m_cache, CurVernWssRS.HvoArray[0]).Name;

			m_iDefaultUserWritingSystem = m_cache.DefaultUserWs;

			m_DefaultUserWritingSystemName =
				new LgWritingSystem(m_cache, m_iDefaultUserWritingSystem).Name;

			m_sDefaultUserWritingSystemICULocale =
				new LgWritingSystem(m_cache, m_iDefaultUserWritingSystem).ICULocale;
		}
Esempio n. 28
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Given an FwTextBox, we get the name of the WS of the current selection. If the
		/// selection spans multiple writing systems, we return an empty string.
		/// </summary>
		/// <param name="fwtextbox">An FwTextBox (either the Find or Replace box)</param>
		/// <returns>Empty string if there is more than one writing system contained in the
		/// selection or if the TsString doesn't have a writing system property (if that's
		/// even possible). Otherwise, the UI name of the writing system.</returns>
		/// ------------------------------------------------------------------------------------
		protected virtual string GetCurrentWS(FwTextBox fwtextbox)
		{
			int hvoWs = SelectionHelper.GetWsOfEntireSelection(fwtextbox.Selection);
			if (hvoWs == 0)
				return string.Empty;
			LgWritingSystem lgws = new LgWritingSystem(m_cache, hvoWs);
			string sWsName = lgws.ShortName;
			return sWsName;
		}
Esempio n. 29
0
		public void WriteParatextSsfFile_SeptuagintVersification()
		{
			int wsHvo = Cache.DefaultVernWs;
			m_scr.Versification = Paratext.ScrVers.Septuagint;
			LgWritingSystem vernWs = new LgWritingSystem(Cache, wsHvo);
			vernWs.Name.UserDefaultWritingSystem = "French";

			DummyFileWriter writer = new DummyFileWriter();
			FileNameFormat fileNameFormat = new FileNameFormat("pre",
				FileNameFormat.SchemeFormat.NNBBB, "suf", "ext");
			m_exporter.ParatextSsfFileAccessor.SaveSsfFile(fileNameFormat, "dummy", "styFile.sty",
				@"C:\My Paratext Projects\dummy", writer, Cache.DefaultVernWs);

			// Verify the .ssf file
			string[] expectedSsf = new string[]
			{
				@"<ScriptureText>",
				@"<BooksPresent>100000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000</BooksPresent>",
				@"<Copyright></Copyright>",
				@"<Directory>C:\My Paratext Projects\dummy</Directory>",
				@"<Editable>T</Editable>",
				@"<Encoding>65001</Encoding>",
				@"<FileNameForm>41MAT</FileNameForm>",
				@"<FileNamePostPart>suf.ext</FileNamePostPart>",
				@"<FileNamePrePart>pre</FileNamePrePart>",
				@"<FullName>" + Cache.LangProject.Name.UserDefaultWritingSystem + "</FullName>",
				@"<Language>French</Language>",
				@"<LeftToRight>" + (vernWs.RightToLeft ? "F" : "T") + "</LeftToRight>",
				@"<Name>dummy</Name>",
				@"<StyleSheet>styFile.sty</StyleSheet>",
				@"<Versification>2</Versification>", // Septuagint
				"<Naming PrePart=\"pre\" PostPart=\"suf.ext\" BookNameForm=\"41MAT\"></Naming>",
				@"</ScriptureText>"
			};

			writer.VerifyOutput(expectedSsf);
		}
Esempio n. 30
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="page">Page info</param>
		/// <param name="wsDefault">default writing system</param>
		/// <param name="printDateTime">Printing date/time</param>
		/// <param name="cache">The cache.</param>
		/// ------------------------------------------------------------------------------------
		public HeaderFooterVc(IPageInfo page, int wsDefault, DateTime printDateTime,
			FdoCache cache)
		{
			m_page = page;
			m_wsDefault = wsDefault;
			m_printDateTime = printDateTime;
			m_cache = cache;
			LgWritingSystem defWs = new LgWritingSystem(m_cache, m_wsDefault);
			RightToLeft = defWs.RightToLeft;
		}
Esempio n. 31
0
		public void UpdateParatextSsfFile_DifferentFolderSameSpec()
		{
			int wsHvo = Cache.DefaultVernWs;
			LgWritingSystem vernWs = new LgWritingSystem(Cache, wsHvo);

			// The existing file has a lot of books.
			string existingSsf =
				@"<ScriptureText>" + Environment.NewLine +
				@"<BooksPresent>111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000</BooksPresent>" + Environment.NewLine +
				@"<Copyright></Copyright>" + Environment.NewLine +
				@"<Directory>C:\My Documents\dummy</Directory>" + Environment.NewLine +
				@"<Editable>T</Editable>" + Environment.NewLine +
				@"<Encoding>65001</Encoding>" + Environment.NewLine +
				@"<FileNameForm>41MAT</FileNameForm>" + Environment.NewLine +
				@"<FileNamePostPart>suf.ext</FileNamePostPart>" + Environment.NewLine +
				@"<FileNamePrePart>pre</FileNamePrePart>" + Environment.NewLine +
				@"<FullName>My project Name</FullName>" + Environment.NewLine +
				@"<Language>Gumbasian</Language>" + Environment.NewLine +
				@"<LeftToRight>" + (vernWs.RightToLeft ? "F" : "T") + "</LeftToRight>" + Environment.NewLine +
				@"<Name>dummy</Name>" + Environment.NewLine +
				@"<StyleSheet>styFile.sty</StyleSheet>" + Environment.NewLine +
				@"<Versification>4</Versification>" + Environment.NewLine +
				"<Naming PrePart=\"pre\" PostPart=\"suf.ext\" BookNameForm=\"41MAT\"></Naming>" + Environment.NewLine +
				@"</ScriptureText>";

			FileNameFormat fileNameFormat = new FileNameFormat("pre",
				FileNameFormat.SchemeFormat.NNBBB, "suf", "ext");
			XmlDocument resultSSF;

			m_filter.Add(m_book.Hvo);

			using (StringReader sr = new StringReader(existingSsf))
			{
				resultSSF = m_exporter.ParatextSsfFileAccessor.UpdateSsfFile(sr, fileNameFormat, "dummy",
					"styFile.sty", @"C:\My Paratext Projects\dummy", wsHvo);
			}

			// Verify the .ssf contents
			Dictionary<string, string> expectedSsfEntries = new Dictionary<string, string>();
			expectedSsfEntries["BooksPresent"] = "100000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000";
			expectedSsfEntries["Copyright"] = string.Empty;
			expectedSsfEntries["Directory"] = @"C:\My Paratext Projects\dummy";
			expectedSsfEntries["Editable"] = "T";
			expectedSsfEntries["Encoding"] = "65001";
			expectedSsfEntries["FileNameForm"] = "41MAT";
			expectedSsfEntries["FileNamePostPart"] = "suf.ext";
			expectedSsfEntries["FileNamePrePart"] = "pre";
			expectedSsfEntries["FullName"] = "My project Name";
			expectedSsfEntries["Language"] = "francés";
			expectedSsfEntries["LeftToRight"] = (vernWs.RightToLeft ? "F" : "T");
			expectedSsfEntries["Name"] = "dummy";
			expectedSsfEntries["StyleSheet"] = "styFile.sty";
			expectedSsfEntries["Versification"] = "4"; // Preserve the versification of their original project
			expectedSsfEntries["Naming"] = string.Empty;

			Assert.AreEqual(1, resultSSF.ChildNodes.Count, "Only node in document should be ScriptureText");
			XmlNode contents = resultSSF.SelectSingleNode("ScriptureText");
			Assert.AreEqual(expectedSsfEntries.Count, contents.ChildNodes.Count);
			foreach (string expectedElement in expectedSsfEntries.Keys)
			{
				XmlNode node = contents.SelectSingleNode(expectedElement);
				Assert.IsNotNull(node);
				Assert.AreEqual(expectedSsfEntries[expectedElement], node.InnerText);
			}
			// Check the Naiming node (only node that uses attributes)
			XmlNode namingNode = contents.SelectSingleNode("Naming");
			Assert.IsNotNull(namingNode);
			Assert.AreEqual("pre", namingNode.Attributes.GetNamedItem("PrePart").Value);
			Assert.AreEqual("suf.ext", namingNode.Attributes.GetNamedItem("PostPart").Value);
			Assert.AreEqual("41MAT", namingNode.Attributes.GetNamedItem("BookNameForm").Value);
		}
Esempio n. 32
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// For the given mapping, compute a string to display in the details column of the
		/// mapping list.
		/// </summary>
		/// <param name="mapping">The mapping</param>
		/// <returns>String to display</returns>
		/// ------------------------------------------------------------------------------------
		private string GetMappingDetailsAsString(ImportMappingInfo mapping)
		{
			string sSubItem = string.Empty;

			// if the style is excluded then don't display anything in the details column
			if (!mapping.IsExcluded)
			{
				switch (mapping.Domain)
				{
					case MarkerDomain.BackTrans:
						sSubItem = ScrImportComponents.kstidImportWizMappingDetailBackTrans;
						break;
					case MarkerDomain.Note:
						sSubItem = ScrImportComponents.kstidImportWizMappingDetailNotes;
						break;
					case MarkerDomain.Footnote:
						sSubItem = ScrImportComponents.kstidImportWizMappingDetailFootnotes;
						break;
					case MarkerDomain.Footnote | MarkerDomain.BackTrans:
						sSubItem = ScrImportComponents.kstidImportWizMappingDetailBTFootnotes;
						break;
					case MarkerDomain.Default:
						break;
					default:
						throw new Exception("Unexpected domain");
				}

				// Figure out what the writing system's name is to display it in the list view.
				if (mapping.IcuLocale != null)
				{
					LgWritingSystem ws = new LgWritingSystem(m_cache,
						m_cache.LanguageWritingSystemFactoryAccessor.GetWsFromStr(mapping.IcuLocale));

					string wsName = ws.ShortName;
					if (wsName != null)
					{
						if (sSubItem != string.Empty)
							sSubItem += ", ";
						sSubItem += wsName;
					}
				}
			}
			return sSubItem;
		}