main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. import os
  8. import argparse
  9. import copy
  10. import time
  11. import tkinter as tk
  12. from tkinter import messagebox
  13. from tkinter import filedialog
  14. from config_data import ConfigData
  15. from keystore_settings import KeystoreSettings
  16. import discovery
  17. from wait_dialog import WaitDialog
  18. from keystore_generator import KeystoreGenerator
  19. from project_generator import ProjectGenerator
  20. DEFAULT_APG_CONFIG_FILE="apg_config.json"
  21. class TkApp(tk.Tk):
  22. """
  23. This is the main UI of the Android Project Generator, known as APG for short.
  24. """
  25. def __init__(self, config: ConfigData, config_file_path: str = ""):
  26. super().__init__()
  27. self.title("Android Project Generator")
  28. # Display the main window wherever the mouse is located.
  29. x, y = self.winfo_pointerx(), self.winfo_pointery()
  30. self.geometry(f"+{x}+{y}")
  31. self._config = config
  32. self._config_file_path_var = tk.StringVar()
  33. self._config_file_path_var.set(config_file_path)
  34. self._init_load_save_ui()
  35. self._init_keystore_settings_ui()
  36. self._init_sdk_settings_ui()
  37. self._init_report_ui()
  38. def _init_load_save_ui(self):
  39. frame = tk.Frame(self)
  40. frame.pack()
  41. buttons_frame = tk.Frame(frame)
  42. buttons_frame.pack()
  43. btn = tk.Button(buttons_frame, text="Load Settings", command=self.on_load_settings_button)
  44. btn.pack(padx=20, side=tk.LEFT)
  45. btn = tk.Button(buttons_frame, text="Save Settings", command=self.on_save_settings_button)
  46. btn.pack(padx=20, side=tk.RIGHT)
  47. lbl = tk.Label(frame, textvariable=self._config_file_path_var)
  48. lbl.pack()
  49. def _init_keystore_settings_ui(self):
  50. # Create a button widget with an event handler.
  51. keystore_frame = tk.Frame(self)
  52. keystore_frame.pack(expand=False, fill=tk.X)
  53. lbl = tk.Label(keystore_frame, text="============ Keystore Settings ============")
  54. lbl.pack()
  55. # Let's add the fields that make the Distinguished Name.
  56. dn_frame = tk.Frame(keystore_frame)
  57. dn_frame.pack(expand=True, fill=tk.X)
  58. self._init_keystore_distinguished_name_ui(dn_frame)
  59. # Now let's add the rest of the keystore fields.
  60. ks_data = self._config.keystore_settings
  61. self._keystore_validity_days_var = self._add_label_entry(keystore_frame, "Validity Days", ks_data.validity_days)[0]
  62. self._keystore_key_size_var = self._add_label_entry(keystore_frame, "Key Size", ks_data.key_size)[0]
  63. self._keystore_app_key_alias_var = self._add_label_entry(keystore_frame, "App Key Alias", ks_data.key_alias)[0]
  64. self._keystore_app_key_password_var = self._add_label_entry(keystore_frame, "App Key Password", ks_data.key_password)[0]
  65. self._keystore_keystore_password_var = self._add_label_entry(keystore_frame, "Keystore Password", ks_data.keystore_password)[0]
  66. self._keystore_file_var, _, row_frame = self._add_label_entry(keystore_frame, "Keystore File", ks_data.keystore_file)
  67. btn = tk.Button(row_frame, text="...", command=self.on_select_keystore_file_button)
  68. btn.pack(side=tk.LEFT)
  69. btn = tk.Button(keystore_frame, text="Create Keystore", command=self.on_create_keystore_button)
  70. btn.pack()
  71. def _init_keystore_distinguished_name_ui(self, parent_frame: tk.Frame):
  72. tk.Label(parent_frame, text="Distinguished Name Settings:").pack(anchor=tk.W)
  73. spaceStr = " "
  74. ks_data = self._config.keystore_settings
  75. self._dn_country_code_var = self._add_label_entry(parent_frame, f"{spaceStr}Country Code", ks_data.dn_country_code)[0]
  76. self._dn_company_var = self._add_label_entry(parent_frame, f"{spaceStr}Company (aka Organization)", ks_data.dn_organization)[0]
  77. self._dn_organizational_unit_var = self._add_label_entry(parent_frame, f"{spaceStr}Organizational Unit", ks_data.dn_organizational_unit)[0]
  78. self._dn_app_name_var = self._add_label_entry(parent_frame, f"{spaceStr}App Name (aka Common Name)", ks_data.dn_common_name)[0]
  79. def _init_sdk_settings_ui(self):
  80. sdk_frame = tk.Frame(self)
  81. sdk_frame.pack(expand=False, fill=tk.X)
  82. lbl = tk.Label(sdk_frame, text="========= Android SDK/NDK Settings ========")
  83. lbl.pack()
  84. cf = self._config
  85. self._android_ndk_version_var = self._add_label_entry(sdk_frame, "NDK Version", cf.android_ndk_version)[0]
  86. self._android_sdk_api_level_var = self._add_label_entry(sdk_frame, "SDK API Level", cf.android_sdk_api_level)[0]
  87. self._android_sdk_path_var, _, row_frame = self._add_label_entry(sdk_frame, "SDK Path", cf.android_sdk_path)
  88. btn = tk.Button(row_frame, text="...", command=self.on_select_sdk_path_button)
  89. btn.pack(side=tk.LEFT)
  90. # Add the meta quest project checkbox
  91. self._android_quest_flag_var = self._add_checkbox(sdk_frame, "This is a Meta Quest project", cf.is_meta_quest_project)[0]
  92. # Add the project generation button.
  93. btn = tk.Button(sdk_frame, text="Generate Project", command=self.on_generate_project_button)
  94. btn.pack()
  95. def _add_label_entry(self, parent_frame: tk.Frame, lbl_name: str, default_value: str = "") -> tuple[tk.StringVar, tk.Entry, tk.Frame]:
  96. """
  97. Returns the tuple (string_var, entry, row_frame),
  98. where @string_var is the TK StringVar bound to the Entry widget,
  99. @entry is the Entry widget,
  100. @row_frame is the parent Frame that owns @entry widget.
  101. """
  102. row_frame = tk.Frame(parent_frame)
  103. row_frame.pack(padx=5, pady=2, expand=True, fill=tk.X)
  104. lbl = tk.Label(row_frame, text=lbl_name)
  105. lbl.pack(side=tk.LEFT, anchor=tk.W)
  106. entry = tk.Entry(row_frame, justify='right')
  107. entry.pack(side=tk.LEFT, expand=True, fill=tk.X)
  108. string_var = tk.StringVar()
  109. string_var.set(default_value)
  110. entry["textvariable"] = string_var
  111. return string_var, entry, row_frame
  112. def _add_checkbox(self, parent_frame: tk.Frame, lbl_name: str, default_value: bool = False) -> tuple[tk.BooleanVar, tk.Checkbutton, tk.Frame]:
  113. """
  114. Returns the tuple (BooleanVar, check_box, row_frame),
  115. where @BooleanVar is the TK BooleanVar bound to the CheckBox widget,
  116. @check_box is the Checkbutton widget,
  117. @row_frame is the parent Frame that owns @check_box widget.
  118. """
  119. row_frame = tk.Frame(parent_frame)
  120. row_frame.pack(padx=5, pady=2, expand=True, fill=tk.X)
  121. bool_var = tk.BooleanVar()
  122. bool_var.set(default_value)
  123. # Create a Checkbutton widget and bind it to the variable.
  124. checkbutton = tk.Checkbutton(row_frame, text=lbl_name, variable=bool_var)
  125. checkbutton.pack(side=tk.LEFT, anchor=tk.W)
  126. return bool_var, checkbutton, row_frame
  127. def _init_report_ui(self):
  128. """
  129. Instanties the scrollable text widget where this app will report
  130. all the stdout and stderr string produced by all subprocess invoked
  131. by this application.
  132. """
  133. lbl = tk.Label(self, text="============ Operations Report ============")
  134. lbl.pack()
  135. self._report_text_widget = tk.Text(self, wrap=tk.WORD, borderwidth=2, relief=tk.SUNKEN)
  136. self._report_scrollbar_widget = tk.Scrollbar(self, orient=tk.VERTICAL, command=self._report_text_widget.yview)
  137. # Configure the Text widget and the Scrollbar widget.
  138. self._report_text_widget.configure(yscrollcommand=self._report_scrollbar_widget.set)
  139. self._report_text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  140. self._report_scrollbar_widget.pack(side=tk.RIGHT, fill=tk.Y)
  141. def _get_time_now_str(self) -> str:
  142. """
  143. @returns The current local time as a formatted string.
  144. """
  145. time_secs = time.time()
  146. time_st = time.localtime(time_secs)
  147. no_millis_str = time.strftime("%H:%M:%S", time_st)
  148. fractional_secs = int(str(time_secs).split(".")[1])
  149. return f"{no_millis_str}.{fractional_secs}"
  150. def _append_log_message(self, msg: str):
  151. """
  152. Append the msg with a timestamp to the report widget, and automatically scrolls to
  153. the bottom of the report.
  154. """
  155. timestamp_str = self._get_time_now_str()
  156. self._report_text_widget.insert(tk.END, f">>{timestamp_str}>>\n{msg}\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n")
  157. self._report_text_widget.see(tk.END) #scroll to the end.
  158. def create_keystore_settings_from_widgets(self) -> KeystoreSettings:
  159. """
  160. @returns A new KeystoreSettings object, where all the values are read from the
  161. current content in the UI text/entry fields.
  162. """
  163. ks = KeystoreSettings()
  164. ks.keystore_file = self._keystore_file_var.get()
  165. ks.keystore_password = self._keystore_keystore_password_var.get()
  166. ks.key_alias = self._keystore_app_key_alias_var.get()
  167. ks.key_password = self._keystore_app_key_password_var.get()
  168. ks.key_size = self._keystore_key_size_var.get()
  169. ks.validity_days = self._keystore_validity_days_var.get()
  170. ks.dn_common_name = self._dn_app_name_var.get()
  171. ks.dn_organizational_unit = self._dn_organizational_unit_var.get()
  172. ks.dn_organization = self._dn_company_var.get()
  173. ks.dn_country_code = self._dn_country_code_var.get()
  174. return ks
  175. def create_config_data_from_widgets(self) -> ConfigData:
  176. """
  177. @returns A new ConfigData object, where all the values are read from the
  178. current content in the UI text/entry fields.
  179. """
  180. config = copy.deepcopy(self._config)
  181. config.android_sdk_path = self._android_sdk_path_var.get()
  182. config.android_ndk_version = self._android_ndk_version_var.get()
  183. config.android_sdk_api_level = self._android_sdk_api_level_var.get()
  184. config.is_meta_quest_project = self._android_quest_flag_var.get()
  185. config.keystore_settings = self.create_keystore_settings_from_widgets()
  186. return config
  187. def update_widgets_from_keystore_settings(self, ks: KeystoreSettings):
  188. self._keystore_file_var.set(ks.keystore_file)
  189. self._keystore_keystore_password_var.set(ks.keystore_password)
  190. self._keystore_app_key_alias_var.set(ks.key_alias)
  191. self._keystore_app_key_password_var.set(ks.key_password)
  192. self._keystore_key_size_var.set(ks.key_size)
  193. self._keystore_validity_days_var.set(ks.validity_days)
  194. self._dn_app_name_var.set(ks.dn_common_name)
  195. self._dn_organizational_unit_var.set(ks.dn_organizational_unit)
  196. self._dn_company_var.set(ks.dn_organization)
  197. self._dn_country_code_var.set(ks.dn_country_code)
  198. def update_widgets_from_config(self, config: ConfigData):
  199. self._android_sdk_path_var.set(config.android_sdk_path)
  200. self._android_ndk_version_var.set(config.android_ndk_version)
  201. self._android_sdk_api_level_var.set(config.android_sdk_api_level)
  202. self._android_quest_flag_var.set(config.is_meta_quest_project)
  203. self.update_widgets_from_keystore_settings(config.keystore_settings)
  204. def on_load_settings_button(self):
  205. """
  206. Invoked when the user clicks the `Load Settings` button.
  207. """
  208. suggested_file_path = self._config_file_path_var.get()
  209. if suggested_file_path == "":
  210. suggested_file_path = os.path.join(self._config.project_path, DEFAULT_APG_CONFIG_FILE)
  211. initial_dir, initial_file = os.path.split(suggested_file_path)
  212. filename = filedialog.askopenfilename(
  213. initialdir=initial_dir,
  214. initialfile=initial_file,
  215. title="Load Settings",
  216. filetypes=[("JSON files", "*.json"), ("All files", "*")],
  217. defaultextension=".json",
  218. parent=self
  219. )
  220. if (not filename) or (not os.path.isfile(filename)):
  221. messagebox.showinfo("Invalid Settings File Path", f"The path {filename} is invalid!")
  222. return
  223. if not self._config.load_from_json_file(filename):
  224. messagebox.showerror("File I/O Error", f"Failed to read settings from file:\n{filename}")
  225. return
  226. self._config_file_path_var.set(filename)
  227. messagebox.showinfo("Success!", f"Current settings were loaded from file:\n{filename}")
  228. self.update_widgets_from_config(self._config)
  229. def on_save_settings_button(self):
  230. """
  231. Invoked when the user clicks the `Save Settings` button.
  232. """
  233. configData = self.create_config_data_from_widgets()
  234. suggested_file_path = self._config_file_path_var.get()
  235. if suggested_file_path == "":
  236. suggested_file_path = os.path.join(configData.project_path, DEFAULT_APG_CONFIG_FILE)
  237. initial_dir, initial_file = os.path.split(suggested_file_path)
  238. filename = filedialog.asksaveasfilename(
  239. initialdir=initial_dir,
  240. initialfile=initial_file,
  241. title="Save Settings",
  242. filetypes=[("JSON files", "*.json"), ("All files", "*")],
  243. defaultextension=".json",
  244. parent=self
  245. )
  246. if (filename is None) or (filename == ""):
  247. return # Cancelled by user.
  248. if not configData.save_to_json_file(filename):
  249. messagebox.showerror("File I/O Error", f"Failed to save settings to file {filename}")
  250. self._config = configData
  251. self._config_file_path_var.set(filename)
  252. messagebox.showinfo("Success!", f"Current settings were saved as file:\n{filename}")
  253. def _on_user_cancel_task(self):
  254. """
  255. This is a callback invoked by self._wait_dialog when the user
  256. decides to cancel the current operation.
  257. """
  258. self._wait_dialog = None
  259. self._cancel_current_operation()
  260. self._current_operation = None # Doesn't hurt to force this to None.
  261. def _tick_operation(self):
  262. """
  263. This function will be called periodically while there's an operation running in the background.
  264. """
  265. if self._current_operation and self._current_operation.is_finished():
  266. # The operation completed. Time to close the progress dialog
  267. # and report the results.
  268. if self._wait_dialog:
  269. self._wait_dialog.close()
  270. self._wait_dialog = None
  271. self._on_current_operation_finished()
  272. return
  273. # Keep ticking, until next time if the operation is finished or the user
  274. # decides to cancel the current operation.
  275. if self._wait_dialog:
  276. self._wait_dialog.on_tick(float(self._tick_delta_ms)/1000.0)
  277. self.after(self._tick_delta_ms, self._tick_operation)
  278. def _cancel_current_operation(self):
  279. """
  280. This one is called upon user request.
  281. """
  282. self._current_operation.cancel()
  283. report_msg = self._current_operation.get_report_msg()
  284. self._append_log_message(report_msg)
  285. messagebox.showinfo("Cancelled By User", f"{self._current_operation.get_basic_description()}\nwas cancelled by user!")
  286. self._current_operation = None
  287. def _on_current_operation_finished(self):
  288. # The current operation is finished. But it could have
  289. # finished with error or success. Let the user know the outcome.
  290. report_msg = self._current_operation.get_report_msg()
  291. self._append_log_message(report_msg)
  292. if self._current_operation.is_success():
  293. messagebox.showinfo("Success", f"{self._current_operation.get_basic_description()}\ncompleted succesfully!")
  294. else:
  295. messagebox.showerror("Error", f"{self._current_operation.get_basic_description()}\ncompleted with errors!")
  296. self._current_operation = None
  297. def on_select_keystore_file_button(self):
  298. """
  299. The user clicked the "..." button next to the `Keystore File` field, with the purpose
  300. of selecting a different keystore file.
  301. """
  302. suggested_file_path = self._keystore_file_var.get()
  303. if suggested_file_path == "":
  304. # If the user input data is empty, try the cached data.
  305. suggested_file_path = self._config.keystore_settings.keystore_file
  306. if suggested_file_path == "":
  307. # If the cached data is empty, let's try a default
  308. suggested_file_path = os.path.join(self._config.project_path, "app.keystore")
  309. initial_dir, initial_file = os.path.split(suggested_file_path)
  310. filename = filedialog.asksaveasfilename(
  311. initialdir=initial_dir,
  312. initialfile=initial_file,
  313. title="Select Keystore File",
  314. filetypes=[("keystore files", "*.keystore"), ("All files", "*")],
  315. defaultextension=".json",
  316. parent=self
  317. )
  318. if (not filename) or (filename == ""):
  319. messagebox.showerror("Error", f"Invalid Keystore File Path!")
  320. return
  321. self._keystore_file_var.set(filename)
  322. self._config.keystore_settings.keystore_file = filename
  323. def on_select_sdk_path_button(self):
  324. """
  325. The user clicked the "..." button next to the `SDK Path` field, with the purpose
  326. of selecting a different Android SDK path.
  327. """
  328. configData = self.create_config_data_from_widgets()
  329. initial_dir = configData.android_sdk_path
  330. directory = filedialog.askdirectory(
  331. initialdir=initial_dir,
  332. title="Pick Android SDK Location",
  333. parent=self
  334. )
  335. if (not directory ) or (directory == "") or (not os.path.isdir(directory)):
  336. messagebox.showerror("Invalid SDK Path", f"The path {directory} is invalid!")
  337. return
  338. if not discovery.could_be_android_sdk_directory(directory):
  339. messagebox.showwarning("Warning", f"The directory:\n{directory}\nDoesn't appear to be an Android SDK directory.")
  340. configData.android_sdk_path = directory
  341. self._config = configData
  342. self.update_widgets_from_config(self._config)
  343. def on_create_keystore_button(self):
  344. """
  345. The user clicked the `Create Keystore` button. Will spawn the required tools to create the keystore.
  346. """
  347. ks = self.create_keystore_settings_from_widgets()
  348. if (not ks.keystore_file) or (ks.keystore_file == ""):
  349. messagebox.showerror("Error", f"A vaid `Keystore File` is required.")
  350. return
  351. if os.path.isfile(ks.keystore_file):
  352. result = messagebox.askyesno("Attention!", f"Do you want to replace the Keystore File:\n{ks.keystore_file}?")
  353. if not result:
  354. return
  355. else:
  356. # It's important to delete the existing keystore file, otherwise the java keytool will fail to replace it.
  357. try:
  358. os.remove(ks.keystore_file)
  359. except Exception as err:
  360. messagebox.showerror("Error", f"Failed to delete keystore file {ks.keystore_file}. Got Exception:\n{err}")
  361. return
  362. self._config.keystore_settings = ks
  363. # Start the in-progress modal dialog.
  364. def _inner_cancel_cb():
  365. self._on_user_cancel_task()
  366. self._wait_dialog = WaitDialog(self, "Creating Keystore.\nThis operation takes around 5 seconds.", _inner_cancel_cb)
  367. self._tick_delta_ms = 250
  368. self.after(self._tick_delta_ms, self._tick_operation)
  369. # Instantiate and start the job.
  370. self._current_operation = KeystoreGenerator(self._config)
  371. self._current_operation.start()
  372. def on_generate_project_button(self):
  373. """
  374. The user clicked the `Generate Project` button. Will spawn the required tools to create the android project.
  375. """
  376. configData = self.create_config_data_from_widgets()
  377. # Make sure the keystore file exist.
  378. ks = configData.keystore_settings
  379. if (not ks.keystore_file) or (ks.keystore_file == ""):
  380. messagebox.showerror("Error", f"Can not generate an android project without a valid `Keystore File`.")
  381. return
  382. if not os.path.isfile(ks.keystore_file):
  383. messagebox.showerror("Error", f"The keystore file {ks.keystore_file} doesn't exist.\nPush the `Create Keystore` button to create it.")
  384. return
  385. # Start the in-progress modal dialog.
  386. def _inner_cancel_cb():
  387. self._on_user_cancel_task()
  388. self._wait_dialog = WaitDialog(self, "Generating the android project.\nThis operation takes around 30 seconds.", _inner_cancel_cb)
  389. self._tick_delta_ms = 250
  390. self.after(self._tick_delta_ms, self._tick_operation)
  391. # Instantiate and start the job.
  392. self._config = configData
  393. self._current_operation = ProjectGenerator(configData)
  394. self._current_operation.start()
  395. # class TkApp END
  396. ######################################################
  397. if __name__ == "__main__":
  398. parser = argparse.ArgumentParser(description='Presents a UI that automates the generation of an Android Project and its keystore.')
  399. parser.add_argument('--engine', '--e', required=True,
  400. help='Path to the engine root directory.')
  401. parser.add_argument('--project', '--p', required=True,
  402. help='Path to the project root directory.')
  403. parser.add_argument('--build', '--b', required=True,
  404. help='Path to the build directory.')
  405. parser.add_argument('--third_party', '--t', required=True,
  406. help='Path to the 3rd Party root folder.')
  407. args = parser.parse_args()
  408. # Check if the project directory contains a json file with configuration data.
  409. configPath = os.path.join(args.project, DEFAULT_APG_CONFIG_FILE)
  410. config_data = ConfigData()
  411. config_data.load_from_json_file(configPath)
  412. # Discover the location of the keystore file if not defined yet.
  413. ks = config_data.keystore_settings
  414. if (not ks.keystore_file) or (ks.keystore_file == ""):
  415. ks.keystore_file = os.path.join(args.project, "app.keystore")
  416. # Discover the android sdk path if empty.
  417. if (config_data.android_sdk_path is None) or (config_data.android_sdk_path == ""):
  418. config_data.android_sdk_path = discovery.discover_android_sdk_path()
  419. config_data.engine_path = args.engine
  420. config_data.project_path = args.project
  421. config_data.build_path = args.build
  422. config_data.third_party_path = args.third_party
  423. app = TkApp(config_data, configPath)
  424. app.mainloop()