com.dimad.gwt.control.text.FontRichTextToolbar.java Source code

Java tutorial

Introduction

Here is the source code for com.dimad.gwt.control.text.FontRichTextToolbar.java

Source

/*
 * Copyright 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.dimad.gwt.control.text;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.dimad.gwt.control.combo.Combobox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * A sample toolbar for use with {@link RichTextArea}. It provides a simple UI
 * for all rich text formatting, dynamically displayed only for the available
 * functionality.
 */
@SuppressWarnings("deprecation")
public class FontRichTextToolbar extends Composite {

    private List<String> fontStyle = new LinkedList<String>();

    /**
     * This {@link ClientBundle} is used for all the button icons. Using a bundle
     * allows all of these images to be packed into a single image, which saves a
     * lot of HTTP requests, drastically improving startup time.
     */
    public interface Images extends ClientBundle {

        ImageResource bold();

        ImageResource createLink();

        ImageResource hr();

        ImageResource indent();

        ImageResource insertImage();

        ImageResource italic();

        ImageResource justifyCenter();

        ImageResource justifyLeft();

        ImageResource justifyRight();

        ImageResource ol();

        ImageResource outdent();

        ImageResource removeFormat();

        ImageResource removeLink();

        ImageResource strikeThrough();

        ImageResource subscript();

        ImageResource superscript();

        ImageResource ul();

        ImageResource underline();
    }

    /**
     * This {@link Constants} interface is used to make the toolbar's strings
     * internationalizable.
     */
    public interface Strings extends Constants {

        String black();

        String blue();

        String bold();

        String color();

        String font();

        String green();

        String italic();

        String large();

        String medium();

        String normal();

        String red();

        String size();

        String small();

        String strikeThrough();

        String underline();

        String white();

        String xlarge();

        String xsmall();

        String xxlarge();

        String xxsmall();

        String yellow();
    }

    /**
     * We use an inner EventHandler class to avoid exposing event methods on the
     * RichTextToolbar itself.
     */
    private class EventHandler implements ClickHandler, ChangeHandler, KeyUpHandler {

        public void onChange(ChangeEvent event) {
            Widget sender = (Widget) event.getSource();

            if (sender == foreColors) {
                extended.setForeColor(foreColors.getValue(foreColors.getSelectedIndex()));
                sendEvent(IRichTextEventListener.FOREGROUND_COLOR, foreColors.getValue().toString());
            } else if (sender == fonts) {
                extended.setFontName(fonts.getValue(fonts.getSelectedIndex()));
                sendEvent(IRichTextEventListener.FONT_NAME, fonts.getValue().toString());
            } else if (sender == fontSizes) {
                extended.setFontSize(fontSizesConstants[fontSizes.getSelectedIndex()]);
                sendEvent(IRichTextEventListener.FONT_SIZE, fontSizes.getValue().toString());
            }
        }

        public void onClick(ClickEvent event) {
            Widget sender = (Widget) event.getSource();

            if (sender == bold) {
                extended.toggleBold();
                Window.alert("FornRichTextToolbar.Bold = " + extended.isBold());
                if (extended.isBold()) {
                    fontStyle.add("bold");
                } else {
                    fontStyle.remove("bold");
                }
            } else if (sender == italic) {
                extended.toggleItalic();
                if (extended.isItalic()) {
                    fontStyle.add("italic");
                } else {
                    fontStyle.remove("italic");
                }
            } else if (sender == underline) {
                extended.toggleUnderline();
                if (extended.isUnderlined()) {
                    fontStyle.add("underline");
                } else {
                    fontStyle.remove("underline");
                }
            } else if (sender == strikethrough) {
                extended.toggleStrikethrough();
                if (extended.isStrikethrough()) {
                    fontStyle.add("strikethrough");
                } else {
                    fontStyle.remove("strikethrough");
                }
            }
            StringBuffer fontStyleString = new StringBuffer();
            int i = 0;
            for (String style : fontStyle) {
                if (i++ > 0) {
                    fontStyleString.append(";");
                }
                fontStyleString.append(style);
            }
            sendEvent(IRichTextEventListener.FONT_STYLE, fontStyleString.toString());
        }

        public void onKeyUp(KeyUpEvent event) {
            Widget sender = (Widget) event.getSource();
            if (sender == richText) {
                // We use the RichTextArea's onKeyUp event to update the toolbar status.
                // This will catch any cases where the user moves the cursur using the
                // keyboard, or uses one of the browser's built-in keyboard shortcuts.
                updateStatus();
            }
        }
    }

    private static final RichTextArea.FontSize[] fontSizesConstants = new RichTextArea.FontSize[] {
            RichTextArea.FontSize.XX_SMALL, RichTextArea.FontSize.X_SMALL, RichTextArea.FontSize.SMALL,
            RichTextArea.FontSize.MEDIUM, RichTextArea.FontSize.LARGE, RichTextArea.FontSize.X_LARGE,
            RichTextArea.FontSize.XX_LARGE };

    private Images images = (Images) GWT.create(Images.class);
    private Strings strings = (Strings) GWT.create(Strings.class);
    private EventHandler handler = new EventHandler();

    private RichTextArea richText;
    private RichTextArea.ExtendedFormatter extended;

    private VerticalPanel outer = new VerticalPanel();
    private HorizontalPanel topPanel = new HorizontalPanel();
    private ToggleButton bold;
    private ToggleButton italic;
    private ToggleButton underline;
    private ToggleButton strikethrough;

    private Combobox foreColors;
    private Combobox fonts;
    private Combobox fontSizes;

    private IRichTextEventListener eventListener = null;

    /**
     * Creates a new toolbar that drives the given rich text area.
     * 
     * @param richText
     *            the rich text area to be controlled
     */
    public FontRichTextToolbar(RichTextArea richText) {
        try {
            this.richText = richText;
            this.extended = richText.getExtendedFormatter();

            outer.add(topPanel);
            topPanel.setWidth("100%");

            initWidget(outer);
            setStyleName("gwt-RichTextToolbar");
            richText.addStyleName("hasRichTextToolbar");

            topPanel.add(fonts = createFontList());
            topPanel.add(fontSizes = createFontSizes());

            topPanel.add(bold = createToggleButton(images.bold(), strings.bold()));
            topPanel.add(italic = createToggleButton(images.italic(), strings.italic()));
            topPanel.add(underline = createToggleButton(images.underline(), strings.underline()));
            topPanel.add(strikethrough = createToggleButton(images.strikeThrough(), strings.strikeThrough()));

            topPanel.add(foreColors = createColorList("Foreground"));

            // We only use these handlers for updating status, so don't hook them up
            // unless at least basic editing is supported.
            richText.addKeyUpHandler(handler);
            richText.addClickHandler(handler);
        } catch (Exception e) {
            Window.alert("FontRichTextToolbar: ex=" + e);
        }
    }

    public void initialize(Map<String, String> defaultValues) {
        try {
            fonts.setValue(defaultValues.get(IRichTextEventListener.FONT_NAME));
            extended.setFontName(fonts.getValue().toString());
            fontSizes.setValue(defaultValues.get(IRichTextEventListener.FONT_SIZE));
            extended.setFontSize(fontSizesConstants[fontSizes.getSelectedIndex()]);
            fontStyle = new LinkedList<String>(
                    Arrays.asList(defaultValues.get(IRichTextEventListener.FONT_STYLE).toLowerCase().split(";")));
            bold.setDown(defaultValues.get(IRichTextEventListener.FONT_STYLE).toLowerCase()
                    .contains(IRichTextEventListener.FONT_STYLE_BOLD));
            italic.setDown(defaultValues.get(IRichTextEventListener.FONT_STYLE).toLowerCase()
                    .contains(IRichTextEventListener.FONT_STYLE_ITALIC));
            underline.setDown(defaultValues.get(IRichTextEventListener.FONT_STYLE).toLowerCase()
                    .contains(IRichTextEventListener.FONT_STYLE_UNDERLINE));
            strikethrough.setDown(defaultValues.get(IRichTextEventListener.FONT_STYLE).toLowerCase()
                    .contains(IRichTextEventListener.FONT_STYLE_STRIKETHROUGH));
            foreColors.setValue(defaultValues.get(IRichTextEventListener.FOREGROUND_COLOR));
            extended.setForeColor(foreColors.getValue(foreColors.getSelectedIndex()));
        } catch (Exception e) {
            Window.alert("FontRichTextToolbar.initialize: ex=" + e);
        }
    }

    private Combobox createColorList(String caption) {
        Combobox lb = new Combobox();
        lb.addChangeHandler(handler);
        lb.setVisibleItemCount(1);

        lb.addItem(strings.white(), "white");
        lb.addItem(strings.black(), "black");
        lb.addItem(strings.red(), "red");
        lb.addItem(strings.green(), "green");
        lb.addItem(strings.yellow(), "yellow");
        lb.addItem(strings.blue(), "blue");
        return lb;
    }

    private Combobox createFontList() {
        Combobox lb = new Combobox();
        lb.addChangeHandler(handler);
        lb.setVisibleItemCount(1);

        lb.addItem(strings.normal(), "Courier");
        lb.addItem("Times New Roman", "Times New Roman");
        lb.addItem("Arial", "Arial");
        lb.addItem("Courier New", "Courier New");
        lb.addItem("Georgia", "Georgia");
        lb.addItem("Trebuchet", "Trebuchet");
        lb.addItem("Verdana", "Verdana");
        return lb;
    }

    private Combobox createFontSizes() {
        Combobox lb = new Combobox();
        lb.addChangeHandler(handler);
        lb.setVisibleItemCount(1);

        lb.addItem(strings.xxsmall());
        lb.addItem(strings.xsmall());
        lb.addItem(strings.small());
        lb.addItem(strings.medium());
        lb.addItem(strings.large());
        lb.addItem(strings.xlarge());
        lb.addItem(strings.xxlarge());
        return lb;
    }

    private ToggleButton createToggleButton(ImageResource img, String tip) {
        ToggleButton tb = new ToggleButton(new Image(img));
        tb.addClickHandler(handler);
        tb.setTitle(tip);
        return tb;
    }

    /**
     * Updates the status of all the stateful buttons.
     */
    private void updateStatus() {
        bold.setDown(extended.isBold());
        italic.setDown(extended.isItalic());
        underline.setDown(extended.isUnderlined());
        strikethrough.setDown(extended.isStrikethrough());
    }

    private void sendEvent(String name, String value) {
        if (eventListener != null) {
            eventListener.sendEvent(name, value);
        }
    }

    public IRichTextEventListener getEventListener() {
        return eventListener;
    }

    public void setEventListener(IRichTextEventListener eventListener) {
        this.eventListener = eventListener;
    }
}