WelcomePagesModel.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. from collections import deque
  5. from typing import TYPE_CHECKING, Optional, List, Dict, Any
  6. from PyQt6.QtCore import QUrl, Qt, pyqtSlot, pyqtProperty, pyqtSignal
  7. from UM.i18n import i18nCatalog
  8. from UM.Logger import Logger
  9. from UM.Qt.ListModel import ListModel
  10. from UM.Resources import Resources
  11. if TYPE_CHECKING:
  12. from PyQt6.QtCore import QObject
  13. from cura.CuraApplication import CuraApplication
  14. class WelcomePagesModel(ListModel):
  15. """
  16. This is the Qt ListModel that contains all welcome pages data. Each page is a page that can be shown as a step in
  17. the welcome wizard dialog. Each item in this ListModel represents a page, which contains the following fields:
  18. - id : A unique page_id which can be used in function goToPage(page_id)
  19. - page_url : The QUrl to the QML file that contains the content of this page
  20. - next_page_id : (OPTIONAL) The next page ID to go to when this page finished. This is optional. If this is
  21. not provided, it will go to the page with the current index + 1
  22. - next_page_button_text : (OPTIONAL) The text to show for the "next" button, by default it's the translated text of
  23. "Next". Note that each step QML can decide whether to use this text or not, so it's not
  24. mandatory.
  25. - should_show_function : (OPTIONAL) An optional function that returns True/False indicating if this page should be
  26. shown. By default all pages should be shown. If a function returns False, that page will
  27. be skipped and its next page will be shown.
  28. Note that in any case, a page that has its "should_show_function" == False will ALWAYS be skipped.
  29. """
  30. IdRole = Qt.ItemDataRole.UserRole + 1 # Page ID
  31. PageUrlRole = Qt.ItemDataRole.UserRole + 2 # URL to the page's QML file
  32. NextPageIdRole = Qt.ItemDataRole.UserRole + 3 # The next page ID it should go to
  33. NextPageButtonTextRole = Qt.ItemDataRole.UserRole + 4 # The text for the next page button
  34. PreviousPageButtonTextRole = Qt.ItemDataRole.UserRole + 5 # The text for the previous page button
  35. def __init__(self, application: "CuraApplication", parent: Optional["QObject"] = None) -> None:
  36. super().__init__(parent)
  37. self.addRoleName(self.IdRole, "id")
  38. self.addRoleName(self.PageUrlRole, "page_url")
  39. self.addRoleName(self.NextPageIdRole, "next_page_id")
  40. self.addRoleName(self.NextPageButtonTextRole, "next_page_button_text")
  41. self.addRoleName(self.PreviousPageButtonTextRole, "previous_page_button_text")
  42. self._application = application
  43. self._catalog = i18nCatalog("cura")
  44. self._default_next_button_text = self._catalog.i18nc("@action:button", "Next")
  45. self._pages: List[Dict[str, Any]] = []
  46. self._current_page_index = 0
  47. # Store all the previous page indices so it can go back.
  48. self._previous_page_indices_stack: deque = deque()
  49. # If the welcome flow should be shown. It can show the complete flow or just the changelog depending on the
  50. # specific case. See initialize() for how this variable is set.
  51. self._should_show_welcome_flow = False
  52. allFinished = pyqtSignal() # emitted when all steps have been finished
  53. currentPageIndexChanged = pyqtSignal()
  54. @pyqtProperty(int, notify = currentPageIndexChanged)
  55. def currentPageIndex(self) -> int:
  56. return self._current_page_index
  57. @pyqtProperty(float, notify = currentPageIndexChanged)
  58. def currentProgress(self) -> float:
  59. """
  60. Returns a float number in [0, 1] which indicates the current progress.
  61. """
  62. if len(self._items) == 0:
  63. return 0
  64. else:
  65. return self._current_page_index / len(self._items)
  66. @pyqtProperty(bool, notify = currentPageIndexChanged)
  67. def isCurrentPageLast(self) -> bool:
  68. """
  69. Indicates if the current page is the last page.
  70. """
  71. return self._current_page_index == len(self._items) - 1
  72. def _setCurrentPageIndex(self, page_index: int) -> None:
  73. if page_index != self._current_page_index:
  74. self._previous_page_indices_stack.append(self._current_page_index)
  75. self._current_page_index = page_index
  76. self.currentPageIndexChanged.emit()
  77. @pyqtSlot()
  78. def atEnd(self) -> None:
  79. """
  80. Ends the Welcome-Pages. Put as a separate function for cases like the 'decline' in the User-Agreement.
  81. """
  82. self.allFinished.emit()
  83. self.resetState()
  84. @pyqtSlot()
  85. def goToNextPage(self, from_index: Optional[int] = None) -> None:
  86. """
  87. Goes to the next page.
  88. If "from_index" is given, it will look for the next page to show starting from the "from_index" page instead of
  89. the "self._current_page_index".
  90. """
  91. # Look for the next page that should be shown
  92. current_index = self._current_page_index if from_index is None else from_index
  93. while True:
  94. page_item = self._items[current_index]
  95. # Check if there's a "next_page_id" assigned. If so, go to that page. Otherwise, go to the page with the
  96. # current index + 1.
  97. next_page_id = page_item.get("next_page_id")
  98. next_page_index = current_index + 1
  99. if next_page_id:
  100. idx = self.getPageIndexById(next_page_id)
  101. if idx is None:
  102. # FIXME: If we cannot find the next page, we cannot do anything here.
  103. Logger.log("e", "Cannot find page with ID [%s]", next_page_id)
  104. return
  105. next_page_index = idx
  106. is_final_page = page_item.get("is_final_page")
  107. # If we have reached the last page, emit allFinished signal and reset.
  108. if next_page_index == len(self._items) or is_final_page:
  109. self.atEnd()
  110. return
  111. # Check if the this page should be shown (default yes), if not, keep looking for the next one.
  112. next_page_item = self.getItem(next_page_index)
  113. if self._shouldPageBeShown(next_page_index):
  114. break
  115. Logger.log("d", "Page [%s] should not be displayed, look for the next page.", next_page_item["id"])
  116. current_index = next_page_index
  117. # Move to the next page
  118. self._setCurrentPageIndex(next_page_index)
  119. @pyqtSlot()
  120. def goToPreviousPage(self) -> None:
  121. """
  122. Goes to the previous page. If there's no previous page, do nothing.
  123. """
  124. if len(self._previous_page_indices_stack) == 0:
  125. Logger.log("i", "No previous page, do nothing")
  126. return
  127. previous_page_index = self._previous_page_indices_stack.pop()
  128. self._current_page_index = previous_page_index
  129. self.currentPageIndexChanged.emit()
  130. @pyqtSlot(str)
  131. def goToPage(self, page_id: str) -> None:
  132. """Sets the current page to the given page ID. If the page ID is not found, do nothing."""
  133. page_index = self.getPageIndexById(page_id)
  134. if page_index is None:
  135. # FIXME: If we cannot find the next page, we cannot do anything here.
  136. Logger.log("e", "Cannot find page with ID [%s], go to the next page by default", page_index)
  137. self.goToNextPage()
  138. return
  139. if self._shouldPageBeShown(page_index):
  140. # Move to that page if it should be shown
  141. self._setCurrentPageIndex(page_index)
  142. else:
  143. # Find the next page to show starting from the "page_index"
  144. self.goToNextPage(from_index = page_index)
  145. def _shouldPageBeShown(self, page_index: int) -> bool:
  146. """
  147. Checks if the page with the given index should be shown by calling the "should_show_function" associated with
  148. it. If the function is not present, returns True (show page by default).
  149. """
  150. next_page_item = self.getItem(page_index)
  151. should_show_function = next_page_item.get("should_show_function", lambda: True)
  152. return should_show_function()
  153. @pyqtSlot()
  154. def resetState(self) -> None:
  155. """
  156. Resets the state of the WelcomePagesModel. This functions does the following:
  157. - Resets current_page_index to 0
  158. - Clears the previous page indices stack
  159. """
  160. self._current_page_index = 0
  161. self._previous_page_indices_stack.clear()
  162. self.currentPageIndexChanged.emit()
  163. shouldShowWelcomeFlowChanged = pyqtSignal()
  164. @pyqtProperty(bool, notify = shouldShowWelcomeFlowChanged)
  165. def shouldShowWelcomeFlow(self) -> bool:
  166. return self._should_show_welcome_flow
  167. def getPageIndexById(self, page_id: str) -> Optional[int]:
  168. """Gets the page index with the given page ID. If the page ID doesn't exist, returns None."""
  169. page_idx = None
  170. for idx, page_item in enumerate(self._items):
  171. if page_item["id"] == page_id:
  172. page_idx = idx
  173. break
  174. return page_idx
  175. @staticmethod
  176. def _getBuiltinWelcomePagePath(page_filename: str) -> QUrl:
  177. """Convenience function to get QUrl path to pages that's located in "resources/qml/WelcomePages"."""
  178. from cura.CuraApplication import CuraApplication
  179. return QUrl.fromLocalFile(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles,
  180. os.path.join("WelcomePages", page_filename)))
  181. # FIXME: HACKs for optimization that we don't update the model every time the active machine gets changed.
  182. def _onActiveMachineChanged(self) -> None:
  183. self._application.getMachineManager().globalContainerChanged.disconnect(self._onActiveMachineChanged)
  184. self._initialize(update_should_show_flag = False)
  185. def initialize(self) -> None:
  186. self._application.getMachineManager().globalContainerChanged.connect(self._onActiveMachineChanged)
  187. self._initialize()
  188. def _initialize(self, update_should_show_flag: bool = True) -> None:
  189. show_whats_new_only = False
  190. if update_should_show_flag:
  191. has_active_machine = self._application.getMachineManager().activeMachine is not None
  192. has_app_just_upgraded = self._application.hasJustUpdatedFromOldVersion()
  193. # Only show the what's new dialog if there's no machine and we have just upgraded
  194. show_complete_flow = not has_active_machine
  195. show_whats_new_only = has_active_machine and has_app_just_upgraded
  196. # FIXME: This is a hack. Because of the circular dependency between MachineManager, ExtruderManager, and
  197. # possibly some others, setting the initial active machine is not done when the MachineManager gets
  198. # initialized. So at this point, we don't know if there will be an active machine or not. It could be that
  199. # the active machine files are corrupted so we cannot rely on Preferences either. This makes sure that once
  200. # the active machine gets changed, this model updates the flags, so it can decide whether to show the
  201. # welcome flow or not.
  202. should_show_welcome_flow = show_complete_flow or show_whats_new_only
  203. if should_show_welcome_flow != self._should_show_welcome_flow:
  204. self._should_show_welcome_flow = should_show_welcome_flow
  205. self.shouldShowWelcomeFlowChanged.emit()
  206. # All pages
  207. all_pages_list = [{"id": "welcome",
  208. "page_url": self._getBuiltinWelcomePagePath("WelcomeContent.qml"),
  209. },
  210. {"id": "user_agreement",
  211. "page_url": self._getBuiltinWelcomePagePath("UserAgreementContent.qml"),
  212. },
  213. {"id": "data_collections",
  214. "page_url": self._getBuiltinWelcomePagePath("DataCollectionsContent.qml"),
  215. },
  216. {"id": "cloud",
  217. "page_url": self._getBuiltinWelcomePagePath("CloudContent.qml"),
  218. "should_show_function": self.shouldShowCloudPage,
  219. },
  220. {"id": "add_network_or_local_printer",
  221. "page_url": self._getBuiltinWelcomePagePath("AddUltimakerOrThirdPartyPrinterStack.qml"),
  222. "next_page_id": "machine_actions",
  223. },
  224. {"id": "add_printer_by_ip",
  225. "page_url": self._getBuiltinWelcomePagePath("AddPrinterByIpContent.qml"),
  226. "next_page_id": "machine_actions",
  227. },
  228. {"id": "add_cloud_printers",
  229. "page_url": self._getBuiltinWelcomePagePath("AddCloudPrintersView.qml"),
  230. "next_page_button_text": self._catalog.i18nc("@action:button", "Next"),
  231. "next_page_id": "whats_new",
  232. },
  233. {"id": "machine_actions",
  234. "page_url": self._getBuiltinWelcomePagePath("FirstStartMachineActionsContent.qml"),
  235. "should_show_function": self.shouldShowMachineActions,
  236. },
  237. {"id": "whats_new",
  238. "page_url": self._getBuiltinWelcomePagePath("WhatsNewContent.qml"),
  239. "next_page_button_text": self._catalog.i18nc("@action:button", "Skip"),
  240. },
  241. {"id": "changelog",
  242. "page_url": self._getBuiltinWelcomePagePath("ChangelogContent.qml"),
  243. "next_page_button_text": self._catalog.i18nc("@action:button", "Finish"),
  244. },
  245. ]
  246. pages_to_show = all_pages_list
  247. if show_whats_new_only:
  248. pages_to_show = list(filter(lambda x: x["id"] == "whats_new", all_pages_list))
  249. self._pages = pages_to_show
  250. self.setItems(self._pages)
  251. def setItems(self, items: List[Dict[str, Any]]) -> None:
  252. # For convenience, inject the default "next" button text to each item if it's not present.
  253. for item in items:
  254. if "next_page_button_text" not in item:
  255. item["next_page_button_text"] = self._default_next_button_text
  256. super().setItems(items)
  257. def shouldShowMachineActions(self) -> bool:
  258. """
  259. Indicates if the machine action panel should be shown by checking if there's any first start machine actions
  260. available.
  261. """
  262. global_stack = self._application.getMachineManager().activeMachine
  263. if global_stack is None:
  264. return False
  265. definition_id = global_stack.definition.getId()
  266. first_start_actions = self._application.getMachineActionManager().getFirstStartActions(definition_id)
  267. return len([action for action in first_start_actions if action.needsUserInteraction()]) > 0
  268. def shouldShowCloudPage(self) -> bool:
  269. """
  270. The cloud page should be shown only if the user is not logged in
  271. :return: True if the user is not logged in, False if he/she is
  272. """
  273. # Import CuraApplication locally or else it fails
  274. from cura.CuraApplication import CuraApplication
  275. api = CuraApplication.getInstance().getCuraAPI()
  276. return not api.account.isLoggedIn
  277. def addPage(self) -> None:
  278. pass