=begin
/****************************************************************************
** $Id: application_lib.rb,v 1.2 2001/01/23 01:11:30 horie Exp $
**
** Copyright (C) 1992-2000 Troll Tech 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
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
#    @e
#    @filename
    super 0, "example application main window", WDestructiveClose
#    @printer = QPrinter.new
#    QPixmap openIcon, saveIcon, printIcon

    @fileTools = QToolBar.new( self, "file operations" )
    @fileTools.setLabel( tr( "File Operations" ) )
    @openIcon = QPixmap.new( "fileopen.xpm" )
    fileOpen = QToolButton.new( @openIcon, "Open File", "", self, "load", @fileTools, "open file" )

    @saveIcon = QPixmap.new( "filesave.xpm" )
    fileSave = QToolButton.new( @saveIcon, "Save File", "",self, "save", @fileTools, "save file" )

    @printIcon = QPixmap.new( "fileprint.xpm" )
    filePrint = QToolButton.new( @printIcon, "Print File", "",self, "printDocument", @fileTools, "print file" )

    QWhatsThis::whatsThisButton( @fileTools )

    QWhatsThis::add( fileOpen, FileOpenText )
    QMimeSourceFactory::defaultFactory().setPixmap( "fileopen", @openIcon )
    QWhatsThis::add( fileSave, FileSaveText )
    QWhatsThis::add( filePrint, FilePrintText )

    file = QPopupMenu.new(  )
    i = menuBar().insertItem( "&File", file )

    file.insertItem("&New", self, "newDoc", Qt::CTRL+Key_N )
    @id0 =file.insertItem( @openIcon, "&Open",self, "load", Qt::CTRL+Key_O )
    file.setWhatsThis( @id0, FileOpenText )
    @id1 = file.insertItem( @saveIcon, "&Save",self, "save", Qt::CTRL+Key_S )
    file.setWhatsThis( @id1, FileSaveText )
    @id2 = file.insertItem("Save &as...", self, "saveAs")
    file.setWhatsThis( @id2, FileSaveText )
    file.insertSeparator()
    @id3 = file.insertItem( @printIcon,"&Print",self, "printDocument", Qt::CTRL+Key_P )
    file.setWhatsThis( @id3, FilePrintText )
    file.insertSeparator()
    file.insertItem("&Close", self, "close", CTRL+Key_W )
    i = file.insertItem("&Quit", QApplication::qApp, "closeAllWindows", Qt::CTRL+Key_Q )

    menuBar().insertSeparator()
    help = QPopupMenu.new(  )

    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 )

    @e = QMultiLineEdit.new( self, "editor" )
    @e.setFocus()
    setCentralWidget( @e )
    statusBar().message("Ready", 2000 )
    resize( 500, 300 )
    catchEvent
end


def newDoc()

    ed = ApplicationWindow.new
    ed.show
end

def load()

    fn = QFileDialog::getOpenFileName( "", "",
					       self)     #QString::null cause seg. fault.
    if ( !fn.isEmpty() )
    @filename = fn
	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()
#    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 ).local8Bit.to_str )
	    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
