ObjectCollection.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.model = QtGui.QStandardItemModel(self.view)
  57. self.view.setModel(self.model)
  58. self.model.itemChanged.connect(self.on_item_changed)
  59. #self.view.setModel(self)
  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.setCheckable(True)
  134. if obj.options["plot"] == True:
  135. item.setCheckState(2)#Qt.Checked)
  136. else:
  137. item.setCheckState(0) #Qt.Unchecked)
  138. self.model.appendRow(item)
  139. # Required after appending (Qt MVC)
  140. #self.endInsertRows()
  141. def get_names(self):
  142. """
  143. Gets a list of the names of all objects in the collection.
  144. :return: List of names.
  145. :rtype: list
  146. """
  147. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> OC.get_names()")
  148. return [x.options['name'] for x in self.object_list]
  149. def get_bounds(self):
  150. """
  151. Finds coordinates bounding all objects in the collection.
  152. :return: [xmin, ymin, xmax, ymax]
  153. :rtype: list
  154. """
  155. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_bounds()")
  156. # TODO: Move the operation out of here.
  157. xmin = Inf
  158. ymin = Inf
  159. xmax = -Inf
  160. ymax = -Inf
  161. for obj in self.object_list:
  162. try:
  163. gxmin, gymin, gxmax, gymax = obj.bounds()
  164. xmin = min([xmin, gxmin])
  165. ymin = min([ymin, gymin])
  166. xmax = max([xmax, gxmax])
  167. ymax = max([ymax, gymax])
  168. except:
  169. FlatCAMApp.App.log.warning("DEV WARNING: Tried to get bounds of empty geometry.")
  170. return [xmin, ymin, xmax, ymax]
  171. def get_by_name(self, name):
  172. """
  173. Fetches the FlatCAMObj with the given `name`.
  174. :param name: The name of the object.
  175. :type name: str
  176. :return: The requested object or None if no such object.
  177. :rtype: FlatCAMObj or None
  178. """
  179. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.get_by_name()")
  180. for obj in self.object_list:
  181. if obj.options['name'] == name:
  182. return obj
  183. return None
  184. def delete_active(self):
  185. selections = self.view.selectedIndexes()
  186. if len(selections) == 0:
  187. return
  188. row = selections[0].row()
  189. #self.beginRemoveRows(QtCore.QModelIndex(), row, row)
  190. self.object_list.pop(row)
  191. self.model.removeRow(row)
  192. #self.endRemoveRows()
  193. def get_active(self):
  194. """
  195. Returns the active object or None
  196. :return: FlatCAMObj or None
  197. """
  198. selections = self.view.selectedIndexes()
  199. if len(selections) == 0:
  200. return None
  201. row = selections[0].row()
  202. return self.object_list[row]
  203. def get_selected(self):
  204. """
  205. Returns list of objects selected in the view.
  206. :return: List of objects
  207. """
  208. return [self.object_list[sel.row()] for sel in self.view.selectedIndexes()]
  209. def set_active(self, name):
  210. """
  211. Selects object by name from the project list. This triggers the
  212. list_selection_changed event and call on_list_selection_changed.
  213. :param name: Name of the FlatCAM Object
  214. :return: None
  215. """
  216. iobj = self.createIndex(self.get_names().index(name), 0) # Column 0
  217. self.view.selectionModel().select(iobj, QtGui.QItemSelectionModel.Select)
  218. def set_inactive(self, name):
  219. """
  220. Unselect object by name from the project list. This triggers the
  221. list_selection_changed event and call on_list_selection_changed.
  222. :param name: Name of the FlatCAM Object
  223. :return: None
  224. """
  225. iobj = self.createIndex(self.get_names().index(name), 0) # Column 0
  226. self.view.selectionModel().select(iobj, QtGui.QItemSelectionModel.Deselect)
  227. def set_all_inactive(self):
  228. """
  229. Unselect all objects from the project list. This triggers the
  230. list_selection_changed event and call on_list_selection_changed.
  231. :return: None
  232. """
  233. for name in self.get_names():
  234. self.set_inactive(name)
  235. def on_list_selection_change(self, current, previous):
  236. FlatCAMApp.App.log.debug("on_list_selection_change()")
  237. FlatCAMApp.App.log.debug("Current: %s, Previous %s" % (str(current), str(previous)))
  238. try:
  239. selection_index = current.indexes()[0].row()
  240. except IndexError:
  241. FlatCAMApp.App.log.debug("on_list_selection_change(): Index Error (Nothing selected?)")
  242. return
  243. self.object_list[selection_index].build_ui()
  244. def on_item_changed(self, item):
  245. #FlatCAMApp.App.log.debug("on_item_changed(): " + str(item.row()) + " " + self.object_list[item.row()].options["name"])
  246. if item.checkState() == QtCore.Qt.Checked:
  247. self.object_list[item.row()].options["plot"] = True #(item.checkState() == QtCore.Qt.Checked)
  248. else:
  249. self.object_list[item.row()].options["plot"] = False #(item.checkState() == QtCore.Qt.Checked)
  250. self.object_list[item.row()].plot()
  251. return
  252. def on_item_activated(self, index):
  253. """
  254. Double-click or Enter on item.
  255. :param index: Index of the item in the list.
  256. :return: None
  257. """
  258. self.object_list[index.row()].build_ui()
  259. def delete_all(self):
  260. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> OC.delete_all()")
  261. self.beginResetModel()
  262. self.model.removeRows(0, self.model.rowCount())
  263. self.object_list = []
  264. self.checked_indexes = []
  265. self.endResetModel()
  266. def get_list(self):
  267. return self.object_list