labelme.py 25 KB

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