/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2004-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

package ipipan.poliqarp.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import javax.swing.JTable;
import javax.swing.JLabel;

/**
 * A <code>LeftSideCellRenderer</code> works exactly like a <code>
 * MultiColorCellRenderer</code>, except that when the rendered text
 * becomes too wide to fit in a table cell, it is shortened from the
 * left side rather than from the right (for instance, <i>a very long
 * text</i> may get shortened to <i>...ng text</i> instead of <i>a
 * very l...</i>).
 */
public class LeftSideCellRenderer extends MultiColorCellRenderer
{
   /**
    * Constructs a <code>LeftSideCellRenderer</code> with the given set
    * of cell background colors.
    */
   public LeftSideCellRenderer(Color[] colors)
   {
      super(colors);
   }

   /**
    * Returns the renderer for a cell. 
    */
   public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column)
   {
      String string = (String)value;
      final String cut = "...";
      FontMetrics fm = getFontMetrics(getFont());
      int width = table.getColumnModel().getColumn(column).getWidth() - 3;
      Component c = super.getTableCellRendererComponent(table, value,
         isSelected, hasFocus, row, column);
      Dimension preferredSize = c.getPreferredSize();
      int swidth = fm.stringWidth(string);
      if (swidth <= width)
         return c;
      preferredSize.width = swidth;
      char[] stringChars = string.toCharArray();
      int len = string.length(), start = 0;
      while (start < len && 
         fm.charsWidth(stringChars, start, len - start) + fm.stringWidth(cut) >
         width)
      {
         start++;
      }
      setText(cut + string.substring(start));
      setPreferredSize(preferredSize);
      return this;
   }
}
