=begin
/****************************************************************************
** $Id: qt/examples/mdi/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
#include "application.h"
#include <qworkspace.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>
#include <qmenubar.h>
#include <qkeycode.h>
#include <qmovie.h>
#include <qmultilineedit.h>
#include <qfile.h>
#include <qfiledialog.h>
#include <qlabel.h>
#include <qstatusbar.h>
#include <qmessagebox.h>
#include <qprinter.h>
#include <qapplication.h>
#include <qpushbutton.h>
#include <qaccel.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qpaintdevicemetrics.h>
#include <qwhatsself.h>
#include <qobjectlist.h>
#include <qvbox.h>

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

require "qt2"
include Qt2

FileOpenText = "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
@@mdiWindow_id = 0
@@mdiWindows = []
def initialize()
    super( nil, "example application main window", WDestructiveClose )

    @fileTools = QToolBar.new( self, "file operations" )
    addToolBar( @fileTools, tr( "File Operations" ), Top, TRUE )

    openIcon = QPixmap.new( "fileopen.xpm" )
    fileOpen = QToolButton.new( openIcon, "Open File", QString::null, self, "load()", @fileTools, "open file" )

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

#ifndef QT_NO_PRINTER
    @printer = QPrinter.new

    printIcon = QPixmap.new( "fileprint.xpm" )
    filePrint = QToolButton.new( printIcon, "Print File", QString::null, self, "printFile()", @fileTools, "print file" )
    QWhatsThis::add( filePrint, FilePrintText )
#endif

    QWhatsThis::whatsThisButton( @fileTools )

    QWhatsThis::add( fileOpen, FileOpenText )
    QWhatsThis::add( fileSave, FileSaveText )

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

    @file.insertItem( "&New", self, "newDoc()", CTRL+Key_N )

    id = @file.insertItem( openIcon, "&Open",  self, "load()", CTRL+Key_O )
    @file.setWhatsThis( id, FileOpenText )

    id = @file.insertItem( saveIcon, "&Save",  self, "save()", CTRL+Key_S )
    @file.setWhatsThis( id, FileSaveText )
    id = @file.insertItem( "Save &as...", self, "saveAs()" )
    @file.setWhatsThis( id, FileSaveText )
#ifndef QT_NO_PRINTER
    @file.insertSeparator()
    id = @file.insertItem( printIcon, "&Print",  self, "printFile()", CTRL+Key_P )
    @file.setWhatsThis( id, FilePrintText )
#endif
    @file.insertSeparator()
    @file.insertItem( "&Close", self, "closeWindow()", CTRL+Key_W )
    @file.insertItem( "&Quit", QApplication::qApp, "quit()", CTRL+Key_Q )

    @windowsMenu = QPopupMenu.new( self )
    @windowsMenu.setCheckable( TRUE )
    connect( @windowsMenu, QSIGNAL( "aboutToShow()" ),  self, "windowsMenuAboutToShow()"  )
    menuBar().insertItem( "&Windows", @windowsMenu )

    menuBar().insertSeparator()
    @help = QPopupMenu.new( self )
    menuBar().insertItem( "&Help", @help )

    @help.insertItem( "&About", self, "about()", Qt::Key_F1)
    @help.insertItem( "About&Qt", self, "aboutQt()")
    @help.insertSeparator()
    @help.insertItem( "What's &This", self, "whatsThis()", Qt::SHIFT+Qt::Key_F1)

    vb = QVBox.new( self )
    vb.setFrameStyle( QFrame::StyledPanel | QFrame::Sunken )
    @ws = QWorkspace.new( vb )
    setCentralWidget( vb )

    statusBar().message( "Ready", 2000 )
end

def showMessage( array )
   statusBar().message(array[0],array[1])
end

def getMDIWindow( mdiw)
    if(!(mdiw.nil?))
      id = mdiw.name
      @@mdiWindows.each{ | w |
         if(w.name == id)
            return w
         end
      }
     end
      nil
end

def newDoc()

    w = MDIWindow.new( @ws, "id:#{@@mdiWindow_id}", WDestructiveClose )
    @@mdiWindow_id += 1
    @@mdiWindows.push(w)
    connect( w.message, self, "showMessage") #statusBar(), QSLOT( "message(const QString&, int )") )
    w.setCaption("unnamed document")
    w.setIcon( QPixmap.new("document.xpm") )
    #// show the very first window in maximized mode
    if ( @ws.windowList().isEmpty() )
	w.showMaximized()
    else
	w.show()
    end
    return w
end

def load()

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

def save()

    m = @ws.activeWindow()
    mw = getMDIWindow(m)
    if ( !mw.nil? )
	mw.save()
    end
end


def saveAs()

    m = @ws.activeWindow()
    mw = getMDIWindow(m)
    if ( !mw.nil? )
	mw.saveAs()
    end
end


def printFile()

#ifndef QT_NO_PRINTER
    m = @ws.activeWindow()
    mw = getMDIWindow(m)
    if ( !mw.nil? )
	mw.print( @printer )
    end
#endif
end


def closeWindow()

    m = @ws.activeWindow()
    mw = getMDIWindow(m)
    if ( !mw.nil? )
p "close MDIWindow: #{m.id},#{m.name()}"
	mw.close()
    end
end

def about()

    QMessageBox::about( self, "Qt Application Example","This example demonstrates simple use of\n "+"Qt's Multiple Document Interface (MDI).")
end


def aboutQt()

    QMessageBox::aboutQt( self, "Qt Application Example" )
end
WMA = 'windowsMenuActivated( int )'

def windowsMenuAboutToShow()
    @windowsMenu.clear()
    cascadeId = @windowsMenu.insertItem("&Cascade", @ws, "cascade()")
    tileId = @windowsMenu.insertItem("&Tile", @ws, "tile()")
    if ( @ws.windowList().isEmpty() )
        @windowsMenu.setItemEnabled( cascadeId, FALSE )
        @windowsMenu.setItemEnabled( tileId, FALSE )
    end
    @windowsMenu.insertSeparator()
    windows = @ws.windowList()
    for i in 0..(windows.count() - 1) #( int i = 0 i < int(windows.count()) ++i )
#GC.start
        id = @windowsMenu.insertItem(windows.at(i).caption(), self, "windowsMenuActivated(int)",0,i)
        @windowsMenu.setItemParameter( id, i )
        @windowsMenu.setItemChecked( id, (@ws.activeWindow().name == windows.at(i).name) )
    end
end

def windowsMenuActivated( id )
print "windowsMenuActivated called id = #{id}\n"

    w = @ws.windowList().at( id )
    if ( w )
	w.setFocus()
    end
end

end


class MDIWindow < QMainWindow

def initialize(  parent,  name,  wflags )
    super( parent, name, wflags )
    @mmovie = 0
    @medit = QMultiLineEdit.new( self )
    setFocusProxy( @medit )
    setCentralWidget( @medit )
    @message = RSignal.new("Object")
p "MDIWindow created: #{id},#{self.name()}"
end

def message
   @message
end


def loadFile(  fn )

    @filename  = fn
    f = File::open( @filename.to_str,"r" )
    if  f.nil?
	   return
   end

    if(fn.to_str.include?("gif"))
	tmp=QWidget.new(self)
	setFocusProxy(tmp)
	setCentralWidget(tmp)
	@medit.hide()
	deleteQObj(@medit)
	qm=QRMovie.new(fn)
#ifdef _WS_QWS_ #// temporary speed-test hack
#	qm.setDisplayWidget(tmp)
#endif
	tmp.setBackgroundMode(QWidget::NoBackground)
	tmp.show()
	@mmovie=qm
    else
	@mmovie = 0
	@medit.setAutoUpdate( FALSE )
	@medit.clear()

	while ( !f.eof? )
	    s = f.gets
                 s.chop!
                 str = QString::fromLocal8Bit(s)
	    @medit.append( str )
	end

	f.close

	@medit.setAutoUpdate( TRUE )
	@medit.repaint()
             @medit.setEdited(false)	
    end
    setCaption( @filename )
#    emit message( QString("Loaded document %1").arg(@filename), 2000 )
    ar = [QString.new("Loaded document #{@filename.to_str}"),2000]
    message.sendWith(ar)
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 = @medit.text
    str = contents.local8Bit
    f .puts str.to_str
    f.close
    @medit.setEdited( false )

    setCaption( @filename )
    #emit message( QString.new( "File %1 saved" ).arg( @filename ), 2000 )
    ar = [QString.new("File #{@filename.to_str} saved"),2000]
    message.sendWith(ar)
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
       ar = [QString.new("Saving aborted"),2000]
       message.sendWith(ar)
    end
end

def print(  printer)
#ifndef QT_NO_PRINTER
    margin = 10
    pageNo = 1
     if ( printer.setup(self) ) 		#// printer dialog
             ar = [QString.new("Printing..."),0]
	message.sendWith(ar)
p "printer is #{printer.printerName.to_str}"
	p = QPainter.new
             if(!(p.begin( printer )))
                 return
             end
	p.setFont( @medit.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..(@medit.numLines - 1) #( int i = 0  i < @medit.numLines()  i++ )
	    if ( margin + yPos > metrics.height() - margin )
		msg = "Printing (page "
		msg += "#{pageNo =  pageNo + 1}"
		msg += ")..."
                          ar = [QString.new(msg),0]
		message.sendWith(ar)
		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,
			@medit.textLine( i ) )
	    yPos = yPos + fm.lineSpacing()
	end
	p.end()				#// send job to printer
	ar = [QString.new("Printing completed"),2000]
             message.sendWith(ar)
    else
	ar = [QString.new("Printing aborted"),2000]
             message.sendWith(ar)
    end
#endif
end


end


