protected Control createDialogArea(Composite parent) {
    UIUtil.bindHelp(parent, IHelpContextIds.XTAB_SHOW_SUMMARY_FIELD_DIALOG);

    Composite dialogArea = (Composite) super.createDialogArea(parent);

    Label infoLabel = new Label(dialogArea, SWT.NONE);
    infoLabel.setText(Messages.getString("ShowSummaryFieldDialog.Label.Info")); // $NON-NLS-1$

    createSummaryFiledViewer(dialogArea);

    init();

    return dialogArea;
  }
  private void initializeItems(MeasureInfo measureInfo) {
    List<String> viewNameList = new ArrayList<String>();
    List<String> itemList = new ArrayList<String>();

    MeasureViewHandle measureView = crosstab.getMeasure(measureInfo.getMeasureName());
    if (measureView != null && measureView instanceof ComputedMeasureViewHandle) {
      itemList.add("");
      viewNameList.add(""); // $NON-NLS-1$
    } else
    // NOT ComputedMeasureViewHandle -- begin --
    {
      AggregationCellHandle cell = getAggregationCell(measureInfo);
      if (cell != null && cellProviderWrapper.getMatchProvider(cell) == null) {
        itemList.add("");
        viewNameList.add(""); // $NON-NLS-1$
      }

      IAggregationCellViewProvider providers[] = cellProviderWrapper.getAllProviders();
      for (int i = 0; i < providers.length; i++) {
        IAggregationCellViewProvider tmp = (IAggregationCellViewProvider) providers[i];
        if (tmp == null) {
          continue;
        }
        SwitchCellInfo info = new SwitchCellInfo(crosstab, SwitchCellInfo.MEASURE);
        info.setMeasureInfo(measureInfo);

        if (!providers[i].canSwitch(info)) {
          continue;
        }

        String displayName = tmp.getViewDisplayName();
        viewNameList.add(tmp.getViewName());
        itemList.add(
            Messages.getString(
                "GrandTotalProvider.ShowAs", //$NON-NLS-1$
                new String[] {displayName}));
      }
    } // NOT ComputedMeasureViewHandle -- end --
    comboItems = (String[]) itemList.toArray(new String[itemList.size()]);
    viewNames = (String[]) viewNameList.toArray(new String[viewNameList.size()]);
  }
 public ShowSummaryFieldDialog(Shell parentShell, CrosstabReportItemHandle crosstab) {
   super(parentShell, Messages.getString("ShowSummaryFieldDialog.Title")); // $NON-NLS-1$
   setCrosstab(crosstab);
 }
public class ShowSummaryFieldDialog extends BaseDialog {

  private String[] columnNames =
      new String[] {
        Messages.getString("ShowSummaryFieldDialog.Column.Measures"), // $NON-NLS-1$
        Messages.getString("ShowSummaryFieldDialog.Column.View")
      }; //$NON-NLS-1$
  private int[] columnWidth = new int[] {230, 130};
  private CellEditor[] cellEditor;

  private String[] comboItems = null;
  // private IAggregationCellViewProvider[] providers;
  private String[] viewNames;

  private CrosstabReportItemHandle crosstab;
  private AggregationCellProviderWrapper cellProviderWrapper;

  private void setCrosstab(CrosstabReportItemHandle crosstab) {
    this.crosstab = crosstab;
    cellProviderWrapper = new AggregationCellProviderWrapper(crosstab);
  }

  public ShowSummaryFieldDialog(Shell parentShell, CrosstabReportItemHandle crosstab) {
    super(parentShell, Messages.getString("ShowSummaryFieldDialog.Title")); // $NON-NLS-1$
    setCrosstab(crosstab);
  }

  protected Control createDialogArea(Composite parent) {
    UIUtil.bindHelp(parent, IHelpContextIds.XTAB_SHOW_SUMMARY_FIELD_DIALOG);

    Composite dialogArea = (Composite) super.createDialogArea(parent);

    Label infoLabel = new Label(dialogArea, SWT.NONE);
    infoLabel.setText(Messages.getString("ShowSummaryFieldDialog.Label.Info")); // $NON-NLS-1$

    createSummaryFiledViewer(dialogArea);

    init();

    return dialogArea;
  }

  private List input = new ArrayList();
  private CheckboxTableViewer summaryFieldViewer;

  public void setInput(List input) {
    if (input != null) this.input.addAll(input);
  }

  private ICellModifier cellModifier =
      new ICellModifier() {

        public boolean canModify(Object element, String property) {
          // TODO Auto-generated method stub
          if (element instanceof Item) {
            element = ((Item) element).getData();
          }
          MeasureInfo info = (MeasureInfo) element;
          MeasureViewHandle measureView = crosstab.getMeasure(info.getMeasureName());
          if (measureView == null
              || measureView instanceof ComputedMeasureViewHandle
              || (measureView.getCubeMeasure() != null
                  && measureView.getCubeMeasure().isCalculated())) {
            return false;
          }

          if (Arrays.asList(columnNames).indexOf(property) == 1) {
            return summaryFieldViewer.getChecked(element);
          } else {
            return false;
          }
        }

        public Object getValue(Object element, String property) {
          if (element instanceof Item) {
            element = ((Item) element).getData();
          }
          Object value = null;
          // TODO Auto-generated method stub
          int index = Arrays.asList(columnNames).indexOf(property);
          switch (index) {
            case 0:
              value = "Measure"; // $NON-NLS-1$
              break;
            case 1:
              initializeItems((MeasureInfo) element);
              ((ComboBoxCellEditor) cellEditor[1]).setItems(comboItems);
              String expectedView = ((MeasureInfo) (element)).getExpectedView();
              if (expectedView == null) {
                expectedView = "";
              }
              int sel = Arrays.asList(viewNames).indexOf(expectedView);
              value = sel <= 0 ? Integer.valueOf(0) : Integer.valueOf(sel);
              break;
            default:
          }
          return value;
        }

        public void modify(Object element, String property, Object value) {
          // TODO Auto-generated method stub

          if (element instanceof Item) {
            element = ((Item) element).getData();
          }

          int index = Arrays.asList(columnNames).indexOf(property);
          switch (index) {
            case 0:
              break;
            case 1:
              int sel = ((Integer) value).intValue();
              if (sel < 0) {
                ((MeasureInfo) (element)).setExpectedView(""); // $NON-NLS-1$
              } else {
                ((MeasureInfo) element).setExpectedView(viewNames[sel]);
              }
              break;
            default:
          }
          summaryFieldViewer.refresh();
        }
      };

  private void createSummaryFiledViewer(Composite dialogArea) {
    Table table =
        new Table(
            dialogArea,
            SWT.BORDER | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.CHECK);
    table.setLinesVisible(true);
    table.setHeaderVisible(true);

    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.heightHint = 250;
    table.setLayoutData(gd);

    summaryFieldViewer = new CheckboxTableViewer(table);
    SummaryFieldProvider provider = new SummaryFieldProvider();

    for (int i = 0; i < columnNames.length; i++) {
      TableColumn column = new TableColumn(table, SWT.LEFT);
      column.setText(columnNames[i]);
      column.setWidth(columnWidth[i]);
    }
    ComboBoxCellEditor comboCell = new ComboBoxCellEditor(table, new String[0], SWT.READ_ONLY);
    // TextCellEditor textCell = new TextCellEditor(table, SWT.NONE);
    cellEditor = new CellEditor[] {null, comboCell};
    summaryFieldViewer.setColumnProperties(columnNames);
    summaryFieldViewer.setCellEditors(cellEditor);
    summaryFieldViewer.setCellModifier(cellModifier);
    summaryFieldViewer.setUseHashlookup(true);
    summaryFieldViewer.setContentProvider(provider);
    summaryFieldViewer.setLabelProvider(provider);

    summaryFieldViewer.addCheckStateListener(
        new ICheckStateListener() {

          public void checkStateChanged(CheckStateChangedEvent event) {
            MeasureInfo info = (MeasureInfo) event.getElement();
            if (event.getChecked()) {
              info.setShow(true);
            } else {
              info.setShow(false);
            }
            checkOKButtonStatus();
          }
        });
  }

  private void init() {
    if (input != null) {
      summaryFieldViewer.setInput(input);
      for (int i = 0; i < summaryFieldViewer.getTable().getItemCount(); i++) {
        TableItem item = summaryFieldViewer.getTable().getItem(i);
        if (item.getData() != null && item.getData() instanceof MeasureInfo) {
          item.setChecked(((MeasureInfo) item.getData()).isShow());
        }
      }
    }
  }

  public Object getResult() {
    return input;
  }

  private void checkOKButtonStatus() {
    int count = 0;
    int listSize = input.size();
    for (int i = 0; i < listSize; i++) {
      MeasureInfo measureInfo = (MeasureInfo) input.get(i);
      if (measureInfo.isShow()) {
        count++;
      }
    }
    if (count <= 0 && getOkButton() != null) {
      getOkButton().setEnabled(false);
    } else if (getOkButton() != null) {
      getOkButton().setEnabled(true);
    }
  }

  class SummaryFieldProvider extends LabelProvider
      implements ITableLabelProvider, IStructuredContentProvider {

    public Image getColumnImage(Object element, int columnIndex) {
      Image image = null;
      switch (columnIndex) {
        case 0:
          image = CrosstabUIHelper.getImage(CrosstabUIHelper.MEASURE_IMAGE);
          break;
        case 1:
          break;
        default:
      }
      return image;
    }

    public String getColumnText(Object element, int columnIndex) {
      if (element instanceof MeasureInfo) {
        if (columnIndex == 0) {
          return ((MeasureInfo) element).getMeasureDisplayName() == null
              ? "" //$NON-NLS-1$
              : ((MeasureInfo) element).getMeasureDisplayName();
        } else {
          initializeItems((MeasureInfo) element);
          ((ComboBoxCellEditor) cellEditor[1]).setItems(comboItems);

          String expectedView = ((MeasureInfo) element).getExpectedView();
          if (expectedView == null) {
            return comboItems[0];
          } else {
            int index = Arrays.asList(viewNames).indexOf(expectedView);
            if (index < 0) {
              index = 0;
              ((MeasureInfo) element).setExpectedView(viewNames[index]);
            }
            return comboItems[index];
          }
        }
      }

      return ""; //$NON-NLS-1$
    }

    public Object[] getElements(Object inputElement) {
      if (inputElement instanceof List) return ((List) inputElement).toArray();
      return new Object[0];
    }

    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      // TODO Auto-generated method stub

    }
  }

  /** MeasureInfo */
  public static class MeasureInfo {

    // private MeasureHandle measure ;
    private String measureName = "";
    private String measureDisplayName = "";

    private boolean isShow = false;

    private String expectedView = ""; // $NON-NLS-1$

    public MeasureInfo copy() {
      MeasureInfo retValue = new MeasureInfo();
      retValue.setShow(isShow());
      retValue.setMeasureName(getMeasureName());
      retValue.setMeasureDisplayName(getMeasureDisplayName());
      retValue.setExpectedView(expectedView);
      return retValue;
    }

    public boolean isSameInfo(MeasureInfo comparedOne) {
      if (comparedOne.measureName.equals(this.measureName)) {
        return true;
      } else {
        return false;
      }
    }

    public void setExpectedView(String view) {
      this.expectedView = view;
    }

    public String getExpectedView() {
      return this.expectedView;
    }

    public void setShow(boolean show) {
      isShow = show;
    }

    public boolean isShow() {
      return isShow;
    }

    // public MeasureHandle getMeasure( )
    // {
    // return measure;
    // }
    //
    // public void setMeasure( MeasureHandle measure )
    // {
    // this.measure = measure;
    // }

    public String getMeasureName() {
      return measureName;
    }

    public void setMeasureName(String name) {
      measureName = name;
    }

    public String getMeasureDisplayName() {
      return measureDisplayName;
    }

    public void setMeasureDisplayName(String displayName) {
      measureDisplayName = displayName;
    }

    // public boolean isSameInfo( Object obj )
    // {
    // if ( !( obj instanceof MeasureInfo ) )
    // {
    // return false;
    // }
    // MeasureInfo temp = (MeasureInfo) obj;
    // return temp.getMeasure( ) == measure;
    // }

    public boolean equals(Object obj) {
      if (!(obj instanceof MeasureInfo)) {
        return false;
      }
      MeasureInfo temp = (MeasureInfo) obj;
      return temp.getMeasureName().equals(measureName)
          && temp.isShow() == isShow
          && temp.getExpectedView() == expectedView;
    }

    public int hashCode() {
      int hash = 31;
      hash = hash * 31 + measureName.hashCode();
      hash = hash * 31 + (expectedView == null ? 0 : expectedView.hashCode());
      return hash;
    }
  }

  private void initializeItems(MeasureInfo measureInfo) {
    List<String> viewNameList = new ArrayList<String>();
    List<String> itemList = new ArrayList<String>();

    MeasureViewHandle measureView = crosstab.getMeasure(measureInfo.getMeasureName());
    if (measureView != null && measureView instanceof ComputedMeasureViewHandle) {
      itemList.add("");
      viewNameList.add(""); // $NON-NLS-1$
    } else
    // NOT ComputedMeasureViewHandle -- begin --
    {
      AggregationCellHandle cell = getAggregationCell(measureInfo);
      if (cell != null && cellProviderWrapper.getMatchProvider(cell) == null) {
        itemList.add("");
        viewNameList.add(""); // $NON-NLS-1$
      }

      IAggregationCellViewProvider providers[] = cellProviderWrapper.getAllProviders();
      for (int i = 0; i < providers.length; i++) {
        IAggregationCellViewProvider tmp = (IAggregationCellViewProvider) providers[i];
        if (tmp == null) {
          continue;
        }
        SwitchCellInfo info = new SwitchCellInfo(crosstab, SwitchCellInfo.MEASURE);
        info.setMeasureInfo(measureInfo);

        if (!providers[i].canSwitch(info)) {
          continue;
        }

        String displayName = tmp.getViewDisplayName();
        viewNameList.add(tmp.getViewName());
        itemList.add(
            Messages.getString(
                "GrandTotalProvider.ShowAs", //$NON-NLS-1$
                new String[] {displayName}));
      }
    } // NOT ComputedMeasureViewHandle -- end --
    comboItems = (String[]) itemList.toArray(new String[itemList.size()]);
    viewNames = (String[]) viewNameList.toArray(new String[viewNameList.size()]);
  }

  private AggregationCellHandle getAggregationCell(MeasureInfo measureInfo) {
    AggregationCellHandle cell = null;
    // MeasureHandle measure = measureInfo.getMeasure( );
    // if(measure == null)
    // {
    // return cell;
    // }
    MeasureViewHandle measureView = crosstab.getMeasure(measureInfo.getMeasureName());
    if (measureView == null) {
      return cell;
    }

    cell = measureView.getCell();
    return cell;
  }
}
/** Drag the cross cell right border to adjust the coumn width */
public class CrosstabColumnDragTracker extends TableDragGuideTracker {
  private static final String RESIZE_COLUMN_TRANS_LABEL =
      Messages.getString("CrosstabColumnDragTracker.ResizeColumn");
  private static final String PREFIX_LABEL =
      Messages.getString("CrosstabColumnDragTracker.Show.Label");

  /**
   * Constructor
   *
   * @param sourceEditPart
   * @param start
   * @param end
   */
  public CrosstabColumnDragTracker(EditPart sourceEditPart, int start, int end) {
    super(sourceEditPart, start, end);
    setDisabledCursor(Cursors.SIZEWE);
  }

  @Override
  protected Cursor getDefaultCursor() {
    if (isCloneActive()) {
      return Cursors.SIZEWE;
    }
    return super.getDefaultCursor();
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.
   * TableDragGuideTracker#getDragWidth()
   */
  protected Dimension getDragWidth(int start, int end) {
    //		return new Dimension( TableUtil.getMinWidth( getCrosstabTableEditPart( ),
    //				getStart( ) )
    //				- CrosstabTableUtil.caleVisualWidth( getCrosstabTableEditPart( ),
    //						getStart( ) ),
    //				Integer.MAX_VALUE );
    if (isCtrlDown()) {
      return new Dimension(
          TableUtil.getMinWidth(getCrosstabTableEditPart(), getStart())
              - CrosstabTableUtil.caleVisualWidth(getCrosstabTableEditPart(), getStart()),
          Integer.MAX_VALUE);
    } else {
      if (getStart() == getEnd()) {
        return new Dimension(
            TableUtil.getMinWidth(getCrosstabTableEditPart(), getStart())
                - CrosstabTableUtil.caleVisualWidth(getCrosstabTableEditPart(), getStart()),
            Integer.MAX_VALUE);
      }

      return new Dimension(
          TableUtil.getMinWidth(getCrosstabTableEditPart(), getStart())
              - CrosstabTableUtil.caleVisualWidth(getCrosstabTableEditPart(), getStart()),
          CrosstabTableUtil.caleVisualWidth(getCrosstabTableEditPart(), getEnd())
              - TableUtil.getMinWidth(getCrosstabTableEditPart(), getEnd()));
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.
   * TableDragGuideTracker#getMarqueeSelectionRectangle()
   */
  protected Rectangle getMarqueeSelectionRectangle() {
    IFigure figure = getCrosstabTableEditPart().getFigure();
    Insets insets = figure.getInsets();

    int value = getLocation().x - getStartLocation().x;
    value = getTrueValueAbsolute(value);

    Point p = getStartLocation().getCopy();
    figure.translateToAbsolute(p);
    figure.translateToRelative(p);
    Rectangle bounds = figure.getBounds().getCopy();
    figure.translateToAbsolute(bounds);

    return new Rectangle(
        value + p.x, bounds.y + insets.top, 2, bounds.height - (insets.top + insets.bottom));
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.birt.report.designer.internal.ui.editors.schematic.tools.
   * TableDragGuideTracker#resize()
   */
  protected void resize() {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    int value = getMouseTrueValueX();
    part.getCrosstabHandleAdapter()
        .getCrosstabItemHandle()
        .getModuleHandle()
        .getCommandStack()
        .startTrans(RESIZE_COLUMN_TRANS_LABEL);
    if (getStart() != getEnd()) {
      value = getTrueValue(value);
      resizeColumn(getStart(), getEnd(), value);
    } else {
      /** This is the Last Column, resize the whole table. */
      Dimension dimension = getDragWidth();

      if (value < dimension.width) {
        value = dimension.width;
      }

      int with = calculateWidth() + value;

      int startWidth = 0;

      startWidth = CrosstabTableUtil.caleVisualWidth(part, getStart());

      part.getCrosstabHandleAdapter().setWidth(with);

      part.getCrosstabHandleAdapter().setColumnWidth(getStart(), startWidth + value);
    }

    part.getCrosstabHandleAdapter()
        .getCrosstabItemHandle()
        .getModuleHandle()
        .getCommandStack()
        .commit();
  }

  /**
   * Calculates table layout size. For table supports auto layout, the layout size need to be
   * calculated when drawing.
   *
   * @return
   */
  private int calculateWidth() {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();

    int columnCount = part.getColumnCount();
    int samColumnWidth = 0;
    for (int i = 0; i < columnCount; i++) {
      samColumnWidth = samColumnWidth + CrosstabTableUtil.caleVisualWidth(part, i + 1);
    }

    return samColumnWidth;
  }

  private void resizeFixColumn(int value, int start, int end) {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    CrosstabHandleAdapter crosstabAdapter = part.getCrosstabHandleAdapter();

    int startWidth = 0;
    int endWidth = 0;
    startWidth = CrosstabTableUtil.caleVisualWidth(part, start);
    endWidth = CrosstabTableUtil.caleVisualWidth(part, end);

    crosstabAdapter.setColumnWidth(start, startWidth + value);
    if (!isCtrlDown() && start != end) {
      crosstabAdapter.setColumnWidth(end, endWidth - value);
    }
  }

  /**
   * Resets size of column.
   *
   * @param start
   * @param end
   * @param value
   */
  public void resizeColumn(int start, int end, int value) {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    CrosstabHandleAdapter crosstabAdapter = part.getCrosstabHandleAdapter();

    int startWidth = 0;
    int endWidth = 0;

    startWidth = CrosstabTableUtil.caleVisualWidth(part, start);
    endWidth = CrosstabTableUtil.caleVisualWidth(part, end);

    crosstabAdapter.setColumnWidth(start, startWidth + value);
    if (!isCtrlDown() && start != end) {
      crosstabAdapter.setColumnWidth(end, endWidth - value);
    }
  }

  private CrosstabTableEditPart getCrosstabTableEditPart() {
    return (CrosstabTableEditPart) getSourceEditPart().getParent();
  }

  @Override
  protected String getInfomation() {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    return getShowLabel(CrosstabTableUtil.caleVisualWidth(part, getStart()));
  }

  private String getShowLabel(int pix) {
    String unit = getDefaultUnits();

    double doubleValue = MetricUtility.pixelToPixelInch(pix);
    double showValue =
        DimensionUtil.convertTo(doubleValue, DesignChoiceConstants.UNITS_IN, unit).getMeasure();

    return PREFIX_LABEL
        + " "
        + getShowValue(showValue)
        + " "
        + getUnitDisplayName(unit)
        + " ("
        + pix
        + " "
        + PIXELS_LABEL
        + ")";
  }

  private String getShowValue(double value) {
    return FORMAT.format(value);
  }

  @Override
  protected boolean handleDragInProgress() {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    boolean bool = super.handleDragInProgress();
    // int value = getTrueValue( getLocation( ).x - getStartLocation( ).x );

    int value = getTrueValue(getMouseTrueValueX());

    int adjustWidth = CrosstabTableUtil.caleVisualWidth(part, getStart()) + value;
    updateInfomation(getShowLabel(adjustWidth));
    return bool;
  }

  @Override
  protected void fitResize() {
    List exclusion = new ArrayList();
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();

    int value = getMouseTrueValueX();

    CommandStack stack =
        part.getCrosstabHandleAdapter().getCrosstabItemHandle().getModuleHandle().getCommandStack();

    stack.startTrans(RESIZE_COLUMN_TRANS_LABEL);
    int width = 0;

    exclusion.add(Integer.valueOf(getStart()));
    width = width + getTrueValue(value, getStart(), getEnd());
    resizeFixColumn(getTrueValue(value), getStart(), getEnd());

    if (!isCtrlDown()) {
      exclusion.add(Integer.valueOf(getEnd()));
      if (getStart() != getEnd()) {
        width = 0;
      }
    }
    // Resize the table
    Dimension tableSize = part.getFigure().getSize();

    part.getCrosstabHandleAdapter()
        .setWidth(converPixToDefaultUnit(tableSize.width + width), getDefaultUnits());

    adjustOthersColumn(exclusion);
    // check the % unit

    stack.commit();
  }

  @Override
  protected AbstractTableEditPart getAbstractTableEditPart() {
    return (AbstractTableEditPart) getSourceEditPart().getParent();
  }

  @Override
  protected String getDefaultUnits() {
    CrosstabTableEditPart part = (CrosstabTableEditPart) getSourceEditPart().getParent();
    CrosstabHandleAdapter crosstabAdapter = part.getCrosstabHandleAdapter();
    return crosstabAdapter.getDesignElementHandle().getModuleHandle().getDefaultUnits();
  }

  // If the column don't set the width or set the percentage unit, set the actual value
  protected void adjustOthersColumn(List exclusion) {
    AbstractTableEditPart part = getAbstractTableEditPart();
    WorkingData data = getTableWorkingData();
    ColumnData[] datas = data.columnWidths;
    if (datas == null) {
      return;
    }
    for (int i = 0; i < datas.length; i++) {
      if (exclusion.contains(Integer.valueOf(datas[i].columnNumber))) {
        continue;
      }

      ITableLayoutOwner.DimensionInfomation dim = part.getColumnWidth(datas[i].columnNumber);
      if (DesignChoiceConstants.UNITS_PERCENTAGE.equals(dim.getUnits())) {
        resizeFixColumn(0, datas[i].columnNumber, 1);
      } else if (dim.getUnits() == null || dim.getUnits().length() == 0) {
        resizeFixColumn(0, datas[i].columnNumber, datas[i].columnNumber);
      }
    }
  }

  @Override
  protected DragGuideInfo createDragGuideInfo() {
    int value = getTrueValue(getMouseTrueValueX());
    Point p = getStartLocation().getCopy();

    getAbstractTableEditPart().getFigure().translateToRelative(p);
    value = value + p.x;
    EditorRulerComposite.DragGuideInfo info = new EditorRulerComposite.DragGuideInfo(true, value);
    return info;
  }
}
/** Add the level handle to the dimension handle. */
public class AddLevelHandleAction extends AbstractCrosstabAction {

  DimensionViewHandle viewHandle = null;
  // private static final String NAME = "Show/Hide Group Levels";//$NON-NLS-1$
  private static final String ID = "add_levelViewhandle"; // $NON-NLS-1$
  // private static final String TEXT = "Show/Hide Group Levels";//$NON-NLS-1$
  private static final String NAME =
      Messages.getString("AddLevelHandleAction_TransName"); // $NON-NLS-1$
  private static final String TEXT =
      Messages.getString("AddLevelHandleAction_Displayname"); // $NON-NLS-1$

  /**
   * Constructor
   *
   * @param handle
   */
  public AddLevelHandleAction(DesignElementHandle handle) {
    super(handle);
    setId(ID);
    setText(TEXT);
    ExtendedItemHandle extendedHandle = CrosstabAdaptUtil.getExtendedItemHandle(handle);
    setHandle(extendedHandle);
    viewHandle = CrosstabAdaptUtil.getDimensionViewHandle(extendedHandle);

    Image image = CrosstabUIHelper.getImage(CrosstabUIHelper.SHOW_HIDE_LEVEL);
    setImageDescriptor(ImageDescriptor.createFromImage(image));
  }

  public boolean isEnabled() {

    return !DEUtil.isReferenceElement(viewHandle.getCrosstabHandle())
        && findDimension(
                CrosstabAdaptUtil.getLevelViewHandle(
                        CrosstabAdaptUtil.getExtendedItemHandle(getHandle()))
                    .getCubeLevel())
            != null;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jface.action.Action#run()
   */
  public void run() {
    transStar(NAME);
    try {
      LevelViewDialog dialog = new LevelViewDialog(true);
      List showLevels = new ArrayList();
      List nullLevelHandle = new ArrayList();
      int viewCount = viewHandle.getLevelCount();
      for (int i = 0; i < viewCount; i++) {
        LevelViewHandle levelHandle = viewHandle.getLevel(i);
        if (levelHandle.getCubeLevel() == null) {
          nullLevelHandle.add(Integer.valueOf(levelHandle.getIndex()));
        } else {
          showLevels.add(levelHandle.getCubeLevel());
        }
      }

      ExtendedItemHandle extendedHandle = CrosstabAdaptUtil.getExtendedItemHandle(getHandle());
      LevelViewHandle levelViewHandle = CrosstabAdaptUtil.getLevelViewHandle(extendedHandle);

      dialog.setInput(findDimension(levelViewHandle.getCubeLevel()), showLevels);
      if (dialog.open() == Window.OK) {
        CrosstabReportItemHandle reportHandle = viewHandle.getCrosstab();

        List result = (List) dialog.getResult();
        boolean isLevelRemoved = processor(showLevels, result, nullLevelHandle, false);

        if (isLevelRemoved) {
          boolean bool = CrosstabAdaptUtil.needRemoveInvaildBindings(reportHandle);
          processor(showLevels, result, nullLevelHandle, true);
          if (bool) {
            CrosstabAdaptUtil.removeInvalidBindings(reportHandle);
          }
        } else {
          processor(showLevels, result, nullLevelHandle, true);
        }

        AggregationCellProviderWrapper providerWrapper =
            new AggregationCellProviderWrapper(reportHandle);
        providerWrapper.updateAllAggregationCells(AggregationCellViewAdapter.SWITCH_VIEW_TYPE);
      }
    } catch (SemanticException e) {
      rollBack();
      ExceptionUtil.handle(e);
      return;
    }
    transEnd();
  }

  private DimensionHandle findDimension(DesignElementHandle element) {
    if (element == null) {
      return null;
    }

    if (element.getContainer() instanceof DimensionHandle) {
      return (DimensionHandle) element.getContainer();
    }

    return findDimension(element.getContainer());
  }

  private boolean processor(List ori, List newList, List nullLevelHandle, boolean doChange)
      throws SemanticException {
    boolean isLevelRemoved = false;
    for (int i = nullLevelHandle.size() - 1; i >= 0; i--) {
      int index = ((Integer) nullLevelHandle.get(i)).intValue();
      if (doChange) {
        viewHandle.removeLevel(index);
      }
      isLevelRemoved = true;
    }

    for (int i = 0; i < ori.size(); i++) {
      LevelHandle tempHandle = (LevelHandle) ori.get(i);
      if (!newList.contains(tempHandle)) {
        if (doChange) {
          viewHandle.removeLevel(tempHandle.getQualifiedName());
        }
        isLevelRemoved = true;
      }
    }

    Collections.sort(newList, new LevelComparator());
    if (doChange) {
      for (int i = 0; i < newList.size(); i++) {
        LevelHandle tempHandle = (LevelHandle) newList.get(i);
        if (viewHandle.getLevel(tempHandle.getQualifiedName()) == null) {
          insertLevelHandle(tempHandle, i);
        }
      }
    }
    return isLevelRemoved;
  }

  private static class LevelComparator implements Comparator {

    public int compare(Object o1, Object o2) {
      LevelHandle handle1 = (LevelHandle) o1;
      LevelHandle handle2 = (LevelHandle) o2;
      return handle1.getIndex() - handle2.getIndex();
    }
  }

  private void insertLevelHandle(LevelHandle levelHandle, int pos) throws SemanticException {

    CrosstabReportItemHandle reportHandle = viewHandle.getCrosstab();
    // int viewCount = viewHandle.getLevelCount( );

    DataItemHandle dataHandle =
        CrosstabAdaptUtil.createColumnBindingAndDataItem(
            (ExtendedItemHandle) reportHandle.getModelHandle(), levelHandle);

    LevelViewHandle levelViewHandle = viewHandle.insertLevel(levelHandle, pos);
    CrosstabCellHandle cellHandle = levelViewHandle.getCell();

    cellHandle.addContent(dataHandle);

    ActionHandle actionHandle = levelHandle.getActionHandle();
    if (actionHandle != null) {
      List source = new ArrayList();
      source.add(actionHandle.getStructure());
      List newAction = ModelUtil.cloneStructList(source);
      dataHandle.setAction((Action) newAction.get(0));
    }

    CrosstabUtil.addLabelToHeader(levelViewHandle);
  }
}