Package com.nexirius.util.text

Source Code of com.nexirius.util.text.HTMLText

//{HEADER
/**
* This class is part of jnex 'Nexirius Application Framework for Java'
* Copyright (C) Nexirius GmbH, CH-4450 Sissach, Switzerland (www.nexirius.ch)
*
* <p>This library is free software; you can redistribute it and/or<br>
* modify it under the terms of the GNU Lesser General Public<br>
* License as published by the Free Software Foundation; either<br>
* version 2.1 of the License, or (at your option) any later version.</p>
*
* <p>This library is distributed in the hope that it will be useful,<br>
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br>
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU<br>
* Lesser General Public License for more details.</p>
*
* <p>You should have received a copy of the GNU Lesser General Public<br>
* License along with this library; if not, write to the Free Software<br>
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA</p>
* </blockquote>
*
* <p>
* Nexirius GmbH, hereby disclaims all copyright interest in<br>
* the library jnex' 'Nexirius Application Framework for Java' written<br>
* by Marcel Baumann.</p>
*/
//}HEADER
package com.nexirius.util.text;

import com.nexirius.util.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;

/**
* A class to help produce HTML files with mixed paragraph types
*/
public class HTMLText implements KeyListener {



    private DefaultStyledDocument m_doc;
    private HTMLEditorKit m_kit = new HTMLEditorKit();
    private TextStyles m_styles;
    private JTextPane m_pane;
    private int m_prev_position = 0;


    public HTMLText() {
        m_doc = (DefaultStyledDocument) m_kit.createDefaultDocument();
        m_styles = new TextStyles(m_doc);
    }

    public Document getDocument() {
        return m_doc;
    }

    public void writeRTF(File file)
            throws Exception {
        FileOutputStream out = new FileOutputStream(file);

        writeRTF(out);
        out.close();
    }

    public void writeRTF(OutputStream out)
            throws Exception {
        RTFEditorKit rtf = new RTFEditorKit();

        rtf.write(out, m_doc, 0, m_doc.getLength());
    }

    /**
     * initialized the list of text styles
     *
     * @param stylefile the file which contains the paragraph style information
     * @throws Exception Throws an exception if the input file contains errors
     * @see com.nexirius.util.text.TextStyles#init
     */
    public void initStyles(String stylefile)
            throws Exception {
        m_styles.init(stylefile);
    }

    /**
     * This functions opens a text file and collects its input into this Document.<BR>
     * Header: <BR>
     * <CODE>
     * FILE_ID:"HTMLText"<BR>
     * VERSION:1
     * </CODE>
     * <BR>The file contains string literals and format identifiers. All the text before
     * the format identifier is shown in that style.
     *
     * @throws Exception Throws an exception if the input file contains errors
     */
    public void readText(String filename)
            throws Exception {
        TextFile file = new TextFile(filename);

        file.openForRead("HTMLText");

        TextToken token;

        for (token = file.nextToken(); token != null; token = file.nextToken()) {
            if (token.isChar('{')) {
                String path = null;
                String label = null;

                token = file.nextToken();

                if (token.isString()) {
                    path = token.getString();
                }

                token = file.nextToken();

                if (token.isString()) {
                    label = token.getString();

                    token = file.nextToken();
                }

                if (!token.isChar('}')) {
                    throw new Exception("wrong reference format");
                }

                if (path != null) {
                    appendReference(path, label);
                }

                token = file.nextToken();
            }

            if (token.isIdentifier()) {
                appendText("\n", token.getString());
            } else if (token.isString()) {
                appendText(token.getString());
            }
        }
    }

    /**
     * Appends a string to the end of the document and assigns the given style to it
     *
     * @param text                the string which is to be appended
     * @param paragraph_stylename the name of the style which will be assigned to the text (may be null)
     * @throws Exception Throws an exception if an undefined style is used
     */
    public void appendText(String text, String paragraph_stylename)
            throws Exception {
        Style style = null;

        if (text == null || text.length() == 0) {
            return;
        }

        if (paragraph_stylename == null) {
            paragraph_stylename = "normal";
        }

        try {
            style = m_doc.getStyle(paragraph_stylename);
        } catch (Exception ex) {
            throw new Exception("Style '" + paragraph_stylename + "' not found");
        }

//        AttributeSet attrib = ((style == null) ? SimpleAttributeSet.EMPTY : style.copyAttributes());
        AttributeSet attrib = SimpleAttributeSet.EMPTY;
       
//System.out.println("APPENDING TEXT" + paragraph_stylename + " :"  + text);
        m_doc.insertString(m_doc.getLength(), text, attrib);

        if (style != null) {
            m_doc.setParagraphAttributes(m_prev_position, m_doc.getLength() - m_prev_position, style, true);
            m_prev_position = m_doc.getLength();
        }
    }

    /**
     * Appends text to the current document.<BR>
     * The style is assigned as soon as the function appendText(String, String) is called with a non null argument
     */
    public void appendText(String text) {
        try {
            appendText(text, null);
        } catch (Exception ex) {
            System.out.println("HTMLText.appendText(String) failed");
        }
    }

    /**
     Appends a string to the current document.<BR>
     The style is assigned as soon as the function appendText(String, String) is called with a non null argument
     */
/*  public void appendString(String string, String character_stylename)
    throws Exception
  {
    Style style = null;

    if (character_stylename != null) {
      try {
        style = m_doc.getStyle(character_stylename);
      }
      catch (Exception ex)
      {
        throw new Exception("Style '" + character_stylename + "' not found");
      }
    }

    m_doc.insertString(m_doc.getLength(), string, style);//fix

//    if (style != null) {//fix
//      m_doc.setParagraphAttributes(m_prev_position, m_doc.getLength() - m_prev_position, style, true);
//      m_prev_position = m_doc.getLength();
//    }
  }
*/


    /**
     * Appends a HTML link
     *
     * @param path the links URL string
     */
    public void appendReference(String path) {
        appendReference(path, null);
    }

    /**
     * Appends a HTML link
     *
     * @param path  the links URL string
     * @param label the label text which will be displayed for the link
     */
    public void appendReference(String path, String label) {
        if (label == null) {
            label = path;
        }

        String ref = "-lt-a href=-qu-" + path + "-qu--gt-" + label + "-lt-/a-gt-";

        appendText(ref);
    }

    /**
     * @return the associated JTextPane
     */
    public JTextPane getTextPane() {
        if (m_pane == null) {
            m_pane = new JTextPane(m_doc);

            //m_pane.addKeyListener(this);
        }

        return m_pane;
    }

    /**
     * write the document to a HTML file
     *
     * @param filename The name of the HTML file (if the file exists it will be overwritten)
     * @throws Exception Throws an exception if the file cannot be written
     */
    public void writeTo(String filename)
            throws Exception {
        FileWriter fw = new FileWriter(filename);

        write(fw);

        fw.close();

        // fix this is a work around because the line breakes are not written by HTMLEditorKit!!!
        XFile xf = new XFile(filename);
        StringVector sv = xf.getTextLines();

        sv = insertLineBreaks(sv);

        xf.writeTextLines(sv);
    }

    private StringVector insertLineBreaks(StringVector sv) {
        String s;
        StringVector ret = new StringVector();
        boolean before_body = true; // before <body>
        String new_line = new String("<br>");
        String body = new String("<body>");

        for (s = sv.firstItem(); s != null; s = sv.nextItem()) {
            if (before_body) {
                if (s.startsWith(body)) {
                    before_body = false;
                }

                ret.append(s);

                continue;
            }

            // look for empty lines and replace them with <br>
            if (s.length() == 0) {
                ret.append(new_line);
            } else {
                // replace subtrings
                XString xs = new XString(s);

                xs.replace("-gt-", ">");
                xs.replace("-lt-", "<");
                xs.replace("-qu-", "\"");

                ret.append(xs.toString());
            }
        }

        return ret;
    }

    public void dump()
            throws Exception {
        System.out.println("---------------------");
        m_doc.dump(System.out);
        System.out.println("---------------------");
        write(new OutputStreamWriter(System.out));
        System.out.println("---------------------");
    }

    public void write(Writer writer)
            throws Exception {
        m_kit.write(writer, m_doc, 0, m_doc.getLength());
    }

    // KeyListener Functions

    public void keyPressed(KeyEvent e) {
        System.out.println("KEY: " + KeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == KeyEvent.VK_Q) {
            System.exit(0);
        } else if (e.getKeyCode() == KeyEvent.VK_D) {
            try {
                writeTo("output.html");
            } catch (Exception ex) {
            }
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

    public static void main(String argv[])
            throws Exception {
        HTMLText text = new HTMLText();
        Frame frame = new Frame();

        frame.add("Center", text.getTextPane());
        frame.setSize(500, 500);
        frame.setVisible(true);
//text.getTextPane().setBackground(Color.yellow);
        text.initStyles(argv[0]);
        text.readText(argv[1]);
/*   
    text.appendText("bigcode Marcel Baumann\n", "bigcode");
//text.newParagraph();
    text.appendText("bold Nexirius\n", "bold");
//text.newParagraph();
    text.appendText("italic Hauptstrasse 27C\n");
    text.appendText("4455 ZUNZGEN\n", "italic");
    text.appendText("code Tel. P: 061 / 973 01 20\nTel. G: 061 / 973 01 23\n", "code");
    text.appendText("underline some stupid information\n\n\n\n3 lines later", "underline");
//    frame.setVisible(false);
*/
        text.dump();
        text.writeTo("output.html");
    }
}
TOP

Related Classes of com.nexirius.util.text.HTMLText

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.