ObjectCollection.py 9.9 KB

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