/*
 * Cueplot: a GUI front-end to gnuplot
 * Copyright (C) 2007 Muneyuki Noguchi
 *
 * This program 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 (at your option) any later version.
 *
 * This program 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "ConsoleDialog.h"

#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QtGui/QTextEdit>
#include <QtGui/QVBoxLayout>

ConsoleDialog::ConsoleDialog(QWidget *parent)
: QDialog(parent)
{
	setWindowTitle(tr("Console") + " - " 
			+ QCoreApplication::applicationName());

	consoleTextEdit = new QTextEdit;
	consoleTextEdit->setReadOnly(true);

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(consoleTextEdit);

	setLayout(mainLayout);
}

namespace {
	//! '&lt;' などをエスケープし、改行を &lt;br&gt; に置き換える
	QString escape(const QString &str)
	{
		QString escapedStr = str;
		escapedStr.replace("<", "&lt;");
		escapedStr.replace(">", "&gt;");
		escapedStr.replace("\r\n", "<br>");
		escapedStr.replace("\r", "<br>");
		escapedStr.replace("\n", "<br>");

		return escapedStr;
	}
}

void ConsoleDialog::execute(const QString &command)
{
	QString escapedCommand = escape(command);
	consoleTextEdit->append("<kbd>" + escapedCommand + "</kbd>");
}

void ConsoleDialog::readStandardError(const QByteArray &output)
{
	QString command = QString(output.data());
	if (!command.trimmed().isEmpty()) {
		command = escape(command);
		// エラー出力は赤で表示
		consoleTextEdit->append("<kbd><font color=\"red\">" +
				command + "</font></kbd>");
	}
}
