SyntaxHighlighterBase.cs :  » Database » SQL-Power-Injector » SQLPowerInjector » SyntaxHighlighter » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Database » SQL Power Injector 
SQL Power Injector » SQLPowerInjector » SyntaxHighlighter » SyntaxHighlighterBase.cs
//*********************************************************************
//                                   //
//  SQL Power Injector 1.2 Copyright (c) 2006-2007 Francois Larouche //
//                                   //
//  Author  : francois.larouche@sqlpowerinjector.com         //
//  Web Site: www.sqlpowerinjector.com                 //
//                                   //
//*******************************************************************//
using System;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Drawing;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Reflection;
using System.Collections;
using System.Diagnostics; // To remove
using System.ComponentModel;
using System.Threading;

namespace SQLPowerInjector.SyntaxHighlighter{
  /// <summary>
  /// Summary description for SyntaxHighlighterBase
  /// Note: Even though I'm just going to implement the HTML syntax
  /// I think it's a good idea to be open to other syntaxes in making
  /// it generic
  /// </summary>
  public abstract class SyntaxHighlighterBase
  {
    #region Members
    #region Protected
    protected string _textToProcess;
    protected string _syntaxFile;
    protected RichTextBox _rtbToProcess = new RichTextBox();
    #endregion
    #endregion

    #region Constants
    private const string RTF_STARTING_COLOR_TABLE_STRING = "colortbl;";
    private const string RTF_ENDING_COLOR_TABLE_STRING = "}";
    private const string RTF_PREFIX_SLASH = "\\";
    private const string RTF_PREFIX_COLOR_CODE = "\\cf";
    private const string RTF_COLOR_CODE_BLACK = "\\cf0";
    private const string RTF_FONT_BOLD = "\\b";
    private const string RTF_FONT_UNBOLD = "\\b0";
    private const string RTF_FONT_ITALIC = "\\i";
    private const string RTF_FONT_UNITALIC = "\\i0";
    private const string RTF_FONT_REGULAR = "\\b0\\i0";
    private const byte COLOR_TABLE_COLORNUMBER = 0;
    private const byte COLOR_TABLE_COLORRGB = 1;
    private const byte FAMILY_COLORNUMBER = 1;
    private const byte FAMILY_FONT_STYLE = 2;
    private const byte FAMILY_STARTING_STRING = 3;
    private const byte FAMILY_ENDING_STRING = 4;
    private const byte MEMBER_HASSUBMEMBER = 0;
    private const byte MEMBER_ISSPECIALMEMBER = 1;
    private const byte MEMBER_COLORNUMBER = 2;
    private const byte MEMBER_FONTSTYLE = 3;
    private const byte MEMBER_ENDINGSTRING = 4;
    private const byte MEMBER_MEMBERCOLORED = 5;
    private const byte MEMBER_ARRAY_DIM_SIZE = 7;
    #endregion

    #region Constructor
    public SyntaxHighlighterBase() {}
    #endregion

    public string GetRTBSyntaxHighlighted()
    {
      XmlDocument xmlDoc = LoadXMLSyntaxHighlighter();

      ParseText(xmlDoc);

      return _rtbToProcess.Rtf;
    }

    private void ParseText(XmlDocument xmlDocToParse)
    {
      XmlNodeList xmlFamilyNodeList = null;
      XmlNodeList xmlMemberNodeList = null;
      XmlNodeList xmlSubMemberNodeList = null;
      XmlNode xmlSubMemberNode = null;
      RTFFontState fontState = new RTFFontState(RTF_COLOR_CODE_BLACK, false, false, true);
      string rtfStringResult = "";
      string curMemberFontColor = RTF_COLOR_CODE_BLACK;
      string curSubMemberFontColor = RTF_COLOR_CODE_BLACK;
      string curMemberFontStyle = RTF_FONT_REGULAR;
      string curSubMemberFontStyle = RTF_FONT_REGULAR;
      string curStartingString = "";
      string curEndingString = "";
      string regExLineDelimiters = GetRegExLineDelimiters(xmlDocToParse);
      string specialMemberColor = null;
      string specialMemberFontStyle = null;
      string specialMemberEndingString = null;
      string parChar = "";
      string colorTableString = GetColorFromXMLInRTFCode(xmlDocToParse);
      ArrayList arrWordSeperator = GetArrayWordDelimiters(xmlDocToParse);
      bool isStillInsideFamily = false;
      bool isStillBetweenPar = false;
      bool isStillSpecialMember = false;
      bool isStillInsideSpecialMemberContent = false;
      string[,] arrXmlMemberList;
      ArrayList arrXmlSubMemberList;
      Regex rexLine = new Regex("(" + regExLineDelimiters + ")");
      _textToProcess = ChangeColorTable(_textToProcess, RTF_STARTING_COLOR_TABLE_STRING + colorTableString); // We need to change the color with the XML one
      string[] lines = rexLine.Split(_textToProcess);

      // We first need to get the Family groups in the XML files
      xmlFamilyNodeList = xmlDocToParse.SelectNodes("descendant::Family");

      foreach(XmlNode curXmlNode in xmlFamilyNodeList)
      {
        xmlSubMemberNode = curXmlNode.SelectSingleNode("Submembers");
        
        curMemberFontColor = RTF_PREFIX_COLOR_CODE + curXmlNode.Attributes.Item(FAMILY_COLORNUMBER).Value;
        curMemberFontStyle = GetFontStyleFromString(curXmlNode.Attributes.Item(FAMILY_FONT_STYLE).Value);
        curStartingString = curXmlNode.Attributes.Item(FAMILY_STARTING_STRING).Value;
        curEndingString = curXmlNode.Attributes.Item(FAMILY_ENDING_STRING).Value;

        if(xmlSubMemberNode != null)
        {
          curSubMemberFontColor = RTF_PREFIX_COLOR_CODE + xmlSubMemberNode.Attributes.Item(FAMILY_COLORNUMBER).Value;
          curSubMemberFontStyle = GetFontStyleFromString(xmlSubMemberNode.Attributes.Item(FAMILY_FONT_STYLE).Value);
        }
        else
        {
          curSubMemberFontColor = RTF_COLOR_CODE_BLACK;
          curSubMemberFontStyle = RTF_FONT_REGULAR;
        }

        xmlMemberNodeList = curXmlNode.SelectNodes("descendant::Members/member");
        xmlSubMemberNodeList = curXmlNode.SelectNodes("descendant::Submembers/submember");

        arrXmlMemberList = GetXmlMemberArray(xmlMemberNodeList);
        arrXmlSubMemberList = GetXmlSubMemberArray(xmlSubMemberNodeList);

        // Process line by line, it's inside we are going parse the code it's much faster
        // I think it's the easiest way to treat the problem
        foreach(string curline in lines)
        {
          if(rexLine.IsMatch(curline) || curline == "")
            rtfStringResult += "";
          else
            rtfStringResult += ParseLine(curline, arrWordSeperator, arrXmlMemberList, arrXmlSubMemberList, curMemberFontColor, curSubMemberFontColor, curMemberFontStyle, curSubMemberFontStyle, curStartingString, curEndingString, ref isStillInsideFamily, ref isStillSpecialMember, ref specialMemberColor, ref specialMemberFontStyle, ref specialMemberEndingString, ref isStillInsideSpecialMemberContent, ref isStillBetweenPar, ref parChar, ref fontState);
        }
      }

      _rtbToProcess.Rtf = rtfStringResult;
    }

    private string ParseLine(string line, ArrayList arrWordDel, string[,] arrCurXmlMemList, ArrayList arrXmlCurSubMemList, string curMemFontColor, string curSubMemFontColor, string curMemFontStyle, string curSubMemFontStyle, string familyStartingString, string familyEndingString, ref bool insideFamily, ref bool isSpecialMember, ref string specialMemberColor, ref string specialMemberFontStyle, ref string specialMemberEndingString, ref bool insideSpecialMemberContent, ref bool isStillBetweenPar, ref string parChar, ref RTFFontState curFontState)
    {  
      bool hasSubMember = false;
      bool isMemberColored = false;
      string parsedLineString = "";
      string memberColor = null;
      string memberFontStyle = null;
      string memberEndingString = null;
      string wordBuffer = "";
      string tmpEndingString = ""; // To keep the correct caracter cases
      char[] arrCharLine = line.ToCharArray();

      // We parse character by character
      for(int curChar=0; curChar<arrCharLine.Length; curChar++)
      {
        wordBuffer += arrCharLine[curChar];

        if(arrCharLine[curChar].ToString() == familyStartingString || insideFamily || arrCharLine[curChar].ToString() == familyEndingString || insideSpecialMemberContent)
        {
          if(arrCharLine[curChar].ToString() == familyStartingString && !insideSpecialMemberContent)
          {
            parsedLineString += wordBuffer.Substring(0, wordBuffer.Length - familyStartingString.Length); // Remove trailing familyStartingString
            wordBuffer = familyStartingString;
            insideFamily = true;
          } // Is at ending string with submembers
          else if(arrCharLine[curChar].ToString() == familyEndingString.ToUpper() && hasSubMember && !insideSpecialMemberContent)
          {
            parsedLineString += wordBuffer.Substring(0, wordBuffer.Length - familyEndingString.Length);
            parsedLineString += ChangeFontState(ref curFontState, curMemFontColor, curMemFontStyle);
            parsedLineString += wordBuffer.Substring(wordBuffer.Length - familyEndingString.Length, familyEndingString.Length) + ChangeFontState(ref curFontState, RTF_COLOR_CODE_BLACK, false, false, true);

            if(isSpecialMember)
            {
              insideSpecialMemberContent = true;
              parsedLineString += ChangeFontState(ref curFontState, specialMemberColor, specialMemberFontStyle);
            }

            wordBuffer = "";
            hasSubMember = false;
            insideFamily = false;
            isStillBetweenPar = false;
          }
          else if(arrWordDel.Contains(arrCharLine[curChar].ToString()) || (arrCharLine[curChar].ToString() == "\"" || arrCharLine[curChar].ToString() == "'"))
          {
            if(hasSubMember)
            {
              if((arrCharLine[curChar].ToString() == "\"" || arrCharLine[curChar].ToString() == "'") && isStillBetweenPar == false)
              {
                parChar = arrCharLine[curChar].ToString();
                isStillBetweenPar = true;
              }
              else if(arrCharLine[curChar].ToString() == parChar && isStillBetweenPar)
              {
                parChar = "";
                isStillBetweenPar = false;
              }
              else if(!isStillBetweenPar)
              {
                if(doesBelongToNodeList(arrXmlCurSubMemList, wordBuffer))
                  parsedLineString += ChangeFontState(ref curFontState, curSubMemFontColor, curSubMemFontStyle);
              }
              
              if(isStillBetweenPar)
                parsedLineString += wordBuffer;
              else
                parsedLineString += wordBuffer + ChangeFontState(ref curFontState, RTF_COLOR_CODE_BLACK, false, false, true);
              
              wordBuffer = "";
            }
            else if(isSpecialMember)
            {
              if(wordBuffer.ToUpper().EndsWith(specialMemberEndingString))
              {
                isSpecialMember = false;
                insideSpecialMemberContent = false;
                insideFamily = false;
                isStillBetweenPar = false;
                tmpEndingString = wordBuffer.Substring(wordBuffer.Length - specialMemberEndingString.Length, specialMemberEndingString.Length);
                parsedLineString += wordBuffer.Substring(0, wordBuffer.Length - specialMemberEndingString.Length);

                if(doesBelongToNodeList(arrCurXmlMemList, specialMemberEndingString))
                  parsedLineString += ChangeFontState(ref curFontState, curMemFontColor, curMemFontStyle) + tmpEndingString + ChangeFontState(ref curFontState, null, false, false, true);
                else
                  parsedLineString += tmpEndingString + ChangeFontState(ref curFontState, null, false, false, true);

                wordBuffer = "";
              }
            }
            else if(doesBelongToNodeList(arrCurXmlMemList, wordBuffer, out hasSubMember, out isSpecialMember, out memberColor, out memberFontStyle, out memberEndingString, out isMemberColored))
            {
              insideFamily = hasSubMember;
              specialMemberColor = memberColor;
              specialMemberFontStyle = memberFontStyle;
              specialMemberEndingString = memberEndingString;

              if(isSpecialMember && !hasSubMember)
              {
                insideSpecialMemberContent = true;
                
                if(isMemberColored)
                  parsedLineString += ChangeFontState(ref curFontState, specialMemberColor, specialMemberFontStyle) + wordBuffer;
                else
                  parsedLineString += ChangeFontState(ref curFontState, curMemFontColor, curMemFontStyle) + wordBuffer + ChangeFontState(ref curFontState, specialMemberColor, specialMemberFontStyle);
              }
              else
              {
                parsedLineString += ChangeFontState(ref curFontState, curMemFontColor, curMemFontStyle);
                parsedLineString += wordBuffer + ChangeFontState(ref curFontState, RTF_COLOR_CODE_BLACK, false, false, true);
              }

              wordBuffer = "";
            }
          }
        }
      }

      if(parsedLineString == "") // Means that they weren't anything to process, we still need to keep the words though
        parsedLineString = wordBuffer;
      else if(wordBuffer != "") // We don't want to leave any trailing words that weren't processed
        parsedLineString += wordBuffer;

      if(parsedLineString.EndsWith("\\par"))
      {  
        parsedLineString = parsedLineString.Remove(parsedLineString.Length - 4, 4);
        parsedLineString = parsedLineString + "\\par ";
      }

      return parsedLineString;
    }

    private string GetRegExLineDelimiters(XmlDocument xmlDocToParse)
    {
      string regExLineDel = "";
      XmlElement curXMLEle = null;
      
      XmlNodeList xmlNodeList = xmlDocToParse.SelectNodes("descendant::LineDelimiters/LineDelimiter");

      IEnumerator nodeList = xmlNodeList.GetEnumerator();
      while (nodeList.MoveNext())
      {
        curXMLEle = (XmlElement)nodeList.Current;
        regExLineDel += "[" + curXMLEle.InnerText + "]|";
      }

      // Remove trailing | at the end, if not we get all characters one by one
      regExLineDel = regExLineDel.EndsWith("|") ? regExLineDel.Substring(0, regExLineDel.Length-1) : regExLineDel;
      
      return regExLineDel;
    }

    private ArrayList GetArrayWordDelimiters(XmlDocument xmlDocToParse)
    {
      ArrayList wordDel = new ArrayList();
      XmlElement curXMLEle = null;
      
      XmlNodeList xmlNodeList = xmlDocToParse.SelectNodes("descendant::WordDelimiters/WordDelimiter");

      IEnumerator nodeList = xmlNodeList.GetEnumerator();
      while (nodeList.MoveNext())
      {
        curXMLEle = (XmlElement)nodeList.Current;
        wordDel.Add(curXMLEle.InnerText);
      }
    
      return wordDel;
    }

    private string GetColorFromXMLInRTFCode(XmlDocument xmlDocToParse)
    {
      XmlElement curXMLEle = null;
      string curColorRGB = "";
      string colorFromXMLInRTFCode = "";

      XmlNodeList xmlNodeList = xmlDocToParse.SelectNodes("descendant::ColorTable/Color");

      IEnumerator nodeList = xmlNodeList.GetEnumerator();
      while(nodeList.MoveNext())
      {
        curXMLEle = (XmlElement)nodeList.Current;
        curColorRGB = curXMLEle.Attributes.Item(COLOR_TABLE_COLORRGB).Value;

        colorFromXMLInRTFCode += GetRTFColorFromXML(curColorRGB);
      }
    
      return colorFromXMLInRTFCode;
    }

    private XmlDocument LoadXMLSyntaxHighlighter()
    {
      XmlDocument xmlDoc = Utilities.LoadXMLFile(_syntaxFile);
      
      return xmlDoc;
    }

    private string[,] GetXmlMemberArray(XmlNodeList xmlMemberNodeList)
    {
      int curXmlMemberIndex = 0;
      string[,] arrXmlMemberArray = new string[xmlMemberNodeList.Count, MEMBER_ARRAY_DIM_SIZE];

      foreach(XmlNode curXmlNode in xmlMemberNodeList)
      {
        arrXmlMemberArray.SetValue(curXmlNode.InnerText, curXmlMemberIndex, 0);
        arrXmlMemberArray.SetValue(curXmlNode.Attributes.Item(MEMBER_HASSUBMEMBER).Value, curXmlMemberIndex, MEMBER_HASSUBMEMBER+1);
        arrXmlMemberArray.SetValue(curXmlNode.Attributes.Item(MEMBER_ISSPECIALMEMBER).Value, curXmlMemberIndex, MEMBER_ISSPECIALMEMBER+1);
        
        if(curXmlNode.Attributes.Item(MEMBER_ISSPECIALMEMBER).Value.ToUpper() == "TRUE")
        {
          arrXmlMemberArray.SetValue(RTF_PREFIX_COLOR_CODE + curXmlNode.Attributes.Item(MEMBER_COLORNUMBER).Value, curXmlMemberIndex, MEMBER_COLORNUMBER+1);
          arrXmlMemberArray.SetValue(GetFontStyleFromString(curXmlNode.Attributes.Item(MEMBER_FONTSTYLE).Value), curXmlMemberIndex, MEMBER_FONTSTYLE+1);
          arrXmlMemberArray.SetValue(curXmlNode.Attributes.Item(MEMBER_ENDINGSTRING).Value, curXmlMemberIndex, MEMBER_ENDINGSTRING+1);
          arrXmlMemberArray.SetValue(curXmlNode.Attributes.Item(MEMBER_MEMBERCOLORED).Value, curXmlMemberIndex, MEMBER_MEMBERCOLORED+1);
        }
        else
        {
          arrXmlMemberArray.SetValue(null, curXmlMemberIndex, MEMBER_COLORNUMBER+1);
          arrXmlMemberArray.SetValue(null, curXmlMemberIndex, MEMBER_FONTSTYLE+1);
          arrXmlMemberArray.SetValue(null, curXmlMemberIndex, MEMBER_ENDINGSTRING+1);
          arrXmlMemberArray.SetValue(null, curXmlMemberIndex, MEMBER_MEMBERCOLORED+1);
        }
        curXmlMemberIndex++;
      }

      return arrXmlMemberArray;
    }

    private ArrayList GetXmlSubMemberArray(XmlNodeList xmlSubMemberNodeList)
    {
      ArrayList arrXmlSubMemberArray = new ArrayList();

      foreach(XmlNode curXmlNode in xmlSubMemberNodeList)
        arrXmlSubMemberArray.Add(curXmlNode.InnerText);

      return arrXmlSubMemberArray;
    }

    private string GetRTFColorFromXML(string curColor)
    {
      string rtfColor = "";
      string[] colorsPairValue;
      string[] colorPairValue;
      string[] arrRGBColorNames = {"red", "green", "blue"};
      int curColorNameIndex = 0;

      colorsPairValue = curColor.Split(';');

      foreach(string el in colorsPairValue)
      {
        colorPairValue = el.Split(':');
            
        if(colorPairValue.Length == 2)
        {
          if(Utilities.IsNumeric(colorPairValue[1]))
          {
            rtfColor += RTF_PREFIX_SLASH + arrRGBColorNames[curColorNameIndex] + Convert.ToString(colorPairValue[1]);
          }
          else
          {
            // If it's not a number there is an error and we take the decision 
            // to make the current RGB color neutral with 0
            rtfColor += RTF_PREFIX_SLASH + arrRGBColorNames[curColorNameIndex] + "0";
          }
        }
        else
        {
          // If it's beyond two there is an error and we take the decision 
          // to make the current RGB color neutral with 0
          rtfColor += RTF_PREFIX_SLASH + arrRGBColorNames[curColorNameIndex] + "0";
        }

        curColorNameIndex++;
      }

      rtfColor += ";";

      return rtfColor;
    }

    private string GetFontStyleFromString(string fontStyleValue)
    {
      string retFontStyle = RTF_FONT_REGULAR;

      switch(fontStyleValue.ToUpper().Trim())
      {
        case "REGULAR":  retFontStyle = RTF_FONT_REGULAR;
                break;

        case "BOLD":  retFontStyle = RTF_FONT_BOLD;
                break;

        case "ITALIC":  retFontStyle = RTF_FONT_ITALIC;
                break;

        default:    retFontStyle = RTF_FONT_REGULAR;
                break;
      }

      return retFontStyle;
    }

    private bool doesBelongToNodeList(string[,] arrCurXmlMemberList, string wordToCompare, out bool hasSubMember, out bool isSpecialMember, out string memberColor, out string memberFontStyle, out string memberEndingString, out bool isMemberColored)
    {
      bool belongsTo = false;
      hasSubMember = false;
      isSpecialMember = false;
      memberColor = null;
      memberFontStyle = null;
      memberEndingString = null;
      isMemberColored = false;

      for(int curXmlMemberIndex=0; curXmlMemberIndex<arrCurXmlMemberList.GetUpperBound(0); curXmlMemberIndex++)
      {
        if(arrCurXmlMemberList[curXmlMemberIndex,0] == wordToCompare.ToUpper())
        {
          belongsTo = true;
          hasSubMember = Convert.ToBoolean(arrCurXmlMemberList[curXmlMemberIndex, MEMBER_HASSUBMEMBER+1]);
          isSpecialMember = Convert.ToBoolean(arrCurXmlMemberList[curXmlMemberIndex, MEMBER_ISSPECIALMEMBER+1]);
          memberColor = arrCurXmlMemberList[curXmlMemberIndex, MEMBER_COLORNUMBER+1];
          memberFontStyle = arrCurXmlMemberList[curXmlMemberIndex, MEMBER_FONTSTYLE+1];
          memberEndingString = arrCurXmlMemberList[curXmlMemberIndex, MEMBER_ENDINGSTRING+1];
          isMemberColored = Convert.ToBoolean(arrCurXmlMemberList[curXmlMemberIndex, MEMBER_MEMBERCOLORED+1]);
          break;
        }
      }

      return belongsTo;
    }

    private bool doesBelongToNodeList(string[,] arrCurXmlMemberList, string wordToCompare)
    {
      bool belongsTo = false;

      for(int curXmlMemberIndex=0; curXmlMemberIndex<arrCurXmlMemberList.GetUpperBound(0); curXmlMemberIndex++)
      {
        if(arrCurXmlMemberList[curXmlMemberIndex,0] == wordToCompare.ToUpper())
        {
          belongsTo = true;
          break;
        }
      }

      return belongsTo;
    }

    private bool doesBelongToNodeList(ArrayList arrCurXmlMemberList, string wordToCompare)
    {
      bool belongsTo = false;

      for(int curXmlMemberIndex=0; curXmlMemberIndex<arrCurXmlMemberList.Count; curXmlMemberIndex++)
      {
        if(arrCurXmlMemberList.Contains(wordToCompare.ToUpper()))
        {
          belongsTo = true;
          break;
        }
      }

      return belongsTo;
    }

    // To optimize the RTF processing in avoiding to add unecessary RTF tags
    private string ChangeFontState(ref RTFFontState curFontState, string color, bool isItalic, bool isBold, bool isRegular)
    {
      string newFontState = "";

      if(curFontState.Color != color && color != null)
      {
        newFontState = color;
        curFontState.Color = color;
      }

      if(curFontState.IsRegular != isRegular)
      {
        // If it was regular and it's no more regular we don't care since it's not a real state anyways
        if(isRegular)
        {
          if(curFontState.IsBold)
            newFontState += RTF_FONT_UNBOLD;
          if(curFontState.IsItalic)
            newFontState += RTF_FONT_UNITALIC;

          curFontState.IsRegular = true;
        }
        else
          curFontState.IsRegular = false;
      }
      
      // If it is regular all the settings will be set by itself in the object
      if(!isRegular)
      {
        if(curFontState.IsBold != isBold)
        {
          newFontState += isBold ? RTF_FONT_BOLD : RTF_FONT_UNBOLD;
          curFontState.IsBold = isBold;
        }
        if(curFontState.IsItalic != isItalic)
        {
          newFontState += isItalic ? RTF_FONT_ITALIC : RTF_FONT_UNITALIC;
          curFontState.IsItalic = isItalic;
        }
      }

      if(newFontState != "")
        newFontState += " ";

      return newFontState;
    }

    private string ChangeFontState(ref RTFFontState curFontState, string color, string fontStyle) 
    {
      string newFontState = "";
      bool isItalic = false;
      bool isBold = false;
      bool isRegular = false;
        
      if(fontStyle == RTF_FONT_BOLD)
        isBold = true;
      else if(fontStyle == RTF_FONT_ITALIC)
        isItalic = true;
      else if(fontStyle == RTF_FONT_REGULAR)
        isRegular = true;

      newFontState = ChangeFontState(ref curFontState, color, isItalic, isBold, isRegular);

      return newFontState;
    }

    private string ChangeColorTable(string rtfText, string colorTable)
    {
      // We omitted the prefix {/ in case that there is some extra before,
      // in any cases it's better to search directly for the right word
      int colorTblStartIndex = rtfText.ToUpper().IndexOf("COLORTBL");
      int colorTablEndIndex = -1;
      int rtfHeaderStartIndex = -1;
      int locationToInsert = -1;
      string modifiedRtfText = "";

      if(colorTblStartIndex != -1)
      {
        colorTablEndIndex = rtfText.IndexOf("}", colorTblStartIndex);

        // Now we have the exact position we remove it
        rtfText = rtfText.Remove(colorTblStartIndex, colorTablEndIndex - colorTblStartIndex);

        // We reinsert the new color table at the right index
        modifiedRtfText = rtfText.Insert(colorTblStartIndex, colorTable);
      }
      else // No existing color table, we need to create it from scratch
      {
        // find index of start of header
        rtfHeaderStartIndex = rtfText.ToUpper().IndexOf("\\RTF");
        
        // Since we can insert the color table anywhere inside the RTF header we try
        // to find the first property to insert it before
        locationToInsert = rtfText.IndexOf("{", rtfHeaderStartIndex);

        // In case there are no properties we insert it before the RTF header closes
        if(locationToInsert == -1) locationToInsert = rtfText.IndexOf("}", locationToInsert) - 1;
            
        modifiedRtfText = rtfText.Insert(locationToInsert, "{\\" + colorTable + RTF_ENDING_COLOR_TABLE_STRING);
      }

      return modifiedRtfText;
    }
  }
}
www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.