
#include<ktmainwindow.h>		// For KTMainWindow
#include<kapp.h>			// For KApplication
#include<kmsgbox.h>			// For KMsgBox
#include<kfiledialog.h>			// For KFileDialog

#include<qfile.h>			// For QFile
#include<qstring.h>			// For QString
#include<qmultilinedit.h>		// For QMultiLineEdit
#include<qkeycode.h>			// For key codes

class KPadWidget : public KTMainWindow
{
	Q_OBJECT
	
public:
	// constructor and destructor
	KPadWidget();
	virtual ~KPadWidget() {}

public slots:
	void save();
	void load();
	void quit();

protected slots:
	void setDirty();
	
private:
	QPopupMenu	*_fileMenu;
	QMultiLineEdit *_editor;

	QString	_fileName;
	bool	_textChanged;
};

KPadWidget::KPadWidget()
	: KTMainWindow(),
	_editor( new QMultiLineEdit( this ) ),
	_fileName( "Untitled" ),
	_textChanged( false )
{
	// set up the editor widget
	setView( _editor );
	connect( _editor, SIGNAL(textChanged()), this, SLOT(setDirty()) );

	// set up the popup menu
	_fileMenu = new QPopupMenu;
	_fileMenu->insertItem( i18n( "&Open" ), this, SLOT(load()), 
		CTRL + Key_O );
	_fileMenu->insertItem( i18n( "&Save" ), this, SLOT(save()), 
		CTRL + Key_S );
	_fileMenu->insertSeparator();
	_fileMenu->insertItem( i18n( "E&xit" ), this, SLOT(quit()),
		CTRL + Key_X );


	// set up the menubar and insert the popup menu
	KMenuBar *menubar = menuBar();
	menubar->insertItem( i18n( "&File" ), _fileMenu );
}

void KPadWidget::save()
{
	QFile f( _fileName );
	bool ok = f.open( IO_WriteOnly );

	if( !ok ) {
		// file write error
		QString errormsg = i18n( "Couldn't write to File:" );
		errormsg += _fileName;
		
		KMsgBox::message( 0, i18n( "File Write Error" ), errormsg );

		return;
	}

	QString text = _editor->text();
	f.writeBlock( text, text.length() );
	f.close();

	_textChanged = false;
}

void KPadWidget::load()
{
	QString name = KFileDialog::getOpenFileName();
	
	if( name.isEmpty() ) {
		// no file was selected.
		return;
	}

	QFile f( name );
	bool ok = f.open( IO_ReadOnly );
	
	if( !ok ) {
		QString errormsg = i18n( "Couldn't Read File:" );
		errormsg += name;

		KMsgBox::message( 0, i18n( "File Read Error" ), errormsg );

		return;
	}

	QString buffer( 1024 );

	_editor->setText( "" );

	while( !f.atEnd() ) {
		f.readBlock( buffer.data(), 1024 );
		_editor->append( buffer );
	}

	f.close();
	_fileName	= name;
	_textChanged	= false;
}

void KPadWidget::quit()
{
	if( _textChanged ) {
		int result = KMsgBox::yesNoCancel( 0, 
			i18n( "File has changed" ),
			i18n( "Save file before exit?" ) );

		switch ( result ) {
			case 1:		save();		// Yes
					break;

			case 2:		break;		// No

			case 3:		return;		// Cancel

			default:	break;
		}
	}

	kapp->quit();
}

void KPadWidget::setDirty()
{
	_textChanged = true;
}


int main( int argc, char **argv )
{
	KApplication app( argc, argv );

	KPadWidget *editor = new KPadWidget;

	app.setMainWidget( editor );

	editor->show();

	return app.exec();
}

#include"kpad.moc"

