=begin
/****************************************************************************
** $Id: qt/examples/action/application.cpp   2.2.2   edited 2000-08-31 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
=end
require "qt2"
include Qt2
#include "application.h"

#include <qimage.h>
#include <qpixmap.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qkeycode.h>
#include <qmultilineedit.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qprinter.h>
#include <qapplication.h>
#include <qaccel.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qwhatsself.h>
#include <qaction.h>

#include "filesave.xpm"
#include "fileopen.xpm"
#include "fileprint.xpm"

FileOpenText = "<img source=\"fileopen\"> "+ "Click self button to open a <em>new file</em>. <br><br>"+ "You can also select the <b>Open command</b> from the File menu."
FileSaveText = "Click self button to save the file you are "+ "editing.  You will be prompted for a file name.\n\n"+ "You can also select the Save command from the File menu.\n\n"+ "Note that implementing self function is left as an exercise for the reader."
FilePrintText = "Click self button to print the file you "+ "are editing.\n\n"+ "You can also select the Print command from the File menu."

class ApplicationWindow < QMainWindow
   def initialize
    super ( 0, "example application main window", WDestructiveClose )
    fileopen = "fileopen.xpm"
    filesave = "filesave.xpm"
    filenew = "filenew.xpm"
    fileprint = "fileprint.xpm"
    
    #// create a printer
    
    @printer = QPrinter.new

    
    #// create user interface actions
    
    #QAction *fileNewAction, *fileOpenAction, *fileSaveAction,
#	* fileSaveAsAction, *filePrintAction, *fileCloseAction,
#	*fileQuitAction
    
    fileNewAction = QAction.new( "New", "&New", CTRL+Key_N, self, "new" )
    Qt2::connect( fileNewAction, QSIGNAL( "activated()" ) , self, "newDoc" )
    
    fileOpenAction = QAction.new( "Open File", QPixmap.new( fileopen ), "&Open", CTRL+Key_O, self, "open" )
    connect( fileOpenAction, QSIGNAL( "activated()" ) , self, "load" )
    QMimeSourceFactory::defaultFactory().setPixmap( "fileopen", QPixmap.new( fileopen ) )
    fileOpenAction.setWhatsThis( FileOpenText )
    
    fileSaveAction = QAction.new( "Save File", QPixmap.new( filesave ), "&Save", CTRL+Key_S, self, "save" )
    connect( fileSaveAction, QSIGNAL( "activated()" ) , self, "save" )
    fileSaveAction.setWhatsThis( FileSaveText )

    fileSaveAsAction = QAction.new( "Save File As", "Save &as", 0,  self, "save as" )
    connect( fileSaveAsAction, QSIGNAL( "activated()" ) , self, "saveAs" )
    fileSaveAsAction.setWhatsThis( FileSaveText )
    
    filePrintAction = QAction.new( "Print File", QPixmap.new( fileprint ), "&Print", CTRL+Key_P, self, "print" )
    connect( filePrintAction, QSIGNAL( "activated()" ) , self, "printDocument" )
    filePrintAction.setWhatsThis( FilePrintText )
    
    fileCloseAction = QAction.new( "Close", "&Close", CTRL+Key_W, self, "close" )
    connect( fileCloseAction, QSIGNAL( "activated()" ) , self, "close" )

    fileQuitAction = QAction.new( "Quit", "&Quit", CTRL+Key_Q, self, "quit" )
    connect( fileQuitAction, QSIGNAL( "activated()" ) , QApplication::qApp, QSLOT( "closeAllWindows()" ) )

    
    #// populate a tool bar with some actions
    
    fileTools = QToolBar.new( self, "file operations" )
    fileTools.setLabel( tr( "File Operations" ) )
    fileOpenAction.addTo( fileTools )
    fileSaveAction.addTo( fileTools )
    #filePrintAction.addTo( fileTools )
    QWhatsThis::whatsThisButton( fileTools )

    
    #// popuplate a menu with all actions
    
    file = QPopupMenu.new( self )
    menuBar().insertItem( "&File", file )
    fileNewAction.addTo( file )
    fileOpenAction.addTo( file )
    fileSaveAction.addTo( file )
    fileSaveAsAction.addTo( file )
    file.insertSeparator()
    filePrintAction.addTo( file )
    file.insertSeparator()
    fileCloseAction.addTo( file )
    fileQuitAction.addTo( file )

    
    #// add a help menu
    
    help = QPopupMenu.new( self )
    menuBar().insertSeparator()
    menuBar().insertItem( "&Help", help )
    help.insertItem( "&About", self, "about", Key_F1 )
    help.insertItem( "About &Qt", self, "aboutQt" )
    help.insertSeparator()
    help.insertItem( "What's &This", self, "whatsThis", SHIFT+Key_F1 )

    
    #// create and define the central widget
    
    @e = QMultiLineEdit.new( self, "editor" )
    @e.setFocus()
    setCentralWidget( @e )
    statusBar().message( "Ready", 2000 )
    resize( 450, 600 )
end



def newDoc()

    ed = ApplicationWindow.new
    ed.show()
end

def load()

    fn = QFileDialog::getOpenFileName( QString::null, QString::null, self)
    if ( !fn.isEmpty() )
	loadFile( fn )
    else
	statusBar().message( "Loading aborted", 2000 )
    end
end

def loadFile( fileName )
    f = File::open( fileName.to_str,"r" )
    if  f.nil?
	   return
   end
    @e.setAutoUpdate( false )
    @e.clear()
    while (!f.eof?)
      s = f.gets
      s.chop!
      str = QString::fromLocal8Bit(s)
      @e.append(str)
    end
    f.close

    @e.setAutoUpdate( true )
    @e.repaint
    @e.setEdited( false )
    setCaption( fileName )
    s = ""
    s += "Loaded document #{fileName.to_str}"
    statusBar().message(s, 2000 )
end


def save()

    if ( @filename == "" or @filename.nil?)
	saveAs()
	return
   end

    f = File::open( @filename.to_str,"w+" )
    if ( f.nil?)
	statusBar().message( "Could not write to #{@filename.to_str}",2000 )
	return
    end
    contents = @e.text
    str = contents.local8Bit
    f .puts str.to_str
    f.close
    @e.setEdited( false )

    setCaption( @filename )

    statusBar().message( "File #{@filename.to_str} saved" , 2000 )
end


def saveAs()
print "saveAs called\n"
#    fn = QFileDialog::getSaveFileName( QString::null, QString::null, self )
    fn = QFileDialog::getSaveFileName( "","", self )
    if ( !fn.isEmpty and fn.to_str != "" )
	@filename = fn
	save()
    else
	statusBar().message( "Saving aborted", 2000 )
    end
end

def printDocument

    margin = 10
    pageNo = 1
    printer = QPrinter.new
    if ( printer.setup(self) ) 		#// printer dialog
	statusBar().message( "Printing..." )
	p = QPainter.new
	if(!p.begin( printer ))			#// paint on printer
          return
        end
	p.setFont( @e.font() )
	yPos	= 0			#// y position for each line
	fm = p.fontMetrics()
	metrics = QPaintDeviceMetrics.new( printer ) #// need width/height
						#// of printer surface
	for i in 0..(@e.numLines)            #( int i = 0  i < e.numLines()  i++ )
	    if ( margin + yPos > metrics.height() - margin )
		    msg =  "Printing (page "
		    msg += "#{pageNo = pageNo + 1}"
		    msg += ")..."
		    statusBar().message(msg)
		    printer.newPage()		#// no more room on self page
		    yPos = 0			#// back to top of page
	    end
	    p.drawText( margin, margin + yPos,
		metrics.width(), fm.lineSpacing(),
		ExpandTabs | DontClip,
		@e.textLine( i ) )
	    yPos = yPos + fm.lineSpacing()
	end
	p.end()				#// send job to printer
	statusBar().message( "Printing completed", 2000 )
    else
	statusBar().message( "Printing aborted", 2000 )
    end

end

def closeEvent( ce )

    if ( !@e.edited() )
	ce.accept()
	return
    end

    case ( QMessageBox::information( self, "Qt Application Example","The document has been changed since "+"the last save.","Save Now", "Cancel", "Leave Anyway",0, 1 ) )
    when 0
	save()
	ce.accept()
    when 1
	ce.ignore()
    when 2
	ce.accept()
    else
	ce.ignore()
    end
end


def about()

    QMessageBox::about( self, "Qt Application Example","This example demonstrates simple use of "+"QMainWindow,\nQMenuBar and QToolBar.")
end


def aboutQt()

    QMessageBox::aboutQt( self, "Qt Application Example" )
end

end
