Ejemplo n.º 1
0
        public FilteredFieldsForm(Dictionary <string, List <string> > mapFilteredSfms, List <string> astrSfmsToConvert,
                                  List <string> astrSfmsToNotConvert, Font font, Font fontConverted, IEncConverter aEC)
        {
            InitializeComponent();

            m_aEC             = aEC;
            m_mapFilteredSfms = mapFilteredSfms;

            dataGridViewFilterSfms.Columns[cnColumnExampleData].DefaultCellStyle.Font   = font;
            dataGridViewFilterSfms.Columns[cnColumnExampleResult].DefaultCellStyle.Font = fontConverted;

            foreach (KeyValuePair <string, List <string> > kvp in mapFilteredSfms)
            {
                if (!astrSfmsToConvert.Contains(kvp.Key) && !astrSfmsToNotConvert.Contains(kvp.Key))
                {
                    System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(kvp.Value[0]));
                    string   strInput     = kvp.Value[0];
                    string   strOutput    = m_aEC.Convert(strInput);
                    bool     bOnByDefault = Properties.Settings.Default.DefaultFieldsToConvert.Contains(kvp.Key);
                    object[] aoRowData    = new object[4] {
                        bOnByDefault, kvp.Key, kvp.Value[0], strOutput
                    };
                    int             nIndex = dataGridViewFilterSfms.Rows.Add(aoRowData);
                    DataGridViewRow theRow = dataGridViewFilterSfms.Rows[nIndex];
                    theRow.Tag = 0;
                }
            }
        }
        // initialize an EncConverter which will tell us when we've hit a match. Uses ICU RegEx (though, there's
        //  no reason this couldn't be .Net regex...)
        protected IEncConverter InitSearchFontConverter(string strFindWhat, string strReplaceWith, Font font, bool bMatchCase)
        {
            // we're going to use a temporary ICU RegEx EncConverter to do our 'searching' for us.
            // get a blank ICU Regex converter that we can program with our FindWhat string
            // but, it may be null if ICU isn't installed
            System.Diagnostics.Debug.Assert(m_aECs != null);
            IEncConverter aIEC = null;

            try
            {
                aIEC = m_aECs.NewEncConverterByImplementationType(EncConverters.strTypeSILicuRegex);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("ICU doesn't appear to have been installed. This feature won't work without ICU.", ex);
            }

            // we search for different things depending on whether it's "Find" (only) vs. "Find & Replace"
            // delimit the replacement string with something we can detect, which we wouldn't otherwise expect
            //  to find in user text.
            string strConverterSpec = String.Format("{0}->{2}{1}{2}{3}", strFindWhat, strReplaceWith,
                                                    m_achDelimiter[0], (bMatchCase) ? " /i" : null);

            // Give it a friendly name that isn't likely to conflict with anything 'real' the user might name it.
            string   strName   = String.Format("{0} FindReplaceConverter", OfficeApp.cstrCaption);
            ConvType eConvType = ConvType.Unicode_to_Unicode;
            string   strDummy  = null;
            int      nProcType = (int)ProcessTypeFlags.ICURegularExpression;

            // initialize it so it's ready and put it in the current repository object (as a temporary converter)
            aIEC.Initialize(strName, strConverterSpec, ref strDummy, ref strDummy, ref eConvType,
                            ref nProcType, 0, 0, true);

            return(aIEC);
        }
        private void setDefaultConverterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_aEcDefault = null;
            EncConverters aECs = GetEncConverters;

            if (aECs != null)
            {
                IEncConverter aIEC = aECs.AutoSelectWithTitle(ConvType.Unknown, "Choose Default Converter");
                if (aIEC != null)
                {
                    m_aEcDefault = new DirectableEncConverter(aIEC);

                    foreach (DataGridViewRow aRow in dataGridViewConverterMapping.Rows)
                    {
                        string strXmlPath = (string)aRow.Cells[cnXmlPathsColumn].Value;
                        if (!IsConverterDefined(strXmlPath))
                        {
                            DataGridViewCell cellConverter = aRow.Cells[cnEncConverterColumn];
                            cellConverter.Value       = m_aEcDefault.Name;
                            cellConverter.ToolTipText = m_aEcDefault.ToString();
                            string strInput = (string)aRow.Cells[cnExampleDataColumn].Value;
                            aRow.Cells[cnExampleOutputColumn].Value = CallSafeConvert(m_aEcDefault, strInput);
                            DefineConverter(strXmlPath, m_aEcDefault);
                        }
                    }

                    m_aECLast = null;
                }
            }
        }
Ejemplo n.º 4
0
		public FilteredFieldsForm(Dictionary<string, List<string>> mapFilteredSfms, List<string> astrSfmsToConvert,
			List<string> astrSfmsToNotConvert, Font font, Font fontConverted, IEncConverter aEC)
		{
			InitializeComponent();

			m_aEC = aEC;
			m_mapFilteredSfms = mapFilteredSfms;

			dataGridViewFilterSfms.Columns[cnColumnExampleData].DefaultCellStyle.Font = font;
			dataGridViewFilterSfms.Columns[cnColumnExampleResult].DefaultCellStyle.Font = fontConverted;

			foreach (KeyValuePair<string, List<string>> kvp in mapFilteredSfms)
			{
				if (!astrSfmsToConvert.Contains(kvp.Key) && !astrSfmsToNotConvert.Contains(kvp.Key))
				{
					System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(kvp.Value[0]));
					string strInput = kvp.Value[0];
					string strOutput = m_aEC.Convert(strInput);
					bool bOnByDefault = Properties.Settings.Default.DefaultFieldsToConvert.Contains(kvp.Key);
					object[] aoRowData = new object[4] { bOnByDefault, kvp.Key, kvp.Value[0], strOutput };
					int nIndex = dataGridViewFilterSfms.Rows.Add(aoRowData);
					DataGridViewRow theRow = dataGridViewFilterSfms.Rows[nIndex];
					theRow.Tag = 0;
				}
			}
		}
        private void buttonTest_Click(object sender, EventArgs e)
        {
            Util.DebugWriteLine(this, "BEGIN");
            IEncConverter aEC = InitializeEncConverter;

            if (aEC != null)
            {
                try
                {
                    aEC.DirectionForward = !checkBoxTestReverse.Checked;
                    //ecTextBoxOutput.Text = aEC.Convert(ecTextBoxInput.Text);
                    string result = aEC.Convert(ecTextBoxInput.Text);
                    Util.DebugWriteLine(this, "Putting in text box: '" + result + "'");
                    ecTextBoxOutput.Text = result;
                    //ecTextBoxOutput.Text = "Hello there!";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("Test failed! Reason: {0}", ex.Message),
                                    EncConverters.cstrCaption);
                }

                NormConversionType eType = (checkBoxTestReverse.Checked)
                    ? EncConverter.NormalizeLhsConversionType(ConversionType) : EncConverter.NormalizeRhsConversionType(ConversionType);

                if (eType == NormConversionType.eLegacy)
                {
                    UpdateLegacyCodes(ecTextBoxOutput.Text, m_aEC.CodePageOutput, richTextBoxHexOutput);
                }
                else
                {
                    UpdateUniCodes(ecTextBoxOutput.Text, richTextBoxHexOutput);
                }
            }
        }
        protected DirectableEncConverter GetTempFixedValueConverter(string strFixedValue)
        {
            string        strName = String.Format("{0}{1}", cstrFixedStringConverterPrefix, strFixedValue);
            EncConverters aECs    = GetEncConverters;

            if (aECs != null)
            {
                IEncConverter aIEC = null;
                if (!aECs.ContainsKey(strName))
                {
                    aIEC = aECs.NewEncConverterByImplementationType(EncConverters.strTypeSILicuRegex);
                    ConvType eConvType = ConvType.Unicode_to_Unicode;
                    string   strDummy  = null;
                    int      nProcType = (int)ProcessTypeFlags.ICURegularExpression;
                    aIEC.Initialize(strName, String.Format(".+->{0}", strFixedValue), ref strDummy, ref strDummy,
                                    ref eConvType, ref nProcType, 0, 0, true);
                    aECs.Add(strName, aIEC);
                }
                else
                {
                    aIEC = aECs[strName];
                }

                return(new DirectableEncConverter(aIEC));
            }
            return(null);
        }
Ejemplo n.º 7
0
        private void setDefaultConverterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EncConverters aECs = OfficeApp.GetEncConverters;

            if (aECs != null)
            {
                IEncConverter aIEC = aECs.AutoSelectWithTitle(ConvType.Unknown, "Select Default Converter");
                if (aIEC != null)
                {
                    DirectableEncConverter aEC = new DirectableEncConverter(aIEC.Name, aIEC.DirectionForward, aIEC.NormalizeOutput);
                    foreach (DataGridViewRow aRow in dataGridViewFontsConverters.Rows)
                    {
                        string strFontName = (string)aRow.Cells[nColumnFontNames].Value;
                        if (!m_mapEncConverters.ContainsKey(strFontName))
                        {
                            m_mapEncConverters.Add(strFontName, aEC);                                // add it
                            DataGridViewCell cellConverter = aRow.Cells[nColumnConverterNames];
                            cellConverter.Value       = aEC.Name;
                            cellConverter.ToolTipText = aEC.ToString();
                        }
                    }

                    // clear the last one selected so that a right-click can be used to cancel the selection
                    m_aECLast = null;
                }
            }
        }
 protected void ResetFields()
 {
     ConversionType      = m_eOrigConvType;
     ConverterIdentifier = null;
     ProcessType         = 0;
     m_aEC = null;
 }
Ejemplo n.º 9
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Convert one line of text for display
        /// </summary>
        /// <param name="ec"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        private string ConvertOneLine(IEncConverter ec, string input)
        {
            string marker    = string.Empty;
            string remainder = string.Empty;

            // if the input string is empty, don't try to convert it
            if (input == string.Empty)
            {
                return(input);
            }

            // split the marker and the remainder portions of the text line.
            if (input[0] != '\\')
            {
                remainder = input;
            }
            else
            {
                int spacePosition = input.IndexOf(" ");
                if (spacePosition == -1)
                {
                    return(input);
                }
                else
                {
                    marker    = input.Substring(0, spacePosition);
                    remainder = input.Substring(spacePosition);
                }
            }

            return(marker + ec.Convert(remainder));
        }
        protected void InitFromIEncConverter(IEncConverter aEC, bool bInputOutputAlreadySet)
        {
            m_strEncConverterName = aEC.Name;
            m_bDirectionForward   = aEC.DirectionForward;
            m_eNormalForm         = aEC.NormalizeOutput;

            // in some cases (e.g. the SelectConverter dialog), the input/ouput code page values
            //	are already set from the proper perspective and don't need to be reversed as in the other cases
            //	(see CodePageInput below). So swap them if they need to be (so the later swap will put them
            //	back to what they were at the start -- sorry, I know this is confusing)
            if (!m_bDirectionForward && bInputOutputAlreadySet)
            {
                var aEcInputCodePage = aEC.CodePageOutput;
                aEC.CodePageOutput = aEC.CodePageInput;
                aEC.CodePageInput  = aEcInputCodePage;
            }

            // if the user intends for this to be a temporary converter, it won't be available to
            //  subsequent calls of "GetEncConverter" unless we add it to this particular instance
            //  of the local repository object.
            if (EncConverters[m_strEncConverterName] == null)
            {
                EncConverters.Add(m_strEncConverterName, aEC);
            }
        }
Ejemplo n.º 11
0
        void ConvertTableField_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                if (Application.Selection == null)
                {
                    throw new ApplicationException("First select the cells that you want to convert using a system converter");
                }

                ExcelDocument doc = new ExcelDocument(Application.Selection);
                if (m_aSelectionProcessor == null)
                {
                    string        strTitle = "Choose the converter for the selected areas/cells";
                    EncConverters aECs     = GetEncConverters;
                    if (aECs != null)
                    {
                        IEncConverter aIEC = aECs.AutoSelectWithTitle(ConvType.Unknown, strTitle);
                        FontConverter aFC  = new FontConverter(new DirectableEncConverter(aIEC));
                        m_aSelectionProcessor = new OfficeDocumentProcessor(aFC, new SILConverterProcessorForm());
                    }
                }

                if (m_aSelectionProcessor != null)
                {
                    if (doc.ProcessWordByWord(m_aSelectionProcessor))
                    {
                        m_aSelectionProcessor = null;
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
Ejemplo n.º 12
0
        private void buttonTest_Click(object sender, EventArgs e)
        {
            IEncConverter aEC = InitializeEncConverter;

            if (aEC != null)
            {
                try
                {
                    aEC.DirectionForward = !checkBoxTestReverse.Checked;
                    ecTextBoxOutput.Text = aEC.Convert(ecTextBoxInput.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("Test failed! Reason: {0}", ex.Message),
                                    EncConverters.cstrCaption);
                }

                NormConversionType eType = (checkBoxTestReverse.Checked)
                                        ? EncConverter.NormalizeLhsConversionType(ConversionType) : EncConverter.NormalizeRhsConversionType(ConversionType);

                if (eType == NormConversionType.eLegacy)
                {
                    UpdateLegacyCodes(ecTextBoxOutput.Text, m_aEC.CodePageOutput, richTextBoxHexOutput);
                }
                else
                {
                    UpdateUniCodes(ecTextBoxOutput.Text, richTextBoxHexOutput);
                }
            }
        }
Ejemplo n.º 13
0
        public virtual void Initialize
        (
            IEncConverters aECs,
            string strFriendlyName,
            string strConverterIdentifier,
            ConvType eConversionType,
            string strTestData
        )
        {
            FriendlyName        = strFriendlyName;
            ConverterIdentifier = strConverterIdentifier;
            ConversionType      = eConversionType;

            m_aECs = aECs;
            m_aEC  = InitializeEncConverter;

            tabControl.Controls.Remove(tabPageAbout);
            tabControl.Controls.Remove(tabPageSetup);
            tabControl.Controls.Remove(tabPageAdvanced);

            // for 'test', it's possible that there may be some font mapping in the repository
            string strLhsName, strRhsName;

            if (m_aECs.GetFontMappingFromMapping(strFriendlyName, out strLhsName, out strRhsName))
            {
                ecTextBoxInput.Font  = CreateFontSafe(strLhsName, ecTextBoxInput.Font);
                ecTextBoxOutput.Font = CreateFontSafe(strRhsName, ecTextBoxOutput.Font);
            }

            ecTextBoxInput.Text = strTestData;
            buttonOK.Visible    = buttonApply.Visible = false;
            buttonCancel.Text   = "Close";

            helpProvider.SetHelpString(buttonCancel, Properties.Resources.CloseButtonHelpString);
        }
Ejemplo n.º 14
0
        // we override this method from EncConverter so that we can call all of the step's
        //  convert functions in turn (i.e. for this one, it isn't sufficient to just
        //  provide a "DoConvert" method)
        // and we override this from CmpdEncConverter to we can add our bit of only calling
        //  the 2nd step (i.e. the fallback converter) if the 1st step doesn't change the
        //  string.
        protected override string InternalConvertEx
        (
            EncodingForm eInEncodingForm,
            string sInput,
            int ciInput,
            EncodingForm eOutEncodingForm,
            NormalizeFlags eNormalizeOutput,
            out int rciOutput,
            bool bForward
        )
        {
            if (CountConverters != 2)
            {
                EncConverters.ThrowError(ErrStatus.FallbackTwoStepsRequired);
            }

            IEncConverter rConverter = (IEncConverter)m_aEncConverter[0];

            if (rConverter == null)
            {
                EncConverters.ThrowError(ErrStatus.MissingConverter);
            }

            rConverter.Debug = Debug;
            bool bDirectionForward = (bForward) ? (bool)m_aDirectionForward[0] : !(bool)m_aDirectionForward[0];

            string strOutput = rConverter.ConvertEx(
                sInput,
                eInEncodingForm,
                ciInput,
                eOutEncodingForm,
                out rciOutput,
                eNormalizeOutput,
                bDirectionForward);

            // call the fallback if the string wasn't changed
            if (strOutput == sInput)
            {
                IEncConverter rFallbackConverter = (IEncConverter)m_aEncConverter[1];
                if (rFallbackConverter == null)
                {
                    EncConverters.ThrowError(ErrStatus.MissingConverter);
                }

                rFallbackConverter.Debug = Debug;
                bDirectionForward        = (bForward) ? (bool)m_aDirectionForward[1] : !(bool)m_aDirectionForward[1];

                strOutput = rFallbackConverter.ConvertEx(
                    sInput,
                    eInEncodingForm,
                    ciInput,
                    eOutEncodingForm,
                    out rciOutput,
                    eNormalizeOutput,
                    bDirectionForward);
            }

            return(strOutput);
        }
Ejemplo n.º 15
0
        /// -----------------------------------------------------------------------------------
        /// <summary>
        /// Convert a file and display it in the window
        /// </summary>
        /// -----------------------------------------------------------------------------------
        public void DoFileConvert(IEncConverter ec, string inputFilename)
        {
            CheckDisposed();

            // start hour glass
            Cursor cursorBefore = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            // open the input and output files using the given encoding formats
            // 28591 is a 'magic' code page that stuffs each input byte into
            // the low byte of the unicode character, leaving the top byte zero.
            // This is a good code page to use because it is simple and fully reversible
            // for any input.
            StreamReader reader = new StreamReader(inputFilename,
                                                   System.Text.Encoding.GetEncoding(28591), true);

            // This tells the converter that the input will be 16-bit characters
            // produced by converting the bytes of the file using CP28591.
            ec.CodePageInput = 28591;
            ec.EncodingIn    = ECInterfaces.EncodingForm.LegacyString;

            reader.BaseStream.Seek(0, SeekOrigin.Begin);

            // read the lines of the input file, (optionally convert,) and write them out.
            string sOutput = string.Empty;
            string sInput;

            m_savedOutput = new StringBuilder();

            m_svOutput.Clear(false);
            m_fHasOutput = false;

            // Read the lines of the input file, convert them, and display them
            // in the view.
            while (reader.Peek() > -1)
            {
                sInput = reader.ReadLine();

                if (sInput == string.Empty || sInput.StartsWith(@"\_sh ") || sInput.StartsWith(@"\id "))
                {
                    sOutput = sInput;
                }
                else
                {
                    sOutput = ConvertOneLine(ec, sInput);
                }
                m_svOutput.AddPara(sOutput);
                m_savedOutput.Append(sOutput);
                m_savedOutput.Append("\r\n");
                m_fHasOutput = true;
            }

            reader.Close();
            m_svOutput.CompleteSetText();
            Cursor.Current = cursorBefore;
        }
Ejemplo n.º 16
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Open the next source file to read. Skip over any files that do not contain
        /// data in the desired range.
        /// </summary>
        /// <returns>true if a file was opened, else false and there are no more
        /// files available</returns>
        /// ------------------------------------------------------------------------------------
        private bool OpenNextSourceFile(BCVRef startRef, BCVRef endRef)
        {
            // Clear the indicator that tells that an ID line has been encountered
            m_seenIdInFile = false;
            m_lineNumber   = 0;

            // If the first file is being opened, then initialize the reference
            if (m_currentFile == null)
            {
                m_currentStartRef = new BCVRef();
                m_currentEndRef   = new BCVRef();
            }
            // Find the next book in the project that has books in the import range
            bool fileHasBooksInRange = false;

            while (!fileHasBooksInRange)
            {
                if (!m_importSourceEnum.MoveNext())
                {
                    return(false);
                }
                m_currentFile = (ScrImportFileInfo)m_importSourceEnum.Current;

                if (m_domain != ImportDomain.Main)
                {
                    m_prevDataEncoding = GetEncodingConverterForLocale(m_currentFile.IcuLocale,
                                                                       ScrImportSet.s_markerBook);
                }

                // make sure the file contains books in the desired range
                foreach (int book in m_currentFile.BooksInFile)
                {
                    if (book >= startRef.Book && book <= endRef.Book)
                    {
                        fileHasBooksInRange = true;
                        break;
                    }
                }
            }

            try
            {
                // ASCII encoding will convert all high-bit characters to a '?'.
                // The magic code page will map all high-bit characters to the same
                // value with a high-byte of 0 in unicode. For example, character 0x84
                // will end up as 0x0084.
                Encoding useEncoding = (m_currentFile.FileEncoding == Encoding.ASCII) ?
                                       Encoding.GetEncoding(kMagicCodePage) : m_currentFile.FileEncoding;

                m_sfFileReader = new StreamReader(m_currentFile.FileName, useEncoding);
            }
            catch (Exception e)
            {
                throw new ScriptureUtilsException(SUE_ErrorCode.FileError, m_currentFile.FileName, e);
            }
            return(true);
        }
Ejemplo n.º 17
0
        private bool ChaChaChaChaChanges(IEncConverter aEC, string strFileName, string strWord)
        {
            string   strDummy     = null;
            int      lProcessType = (int)SpellingFixerEC.SFProcessType;
            ConvType eConvType    = (m_bLegacy) ? ConvType.Legacy_to_Legacy : ConvType.Unicode_to_Unicode;

            aEC.Initialize("dummyname", strFileName, ref strDummy, ref strDummy, ref eConvType, ref lProcessType, 0, 0, true);
            return(aEC.Convert(strWord) != strWord);
        }
Ejemplo n.º 18
0
 public bool SetConverter(EncConverters converters)
 {
     if (m_EncCvtrMap == null)
     {
         return(true);                   // if the map is empty, this means the lang is already UTF8
     }
     m_iconverter = converters[m_EncCvtrMap];
     return(m_iconverter != null);
 }
Ejemplo n.º 19
0
        public void DoFileConvert
        (
            string strConverterName,
            string strOutputFileName,
            System.Text.Encoding outEnc,
            string strInputFileName,
            System.Text.Encoding inEnc,
            bool bDirectionForward
        )
        {
            // the user *might* not give us a converter name if they simply want to change
            //  the encoding from, say, UTF8 to UTF16.
            bool bIsConverter = !(strConverterName == null);

            IEncConverter aEC = null;

            if (bIsConverter)
            {
                EncConverters aECs = new EncConverters();
                aEC = aECs[strConverterName];
            }

            // open the input and output files using the given encoding formats
            StreamReader srReadLine = new StreamReader(strInputFileName, inEnc, true);

            srReadLine.BaseStream.Seek(0, SeekOrigin.Begin);
            StreamWriter swWriteLine = new StreamWriter(strOutputFileName, false, outEnc);

            // tell the converter to go the other way, if the user selected 'reverse'
            if (!bDirectionForward && bIsConverter)
            {
                aEC.DirectionForward = false;
            }

            // read the lines of the input file, (optionally convert,) and write them out.
            string sOutput, sInput;

            while (srReadLine.Peek() > -1)
            {
                sInput = srReadLine.ReadLine();

                if (bIsConverter)
                {
                    sOutput = aEC.Convert(sInput);
                }
                else
                {
                    sOutput = sInput;
                }

                swWriteLine.WriteLine(sOutput);
            }

            srReadLine.Close();
            swWriteLine.Close();
        }
Ejemplo n.º 20
0
		/// <summary>
		/// FontConvertersPicker: to choose the font you want to process in the Word document
		///
		/// This version of the constructor is for when you want the same (given) EncConverter
		/// used for all fonts.
		/// </summary>
		/// <param name="doc"></param>
		/// <param name="aEC"></param>
		public FontConvertersPicker(OfficeDocument doc, IEncConverter aEC)
		{
			System.Diagnostics.Debug.Assert(aEC != null);
			m_aECForAll = new DirectableEncConverter(aEC);
			m_strApplyEC = String.Format(cstrApplyECFormat, aEC.Name);
			CommonConstruct(doc);

			// no mapping in this mode
			converterMappingToolStripMenuItem.Visible = false;
		}
Ejemplo n.º 21
0
        /// <summary>
        /// FontConvertersPicker: to choose the font you want to process in the Word document
        ///
        /// This version of the constructor is for when you want the same (given) EncConverter
        /// used for all fonts.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="aEC"></param>
        public FontConvertersPicker(OfficeDocument doc, IEncConverter aEC)
        {
            System.Diagnostics.Debug.Assert(aEC != null);
            m_aECForAll  = new DirectableEncConverter(aEC);
            m_strApplyEC = String.Format(cstrApplyECFormat, aEC.Name);
            CommonConstruct(doc);

            // no mapping in this mode
            converterMappingToolStripMenuItem.Visible = false;
        }
Ejemplo n.º 22
0
        private void buttonDebug_Click(object sender, EventArgs e)
        {
            IEncConverter aEC        = m_aEC.GetEncConverter;
            bool          bOrigValue = aEC.Debug;

            aEC.Debug = true;

            RefreshTextBoxes(aEC);

            aEC.Debug = bOrigValue;
        }
 protected bool IsLhsLegacy(IEncConverter aEC)
 {
     if (aEC.DirectionForward)
     {
         return(EncConverter.NormalizeLhsConversionType(aEC.ConversionType) == NormConversionType.eLegacy);
     }
     else
     {
         return(EncConverter.NormalizeRhsConversionType(aEC.ConversionType) == NormConversionType.eLegacy);
     }
 }
Ejemplo n.º 24
0
        public static AdaptItEncConverter InitLookupAdapter(ProjectSettings proj, GlossType eGlossType)
        {
            EncConverters aECs = new EncConverters();
            string        strName, strConverterSpec;

            ProjectSettings.LanguageInfo liSource, liTarget;
            switch (eGlossType)
            {
            case GlossType.eVernacularToNational:
                strName          = AdaptItLookupConverterName(proj.Vernacular.LangName, proj.NationalBT.LangName);
                strConverterSpec = AdaptItLookupFileSpec(proj.Vernacular.LangName, proj.NationalBT.LangName);
                liSource         = proj.Vernacular;
                liTarget         = proj.NationalBT;
                break;

            case GlossType.eVernacularToEnglish:                        // the glossing KB for the Vern to Natl project
                strName          = AdaptItLookupConverterName(proj.Vernacular.LangName, proj.InternationalBT.LangName);
                strConverterSpec = AdaptItLookupFileSpec(proj.Vernacular.LangName, proj.InternationalBT.LangName);
                liSource         = proj.Vernacular;
                liTarget         = proj.InternationalBT;                 // this is still the national lg project (but the glossing KB)
                break;

            case GlossType.eNationalToEnglish:
                strName          = AdaptItLookupConverterName(proj.NationalBT.LangName, proj.InternationalBT.LangName);
                strConverterSpec = AdaptItLookupFileSpec(proj.NationalBT.LangName, proj.InternationalBT.LangName);
                liSource         = proj.NationalBT;                         // this is a whole nuther national to English project
                liTarget         = proj.InternationalBT;
                break;

            default:
                System.Diagnostics.Debug.Assert(false);
                throw new ApplicationException("Wrong glossing type specified. Send to [email protected] for help");
            }

            // just in case the project doesn't exist yet...
            WriteAdaptItProjectFiles(liSource, liTarget, proj.InternationalBT);             // move this to AIGuesserEC project when it's mature.

            // if we don't have the converter already in the repository.
            if (!aECs.ContainsKey(strName))
            {
                aECs.AddConversionMap(strName, strConverterSpec, ConvType.Unicode_to_from_Unicode,
                                      EncConverters.strTypeSILadaptit, "UNICODE", "UNICODE", ProcessTypeFlags.DontKnow);
            }

            IEncConverter aEC = aECs[strName];

            System.Diagnostics.Debug.Assert((aEC != null) && (aEC is AdaptItEncConverter));
            AdaptItEncConverter theLookupAdapter = (AdaptItEncConverter)aEC;

            // in order to get the converter to load the database, do a dummy Convert
            theLookupAdapter.Convert("nothing");
            return(theLookupAdapter);
        }
Ejemplo n.º 25
0
		protected void InitFromIEncConverter(IEncConverter aEC)
		{
			m_strEncConverterName = aEC.Name;
			m_bDirectionForward = aEC.DirectionForward;
			m_eNormalForm = aEC.NormalizeOutput;

			// if the user intends for this to be a temporary converter, it won't be available to
			//  subsequent calls of "GetEncConverter" unless we add it to this particular instance
			//  of the local repository object.
			if (EncConverters[m_strEncConverterName] == null)
				EncConverters.Add(m_strEncConverterName, aEC);
		}
        public string Convert(string sInput)
        {
            IEncConverter aEC = GetEncConverter;

            if (aEC != null)
            {
                return(aEC.Convert(sInput));
            }
            else
            {
                throw NoConverterException;
            }
        }
        public override string ToString()
        {
            IEncConverter aEC = GetEncConverter;

            if (aEC != null)
            {
                return(aEC.ToString());
            }
            else
            {
                return(Name);
            }
        }
Ejemplo n.º 28
0
        protected void InitConverterDetails(string strFontName, out string strConverterName, out string strTooltip, out string strFontNameOutput)
        {
            strConverterName  = (UsingSameEncConverter) ? m_strApplyEC : cstrClickMsg;
            strTooltip        = strConverterName;
            strFontNameOutput = (UsingSameEncConverter) ? strFontName : cstrFontClickMsg;

            // if there is no converted selected, then see if the repository has a suggestion
            if (!m_mapEncConverters.ContainsKey(strFontName) && (strConverterName == cstrClickMsg))
            {
                EncConverters aECs = OfficeApp.GetEncConverters;
                if (aECs != null)
                {
                    string strMappingName = aECs.GetMappingNameFromFont(strFontName);
                    if (!String.IsNullOrEmpty(strMappingName))
                    {
                        strConverterName = strMappingName;
                        IEncConverter aIEC = aECs[strConverterName];

                        if (aIEC != null)
                        {
                            DirectableEncConverter aEC = new DirectableEncConverter(aIEC);
                            m_mapEncConverters.Add(strFontName, aEC);
                        }
                    }
                }
            }

            if (m_mapEncConverters.ContainsKey(strFontName))
            {
                DirectableEncConverter aEC = (DirectableEncConverter)m_mapEncConverters[strFontName];
                strConverterName = aEC.Name;
                strTooltip       = aEC.ToString();
                if (aEC.TargetFont != null)
                {
                    strFontNameOutput = aEC.TargetFont.Name;
                }
                else                 // otherwise, the repository might be able to tell us what font to use
                {
                    EncConverters aECs = OfficeApp.GetEncConverters;
                    if (aECs != null)
                    {
                        string[] astrFontnames = aECs.GetFontMapping(aEC.Name, strFontName);
                        if (astrFontnames.Length > 0)
                        {
                            strFontNameOutput = astrFontnames[0];
                            aEC.TargetFont    = new Font(strFontNameOutput, 14);
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        protected void InitFromIEncConverter(IEncConverter aEC)
        {
            m_strEncConverterName = aEC.Name;
            m_bDirectionForward   = aEC.DirectionForward;
            m_eNormalForm         = aEC.NormalizeOutput;

            // if the user intends for this to be a temporary converter, it won't be available to
            //  subsequent calls of "GetEncConverter" unless we add it to this particular instance
            //  of the local repository object.
            if (EncConverters[m_strEncConverterName] == null)
            {
                EncConverters.Add(m_strEncConverterName, aEC);
            }
        }
Ejemplo n.º 30
0
        protected void UpdateConverterCellValue(DataGridViewRow theRow, IEncConverter aEC)
        {
            string strStepName = aEC.Name;

            if (strStepName.Length > cnMaxConverterName)
            {
                strStepName = strStepName.Substring(0, cnMaxConverterName);
            }

            DataGridViewCell theCell = theRow.Cells[cnStepNameColumn];

            theCell.Value       = strStepName;
            theCell.ToolTipText = aEC.ToString();
        }
Ejemplo n.º 31
0
        private void comboBox_SelectedIndexChanged(ComboBox sender, CheckBox chk)
        {
            if (!m_bIgnoreSelItemChgWhileLoading)
            {
                string        strConverter = sender.Text;
                IEncConverter aEC          = m_aECs[strConverter];
                if (aEC != null)
                {
                    chk.Enabled = !EncConverters.IsUnidirectional(aEC.ConversionType);
                }

                // to enable the name to be changed
                IsModified = true;
            }
        }
Ejemplo n.º 32
0
 protected override void GetConverterNameEnum(out string [] rSa)
 {
     rSa = new string[CountConverters];
     for (int i = 0; i < CountConverters; i++)
     {
         IEncConverter rConvert = (IEncConverter)m_aEncConverter[i];
         if (rConvert == null)
         {
             EncConverters.ThrowError(ErrStatus.MissingConverter);
         }
         else
         {
             rSa[i] = FormatConverterStep(rConvert.Name, (bool)m_aDirectionForward[i], (NormalizeFlags)m_aNormalizeOutput[i]);
         }
     }
 }
        // convert in the opposite direction (if it started as "reverse", then this
        //  means forward
        public string ConvertDirectionOpposite(string sInput)
        {
            IEncConverter aEC = EncConverters[m_strEncConverterName];

            if (aEC != null)
            {
                aEC.DirectionForward = !m_bDirectionForward;
                string strOutput = aEC.Convert(sInput);
                aEC.DirectionForward = m_bDirectionForward;
                return(strOutput);
            }
            else
            {
                throw NoConverterException;
            }
        }
Ejemplo n.º 34
0
		protected void ConvertProjectFile(string strProjectFileSource, string strProjectFileTarget,
			IEncConverter aEcSource, IEncConverter aEcTarget, string strFontNameSource, string strFontNameTarget)
		{
			// convert the punctuation in the legacy project file.
			Encoding enc = Encoding.Default;
			if (aEcSource != null)
			{
				// the "symbol" code page apparently isn't valid for GetEncoding, so use the cp for ISO-8859-1
				if (aEcSource.CodePageInput == EncConverters.cnSymbolFontCodePage)
					enc = Encoding.GetEncoding(EncConverters.cnIso8859_1CodePage);
				else
					enc = Encoding.GetEncoding(aEcSource.CodePageInput);
			}
			string strProjectFileContents = File.ReadAllText(strProjectFileSource, enc);

			int nIndex;
			int nLength = 0;

			// the charset value has to be 0 in a Unicode project
			// first the 'Source language'
			nIndex = strProjectFileContents.IndexOf(cstrAdaptItCharMapDelimiter);
			if (nIndex != -1)
			{
				nIndex += cstrAdaptItCharMapDelimiter.Length;
				nLength = strProjectFileContents.IndexOfAny(caSplitChars, nIndex) - nIndex;
				strProjectFileContents = ReplaceSubstring(strProjectFileContents, nIndex, nLength, "0");

				// next the target language...
				nIndex = strProjectFileContents.IndexOf(cstrAdaptItCharMapDelimiter, nIndex);
				if (nIndex != -1)
				{
					nIndex += cstrAdaptItCharMapDelimiter.Length;
					nLength = strProjectFileContents.IndexOfAny(caSplitChars, nIndex) - nIndex;
					strProjectFileContents = ReplaceSubstring(strProjectFileContents, nIndex, nLength, "0");

					// finally do the navigation language as well.
					nIndex = strProjectFileContents.IndexOf(cstrAdaptItCharMapDelimiter, nIndex);
					if (nIndex != -1)
					{
						nIndex += cstrAdaptItCharMapDelimiter.Length;
						nLength = strProjectFileContents.IndexOfAny(caSplitChars, nIndex) - nIndex;
						strProjectFileContents = ReplaceSubstring(strProjectFileContents, nIndex, nLength, "0");
					}
				}
			}

			// see about replacing the font names
			if (m_strDefaultUnicodeFontSource != m_strStatusBoxDefaultFont)
			{
				nIndex = strProjectFileContents.IndexOf(strFontNameSource);
				nLength = strFontNameSource.Length;
				strProjectFileContents = ReplaceSubstring(strProjectFileContents, nIndex, nLength, m_strDefaultUnicodeFontSource);
			}
			else
			{
				nIndex = strProjectFileContents.IndexOf(cstrAdaptItFontNameDelimiter);
				nIndex = strProjectFileContents.IndexOf(cstrAdaptItFontNameDelimiter, nIndex);
			}

			if (m_strDefaultUnicodeFontTarget != m_strStatusBoxDefaultFont)
			{
				nIndex = strProjectFileContents.IndexOf(strFontNameTarget, nIndex + nLength);
				nLength = strFontNameTarget.Length;
				strProjectFileContents = ReplaceSubstring(strProjectFileContents, nIndex, nLength, m_strDefaultUnicodeFontTarget);
			}

			int nIndexPunctDelimiter = strProjectFileContents.IndexOf(cstrAdaptItPunctuationPairsLegacy, nIndex);
			nIndex = nIndexPunctDelimiter + cstrAdaptItPunctuationPairsLegacy.Length;
			nLength = strProjectFileContents.IndexOfAny(caSplitChars, nIndex) - nIndex;
			string strPunctuation = strProjectFileContents.Substring(nIndex, nLength);

			char[] aPunctSource, aPunctTarget;
			UnpackPunctuationLegacy(strPunctuation, out aPunctSource, out aPunctTarget);

			string strNewPunctuationSource = new string(aPunctSource);
			AppendStatusOutputNl("found: legacy source punctuation: ", m_strStatusBoxDefaultFont, true);
			AppendStatusOutput(strNewPunctuationSource, strFontNameSource, true);

			string strNewPunctuationSourceConverted = strNewPunctuationSource;
			if (aEcSource != null)
				strNewPunctuationSourceConverted = aEcSource.Convert(strNewPunctuationSource);

			if (strNewPunctuationSourceConverted != strNewPunctuationSource)
				AppendStatusOutputNl("converted to: " + strNewPunctuationSourceConverted, m_strDefaultUnicodeFontSource, true);
			else
				AppendStatusOutputNl("result: no changes", m_strStatusBoxDefaultFont, true);

			string strNewPunctuationTarget = new string(aPunctTarget);
			AppendStatusOutputNl("found: legacy target punctuation: ", m_strStatusBoxDefaultFont, true);
			AppendStatusOutput(strNewPunctuationTarget, strFontNameTarget, true);

			string strNewPunctuationTargetConverted = strNewPunctuationTarget;
			if (aEcTarget != null)
				strNewPunctuationTargetConverted = aEcTarget.Convert(strNewPunctuationTarget);

			if (strNewPunctuationTargetConverted != strNewPunctuationTarget)
				AppendStatusOutputNl("converted to: " + strNewPunctuationTargetConverted, m_strDefaultUnicodeFontTarget, true);
			else
				AppendStatusOutputNl("result: no changes", m_strStatusBoxDefaultFont, true);

			nIndex = strProjectFileContents.IndexOf(cstrAdaptItPunctuationExtraLegacy, nIndex) + cstrAdaptItPunctuationExtraLegacy.Length;
			nLength = strProjectFileContents.IndexOfAny(caSplitChars, nIndex) - nIndex;

			string strProjectFileContentsNew =
				strProjectFileContents.Substring(0, nIndexPunctDelimiter) +
				cstrAdaptItPunctuationPairsNRSource + strNewPunctuationSourceConverted + CRLF +
				cstrAdaptItPunctuationPairsNRTarget + strNewPunctuationTargetConverted + CRLF +
				cstrAdaptItPunctuationExtraNR +
				strProjectFileContents.Substring(nIndex);

			// as a special case, if the 'after-conversion' fonts are both defined and are equal to each other,
			//  then go ahead and update in the project file
			if (    (strFontNameSource == strFontNameTarget)
				&&  (m_strDefaultUnicodeFontSource != m_strStatusBoxDefaultFont)
				&&  (m_strDefaultUnicodeFontTarget != m_strStatusBoxDefaultFont)
				&&  (m_strDefaultUnicodeFontSource == m_strDefaultUnicodeFontTarget))
				strProjectFileContentsNew = strProjectFileContentsNew.Replace(strFontNameSource, m_strDefaultUnicodeFontSource);

			InsureDirectoryExists(strProjectFileTarget);

			// don't use WriteAllText (c.f. ReadAllText above), because that inserts the BOM which causes AIU grief
			byte[] abyContents = Encoding.UTF8.GetBytes(strProjectFileContentsNew);
			File.WriteAllBytes(strProjectFileTarget, abyContents);
		}
Ejemplo n.º 35
0
		void buttonSelectGlossConverter_Click(object sender, System.EventArgs e)
		{
			ConvType eFilter = (IsLegacyToUnicode) ? ConvType.Legacy_to_from_Unicode : ConvType.Unicode_to_from_Legacy;
			m_aEcGloss = GetEncConverters.AutoSelectWithTitle(eFilter, "Choose Glossing Language Converter");
			if (m_aEcGloss != null)
				labelGlossLanguageConverter.Text = m_aEcGloss.Name;
			else
				labelGlossLanguageConverter.Text = cstrDefaultConvertLabelGloss;
		}
Ejemplo n.º 36
0
		protected void ConvertKbFile(string strKbFileSource, string strKbFileTarget,
			IEncConverter aEcSource, IEncConverter aEcTarget, string strFontNameSource, string strFontNameTarget)
		{
			// Since AdaptIt will make different records for two words which are canonically
			//  equivalent, if we use the class object to read it in via ReadXml, that will throw
			//  an exception in such a case. So see if using XmlDocument is any less restrictive
			try
			{
				AppendStatusOutputNl("Processing KB file: " + strKbFileSource, m_strStatusBoxDefaultFont, true);
				string strTempKbFileSource = strKbFileSource;
				CheckForIncorrectEncodingString(ref strTempKbFileSource);
				XmlDocument doc;
				XPathNavigator navigator;
				XmlNamespaceManager manager;
				GetXmlDocument(strTempKbFileSource, out doc, out navigator, out manager);

				XPathNodeIterator xpMapIterator = navigator.Select("/aikb:AdaptItKnowledgeBase/aikb:KB/aikb:MAP", manager);

				progressBarAdaptationFile.Visible = true;

				// can't have two source words with the same value
				List<string> astrSourceWords = new List<string>();
				while (xpMapIterator.MoveNext())
				{
					// find the first (next) source word element
					XPathNodeIterator xpSourceWords = xpMapIterator.Current.Select("aikb:TU", manager);

					progressBarAdaptationFile.Value = 0;
					progressBarAdaptationFile.Maximum = xpSourceWords.Count;
					while (xpSourceWords.MoveNext())
					{
						progressBarAdaptationFile.Value++;
						// get an iterator for the source word attribute (so we can change it later)
						XPathNodeIterator xpSourceWord = xpSourceWords.Current.Select("@k", manager);
						if (xpSourceWord.MoveNext())
						{
							// get and convert the source word value
							string strSourceWord = xpSourceWord.Current.Value;
							string strSourceWordConverted = ((aEcSource != null) && !String.IsNullOrEmpty(strSourceWord)) ? aEcSource.Convert(strSourceWord) : strSourceWord;

							// if this word has already come up before, then we have to do something else (TODO: e.g. merge the two)
							if (astrSourceWords.Contains(strSourceWordConverted))
							{
								AppendStatusOutputNl("Found two source words that have the same value: ", m_strStatusBoxDefaultFont, true);
								AppendStatusOutput(strSourceWordConverted, m_strDefaultUnicodeFontSource, true);

								while (astrSourceWords.Contains(strSourceWordConverted))
									strSourceWordConverted = "DuplicateOf:" + strSourceWordConverted;

								AppendStatusOutput(". Changing it to: ", m_strStatusBoxDefaultFont, true);
								AppendStatusOutput(strSourceWordConverted, m_strDefaultUnicodeFontSource, true);
							}

							AppendStatusOutputNl("source: ", m_strStatusBoxDefaultFont, false);
							AppendStatusOutput(strSourceWord, strFontNameSource, false);

							if (strSourceWord != strSourceWordConverted)
							{
								// otherwise, just change the value in-situ
								xpSourceWord.Current.SetValue(strSourceWordConverted);
								astrSourceWords.Add(strSourceWordConverted);

								AppendStatusOutput(", becomes: ", m_strStatusBoxDefaultFont, false);
								AppendStatusOutput(strSourceWordConverted, m_strDefaultUnicodeFontSource, false);
							}
							else
							{
								AppendStatusOutput(cstrNoChange, m_strStatusBoxDefaultFont, false);
							}

							// now get an iterator for all of the target words for the current source word
							//  (here we'll go directly to the attribute value)
							XPathNodeIterator xpTargetWords = xpSourceWords.Current.Select("aikb:RS", manager);

							// maintain a list of all target words in case the conversion merges them.
							List<string> astrTargetWords = new List<string>();
							while (xpTargetWords.MoveNext())
							{
								XPathNodeIterator xpTargetWord = xpTargetWords.Current.Select("@a", manager);
								if (xpTargetWord.MoveNext())
								{
									// get and convert the target word
									string strTargetWord = xpTargetWord.Current.Value;
									string strTargetWordConverted = ((aEcTarget != null) && !String.IsNullOrEmpty(strTargetWord)) ? aEcTarget.Convert(strTargetWord) : strTargetWord;

									// if this word has already come up before, then we have to do something else (TODO: e.g. merge the two)
									if (astrTargetWords.Contains(strTargetWordConverted))
									{
										AppendStatusOutputNl("Found two target words that have the same value: ", m_strStatusBoxDefaultFont, true);
										AppendStatusOutput(strTargetWordConverted, m_strDefaultUnicodeFontTarget, true);

										while (astrTargetWords.Contains(strTargetWordConverted))
											strTargetWordConverted = "DuplicateOf:" + strTargetWordConverted;

										AppendStatusOutput(". Changing it to: ", m_strStatusBoxDefaultFont, true);
										AppendStatusOutput(strTargetWordConverted, m_strDefaultUnicodeFontTarget, true);
									}

									AppendStatusOutputNl("target: ", m_strStatusBoxDefaultFont, false);
									AppendStatusOutput(strTargetWord, strFontNameTarget, false);

									if (strTargetWord != strTargetWordConverted)
									{
										// otherwise, just change the value in-situ
										xpTargetWord.Current.SetValue(strTargetWordConverted);
										astrTargetWords.Add(strTargetWordConverted);

										AppendStatusOutput(", becomes: ", m_strStatusBoxDefaultFont, false);
										AppendStatusOutput(strTargetWordConverted, m_strDefaultUnicodeFontTarget, false);
									}
									else
									{
										AppendStatusOutput(cstrNoChange, m_strStatusBoxDefaultFont, false);
									}
								}
							}
						}
					}
				}

				// now write it to the target folder
				XmlTextWriter writer = new XmlTextWriter(strKbFileTarget, Encoding.UTF8);
				writer.Formatting = Formatting.Indented;
				doc.Save(writer);

				progressBarAdaptationFile.Visible = false;
			}
			catch (System.Data.DataException ex)
			{
				if (ex.Message == "A child row has multiple parents.")
				{
					// this happens when the knowledge base has invalid data in it (e.g. when there is two
					//  canonically equivalent words in different records). This is technically a bug in
					//  AdaptIt.
					throw new ApplicationException(String.Format("The AdaptIt xml file '{0}' has invalid data in it! Contact [email protected]", strKbFileSource), ex);
				}

				throw ex;
			}
			catch (Exception ex)
			{
				throw new ApplicationException(String.Format("Unable to process the AdaptIt xml file '{0}'. Contact [email protected]", strKbFileSource), ex);
			}
		}
Ejemplo n.º 37
0
		// this method is called either when the user clicks the "Apply" or "OK" buttons *OR* if she
		//  tries to switch to the Test or Advanced tab. It is usually called by one of the sub-classes
		//  which have overriden the method in order to confirm their own configuration information. So
		//  here is checking code that all possible sub-classes must adhere to (or totally re-write).
		protected virtual bool OnApply()
		{
			// every converter must have a Converter Identifier (I think)
			if (String.IsNullOrEmpty(ConverterIdentifier))
				return false;

			// if the user has switched to the Advanced tab...
			else if (m_bAdvancedTabVisited)
			{
				// means we're saving that extra information in the repository also (e.g. Encoding Names)
				// update the values from those the Advanced tab
				FriendlyName = textBoxFriendlyName.Text;
				LhsEncodingId = comboBoxEncodingNamesLhs.Text;
				RhsEncodingId = comboBoxEncodingNamesRhs.Text;
				ProcessType = ProcessTypesChecked;

				// finally, add it to the repository
				//  (again, some sub-classes do something different at this point, so call a virtual function)
				AddConverterMapping();
				IsModified = false;
			}
			else
			{
				m_aEC = InitializeEncConverter;
				IsModified = false;

				// finally, if we're in 'edit mode' and the converter is already in the repository
				//  then re-add it to save changes to the repository (i.e. make the default behavior
				//  to save to repository in this case, rather than requiring the user to explicitly
				//  click the Update... button)
				if ((m_aEC != null) && m_bEditMode && IsInRepository)
					AddConverterMapping();
			}

			return true;
		}
Ejemplo n.º 38
0
		private void addToSystemRepositoryToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// we have to have a file saved to add it
			if (m_strMapNameReal == null)
				saveAsToolStripMenuItem_Click(sender, e);

			// check again, just in case they cancelled.
			if (m_strMapNameReal != null)
			{
				m_aEC = null;   // free it so we can re-create it with the "real" content
				string strFriendlyName = null, strLhsEncodingID = null, strRhsEncodingID = null;
				if (CompileRealMap())
				{
					m_aEC = new TecEncConverter();
					int nProcType = (int)ProcessTypeFlags.DontKnow;
					m_aEC.Initialize(cstrMyEncConverterName, m_strTecNameReal,
						ref strLhsEncodingID, ref strRhsEncodingID, ref m_eConvType, ref nProcType, 0, 0, true);
				}
				else
					return; // compile failed, so just quit

				if (m_aEC != null)
				{
					try
					{
						strFriendlyName = String.Format("{0}{2}{1}",
							strLhsEncodingID,
							strRhsEncodingID,
							(EncConverters.IsUnidirectional(m_aEC.ConversionType)) ? ">" : "<>");
					}
					catch { }

					EncConverters aECs = new EncConverters();
					IEncConverterConfig rConfigurator = m_aEC.Configurator;

					// call its Configure method to do the UI
					rConfigurator.Configure(aECs, strFriendlyName, m_eConvType, strLhsEncodingID, strRhsEncodingID);
				}
			}
		}
Ejemplo n.º 39
0
		public virtual void Initialize
			(
			IEncConverters aECs,
			string strHtmlFileName,
			string strDisplayName,
			string strFriendlyName,
			string strConverterIdentifier,
			ConvType eConversionType,
			string strLhsEncodingId,
			string strRhsEncodingId,
			int lProcessTypeFlags,
			bool bIsInRepository
			)
		{
			m_strOriginalFriendlyName = FriendlyName = strFriendlyName;
			ConverterIdentifier = strConverterIdentifier;
			LhsEncodingId = strLhsEncodingId;
			RhsEncodingId = strRhsEncodingId;
			m_eOrigConvType = ConversionType = eConversionType;
			ProcessType = lProcessTypeFlags;
			IsInRepository = bIsInRepository;

			m_aECs = aECs;

			// if the identifier is given, then it means we're editing.
			// (which means our button says *Update* rather than "Save in system repository"
			//  and we should ask during OnOK whether they want to update or not)
			m_bEditMode = !String.IsNullOrEmpty(ConverterIdentifier);

			// if we're editing, then it starts out clean
			IsModified = !m_bEditMode;

			// if we're editing, then we already have this converter in the collection (even if it's
			//  temporary)
			if (m_bEditMode)
			{
				m_aEC = m_aECs[FriendlyName];
				if (FriendlyName.IndexOf(EncConverters.cstrTempConverterPrefix) == 0)
					FriendlyName = m_strOriginalFriendlyName = null;
			}

			// this parameter seems the most confusing and yet is a crucial part of EncConverters
			//  so if this is *given* to us, then just use those values rather than prompting the user
			//  for them (e.g. FW knows that the BulkEdits are Unicode_to_(from_)Unicode, so we don't
			//  have to bother the user with it.
			// If we're in 'edit' mode, it is often because the user has mis-configured these parameters
			//  so if edit mode, then query for the ConvType value.
			if ((ConversionType == ConvType.Unknown) || m_bEditMode)
			{
				m_bQueryForConvType = true;
				SetConvTypeControls();
			}

			this.Text = strDisplayName;

			// get the help for the about tab
			RegistryKey keyRoot = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\SIL\SilEncConverters31", false);
			if (keyRoot != null)
			{
				string strXmlFilePath = (string)keyRoot.GetValue("RootDir");
				if (strXmlFilePath[strXmlFilePath.Length - 1] != '\\')
					strXmlFilePath += '\\';
				strXmlFilePath += @"help\" + strHtmlFileName;
				System.Diagnostics.Debug.Assert(System.IO.File.Exists(strXmlFilePath), String.Format("Can find '{0}'. If this is a development machine, you need to add the following reg key to see the About help files: HLKM\\SOFTWARE\\SIL\\SilEncConverters31\\[RootDir] = '<parent folder where the 'help' sub-folder exists>' along with a trailing slash (e.g. \"C:\\fw\\lib\\release\\\")", strHtmlFileName));
				this.webBrowserHelp.Url = new Uri(strXmlFilePath);
			}
#if DEBUG
			else
				throw new ApplicationException(@"Can't read the HLKM\SOFTWARE\SIL\SilEncConverters31\[RootDir] registry key!");
#endif

			ecTextBoxInput.Text = "Test Data";
		}
Ejemplo n.º 40
0
		public void NoConvert()
		{
			m_EncCvtrMap = null;	// if the map is empty, this means the lang is already UTF8
			m_iconverter = null;	// also null
		}
Ejemplo n.º 41
0
		// see if the user has some hidden SFM marker which we'll ask whether they want converted or not
		// the value could be things like:
		//  "\c 1  \v 1 "
		// or
		/*
		//  "\~FILTER \note a note
a second line
a third line
it is okay to type ENTER to begin each new line
the end \note* \~FILTER* \~FILTER \free This is a bit of free translation. \free* \~FILTER* "
		*/
		protected void CheckForEmbeddedMarkers(XmlAttributeCollection xnAttributes, string strAttributeName, IEncConverter aEC)
		{
			XmlAttribute xa = xnAttributes[strAttributeName];
			if (xa != null)
			{
				string strValue = xa.Value;
				if (!String.IsNullOrEmpty(strValue))
				{
					// put all text between "\" into an array of strings
					int nIndexThat, nIndexBOC, nLengthContents, nIndexThis = strValue.IndexOf('\\');
					List<string> astrOpenedMarkers = new List<string>();
					while (nIndexThis != -1)
					{
						string strMarker, strContents;
						if (FindMarkerAndContents(strValue, nIndexThis, out nIndexThat, out nIndexBOC,
							out strMarker, out strContents, out nLengthContents, astrOpenedMarkers))
						{
							List<string> astrSfmContents;
							if (!m_mapFilteredSfms.TryGetValue(strMarker, out astrSfmContents))
							{
								astrSfmContents = new List<string>();
								m_mapFilteredSfms.Add(strMarker, astrSfmContents);
							}

							// do about 20 occurrences max (just in case there's lots!)
							if (astrSfmContents.Count < cnMaxExamples)
								astrSfmContents.Add(strContents);
						}

						// check the next chunk
						nIndexThis = nIndexThat;
					}
				}
			}
		}
Ejemplo n.º 42
0
		public virtual void AddConverterStep(IEncConverter rConvert, bool bDirectionForward, NormalizeFlags eNormalizeOutput)
		{
			m_aEncConverter.Add(rConvert);
			m_aDirectionForward.Add(bDirectionForward);
			m_aNormalizeOutput.Add(eNormalizeOutput);
		}
Ejemplo n.º 43
0
		public FindWordProcessor(string strFindWhat, string strReplaceWith, bool bMatchCase, Font font)
		{
			if (m_aECs == null)
				m_aECs = new EncConverters(true);

			// for some reason, the text that goes to constructing the 'Find what' part of the CRegexMatcher is
			//  expecting doubly-escaped text (e.g. "\\r" for CR), but the text that goes for the 'Replace with'
			//  (i.e. the CRegex::ReplaceAll) is expecting singly-escaped text. Our text boxes, however, will always
			//  return these as doubly-escaped. So for the 'Replace with' stuff, we need to turn certain doubly-
			//  escaped codes into their single-escaped flavors).
			int nNumEscapeCodes = astrReplaceDoubleEscapeCodes.Length;
			for (int i = 0; i < nNumEscapeCodes; i++)
				strReplaceWith = strReplaceWith.Replace(astrReplaceDoubleEscapeCodes[i], astrReplaceEscapeCodes[i]);

			m_aECRegex = InitSearchFontConverter(strFindWhat, strReplaceWith, font, bMatchCase);
			AutoReplaceOnNextFind = false;  // we'll take care of this as well

			// Normally, we search the text one paragraph at a time for the FindWhat string, but if the user
			//  has multiple "\r"s in the search string, it means we're supposed to find stuff beyond paragraph
			//  boundaries. So indicate how many paragraphs we should include in the Search based on the number
			//  of "\r"s in the search string...
			string[] strTokens = strFindWhat.Split(new string[] { @"\r\n", @"\r" }, StringSplitOptions.None);
			NumOfParagraphsToSearch = strTokens.Length;
			IsAnyCRs = (NumOfParagraphsToSearch > 1);

			// ... however, we don't need to get an extra paragraph if the \r occurs at the end of the FindWhat string
			if (String.IsNullOrEmpty(strTokens[NumOfParagraphsToSearch - 1]))
			{
				NumOfParagraphsToSearch--;
			}
		}
Ejemplo n.º 44
0
		private void DoEdit(EncConverters aECs, IEncConverter aEC, string strProjectName, string strFontName, string sFontSize)
		{
			this.textBoxNewProjectName.Text = strProjectName;
			this.textBoxWordBoundaryDelimiter.Text = m_strWordBoundaryDelimiter;

			// new in 1.2 (so it might not exist)
			this.textBoxAddlPunctuation.Text = this.DecodePunctuationForCC(m_strNonWordCharacters);

			this.listBoxFontSize.SelectedItem = sFontSize;
			this.comboBoxFont.SelectedItem = strFontName;

			m_bLegacy = (aEC.ConversionType == ConvType.Legacy_to_Legacy);
			this.checkBoxUnicode.Checked = !m_bLegacy;
			if( m_bLegacy )
			{
				this.labelCP.Visible = this.textBoxCP.Visible = true;
				this.textBoxCP.Text = aECs.CodePage(strFontName).ToString();
			}

			// update the "Add New Project" button to say "Update Project"
			this.groupBoxNewProject.Text = "Edit Project Settings";
			this.buttonAddNewProject.Text = "Update &Project";
			this.toolTips.SetToolTip(this.buttonAddNewProject, "Click to update the project information");
			this.textBoxNewProjectName.ReadOnly = true;
			EnableAddNewProjectButton();
		}
Ejemplo n.º 45
0
		/// -----------------------------------------------------------------------------------
		/// <summary>
		/// Convert a file and display it in the window
		/// </summary>
		/// -----------------------------------------------------------------------------------
		public void DoFileConvert(IEncConverter ec, string inputFilename)
		{
			CheckDisposed();

			// start hour glass
			using (new WaitCursor(this))
			{
				// open the input and output files using the given encoding formats
				// 28591 is a 'magic' code page that stuffs each input byte into
				// the low byte of the unicode character, leaving the top byte zero.
				// This is a good code page to use because it is simple and fully reversible
				// for any input.
				using (StreamReader reader = new StreamReader(inputFilename,
					Encoding.GetEncoding(EncodingConstants.kMagicCodePage), true))
				{
					// This tells the converter that the input will be 16-bit characters
					// produced by converting the bytes of the file using CP28591.
					ec.CodePageInput = EncodingConstants.kMagicCodePage;
					ec.EncodingIn = ECInterfaces.EncodingForm.LegacyString;

					reader.BaseStream.Seek(0, SeekOrigin.Begin);

					// read the lines of the input file, (optionally convert,) and write them out.
					string sOutput = string.Empty;
					string sInput;
					m_savedOutput = new StringBuilder();

					m_svOutput.Clear(false);
					m_fHasOutput = false;

					// Read the lines of the input file, convert them, and display them
					// in the view.
					while (reader.Peek() > -1)
					{
						sInput = reader.ReadLine();

						if (sInput == string.Empty || sInput.StartsWith(@"\_sh ") || sInput.StartsWith(@"\id "))
							sOutput = sInput;
						else
							sOutput = ConvertOneLine(ec, sInput);
						m_svOutput.AddPara(sOutput);
						m_savedOutput.AppendLine(sOutput);
						m_fHasOutput = true;
					}

					reader.Close();
					m_svOutput.CompleteSetText();
				}
			}
		}
Ejemplo n.º 46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Convert one line of text for display
		/// </summary>
		/// <param name="ec"></param>
		/// <param name="input"></param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private string ConvertOneLine(IEncConverter ec, string input)
		{
			string marker = string.Empty;
			string remainder = string.Empty;

			// if the input string is empty, don't try to convert it
			if (input == string.Empty)
				return input;

			// split the marker and the remainder portions of the text line.
			if (input[0] != '\\')
				remainder = input;
			else
			{
				int spacePosition = input.IndexOf(" ");
				if (spacePosition == -1)
					return input;
				else
				{
					marker = input.Substring(0, spacePosition);
					remainder = input.Substring(spacePosition);
				}
			}

			return marker + ec.Convert(remainder);
		}
Ejemplo n.º 47
0
		private void buttonTargetLanguageConverter_Click(object sender, EventArgs e)
		{
			ConvType eFilter = (IsLegacyToUnicode) ? ConvType.Legacy_to_from_Unicode : ConvType.Unicode_to_from_Legacy;
			m_aEcTarget = GetEncConverters.AutoSelectWithTitle(eFilter, "Choose Target Language Converter");
			if (m_aEcTarget != null)
				labelTargetLanguageConverter.Text = m_aEcTarget.Name;
			else
				labelTargetLanguageConverter.Text = cstrDefaultConvertLabelTarget;
		}
Ejemplo n.º 48
0
		public bool SetConverter(EncConverters converters)
		{
			if (m_EncCvtrMap == null)
				return true;	// if the map is empty, this means the lang is already UTF8

			m_iconverter = converters[m_EncCvtrMap];
			return (m_iconverter != null);
		}
Ejemplo n.º 49
0
		protected void ConvertAttribute(XmlAttributeCollection xnAttributes, string strAttributeName, IEncConverter aEC)
		{
			XmlAttribute xa = xnAttributes[strAttributeName];
			if (xa != null)
			{
				string strValue = xa.Value;

				if (!String.IsNullOrEmpty(strValue))
				{
					string strValueConverted = (aEC != null) ? aEC.Convert(strValue) : strValue;
					xa.Value = strValueConverted;
				}
			}
		}
Ejemplo n.º 50
0
		internal void NewDocument()
		{
			// reset the name
			m_strTecNameReal = m_strMapNameReal = null;

			InitCharacterMapDialogs();
			Program.AddFilenameToTitle(m_strMapNameReal);

			// query the user for the ConvType (kind of need it)
			bool bUserCancelled = !QueryConvType();

			InitTempVars();

			// reset vars in case they were something else
			m_nCodePageLegacyLhs = 0;
			m_nCodePageLegacyRhs = 0;

			if (!bUserCancelled)
			{
				// for legacy encodings, prompt for the font.
#if !DEBUG
				MessageBox.Show("Select the font for the left-hand side encoding", cstrCaption);
#endif
				bUserCancelled |= !SetFontLhs();
			}

			if (!bUserCancelled)
			{
				// for legacy encodings, prompt for the font.
#if !DEBUG
				MessageBox.Show("Select the font for the right-hand side encoding", cstrCaption);
#endif
				SetFontRhs();
			}

			Point ptLocation = new Point(Location.X + Bounds.Size.Width, Location.Y);
			m_formDisplayUnicodeNamesLhs.Location = ptLocation;

			ptLocation = new Point(m_formDisplayUnicodeNamesLhs.Location.X, m_formDisplayUnicodeNamesLhs.Location.Y + m_formDisplayUnicodeNamesLhs.Bounds.Size.Height);
			m_formDisplayUnicodeNamesRhs.Location = ptLocation;

			// initialize it with our clues
			this.richTextBoxMapEditor.Text = String.Format("; This file was created by <author> using TECkitMappingEditorU.exe v{1} on {2}.{0};   {3}{4}{0};   {5}{6};{7}{0};   {8}{9};{10}{0}{11}{0}{12}{0}{13}{0}{0}",
				Environment.NewLine,
				Application.ProductVersion,
				DateTime.Now.ToShortDateString(),
				cstrConvTypeClue,
				m_eConvType.ToString(),
				cstrLhsFontClue,
				textBoxSample.Font.Name,
				textBoxSample.Font.Size,
				cstrRhsFontClue,
				textBoxSampleForward.Font.Name,
				textBoxSampleForward.Font.Size,
				BoundsClueString(cstrMainFormClue, Bounds),
				BoundsClueString(cstrCodePointFormClueLhs, m_formDisplayUnicodeNamesLhs.Bounds),
				BoundsClueString(cstrCodePointFormClueRhs, m_formDisplayUnicodeNamesRhs.Bounds));

			if (IsLhsLegacy)
			{
				if (IsRhsLegacy)
				{
					this.richTextBoxMapEditor.Text += String.Format("LHSName                 \"canonical name of the 'source' encoding or left-hand side of the conversion\"{0}RHSName                 \"canonical name of the 'target' encoding or right-hand side of the conversion\"{0}LHSDescription          \"description for the left-hand side of the mapping\"{0}RHSDescription          \"description for the right-hand side of the mapping\"{0}Version                 \"1\"{0}Contact                 \"mailto:user@addr\"{0}RegistrationAuthority   \"the organization responsible for the encoding\"{0}RegistrationName        \"the name and version of the mapping, as recognized by that authority\"{0}Copyright               \"© {1} <CompanyName>. All rights reserved.\"{0}LHSFlags                (){0}RHSFlags                (){0}{0}pass(Byte){0}{0}; type a 'k' in the 'Left-side Sample' box below to see how this works.{0}107     <>  110     ; 'k' <> 'n'{0}", Environment.NewLine, DateTime.Today.Year);
				}
				else
				{
					this.richTextBoxMapEditor.Text += String.Format("EncodingName            \"a canonical name that uniquely identifies this mapping table from all others\"{0}DescriptiveName         \"a string that describes the mapping\"{0}Version                 \"1\"{0}Contact                 \"mailto:user@addr\"{0}RegistrationAuthority   \"the organization responsible for the encoding\"{0}RegistrationName        \"the name and version of the mapping, as recognized by that authority\"{0}Copyright               \"© {1} <CompanyName>. All rights reserved.\"{0}LHSFlags                (){0}RHSFlags                (){0}{0}pass(Byte_Unicode){0}{0}; type a 'k' in the 'Left-side Sample' box below to see how this works.{0}107     <>  LATIN_SMALL_LETTER_N    ; 'k' <> 'n'{0}", Environment.NewLine, DateTime.Today.Year);
				}
			}
			else
			{
				if (IsRhsLegacy)
				{
					this.richTextBoxMapEditor.Text += String.Format("LHSName                 \"canonical name of the 'source' encoding or left-hand side of the conversion\"{0}RHSName                 \"canonical name of the 'target' encoding or right-hand side of the conversion\"{0}LHSDescription          \"description for the left-hand side of the mapping\"{0}RHSDescription          \"description for the right-hand side of the mapping\"{0}Version                 \"1\"{0}Contact                 \"mailto:user@addr\"{0}RegistrationAuthority   \"the organization responsible for the encoding\"{0}RegistrationName        \"the name and version of the mapping, as recognized by that authority\"{0}Copyright               \"© {1} <CompanyName>. All rights reserved.\"{0}LHSFlags                (){0}RHSFlags                (){0}{0}pass(Unicode_Byte){0}{0}; type a 'k' in the 'Left-side Sample' box below to see how this works.{0}LATIN_SMALL_LETTER_K    <>  110 ; 'k' <> 'n'{0}", Environment.NewLine, DateTime.Today.Year);
				}
				else
				{
					this.richTextBoxMapEditor.Text += String.Format("LHSName                 \"canonical name of the 'source' encoding or left-hand side of the conversion\"{0}RHSName                 \"canonical name of the 'target' encoding or right-hand side of the conversion\"{0}LHSDescription          \"description for the left-hand side of the mapping\"{0}RHSDescription          \"description for the right-hand side of the mapping\"{0}Version                 \"1\"{0}Contact                 \"mailto:user@addr\"{0}RegistrationAuthority   \"the organization responsible for the encoding\"{0}RegistrationName        \"the name and version of the mapping, as recognized by that authority\"{0}Copyright               \"© {1} <CompanyName>. All rights reserved.\"{0}LHSFlags                (){0}RHSFlags                (){0}{0}pass(Unicode){0}{0}; type a 'k' in the 'Left-side Sample' box below to see how this works.{0}LATIN_SMALL_LETTER_K    <>  LATIN_SMALL_LETTER_N    ; 'k' <> 'n'{0}", Environment.NewLine, DateTime.Today.Year);
				}
			}

			this.richTextBoxMapEditor.Select(richTextBoxMapEditor.Text.Length, 0);

			// so it re-creates for this "new" map
			m_aEC = null;
			Program.Modified = false;   // until the user does something, this doesn't need to be saved
		}
Ejemplo n.º 51
0
		protected void ConvertEmbeddedMarkers(XmlAttributeCollection xnAttributes, string strAttributeName, IEncConverter aEC, List<string> astrSfmsToConvert)
		{
			XmlAttribute xa = xnAttributes[strAttributeName];
			if (xa != null)
			{
				string strValue = xa.Value;
				if (!String.IsNullOrEmpty(strValue))
				{
					// iterate thru the chunks of sfm data and convert them with the source converter if in the
					//  list of SFMs to convert
					int nIndexThat, nIndexBOC, nLengthContents, nIndexThis = strValue.IndexOf('\\');
					List<string> astrOpenedMarkers = new List<string>();
					while (nIndexThis != -1)
					{
						string strMarker, strContents;
						if (FindMarkerAndContents(strValue, nIndexThis, out nIndexThat, out nIndexBOC,
							out strMarker, out strContents, out nLengthContents, astrOpenedMarkers))
						{
							// check if it's in the list of SFMs to convert
							if (astrSfmsToConvert.Contains(strMarker))
							{
								string strContentsConverted = aEC.Convert(strContents);
								strValue = ReplaceSubstring(strValue, nIndexThis + nIndexBOC, nLengthContents, strContentsConverted);
							}
						}

						nIndexThis = nIndexThat;
					}

					xa.Value = strValue;
				}
			}
		}
Ejemplo n.º 52
0
		private void UpdateTextChanged(TextBox tbSrc, TextBox tbDst, IEncConverter aEC, bool bDirectionForward)
		{
			if (tbSrc.Text.Length > 0)
			{
				if (aEC != null)
				{
					try
					{
						tbDst.Text = null;  // to force the "TextChanged"
						aEC.DirectionForward = bDirectionForward;
						tbDst.Text = aEC.Convert(tbSrc.Text);
					}
					catch (ECException e)
					{
						if (e.ErrorCode != (int)ErrStatus.InvalidForm)
							MessageBox.Show(e.Message);
					}
				}
			}
			else
				tbDst.Text = null;
		}
Ejemplo n.º 53
0
		internal bool OpenDocument(string strMapName)
		{
			if (Program.Modified)
				CheckForSaveDirtyFile();

			InitCharacterMapDialogs();

			bool bModified = false;

			// if we are dealing with a real file...
			m_strMapNameReal = strMapName;

			// check to see if it exists (the alternate exception isn't very helpful)
			if (!File.Exists(m_strMapNameReal))
			{
				MessageBox.Show(String.Format("The file '{0}' doesn't exist!", m_strMapNameReal, cstrCaption));
				return false;
			}

			// otherwise, determine the .tec filename
			m_strTecNameReal = m_strMapNameReal.Remove(m_strMapNameReal.Length - 3, 3) + "tec";
			Program.AddFilenameToTitle(m_strMapNameReal);

			// and put it's contents into the editor.
			this.richTextBoxMapEditor.Lines = File.ReadAllLines(m_strMapNameReal, m_enc);

			// see if our 'clues' are in the file
			ConvType eConvType = ConvType.Unknown;
			bool bLhsFontFound = false;
			bool bRhsFontFound = false;
			bool bCodePointFormSizeHasBeenSetLhs = false;
			bool bCodePointFormSizeHasBeenSetRhs = false;
			m_nCodePageLegacyLhs = 0;
			m_nCodePageLegacyRhs = 0;

			foreach (string strLine in richTextBoxMapEditor.Lines)
			{
				int nIndex = strLine.IndexOf(cstrConvTypeClue);
				if (nIndex != -1)
				{
					string strConvType = strLine.Substring(nIndex + cstrConvTypeClue.Length);

					foreach (string asName in Enum.GetNames(typeof(ConvType)))
					{
						if (asName == strConvType)
						{
							eConvType = (ConvType)Enum.Parse(typeof(ConvType), strConvType);
							break;
						}
					}
				}

				nIndex = strLine.IndexOf(cstrLhsFontClue);
				if (nIndex != -1)
				{
					int nDelimiter = strLine.LastIndexOf(';');
					int nLen = nDelimiter - (nIndex + cstrLhsFontClue.Length);
					string strFontName = strLine.Substring(nIndex + cstrLhsFontClue.Length, nLen);
					string strFontSize = strLine.Substring(nDelimiter + 1);
					float emSize = Convert.ToSingle(strFontSize);
					Font font = Program.GetSafeFont(strFontName, emSize);
					textBoxSample.Font = font;
					textBoxSampleReverse.Font = font;
					bLhsFontFound = true;
				}

				nIndex = strLine.IndexOf(cstrRhsFontClue);
				if (nIndex != -1)
				{
					int nDelimiter = strLine.LastIndexOf(';');
					int nLen = nDelimiter - (nIndex + cstrRhsFontClue.Length);
					string strFontName = strLine.Substring(nIndex + cstrRhsFontClue.Length, nLen);
					string strFontSize = strLine.Substring(nDelimiter + 1);
					float emSize = Convert.ToSingle(strFontSize);
					Font font = Program.GetSafeFont(strFontName, emSize);
					textBoxSampleForward.Font = font;
					bRhsFontFound = true;
				}

				nIndex = strLine.IndexOf(cstrLhsCodePageClue);
				if (nIndex != -1)
				{
					string strCodePage = strLine.Substring(nIndex + cstrLhsCodePageClue.Length);
					try
					{
						m_nCodePageLegacyLhs = Convert.ToInt32(strCodePage);
					}
					catch { }
				}

				nIndex = strLine.IndexOf(cstrRhsCodePageClue);
				if (nIndex != -1)
				{
					string strCodePage = strLine.Substring(nIndex + cstrRhsCodePageClue.Length);
					try
					{
						m_nCodePageLegacyRhs = Convert.ToInt32(strCodePage);
					}
					catch { }
				}

				nIndex = strLine.IndexOf(cstrMainFormClue);
				if (nIndex != -1)
				{
					try
					{
						string strXYWH = strLine.Substring(nIndex + cstrMainFormClue.Length);
						string[] aStrBounds = strXYWH.Split(new char[] { ',' });
						Rectangle rectBounds = new Rectangle
						(
							Int32.Parse(aStrBounds[0]),
							Int32.Parse(aStrBounds[1]),
							Int32.Parse(aStrBounds[2]),
							Int32.Parse(aStrBounds[3])
						);

						if (SetBounds(this, ref rectBounds))
							SetBoundsClue(cstrMainFormClue, rectBounds);
					}
					catch { }
				}

				// search for the character map window location (what used to be the 'code point' window)
				string strClue = cstrCodePointFormClueLhs;
				nIndex = strLine.IndexOf(cstrCodePointFormClueLhs);
				if (nIndex != -1)
				{
					try
					{
						string strXYWH = strLine.Substring(nIndex + strClue.Length);
						string[] aStrBounds = strXYWH.Split(new char[] { ',' });
						Rectangle rectBounds = new Rectangle
						(
							Int32.Parse(aStrBounds[0]),
							Int32.Parse(aStrBounds[1]),
							Int32.Parse(aStrBounds[2]),
							Int32.Parse(aStrBounds[3])
						);

						if (SetBounds(m_formDisplayUnicodeNamesLhs, ref rectBounds))
							SetBoundsClue(strClue, rectBounds);
						bCodePointFormSizeHasBeenSetLhs = true;
					}
					catch { }
				}

				nIndex = strLine.IndexOf(cstrCodePointFormClueRhs);
				if (nIndex != -1)
				{
					try
					{
						string strXYWH = strLine.Substring(nIndex + cstrCodePointFormClueRhs.Length);
						string[] aStrBounds = strXYWH.Split(new char[] { ',' });
						Rectangle rectBounds = new Rectangle
						(
							Int32.Parse(aStrBounds[0]),
							Int32.Parse(aStrBounds[1]),
							Int32.Parse(aStrBounds[2]),
							Int32.Parse(aStrBounds[3])
						);

						if (SetBounds(m_formDisplayUnicodeNamesRhs, ref rectBounds))
							SetBoundsClue(cstrCodePointFormClueRhs, rectBounds);
						bCodePointFormSizeHasBeenSetRhs = true;
					}
					catch { }
				}
			}

			// if we didn't find the ConvType, then query for it
			bool bUserCancelled = false;
			if (eConvType == ConvType.Unknown)
				bUserCancelled = !QueryConvType();
			else
				ConversionType = eConvType;

			InitTempVars();

			if (!bUserCancelled && !bLhsFontFound)
			{
				// for legacy encodings, prompt for the font.
				MessageBox.Show("Select the font for the left-hand side encoding", cstrCaption);
				bUserCancelled |= !SetFontLhs();
			}
			else if (unicodeValuesWindowToolStripMenuItem.Checked)
			{
				if (IsLhsLegacy && (m_nCodePageLegacyLhs == 0))
				{
					EncConverters aECs = new EncConverters(true);
					try
					{
						m_nCodePageLegacyLhs = aECs.CodePage(textBoxSample.Font.Name);
					}
					catch { }
				}

				m_formDisplayUnicodeNamesLhs.Initialize(IsLhsLegacy, textBoxSample.Font, m_nCodePageLegacyLhs);
			}

			if (!bUserCancelled && !bRhsFontFound)
			{
				// for legacy encodings, prompt for the font.
				MessageBox.Show("Select the font for the right-hand side encoding", cstrCaption);
				SetFontRhs();
			}
			else if (unicodeValuesWindowToolStripMenuItem.Checked)
			{
				if (IsRhsLegacy && (m_nCodePageLegacyRhs == 0))
				{
					EncConverters aECs = new EncConverters(true);
					try
					{
						m_nCodePageLegacyRhs = aECs.CodePage(textBoxSampleForward.Font.Name);
					}
					catch { }
				}

				m_formDisplayUnicodeNamesRhs.Initialize(IsRhsLegacy, textBoxSampleForward.Font, m_nCodePageLegacyRhs);
			}

			if (!bCodePointFormSizeHasBeenSetLhs)
			{
				Point ptLocation = new Point(Location.X + Bounds.Size.Width, Location.Y);
				m_formDisplayUnicodeNamesLhs.Location = ptLocation;
			}

			if (!bCodePointFormSizeHasBeenSetRhs)
			{
				Point ptLocation = new Point(m_formDisplayUnicodeNamesLhs.Location.X, m_formDisplayUnicodeNamesLhs.Location.Y + m_formDisplayUnicodeNamesLhs.Bounds.Size.Height);
				m_formDisplayUnicodeNamesRhs.Location = ptLocation;
			}

			if (!bLhsFontFound || !bRhsFontFound || !bCodePointFormSizeHasBeenSetLhs || !bCodePointFormSizeHasBeenSetRhs)
			{
				// initialize it with our clues
				string strPrefixHeader = cstrOpeningHeader + String.Format("v{1} on {2}.{0};   {3}{4}{0};   {5}{6};{7}{0};   {8}{9};{10}{0}{11}{0}{12}{0}{13}{0}",
					Environment.NewLine,
					Application.ProductVersion,
					DateTime.Now.ToShortDateString(),
					cstrConvTypeClue,
					m_eConvType.ToString(),
					cstrLhsFontClue,
					textBoxSample.Font.Name,
					textBoxSample.Font.Size,
					cstrRhsFontClue,
					textBoxSampleForward.Font.Name,
					textBoxSampleForward.Font.Size,
					BoundsClueString(cstrMainFormClue, Bounds),
					BoundsClueString(cstrCodePointFormClueLhs, m_formDisplayUnicodeNamesLhs.Bounds),
					BoundsClueString(cstrCodePointFormClueRhs, m_formDisplayUnicodeNamesRhs.Bounds));

				strPrefixHeader += AddCodePageClue(cstrLhsCodePageClue, m_nCodePageLegacyLhs);
				strPrefixHeader += AddCodePageClue(cstrRhsCodePageClue, m_nCodePageLegacyRhs);
				strPrefixHeader += String.Format("{0}", Environment.NewLine);

				this.richTextBoxMapEditor.Text = strPrefixHeader + SkipPast0900Header;
				bModified = true;
			}

			// so it re-creates for this "new" map
			m_aEC = null;
			Program.Modified = bModified;

			return true;
		}
Ejemplo n.º 54
0
		protected void ResetFields()
		{
			ConversionType = m_eOrigConvType;
			ConverterIdentifier = null;
			ProcessType = 0;
			m_aEC = null;
		}
Ejemplo n.º 55
0
		public void SaveTempAndCompile()
		{
			File.WriteAllLines(m_strMapNameTemp, this.richTextBoxMapEditor.Lines, m_enc);

			try
			{
				string strTecName = m_strTecNameTemp;
				TECkitDllWrapper.CompileMap(m_strMapNameTemp, ref strTecName);

				// if the compiler had to use a different file, then clear the reference to rebuild it
				// if (m_strTecNameTemp != strTecName)
				m_aEC = null;

				this.textBoxCompilerResults.Text = "Compiled successfully!";

				// now that we have something we can compile successfully, create a converter of it
				if (m_aEC == null)
				{
					m_strTecNameTemp = strTecName;
					m_aEC = new TecEncConverter();
					string strDummy = null;
					int nProcType = (int)ProcessTypeFlags.DontKnow;
					m_aEC.Initialize(cstrMyEncConverterName, m_strTecNameTemp,
						ref strDummy, ref strDummy, ref m_eConvType, ref nProcType, m_nCodePageLegacyLhs, m_nCodePageLegacyRhs, true);
				}

				if (this.textBoxSample.Text.Length > 0)
				{
					UpdateTextChanged(this.textBoxSample, this.textBoxSampleForward, m_aEC, true);
					UpdateUnicodeDetails(this.textBoxSample);
				}
			}
			catch (Exception ex)
			{
				this.textBoxCompilerResults.Text = ex.Message;

				// clear the converter so we don't accidentally call it while we don't have a good map
				m_aEC = null;
			}
		}
Ejemplo n.º 56
0
		protected void SetConverter(string strFontName, ref IEncConverter aEC, Label aLabel, ref string strConvertedFontName)
		{
			string strMappingName = GetEncConverters.GetMappingNameFromFont(strFontName);
			if (!String.IsNullOrEmpty(strMappingName))
			{
				aEC = GetEncConverters[strMappingName];
				if (aEC != null)
					aLabel.Text = aEC.Name;

				// also see if we have a default font for the converted text
				string[] astrFontMappings = GetEncConverters.GetFontMapping(aEC.Name, strFontName);
				if (astrFontMappings.Length > 0)
					strConvertedFontName = astrFontMappings[0];
			}

			Font font;
			if (!m_mapFonts.TryGetValue(strConvertedFontName, out font))
			{
				font = new Font(strConvertedFontName, m_nStatusBoxDefaultFontSize);
				m_mapFonts.Add(strConvertedFontName, font);
			}
		}
Ejemplo n.º 57
0
		protected void ConvertAdaptationFile(string strAdaptationFileSource, string strAdaptationFileTarget,
			IEncConverter aEcSource, IEncConverter aEcTarget, IEncConverter aEcGloss, string strFontNameSource, string strFontNameConvertedSource)
		{
			// Since AdaptIt will make different records for two words which are canonically
			//  equivalent, if we use the class object to read it in via ReadXml, that will throw
			//  an exception in such a case. So see if using XmlDocument is any less restrictive
			try
			{
				string strTempAdaptationFileSource = strAdaptationFileSource;
				CheckForIncorrectEncodingString(ref strTempAdaptationFileSource);
				AppendStatusOutputNl("Processing Adaptation file: " + strAdaptationFileSource, m_strStatusBoxDefaultFont, true);
				XmlDocument doc = new XmlDocument();
				doc.Load(strTempAdaptationFileSource);
				XmlNodeList xnlBucketIterator = doc.SelectNodes("/AdaptItDoc//S");  // use "//" since the 'S' element can be embedded

				// go thru it all looking for extra fields we'll need to convert from within the 'm', 'mm' fields.
				foreach (XmlNode xnBucket in xnlBucketIterator)
				{
					XmlAttributeCollection xacAttributes = xnBucket.Attributes;
					CheckForEmbeddedMarkers(xacAttributes, "m", aEcSource);
					CheckForEmbeddedMarkers(xacAttributes, "mm", aEcSource);
				}

				// ask the user to decide about these fields
				FilteredFieldsForm dlg = new FilteredFieldsForm(m_mapFilteredSfms, m_astrSfmsToConvert, m_astrSfmsToNotConvert,
					m_mapFonts[strFontNameSource], m_mapFonts[strFontNameConvertedSource], aEcSource);

				if (dlg.ShowDialog() == DialogResult.OK)
					dlg.DivyUpSfmsToConvert(m_astrSfmsToConvert, m_astrSfmsToNotConvert);

				progressBarAdaptationFile.Visible = true;
				progressBarAdaptationFile.Value = 0;
				progressBarAdaptationFile.Maximum = xnlBucketIterator.Count;
				foreach (XmlNode xnBucket in xnlBucketIterator)
				{
					progressBarAdaptationFile.Value++;

					// convert: <S s="I" k="I" t="v3.0" a="v3.0"
					XmlAttributeCollection	xacAttributes = xnBucket.Attributes;
					ConvertAttribute(xacAttributes, "s", aEcSource);
					ConvertAttribute(xacAttributes, "k", aEcSource);
					ConvertAttribute(xacAttributes, "pp", aEcSource);
					ConvertAttribute(xacAttributes, "fp", aEcSource);
					ConvertAttribute(xacAttributes, "mp", aEcSource);
					ConvertAttribute(xacAttributes, "t", aEcTarget);
					ConvertAttribute(xacAttributes, "a", aEcTarget);
					ConvertAttribute(xacAttributes, "g", aEcGloss);

					if (m_astrSfmsToConvert.Count > 0)
					{
						ConvertEmbeddedMarkers(xacAttributes, "m", aEcSource, m_astrSfmsToConvert);
						ConvertEmbeddedMarkers(xacAttributes, "mm", aEcSource, m_astrSfmsToConvert);
					}
				}

				// now write it to the target folder
				InsureDirectoryExists(strAdaptationFileTarget);
				XmlTextWriter writer = new XmlTextWriter(strAdaptationFileTarget, Encoding.UTF8);
				writer.Formatting = Formatting.Indented;
				doc.Save(writer);

				progressBarAdaptationFile.Visible = false;
			}
			catch (System.Data.DataException ex)
			{
				if (ex.Message == "A child row has multiple parents.")
				{
					// this happens when the knowledge base has invalid data in it (e.g. when there is two
					//  canonically equivalent words in different records). This is technically a bug in
					//  AdaptIt.
					throw new ApplicationException(String.Format("The AdaptIt xml file '{0}' has invalid data in it! Contact [email protected]", strAdaptationFileSource), ex);
				}

				throw ex;
			}
			catch (Exception ex)
			{
				throw new ApplicationException(String.Format("Unable to process the AdaptIt xml file '{0}'. Contact [email protected]", strAdaptationFileSource), ex);
			}
		}
Ejemplo n.º 58
0
		private void listBoxProjects_SelectedIndexChanged(object sender, EventArgs e)
		{
			buttonConvert.Enabled = (listBoxProjects.SelectedIndex != -1);
			if (buttonConvert.Enabled)
			{
				string strSelectedProjectName = (string)listBoxProjects.SelectedItem;

				// get the file spec for the project configuration file (so we can harvest the font names)
				string strProjectFileSource = String.Format(@"{0}\{1}\{2}", ProjectsFolder(ProjectType), strSelectedProjectName, cstrAdaptItProjectFilename);

				// reset all the details
				m_aEcGloss = m_aEcSource = m_aEcTarget = null;
				m_strFontNameSource = m_strFontNameTarget = null;
				labelSourceLanguageConverter.Text = cstrDefaultConvertLabelSource;
				labelTargetLanguageConverter.Text = cstrDefaultConvertLabelTarget;
				labelGlossLanguageConverter.Text = cstrDefaultConvertLabelGloss;
				m_strDefaultUnicodeFontSource = m_strStatusBoxDefaultFont;
				m_strDefaultUnicodeFontTarget = m_strStatusBoxDefaultFont;

				// get the fonts associated with this project
				GetProjectFonts(strProjectFileSource, out m_strFontNameSource, out m_strFontNameTarget);

				// see if there's a converter assigned in the repository for these font names
				SetConverter(m_strFontNameSource, ref m_aEcSource, labelSourceLanguageConverter, ref m_strDefaultUnicodeFontSource);
				SetConverter(m_strFontNameTarget, ref m_aEcTarget, labelTargetLanguageConverter, ref m_strDefaultUnicodeFontTarget);

				InitStatusBox();
			}
		}
Ejemplo n.º 59
0
		public virtual void Initialize
			(
			IEncConverters aECs,
			string strFriendlyName,
			string strConverterIdentifier,
			ConvType eConversionType,
			string strTestData
			)
		{
			FriendlyName = strFriendlyName;
			ConverterIdentifier = strConverterIdentifier;
			ConversionType = eConversionType;

			m_aECs = aECs;
			m_aEC = InitializeEncConverter;

			tabControl.Controls.Remove(tabPageAbout);
			tabControl.Controls.Remove(tabPageSetup);
			tabControl.Controls.Remove(tabPageAdvanced);

			// for 'test', it's possible that there may be some font mapping in the repository
			string strLhsName, strRhsName;
			if (m_aECs.GetFontMappingFromMapping(strFriendlyName, out strLhsName, out strRhsName))
			{
				ecTextBoxInput.Font = CreateFontSafe(strLhsName, ecTextBoxInput.Font);
				ecTextBoxOutput.Font = CreateFontSafe(strRhsName, ecTextBoxOutput.Font);
			}

			ecTextBoxInput.Text = strTestData;
			buttonOK.Visible = buttonApply.Visible = false;
			buttonCancel.Text = "Close";

			helpProvider.SetHelpString(buttonCancel, Properties.Resources.CloseButtonHelpString);

		}
Ejemplo n.º 60
0
		protected bool IsLhsLegacy(IEncConverter aEC)
		{
			if (aEC.DirectionForward)
				return (EncConverter.NormalizeLhsConversionType(aEC.ConversionType) == NormConversionType.eLegacy);
			else
				return (EncConverter.NormalizeRhsConversionType(aEC.ConversionType) == NormConversionType.eLegacy);
		}