labelme.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/env python
  2. # -*- coding: utf8 -*-
  3. import re
  4. import sys
  5. from collections import defaultdict
  6. from PyQt4.QtGui import *
  7. from PyQt4.QtCore import *
  8. __appname__ = 'labelme'
  9. ### Utility functions and classes.
  10. def action(parent, text, slot=None, shortcut=None, icon=None,
  11. tip=None, checkable=False):
  12. """Create a new action and assign callbacks, shortcuts, etc."""
  13. a = QAction(text, parent)
  14. if icon is not None:
  15. a.setIcon(QIcon(u':/%s' % icon))
  16. if shortcut is not None:
  17. a.setShortcut(shortcut)
  18. if tip is not None:
  19. a.setToolTip(tip)
  20. a.setStatusTip(tip)
  21. if slot is not None:
  22. a.triggered.connect(slot)
  23. if checkable:
  24. a.setCheckable(True)
  25. return a
  26. def add_actions(widget, actions):
  27. for action in actions:
  28. if action is None:
  29. widget.addSeparator()
  30. else:
  31. widget.addAction(action)
  32. class WindowMixin(object):
  33. def menu(self, title, actions=None):
  34. menu = self.menuBar().addMenu(title)
  35. if actions:
  36. add_actions(menu, actions)
  37. return menu
  38. def toolbar(self, title, actions=None):
  39. toolbar = QToolBar(title)
  40. toolbar.setObjectName(u'%sToolBar' % title)
  41. #toolbar.setOrientation(Qt.Vertical)
  42. toolbar.setContentsMargins(0,0,0,0)
  43. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  44. toolbar.layout().setContentsMargins(0,0,0,0)
  45. if actions:
  46. add_actions(toolbar, actions)
  47. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  48. return toolbar
  49. class MainWindow(QMainWindow, WindowMixin):
  50. def __init__(self):
  51. super(MainWindow, self).__init__()
  52. self.setWindowTitle(__appname__)
  53. self.setContentsMargins(0, 0, 0, 0)
  54. # Main widgets.
  55. self.label = QLineEdit(u'Hello world, مرحبا ، العالم, Γεια σου κόσμε!')
  56. self.dock = QDockWidget(u'Label', parent=self)
  57. self.dock.setObjectName(u'Label')
  58. self.dock.setWidget(self.label)
  59. self.imageWidget = QLabel()
  60. self.imageWidget.setAlignment(Qt.AlignCenter)
  61. self.imageWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
  62. self.addDockWidget(Qt.BottomDockWidgetArea, self.dock)
  63. self.setCentralWidget(self.imageWidget)
  64. # Actions
  65. quit = action(self, '&Quit', self.close, 'Ctrl+Q', u'Exit application')
  66. labl = self.dock.toggleViewAction()
  67. labl.setShortcut('Ctrl+L')
  68. add_actions(self.menu('&File'), (labl, None, quit))
  69. add_actions(self.toolbar('Tools'), (labl, None, quit,))
  70. self.statusBar().showMessage('%s started.' % __appname__)
  71. self.statusBar().show()
  72. # Application state.
  73. self.filename = ''
  74. self.recent_files = []
  75. # TODO: Could be completely declarative.
  76. # Restore application settings.
  77. types = {
  78. 'filename': QString,
  79. 'recent-files': QStringList,
  80. 'window/size': QSize,
  81. 'window/position': QPoint,
  82. 'window/geometry': QByteArray,
  83. # Docks and toolbars:
  84. 'window/state': QByteArray,
  85. }
  86. self.settings = settings = Settings(types)
  87. self.recent_files = settings['recent-files']
  88. size = settings.get('window/size', QSize(600, 500))
  89. position = settings.get('window/position', QPoint(0, 0))
  90. self.resize(size)
  91. self.move(position)
  92. # or simply:
  93. #self.restoreGeometry(settings['window/geometry']
  94. self.restoreState(settings['window/state'])
  95. # The file menu has default dynamically generated entries.
  96. self.updateFileMenu()
  97. # Since loading the file may take some time, make sure it runs in the background.
  98. self.queueEvent(self.loadFile)
  99. def queueEvent(self, function):
  100. QTimer.singleShot(0, function)
  101. def loadFile(self, filename=None):
  102. """Load the specified file, or the last opened file if None."""
  103. if filename is None:
  104. filename = self.settings['filename']
  105. # FIXME: Load the actual file here.
  106. if QFile.exists(filename):
  107. # Load image
  108. image = QImage(filename)
  109. if image.isNull():
  110. message = "Failed to read %s" % filename
  111. else:
  112. message = "Loaded %s" % os.path.basename(unicode(filename))
  113. self.showImage()
  114. self.image = image
  115. self.filename = filename
  116. self.statusBar().showMessage(message)
  117. def showImage(self):
  118. if self.image.isNull():
  119. return
  120. self.imageWidget.setPixmap(QPixmap.fromImage(self.image))
  121. def closeEvent(self, event):
  122. # TODO: Make sure changes are saved.
  123. s = self.settings
  124. s['filename'] = self.filename if self.filename else QString()
  125. s['window/size'] = self.size()
  126. s['window/position'] = self.pos()
  127. s['window/state'] = self.saveState()
  128. #s['window/geometry'] = self.saveGeometry()
  129. def updateFileMenu(self):
  130. """Populate menu with recent files."""
  131. class Settings(object):
  132. """Convenience dict-like wrapper around QSettings."""
  133. def __init__(self, types=None):
  134. self.data = QSettings()
  135. self.types = defaultdict(lambda: QVariant, types if types else {})
  136. def __setitem__(self, key, value):
  137. t = self.types[key]
  138. self.data.setValue(key,
  139. t(value) if not isinstance(value, t) else value)
  140. def __getitem__(self, key):
  141. return self._cast(key, self.data.value(key))
  142. def get(self, key, default=None):
  143. return self._cast(key, self.data.value(key, default))
  144. def _cast(self, key, value):
  145. # XXX: Very nasty way of converting types to QVariant methods :P
  146. t = self.types[key]
  147. if t != QVariant:
  148. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  149. return method(value)
  150. return value
  151. def main(argv):
  152. """Standard boilerplate Qt application code."""
  153. app = QApplication(argv)
  154. app.setApplicationName(__appname__)
  155. win = MainWindow()
  156. win.show()
  157. return app.exec_()
  158. if __name__ == '__main__':
  159. sys.exit(main(sys.argv))