ObjectCollection.py 12 KB

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