Debian Codegraph @

editor/asset_library/asset_library_editor_plugin.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* asset_library_editor_plugin.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 "asset_library_editor_plugin.h"
32
33 #include "core/io/dir_access.h"
34 #include "core/io/json.h"
35 #include "core/io/stream_peer_tls.h"
36 #include "core/os/keyboard.h"
37 #include "core/version.h"
38 #include "editor/editor_main_screen.h"
39 #include "editor/editor_node.h"
40 #include "editor/editor_string_names.h"
41 #include "editor/file_system/editor_paths.h"
42 #include "editor/gui/editor_file_dialog.h"
43 #include "editor/settings/editor_settings.h"
44 #include "editor/settings/project_settings_editor.h"
45 #include "editor/themes/editor_scale.h"
46 #include "scene/gui/menu_button.h"
47 #include "scene/gui/separator.h"
48 #include "scene/resources/image_texture.h"
49
50 static inline void setup_http_request(HTTPRequest *request) {
51 request->set_use_threads(EDITOR_GET("asset_library/use_threads"));
52
53 const String proxy_host = EDITOR_GET("network/http_proxy/host");
54 const int proxy_port = EDITOR_GET("network/http_proxy/port");
55 request->set_http_proxy(proxy_host, proxy_port);
56 request->set_https_proxy(proxy_host, proxy_port);
57 }
58
59 void EditorAssetLibraryItem::configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, const String &p_cost) {
60 title_text = p_title;
61 title->set_text(title_text);
62 title->set_tooltip_text(title_text);
63 asset_id = p_asset_id;
64 category->set_text(p_category);
65 category_id = p_category_id;
66 author->set_text(p_author);
67 author_id = p_author_id;
68 price->set_text(p_cost);
69
70 _calculate_misc_links_size();
71 }
72
73 void EditorAssetLibraryItem::set_image(int p_type, int p_index, const Ref<Texture2D> &p_image) {
74 ERR_FAIL_COND(p_type != EditorAssetLibrary::IMAGE_QUEUE_ICON);
75 ERR_FAIL_COND(p_index != 0);
76
77 icon->set_texture_normal(p_image);
78 }
79
80 void EditorAssetLibraryItem::_notification(int p_what) {
81 switch (p_what) {
82 case NOTIFICATION_ENTER_TREE: {
83 icon->set_texture_normal(get_editor_theme_icon(SNAME("ProjectIconLoading")));
84 category->add_theme_color_override(SceneStringName(font_color), Color(0.5, 0.5, 0.5));
85 author->add_theme_color_override(SceneStringName(font_color), Color(0.5, 0.5, 0.5));
86 price->add_theme_color_override(SceneStringName(font_color), Color(0.5, 0.5, 0.5));
87
88 if (author->get_default_cursor_shape() == CURSOR_ARROW) {
89 // Disable visible feedback if author link isn't clickable.
90 author->add_theme_color_override("font_pressed_color", Color(0.5, 0.5, 0.5));
91 author->add_theme_color_override("font_hover_color", Color(0.5, 0.5, 0.5));
92 }
93
94 _calculate_misc_links_size();
95 } break;
96
97 case NOTIFICATION_TRANSLATION_CHANGED: {
98 _calculate_misc_links_size();
99 } break;
100
101 case NOTIFICATION_RESIZED: {
102 calculate_misc_links_ratio();
103 } break;
104 }
105 }
106
107 void EditorAssetLibraryItem::_calculate_misc_links_size() {
108 Ref<TextLine> text_buf;
109 text_buf.instantiate();
110 text_buf->add_string(author->get_text(), author->get_button_font(), author->get_button_font_size());
111 author_width = text_buf->get_line_width();
112
113 text_buf->clear();
114 const Ref<Font> font = get_theme_font(SceneStringName(font), SNAME("Label"));
115 const int font_size = get_theme_font_size(SceneStringName(font_size), SNAME("Label"));
116 text_buf->add_string(price->get_text(), font, font_size);
117 price_width = text_buf->get_line_width();
118
119 calculate_misc_links_ratio();
120 }
121
122 void EditorAssetLibraryItem::calculate_misc_links_ratio() {
123 const int separators_width = 15 * EDSCALE;
124 const float total_width = author_price_hbox->get_size().width - (separator->get_size().width + separators_width);
125 if (total_width <= 0) {
126 return;
127 }
128
129 float ratio_left = 1;
130 // Make the ratios a fraction bigger, to avoid unnecessary trimming.
131 const float extra_ratio = 4.0 / total_width;
132
133 const float author_ratio = MIN(1, author_width / total_width);
134 author->set_stretch_ratio(author_ratio + extra_ratio);
135 ratio_left -= author_ratio;
136
137 const float price_ratio = MIN(1, price_width / total_width);
138 price->set_stretch_ratio(price_ratio + extra_ratio);
139 ratio_left -= price_ratio;
140
141 spacer->set_stretch_ratio(ratio_left);
142 }
143
144 void EditorAssetLibraryItem::_asset_clicked() {
145 emit_signal(SNAME("asset_selected"), asset_id);
146 }
147
148 void EditorAssetLibraryItem::_category_clicked() {
149 emit_signal(SNAME("category_selected"), category_id);
150 }
151
152 void EditorAssetLibraryItem::_author_clicked() {
153 emit_signal(SNAME("author_selected"), author->get_text());
154 }
155
156 void EditorAssetLibraryItem::_bind_methods() {
157 ClassDB::bind_method("set_image", &EditorAssetLibraryItem::set_image);
158 ADD_SIGNAL(MethodInfo("asset_selected"));
159 ADD_SIGNAL(MethodInfo("category_selected"));
160 ADD_SIGNAL(MethodInfo("author_selected"));
161 }
162
163 EditorAssetLibraryItem::EditorAssetLibraryItem(bool p_clickable) {
164 Ref<StyleBoxEmpty> border;
165 border.instantiate();
166 border->set_content_margin_all(5 * EDSCALE);
167 add_theme_style_override(SceneStringName(panel), border);
168
169 HBoxContainer *hb = memnew(HBoxContainer);
170 // Add some spacing to visually separate the icon from the asset details.
171 hb->add_theme_constant_override("separation", 15 * EDSCALE);
172 add_child(hb);
173
174 icon = memnew(TextureButton);
175 icon->set_accessibility_name(TTRC("Open asset details"));
176 icon->set_custom_minimum_size(Size2(64, 64) * EDSCALE);
177 hb->add_child(icon);
178
179 VBoxContainer *vb = memnew(VBoxContainer);
180
181 hb->add_child(vb);
182 vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
183
184 title = memnew(LinkButton);
185 title->set_accessibility_name(TTRC("Title"));
186 title->set_auto_translate_mode(AutoTranslateMode::AUTO_TRANSLATE_MODE_DISABLED);
187 title->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
188 title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
189 vb->add_child(title);
190
191 category = memnew(LinkButton);
192 category->set_accessibility_name(TTRC("Category"));
193 category->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
194 category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
195 vb->add_child(category);
196
197 author_price_hbox = memnew(HBoxContainer);
198 author_price_hbox->add_theme_constant_override("separation", 5 * EDSCALE);
199 vb->add_child(author_price_hbox);
200
201 author = memnew(LinkButton);
202 author->set_tooltip_text(TTRC("Author"));
203 author->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
204 author->set_accessibility_name(TTRC("Author"));
205 author->set_h_size_flags(Control::SIZE_EXPAND_FILL);
206 author_price_hbox->add_child(author);
207
208 separator = memnew(HSeparator);
209 author_price_hbox->add_child(separator);
210
211 if (p_clickable) {
212 author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
213 icon->set_default_cursor_shape(CURSOR_POINTING_HAND);
214 icon->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItem::_asset_clicked));
215 title->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItem::_asset_clicked));
216 category->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItem::_category_clicked));
217 author->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItem::_author_clicked));
218 } else {
219 title->set_mouse_filter(MOUSE_FILTER_IGNORE);
220 category->set_mouse_filter(MOUSE_FILTER_IGNORE);
221 author->set_underline_mode(LinkButton::UNDERLINE_MODE_NEVER);
222 author->set_default_cursor_shape(CURSOR_ARROW);
223 }
224
225 Ref<StyleBoxEmpty> label_margin;
226 label_margin.instantiate();
227 label_margin->set_content_margin_all(0);
228
229 price = memnew(Label);
230 price->set_focus_mode(FOCUS_ACCESSIBILITY);
231 price->add_theme_style_override(CoreStringName(normal), label_margin);
232 price->set_tooltip_text(TTRC("License"));
233 price->set_text_overrun_behavior(TextServer::OVERRUN_TRIM_ELLIPSIS);
234 price->set_accessibility_name(TTRC("License"));
235 price->set_h_size_flags(Control::SIZE_EXPAND_FILL);
236 price->set_mouse_filter(MOUSE_FILTER_PASS);
237 author_price_hbox->add_child(price);
238
239 spacer = memnew(Control);
240 spacer->set_h_size_flags(Control::SIZE_EXPAND_FILL);
241 author_price_hbox->add_child(spacer);
242
243 set_custom_minimum_size(Size2(250, 80) * EDSCALE);
244 set_h_size_flags(Control::SIZE_EXPAND_FILL);
245 }
246
247 //////////////////////////////////////////////////////////////////////////////
248
249 void EditorAssetLibraryItemDescription::set_image(int p_type, int p_index, const Ref<Texture2D> &p_image) {
250 switch (p_type) {
251 case EditorAssetLibrary::IMAGE_QUEUE_ICON: {
252 item->call("set_image", p_type, p_index, p_image);
253 icon = p_image;
254 } break;
255 case EditorAssetLibrary::IMAGE_QUEUE_THUMBNAIL: {
256 for (int i = 0; i < preview_images.size(); i++) {
257 if (preview_images[i].id == p_index) {
258 if (preview_images[i].is_video) {
259 Ref<Image> overlay = previews->get_editor_theme_icon(SNAME("PlayOverlay"))->get_image();
260 Ref<Image> thumbnail = p_image->get_image();
261 thumbnail = thumbnail->duplicate();
262 Point2i overlay_pos = Point2i((thumbnail->get_width() - overlay->get_width()) / 2, (thumbnail->get_height() - overlay->get_height()) / 2);
263
264 // Overlay and thumbnail need the same format for `blend_rect` to work.
265 thumbnail->convert(Image::FORMAT_RGBA8);
266 thumbnail->blend_rect(overlay, overlay->get_used_rect(), overlay_pos);
267 preview_images[i].button->set_button_icon(ImageTexture::create_from_image(thumbnail));
268
269 // Make it clearer that clicking it will open an external link
270 preview_images[i].button->set_default_cursor_shape(Control::CURSOR_POINTING_HAND);
271 } else {
272 preview_images[i].button->set_button_icon(p_image);
273 }
274 break;
275 }
276 }
277 } break;
278 case EditorAssetLibrary::IMAGE_QUEUE_SCREENSHOT: {
279 for (int i = 0; i < preview_images.size(); i++) {
280 if (preview_images[i].id == p_index) {
281 preview_images.write[i].image = p_image;
282 if (preview_images[i].button->is_pressed()) {
283 _preview_click(p_index);
284 }
285 break;
286 }
287 }
288 } break;
289 }
290 }
291
292 void EditorAssetLibraryItemDescription::_notification(int p_what) {
293 switch (p_what) {
294 case NOTIFICATION_THEME_CHANGED: {
295 previews_bg->add_theme_style_override(SceneStringName(panel), previews->get_theme_stylebox(CoreStringName(normal), SNAME("TextEdit")));
296 } break;
297
298 case NOTIFICATION_POST_POPUP: {
299 callable_mp(item, &EditorAssetLibraryItem::calculate_misc_links_ratio).call_deferred();
300 } break;
301 }
302 }
303
304 void EditorAssetLibraryItemDescription::_bind_methods() {
305 ClassDB::bind_method(D_METHOD("set_image"), &EditorAssetLibraryItemDescription::set_image);
306 }
307
308 void EditorAssetLibraryItemDescription::_link_click(const String &p_url) {
309 ERR_FAIL_COND(!p_url.begins_with("http"));
310 OS::get_singleton()->shell_open(p_url);
311 }
312
313 void EditorAssetLibraryItemDescription::_preview_click(int p_id) {
314 for (int i = 0; i < preview_images.size(); i++) {
315 if (preview_images[i].id == p_id) {
316 preview_images[i].button->set_pressed(true);
317 if (!preview_images[i].is_video) {
318 if (preview_images[i].image.is_valid()) {
319 preview->set_texture(preview_images[i].image);
320 child_controls_changed();
321 }
322 } else {
323 _link_click(preview_images[i].video_link);
324 }
325 } else {
326 preview_images[i].button->set_pressed(false);
327 }
328 }
329 }
330
331 void EditorAssetLibraryItemDescription::configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, const String &p_cost, int p_version, const String &p_version_string, const String &p_description, const String &p_download_url, const String &p_browse_url, const String &p_sha256_hash) {
332 asset_id = p_asset_id;
333 title = p_title;
334 download_url = p_download_url;
335 sha256 = p_sha256_hash;
336 item->configure(p_title, p_asset_id, p_category, p_category_id, p_author, p_author_id, p_cost);
337 description->clear();
338 description->add_text(TTR("Version:") + " " + p_version_string + "\n");
339 description->add_text(TTR("Contents:") + " ");
340 description->push_meta(p_browse_url);
341 description->add_text(TTR("View Files"));
342 description->pop();
343 description->add_text("\n" + TTR("Description:") + "\n\n");
344 description->append_text(p_description);
345 description->set_selection_enabled(true);
346 description->set_context_menu_enabled(true);
347 set_title(p_title);
348 }
349
350 void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video, const String &p_url) {
351 if (preview_images.is_empty()) {
352 previews_vbox->show();
353 }
354
355 Preview new_preview;
356 new_preview.id = p_id;
357 new_preview.video_link = p_url;
358 new_preview.is_video = p_video;
359 new_preview.button = memnew(Button);
360 new_preview.button->set_button_icon(previews->get_editor_theme_icon(SNAME("ThumbnailWait")));
361 new_preview.button->set_toggle_mode(true);
362 new_preview.button->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItemDescription::_preview_click).bind(p_id));
363 preview_hb->add_child(new_preview.button);
364 if (!p_video) {
365 new_preview.image = previews->get_editor_theme_icon(SNAME("ThumbnailWait"));
366 }
367 preview_images.push_back(new_preview);
368 if (preview_images.size() == 1 && !p_video) {
369 _preview_click(p_id);
370 }
371 }
372
373 EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() {
374 HBoxContainer *hbox = memnew(HBoxContainer);
375 add_child(hbox);
376 VBoxContainer *desc_vbox = memnew(VBoxContainer);
377 hbox->add_child(desc_vbox);
378 hbox->add_theme_constant_override("separation", 15 * EDSCALE);
379
380 item = memnew(EditorAssetLibraryItem);
381
382 desc_vbox->add_child(item);
383 desc_vbox->set_custom_minimum_size(Size2(440 * EDSCALE, 440 * EDSCALE));
384
385 description = memnew(RichTextLabel);
386 desc_vbox->add_child(description);
387 description->set_v_size_flags(Control::SIZE_EXPAND_FILL);
388 description->connect("meta_clicked", callable_mp(this, &EditorAssetLibraryItemDescription::_link_click));
389 description->add_theme_constant_override(SceneStringName(line_separation), Math::round(5 * EDSCALE));
390
391 previews_vbox = memnew(VBoxContainer);
392 previews_vbox->hide(); // Will be shown if we add any previews later.
393
394 hbox->add_child(previews_vbox);
395 previews_vbox->add_theme_constant_override("separation", 15 * EDSCALE);
396 previews_vbox->set_v_size_flags(Control::SIZE_EXPAND_FILL);
397 previews_vbox->set_h_size_flags(Control::SIZE_EXPAND_FILL);
398
399 preview = memnew(TextureRect);
400 previews_vbox->add_child(preview);
401 preview->set_expand_mode(TextureRect::EXPAND_IGNORE_SIZE);
402 preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
403 preview->set_custom_minimum_size(Size2(640 * EDSCALE, 345 * EDSCALE));
404 preview->set_v_size_flags(Control::SIZE_EXPAND_FILL);
405 preview->set_h_size_flags(Control::SIZE_EXPAND_FILL);
406
407 previews_bg = memnew(PanelContainer);
408 previews_vbox->add_child(previews_bg);
409 previews_bg->set_custom_minimum_size(Size2(640 * EDSCALE, 101 * EDSCALE));
410
411 previews = memnew(ScrollContainer);
412 previews_bg->add_child(previews);
413 previews->set_vertical_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
414 preview_hb = memnew(HBoxContainer);
415 preview_hb->set_v_size_flags(Control::SIZE_EXPAND_FILL);
416
417 previews->add_child(preview_hb);
418 set_ok_button_text(TTRC("Download"));
419 set_cancel_button_text(TTRC("Close"));
420 }
421
422 ///////////////////////////////////////////////////////////////////////////////////
423
424 void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
425 String error_text;
426
427 switch (p_status) {
428 case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH:
429 case HTTPRequest::RESULT_CONNECTION_ERROR:
430 case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED: {
431 error_text = TTR("Connection error, please try again.");
432 status->set_text(TTRC("Can't connect."));
433 } break;
434 case HTTPRequest::RESULT_CANT_CONNECT:
435 case HTTPRequest::RESULT_TLS_HANDSHAKE_ERROR: {
436 error_text = TTR("Can't connect to host:") + " " + host;
437 status->set_text(TTRC("Can't connect."));
438 } break;
439 case HTTPRequest::RESULT_NO_RESPONSE: {
440 error_text = TTR("No response from host:") + " " + host;
441 status->set_text(TTRC("No response."));
442 } break;
443 case HTTPRequest::RESULT_CANT_RESOLVE: {
444 error_text = TTR("Can't resolve hostname:") + " " + host;
445 status->set_text(TTRC("Can't resolve."));
446 } break;
447 case HTTPRequest::RESULT_REQUEST_FAILED: {
448 error_text = TTR("Request failed, return code:") + " " + itos(p_code);
449 status->set_text(TTRC("Request failed."));
450 } break;
451 case HTTPRequest::RESULT_DOWNLOAD_FILE_CANT_OPEN:
452 case HTTPRequest::RESULT_DOWNLOAD_FILE_WRITE_ERROR: {
453 error_text = TTR("Cannot save response to:") + " " + download->get_download_file();
454 status->set_text(TTRC("Write error."));
455 } break;
456 case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
457 error_text = TTR("Request failed, too many redirects");
458 status->set_text(TTRC("Redirect loop."));
459 } break;
460 case HTTPRequest::RESULT_TIMEOUT: {
461 error_text = TTR("Request failed, timeout");
462 status->set_text(TTRC("Timeout."));
463 } break;
464 default: {
465 if (p_code != 200) {
466 error_text = TTR("Request failed, return code:") + " " + itos(p_code);
467 status->set_text(TTR("Failed:") + " " + itos(p_code));
468 } else if (!sha256.is_empty()) {
469 String download_sha256 = FileAccess::get_sha256(download->get_download_file());
470 if (sha256 != download_sha256) {
471 error_text = TTR("Bad download hash, assuming file has been tampered with.") + "\n";
472 error_text += TTR("Expected:") + " " + sha256 + "\n" + TTR("Got:") + " " + download_sha256;
473 status->set_text(TTRC("Failed SHA-256 hash check"));
474 }
475 }
476 } break;
477 }
478
479 // Make the progress bar invisible but don't reflow other Controls around it.
480 progress->set_modulate(Color(0, 0, 0, 0));
481 progress->set_indeterminate(false);
482
483 if (!error_text.is_empty()) {
484 download_error->set_text(TTR("Asset Download Error:") + "\n" + error_text);
485 download_error->popup_centered();
486 // Let the user retry the download.
487 retry_button->show();
488 return;
489 }
490
491 install_button->set_disabled(false);
492 status->set_text(TTRC("Ready to install!"));
493
494 set_process(false);
495
496 // Automatically prompt for installation once the download is completed.
497 install();
498 }
499
500 void EditorAssetLibraryItemDownload::configure(const String &p_title, int p_asset_id, const Ref<Texture2D> &p_preview, const String &p_download_url, const String &p_sha256_hash) {
501 title->set_text(p_title);
502 icon->set_texture(p_preview);
503 asset_id = p_asset_id;
504 if (p_preview.is_null()) {
505 icon->set_texture(get_editor_theme_icon(SNAME("FileBrokenBigThumb")));
506 }
507 host = p_download_url;
508 sha256 = p_sha256_hash;
509 _make_request();
510 }
511
512 void EditorAssetLibraryItemDownload::_notification(int p_what) {
513 switch (p_what) {
514 case NOTIFICATION_THEME_CHANGED: {
515 panel->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SceneStringName(panel), SNAME("AssetLib")));
516 status->add_theme_color_override(SceneStringName(font_color), get_theme_color(SNAME("status_color"), SNAME("AssetLib")));
517 dismiss_button->set_texture_normal(get_theme_icon(SNAME("dismiss"), SNAME("AssetLib")));
518 } break;
519
520 case NOTIFICATION_PROCESS: {
521 // Make the progress bar visible again when retrying the download.
522 progress->set_modulate(Color(1, 1, 1, 1));
523
524 if (download->get_downloaded_bytes() > 0) {
525 progress->set_max(download->get_body_size());
526 progress->set_value(download->get_downloaded_bytes());
527 }
528
529 int cstatus = download->get_http_client_status();
530
531 if (cstatus == HTTPClient::STATUS_BODY) {
532 if (download->get_body_size() > 0) {
533 progress->set_indeterminate(false);
534 status->set_text(vformat(
535 TTR("Downloading (%s / %s)..."),
536 String::humanize_size(download->get_downloaded_bytes()),
537 String::humanize_size(download->get_body_size())));
538 } else {
539 progress->set_indeterminate(true);
540 status->set_text(vformat(
541 TTR("Downloading...") + " (%s)",
542 String::humanize_size(download->get_downloaded_bytes())));
543 }
544 }
545
546 if (cstatus != prev_status) {
547 switch (cstatus) {
548 case HTTPClient::STATUS_RESOLVING: {
549 status->set_text(TTRC("Resolving..."));
550 progress->set_max(1);
551 progress->set_value(0);
552 } break;
553 case HTTPClient::STATUS_CONNECTING: {
554 status->set_text(TTRC("Connecting..."));
555 progress->set_max(1);
556 progress->set_value(0);
557 } break;
558 case HTTPClient::STATUS_REQUESTING: {
559 status->set_text(TTRC("Requesting..."));
560 progress->set_max(1);
561 progress->set_value(0);
562 } break;
563 default: {
564 }
565 }
566 prev_status = cstatus;
567 }
568 } break;
569 }
570 }
571
572 void EditorAssetLibraryItemDownload::_close() {
573 // Clean up downloaded file.
574 DirAccess::remove_file_or_error(download->get_download_file());
575 queue_free();
576 }
577
578 bool EditorAssetLibraryItemDownload::can_install() const {
579 return !install_button->is_disabled();
580 }
581
582 void EditorAssetLibraryItemDownload::install() {
583 String file = download->get_download_file();
584
585 if (external_install) {
586 emit_signal(SNAME("install_asset"), file, title->get_text());
587 return;
588 }
589
590 asset_installer->set_asset_name(title->get_text());
591 asset_installer->open_asset(file, true);
592 }
593
594 void EditorAssetLibraryItemDownload::_make_request() {
595 // Hide the Retry button if we've just pressed it.
596 retry_button->hide();
597
598 download->cancel_request();
599 download->set_download_file(EditorPaths::get_singleton()->get_cache_dir().path_join("tmp_asset_" + itos(asset_id)) + ".zip");
600
601 Error err = download->request(host);
602 if (err != OK) {
603 status->set_text(TTRC("Error making request"));
604 } else {
605 progress->set_indeterminate(true);
606 set_process(true);
607 }
608 }
609
610 void EditorAssetLibraryItemDownload::_bind_methods() {
611 ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
612 }
613
614 EditorAssetLibraryItemDownload::EditorAssetLibraryItemDownload() {
615 panel = memnew(PanelContainer);
616 add_child(panel);
617
618 HBoxContainer *hb = memnew(HBoxContainer);
619 panel->add_child(hb);
620 icon = memnew(TextureRect);
621 icon->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
622 icon->set_v_size_flags(0);
623 hb->add_child(icon);
624
625 VBoxContainer *vb = memnew(VBoxContainer);
626 hb->add_child(vb);
627 vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
628
629 HBoxContainer *title_hb = memnew(HBoxContainer);
630 vb->add_child(title_hb);
631 title = memnew(Label);
632 title->set_focus_mode(FOCUS_ACCESSIBILITY);
633 title_hb->add_child(title);
634 title->set_h_size_flags(Control::SIZE_EXPAND_FILL);
635
636 dismiss_button = memnew(TextureButton);
637 dismiss_button->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItemDownload::_close));
638 dismiss_button->set_accessibility_name(TTRC("Close"));
639 title_hb->add_child(dismiss_button);
640
641 title->set_clip_text(true);
642
643 vb->add_spacer();
644
645 status = memnew(Label(TTRC("Idle")));
646 vb->add_child(status);
647 progress = memnew(ProgressBar);
648 progress->set_editor_preview_indeterminate(true);
649 vb->add_child(progress);
650
651 HBoxContainer *hb2 = memnew(HBoxContainer);
652 vb->add_child(hb2);
653 hb2->add_spacer();
654
655 install_button = memnew(Button);
656 install_button->set_text(TTRC("Install..."));
657 install_button->set_disabled(true);
658 install_button->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItemDownload::install));
659
660 retry_button = memnew(Button);
661 retry_button->set_text(TTRC("Retry"));
662 retry_button->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibraryItemDownload::_make_request));
663 // Only show the Retry button in case of a failure.
664 retry_button->hide();
665
666 hb2->add_child(retry_button);
667 hb2->add_child(install_button);
668 set_custom_minimum_size(Size2(310, 0) * EDSCALE);
669
670 download = memnew(HTTPRequest);
671 panel->add_child(download);
672 download->connect("request_completed", callable_mp(this, &EditorAssetLibraryItemDownload::_http_download_completed));
673 setup_http_request(download);
674
675 download_error = memnew(AcceptDialog);
676 panel->add_child(download_error);
677 download_error->set_title(TTRC("Download Error"));
678
679 asset_installer = memnew(EditorAssetInstaller);
680 panel->add_child(asset_installer);
681 asset_installer->connect(SceneStringName(confirmed), callable_mp(this, &EditorAssetLibraryItemDownload::_close));
682
683 prev_status = -1;
684
685 external_install = false;
686 }
687
688 ////////////////////////////////////////////////////////////////////////////////
689 void EditorAssetLibrary::_notification(int p_what) {
690 switch (p_what) {
691 case NOTIFICATION_READY: {
692 add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("bg"), SNAME("AssetLib")));
693 error_label->move_to_front();
694 } break;
695
696 case NOTIFICATION_TRANSLATION_CHANGED: {
697 if (!initial_loading) {
698 _rerun_search(-1);
699 }
700 } break;
701
702 case NOTIFICATION_THEME_CHANGED: {
703 error_tr->set_texture(get_editor_theme_icon(SNAME("Error")));
704 filter->set_right_icon(get_editor_theme_icon(SNAME("Search")));
705 library_scroll->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SceneStringName(panel), SNAME("Tree")));
706 downloads_scroll->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("downloads"), SNAME("AssetLib")));
707 error_label->add_theme_color_override("color", get_theme_color(SNAME("error_color"), EditorStringName(Editor)));
708 } break;
709
710 case NOTIFICATION_VISIBILITY_CHANGED: {
711 if (is_visible()) {
712 #ifndef ANDROID_ENABLED
713 // Focus the search box automatically when switching to the Templates tab (in the Project Manager)
714 // or switching to the AssetLib tab (in the editor).
715 // The Project Manager's project filter box is automatically focused in the project manager code.
716 filter->grab_focus();
717 #endif
718
719 if (initial_loading) {
720 _repository_changed(0); // Update when shown for the first time.
721 }
722 }
723 } break;
724
725 case NOTIFICATION_PROCESS: {
726 HTTPClient::Status s = request->get_http_client_status();
727 const bool loading = s != HTTPClient::STATUS_DISCONNECTED;
728
729 if (loading) {
730 library_scroll->set_modulate(Color(1, 1, 1, 0.5));
731 } else {
732 library_scroll->set_modulate(Color(1, 1, 1, 1));
733 }
734
735 const bool no_downloads = downloads_hb->get_child_count() == 0;
736 if (no_downloads == downloads_scroll->is_visible()) {
737 downloads_scroll->set_visible(!no_downloads);
738
739 library_mc->set_theme_type_variation(no_downloads ? (Engine::get_singleton()->is_project_manager_hint() ? "NoBorderAssetLibProjectManager" : "NoBorderAssetLib") : "NoBorderHorizontal");
740 library_scroll->set_scroll_hint_mode(no_downloads ? ScrollContainer::SCROLL_HINT_MODE_TOP_AND_LEFT : ScrollContainer::SCROLL_HINT_MODE_ALL);
741 }
742
743 } break;
744
745 case NOTIFICATION_RESIZED: {
746 _update_asset_items_columns();
747 } break;
748
749 case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
750 if (!EditorSettings::get_singleton()->check_changed_settings_in_group("asset_library") &&
751 !EditorSettings::get_singleton()->check_changed_settings_in_group("network")) {
752 break;
753 }
754
755 _update_repository_options();
756 setup_http_request(request);
757
758 const bool loading_blocked_new = ((int)EDITOR_GET("network/connection/network_mode") == EditorSettings::NETWORK_OFFLINE);
759 if (loading_blocked_new != loading_blocked) {
760 loading_blocked = loading_blocked_new;
761
762 if (!loading_blocked && is_visible()) {
763 _request_current_config(); // Reload config now that the network is available.
764 }
765 }
766 } break;
767 }
768 }
769
770 void EditorAssetLibrary::_update_repository_options() {
771 // TODO: Move to editor_settings.cpp
772 Dictionary default_urls;
773 default_urls["godotengine.org (Official)"] = "https://godotengine.org/asset-library/api";
774 Dictionary available_urls = _EDITOR_DEF("asset_library/available_urls", default_urls, true);
775 repository->clear();
776 int i = 0;
777 for (const KeyValue<Variant, Variant> &kv : available_urls) {
778 repository->add_item(kv.key);
779 repository->set_item_metadata(i, kv.value);
780 i++;
781 }
782 }
783
784 void EditorAssetLibrary::shortcut_input(const Ref<InputEvent> &p_event) {
785 ERR_FAIL_COND(p_event.is_null());
786
787 const Ref<InputEventKey> key = p_event;
788
789 if (key.is_valid() && key->is_pressed()) {
790 if (key->is_match(InputEventKey::create_reference(KeyModifierMask::CMD_OR_CTRL | Key::F)) && is_visible_in_tree()) {
791 filter->grab_focus();
792 filter->select_all();
793 accept_event();
794 }
795 }
796 }
797
798 void EditorAssetLibrary::_install_asset() {
799 ERR_FAIL_NULL(description);
800
801 EditorAssetLibraryItemDownload *d = _get_asset_in_progress(description->get_asset_id());
802 if (d) {
803 d->install();
804 return;
805 }
806
807 EditorAssetLibraryItemDownload *download = memnew(EditorAssetLibraryItemDownload);
808 downloads_hb->add_child(download);
809 download->configure(description->get_title(), description->get_asset_id(), description->get_preview_icon(), description->get_download_url(), description->get_sha256());
810
811 if (templates_only) {
812 download->set_external_install(true);
813 download->connect("install_asset", callable_mp(this, &EditorAssetLibrary::_install_external_asset));
814 }
815 }
816
817 const char *EditorAssetLibrary::sort_key[SORT_MAX] = {
818 "updated",
819 "updated",
820 "name",
821 "name",
822 "cost",
823 "cost",
824 };
825
826 const char *EditorAssetLibrary::sort_text[SORT_MAX] = {
827 TTRC("Recently Updated"),
828 TTRC("Least Recently Updated"),
829 TTRC("Name (A-Z)"),
830 TTRC("Name (Z-A)"),
831 TTRC("License (A-Z)"), // "cost" stores the SPDX license name in the Godot Asset Library.
832 TTRC("License (Z-A)"), // "cost" stores the SPDX license name in the Godot Asset Library.
833 };
834
835 const char *EditorAssetLibrary::support_key[SUPPORT_MAX] = {
836 "official", // Former name for the Featured support level (still used on the API backend).
837 "community",
838 "testing",
839 };
840
841 const char *EditorAssetLibrary::support_text[SUPPORT_MAX] = {
842 TTRC("Featured"),
843 TTRC("Community"),
844 TTRC("Testing"),
845 };
846
847 void EditorAssetLibrary::_select_author(const String &p_author) {
848 if (!host.contains("godotengine.org")) {
849 // Don't open the link for alternative repositories.
850 return;
851 }
852 OS::get_singleton()->shell_open("https://godotengine.org/asset-library/asset?user=" + p_author.uri_encode());
853 }
854
855 void EditorAssetLibrary::_select_category(int p_id) {
856 for (int i = 0; i < categories->get_item_count(); i++) {
857 if (i == 0) {
858 continue;
859 }
860 int id = categories->get_item_metadata(i);
861 if (id == p_id) {
862 categories->select(i);
863 _search();
864 break;
865 }
866 }
867 }
868
869 void EditorAssetLibrary::_select_asset(int p_id) {
870 _api_request("asset/" + itos(p_id), REQUESTING_ASSET);
871 }
872
873 void EditorAssetLibrary::_image_update(bool p_use_cache, bool p_final, const PackedByteArray &p_data, int p_queue_id) {
874 Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
875 if (!obj) {
876 return;
877 }
878
879 bool image_set = false;
880 PackedByteArray image_data = p_data;
881
882 if (p_use_cache) {
883 String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
884
885 Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".data", FileAccess::READ);
886 if (file.is_valid()) {
887 PackedByteArray cached_data;
888 int len = file->get_32();
889 cached_data.resize(len);
890
891 uint8_t *w = cached_data.ptrw();
892 file->get_buffer(w, len);
893
894 image_data = cached_data;
895 }
896 }
897
898 int len = image_data.size();
899 const uint8_t *r = image_data.ptr();
900 Ref<Image> image = memnew(Image);
901
902 uint8_t png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
903 uint8_t jpg_signature[3] = { 255, 216, 255 };
904 uint8_t webp_signature[4] = { 82, 73, 70, 70 };
905 uint8_t bmp_signature[2] = { 66, 77 };
906
907 if (r) {
908 Ref<Image> parsed_image;
909
910 if ((memcmp(&r[0], &png_signature[0], 8) == 0) && Image::_png_mem_loader_func) {
911 parsed_image = Image::_png_mem_loader_func(r, len);
912 } else if ((memcmp(&r[0], &jpg_signature[0], 3) == 0) && Image::_jpg_mem_loader_func) {
913 parsed_image = Image::_jpg_mem_loader_func(r, len);
914 } else if ((memcmp(&r[0], &webp_signature[0], 4) == 0) && Image::_webp_mem_loader_func) {
915 parsed_image = Image::_webp_mem_loader_func(r, len);
916 } else if ((memcmp(&r[0], &bmp_signature[0], 2) == 0) && Image::_bmp_mem_loader_func) {
917 parsed_image = Image::_bmp_mem_loader_func(r, len);
918 } else if (Image::_svg_scalable_mem_loader_func) {
919 parsed_image = Image::_svg_scalable_mem_loader_func(r, len, 1.0);
920 }
921
922 if (parsed_image.is_null()) {
923 if (is_print_verbose_enabled()) {
924 ERR_PRINT(vformat("Asset Library: Invalid image downloaded from '%s' for asset # %d", image_queue[p_queue_id].image_url, image_queue[p_queue_id].asset_id));
925 }
926 } else {
927 image->copy_internals_from(parsed_image);
928 }
929 }
930
931 if (!image->is_empty()) {
932 switch (image_queue[p_queue_id].image_type) {
933 case IMAGE_QUEUE_ICON:
934 image->resize(64 * EDSCALE, 64 * EDSCALE, Image::INTERPOLATE_LANCZOS);
935 break;
936
937 case IMAGE_QUEUE_THUMBNAIL: {
938 float max_height = 85 * EDSCALE;
939
940 float scale_ratio = max_height / (image->get_height() * EDSCALE);
941 if (scale_ratio < 1) {
942 image->resize(image->get_width() * EDSCALE * scale_ratio, image->get_height() * EDSCALE * scale_ratio, Image::INTERPOLATE_LANCZOS);
943 }
944 } break;
945
946 case IMAGE_QUEUE_SCREENSHOT: {
947 float max_height = 397 * EDSCALE;
948
949 float scale_ratio = max_height / (image->get_height() * EDSCALE);
950 if (scale_ratio < 1) {
951 image->resize(image->get_width() * EDSCALE * scale_ratio, image->get_height() * EDSCALE * scale_ratio, Image::INTERPOLATE_LANCZOS);
952 }
953 } break;
954 }
955
956 Ref<ImageTexture> tex = ImageTexture::create_from_image(image);
957
958 obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, tex);
959 image_set = true;
960 }
961
962 if (!image_set && p_final) {
963 obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_editor_theme_icon(SNAME("FileBrokenBigThumb")));
964 }
965 }
966
967 void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data, int p_queue_id) {
968 ERR_FAIL_COND(!image_queue.has(p_queue_id));
969
970 if (p_status == HTTPRequest::RESULT_SUCCESS && p_code < HTTPClient::RESPONSE_BAD_REQUEST) {
971 if (p_code != HTTPClient::RESPONSE_NOT_MODIFIED) {
972 for (int i = 0; i < headers.size(); i++) {
973 if (headers[i].findn("ETag:") == 0) { // Save etag
974 String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
975 String new_etag = headers[i].substr(headers[i].find_char(':') + 1).strip_edges();
976 Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::WRITE);
977 if (file.is_valid()) {
978 file->store_line(new_etag);
979 }
980
981 int len = p_data.size();
982 const uint8_t *r = p_data.ptr();
983 file = FileAccess::open(cache_filename_base + ".data", FileAccess::WRITE);
984 if (file.is_valid()) {
985 file->store_32(len);
986 file->store_buffer(r, len);
987 }
988
989 break;
990 }
991 }
992 }
993 _image_update(p_code == HTTPClient::RESPONSE_NOT_MODIFIED, true, p_data, p_queue_id);
994
995 } else {
996 if (is_print_verbose_enabled()) {
997 WARN_PRINT(vformat("Asset Library: Error getting image from '%s' for asset # %d.", image_queue[p_queue_id].image_url, image_queue[p_queue_id].asset_id));
998 }
999
1000 Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
1001 if (obj) {
1002 obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_editor_theme_icon(SNAME("FileBrokenBigThumb")));
1003 }
1004 }
1005
1006 image_queue[p_queue_id].request->queue_free();
1007 image_queue.erase(p_queue_id);
1008
1009 _update_image_queue();
1010 }
1011
1012 void EditorAssetLibrary::_update_image_queue() {
1013 const int max_images = 6;
1014 int current_images = 0;
1015
1016 List<int> to_delete;
1017 for (KeyValue<int, ImageQueue> &E : image_queue) {
1018 if (!E.value.active && current_images < max_images) {
1019 String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + E.value.image_url.md5_text());
1020 Vector<String> headers;
1021
1022 if (FileAccess::exists(cache_filename_base + ".etag") && FileAccess::exists(cache_filename_base + ".data")) {
1023 Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::READ);
1024 if (file.is_valid()) {
1025 headers.push_back("If-None-Match: " + file->get_line());
1026 }
1027 }
1028
1029 Error err = E.value.request->request(E.value.image_url, headers);
1030 if (err != OK) {
1031 to_delete.push_back(E.key);
1032 } else {
1033 E.value.active = true;
1034 }
1035 current_images++;
1036 } else if (E.value.active) {
1037 current_images++;
1038 }
1039 }
1040
1041 while (to_delete.size()) {
1042 image_queue[to_delete.front()->get()].request->queue_free();
1043 image_queue.erase(to_delete.front()->get());
1044 to_delete.pop_front();
1045 }
1046 }
1047
1048 void EditorAssetLibrary::_request_image(ObjectID p_for, int p_asset_id, String p_image_url, ImageType p_type, int p_image_index) {
1049 // Remove extra spaces around the URL. This isn't strictly valid, but recoverable.
1050 String trimmed_url = p_image_url.strip_edges();
1051 if (trimmed_url != p_image_url && is_print_verbose_enabled()) {
1052 WARN_PRINT(vformat("Asset Library: Badly formatted image URL '%s' for asset # %d.", p_image_url, p_asset_id));
1053 }
1054
1055 // Validate the image URL first.
1056 {
1057 String url_scheme;
1058 String url_host;
1059 int url_port;
1060 String url_path;
1061 String url_fragment;
1062 Error err = trimmed_url.parse_url(url_scheme, url_host, url_port, url_path, url_fragment);
1063 if (err != OK) {
1064 if (is_print_verbose_enabled()) {
1065 ERR_PRINT(vformat("Asset Library: Invalid image URL '%s' for asset # %d.", trimmed_url, p_asset_id));
1066 }
1067
1068 Object *obj = ObjectDB::get_instance(p_for);
1069 if (obj) {
1070 obj->call("set_image", p_type, p_image_index, get_editor_theme_icon(SNAME("FileBrokenBigThumb")));
1071 }
1072 return;
1073 }
1074 }
1075
1076 ImageQueue iq;
1077 iq.image_url = trimmed_url;
1078 iq.image_index = p_image_index;
1079 iq.image_type = p_type;
1080 iq.request = memnew(HTTPRequest);
1081 setup_http_request(iq.request);
1082
1083 iq.target = p_for;
1084 iq.asset_id = p_asset_id;
1085 iq.queue_id = ++last_queue_id;
1086 iq.active = false;
1087
1088 iq.request->connect("request_completed", callable_mp(this, &EditorAssetLibrary::_image_request_completed).bind(iq.queue_id));
1089
1090 image_queue[iq.queue_id] = iq;
1091 add_child(iq.request);
1092
1093 _image_update(true, false, PackedByteArray(), iq.queue_id);
1094 _update_image_queue();
1095 }
1096
1097 void EditorAssetLibrary::_repository_changed(int p_repository_id) {
1098 _set_library_message(TTRC("Loading..."));
1099
1100 asset_top_page->hide();
1101 asset_bottom_page->hide();
1102 asset_items->hide();
1103
1104 filter->set_editable(false);
1105 sort->set_disabled(true);
1106 categories->set_disabled(true);
1107 support->set_disabled(true);
1108
1109 host = repository->get_item_metadata(p_repository_id);
1110 if (templates_only) {
1111 _api_request("configure", REQUESTING_CONFIG, "?type=project");
1112 } else {
1113 _api_request("configure", REQUESTING_CONFIG);
1114 }
1115 }
1116
1117 void EditorAssetLibrary::_support_toggled(int p_support) {
1118 support->get_popup()->set_item_checked(p_support, !support->get_popup()->is_item_checked(p_support));
1119 _search();
1120 }
1121
1122 void EditorAssetLibrary::_rerun_search(int p_ignore) {
1123 _search();
1124 }
1125
1126 void EditorAssetLibrary::_search(int p_page) {
1127 String args;
1128
1129 if (templates_only) {
1130 args += "?type=project&";
1131 } else {
1132 args += "?";
1133 }
1134 args += String() + "sort=" + sort_key[sort->get_selected()];
1135
1136 // We use the "branch" version, i.e. major.minor, as patch releases should be compatible
1137 args += "&godot_version=" + String(GODOT_VERSION_BRANCH);
1138
1139 String support_list;
1140 for (int i = 0; i < SUPPORT_MAX; i++) {
1141 if (support->get_popup()->is_item_checked(i)) {
1142 support_list += String(support_key[i]) + "+";
1143 }
1144 }
1145 if (!support_list.is_empty()) {
1146 args += "&support=" + support_list.substr(0, support_list.length() - 1);
1147 }
1148
1149 if (categories->get_selected() > 0) {
1150 args += "&category=" + itos(categories->get_item_metadata(categories->get_selected()));
1151 }
1152
1153 // Sorting options with an odd index are always the reverse of the previous one
1154 if (sort->get_selected() % 2 == 1) {
1155 args += "&reverse=true";
1156 }
1157
1158 if (!filter->get_text().is_empty()) {
1159 args += "&filter=" + filter->get_text().uri_encode();
1160 }
1161
1162 if (p_page > 0) {
1163 args += "&page=" + itos(p_page);
1164 }
1165
1166 _api_request("asset", REQUESTING_SEARCH, args);
1167 }
1168
1169 void EditorAssetLibrary::_search_text_changed(const String &p_text) {
1170 filter_debounce_timer->start();
1171 }
1172
1173 void EditorAssetLibrary::_filter_debounce_timer_timeout() {
1174 _search();
1175 }
1176
1177 void EditorAssetLibrary::_request_current_config() {
1178 _repository_changed(repository->get_selected());
1179 }
1180
1181 HBoxContainer *EditorAssetLibrary::_make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items) {
1182 HBoxContainer *hbc = memnew(HBoxContainer);
1183
1184 if (p_page_count < 2) {
1185 return hbc;
1186 }
1187
1188 //do the mario
1189 int from = p_page - (5 / EDSCALE);
1190 if (from < 0) {
1191 from = 0;
1192 }
1193 int to = from + (10 / EDSCALE);
1194 if (to > p_page_count) {
1195 to = p_page_count;
1196 }
1197
1198 hbc->add_spacer();
1199 hbc->add_theme_constant_override("separation", 5 * EDSCALE);
1200
1201 Button *first = memnew(Button);
1202 first->set_text(TTR("First", "Pagination"));
1203 first->set_theme_type_variation("PanelBackgroundButton");
1204 if (p_page != 0) {
1205 first->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_search).bind(0));
1206 } else {
1207 first->set_disabled(true);
1208 first->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
1209 }
1210 hbc->add_child(first);
1211
1212 Button *prev = memnew(Button);
1213 prev->set_text(TTR("Previous", "Pagination"));
1214 prev->set_theme_type_variation("PanelBackgroundButton");
1215 if (p_page > 0) {
1216 prev->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_search).bind(p_page - 1));
1217 } else {
1218 prev->set_disabled(true);
1219 prev->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
1220 }
1221 hbc->add_child(prev);
1222 hbc->add_child(memnew(VSeparator));
1223
1224 for (int i = from; i < to; i++) {
1225 Button *current = memnew(Button);
1226 // Add padding to make page number buttons easier to click.
1227 current->set_text(vformat(" %d ", i + 1));
1228 current->set_theme_type_variation("PanelBackgroundButton");
1229 if (i == p_page) {
1230 current->set_disabled(true);
1231 current->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
1232 } else {
1233 current->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_search).bind(i));
1234 }
1235 hbc->add_child(current);
1236 }
1237
1238 Button *next = memnew(Button);
1239 next->set_text(TTR("Next", "Pagination"));
1240 next->set_theme_type_variation("PanelBackgroundButton");
1241 if (p_page < p_page_count - 1) {
1242 next->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_search).bind(p_page + 1));
1243 } else {
1244 next->set_disabled(true);
1245 next->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
1246 }
1247 hbc->add_child(memnew(VSeparator));
1248 hbc->add_child(next);
1249
1250 Button *last = memnew(Button);
1251 last->set_text(TTR("Last", "Pagination"));
1252 last->set_theme_type_variation("PanelBackgroundButton");
1253 if (p_page != p_page_count - 1) {
1254 last->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_search).bind(p_page_count - 1));
1255 } else {
1256 last->set_disabled(true);
1257 last->set_focus_mode(Control::FOCUS_ACCESSIBILITY);
1258 }
1259 hbc->add_child(last);
1260
1261 hbc->add_spacer();
1262
1263 return hbc;
1264 }
1265
1266 void EditorAssetLibrary::_api_request(const String &p_request, RequestType p_request_type, const String &p_arguments) {
1267 if (requesting != REQUESTING_NONE) {
1268 request->cancel_request();
1269 }
1270 error_hb->hide();
1271
1272 if (loading_blocked) {
1273 _set_library_message_with_action(TTRC("The Asset Library requires an online connection and involves sending data over the internet."), TTRC("Go Online"), callable_mp(this, &EditorAssetLibrary::_force_online_mode));
1274 return;
1275 }
1276
1277 requesting = p_request_type;
1278 request->request(host + "/" + p_request + p_arguments);
1279 }
1280
1281 void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
1282 String str = String::utf8((const char *)p_data.ptr(), (int)p_data.size());
1283 bool error_abort = true;
1284
1285 switch (p_status) {
1286 case HTTPRequest::RESULT_CANT_RESOLVE: {
1287 error_label->set_text(TTR("Can't resolve hostname:") + " " + host);
1288 } break;
1289 case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
1290 case HTTPRequest::RESULT_CONNECTION_ERROR:
1291 case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH: {
1292 error_label->set_text(TTR("Connection error, please try again."));
1293 } break;
1294 case HTTPRequest::RESULT_TLS_HANDSHAKE_ERROR:
1295 case HTTPRequest::RESULT_CANT_CONNECT: {
1296 error_label->set_text(TTR("Can't connect to host:") + " " + host);
1297 } break;
1298 case HTTPRequest::RESULT_NO_RESPONSE: {
1299 error_label->set_text(TTR("No response from host:") + " " + host);
1300 } break;
1301 case HTTPRequest::RESULT_REQUEST_FAILED: {
1302 error_label->set_text(TTR("Request failed, return code:") + " " + itos(p_code));
1303 } break;
1304 case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
1305 error_label->set_text(TTRC("Request failed, too many redirects"));
1306
1307 } break;
1308 default: {
1309 if (p_code != 200) {
1310 error_label->set_text(TTR("Request failed, return code:") + " " + itos(p_code));
1311 } else {
1312 error_abort = false;
1313 }
1314 } break;
1315 }
1316
1317 if (error_abort) {
1318 if (requesting == REQUESTING_CONFIG) {
1319 _set_library_message_with_action(TTRC("Failed to get repository configuration."), TTRC("Retry"), callable_mp(this, &EditorAssetLibrary::_request_current_config));
1320 }
1321 error_hb->show();
1322 return;
1323 }
1324
1325 Dictionary d;
1326 {
1327 JSON json;
1328 json.parse(str);
1329 d = json.get_data();
1330 }
1331
1332 RequestType requested = requesting;
1333 requesting = REQUESTING_NONE;
1334
1335 switch (requested) {
1336 case REQUESTING_CONFIG: {
1337 categories->clear();
1338 categories->add_item(TTRC("All"));
1339 categories->set_item_metadata(0, 0);
1340 if (d.has("categories")) {
1341 Array clist = d["categories"];
1342 for (int i = 0; i < clist.size(); i++) {
1343 Dictionary cat = clist[i];
1344 if (!cat.has("name") || !cat.has("id")) {
1345 continue;
1346 }
1347 String name = cat["name"];
1348 int id = cat["id"];
1349 categories->add_item(name);
1350 categories->set_item_metadata(-1, id);
1351 category_map[cat["id"]] = name;
1352 }
1353 }
1354
1355 filter->set_editable(true);
1356 sort->set_disabled(false);
1357 categories->set_disabled(false);
1358 support->set_disabled(false);
1359
1360 _search();
1361 } break;
1362 case REQUESTING_SEARCH: {
1363 initial_loading = false;
1364
1365 if (asset_items) {
1366 memdelete(asset_items);
1367 }
1368
1369 if (asset_top_page) {
1370 memdelete(asset_top_page);
1371 }
1372
1373 if (asset_bottom_page) {
1374 memdelete(asset_bottom_page);
1375 }
1376
1377 int page = 0;
1378 int pages = 1;
1379 int page_len = 10;
1380 int total_items = 1;
1381 Array result;
1382
1383 if (d.has("page")) {
1384 page = d["page"];
1385 }
1386 if (d.has("pages")) {
1387 pages = d["pages"];
1388 }
1389 if (d.has("page_length")) {
1390 page_len = d["page_length"];
1391 }
1392 if (d.has("total")) {
1393 total_items = d["total"];
1394 }
1395 if (d.has("result")) {
1396 result = d["result"];
1397 }
1398
1399 asset_top_page = _make_pages(page, pages, page_len, total_items, result.size());
1400 library_vb->add_child(asset_top_page);
1401
1402 asset_items = memnew(GridContainer);
1403 _update_asset_items_columns();
1404 asset_items->add_theme_constant_override("h_separation", 10 * EDSCALE);
1405 asset_items->add_theme_constant_override("v_separation", 10 * EDSCALE);
1406
1407 library_vb->add_child(asset_items);
1408
1409 asset_bottom_page = _make_pages(page, pages, page_len, total_items, result.size());
1410 library_vb->add_child(asset_bottom_page);
1411
1412 if (result.is_empty()) {
1413 String support_list;
1414 for (int i = 0; i < SUPPORT_MAX; i++) {
1415 if (support->get_popup()->is_item_checked(i)) {
1416 if (!support_list.is_empty()) {
1417 support_list += ", ";
1418 }
1419 support_list += TTRGET(support_text[i]);
1420 }
1421 }
1422 if (support_list.is_empty()) {
1423 support_list = "-";
1424 }
1425
1426 if (!filter->get_text().is_empty()) {
1427 _set_library_message(
1428 vformat(TTR("No results for \"%s\" for support level(s): %s."), filter->get_text(), support_list));
1429 } else {
1430 // No results, even though the user didn't search for anything specific.
1431 // This is typically because the version number changed recently
1432 // and no assets compatible with the new version have been published yet.
1433 _set_library_message(
1434 vformat(TTR("No results compatible with %s %s for support level(s): %s.\nCheck the enabled support levels using the 'Support' button in the top-right corner."), String(GODOT_VERSION_SHORT_NAME).capitalize(), String(GODOT_VERSION_BRANCH), support_list));
1435 }
1436 } else {
1437 library_message_box->hide();
1438 }
1439
1440 for (int i = 0; i < result.size(); i++) {
1441 Dictionary r = result[i];
1442
1443 ERR_CONTINUE(!r.has("title"));
1444 ERR_CONTINUE(!r.has("asset_id"));
1445 ERR_CONTINUE(!r.has("author"));
1446 ERR_CONTINUE(!r.has("author_id"));
1447 ERR_CONTINUE(!r.has("category_id"));
1448 ERR_FAIL_COND(!category_map.has(r["category_id"]));
1449 ERR_CONTINUE(!r.has("cost"));
1450
1451 EditorAssetLibraryItem *item = memnew(EditorAssetLibraryItem(true));
1452 asset_items->add_child(item);
1453 asset_items->connect(SceneStringName(sort_children), callable_mp(item, &EditorAssetLibraryItem::calculate_misc_links_ratio));
1454 item->configure(r["title"], r["asset_id"], category_map[r["category_id"]], r["category_id"], r["author"], r["author_id"], r["cost"]);
1455 item->connect("asset_selected", callable_mp(this, &EditorAssetLibrary::_select_asset));
1456 item->connect("author_selected", callable_mp(this, &EditorAssetLibrary::_select_author));
1457 item->connect("category_selected", callable_mp(this, &EditorAssetLibrary::_select_category));
1458
1459 if (r.has("icon_url") && !r["icon_url"].operator String().is_empty()) {
1460 _request_image(item->get_instance_id(), r["asset_id"], r["icon_url"], IMAGE_QUEUE_ICON, 0);
1461 }
1462 }
1463
1464 if (!result.is_empty()) {
1465 library_scroll->set_v_scroll(0);
1466 }
1467 } break;
1468 case REQUESTING_ASSET: {
1469 Dictionary r = d;
1470
1471 ERR_FAIL_COND(!r.has("title"));
1472 ERR_FAIL_COND(!r.has("asset_id"));
1473 ERR_FAIL_COND(!r.has("author"));
1474 ERR_FAIL_COND(!r.has("author_id"));
1475 ERR_FAIL_COND(!r.has("version"));
1476 ERR_FAIL_COND(!r.has("version_string"));
1477 ERR_FAIL_COND(!r.has("category_id"));
1478 ERR_FAIL_COND(!category_map.has(r["category_id"]));
1479 ERR_FAIL_COND(!r.has("cost"));
1480 ERR_FAIL_COND(!r.has("description"));
1481 ERR_FAIL_COND(!r.has("download_url"));
1482 ERR_FAIL_COND(!r.has("download_hash"));
1483 ERR_FAIL_COND(!r.has("browse_url"));
1484
1485 if (description) {
1486 memdelete(description);
1487 }
1488
1489 description = memnew(EditorAssetLibraryItemDescription);
1490 add_child(description);
1491 description->connect(SceneStringName(confirmed), callable_mp(this, &EditorAssetLibrary::_install_asset));
1492
1493 description->configure(r["title"], r["asset_id"], category_map[r["category_id"]], r["category_id"], r["author"], r["author_id"], r["cost"], r["version"], r["version_string"], r["description"], r["download_url"], r["browse_url"], r["download_hash"]);
1494
1495 EditorAssetLibraryItemDownload *download_item = _get_asset_in_progress(description->get_asset_id());
1496 if (download_item) {
1497 if (download_item->can_install()) {
1498 description->set_ok_button_text(TTRC("Install"));
1499 description->get_ok_button()->set_disabled(false);
1500 } else {
1501 description->set_ok_button_text(TTRC("Downloading..."));
1502 description->get_ok_button()->set_disabled(true);
1503 }
1504 } else {
1505 description->set_ok_button_text(TTRC("Download"));
1506 description->get_ok_button()->set_disabled(false);
1507 }
1508
1509 if (r.has("icon_url") && !r["icon_url"].operator String().is_empty()) {
1510 _request_image(description->get_instance_id(), r["asset_id"], r["icon_url"], IMAGE_QUEUE_ICON, 0);
1511 }
1512
1513 if (d.has("previews")) {
1514 Array previews = d["previews"];
1515
1516 for (int i = 0; i < previews.size(); i++) {
1517 Dictionary p = previews[i];
1518
1519 ERR_CONTINUE(!p.has("type"));
1520 ERR_CONTINUE(!p.has("link"));
1521
1522 bool is_video = p.has("type") && String(p["type"]) == "video";
1523 String video_url;
1524 if (is_video && p.has("link")) {
1525 video_url = p["link"];
1526 }
1527
1528 description->add_preview(i, is_video, video_url);
1529
1530 if (p.has("thumbnail")) {
1531 _request_image(description->get_instance_id(), r["asset_id"], p["thumbnail"], IMAGE_QUEUE_THUMBNAIL, i);
1532 }
1533
1534 if (!is_video) {
1535 _request_image(description->get_instance_id(), r["asset_id"], p["link"], IMAGE_QUEUE_SCREENSHOT, i);
1536 }
1537 }
1538 }
1539
1540 description->popup_centered();
1541 } break;
1542 default:
1543 break;
1544 }
1545 }
1546
1547 void EditorAssetLibrary::_asset_file_selected(const String &p_file) {
1548 if (asset_installer) {
1549 memdelete(asset_installer);
1550 asset_installer = nullptr;
1551 }
1552
1553 asset_installer = memnew(EditorAssetInstaller);
1554 asset_installer->set_asset_name(p_file);
1555 add_child(asset_installer);
1556 asset_installer->open_asset(p_file);
1557 }
1558
1559 void EditorAssetLibrary::_asset_open() {
1560 asset_open->popup_file_dialog();
1561 }
1562
1563 void EditorAssetLibrary::_manage_plugins() {
1564 ProjectSettingsEditor::get_singleton()->popup_project_settings(true);
1565 ProjectSettingsEditor::get_singleton()->set_plugins_page();
1566 }
1567
1568 EditorAssetLibraryItemDownload *EditorAssetLibrary::_get_asset_in_progress(int p_asset_id) const {
1569 for (int i = 0; i < downloads_hb->get_child_count(); i++) {
1570 EditorAssetLibraryItemDownload *d = Object::cast_to<EditorAssetLibraryItemDownload>(downloads_hb->get_child(i));
1571 if (d && d->get_asset_id() == p_asset_id) {
1572 return d;
1573 }
1574 }
1575
1576 return nullptr;
1577 }
1578
1579 void EditorAssetLibrary::_install_external_asset(String p_zip_path, String p_title) {
1580 emit_signal(SNAME("install_asset"), p_zip_path, p_title);
1581 }
1582
1583 void EditorAssetLibrary::_update_asset_items_columns() {
1584 int new_columns = get_size().x / (450.0 * EDSCALE);
1585 new_columns = MAX(1, new_columns);
1586
1587 if (new_columns != asset_items->get_columns()) {
1588 asset_items->set_columns(new_columns);
1589 }
1590 }
1591
1592 void EditorAssetLibrary::_set_library_message(const String &p_message) {
1593 library_message->set_text(p_message);
1594
1595 if (library_message_action.is_valid()) {
1596 library_message_button->disconnect(SceneStringName(pressed), library_message_action);
1597 library_message_action = Callable();
1598 }
1599 library_message_button->hide();
1600
1601 library_message_box->show();
1602 }
1603
1604 void EditorAssetLibrary::_set_library_message_with_action(const String &p_message, const String &p_action_text, const Callable &p_action) {
1605 library_message->set_text(p_message);
1606
1607 library_message_button->set_text(p_action_text);
1608 if (library_message_action.is_valid()) {
1609 library_message_button->disconnect(SceneStringName(pressed), library_message_action);
1610 library_message_action = Callable();
1611 }
1612 library_message_action = p_action;
1613 library_message_button->connect(SceneStringName(pressed), library_message_action);
1614 library_message_button->show();
1615
1616 library_message_box->show();
1617 }
1618
1619 void EditorAssetLibrary::_force_online_mode() {
1620 EditorSettings::get_singleton()->set_setting("network/connection/network_mode", EditorSettings::NETWORK_ONLINE);
1621 EditorSettings::get_singleton()->notify_changes();
1622 EditorSettings::get_singleton()->save();
1623 }
1624
1625 void EditorAssetLibrary::disable_community_support() {
1626 support->get_popup()->set_item_checked(SUPPORT_COMMUNITY, false);
1627 }
1628
1629 void EditorAssetLibrary::_bind_methods() {
1630 ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
1631 }
1632
1633 EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
1634 requesting = REQUESTING_NONE;
1635 templates_only = p_templates_only;
1636 loading_blocked = ((int)EDITOR_GET("network/connection/network_mode") == EditorSettings::NETWORK_OFFLINE);
1637
1638 VBoxContainer *library_main = memnew(VBoxContainer);
1639 add_child(library_main);
1640
1641 HBoxContainer *search_hb = memnew(HBoxContainer);
1642
1643 library_main->add_child(search_hb);
1644 library_main->add_theme_constant_override("separation", 10 * EDSCALE);
1645
1646 filter = memnew(LineEdit);
1647 if (templates_only) {
1648 filter->set_placeholder(TTRC("Search Templates, Projects, and Demos"));
1649 } else {
1650 filter->set_placeholder(TTRC("Search Assets (Excluding Templates, Projects, and Demos)"));
1651 }
1652 filter->set_clear_button_enabled(true);
1653 search_hb->add_child(filter);
1654 filter->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1655 filter->connect(SceneStringName(text_changed), callable_mp(this, &EditorAssetLibrary::_search_text_changed));
1656
1657 // Perform a search automatically if the user hasn't entered any text for a certain duration.
1658 // This way, the user doesn't need to press Enter to initiate their search.
1659 filter_debounce_timer = memnew(Timer);
1660 filter_debounce_timer->set_one_shot(true);
1661 filter_debounce_timer->set_wait_time(0.25);
1662 filter_debounce_timer->connect("timeout", callable_mp(this, &EditorAssetLibrary::_filter_debounce_timer_timeout));
1663 search_hb->add_child(filter_debounce_timer);
1664
1665 if (!p_templates_only) {
1666 search_hb->add_child(memnew(VSeparator));
1667 }
1668
1669 Button *open_asset = memnew(Button);
1670 open_asset->set_text(TTRC("Import..."));
1671 search_hb->add_child(open_asset);
1672 open_asset->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_asset_open));
1673
1674 Button *plugins = memnew(Button);
1675 plugins->set_text(TTRC("Plugins..."));
1676 search_hb->add_child(plugins);
1677 plugins->connect(SceneStringName(pressed), callable_mp(this, &EditorAssetLibrary::_manage_plugins));
1678
1679 if (p_templates_only) {
1680 open_asset->hide();
1681 plugins->hide();
1682 }
1683
1684 HBoxContainer *search_hb2 = memnew(HBoxContainer);
1685 library_main->add_child(search_hb2);
1686
1687 search_hb2->add_child(memnew(Label(TTRC("Sort:"))));
1688 sort = memnew(OptionButton);
1689 for (int i = 0; i < SORT_MAX; i++) {
1690 sort->add_item(sort_text[i]);
1691 }
1692
1693 search_hb2->add_child(sort);
1694
1695 sort->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1696 sort->set_clip_text(true);
1697 sort->connect(SceneStringName(item_selected), callable_mp(this, &EditorAssetLibrary::_rerun_search));
1698
1699 search_hb2->add_child(memnew(VSeparator));
1700
1701 search_hb2->add_child(memnew(Label(TTRC("Category:"))));
1702 categories = memnew(OptionButton);
1703 categories->add_item(TTRC("All"));
1704 search_hb2->add_child(categories);
1705 categories->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1706 categories->set_clip_text(true);
1707 categories->connect(SceneStringName(item_selected), callable_mp(this, &EditorAssetLibrary::_rerun_search));
1708
1709 search_hb2->add_child(memnew(VSeparator));
1710
1711 search_hb2->add_child(memnew(Label(TTRC("Site:"))));
1712 repository = memnew(OptionButton);
1713
1714 _update_repository_options();
1715
1716 repository->connect(SceneStringName(item_selected), callable_mp(this, &EditorAssetLibrary::_repository_changed));
1717
1718 search_hb2->add_child(repository);
1719 repository->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1720 repository->set_clip_text(true);
1721
1722 search_hb2->add_child(memnew(VSeparator));
1723
1724 support = memnew(MenuButton);
1725 search_hb2->add_child(support);
1726 support->set_text(TTRC("Support"));
1727 support->get_popup()->set_hide_on_checkable_item_selection(false);
1728 support->get_popup()->add_check_item(support_text[SUPPORT_FEATURED], SUPPORT_FEATURED);
1729 support->get_popup()->add_check_item(support_text[SUPPORT_COMMUNITY], SUPPORT_COMMUNITY);
1730 support->get_popup()->add_check_item(support_text[SUPPORT_TESTING], SUPPORT_TESTING);
1731 support->get_popup()->set_item_checked(SUPPORT_FEATURED, true);
1732 support->get_popup()->set_item_checked(SUPPORT_COMMUNITY, true);
1733 support->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &EditorAssetLibrary::_support_toggled));
1734
1735 /////////
1736
1737 library_mc = memnew(MarginContainer);
1738 library_mc->set_theme_type_variation(Engine::get_singleton()->is_project_manager_hint() ? "NoBorderAssetLibProjectManager" : "NoBorderAssetLib");
1739 library_mc->set_v_size_flags(Control::SIZE_EXPAND_FILL);
1740 library_main->add_child(library_mc);
1741
1742 library_scroll = memnew(ScrollContainer);
1743 library_scroll->set_scroll_hint_mode(ScrollContainer::SCROLL_HINT_MODE_TOP_AND_LEFT);
1744 library_scroll->set_horizontal_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
1745 library_mc->add_child(library_scroll);
1746
1747 Ref<StyleBoxEmpty> border2;
1748 border2.instantiate();
1749 border2->set_content_margin_individual(15 * EDSCALE, 15 * EDSCALE, 35 * EDSCALE, 15 * EDSCALE);
1750
1751 PanelContainer *library_vb_border = memnew(PanelContainer);
1752 library_scroll->add_child(library_vb_border);
1753 library_vb_border->add_theme_style_override(SceneStringName(panel), border2);
1754 library_vb_border->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1755
1756 library_vb = memnew(VBoxContainer);
1757 library_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
1758
1759 library_vb_border->add_child(library_vb);
1760
1761 library_message_box = memnew(VBoxContainer);
1762 library_message_box->hide();
1763 library_vb->add_child(library_message_box);
1764
1765 library_message = memnew(Label);
1766 library_message->set_focus_mode(FOCUS_ACCESSIBILITY);
1767 library_message->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
1768 library_message_box->add_child(library_message);
1769
1770 library_message_button = memnew(Button);
1771 library_message_button->set_h_size_flags(SIZE_SHRINK_CENTER);
1772 library_message_button->set_theme_type_variation("PanelBackgroundButton");
1773 library_message_box->add_child(library_message_button);
1774
1775 asset_top_page = memnew(HBoxContainer);
1776 library_vb->add_child(asset_top_page);
1777
1778 asset_items = memnew(GridContainer);
1779 _update_asset_items_columns();
1780 asset_items->add_theme_constant_override("h_separation", 10 * EDSCALE);
1781 asset_items->add_theme_constant_override("v_separation", 10 * EDSCALE);
1782
1783 library_vb->add_child(asset_items);
1784
1785 asset_bottom_page = memnew(HBoxContainer);
1786 library_vb->add_child(asset_bottom_page);
1787
1788 request = memnew(HTTPRequest);
1789 add_child(request);
1790 setup_http_request(request);
1791 request->connect("request_completed", callable_mp(this, &EditorAssetLibrary::_http_request_completed));
1792
1793 last_queue_id = 0;
1794
1795 library_vb->add_theme_constant_override("separation", 20 * EDSCALE);
1796
1797 error_hb = memnew(HBoxContainer);
1798 library_main->add_child(error_hb);
1799 error_label = memnew(Label);
1800 error_label->set_focus_mode(FOCUS_ACCESSIBILITY);
1801 error_hb->add_child(error_label);
1802 error_tr = memnew(TextureRect);
1803 error_tr->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
1804 error_hb->add_child(error_tr);
1805
1806 description = nullptr;
1807
1808 set_process(true);
1809 set_process_shortcut_input(true); // Global shortcuts since there is no main element to be focused.
1810
1811 downloads_scroll = memnew(ScrollContainer);
1812 downloads_scroll->set_vertical_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
1813 downloads_scroll->set_theme_type_variation("ScrollContainerSecondary");
1814 library_main->add_child(downloads_scroll);
1815 downloads_hb = memnew(HBoxContainer);
1816 downloads_scroll->add_child(downloads_hb);
1817
1818 asset_open = memnew(EditorFileDialog);
1819
1820 asset_open->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
1821 asset_open->add_filter("*.zip", TTRC("Assets ZIP File"));
1822 asset_open->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
1823 add_child(asset_open);
1824 asset_open->connect("file_selected", callable_mp(this, &EditorAssetLibrary::_asset_file_selected));
1825
1826 asset_installer = nullptr;
1827 }
1828
1829 ///////
1830
1831 bool AssetLibraryEditorPlugin::is_available() {
1832 #ifdef WEB_ENABLED
1833 // Asset Library can't work on Web editor for now as most assets are sourced
1834 // directly from GitHub which does not set CORS.
1835 return false;
1836 #else
1837 return StreamPeerTLS::is_available() && !Engine::get_singleton()->is_recovery_mode_hint();
1838 #endif
1839 }
1840
1841 void AssetLibraryEditorPlugin::make_visible(bool p_visible) {
1842 if (p_visible) {
1843 addon_library->show();
1844 } else {
1845 addon_library->hide();
1846 }
1847 }
1848
1849 AssetLibraryEditorPlugin::AssetLibraryEditorPlugin() {
1850 addon_library = memnew(EditorAssetLibrary);
1851 addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL);
1852 EditorNode::get_singleton()->get_editor_main_screen()->get_control()->add_child(addon_library);
1853 addon_library->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
1854 addon_library->hide();
1855 }