WelcomePagesModel.py 15 KB

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