ObjectCollection.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #from PyQt4.QtCore import QModelIndex
  2. from FlatCAMObj import *
  3. import inspect # TODO: Remove
  4. import FlatCAMApp
  5. from PyQt4 import Qt, QtGui, QtCore
  6. class KeySensitiveListView(QtGui.QListView):
  7. """
  8. QtGui.QListView extended to emit a signal on key press.
  9. """
  10. keyPressed = QtCore.pyqtSignal(int)
  11. def keyPressEvent(self, event):
  12. super(KeySensitiveListView, self).keyPressEvent(event)
  13. self.keyPressed.emit(event.key())
  14. class ObjectCollection(QtCore.QAbstractListModel):
  15. """
  16. Object storage and management.
  17. """
  18. classdict = {
  19. "gerber": FlatCAMGerber,
  20. "excellon": FlatCAMExcellon,
  21. "cncjob": FlatCAMCNCjob,
  22. "geometry": FlatCAMGeometry
  23. }
  24. icon_files = {
  25. "gerber": "share/flatcam_icon16.png",
  26. "excellon": "share/drill16.png",
  27. "cncjob": "share/cnc16.png",
  28. "geometry": "share/geometry16.png"
  29. }
  30. def __init__(self, parent=None):
  31. QtCore.QAbstractListModel.__init__(self, parent=parent)
  32. ### Icons for the list view
  33. self.icons = {}
  34. for kind in ObjectCollection.icon_files:
  35. self.icons[kind] = QtGui.QPixmap(ObjectCollection.icon_files[kind])
  36. ### Data ###
  37. self.object_list = []
  38. self.checked_indexes = []
  39. # Names of objects that are expected to become available.
  40. # For example, when the creation of a new object will run
  41. # in the background and will complete some time in the
  42. # future. This is a way to reserve the name and to let other
  43. # tasks know that they have to wait until available.
  44. self.promises = set()
  45. ### View
  46. #self.view = QtGui.QListView()
  47. self.view = KeySensitiveListView()
  48. self.view.setSelectionMode(Qt.QAbstractItemView.ExtendedSelection)
  49. self.view.setModel(self)
  50. self.click_modifier = None
  51. ## GUI Events
  52. self.view.selectionModel().selectionChanged.connect(self.on_list_selection_change)
  53. self.view.activated.connect(self.on_item_activated)
  54. self.view.keyPressed.connect(self.on_key)
  55. self.view.clicked.connect(self.on_mouse_down)
  56. def promise(self, obj_name):
  57. FlatCAMApp.App.log.debug("Object %s has been promised." % obj_name)
  58. self.promises.add(obj_name)
  59. def has_promises(self):
  60. return len(self.promises) > 0
  61. def on_key(self, key):
  62. # Delete
  63. if key == QtCore.Qt.Key_Delete:
  64. # Delete via the application to
  65. # ensure cleanup of the GUI
  66. self.get_active().app.on_delete()
  67. def on_mouse_down(self, event):
  68. FlatCAMApp.App.log.debug("Mouse button pressed on list")
  69. def rowCount(self, parent=QtCore.QModelIndex(), *args, **kwargs):
  70. return len(self.object_list)
  71. def columnCount(self, *args, **kwargs):
  72. return 1
  73. def data(self, index, role=Qt.Qt.DisplayRole):
  74. if not index.isValid() or not 0 <= index.row() < self.rowCount():
  75. return QtCore.QVariant()
  76. row = index.row()
  77. if role == Qt.Qt.DisplayRole:
  78. return self.object_list[row].options["name"]
  79. if role == Qt.Qt.DecorationRole:
  80. return self.icons[self.object_list[row].kind]
  81. # if role == Qt.Qt.CheckStateRole:
  82. # if row in self.checked_indexes:
  83. # return Qt.Qt.Checked
  84. # else:
  85. # return Qt.Qt.Unchecked
  86. def print_list(self):
  87. for obj in self.object_list:
  88. print obj
  89. def append(self, obj, active=False):
  90. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> OC.append()")
  91. name = obj.options["name"]
  92. # Check promises and clear if exists
  93. if name in self.promises:
  94. self.promises.remove(name)
  95. FlatCAMApp.App.log.debug("Promised object %s became available." % name)
  96. FlatCAMApp.App.log.debug("%d promised objects remaining." % len(self.promises))
  97. # Prevent same name
  98. while name in self.get_names():
  99. ## Create a new name
  100. # Ends with number?
  101. FlatCAMApp.App.log.debug("new_object(): Object name (%s) exists, changing." % name)
  102. match = re.search(r'(.*[^\d])?(\d+)$', name)
  103. if match: # Yes: Increment the number!
  104. base = match.group(1) or ''
  105. num = int(match.group(2))
  106. name = base + str(num + 1)
  107. else: # No: add a number!
  108. name += "_1"
  109. obj.options["name"] = name
  110. obj.set_ui(obj.ui_type())
  111. # Required before appending (Qt MVC)
  112. self.beginInsertRows(QtCore.QModelIndex(), len(self.object_list), len(self.object_list))
  113. # Simply append to the python list
  114. self.object_list.append(obj)
  115. # Required after appending (Qt MVC)
  116. self.endInsertRows()
  117. def get_names(self):
  118. """
  119. Gets a list of the names of all objects in the collection.
  120. :return: List of names.
  121. :rtype: list
  122. """
  123. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> OC.get_names()")
  124. return [x.options['name'] for x in self.object_list]
  125. def get_bounds(self):
  126. """
  127. Finds coordinates bounding all objects in the collection.
  128. :return: [xmin, ymin, xmax, ymax]
  129. :rtype: list
  130. """
  131. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_bounds()")
  132. # TODO: Move the operation out of here.
  133. xmin = Inf
  134. ymin = Inf
  135. xmax = -Inf
  136. ymax = -Inf
  137. for obj in self.object_list:
  138. try:
  139. gxmin, gymin, gxmax, gymax = obj.bounds()
  140. xmin = min([xmin, gxmin])
  141. ymin = min([ymin, gymin])
  142. xmax = max([xmax, gxmax])
  143. ymax = max([ymax, gymax])
  144. except:
  145. FlatCAMApp.App.log.warning("DEV WARNING: Tried to get bounds of empty geometry.")
  146. return [xmin, ymin, xmax, ymax]
  147. def get_by_name(self, name):
  148. """
  149. Fetches the FlatCAMObj with the given `name`.
  150. :param name: The name of the object.
  151. :type name: str
  152. :return: The requested object or None if no such object.
  153. :rtype: FlatCAMObj or None
  154. """
  155. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_by_name()")
  156. for obj in self.object_list:
  157. if obj.options['name'] == name:
  158. return obj
  159. return None
  160. def delete_active(self):
  161. selections = self.view.selectedIndexes()
  162. if len(selections) == 0:
  163. return
  164. row = selections[0].row()
  165. self.beginRemoveRows(QtCore.QModelIndex(), row, row)
  166. self.object_list.pop(row)
  167. self.endRemoveRows()
  168. def get_active(self):
  169. """
  170. Returns the active object or None
  171. :return: FlatCAMObj or None
  172. """
  173. selections = self.view.selectedIndexes()
  174. if len(selections) == 0:
  175. return None
  176. row = selections[0].row()
  177. return self.object_list[row]
  178. def get_selected(self):
  179. """
  180. Returns list of objects selected in the view.
  181. :return: List of objects
  182. """
  183. return [self.object_list[sel.row()] for sel in self.view.selectedIndexes()]
  184. def set_active(self, name):
  185. """
  186. Selects object by name from the project list. This triggers the
  187. list_selection_changed event and call on_list_selection_changed.
  188. :param name: Name of the FlatCAM Object
  189. :return: None
  190. """
  191. iobj = self.createIndex(self.get_names().index(name), 0) # Column 0
  192. self.view.selectionModel().select(iobj, QtGui.QItemSelectionModel.Select)
  193. def set_inactive(self, name):
  194. """
  195. Unselect object by name from the project list. This triggers the
  196. list_selection_changed event and call on_list_selection_changed.
  197. :param name: Name of the FlatCAM Object
  198. :return: None
  199. """
  200. iobj = self.createIndex(self.get_names().index(name), 0) # Column 0
  201. self.view.selectionModel().select(iobj, QtGui.QItemSelectionModel.Deselect)
  202. def set_all_inactive(self):
  203. """
  204. Unselect all objects from the project list. This triggers the
  205. list_selection_changed event and call on_list_selection_changed.
  206. :return: None
  207. """
  208. for name in self.get_names():
  209. self.set_inactive(name)
  210. def on_list_selection_change(self, current, previous):
  211. FlatCAMApp.App.log.debug("on_list_selection_change()")
  212. FlatCAMApp.App.log.debug("Current: %s, Previous %s" % (str(current), str(previous)))
  213. try:
  214. selection_index = current.indexes()[0].row()
  215. except IndexError:
  216. FlatCAMApp.App.log.debug("on_list_selection_change(): Index Error (Nothing selected?)")
  217. return
  218. self.object_list[selection_index].build_ui()
  219. def on_item_activated(self, index):
  220. """
  221. Double-click or Enter on item.
  222. :param index: Index of the item in the list.
  223. :return: None
  224. """
  225. self.object_list[index.row()].build_ui()
  226. def delete_all(self):
  227. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.delete_all()")
  228. self.beginResetModel()
  229. self.object_list = []
  230. self.checked_indexes = []
  231. self.endResetModel()
  232. def get_list(self):
  233. return self.object_list