001    /*
002     * Copyright (C) 2012 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    
020    package org.crsh.text.ui;
021    
022    import org.crsh.text.Renderer;
023    import org.crsh.text.Style;
024    
025    public class LabelElement extends Element {
026    
027      /** . */
028      final String value;
029    
030      /** . */
031      final int minWidth;
032    
033      /** . */
034      final int width;
035    
036      private static int width(String s, int index) {
037        if (index < s.length()) {
038          int pos = s.indexOf('\n', index + 1);
039          if (pos == -1) {
040            return s.length() - index;
041          } else {
042            return Math.max(pos - index, width(s, pos + 1));
043          }
044        } else {
045          return 0;
046        }
047      }
048    
049      public LabelElement(String value, int minWidth) {
050        if (minWidth < 0) {
051          throw new IllegalArgumentException("No negative min size allowed");
052        }
053    
054        // Determine width
055        int width = width(value, 0);
056    
057        //
058        this.value = value;
059        this.minWidth = Math.min(width, minWidth);
060        this.width = width;
061      }
062    
063      public LabelElement(String value) {
064        this(value, 1);
065      }
066    
067      public LabelElement(Object value, int minWidth) {
068        this(String.valueOf(value), minWidth);
069      }
070    
071      public LabelElement(Object value) {
072        this(String.valueOf(value));
073      }
074    
075      public String getValue() {
076        return value;
077      }
078    
079      public Renderer renderer() {
080        return new LabelRenderer(this);
081      }
082    
083      @Override
084      public String toString() {
085        return "Label[" + value + "]";
086      }
087    
088      @Override
089      public LabelElement style(Style.Composite style) {
090        return (LabelElement)super.style(style);
091      }
092    }