⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 saveaswebpageaction.java

📁 具有不同语法高亮的编辑器实例
💻 JAVA
字号:
/*
 * 03/30/2004
 *
 * SaveAsWebPageAction.java - Action to save a copy of the current
 *                            file as HTML in RText.
 * Copyright (C) 2004 Robert Futrell
 * email@address.com
 * www.website.com
 *
 * This file is a part of RText.
 *
 * RText is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * RText is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.fife.rtext;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.text.Document;
import javax.swing.text.Element;

import org.fife.RUtilities;
import org.fife.ui.rtextfilechooser.filters.HTMLFileFilter;
import org.fife.ui.rsyntaxtextarea.SyntaxScheme;
import org.fife.ui.rsyntaxtextarea.Token;


/**
 * Action used by an <code>RText</code> to save a copy
 * of the current document as HTML.
 *
 * @author Robert Futrell
 * @version 1.0
 */
class SaveAsWebPageAction extends AbstractAction {

	// Pointers to other objects we have to access.
	private RText owner;


/*************************************************************************************/


	/**
	 * Creates a new <code>SaveAsWebPageAction</code>.
	 *
	 * @param text The text associated with the action.
	 * @param icon The icon associated with the action.
	 * @param desc The description of the action (used in tooltips???).
	 * @param mnemonic The mnemonic for the action.
	 * @param accelerator The accelerator key for the action.
	 * @param owner the main window of this rtext instance.
	 */
	public SaveAsWebPageAction(String text, ImageIcon icon, String desc, Integer mnemonic,
						KeyStroke accelerator, RText owner) {
		super(text, icon);
		putValue(SHORT_DESCRIPTION, desc);
		putValue(MNEMONIC_KEY, mnemonic);
		putValue(ACCELERATOR_KEY, accelerator);
		this.owner = owner;
	}


/*************************************************************************************/


	// Callback routine called when user uses this component.
	public void actionPerformed(ActionEvent e) {

		ResourceBundle msg = owner.getResourceBundle();

		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle("Save Copy as Web Page");
		chooser.addChoosableFileFilter(new HTMLFileFilter());
		chooser.removeChoosableFileFilter(chooser.getChoosableFileFilters()[0]);

		String htmlFileName = owner.getMainView().currentTextArea.getFileFullPath();
		int extensionStart = htmlFileName.lastIndexOf('.');
		if (extensionStart!=-1)
			htmlFileName = htmlFileName.substring(0,extensionStart) + ".html";
		else
			htmlFileName += ".html";
		chooser.setSelectedFile(new File(htmlFileName));

		if (chooser.showSaveDialog(owner)==JFileChooser.APPROVE_OPTION) {

			File chosenFile = chooser.getSelectedFile();
			String chosenFilePath = chosenFile.getAbsolutePath();

			// If the file already exists, prompt them to see whether or not they want to overwrite it.
			if (chosenFile.exists()) {
				String temp = RTextUtilities.getRegularExpressionForLine(chosenFile.getAbsolutePath(), true);
				if (temp!=null)
					temp = msg.getString("FileAlreadyExists").replaceFirst("%file%", temp);
				else
					temp = msg.getString("FileAlreadyExists"); // Just have the "%file% still in there.
				if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(owner, temp,
								msg.getString("ConfDialogTitle"), JOptionPane.YES_NO_OPTION))
					return;
			}

			// Ensure that it has an HTML extension.
			if (!chosenFilePath.matches("[^\\.]*\\.htm[l]?"))
				chosenFilePath = chosenFilePath + ".html";

			// Try and write output to the current filename.
			try {

				String lineSeparator = System.getProperty("line.separator");

				PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(chosenFilePath)));
				out.println("<html>" + lineSeparator + "<head><title>" + chosenFilePath + "</title></head>");
				out.println("<body>" + lineSeparator + "<basefont face=\"monospaced, courier, courier new\" size=\"1\">");

				String s;
				String styleString, endStyleString;
				String lastFontColorString = "";
				RTextEditorPane textArea = owner.getMainView().currentTextArea;
				String tabString = "   ";
				int numLines = textArea.getLineCount();
				for (int i=0; i<numLines; i++) {
					Token token = textArea.getTokenListForLine(i);
					while (token!=null && token.isPaintable()) {
						SyntaxScheme scheme = textArea.getSchemeForTokenType(token.type);
						styleString = "";
						endStyleString = "";
						if ((scheme.font.getStyle()&Font.BOLD)!=0) {
							styleString = "<b>";
							endStyleString = "</b>";
						}
						if ((scheme.font.getStyle()&Font.ITALIC)!=0) {
							styleString += "<em>";
							endStyleString = "</em>" + endStyleString;
						};
						s = new String(token.text, token.textOffset,token.textCount);
						s = s.replaceAll("\n", "").replaceAll("&", "&amp;").replaceAll("\t", tabString).replaceAll(" ", "&nbsp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
                              if (!token.isWhitespace()) {
							Color color = textArea.getSchemeForTokenType(token.type).foreground;
							String fontColorString = RUtilities.getHTMLFormatForColor(color);
							s = "<font color=" + fontColorString + ">" + s;
						}
						out.print( styleString + s + endStyleString);	
						token = token.getNextToken();
					}
					out.println("<br>");
				}

				out.println("</body>" + lineSeparator + "</html>");
				out.close();

			} catch (Exception f) {
				String temp = RTextUtilities.getRegularExpressionForLine(chosenFilePath, true);
				if (temp!=null)
					temp = msg.getString("ErrorWritingFile").replaceFirst("%fileName%", temp) + "" + f;
				else
					temp = msg.getString("ErrorWritingFile"); // Just have the "%fileName% still in there.
				JOptionPane.showMessageDialog(null, temp,
					msg.getString("ErrorDialogTitle"), JOptionPane.ERROR_MESSAGE);
				owner.setMessages(null, "ERROR:  Could not save file!");
				f.printStackTrace();
			} // End of catch (Exception f).

		}

	}


/*****************************************************************************/


}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -