labelme.py 6.3 KB

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