labelme.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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. import resources
  11. from lib import struct, newAction, addActions, labelValidator
  12. from shape import Shape, DEFAULT_LINE_COLOR, DEFAULT_FILL_COLOR
  13. from canvas import Canvas
  14. from zoomWidget import ZoomWidget
  15. from labelDialog import LabelDialog
  16. from colorDialog import ColorDialog
  17. from labelFile import LabelFile, LabelFileError
  18. from toolBar import ToolBar
  19. __appname__ = 'labelme'
  20. # FIXME
  21. # - [medium] Set max zoom value to something big enough for FitWidth/Window
  22. # - [medium] Disabling the save button prevents the user from saving to
  23. # alternate files. Either keep enabled, or add "Save As" button.
  24. # - [low] Label validation/postprocessing breaks with TAB.
  25. # TODO:
  26. # - [medium] Zoom should keep the image centered.
  27. # - [high] Label dialog options are vague.
  28. # - [high] Add 'Edit label' in context menu.
  29. # - [high] Add recently opened files list in File menu.
  30. # - [high] Escape should cancel editing mode if no point in canvas.
  31. # - [medium] Maybe have separate colors for different shapes, and
  32. # color the background in the label list accordingly (kostas).
  33. # - [medium] Highlight label list on shape selection and vice-verca.
  34. # - [medium] Add undo button for vertex addition.
  35. # - [medium,maybe] Support vertex moving.
  36. # - [low,easy] Add button to Hide/Show all labels.
  37. # - [low,maybe] Open images with drag & drop.
  38. # - [low,maybe] Preview images on file dialogs.
  39. # - [low,maybe] Sortable label list.
  40. # - [extra] Add beginner/advanced mode, where different settings are set for
  41. # the application, e.g. closable labels, different toolbuttons etc.
  42. # - Zoom is too "steppy".
  43. ### Utility functions and classes.
  44. class WindowMixin(object):
  45. def menu(self, title, actions=None):
  46. menu = self.menuBar().addMenu(title)
  47. if actions:
  48. addActions(menu, actions)
  49. return menu
  50. def toolbar(self, title, actions=None):
  51. toolbar = ToolBar(title)
  52. toolbar.setObjectName(u'%sToolBar' % title)
  53. #toolbar.setOrientation(Qt.Vertical)
  54. toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  55. if actions:
  56. addActions(toolbar, actions)
  57. self.addToolBar(Qt.LeftToolBarArea, toolbar)
  58. return toolbar
  59. class MainWindow(QMainWindow, WindowMixin):
  60. FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = range(3)
  61. def __init__(self, filename=None):
  62. super(MainWindow, self).__init__()
  63. self.setWindowTitle(__appname__)
  64. # Whether we need to save or not.
  65. self.dirty = False
  66. self._noSelectionSlot = False
  67. # Main widgets.
  68. self.label = LabelDialog(parent=self)
  69. self.labels = {}
  70. self.items = {}
  71. self.highlighted = None
  72. self.labelList = QListWidget()
  73. self.dock = QDockWidget(u'Polygon Labels', self)
  74. self.dock.setObjectName(u'Labels')
  75. self.dock.setWidget(self.labelList)
  76. self.zoomWidget = ZoomWidget()
  77. self.colorDialog = ColorDialog(parent=self)
  78. self.labelList.setItemDelegate(LabelDelegate())
  79. self.labelList.itemActivated.connect(self.highlightLabel)
  80. # Connect to itemChanged to detect checkbox changes.
  81. self.labelList.itemChanged.connect(self.labelItemChanged)
  82. self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
  83. self.canvas = Canvas()
  84. self.canvas.zoomRequest.connect(self.zoomRequest)
  85. scroll = QScrollArea()
  86. scroll.setWidget(self.canvas)
  87. scroll.setWidgetResizable(True)
  88. self.scrollBars = {
  89. Qt.Vertical: scroll.verticalScrollBar(),
  90. Qt.Horizontal: scroll.horizontalScrollBar()
  91. }
  92. self.canvas.scrollRequest.connect(self.scrollRequest)
  93. self.canvas.newShape.connect(self.newShape)
  94. self.canvas.shapeMoved.connect(self.setDirty)
  95. self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
  96. self.setCentralWidget(scroll)
  97. self.addDockWidget(Qt.RightDockWidgetArea, self.dock)
  98. # Actions
  99. action = partial(newAction, self)
  100. quit = action('&Quit', self.close,
  101. 'Ctrl+Q', 'quit', u'Quit application')
  102. open = action('&Open', self.openFile,
  103. 'Ctrl+O', 'open', u'Open image or label file')
  104. save = action('&Save', self.saveFile,
  105. 'Ctrl+S', 'save', u'Save labels to file', enabled=False)
  106. close = action('&Close', self.closeFile,
  107. 'Ctrl+K', 'close', u'Close current file')
  108. color1 = action('Polygon &Line Color', self.chooseColor1,
  109. 'Ctrl+C', 'color', u'Choose polygon line color')
  110. color2 = action('Polygon &Fill Color', self.chooseColor2,
  111. 'Ctrl+Shift+C', 'color', u'Choose polygon fill color')
  112. label = action('&New Polygon', self.newLabel,
  113. 'Ctrl+N', 'new', u'Start a new polygon', enabled=False)
  114. copy = action('&Copy Polygon', self.copySelectedShape,
  115. 'Ctrl+C', 'copy', u'Copy selected polygon', enabled=False)
  116. delete = action('&Delete Polygon', self.deleteSelectedShape,
  117. ['Ctrl+D', 'Delete'], 'delete', u'Delete', enabled=False)
  118. hide = action('&Hide Polygons', self.hideLabelsToggle,
  119. 'Ctrl+H', 'hide', u'Hide all polygons',
  120. checkable=True)
  121. zoom = QWidgetAction(self)
  122. zoom.setDefaultWidget(self.zoomWidget)
  123. zoomIn = action('Zoom &In', partial(self.addZoom, 10),
  124. 'Ctrl++', 'zoom-in', u'Increase zoom level')
  125. zoomOut = action('&Zoom Out', partial(self.addZoom, -10),
  126. 'Ctrl+-', 'zoom-out', u'Decrease zoom level')
  127. zoomOrg = action('&Original size', partial(self.setZoom, 100),
  128. 'Ctrl+=', 'zoom', u'Zoom to original size')
  129. fitWindow = action('&Fit Window', self.setFitWindow,
  130. 'Ctrl+F', 'fit-window', u'Zoom follows window size',
  131. checkable=True)
  132. fitWidth = action('Fit &Width', self.setFitWidth,
  133. 'Ctrl+W', 'fit-width', u'Zoom follows window width',
  134. checkable=True)
  135. self.zoomMode = self.MANUAL_ZOOM
  136. self.scalers = {
  137. self.FIT_WINDOW: self.scaleFitWindow,
  138. self.FIT_WIDTH: self.scaleFitWidth,
  139. }
  140. edit = action('&Modify Label', self.editLabelDialog,
  141. 'Ctrl+E', 'edit', u'Modify the label of the selected polygon')
  142. # Custom context menu for the canvas widget:
  143. addActions(self.canvas.menus[0], (label, edit, copy, delete))
  144. addActions(self.canvas.menus[1], (
  145. action('&Copy here', self.copyShape),
  146. action('&Move here', self.moveShape)))
  147. labels = self.dock.toggleViewAction()
  148. labels.setShortcut('Ctrl+L')
  149. # Context menu for the label
  150. editLabel = action('Edit &Label', self.editLabel,
  151. 'Ctrl+Return', 'edit', u'Modify this label')
  152. lmenu = QMenu()
  153. addActions(lmenu, (editLabel, delete))
  154. self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
  155. self.labelList.customContextMenuRequested.connect(self.popLabelListMenu)
  156. # Add the action to the main window, effectively making its shortcut glogal!
  157. self.addAction(editLabel)
  158. # Store actions for further handling.
  159. self.actions = struct(save=save, open=open, close=close,
  160. lineColor=color1, fillColor=color2,
  161. label=label, delete=delete, zoom=zoom, copy=copy,
  162. zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
  163. fitWindow=fitWindow, fitWidth=fitWidth)
  164. self.menus = struct(
  165. file=self.menu('&File'),
  166. edit=self.menu('&Polygons'),
  167. view=self.menu('&View'),
  168. labelList=lmenu)
  169. addActions(self.menus.file, (open, save, close, quit))
  170. addActions(self.menus.edit, (label, color1, color2))
  171. addActions(self.menus.view, (
  172. labels, None,
  173. zoomIn, zoomOut, zoomOrg, None,
  174. fitWindow, fitWidth))
  175. self.tools = self.toolbar('Tools')
  176. addActions(self.tools, (
  177. open, save, None,
  178. label, delete, hide, None,
  179. zoomIn, zoom, zoomOut, fitWindow, fitWidth))
  180. self.statusBar().showMessage('%s started.' % __appname__)
  181. self.statusBar().show()
  182. # Application state.
  183. self.image = QImage()
  184. self.filename = filename
  185. self.recent_files = []
  186. self.lineColor = None
  187. self.fillColor = None
  188. self.zoom_level = 100
  189. self.fit_window = False
  190. # XXX: Could be completely declarative.
  191. # Restore application settings.
  192. types = {
  193. 'filename': QString,
  194. 'recent-files': QStringList,
  195. 'window/size': QSize,
  196. 'window/position': QPoint,
  197. 'window/geometry': QByteArray,
  198. # Docks and toolbars:
  199. 'window/state': QByteArray,
  200. }
  201. self.settings = settings = Settings(types)
  202. self.recent_files = settings['recent-files']
  203. size = settings.get('window/size', QSize(600, 500))
  204. position = settings.get('window/position', QPoint(0, 0))
  205. self.resize(size)
  206. self.move(position)
  207. # or simply:
  208. #self.restoreGeometry(settings['window/geometry']
  209. self.restoreState(settings['window/state'])
  210. self.lineColor = QColor(settings.get('line/color', Shape.line_color))
  211. self.fillColor = QColor(settings.get('fill/color', Shape.fill_color))
  212. Shape.line_color = self.lineColor
  213. Shape.fill_color = self.fillColor
  214. # The file menu has default dynamically generated entries.
  215. self.updateFileMenu()
  216. # Since loading the file may take some time, make sure it runs in the background.
  217. self.queueEvent(partial(self.loadFile, self.filename))
  218. # Callbacks:
  219. self.zoomWidget.valueChanged.connect(self.paintCanvas)
  220. ## Support Functions ##
  221. def setDirty(self):
  222. self.dirty = True
  223. self.actions.save.setEnabled(True)
  224. def setClean(self):
  225. self.dirty = False
  226. self.actions.save.setEnabled(False)
  227. self.actions.label.setEnabled(True)
  228. def queueEvent(self, function):
  229. QTimer.singleShot(0, function)
  230. def status(self, message, delay=5000):
  231. self.statusBar().showMessage(message, delay)
  232. def resetState(self):
  233. self.labels.clear()
  234. self.items.clear()
  235. self.labelList.clear()
  236. self.zoomWidget.setValue(100)
  237. self.filename = None
  238. self.imageData = None
  239. self.labelFile = None
  240. self.canvas.resetState()
  241. ## Callbacks ##
  242. def popLabelListMenu(self, point):
  243. self.menus.labelList.exec_(self.labelList.mapToGlobal(point))
  244. def editLabelDialog(self):
  245. print "TODO"
  246. pass
  247. def editLabel(self):
  248. items = self.labelList.selectedItems()
  249. if items:
  250. self.labelList.editItem(items[0])
  251. # React to canvas signals.
  252. def shapeSelectionChanged(self, selected=False):
  253. if self._noSelectionSlot:
  254. self._noSelectionSlot = False
  255. else:
  256. shape = self.canvas.selectedShape
  257. if shape:
  258. self.labelList.setItemSelected(self.items[shape], True)
  259. else:
  260. self.labelList.clearSelection()
  261. self.actions.delete.setEnabled(selected)
  262. self.actions.copy.setEnabled(selected)
  263. def addLabel(self, shape):
  264. item = QListWidgetItem(shape.label)
  265. item.setFlags(item.flags() | Qt.ItemIsUserCheckable | Qt.ItemIsEditable)
  266. item.setCheckState(Qt.Checked)
  267. self.labels[item] = shape
  268. self.items[shape] = item
  269. self.labelList.addItem(item)
  270. def remLabel(self, shape):
  271. item = self.items.get(shape, None)
  272. self.labelList.takeItem(self.labelList.row(item))
  273. def loadLabels(self, shapes):
  274. s = []
  275. for label, points in shapes:
  276. shape = Shape(label=label)
  277. shape.fill = True
  278. for x, y in points:
  279. shape.addPoint(QPointF(x, y))
  280. s.append(shape)
  281. self.addLabel(shape)
  282. self.canvas.loadShapes(s)
  283. def saveLabels(self, filename):
  284. lf = LabelFile()
  285. shapes = [(unicode(shape.label), [(p.x(), p.y()) for p in shape.points])\
  286. for shape in self.canvas.shapes]
  287. try:
  288. lf.save(filename, shapes, unicode(self.filename), self.imageData)
  289. return True
  290. except LabelFileError, e:
  291. self.errorMessage(u'Error saving label data',
  292. u'<b>%s</b>' % e)
  293. return False
  294. def copySelectedShape(self):
  295. self.addLabel(self.canvas.copySelectedShape())
  296. #fix copy and delete
  297. self.shapeSelectionChanged(True)
  298. def highlightLabel(self, item):
  299. if self.highlighted:
  300. self.highlighted.fill_color = Shape.fill_color
  301. shape = self.labels[item]
  302. shape.fill_color = inverted(Shape.fill_color)
  303. self.highlighted = shape
  304. self.canvas.repaint()
  305. def labelSelectionChanged(self):
  306. items = self.labelList.selectedItems()
  307. if not items:
  308. return
  309. shape = self.labels[items[0]]
  310. self._noSelectionSlot = True
  311. self.canvas.selectShape(shape)
  312. def labelItemChanged(self, item):
  313. shape = self.labels[item]
  314. label = unicode(item.text())
  315. if label != shape.label:
  316. shape.label = unicode(item.text())
  317. self.setDirty()
  318. else: # User probably changed item visibility
  319. self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
  320. ## Callback functions:
  321. def newShape(self, position):
  322. """Pop-up and give focus to the label editor.
  323. position MUST be in global coordinates.
  324. """
  325. action = self.label.popUp(position)
  326. if action == self.label.OK:
  327. self.addLabel(self.canvas.setLastLabel(self.label.text()))
  328. self.setDirty()
  329. # Enable appropriate actions.
  330. self.actions.label.setEnabled(True)
  331. elif action == self.label.UNDO:
  332. self.canvas.undoLastLine()
  333. elif action == self.label.DELETE:
  334. self.canvas.deleteLastShape()
  335. else:
  336. assert False, "unknown label action"
  337. def scrollRequest(self, delta, orientation):
  338. units = - delta / (8 * 15)
  339. bar = self.scrollBars[orientation]
  340. bar.setValue(bar.value() + bar.singleStep() * units)
  341. def setZoom(self, value):
  342. self.actions.fitWidth.setChecked(False)
  343. self.actions.fitWindow.setChecked(False)
  344. self.zoomMode = self.MANUAL_ZOOM
  345. self.zoomWidget.setValue(value)
  346. def addZoom(self, increment=10):
  347. self.setZoom(self.zoomWidget.value() + increment)
  348. def zoomRequest(self, delta):
  349. units = delta / (8 * 15)
  350. scale = 10
  351. self.addZoom(scale * units)
  352. def setFitWindow(self, value=True):
  353. if value:
  354. self.actions.fitWidth.setChecked(False)
  355. self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
  356. self.adjustScale()
  357. def setFitWidth(self, value=True):
  358. if value:
  359. self.actions.fitWindow.setChecked(False)
  360. self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
  361. self.adjustScale()
  362. def hideLabelsToggle(self, value):
  363. #self.canvas.hideBackroundShapes(value)
  364. for item, shape in self.labels.iteritems():
  365. item.setCheckState(Qt.Unchecked if value and not shape.selected\
  366. else Qt.Checked)
  367. def loadFile(self, filename=None):
  368. """Load the specified file, or the last opened file if None."""
  369. self.resetState()
  370. self.canvas.setEnabled(False)
  371. if filename is None:
  372. filename = self.settings['filename']
  373. filename = unicode(filename)
  374. if QFile.exists(filename):
  375. if LabelFile.isLabelFile(filename):
  376. try:
  377. self.labelFile = LabelFile(filename)
  378. except LabelFileError, e:
  379. self.errorMessage(u'Error opening file',
  380. (u"<p><b>%s</b></p>"
  381. u"<p>Make sure <i>%s</i> is a valid label file.")\
  382. % (e, filename))
  383. self.status("Error reading %s" % filename)
  384. return False
  385. self.imageData = self.labelFile.imageData
  386. else:
  387. # Load image:
  388. # read data first and store for saving into label file.
  389. self.imageData = read(filename, None)
  390. self.labelFile = None
  391. image = QImage.fromData(self.imageData)
  392. if image.isNull():
  393. self.errorMessage(u'Error opening file',
  394. u"<p>Make sure <i>%s</i> is a valid image file." % filename)
  395. self.status("Error reading %s" % filename)
  396. return False
  397. self.status("Loaded %s" % os.path.basename(unicode(filename)))
  398. self.image = image
  399. self.filename = filename
  400. self.canvas.loadPixmap(QPixmap.fromImage(image))
  401. if self.labelFile:
  402. self.loadLabels(self.labelFile.shapes)
  403. self.setClean()
  404. self.canvas.setEnabled(True)
  405. return True
  406. return False
  407. def resizeEvent(self, event):
  408. if self.canvas and not self.image.isNull()\
  409. and self.zoomMode != self.MANUAL_ZOOM:
  410. self.adjustScale()
  411. super(MainWindow, self).resizeEvent(event)
  412. def paintCanvas(self):
  413. assert not self.image.isNull(), "cannot paint null image"
  414. self.canvas.scale = 0.01 * self.zoomWidget.value()
  415. self.canvas.adjustSize()
  416. self.canvas.repaint()
  417. def adjustScale(self):
  418. self.zoomWidget.setValue(int(100 * self.scalers[self.zoomMode]()))
  419. def scaleFitWindow(self):
  420. """Figure out the size of the pixmap in order to fit the main widget."""
  421. e = 2.0 # So that no scrollbars are generated.
  422. w1 = self.centralWidget().width() - e
  423. h1 = self.centralWidget().height() - e
  424. a1 = w1/ h1
  425. # Calculate a new scale value based on the pixmap's aspect ratio.
  426. w2 = self.canvas.pixmap.width() - 0.0
  427. h2 = self.canvas.pixmap.height() - 0.0
  428. a2 = w2 / h2
  429. return w1 / w2 if a2 >= a1 else h1 / h2
  430. def scaleFitWidth(self):
  431. # The epsilon does not seem to work too well here.
  432. w = self.centralWidget().width() - 2.0
  433. return w / self.canvas.pixmap.width()
  434. def closeEvent(self, event):
  435. if not self.mayContinue():
  436. event.ignore()
  437. s = self.settings
  438. s['filename'] = self.filename if self.filename else QString()
  439. s['window/size'] = self.size()
  440. s['window/position'] = self.pos()
  441. s['window/state'] = self.saveState()
  442. s['line/color'] = self.lineColor
  443. s['fill/color'] = self.fillColor
  444. # ask the use for where to save the labels
  445. #s['window/geometry'] = self.saveGeometry()
  446. def updateFileMenu(self):
  447. """Populate menu with recent files."""
  448. ## User Dialogs ##
  449. def openFile(self, _value=False):
  450. if not self.mayContinue():
  451. return
  452. path = os.path.dirname(unicode(self.filename))\
  453. if self.filename else '.'
  454. formats = ['*.%s' % unicode(fmt).lower()\
  455. for fmt in QImageReader.supportedImageFormats()]
  456. filters = 'Image files (%s)\nLabel files (*%s)'\
  457. % (' '.join(formats), LabelFile.suffix)
  458. filename = unicode(QFileDialog.getOpenFileName(self,
  459. '%s - Choose Image', path, filters))
  460. if filename:
  461. if self.loadFile(filename):
  462. self.actions.close.setEnabled(True)
  463. self.canvas.setEnabled(True)
  464. def saveFile(self, _value=False):
  465. assert not self.image.isNull(), "cannot save empty image"
  466. assert self.labels, "cannot save empty labels"
  467. formats = ['*%s' % LabelFile.suffix]
  468. filename = unicode(QFileDialog.getSaveFileName(self,
  469. '%s - Choose File', self.currentPath(),
  470. 'Label files (%s)' % ''.join(formats)))
  471. if filename:
  472. if self.saveLabels(filename):
  473. self.setClean()
  474. def closeFile(self, _value=False):
  475. if not self.mayContinue():
  476. return
  477. self.resetState()
  478. self.canvas.setEnabled(False)
  479. self.actions.close.setEnabled(False)
  480. # Message Dialogs. #
  481. def mayContinue(self):
  482. return not (self.dirty and not self.discardChangesDialog())
  483. def discardChangesDialog(self):
  484. yes, no = QMessageBox.Yes, QMessageBox.No
  485. msg = u'You have unsaved changes, proceed anyway?'
  486. return yes == QMessageBox.warning(self, u'Attention', msg, yes|no)
  487. def errorMessage(self, title, message):
  488. return QMessageBox.critical(self, title,
  489. '<p><b>%s</b></p>%s' % (title, message))
  490. def currentPath(self):
  491. return os.path.dirname(unicode(self.filename)) if self.filename else '.'
  492. def chooseColor1(self):
  493. color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
  494. default=DEFAULT_LINE_COLOR)
  495. if color:
  496. self.lineColor = color
  497. # Change the color for all shape lines:
  498. Shape.line_color = self.lineColor
  499. self.canvas.repaint()
  500. def chooseColor2(self):
  501. color = self.colorDialog.getColor(self.fillColor, u'Choose fill color',
  502. default=DEFAULT_FILL_COLOR)
  503. if color:
  504. self.fillColor = color
  505. Shape.fill_color = self.fillColor
  506. self.canvas.repaint()
  507. def newLabel(self):
  508. self.canvas.deSelectShape()
  509. self.canvas.setEditing()
  510. self.actions.label.setEnabled(False)
  511. def deleteSelectedShape(self):
  512. self.remLabel(self.canvas.deleteSelected())
  513. self.setDirty()
  514. def copyShape(self):
  515. self.canvas.endMove(copy=True)
  516. self.addLabel(self.canvas.selectedShape)
  517. self.setDirty()
  518. def moveShape(self):
  519. self.canvas.endMove(copy=False)
  520. self.setDirty()
  521. class LabelDelegate(QItemDelegate):
  522. def __init__(self, parent=None):
  523. super(LabelDelegate, self).__init__(parent)
  524. self.validator = labelValidator()
  525. # FIXME: Validation and trimming are completely broken if the
  526. # user navigates away from the editor with something like TAB.
  527. def createEditor(self, parent, option, index):
  528. """Make sure the user cannot enter empty labels.
  529. Also remove trailing whitespace."""
  530. edit = super(LabelDelegate, self).createEditor(parent, option, index)
  531. if isinstance(edit, QLineEdit):
  532. edit.setValidator(self.validator)
  533. def strip():
  534. edit.setText(edit.text().trimmed())
  535. edit.editingFinished.connect(strip)
  536. return edit
  537. class Settings(object):
  538. """Convenience dict-like wrapper around QSettings."""
  539. def __init__(self, types=None):
  540. self.data = QSettings()
  541. self.types = defaultdict(lambda: QVariant, types if types else {})
  542. def __setitem__(self, key, value):
  543. t = self.types[key]
  544. self.data.setValue(key,
  545. t(value) if not isinstance(value, t) else value)
  546. def __getitem__(self, key):
  547. return self._cast(key, self.data.value(key))
  548. def get(self, key, default=None):
  549. return self._cast(key, self.data.value(key, default))
  550. def _cast(self, key, value):
  551. # XXX: Very nasty way of converting types to QVariant methods :P
  552. t = self.types[key]
  553. if t != QVariant:
  554. method = getattr(QVariant, re.sub('^Q', 'to', t.__name__, count=1))
  555. return method(value)
  556. return value
  557. def inverted(color):
  558. return QColor(*[255 - v for v in color.getRgb()])
  559. def read(filename, default=None):
  560. try:
  561. with open(filename, 'rb') as f:
  562. return f.read()
  563. except:
  564. return default
  565. def main(argv):
  566. """Standard boilerplate Qt application code."""
  567. app = QApplication(argv)
  568. app.setApplicationName(__appname__)
  569. win = MainWindow(argv[1] if len(argv) == 2 else None)
  570. win.show()
  571. return app.exec_()
  572. if __name__ == '__main__':
  573. sys.exit(main(sys.argv))