/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */


#include "terminaldisplay.h"

#include <qprocess.h>
#include <qpalette.h>

#include <terminalformatter.h>

#define	TERMINAL_FONT			"Monospace"
#define	TERMINAL_POINTSIZE	9
#define	TERMINAL_COLS			80
#define	TERMINAL_MINWIDTH		600
#define	TERMINAL_MINHEIGHT	510
#define	TERMINAL_MAX_STORED	300

TerminalDisplay::TerminalDisplay(QWidget *parent,  const char *name)
	:	QTextEdit(parent, name),
		process(NULL),
		formatter(NULL)
{
	setReadOnly(true);
	setTextFormat(LogText);
	setMaxLogLines(TERMINAL_MAX_STORED);
	setHScrollBarMode(AlwaysOff);
	setVScrollBarMode(AlwaysOn);

	QFont font = currentFont();
	font.setFamily(TERMINAL_FONT);
	font.setPointSize(TERMINAL_POINTSIZE);
	setFont(font);

	setMinimumWidth(TERMINAL_MINWIDTH);
	setMinimumHeight(TERMINAL_MINHEIGHT);
	
	clearOnSetProcess = true;
}


void  TerminalDisplay::clear() {
	QTextEdit::clear();
}


/** Only use this BEFORE QProcess::start() or QProcess::launch()
  * is called because Communication settings must be set.
  */
void  TerminalDisplay::setProcess(QProcess  *p) {
	if(process != NULL)
		disconnect(process, NULL, NULL, NULL);

	if(clearOnSetProcess)
		clear();

	process = p;
	if(process != NULL) {
		p->setCommunication(QProcess::Stdout | QProcess::Stderr | QProcess::DupStderr);
		connect(p, SIGNAL(readyReadStdout()), SLOT(readStdout()));
		connect(p, SIGNAL(processExited()), SLOT(processExited()));
	}
}


void	TerminalDisplay::readStdout() {
	static QString  buffer;

	QString  out = process->readStdout();

	/* Begin a new line instead of erasing
	 * the current one and jumping to it's begin.
	 *
	 * Replace \t with 8 tabs.
	 */
	out.replace('\r', '\n');
	out.replace('\t', "		  ");

	int  pos;
	while((pos = out.find('\n')) != -1) {
		/* \n is not appended, but removed from the string.
		 *
		 * Keep this!
		 */

		buffer += out.left(pos);

		if(buffer.isEmpty())
			/* Empty line */
			append(" ");
		else
		{
			QString begin, end;
			if(formatter != NULL) {
				begin = "<font color=\"" + formatter->format(buffer).name() + "\">";
				end = "</font>";
			}
	
			while(!buffer.isEmpty()) {
				append(begin + QStyleSheet::escape(buffer.left(TERMINAL_COLS)) + end);
				buffer.remove(0, TERMINAL_COLS);
			}
		}

		out.remove(0, pos + 1);
	}

	buffer += out;
}

void  TerminalDisplay::processExited() {
	/* Append data not written */
	append(process->readStdout());

	disconnect(this->process, NULL, NULL, NULL);
	process = NULL;
}

void  TerminalDisplay::setFormatter(TerminalFormatter *f) {
	formatter = f;
}
