ObjectCollection.py 12 KB

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