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