#!/usr/bin/env python

import string
import sys
from qt import *

# icônes au format pixmap
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.............'
]

# liste des fenêtres ouvertes
# indispensable pour conserver
# les instances
# sans cela nos fenêtres seraient fermées
# dès leur ouverture
windowsList = []

# DP Commande
class EdCommand:
    def execute(self):
      pass

# DP Médiateur
class Mediator:
    def registerClipboard(self, clipboard):
      self.clipboard = clipboard

    def clear(self):
      qApp.clipboard().clear()
      self.clipboard.setText("")

    def registerTextView(self, textView):
      self.textView = textView

    def copy(self):
      if self.textView is not None:
        self.textView.copy()
        if self.clipboard is not None:
          self.clipboard.setText(qApp.clipboard().text())

    def cut(self):
      if self.textView is not None:
        self.textView.cut()
        if self.clipboard is not None:
          self.clipboard.setText(qApp.clipboard().text())

    def paste(self):
      if self.textView is not None:
        self.textView.paste()

# classe de base de nos boutons
class EdButton(QPushButton):
    def __init__(self, parent, mediator, name):
      QPushButton.__init__(self, name, parent)
      QObject.connect(self, SIGNAL("pressed()"), self.handlePress)
      self.mediator = mediator

    def handlePress(self):
      self.emit(PYSIGNAL("action"), (self, ))

# COPIER
class CopyButton(EdButton, EdCommand):
    def __init__(self, parent, mediator):
      EdButton.__init__(self, parent, mediator, "Copy")

    def execute(self):
      self.mediator.copy()

# COUPER
class CutButton(EdButton, EdCommand):
    def __init__(self, parent, mediator):
      EdButton.__init__(self, parent, mediator, "Cut")

    def execute(self):
      self.mediator.cut()

# COLLER
class PasteButton(EdButton, EdCommand):
    def __init__(self, parent, mediator):
      EdButton.__init__(self, parent, mediator, "Paste")

    def execute(self):
      self.mediator.paste()

# EFFACER
class ClearButton(EdButton, EdCommand):
    def __init__(self, parent, mediator):
      EdButton.__init__(self, parent, mediator, "Clear")

    def execute(self):
      self.mediator.clear()

# FENETRE PRINCIPALE

class EdMainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self, None, "QtEd", Qt.WDestructiveClose)

        # voici la zone de texte principale
        self.textView = QMultiLineEdit(self)
        self.setCentralWidget(self.textView)
        self.textView.setFocus()

        # nous créons ici la barre de menus
        # ainsi que la barre de statut
        self.menuBar   = self.menuBar()
        self.statusBar = self.statusBar()

        # initialisation des menus
        fileMenu = QPopupMenu(self)
        fileMenu.insertItem('&New',   self.newFile, Qt.CTRL + Qt.Key_N)
        fileMenu.insertItem('&Open',  self.open,    Qt.CTRL + Qt.Key_O)
        fileMenu.insertItem('&Save',  self.save,    Qt.CTRL + Qt.Key_S)
        fileMenu.insertSeparator()
        fileMenu.insertItem('&Close', self, SLOT('close()'),           Qt.CTRL + Qt.Key_W)
        fileMenu.insertItem('&Quit',  qApp, SLOT('closeAllWindows()'), Qt.CTRL + Qt.Key_Q)

        self.menuBar.insertItem('&File', fileMenu)

        # nous créons ensuite la barre d'outils
        toolBar = QToolBar(self)

        # ajout des boutons
        self.fileOpen = QToolButton(QPixmap(fileopen), 'Open File', 'Opens a new file', self.open, \
                                    toolBar, 'Open file')
        self.fileSave = QToolButton(QPixmap(filesave), 'Save File', 'Saves current file', self.save, \
                                    toolBar, 'Save file')

        ########################################################
        # MEDIATEUR
        ########################################################
        toolBar.addSeparator()

        self.med = Mediator()
        self.med.registerTextView(self.textView)

        self.textCopy  = CopyButton(toolBar,  self.med)
        self.textCut   = CutButton(toolBar,   self.med)
        self.textPaste = PasteButton(toolBar, self.med)
        self.textClear = ClearButton(toolBar, self.med)

        self.clipboard = QLineEdit(toolBar)
        self.med.registerClipboard(self.clipboard)

        QObject.connect(self.textCopy,  PYSIGNAL("action"), self.commandEvent)
        QObject.connect(self.textCut,   PYSIGNAL("action"), self.commandEvent)
        QObject.connect(self.textPaste, PYSIGNAL("action"), self.commandEvent)
        QObject.connect(self.textClear, PYSIGNAL("action"), self.commandEvent)
        ########################################################

        self.addToolBar(toolBar, "Main toolbar")
        self.statusBar.message("[New File]")

        self.fileName = QString.null

        # attribuons une taille spécifique
        self.resize(320, 240)

    def commandEvent(self, source):
      source.execute()

    def newFile(self):
      ed = EdMainWindow()
      ed.show()
      windowsList.append(ed)

    def open(self):
      file = QFileDialog.getOpenFileName(QString.null, QString.null, self)
      if file.isEmpty():
        self.statusBar.message('Loading aborted', 2000)
        return

      fileName = str(file)

      self.textView.setAutoUpdate(0)
      self.textView.clear()

      try:
        fstream = open(fileName, 'r')
      except:
        return

      for line in fstream.readlines():
        self.textView.append(string.rstrip(line))

      fstream.close()

      self.textView.setAutoUpdate(1)
      self.textView.repaint()
      self.textView.setEdited(0)
      self.statusBar.message('Loaded document %s' % (fileName),2000) 

    def save(self):
      if self.fileName.isEmpty():
        self.saveAs()
        return

      try:
        f = open(str(self.fileName), 'w+')
      except:
        self.statusBar.message('Could not write to %s' % (self.fileName), 2000)
        return

      f.write(str(self.textView.text()))
      f.close()

      self.textView.setEdited(0)
      self.statusBar.message('File %s saved' % (self.fileName), 2000) 

    def saveAs(self):
      file = QFileDialog.getSaveFileName(QString.null, QString.null, self)
      if not file.isEmpty():
        self.fileName = file
        self.save()
      else:
        self.statusBar.message('Saving aborted', 2000) 

# création de l'application
app = QApplication(sys.argv)

# création du widget principal
mainWindow = EdMainWindow()

# exécution de l'application
mainWindow.show()
app.connect(app, SIGNAL('lastWindowClosed()'), app, SLOT('quit()'))
app.exec_loop()

# fin du script qted.py 
