//
// C++ Interface: runcommandforoutput
//
// Description: 
//
//
// Author: Benjamin Mesing <bensmail@gmx.net>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef __RUNCOMMANDFOROUTPUT_H_2004_07_18
#define __RUNCOMMANDFOROUTPUT_H_2004_07_18

#include <qobject.h>
#include <qstringlist.h>

class QProcess;

namespace NApplication {


/** @brief This class can be used to run a program where you are interested in its output.
  *
  * When the program has finished, a processExited(RunCommandForOutput*) signal will be 
  * emitted. After this the output can be gotten via getOutput();
  *
  * You can also use the run(const QString&, size_t) function which runs synchrone, i.e.
  * it will run the command and return after it is finished. 
  * @warning every RunCommandForOutput command should used only ones!
  * @note this class relies on a working event queue, so make sure that
  * it will be evaluated or the program might never finish...
  * @author Benjamin Mesing
  */
class RunCommandForOutput :  public QObject
{
	Q_OBJECT
 	QProcess* _pProcess;
 	const QString _command;
	QStringList _arguments;
	/** Holds the output generated by the application. 
	  *
	  * Each entry in the string list contains a single line.
	  */
	QStringList _output;
	bool _finished;
public:
	/** @param command the command to be executed */
	RunCommandForOutput(const QString& command);
	~RunCommandForOutput();
	void addArgument(const QString& arg);
	/** Starts the given command. */
	void start();
	/** @returns a list of all output lines created by the application. */
	const QStringList getOutput() const	{ return _output; }
	/** @returns a list of all output lines created by the application, the lines are stripped
	  * of the trailing \\n. 
	  */
	QStringList getOutput()	{ return _output; };
	bool normalExit();
	/** @brief Starts the command and blocks until it terminates.
	  *
	  * The output can be fetched with the getOutput() function. This function ignores the command
	  * handed on construction.
	  *
	  * @param command the command that should be executed
	  * @param maximumLineLength hand the maximum length for single line, hand 0 if you
	  * can't make any ensurance about the line length (this will be slower)
	  * @returns if the program exited successfully
	  */
	bool run(const QString& command, size_t maximumLineLength=10000);
signals:
	/** This is emitted when the process has finished*/
	void processExited(RunCommandForOutput*);
private Q_SLOTS:
	/** @brief Called whenever the process released something to stdout. 
	  *
	  * This reads a line and attaches it to output. If a whole line can not
	  * be read it does nothing. 
	  */
	void onReadyReadStdout();
	void onProcessExited();
};



};

#endif	// __RUNCOMMANDFOROUTPUT_H_2004_07_18
