ObjectCollection.py 7.7 KB

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