Debian Codegraph @

editor/export/export_template_manager.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* export_template_manager.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "export_template_manager.h"
32
33 #include "core/io/dir_access.h"
34 #include "core/io/json.h"
35 #include "core/io/zip_io.h"
36 #include "core/version.h"
37 #include "editor/editor_node.h"
38 #include "editor/editor_string_names.h"
39 #include "editor/export/editor_export_preset.h"
40 #include "editor/file_system/editor_file_system.h"
41 #include "editor/file_system/editor_paths.h"
42 #include "editor/gui/editor_file_dialog.h"
43 #include "editor/gui/progress_dialog.h"
44 #include "editor/settings/editor_settings.h"
45 #include "editor/themes/editor_scale.h"
46 #include "scene/gui/line_edit.h"
47 #include "scene/gui/link_button.h"
48 #include "scene/gui/margin_container.h"
49 #include "scene/gui/menu_button.h"
50 #include "scene/gui/option_button.h"
51 #include "scene/gui/separator.h"
52 #include "scene/gui/tree.h"
53 #include "scene/main/http_request.h"
54
55 enum DownloadsAvailability {
56 DOWNLOADS_AVAILABLE,
57 DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE,
58 DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS,
59 DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS,
60 };
61
62 static DownloadsAvailability _get_downloads_availability() {
63 // Downloadable export templates are only available for stable and official alpha/beta/RC builds
64 // (which always have a number following their status, e.g. "alpha1").
65 // Therefore, don't display download-related features when using a development version
66 // (whose builds aren't numbered).
67 if (String(GODOT_VERSION_STATUS) == String("dev") ||
68 String(GODOT_VERSION_STATUS) == String("alpha") ||
69 String(GODOT_VERSION_STATUS) == String("beta") ||
70 String(GODOT_VERSION_STATUS) == String("rc")) {
71 return DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS;
72 }
73
74 #ifdef REAL_T_IS_DOUBLE
75 return DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS;
76 #else
77
78 const int network_mode = EDITOR_GET("network/connection/network_mode");
79
80 if (network_mode == EditorSettings::NETWORK_OFFLINE) {
81 return DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE;
82 }
83
84 return DOWNLOADS_AVAILABLE;
85 #endif
86 }
87
88 void ExportTemplateManager::_update_template_status() {
89 // Fetch installed templates from the file system.
90 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
91 const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();
92
93 Error err = da->change_dir(templates_dir);
94 ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir + "'.");
95
96 RBSet<String> templates;
97 da->list_dir_begin();
98 if (err == OK) {
99 String c = da->get_next();
100 while (!c.is_empty()) {
101 if (da->current_is_dir() && !c.begins_with(".")) {
102 templates.insert(c);
103 }
104 c = da->get_next();
105 }
106 }
107 da->list_dir_end();
108
109 // Update the state of the current version.
110 String current_version = GODOT_VERSION_FULL_CONFIG;
111 current_value->set_text(current_version);
112
113 if (templates.has(current_version)) {
114 current_missing_label->hide();
115 current_installed_label->show();
116
117 current_installed_hb->show();
118 current_version_exists = true;
119 } else {
120 current_installed_label->hide();
121 current_missing_label->show();
122
123 current_installed_hb->hide();
124 current_version_exists = false;
125 }
126
127 if (is_downloading_templates) {
128 install_options_vb->hide();
129 download_progress_hb->show();
130 } else {
131 download_progress_hb->hide();
132 install_options_vb->show();
133
134 if (templates.has(current_version)) {
135 current_installed_path->set_text(templates_dir.path_join(current_version));
136 }
137 }
138
139 // Update the list of other installed versions.
140 installed_table->clear();
141 TreeItem *installed_root = installed_table->create_item();
142
143 for (RBSet<String>::Element *E = templates.back(); E; E = E->prev()) {
144 String version_string = E->get();
145 if (version_string == current_version) {
146 continue;
147 }
148
149 TreeItem *ti = installed_table->create_item(installed_root);
150 ti->set_text(0, version_string);
151
152 #ifndef ANDROID_ENABLED
153 ti->add_button(0, get_editor_theme_icon(SNAME("Folder")), OPEN_TEMPLATE_FOLDER, false, TTR("Open the folder containing these templates."));
154 #endif
155 ti->add_button(0, get_editor_theme_icon(SNAME("Remove")), UNINSTALL_TEMPLATE, false, TTR("Uninstall these templates."));
156 }
157 }
158
159 void ExportTemplateManager::_download_current() {
160 if (is_downloading_templates) {
161 return;
162 }
163 is_downloading_templates = true;
164
165 install_options_vb->hide();
166 download_progress_hb->show();
167
168 if (mirrors_available) {
169 String mirror_url = _get_selected_mirror();
170 if (mirror_url.is_empty()) {
171 _set_current_progress_status(TTR("There are no mirrors available."), true);
172 return;
173 }
174
175 _download_template(mirror_url, true);
176 } else if (!is_refreshing_mirrors) {
177 _set_current_progress_status(TTR("Retrieving the mirror list..."));
178 _refresh_mirrors();
179 }
180 }
181
182 void ExportTemplateManager::_download_template(const String &p_url, bool p_skip_check) {
183 if (!p_skip_check && is_downloading_templates) {
184 return;
185 }
186 is_downloading_templates = true;
187
188 install_options_vb->hide();
189 download_progress_hb->show();
190 download_progress_bar->show();
191 download_progress_bar->set_indeterminate(true);
192
193 _set_current_progress_status(TTR("Starting the download..."));
194
195 download_templates->set_download_file(EditorPaths::get_singleton()->get_cache_dir().path_join("tmp_templates.tpz"));
196 download_templates->set_use_threads(true);
197
198 const String proxy_host = EDITOR_GET("network/http_proxy/host");
199 const int proxy_port = EDITOR_GET("network/http_proxy/port");
200 download_templates->set_http_proxy(proxy_host, proxy_port);
201 download_templates->set_https_proxy(proxy_host, proxy_port);
202
203 Error err = download_templates->request(p_url);
204 if (err != OK) {
205 _set_current_progress_status(TTR("Error requesting URL:") + " " + p_url, true);
206 download_progress_hb->hide();
207 return;
208 }
209
210 set_process(true);
211 _set_current_progress_status(TTR("Connecting to the mirror..."));
212 }
213
214 void ExportTemplateManager::_download_template_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
215 switch (p_status) {
216 case HTTPRequest::RESULT_CANT_RESOLVE: {
217 _set_current_progress_status(TTR("Can't resolve the requested address."), true);
218 } break;
219 case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
220 case HTTPRequest::RESULT_CONNECTION_ERROR:
221 case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH:
222 case HTTPRequest::RESULT_TLS_HANDSHAKE_ERROR:
223 case HTTPRequest::RESULT_CANT_CONNECT: {
224 _set_current_progress_status(TTR("Can't connect to the mirror."), true);
225 } break;
226 case HTTPRequest::RESULT_NO_RESPONSE: {
227 _set_current_progress_status(TTR("No response from the mirror."), true);
228 } break;
229 case HTTPRequest::RESULT_REQUEST_FAILED: {
230 _set_current_progress_status(TTR("Request failed."), true);
231 } break;
232 case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
233 _set_current_progress_status(TTR("Request ended up in a redirect loop."), true);
234 } break;
235 default: {
236 if (p_code != 200) {
237 _set_current_progress_status(TTR("Request failed:") + " " + itos(p_code), true);
238 } else {
239 _set_current_progress_status(TTR("Download complete; extracting templates..."));
240 String path = download_templates->get_download_file();
241
242 is_downloading_templates = false;
243 bool ret = _install_file_selected(path, true);
244 if (ret) {
245 // Clean up downloaded file.
246 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
247 Error err = da->remove(path);
248 if (err != OK) {
249 EditorNode::get_singleton()->add_io_error(TTR("Cannot remove temporary file:") + "\n" + path + "\n");
250 }
251 } else {
252 EditorNode::get_singleton()->add_io_error(vformat(TTR("Templates installation failed.\nThe problematic templates archives can be found at '%s'."), path));
253 }
254 }
255 } break;
256 }
257
258 set_process(false);
259 }
260
261 void ExportTemplateManager::_cancel_template_download() {
262 if (!is_downloading_templates) {
263 return;
264 }
265
266 download_templates->cancel_request();
267 download_progress_hb->hide();
268 install_options_vb->show();
269 is_downloading_templates = false;
270 }
271
272 void ExportTemplateManager::_refresh_mirrors() {
273 if (is_refreshing_mirrors) {
274 return;
275 }
276 is_refreshing_mirrors = true;
277
278 String current_version = GODOT_VERSION_FULL_CONFIG;
279 const String mirrors_metadata_url = "https://godotengine.org/mirrorlist/" + current_version + ".json";
280 request_mirrors->request(mirrors_metadata_url);
281 }
282
283 void ExportTemplateManager::_refresh_mirrors_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
284 if (p_status != HTTPRequest::RESULT_SUCCESS || p_code != 200) {
285 EditorNode::get_singleton()->show_warning(TTR("Error getting the list of mirrors."));
286 is_refreshing_mirrors = false;
287 if (is_downloading_templates) {
288 _cancel_template_download();
289 }
290 return;
291 }
292
293 String response_json = String::utf8((const char *)p_data.ptr(), p_data.size());
294
295 JSON json;
296 Error err = json.parse(response_json);
297 if (err != OK) {
298 EditorNode::get_singleton()->show_warning(TTR("Error parsing JSON with the list of mirrors. Please report this issue!"));
299 is_refreshing_mirrors = false;
300 if (is_downloading_templates) {
301 _cancel_template_download();
302 }
303 return;
304 }
305
306 mirrors_list->clear();
307 mirrors_list->add_item(TTR("Best available mirror"), 0);
308
309 mirrors_available = false;
310
311 Dictionary mirror_data = json.get_data();
312 if (mirror_data.has("mirrors")) {
313 Array mirrors = mirror_data["mirrors"];
314
315 for (int i = 0; i < mirrors.size(); i++) {
316 Dictionary m = mirrors[i];
317 ERR_CONTINUE(!m.has("url") || !m.has("name"));
318
319 mirrors_list->add_item(m["name"]);
320 mirrors_list->set_item_metadata(i + 1, m["url"]);
321
322 mirrors_available = true;
323 }
324 }
325 if (!mirrors_available) {
326 EditorNode::get_singleton()->show_warning(TTR("No download links found for this version. Direct download is only available for official releases."));
327 if (is_downloading_templates) {
328 _cancel_template_download();
329 }
330 }
331
332 is_refreshing_mirrors = false;
333
334 if (is_downloading_templates) {
335 String mirror_url = _get_selected_mirror();
336 if (mirror_url.is_empty()) {
337 _set_current_progress_status(TTR("There are no mirrors available."), true);
338 return;
339 }
340
341 _download_template(mirror_url, true);
342 }
343 }
344
345 void ExportTemplateManager::_force_online_mode() {
346 EditorSettings::get_singleton()->set_setting("network/connection/network_mode", EditorSettings::NETWORK_ONLINE);
347 EditorSettings::get_singleton()->notify_changes();
348 EditorSettings::get_singleton()->save();
349
350 popup_manager();
351 }
352
353 bool ExportTemplateManager::_humanize_http_status(HTTPRequest *p_request, String *r_status, int *r_downloaded_bytes, int *r_total_bytes) {
354 *r_status = "";
355 *r_downloaded_bytes = -1;
356 *r_total_bytes = -1;
357 bool success = true;
358
359 switch (p_request->get_http_client_status()) {
360 case HTTPClient::STATUS_DISCONNECTED:
361 *r_status = TTR("Disconnected");
362 success = false;
363 break;
364 case HTTPClient::STATUS_RESOLVING:
365 *r_status = TTR("Resolving");
366 break;
367 case HTTPClient::STATUS_CANT_RESOLVE:
368 *r_status = TTR("Can't Resolve");
369 success = false;
370 break;
371 case HTTPClient::STATUS_CONNECTING:
372 *r_status = TTR("Connecting...");
373 break;
374 case HTTPClient::STATUS_CANT_CONNECT:
375 *r_status = TTR("Can't Connect");
376 success = false;
377 break;
378 case HTTPClient::STATUS_CONNECTED:
379 *r_status = TTR("Connected");
380 break;
381 case HTTPClient::STATUS_REQUESTING:
382 *r_status = TTR("Requesting...");
383 break;
384 case HTTPClient::STATUS_BODY:
385 *r_status = TTR("Downloading");
386 *r_downloaded_bytes = p_request->get_downloaded_bytes();
387 *r_total_bytes = p_request->get_body_size();
388
389 if (p_request->get_body_size() > 0) {
390 *r_status += " " + String::humanize_size(p_request->get_downloaded_bytes()) + "/" + String::humanize_size(p_request->get_body_size());
391 } else {
392 *r_status += " " + String::humanize_size(p_request->get_downloaded_bytes());
393 }
394 break;
395 case HTTPClient::STATUS_CONNECTION_ERROR:
396 *r_status = TTR("Connection Error");
397 success = false;
398 break;
399 case HTTPClient::STATUS_TLS_HANDSHAKE_ERROR:
400 *r_status = TTR("TLS Handshake Error");
401 success = false;
402 break;
403 }
404
405 return success;
406 }
407
408 void ExportTemplateManager::_set_current_progress_status(const String &p_status, bool p_error) {
409 download_progress_label->set_text(p_status);
410
411 if (p_error) {
412 download_progress_bar->hide();
413 download_progress_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
414 } else {
415 download_progress_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SceneStringName(font_color), SNAME("Label")));
416 }
417 }
418
419 void ExportTemplateManager::_set_current_progress_value(float p_value, const String &p_status) {
420 download_progress_bar->show();
421 download_progress_bar->set_indeterminate(false);
422 download_progress_bar->set_value(p_value);
423 download_progress_label->set_text(p_status);
424 }
425
426 void ExportTemplateManager::_install_file() {
427 install_file_dialog->popup_file_dialog();
428 }
429
430 bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_skip_progress) {
431 Ref<FileAccess> io_fa;
432 zlib_filefunc_def io = zipio_create_io(&io_fa);
433
434 unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
435 if (!pkg) {
436 EditorNode::get_singleton()->show_warning(TTR("Can't open the export templates file."));
437 return false;
438 }
439 int ret = unzGoToFirstFile(pkg);
440
441 // Count them and find version.
442 int fc = 0;
443 String version;
444 String contents_dir;
445
446 while (ret == UNZ_OK) {
447 unz_file_info info;
448 char fname[16384];
449 ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
450 if (ret != UNZ_OK) {
451 break;
452 }
453
454 String file = String::utf8(fname);
455
456 // Skip the __MACOSX directory created by macOS's built-in file zipper.
457 if (file.begins_with("__MACOSX")) {
458 ret = unzGoToNextFile(pkg);
459 continue;
460 }
461
462 if (file.ends_with("version.txt")) {
463 Vector<uint8_t> uncomp_data;
464 uncomp_data.resize(info.uncompressed_size);
465
466 // Read.
467 unzOpenCurrentFile(pkg);
468 ret = unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());
469 ERR_BREAK_MSG(ret < 0, vformat("An error occurred while attempting to read from file: %s. This file will not be used.", file));
470 unzCloseCurrentFile(pkg);
471
472 String data_str = String::utf8((const char *)uncomp_data.ptr(), uncomp_data.size());
473 data_str = data_str.strip_edges();
474
475 // Version number should be of the form major.minor[.patch].status[.module_config]
476 // so it can in theory have 3 or more slices.
477 if (data_str.get_slice_count(".") < 3) {
478 EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside the export templates file: %s."), data_str));
479 unzClose(pkg);
480 return false;
481 }
482
483 version = data_str;
484 contents_dir = file.get_base_dir().trim_suffix("/").trim_suffix("\\");
485 }
486
487 if (file.get_file().size() != 0) {
488 fc++;
489 }
490
491 ret = unzGoToNextFile(pkg);
492 }
493
494 if (version.is_empty()) {
495 EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside the export templates file."));
496 unzClose(pkg);
497 return false;
498 }
499
500 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
501 String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(version);
502 Error err = d->make_dir_recursive(template_path);
503 if (err != OK) {
504 EditorNode::get_singleton()->show_warning(TTR("Error creating path for extracting templates:") + "\n" + template_path);
505 unzClose(pkg);
506 return false;
507 }
508
509 EditorProgress *p = nullptr;
510 if (!p_skip_progress) {
511 p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
512 }
513
514 fc = 0;
515 ret = unzGoToFirstFile(pkg);
516 while (ret == UNZ_OK) {
517 // Get filename.
518 unz_file_info info;
519 char fname[16384];
520 ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0);
521 if (ret != UNZ_OK) {
522 break;
523 }
524
525 if (String::utf8(fname).ends_with("/")) {
526 // File is a directory, ignore it.
527 // Directories will be created when extracting each file.
528 ret = unzGoToNextFile(pkg);
529 continue;
530 }
531
532 String file_path(String::utf8(fname).simplify_path());
533
534 String file = file_path.get_file();
535
536 // Skip the __MACOSX directory created by macOS's built-in file zipper.
537 if (file.is_empty() || file.begins_with("__MACOSX")) {
538 ret = unzGoToNextFile(pkg);
539 continue;
540 }
541
542 Vector<uint8_t> uncomp_data;
543 uncomp_data.resize(info.uncompressed_size);
544
545 // Read
546 unzOpenCurrentFile(pkg);
547 ret = unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());
548 ERR_BREAK_MSG(ret < 0, vformat("An error occurred while attempting to read from file: %s. This file will not be used.", file));
549 unzCloseCurrentFile(pkg);
550
551 String base_dir = file_path.get_base_dir().trim_suffix("/");
552
553 if (base_dir != contents_dir && base_dir.begins_with(contents_dir)) {
554 base_dir = base_dir.substr(contents_dir.length(), file_path.length()).trim_prefix("/");
555 file = base_dir.path_join(file);
556
557 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
558 ERR_CONTINUE(da.is_null());
559
560 String output_dir = template_path.path_join(base_dir);
561
562 if (!DirAccess::exists(output_dir)) {
563 Error mkdir_err = da->make_dir_recursive(output_dir);
564 ERR_CONTINUE(mkdir_err != OK);
565 }
566 }
567
568 if (p) {
569 p->step(TTR("Importing:") + " " + file, fc);
570 }
571
572 String to_write = template_path.path_join(file);
573 Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE);
574
575 if (f.is_null()) {
576 ret = unzGoToNextFile(pkg);
577 fc++;
578 ERR_CONTINUE_MSG(true, "Can't open file from path '" + String(to_write) + "'.");
579 }
580
581 f->store_buffer(uncomp_data.ptr(), uncomp_data.size());
582 f.unref(); // close file.
583 #ifndef WINDOWS_ENABLED
584 FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF);
585 #endif
586
587 ret = unzGoToNextFile(pkg);
588 fc++;
589 }
590
591 if (p) {
592 memdelete(p);
593 }
594 unzClose(pkg);
595
596 _update_template_status();
597 EditorSettings::get_singleton()->set("_export_template_download_directory", p_file.get_base_dir());
598 return true;
599 }
600
601 void ExportTemplateManager::_uninstall_template(const String &p_version) {
602 uninstall_confirm->set_text(vformat(TTR("Remove templates for the version '%s'?"), p_version));
603 uninstall_confirm->popup_centered();
604 uninstall_version = p_version;
605 }
606
607 void ExportTemplateManager::_uninstall_template_confirmed() {
608 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
609 const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();
610
611 Error err = da->change_dir(templates_dir);
612 ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir + "'.");
613 err = da->change_dir(uninstall_version);
614 ERR_FAIL_COND_MSG(err != OK, "Could not access templates directory at '" + templates_dir.path_join(uninstall_version) + "'.");
615
616 err = da->erase_contents_recursive();
617 ERR_FAIL_COND_MSG(err != OK, "Could not remove all templates in '" + templates_dir.path_join(uninstall_version) + "'.");
618
619 da->change_dir("..");
620 err = da->remove(uninstall_version);
621 ERR_FAIL_COND_MSG(err != OK, "Could not remove templates directory at '" + templates_dir.path_join(uninstall_version) + "'.");
622
623 _update_template_status();
624 }
625
626 String ExportTemplateManager::_get_selected_mirror() const {
627 if (mirrors_list->get_item_count() == 1) {
628 return "";
629 }
630
631 int selected = mirrors_list->get_selected_id();
632 if (selected == 0) {
633 // This is a special "best available" value; so pick the first available mirror from the rest of the list.
634 selected = 1;
635 }
636
637 return mirrors_list->get_item_metadata(selected);
638 }
639
640 void ExportTemplateManager::_mirror_options_button_cbk(int p_id) {
641 switch (p_id) {
642 case VISIT_WEB_MIRROR: {
643 String mirror_url = _get_selected_mirror();
644 if (mirror_url.is_empty()) {
645 EditorNode::get_singleton()->show_warning(TTR("There are no mirrors available."));
646 return;
647 }
648
649 OS::get_singleton()->shell_open(mirror_url);
650 } break;
651
652 case COPY_MIRROR_URL: {
653 String mirror_url = _get_selected_mirror();
654 if (mirror_url.is_empty()) {
655 EditorNode::get_singleton()->show_warning(TTR("There are no mirrors available."));
656 return;
657 }
658
659 DisplayServer::get_singleton()->clipboard_set(mirror_url);
660 } break;
661 }
662 }
663
664 void ExportTemplateManager::_installed_table_button_cbk(Object *p_item, int p_column, int p_id, MouseButton p_button) {
665 if (p_button != MouseButton::LEFT) {
666 return;
667 }
668 TreeItem *ti = Object::cast_to<TreeItem>(p_item);
669 if (!ti) {
670 return;
671 }
672
673 switch (p_id) {
674 case OPEN_TEMPLATE_FOLDER: {
675 String version_string = ti->get_text(0);
676 _open_template_folder(version_string);
677 } break;
678
679 case UNINSTALL_TEMPLATE: {
680 String version_string = ti->get_text(0);
681 _uninstall_template(version_string);
682 } break;
683 }
684 }
685
686 void ExportTemplateManager::_open_template_folder(const String &p_version) {
687 const String &templates_dir = EditorPaths::get_singleton()->get_export_templates_dir();
688 OS::get_singleton()->shell_show_in_file_manager(templates_dir.path_join(p_version), true);
689 }
690
691 void ExportTemplateManager::popup_manager() {
692 _update_template_status();
693
694 switch (_get_downloads_availability()) {
695 case DOWNLOADS_AVAILABLE: {
696 current_missing_label->set_text(TTR("Export templates are missing. Download them or install from a file."));
697
698 mirrors_list->clear();
699 mirrors_list->add_item(TTR("Best available mirror"), 0);
700 mirrors_list->set_disabled(false);
701 mirrors_list->set_tooltip_text("");
702
703 mirror_options_button->set_disabled(false);
704
705 download_current_button->set_disabled(false);
706 download_current_button->set_tooltip_text("");
707
708 if (!is_downloading_templates) {
709 _refresh_mirrors();
710 }
711
712 enable_online_hb->hide();
713 } break;
714
715 case DOWNLOADS_NOT_AVAILABLE_IN_OFFLINE_MODE: {
716 current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));
717
718 mirrors_list->clear();
719 mirrors_list->add_item(TTR("Not available in offline mode"), 0);
720 mirrors_list->set_disabled(true);
721 mirrors_list->set_tooltip_text(TTR("Template downloading is disabled in offline mode."));
722
723 mirror_options_button->set_disabled(true);
724
725 download_current_button->set_disabled(true);
726 download_current_button->set_tooltip_text(TTR("Template downloading is disabled in offline mode."));
727
728 enable_online_hb->show();
729 } break;
730
731 case DOWNLOADS_NOT_AVAILABLE_FOR_DEV_BUILDS: {
732 current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));
733
734 mirrors_list->clear();
735 mirrors_list->add_item(TTR("No templates for development builds"), 0);
736 mirrors_list->set_disabled(true);
737 mirrors_list->set_tooltip_text(TTR("Official export templates aren't available for development builds."));
738
739 mirror_options_button->set_disabled(true);
740
741 download_current_button->set_disabled(true);
742 download_current_button->set_tooltip_text(TTR("Official export templates aren't available for development builds."));
743
744 enable_online_hb->hide();
745 } break;
746
747 case DOWNLOADS_NOT_AVAILABLE_FOR_DOUBLE_BUILDS: {
748 current_missing_label->set_text(TTR("Export templates are missing. Install them from a file."));
749
750 mirrors_list->clear();
751 mirrors_list->add_item(TTR("No templates for double-precision builds"), 0);
752 mirrors_list->set_disabled(true);
753 mirrors_list->set_tooltip_text(TTR("Official export templates aren't available for double-precision builds."));
754
755 mirror_options_button->set_disabled(true);
756
757 download_current_button->set_disabled(true);
758 download_current_button->set_tooltip_text(TTR("Official export templates aren't available for double-precision builds."));
759 }
760 }
761
762 popup_centered(Size2(720, 280) * EDSCALE);
763 }
764
765 void ExportTemplateManager::ok_pressed() {
766 if (!is_downloading_templates) {
767 hide();
768 return;
769 }
770
771 hide_dialog_accept->popup_centered();
772 }
773
774 void ExportTemplateManager::_hide_dialog() {
775 hide();
776 }
777
778 String ExportTemplateManager::get_android_build_directory(const Ref<EditorExportPreset> &p_preset) {
779 if (p_preset.is_valid()) {
780 String gradle_build_dir = p_preset->get("gradle_build/gradle_build_directory");
781 if (!gradle_build_dir.is_empty()) {
782 return gradle_build_dir.path_join("build");
783 }
784 }
785 return "res://android/build";
786 }
787
788 String ExportTemplateManager::get_android_source_zip(const Ref<EditorExportPreset> &p_preset) {
789 if (p_preset.is_valid()) {
790 String android_source_zip = p_preset->get("gradle_build/android_source_template");
791 if (!android_source_zip.is_empty()) {
792 return android_source_zip;
793 }
794 }
795
796 const String templates_dir = EditorPaths::get_singleton()->get_export_templates_dir().path_join(GODOT_VERSION_FULL_CONFIG);
797 return templates_dir.path_join("android_source.zip");
798 }
799
800 String ExportTemplateManager::get_android_template_identifier(const Ref<EditorExportPreset> &p_preset) {
801 // The template identifier is the Godot version for the default template, and the full path plus md5 hash for custom templates.
802 if (p_preset.is_valid()) {
803 String android_source_zip = p_preset->get("gradle_build/android_source_template");
804 if (!android_source_zip.is_empty()) {
805 return android_source_zip + String(" [") + FileAccess::get_md5(android_source_zip) + String("]");
806 }
807 }
808 return GODOT_VERSION_FULL_CONFIG;
809 }
810
811 bool ExportTemplateManager::is_android_template_installed(const Ref<EditorExportPreset> &p_preset) {
812 return DirAccess::exists(get_android_build_directory(p_preset));
813 }
814
815 bool ExportTemplateManager::can_install_android_template(const Ref<EditorExportPreset> &p_preset) {
816 return FileAccess::exists(get_android_source_zip(p_preset));
817 }
818
819 Error ExportTemplateManager::install_android_template(const Ref<EditorExportPreset> &p_preset) {
820 const String source_zip = get_android_source_zip(p_preset);
821 ERR_FAIL_COND_V(!FileAccess::exists(source_zip), ERR_CANT_OPEN);
822 return install_android_template_from_file(source_zip, p_preset);
823 }
824
825 Error ExportTemplateManager::install_android_template_from_file(const String &p_file, const Ref<EditorExportPreset> &p_preset) {
826 // To support custom Android builds, we install the Java source code and buildsystem
827 // from android_source.zip to the project's res://android folder.
828
829 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
830 ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
831
832 String build_dir = get_android_build_directory(p_preset);
833 String parent_dir = build_dir.get_base_dir();
834
835 // Make parent of the build dir (if it does not exist).
836 da->make_dir_recursive(parent_dir);
837 {
838 // Add identifier, to ensure building won't work if the current template doesn't match.
839 Ref<FileAccess> f = FileAccess::open(parent_dir.path_join(".build_version"), FileAccess::WRITE);
840 ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE);
841 f->store_line(get_android_template_identifier(p_preset));
842 }
843
844 // Create the android build directory.
845 Error err = da->make_dir_recursive(build_dir);
846 ERR_FAIL_COND_V(err != OK, err);
847 {
848 // Add an empty .gdignore file to avoid scan.
849 Ref<FileAccess> f = FileAccess::open(build_dir.path_join(".gdignore"), FileAccess::WRITE);
850 ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE);
851 f->store_line("");
852 }
853
854 // Uncompress source template.
855
856 Ref<FileAccess> io_fa;
857 zlib_filefunc_def io = zipio_create_io(&io_fa);
858
859 unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
860 ERR_FAIL_NULL_V_MSG(pkg, ERR_CANT_OPEN, "Android sources not in ZIP format.");
861
862 int ret = unzGoToFirstFile(pkg);
863 int total_files = 0;
864 // Count files to unzip.
865 while (ret == UNZ_OK) {
866 total_files++;
867 ret = unzGoToNextFile(pkg);
868 }
869 ret = unzGoToFirstFile(pkg);
870
871 ProgressDialog::get_singleton()->add_task("uncompress_src", TTR("Uncompressing Android Build Sources"), total_files);
872
873 HashSet<String> dirs_tested;
874 int idx = 0;
875 while (ret == UNZ_OK) {
876 // Get file path.
877 unz_file_info info;
878 char fpath[16384];
879 ret = unzGetCurrentFileInfo(pkg, &info, fpath, 16384, nullptr, 0, nullptr, 0);
880 if (ret != UNZ_OK) {
881 break;
882 }
883
884 String path = String::utf8(fpath);
885 String base_dir = path.get_base_dir();
886
887 if (!path.ends_with("/")) {
888 Vector<uint8_t> uncomp_data;
889 uncomp_data.resize(info.uncompressed_size);
890
891 // Read.
892 unzOpenCurrentFile(pkg);
893 unzReadCurrentFile(pkg, uncomp_data.ptrw(), uncomp_data.size());
894 unzCloseCurrentFile(pkg);
895
896 if (!dirs_tested.has(base_dir)) {
897 da->make_dir_recursive(build_dir.path_join(base_dir));
898 dirs_tested.insert(base_dir);
899 }
900
901 String to_write = build_dir.path_join(path);
902 Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE);
903 if (f.is_valid()) {
904 f->store_buffer(uncomp_data.ptr(), uncomp_data.size());
905 f.unref(); // close file.
906 #ifndef WINDOWS_ENABLED
907 FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF);
908 #endif
909 } else {
910 ERR_PRINT("Can't uncompress file: " + to_write);
911 }
912 }
913
914 ProgressDialog::get_singleton()->task_step("uncompress_src", path, idx);
915
916 idx++;
917 ret = unzGoToNextFile(pkg);
918 }
919
920 ProgressDialog::get_singleton()->end_task("uncompress_src");
921 unzClose(pkg);
922 EditorFileSystem::get_singleton()->scan_changes();
923 return OK;
924 }
925
926 void ExportTemplateManager::_notification(int p_what) {
927 switch (p_what) {
928 case NOTIFICATION_THEME_CHANGED: {
929 current_value->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("main"), EditorStringName(EditorFonts)));
930 current_missing_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
931 current_installed_label->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("font_disabled_color"), EditorStringName(Editor)));
932
933 mirror_options_button->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
934 } break;
935
936 case NOTIFICATION_VISIBILITY_CHANGED: {
937 if (!is_visible()) {
938 set_process(false);
939 } else if (is_visible() && is_downloading_templates) {
940 set_process(true);
941 }
942 } break;
943
944 case NOTIFICATION_PROCESS: {
945 update_countdown -= get_process_delta_time();
946 if (update_countdown > 0) {
947 return;
948 }
949 update_countdown = 0.5;
950
951 String status;
952 int downloaded_bytes;
953 int total_bytes;
954 bool success = _humanize_http_status(download_templates, &status, &downloaded_bytes, &total_bytes);
955
956 if (downloaded_bytes >= 0) {
957 if (total_bytes > 0) {
958 _set_current_progress_value(float(downloaded_bytes) / total_bytes, status);
959 } else {
960 _set_current_progress_value(0, status);
961 }
962 } else {
963 _set_current_progress_status(status);
964 }
965
966 if (!success) {
967 set_process(false);
968 }
969 } break;
970
971 case NOTIFICATION_WM_CLOSE_REQUEST: {
972 // This won't stop the window from closing, but will show the alert if the download is active.
973 ok_pressed();
974 } break;
975 }
976 }
977
978 ExportTemplateManager::ExportTemplateManager() {
979 set_title(TTR("Export Template Manager"));
980 set_hide_on_ok(false);
981 set_ok_button_text(TTR("Close"));
982
983 VBoxContainer *main_vb = memnew(VBoxContainer);
984 add_child(main_vb);
985
986 // Current version controls.
987 HBoxContainer *current_hb = memnew(HBoxContainer);
988 main_vb->add_child(current_hb);
989
990 Label *current_label = memnew(Label);
991 current_label->set_theme_type_variation("HeaderSmall");
992 current_label->set_text(TTR("Current Version:"));
993 current_hb->add_child(current_label);
994
995 current_value = memnew(Label);
996 current_value->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
997 current_hb->add_child(current_value);
998
999 // Current version statuses.
1000 // Status: Current version is missing.
1001 current_missing_label = memnew(Label);
1002 current_missing_label->set_theme_type_variation("HeaderSmall");
1003
1004 current_missing_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1005 current_missing_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
1006 current_hb->add_child(current_missing_label);
1007
1008 // Status: Current version is installed.
1009 current_installed_label = memnew(Label);
1010 current_installed_label->set_theme_type_variation("HeaderSmall");
1011 current_installed_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1012 current_installed_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
1013 current_installed_label->set_text(TTR("Export templates are installed and ready to be used."));
1014 current_hb->add_child(current_installed_label);
1015 current_installed_label->hide();
1016
1017 // Currently installed template.
1018 current_installed_hb = memnew(HBoxContainer);
1019 main_vb->add_child(current_installed_hb);
1020
1021 current_installed_path = memnew(LineEdit);
1022 current_installed_path->set_editable(false);
1023 current_installed_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1024 current_installed_path->set_accessibility_name(TTRC("Installed Path"));
1025 current_installed_hb->add_child(current_installed_path);
1026
1027 #ifndef ANDROID_ENABLED
1028 Button *current_open_button = memnew(Button);
1029 current_open_button->set_text(TTR("Open Folder"));
1030 current_open_button->set_tooltip_text(TTR("Open the folder containing installed templates for the current version."));
1031 current_installed_hb->add_child(current_open_button);
1032 current_open_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_open_template_folder).bind(GODOT_VERSION_FULL_CONFIG));
1033 #endif
1034
1035 current_uninstall_button = memnew(Button);
1036 current_uninstall_button->set_text(TTR("Uninstall"));
1037 current_uninstall_button->set_tooltip_text(TTR("Uninstall templates for the current version."));
1038 current_installed_hb->add_child(current_uninstall_button);
1039 current_uninstall_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_uninstall_template).bind(GODOT_VERSION_FULL_CONFIG));
1040
1041 main_vb->add_child(memnew(HSeparator));
1042
1043 // Download and install section.
1044 HBoxContainer *install_templates_hb = memnew(HBoxContainer);
1045 main_vb->add_child(install_templates_hb);
1046
1047 // Download and install buttons are available.
1048 install_options_vb = memnew(VBoxContainer);
1049 install_options_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1050 install_templates_hb->add_child(install_options_vb);
1051
1052 HBoxContainer *download_install_hb = memnew(HBoxContainer);
1053 install_options_vb->add_child(download_install_hb);
1054
1055 Label *mirrors_label = memnew(Label);
1056 mirrors_label->set_text(TTR("Download from:"));
1057 download_install_hb->add_child(mirrors_label);
1058
1059 mirrors_list = memnew(OptionButton);
1060 mirrors_list->set_accessibility_name(TTRC("Mirror"));
1061 mirrors_list->set_custom_minimum_size(Size2(280, 0) * EDSCALE);
1062 download_install_hb->add_child(mirrors_list);
1063
1064 request_mirrors = memnew(HTTPRequest);
1065 mirrors_list->add_child(request_mirrors);
1066 request_mirrors->connect("request_completed", callable_mp(this, &ExportTemplateManager::_refresh_mirrors_completed));
1067
1068 mirror_options_button = memnew(MenuButton);
1069 mirror_options_button->set_accessibility_name(TTRC("Mirror Options"));
1070 mirror_options_button->get_popup()->add_item(TTR("Open in Web Browser"), VISIT_WEB_MIRROR);
1071 mirror_options_button->get_popup()->add_item(TTR("Copy Mirror URL"), COPY_MIRROR_URL);
1072 download_install_hb->add_child(mirror_options_button);
1073 mirror_options_button->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &ExportTemplateManager::_mirror_options_button_cbk));
1074
1075 download_install_hb->add_spacer();
1076
1077 download_current_button = memnew(Button);
1078 download_current_button->set_text(TTR("Download and Install"));
1079 download_current_button->set_tooltip_text(TTR("Download and install templates for the current version from the best possible mirror."));
1080 download_install_hb->add_child(download_current_button);
1081 download_current_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_download_current));
1082
1083 HBoxContainer *install_file_hb = memnew(HBoxContainer);
1084 install_file_hb->set_alignment(BoxContainer::ALIGNMENT_END);
1085 install_options_vb->add_child(install_file_hb);
1086
1087 install_file_button = memnew(Button);
1088 install_file_button->set_text(TTR("Install from File"));
1089 install_file_button->set_tooltip_text(TTR("Install templates from a local file."));
1090 install_file_hb->add_child(install_file_button);
1091 install_file_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_install_file));
1092
1093 enable_online_hb = memnew(HBoxContainer);
1094 install_options_vb->add_child(enable_online_hb);
1095
1096 Label *enable_online_label = memnew(Label);
1097 enable_online_label->set_text(TTR("Online mode is needed to download the templates."));
1098 enable_online_hb->add_child(enable_online_label);
1099
1100 LinkButton *enable_online_button = memnew(LinkButton);
1101 enable_online_button->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
1102 enable_online_button->set_text(TTR("Go Online"));
1103 enable_online_hb->add_child(enable_online_button);
1104 enable_online_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_force_online_mode));
1105
1106 // Templates are being downloaded; buttons unavailable.
1107 download_progress_hb = memnew(HBoxContainer);
1108 download_progress_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1109 install_templates_hb->add_child(download_progress_hb);
1110 download_progress_hb->hide();
1111
1112 download_progress_bar = memnew(ProgressBar);
1113 download_progress_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1114 download_progress_bar->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
1115 download_progress_bar->set_min(0);
1116 download_progress_bar->set_max(1);
1117 download_progress_bar->set_value(0);
1118 download_progress_bar->set_step(0.01);
1119 download_progress_bar->set_editor_preview_indeterminate(true);
1120 download_progress_hb->add_child(download_progress_bar);
1121
1122 download_progress_label = memnew(Label);
1123 download_progress_label->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1124 download_progress_hb->add_child(download_progress_label);
1125
1126 Button *download_cancel_button = memnew(Button);
1127 download_cancel_button->set_text(TTR("Cancel"));
1128 download_cancel_button->set_tooltip_text(TTR("Cancel the download of the templates."));
1129 download_progress_hb->add_child(download_cancel_button);
1130 download_cancel_button->connect(SceneStringName(pressed), callable_mp(this, &ExportTemplateManager::_cancel_template_download));
1131
1132 download_templates = memnew(HTTPRequest);
1133 install_templates_hb->add_child(download_templates);
1134 download_templates->connect("request_completed", callable_mp(this, &ExportTemplateManager::_download_template_completed));
1135
1136 main_vb->add_child(memnew(HSeparator));
1137
1138 // Other installed templates table.
1139 HBoxContainer *installed_versions_hb = memnew(HBoxContainer);
1140 main_vb->add_child(installed_versions_hb);
1141 Label *installed_label = memnew(Label);
1142 installed_label->set_theme_type_variation("HeaderSmall");
1143 installed_label->set_text(TTR("Other Installed Versions:"));
1144 installed_versions_hb->add_child(installed_label);
1145
1146 MarginContainer *mc = memnew(MarginContainer);
1147 mc->set_theme_type_variation("NoBorderHorizontalWindow");
1148 mc->set_v_size_flags(Control::SIZE_EXPAND_FILL);
1149 main_vb->add_child(mc);
1150
1151 installed_table = memnew(Tree);
1152 installed_table->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
1153 installed_table->set_hide_root(true);
1154 installed_table->set_scroll_hint_mode(Tree::SCROLL_HINT_MODE_BOTH);
1155 installed_table->set_custom_minimum_size(Size2(0, 100) * EDSCALE);
1156 installed_table->set_v_size_flags(Control::SIZE_EXPAND_FILL);
1157 mc->add_child(installed_table);
1158 installed_table->connect("button_clicked", callable_mp(this, &ExportTemplateManager::_installed_table_button_cbk));
1159
1160 // Dialogs.
1161 uninstall_confirm = memnew(ConfirmationDialog);
1162 uninstall_confirm->set_title(TTR("Uninstall Template"));
1163 add_child(uninstall_confirm);
1164 uninstall_confirm->connect(SceneStringName(confirmed), callable_mp(this, &ExportTemplateManager::_uninstall_template_confirmed));
1165
1166 install_file_dialog = memnew(EditorFileDialog);
1167 install_file_dialog->set_title(TTR("Select Template File"));
1168 install_file_dialog->set_access(FileDialog::ACCESS_FILESYSTEM);
1169 install_file_dialog->set_file_mode(FileDialog::FILE_MODE_OPEN_FILE);
1170 install_file_dialog->set_current_dir(EDITOR_DEF("_export_template_download_directory", ""));
1171 install_file_dialog->add_filter("*.tpz", TTR("Godot Export Templates"));
1172 install_file_dialog->connect("file_selected", callable_mp(this, &ExportTemplateManager::_install_file_selected).bind(false));
1173 add_child(install_file_dialog);
1174
1175 hide_dialog_accept = memnew(AcceptDialog);
1176 hide_dialog_accept->set_text(TTR("The templates will continue to download.\nYou may experience a short editor freeze when they finish."));
1177 add_child(hide_dialog_accept);
1178 hide_dialog_accept->connect(SceneStringName(confirmed), callable_mp(this, &ExportTemplateManager::_hide_dialog));
1179 }