labelme.py 25 KB

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