#!/usr/bin/env python

# A simple application.


import sys, string
from qt import *


fileopen = [
    '16 13 5 1',
    '. c #040404',
    '# c #808304',
    'a c None',
    'b c #f3f704',
    'c c #f3f7f3',
    'aaaaaaaaa...aaaa',
    'aaaaaaaa.aaa.a.a',
    'aaaaaaaaaaaaa..a',
    'a...aaaaaaaa...a',
    '.bcb.......aaaaa',
    '.cbcbcbcbc.aaaaa',
    '.bcbcbcbcb.aaaaa',
    '.cbcb...........',
    '.bcb.#########.a',
    '.cb.#########.aa',
    '.b.#########.aaa',
    '..#########.aaaa',
    '...........aaaaa'
]

filesave = [
    '14 14 4 1',
    '. c #040404',
    '# c #808304',
    'a c #bfc2bf',
    'b c None',
    '..............',
    '.#.aaaaaaaa.a.',
    '.#.aaaaaaaa...',
    '.#.aaaaaaaa.#.',
    '.#.aaaaaaaa.#.',
    '.#.aaaaaaaa.#.',
    '.#.aaaaaaaa.#.',
    '.##........##.',
    '.############.',
    '.##.........#.',
    '.##......aa.#.',
    '.##......aa.#.',
    '.##......aa.#.',
    'b.............'
]

fileprint = [
    '16 14 6 1',
    '. c #000000',
    '# c #848284',
    'a c #c6c3c6',
    'b c #ffff00',
    'c c #ffffff',
    'd c None',
    'ddddd.........dd',
    'dddd.cccccccc.dd',
    'dddd.c.....c.ddd',
    'ddd.cccccccc.ddd',
    'ddd.c.....c....d',
    'dd.cccccccc.a.a.',
    'd..........a.a..',
    '.aaaaaaaaaa.a.a.',
    '.............aa.',
    '.aaaaaa###aa.a.d',
    '.aaaaaabbbaa...d',
    '.............a.d',
    'd.aaaaaaaaa.a.dd',
    'dd...........ddd'
]

document = [
"12 16 6 1",
" 	c #040404",
".	c None",
"X	c white",
"o	c #808304",
"O	c black",
"+	c #f3f7f3",
"       .....",
" XXXXX  ....",
" XXXXX X ...",
" XXXXX XX ..",
" XooXX    O.",
" X+XXX+XXXO.",
" XXXXXXXXXO.",
" XoooXooXXO.",
" XXXXXXXXXO.",
" XXXXXXXXXO.",
" XoXXoooXXO.",
" XXXXXXXXXO.",
"OXXXXXXXXXO.",
"OXXXXXXXXXO.",
"OOOOOOOOOOO.",
"............"
]

fileOpenText = \
'''<img source="fileopen">
Click this button to open a <em>new file</em>.<br><br>
You can also select the <b>Open</b> command from the <b>File</b> menu.'''

fileSaveText = \
'''Click this button to save the file you are editing.<br><br>
You will be prompted for a filename.<br><br>
You can also select the <b>Save</b> command from the <b>File</b> menu.'''

filePrintText = \
'''Click this button to print the file you are editing.<br><br>
You can also select the <b>Print</b> command from the <b>File</b> menu.'''

True=1
False=0

class ApplicationWindow(QMainWindow):
    	def __init__(self):
        	QMainWindow.__init__(self,None,'example application main window',Qt.WDestructiveClose)

        	self.filename = QString.null
        	self.printer = QPrinter()

        	self.fileTools = QToolBar(self,'file operations')

        	openIcon = QPixmap(fileopen)
        	self.fileOpen = QToolButton(QIconSet(openIcon),'Open File',QString.null,self.load,self.fileTools,'open file')

       	 	saveIcon = QPixmap(filesave)
       	 	self.fileSave = QToolButton(QIconSet(saveIcon),'Save File',QString.null,self.save,self.fileTools,'save file')
       	 	printIcon = QPixmap(fileprint)
        	self.filePrint = QToolButton(QIconSet(printIcon),'Print File',QString.null,self.printDoc,self.fileTools,'print file')

        	QWhatsThis.whatsThisButton(self.fileTools)

        	QWhatsThis.add(self.fileOpen,fileOpenText)
        	QMimeSourceFactory.defaultFactory().setPixmap('fileopen',openIcon)
        	QWhatsThis.add(self.fileSave,fileSaveText)
        	QWhatsThis.add(self.filePrint,filePrintText)

        	self.file = QPopupMenu(self)
        	self.menuBar().insertItem('&File',self.file)

        	self.file.insertItem('&New',self.newDoc,Qt.CTRL + Qt.Key_N)

        	id = self.file.insertItem(QIconSet(openIcon),'&Open',self.load,Qt.CTRL + Qt.Key_O)
        	self.file.setWhatsThis(id,fileOpenText)

        	id = self.file.insertItem(QIconSet(saveIcon),'&Save',self.save,Qt.CTRL + Qt.Key_S)
        	self.file.setWhatsThis(id,fileSaveText)

        	id = self.file.insertItem('Save &as',self.saveAs)
        	self.file.setWhatsThis(id,fileSaveText)

        	self.file.insertSeparator()

        	id = self.file.insertItem(QIconSet(printIcon),'&Print',self.printDoc,Qt.CTRL + Qt.Key_P)
        	self.file.setWhatsThis(id,filePrintText)

        	self.file.insertSeparator()

        	self.file.insertItem('&Close',self,SLOT('close()'),Qt.CTRL + Qt.Key_W)
        	self.file.insertItem('&Quit',qApp,SLOT('closeAllWindows()'),Qt.CTRL + Qt.Key_Q)

        	self.menuBar().insertSeparator()
		self.windows = QPopupMenu( self )
    		self.windows.setCheckable( True )
    		self.connect( self.windows, SIGNAL( "aboutToShow()" ),
	     	self.windowsMenuAboutToShow )
    		self.menuBar().insertItem( "&Windows", self.windows )

		self.help = QPopupMenu(self)
		self.menuBar().insertSeparator()
        	self.menuBar().insertItem('&Help',self.help)

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

    		self.menuBar().insertSeparator()

    		self.vb = QVBox( self )
    		self.vb.setFrameStyle( QFrame.StyledPanel | QFrame.Sunken )
    		self.ws = QWorkspace( self.vb )
    		self.ws.setScrollBarsEnabled( True )
    		self.setCentralWidget( self.vb )

        	self.statusBar().message('Ready',2000)
        	#self.resize(450,600)

	def newDoc(self):
 	    	w = MDIWindow( self.ws, "", Qt.WDestructiveClose )
    	    	self.connect( w, PYSIGNAL( "message" ), self.statusBar(), SLOT( "message(const QString&, int )") )
    	    	w.setCaption("unnamed document")
    	    	w.setIcon( QPixmap(document) )
    	    	# show the very first window in maximized mode
    	    	if len(self.ws.windowList())==0:
			w.showMaximized()
    	    	else:
			w.show()
    	    	return w

	def load(self):
    	    	fn = QFileDialog.getOpenFileName( QString.null, QString.null, self )
    	    	if not fn.isEmpty():
			w = self.newDoc()
			w.load( fn )
     	    	else:
			self.statusBar().message( "Loading aborted", 2000 )

	def save(self):
        	m = self.ws.activeWindow()
    		if ( m ):
			m.save()

	def saveAs(self):
        	m = self.ws.activeWindow()
    		if ( m ):
			m.saveAs()


	def printDoc(self):
        	m = self.ws.activeWindow()
    		if ( m ):
			m.printDoc( self.printer )

	def closeWindow(self):
        	m = self.ws.activeWindow()
    		if ( m ):
			m.close()

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

	def aboutQt(self):
   		QMessageBox.aboutQt( self, "Qt Application Example" )


	def windowsMenuAboutToShow(self):
    		self.windows.clear()
        	cascadeId = self.windows.insertItem("&Cascade", self.ws, SLOT("cascade() ") )
        	tileId = self.windows.insertItem("&Tile", self.ws, SLOT("tile()" ) )
    		if  len(self.ws.windowList())==0 :
			self.windows.setItemEnabled( cascadeId, False )
			self.windows.setItemEnabled( tileId, False )
    		self.windows.insertSeparator()
    		windows = self.ws.windowList()
		cnt=0
		for i in windows:
			id =self.windows.insertItem(i.caption(),self.windowsMenuActivated )
			self.windows.setItemParameter( id, cnt );
			self.windows.setItemChecked( id, self.ws.activeWindow() == i )
			cnt=cnt+1

	def windowsMenuActivated(self,sid ):
        	w = self.ws.windowList().at( id )
    		if ( w ):
			w.showNormal()
    			w.setFocus()


class MDIWindow( QMainWindow):
	def __init__(self,parent, name, wflags ):
    		QMainWindow.__init__(self,parent, name, wflags )
    		self.mmovie = 0
    		self.medit = QMultiLineEdit( self )
    		self.setFocusProxy( self.medit )
    		self.setCentralWidget( self.medit );


	def load(self, fn ):
    		self.filename  = fn
    		self.f=QFile( self.filename )
    		if not self.f.open( IO_ReadOnly ):
			return

    		if fn.contains(".gif"):
			tmp=QWidget(self)
			self.setFocusProxy(tmp)
			self.setCentralWidget(tmp)
			self.medit.hide()
			del self.medit
			qm=QMovie(fn)
			#ifdef Q_WS_QWS // temporary speed-test hack
			#qm->setDisplayWidget(tmp);
			#endif
			tmp.setBackgroundMode(QWidget.NoBackground)
			tmp.show()
			self.mmovie=qm
    		else :
			self.mmovie = 0
			t=QTextStream(self.f)
			s = t.read()
			self.medit.setText( s )
			self.f.close()
    		self.setCaption( self.filename )
		self.emit(PYSIGNAL( "message"),(QString("Loaded document %1").arg(self.filename),2000 ))

	def save(self):
    		if self.filename.isEmpty():
        		self.saveAs()
        		return
    		text = self.medit.text()
		output=open(str(self.filename),'w')
		output.write(str(text))
        	#emit message( QString("Could not write to %1").arg(filename), 2000 );
        	#return
		output.close()
		self.setCaption(self.filename)
		self.emit(PYSIGNAL( "message"),(QString("File %1 saved").arg(self.filename),2000 ))

	def saveAs(self):
		fn = QFileDialog.getSaveFileName( self.filename, QString.null, self )
    		if not fn.isEmpty():
        		self.filename = fn
        		self.save()
    		else :
			self.emit(PYSIGNAL( "message"),(QString("Saving aborted"),2000 ))

	def printDoc(self,printer):
        	Margin = 10
        	pageNo = 1

        	if printer.setup(self):
			self.emit(PYSIGNAL( "message"),(QString("Printing..."),2000 ))
            		p = QPainter()
            		p.begin(printer)
            		p.setFont(self.medit.font())
            		yPos = 0
            		fm = p.fontMetrics()
            		metrics = QPaintDeviceMetrics(printer)

            		for i in range(self.medit.numLines()):
                		if Margin + yPos > metrics.height() - Margin:
                    			pageNo = pageNo + 1
					self.emit(PYSIGNAL( "message"),(QString("Printing (page %1) ...").arg(pageNo),2000 ))
					printer.newPage()
                    			yPos = 0

                		p.drawText(Margin,Margin + yPos,metrics.width(),fm.lineSpacing(),Qt.ExpandTabs | Qt.DontClip,self.medit.textLine(i))
                		yPos = yPos + fm.lineSpacing()

            		p.end()
			self.emit(PYSIGNAL( "message"),(QString("Printing completed"),2000 ))
        	else:
			self.emit(PYSIGNAL( "message"),(QString("Printing aborted"),2000 ))

if __name__=='__main__':
	a = QApplication(sys.argv)
	mw = ApplicationWindow()
	mw.setCaption("PyQt Example - Multiple Documents Interface (MDI)")
	mw.show()
	a.connect(a, SIGNAL('lastWindowClosed()'), a, SLOT('quit()'))
	a.exec_loop()
