Listing of Source ../source/GOF/GofComboBoxIdentifier.java
package se.entra.phantom.server;

import java.util.StringTokenizer;
import java.util.Vector;

/**
 * This class identifies combination box controls for the Gui-on-the-fly, from unused GofHostFields.
 * @author J. Bergström
 */
public class GofComboBoxIdentifier extends GofControlIdentifierAdapter implements PhantomControlType
{
  // ------------------
  // INSTANCE VARIABLES
  // ------------------

  /**
   * The start indicator for a list of alternativs.
   * <p>
   * Defaults to "(".
   */
  private String comboListStart = "(";

  /**
   * The end indicator for a list of alternativs.
   * <p>
   * Defaults to ")".
   */
  private String comboListEnd = ")";

  /**
   * The separator between the alternativs in the list.
   * <p>
   * Defaults to "/".
   */
  private String comboListSep = "/";

  /**
   * Flag indicating where to search for the combolist, and in what order if multiple search.
   * <p>
   * The following values are valid:
   * <pre>
   *   0  Do not search for combolist.
   *   1  Only search the preceding lead text.
   *   2  Only search the trailing lead text.
   *   3  First search the preceding, then the trailing lead text.
   *   4  First search the trailing, then the preceding lead text.
   * </pre>
   */
  private int combosearch = 0;

  /**
   * Flag indicating if host field text not in the drop down list should be added to the list.
   * If not, then the combination list will be editable if the host field text is not in the list.
   * <p>
   * Defaults to <code>false</code>.
   */
  private boolean doAddMissingTextToList = false;

  /**
   * Filler character if there is one. Will be <coed>null</code> otherwise.
   */
  private String comboFieldFiller;

  /**
   * Indicates the way the check box's layout will be created.
   * Valid values are:
   * <pre>
   *    DEFAULT
   *    FONT
   *    COLOR
   *    FONTANDCOLOR
   * </pre>
   */
  private String layout;
  
  /**
   * Flag indicating if we should always use an editable or un-editable combination box.
   * Defaults to un-editable.
   */
  private boolean isAlwaysEditable = false;

  // ----------------
  // INSTANCE METHODS
  // ----------------

  /**
   * Loads setting for the control from the server ini-file.
   * <p>
   * For the identification of combination boxes, the following settings are used:
   * <pre>
   *   comboliststart       The start indicator for a list of alternatives.
   *   combolistend         The end indicator for a list of alternatives.
   *   combolistsep         The separator between the alternatives in the list.
   * </pre>
   * <p>
   * There are also several possibilities of where the combolist can be placed
   * relative to the entry field that will be replaced by the combination box.
   * The list can either be in the preceding lead text or in the lead text following.
   * <p>
   * The setting <code>combolistsearch</code> will tell this class where to look for
   * the combolist, and in what order to search if multiple places are to be searched.
   * <p>
   * Valid values are:
   * <pre>
   *   pre    Search the preceding leadtext.
   *   post   Search the trailing leadtext.
   * </pre>
   * <p>
   * To handle situations where the original text in the host field is not part of the
   * drop down list, the setting <code>comboaddmissingtext</code> is used.
   * <p>
   * Valid setting for this setting is 0 or 1. 0 means that the original text should not
   * be added to the list. In this case the combination box will be created as an editable
   * combination box. 1 means that the text should be added to the list. Default is 0.
   * <p>
   * It is also possible to force the spin button to always be created as an editable
   * spin button. This is specified in the spinalwayseditable setting.
   * <pre>
   *    comboalwayseditable=1
   * </pre>
   * There is also a setting that specifies if there is a filler character to use, and what 
   * character this should be. This setting as called combofieldfiller, and if the filler 
   * character is the underscore character, it would look like this:
   * <pre>
   *    combofieldfiller=_
   * </pre>
   * This class also uses a setting that affects the look of the combination boxes. This 
   * is the combolayout setting. Valid values for this setting are:
   * <pre>
   *    combolayout=DEFAULT
   *    combolayout =FONT
   *    combolayout =COLOR
   *    combolayout =FONTANDCOLOR
   * </pre>
   * DEFAULT means that no settings are taken from the template panel; default values will be 
   * used instead. 
   * <p>
   * FONT means that the font is taken from template panel, from a combination box with the 
   * id=CMB or CMBE (CMB is for non-editable combination boxes, CMBE is for editable combination 
   * boxes). If this control cannot be found, or if it is not a combination box control, default 
   * values will be used.
   * <p>
   * COLOR means that the color is taken from template panel, from a combination box with the 
   * id=CMB or CMBE (CMB is for non-editable combination boxes, CMBE is for editable combination 
   * boxes). If this control cannot be found, or if it is not a combination box control, default 
   * values will be used.
   * <p>
   * FONTANDCOLOR means that the font and color are taken from template panel, from a combination 
   * box with the id= CMB or CMBE (CMB is for non-editable combination boxes, CMBE is for editable 
   * combination boxes). If this control cannot be found, or if it is not a combination box control, 
   * default values will be used.,
   * <p>
   * Any other value will be treated as DEFAULT.
   * @param confFile The server ini file.
   */
  @Override
  public void getControlSettings( IniFile confFile, String subsection )
  {
    String setting;
    setting = confFile.getData( subsection, "comboliststart" );
    if( setting != null )
      comboListStart = setting;
    setting = confFile.getData( subsection, "combolistend" );
    if( setting != null )
      comboListEnd = setting;
    setting = confFile.getData( subsection, "combolistsep" );
    if( setting != null )
      comboListSep = setting;

    setting = confFile.getData( subsection, "combosearch" );
    combosearch = parseCombosearch( setting );

    setting = confFile.getData( subsection, "comboaddmissingtext" );
    if( setting != null )
    {
      if( setting.equals( "1" ) )
        doAddMissingTextToList = true;
    }

    setting = confFile.getData( subsection, "combofieldfiller" );
    if( setting != null && setting.equals( "" ) == false )
      comboFieldFiller = setting;
    else
      comboFieldFiller = null;

    layout = confFile.getData( subsection, "combolayout" );
    if( layout == null )
      layout = "DEFAULT";
    
    setting = confFile.getData( subsection, "comboalwayseditable" );
    if( setting != null )
    {
      if( setting.equals( "1" ) == true )
        isAlwaysEditable = true;
    }
  }

  /**
   * Identifies all the combination box controls from the <code>GofHostFields</code>.
   * <p>
   * The identification of combination boxes are done by searching for a lead text that 
   * indicates an entry field that could be replaced by a combination box. A lead text 
   * indicating a combination box should have a start indicator, an end indicator and 
   * two or more values separated by a separator. The start indicator is usually a start 
   * parenthesis, the end indicator is usually an end parenthesis, and the separator is 
   * usually a slash. But these are configurable in the configuration file.
   * <p>
   * After a lead text has been identified to hold a combination box indicator, it checks 
   * if the next or previous field is an entry field, and that it is on the same line. There 
   * is a configuration that determines if the lead text should be before the entry field, 
   * or after, or if both are accepted, and if so, in which order to search.
   * @param gofRuntime        The GuiOnTheFlyRuntime instance.
   * @param areaIdentifier    The areaIdentifier in which the controls should be identified.
   * @param phantomHostScreen The Phantom host screen corresponding to the host screen.
   * @param hostScreen        The host screen that we are trying to build a GOF panel for.
   * @param newPanel          The newly created Gui-on-the-fly runtime panel.
   * @param offsetX           Offset in columns used for popup windows.
   * @param offsetY           Offset in lines used for popup windows.
   */
  @Override
  public void identifyCtrls( GuiOnTheFlyRuntime gofRuntime,
                             GofHostAreaIdentifier areaIdentifier, 
                             PhantomHostScreen phantomHostScreen, 
                             HostScreen hostScreen,
                             PhantomPanelData templPanel, 
                             PhantomPanelData newPanel,
                             int offsetX,
                             int offsetY )
  {
    this.templPanel = templPanel;

    Vector<GofHostField> gofHostFields = areaIdentifier.getAreasGofHostFields( );
    Vector<String> cmbList = new Vector<String>( );

    for( int i = 0, s = gofHostFields.size( ); i < s; i++ )
    {
      GofHostField gofHostField = gofHostFields.elementAt( i );
      if( gofHostField.hasBeenProcessed == false && gofHostField.isProtected( ) == true && gofHostField.isEmpty( ) == false )
      {
        String text = gofHostField.getText( );
        int sp = text.indexOf( comboListStart );
        int ep = text.indexOf( comboListEnd, sp + 1 );
        if( sp > -1 && ep > -1 )
        {
          String cmbtext = text.substring( sp + 1, ep );
          int oldseppos = -1;
          int seppos = cmbtext.indexOf( comboListSep );
          while( seppos > -1 )
          {
            String item = cmbtext.substring( oldseppos + 1, seppos );
            cmbList.addElement( item );
            oldseppos = seppos;
            seppos = cmbtext.indexOf( comboListSep, oldseppos + 1 );
            if( seppos == -1 )
            {
              item = cmbtext.substring( oldseppos + 1 );
              cmbList.addElement( item );
            }
          }

          if( cmbList.size( ) > 0 )
          {
            boolean wasFound;
            boolean doLoop = true;
            int curComboSearch = combosearch;
            int j = 0;
            while( doLoop )
            {
              switch( curComboSearch )
              {
                case 1:
                case 3:
                  j++;
                  break;
                case 2:
                case 4:
                  j--;
                  break;
                default:
                  doLoop = false;
              }
              
              int curElement = i + j;
              if( gofHostFields.size( ) > curElement && curElement > 0 )
              {
                GofHostField nxtGofHostField = gofHostFields.elementAt( curElement );
                if( gofHostField.getY( ) == nxtGofHostField.getY( ) )
                {
                  if( nxtGofHostField.isProtected( ) == false && nxtGofHostField.isEmpty( ) == false )
                  {
                    wasFound = convertFieldToCombo( cmbList, 
                                                    nxtGofHostField, 
                                                    areaIdentifier, 
                                                    phantomHostScreen, 
                                                    hostScreen, 
                                                    newPanel, 
                                                    offsetX, 
                                                    offsetY );
                    if( wasFound == true )
                      doLoop = false;
                    else
                    {
                      switch( curComboSearch )
                      {
                        case 3:
                          j = 0;
                          curComboSearch = 2;
                          break;
                        case 4:
                          j = 0;
                          curComboSearch = 1;
                          break;
                        default:
                          doLoop = false;
                      }
                    }
                  }
                  else
                  {
                    switch( curComboSearch )
                    {
                      case 3:
                        j = 0;
                        curComboSearch = 2;
                        break;
                      case 4:
                        j = 0;
                        curComboSearch = 1;
                        break;
                    }
                  }
                }
                else
                {
                  switch( curComboSearch )
                  {
                    case 3:
                      j = 0;
                      curComboSearch = 2;
                      break;
                    case 4:
                      j = 0;
                      curComboSearch = 1;
                      break;
                    default:
                      doLoop = false;
                  }
                }
              }
              else
                doLoop = false;
            }
          }
          cmbList = new Vector<String>( );
        }
      }
    }
  }

  /**
   * Parses the combosearch setting, and converts into a flag value.
   * @param setting The setting from the server.ini file.
   * @return The value for the combosearch flag.
   */
  private int parseCombosearch( String setting )
  {
    if( setting == null || setting.equals( "" ) )
      return 0;

    int flag = 0;
    StringTokenizer st = new StringTokenizer( setting, ", " );
    while( st.hasMoreTokens( ) )
    {
      String s = st.nextToken( );
      switch( flag )
      {
        case 1:
          if( s.equals( "pre" ) )
            flag = 1;
          else if( s.equals( "post" ) )
            flag = 3;
          break;
        case 2:
          if( s.equals( "pre" ) )
            flag = 4;
          else if( s.equals( "post" ) )
            flag = 2;
          break;
        default:
          if( s.equals( "pre" ) )
            flag = 1;
          else if( s.equals( "post" ) )
            flag = 2;
      }
    }
    return flag;
  }

  /**
   * Tries to convert an entry field to a combination box.
   * <p>
   * Before the creation of the PhantomCComboBox, a check will be done to see if the text in the host field
   * is included in the list.
   * @param areaIdentifier    The areaIdentifier in which the controls should be identified.
   * @param phantomHostScreen The Phantom host screen corresponding to the host screen.
   * @param hostScreen        The host screen that we are trying to build a GOF panel for.
   * @param newPanel          The newly created Gui-on-the-fly runtime panel.
   * @param offsetX           Offset in columns used for popup windows.
   * @param offsetY           Offset in lines used for popup windows.
   * @return <code>true</code> if the GofHostField was converted to a combination box,
   *         <code>false</code> otherwise.
   */
  private boolean convertFieldToCombo( Vector<String> cmbList, 
                                       GofHostField gofHostField,
                                       GofHostAreaIdentifier areaIdentifier, 
                                       PhantomHostScreen phantomHostScreen, 
                                       HostScreen hostScreen, 
                                       PhantomPanelData newPanel,
                                       int offsetX,
                                       int offsetY )
  {
    // Get the width of the widest string in the list.

    int maxWidth = 0;
    for( int i = 0, s = cmbList.size( ); i < s; i++ )
    {
      String listElement = cmbList.elementAt( i );
      if( listElement.length( ) > maxWidth )
        maxWidth = listElement.length( );
    }

    if( gofHostField.hasBeenProcessed == false && 
        gofHostField.isProtected( ) == false && 
        gofHostField.isEmpty( ) == false &&
        gofHostField.getCx( ) >= maxWidth )
    {
      HostField hf = gofHostField.getHostField( );

      int x = gofHostField.getX( );
      int y = gofHostField.getY( );
      int cx = gofHostField.getCx( );
      int cy = cmbList.size( ) + 1;
      String orgtext = gofHostField.getText( );

      boolean isInList = isTextInList( orgtext, cmbList );
      boolean isUneditable = true;
      
      if( isAlwaysEditable == true )
      {
        isUneditable = false;
      }
      else
      {
        if( isInList == false )
        {
          if( doAddMissingTextToList == true )
            cmbList.insertElementAt( orgtext, 0 );
          else
            isUneditable = false;
        }
      }

      // Get template values

      int font = -1;
      int foregroundColor = -1;
      PhantomControl templateControl = null;
      if( isUneditable == true )
        templateControl = templPanel.getControlFromID( "CMB" );
      else
        templateControl = templPanel.getControlFromID( "CMBE" );

      if( layout.equals( "FONT" ) )
      {
        if( templateControl != null && templateControl.controlBase.type == CTRLTYPE_COMBO )
          font = ( ( PhantomCComboBox )templateControl ).font;
      }
      else if( layout.equals( "COLOR" ) )
      {
        if( templateControl != null && templateControl.controlBase.type == CTRLTYPE_COMBO )
          foregroundColor = ( ( PhantomCComboBox )templateControl ).getForegroundColor();
      }
      else if( layout.equals( "FONTANDCOLOR" ) )
      {
        if( templateControl != null && templateControl.controlBase.type == CTRLTYPE_COMBO )
        {
          font = ( ( PhantomCComboBox )templateControl ).font;
          foregroundColor = ( ( PhantomCComboBox )templateControl ).getForegroundColor();
        }
      }

      // Create the base control.

      PhantomControlBase bc = new PhantomControlBase( GOF_MARGINX + ( x - offsetX ) * GOF_STEPX - 1,
                                                      GOF_MARGINY + ( y - offsetY ) * GOF_STEPY - 1,
                                                      cx * GOF_GUIUNITX + 15,
                                                      GOF_GUIUNITY * cy + 20,
                                                      CTRLTYPE_COMBO );

      // Create the PhantomHostField.

      PhantomHostField phf = new PhantomHostField( phantomHostScreen, hostScreen, hf );
      if( comboFieldFiller != null )
      {
        phf.filler = comboFieldFiller.charAt( 0 );
        phf.flags = PhantomHostField.FORMAT_STRIPEND;
      }
      phantomHostScreen.addHostField( phf );

      // Create the entry field.

      PhantomCComboBox cb = new PhantomCComboBox( newPanel, bc, phf, cmbList, isUneditable );
      cb.font = font;
      cb.setForegroundColor(foregroundColor);

      // Add the entry field.

      newPanel.addControl( cb );
      areaIdentifier.addControl( cb );
      gofHostField.hasBeenProcessed = true;
      return true;
    }
    return false;
  }

  /**
   * Checks if a String is in a list.
   * @param text  The String to check.
   * @param list  The list to search in.
   * @return <code>true</code> if the String was found in the list,
   *         <code>false</code> otherwise.
   */
  private boolean isTextInList( String text, Vector<String> list )
  {
    if( text == null || list == null )
      return false;

    for( int i = 0, s = list.size( ); i < s; i++ )
    {
      String item = list.elementAt( i );
      if( item.equals( text ) )
        return true;
    }
    return false;
  }
}