asset_library_editor_plugin.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "asset_library_editor_plugin.h"
  31. #include "core/input/input.h"
  32. #include "core/io/json.h"
  33. #include "core/io/stream_peer_ssl.h"
  34. #include "core/os/keyboard.h"
  35. #include "core/version.h"
  36. #include "editor/editor_file_dialog.h"
  37. #include "editor/editor_node.h"
  38. #include "editor/editor_paths.h"
  39. #include "editor/editor_scale.h"
  40. #include "editor/editor_settings.h"
  41. #include "editor/project_settings_editor.h"
  42. static inline void setup_http_request(HTTPRequest *request) {
  43. request->set_use_threads(EDITOR_DEF("asset_library/use_threads", true));
  44. const String proxy_host = EDITOR_GET("network/http_proxy/host");
  45. const int proxy_port = EDITOR_GET("network/http_proxy/port");
  46. request->set_http_proxy(proxy_host, proxy_port);
  47. request->set_https_proxy(proxy_host, proxy_port);
  48. }
  49. 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) {
  50. title->set_text(p_title);
  51. asset_id = p_asset_id;
  52. category->set_text(p_category);
  53. category_id = p_category_id;
  54. author->set_text(p_author);
  55. author_id = p_author_id;
  56. price->set_text(p_cost);
  57. }
  58. void EditorAssetLibraryItem::set_image(int p_type, int p_index, const Ref<Texture2D> &p_image) {
  59. ERR_FAIL_COND(p_type != EditorAssetLibrary::IMAGE_QUEUE_ICON);
  60. ERR_FAIL_COND(p_index != 0);
  61. icon->set_normal_texture(p_image);
  62. }
  63. void EditorAssetLibraryItem::_notification(int p_what) {
  64. switch (p_what) {
  65. case NOTIFICATION_ENTER_TREE: {
  66. icon->set_normal_texture(get_theme_icon(SNAME("ProjectIconLoading"), SNAME("EditorIcons")));
  67. category->add_theme_color_override("font_color", Color(0.5, 0.5, 0.5));
  68. author->add_theme_color_override("font_color", Color(0.5, 0.5, 0.5));
  69. price->add_theme_color_override("font_color", Color(0.5, 0.5, 0.5));
  70. } break;
  71. }
  72. }
  73. void EditorAssetLibraryItem::_asset_clicked() {
  74. emit_signal(SNAME("asset_selected"), asset_id);
  75. }
  76. void EditorAssetLibraryItem::_category_clicked() {
  77. emit_signal(SNAME("category_selected"), category_id);
  78. }
  79. void EditorAssetLibraryItem::_author_clicked() {
  80. emit_signal(SNAME("author_selected"), author_id);
  81. }
  82. void EditorAssetLibraryItem::_bind_methods() {
  83. ClassDB::bind_method("set_image", &EditorAssetLibraryItem::set_image);
  84. ADD_SIGNAL(MethodInfo("asset_selected"));
  85. ADD_SIGNAL(MethodInfo("category_selected"));
  86. ADD_SIGNAL(MethodInfo("author_selected"));
  87. }
  88. EditorAssetLibraryItem::EditorAssetLibraryItem() {
  89. Ref<StyleBoxEmpty> border;
  90. border.instantiate();
  91. border->set_default_margin(SIDE_LEFT, 5 * EDSCALE);
  92. border->set_default_margin(SIDE_RIGHT, 5 * EDSCALE);
  93. border->set_default_margin(SIDE_BOTTOM, 5 * EDSCALE);
  94. border->set_default_margin(SIDE_TOP, 5 * EDSCALE);
  95. add_theme_style_override("panel", border);
  96. HBoxContainer *hb = memnew(HBoxContainer);
  97. // Add some spacing to visually separate the icon from the asset details.
  98. hb->add_theme_constant_override("separation", 15 * EDSCALE);
  99. add_child(hb);
  100. icon = memnew(TextureButton);
  101. icon->set_custom_minimum_size(Size2(64, 64) * EDSCALE);
  102. icon->set_default_cursor_shape(CURSOR_POINTING_HAND);
  103. icon->connect("pressed", callable_mp(this, &EditorAssetLibraryItem::_asset_clicked));
  104. hb->add_child(icon);
  105. VBoxContainer *vb = memnew(VBoxContainer);
  106. hb->add_child(vb);
  107. vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  108. title = memnew(LinkButton);
  109. title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
  110. title->connect("pressed", callable_mp(this, &EditorAssetLibraryItem::_asset_clicked));
  111. vb->add_child(title);
  112. category = memnew(LinkButton);
  113. category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
  114. category->connect("pressed", callable_mp(this, &EditorAssetLibraryItem::_category_clicked));
  115. vb->add_child(category);
  116. author = memnew(LinkButton);
  117. author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
  118. author->connect("pressed", callable_mp(this, &EditorAssetLibraryItem::_author_clicked));
  119. vb->add_child(author);
  120. price = memnew(Label);
  121. vb->add_child(price);
  122. set_custom_minimum_size(Size2(250, 100) * EDSCALE);
  123. set_h_size_flags(Control::SIZE_EXPAND_FILL);
  124. }
  125. //////////////////////////////////////////////////////////////////////////////
  126. void EditorAssetLibraryItemDescription::set_image(int p_type, int p_index, const Ref<Texture2D> &p_image) {
  127. switch (p_type) {
  128. case EditorAssetLibrary::IMAGE_QUEUE_ICON: {
  129. item->call("set_image", p_type, p_index, p_image);
  130. icon = p_image;
  131. } break;
  132. case EditorAssetLibrary::IMAGE_QUEUE_THUMBNAIL: {
  133. for (int i = 0; i < preview_images.size(); i++) {
  134. if (preview_images[i].id == p_index) {
  135. if (preview_images[i].is_video) {
  136. Ref<Image> overlay = previews->get_theme_icon(SNAME("PlayOverlay"), SNAME("EditorIcons"))->get_image();
  137. Ref<Image> thumbnail = p_image->get_image();
  138. thumbnail = thumbnail->duplicate();
  139. Point2i overlay_pos = Point2i((thumbnail->get_width() - overlay->get_width()) / 2, (thumbnail->get_height() - overlay->get_height()) / 2);
  140. // Overlay and thumbnail need the same format for `blend_rect` to work.
  141. thumbnail->convert(Image::FORMAT_RGBA8);
  142. thumbnail->blend_rect(overlay, overlay->get_used_rect(), overlay_pos);
  143. preview_images[i].button->set_icon(ImageTexture::create_from_image(thumbnail));
  144. // Make it clearer that clicking it will open an external link
  145. preview_images[i].button->set_default_cursor_shape(Control::CURSOR_POINTING_HAND);
  146. } else {
  147. preview_images[i].button->set_icon(p_image);
  148. }
  149. break;
  150. }
  151. }
  152. } break;
  153. case EditorAssetLibrary::IMAGE_QUEUE_SCREENSHOT: {
  154. for (int i = 0; i < preview_images.size(); i++) {
  155. if (preview_images[i].id == p_index) {
  156. preview_images.write[i].image = p_image;
  157. if (preview_images[i].button->is_pressed()) {
  158. _preview_click(p_index);
  159. }
  160. break;
  161. }
  162. }
  163. } break;
  164. }
  165. }
  166. void EditorAssetLibraryItemDescription::_notification(int p_what) {
  167. switch (p_what) {
  168. case NOTIFICATION_ENTER_TREE:
  169. case NOTIFICATION_THEME_CHANGED: {
  170. previews_bg->add_theme_style_override("panel", previews->get_theme_stylebox(SNAME("normal"), SNAME("TextEdit")));
  171. } break;
  172. }
  173. }
  174. void EditorAssetLibraryItemDescription::_bind_methods() {
  175. ClassDB::bind_method(D_METHOD("set_image"), &EditorAssetLibraryItemDescription::set_image);
  176. }
  177. void EditorAssetLibraryItemDescription::_link_click(const String &p_url) {
  178. ERR_FAIL_COND(!p_url.begins_with("http"));
  179. OS::get_singleton()->shell_open(p_url);
  180. }
  181. void EditorAssetLibraryItemDescription::_preview_click(int p_id) {
  182. for (int i = 0; i < preview_images.size(); i++) {
  183. if (preview_images[i].id == p_id) {
  184. preview_images[i].button->set_pressed(true);
  185. if (!preview_images[i].is_video) {
  186. if (preview_images[i].image.is_valid()) {
  187. preview->set_texture(preview_images[i].image);
  188. child_controls_changed();
  189. }
  190. } else {
  191. _link_click(preview_images[i].video_link);
  192. }
  193. } else {
  194. preview_images[i].button->set_pressed(false);
  195. }
  196. }
  197. }
  198. 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) {
  199. asset_id = p_asset_id;
  200. title = p_title;
  201. download_url = p_download_url;
  202. sha256 = p_sha256_hash;
  203. item->configure(p_title, p_asset_id, p_category, p_category_id, p_author, p_author_id, p_cost);
  204. description->clear();
  205. description->add_text(TTR("Version:") + " " + p_version_string + "\n");
  206. description->add_text(TTR("Contents:") + " ");
  207. description->push_meta(p_browse_url);
  208. description->add_text(TTR("View Files"));
  209. description->pop();
  210. description->add_text("\n" + TTR("Description:") + "\n\n");
  211. description->append_text(p_description);
  212. description->set_selection_enabled(true);
  213. set_title(p_title);
  214. }
  215. void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video, const String &p_url) {
  216. Preview preview;
  217. preview.id = p_id;
  218. preview.video_link = p_url;
  219. preview.is_video = p_video;
  220. preview.button = memnew(Button);
  221. preview.button->set_icon(previews->get_theme_icon(SNAME("ThumbnailWait"), SNAME("EditorIcons")));
  222. preview.button->set_toggle_mode(true);
  223. preview.button->connect("pressed", callable_mp(this, &EditorAssetLibraryItemDescription::_preview_click).bind(p_id));
  224. preview_hb->add_child(preview.button);
  225. if (!p_video) {
  226. preview.image = previews->get_theme_icon(SNAME("ThumbnailWait"), SNAME("EditorIcons"));
  227. }
  228. preview_images.push_back(preview);
  229. if (preview_images.size() == 1 && !p_video) {
  230. _preview_click(p_id);
  231. }
  232. }
  233. EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() {
  234. HBoxContainer *hbox = memnew(HBoxContainer);
  235. add_child(hbox);
  236. VBoxContainer *desc_vbox = memnew(VBoxContainer);
  237. hbox->add_child(desc_vbox);
  238. hbox->add_theme_constant_override("separation", 15 * EDSCALE);
  239. item = memnew(EditorAssetLibraryItem);
  240. desc_vbox->add_child(item);
  241. desc_vbox->set_custom_minimum_size(Size2(440 * EDSCALE, 0));
  242. description = memnew(RichTextLabel);
  243. desc_vbox->add_child(description);
  244. description->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  245. description->connect("meta_clicked", callable_mp(this, &EditorAssetLibraryItemDescription::_link_click));
  246. description->add_theme_constant_override("line_separation", Math::round(5 * EDSCALE));
  247. VBoxContainer *previews_vbox = memnew(VBoxContainer);
  248. hbox->add_child(previews_vbox);
  249. previews_vbox->add_theme_constant_override("separation", 15 * EDSCALE);
  250. previews_vbox->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  251. previews_vbox->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  252. preview = memnew(TextureRect);
  253. previews_vbox->add_child(preview);
  254. preview->set_ignore_texture_size(true);
  255. preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
  256. preview->set_custom_minimum_size(Size2(640 * EDSCALE, 345 * EDSCALE));
  257. preview->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  258. preview->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  259. previews_bg = memnew(PanelContainer);
  260. previews_vbox->add_child(previews_bg);
  261. previews_bg->set_custom_minimum_size(Size2(640 * EDSCALE, 101 * EDSCALE));
  262. previews = memnew(ScrollContainer);
  263. previews_bg->add_child(previews);
  264. previews->set_vertical_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
  265. preview_hb = memnew(HBoxContainer);
  266. preview_hb->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  267. previews->add_child(preview_hb);
  268. set_ok_button_text(TTR("Download"));
  269. set_cancel_button_text(TTR("Close"));
  270. }
  271. ///////////////////////////////////////////////////////////////////////////////////
  272. void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
  273. String error_text;
  274. switch (p_status) {
  275. case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH:
  276. case HTTPRequest::RESULT_CONNECTION_ERROR:
  277. case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED: {
  278. error_text = TTR("Connection error, please try again.");
  279. status->set_text(TTR("Can't connect."));
  280. } break;
  281. case HTTPRequest::RESULT_CANT_CONNECT:
  282. case HTTPRequest::RESULT_SSL_HANDSHAKE_ERROR: {
  283. error_text = TTR("Can't connect to host:") + " " + host;
  284. status->set_text(TTR("Can't connect."));
  285. } break;
  286. case HTTPRequest::RESULT_NO_RESPONSE: {
  287. error_text = TTR("No response from host:") + " " + host;
  288. status->set_text(TTR("No response."));
  289. } break;
  290. case HTTPRequest::RESULT_CANT_RESOLVE: {
  291. error_text = TTR("Can't resolve hostname:") + " " + host;
  292. status->set_text(TTR("Can't resolve."));
  293. } break;
  294. case HTTPRequest::RESULT_REQUEST_FAILED: {
  295. error_text = TTR("Request failed, return code:") + " " + itos(p_code);
  296. status->set_text(TTR("Request failed."));
  297. } break;
  298. case HTTPRequest::RESULT_DOWNLOAD_FILE_CANT_OPEN:
  299. case HTTPRequest::RESULT_DOWNLOAD_FILE_WRITE_ERROR: {
  300. error_text = TTR("Cannot save response to:") + " " + download->get_download_file();
  301. status->set_text(TTR("Write error."));
  302. } break;
  303. case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
  304. error_text = TTR("Request failed, too many redirects");
  305. status->set_text(TTR("Redirect loop."));
  306. } break;
  307. case HTTPRequest::RESULT_TIMEOUT: {
  308. error_text = TTR("Request failed, timeout");
  309. status->set_text(TTR("Timeout."));
  310. } break;
  311. default: {
  312. if (p_code != 200) {
  313. error_text = TTR("Request failed, return code:") + " " + itos(p_code);
  314. status->set_text(TTR("Failed:") + " " + itos(p_code));
  315. } else if (!sha256.is_empty()) {
  316. String download_sha256 = FileAccess::get_sha256(download->get_download_file());
  317. if (sha256 != download_sha256) {
  318. error_text = TTR("Bad download hash, assuming file has been tampered with.") + "\n";
  319. error_text += TTR("Expected:") + " " + sha256 + "\n" + TTR("Got:") + " " + download_sha256;
  320. status->set_text(TTR("Failed SHA-256 hash check"));
  321. }
  322. }
  323. } break;
  324. }
  325. if (!error_text.is_empty()) {
  326. download_error->set_text(TTR("Asset Download Error:") + "\n" + error_text);
  327. download_error->popup_centered();
  328. // Let the user retry the download.
  329. retry_button->show();
  330. return;
  331. }
  332. install_button->set_disabled(false);
  333. status->set_text(TTR("Ready to install!"));
  334. // Make the progress bar invisible but don't reflow other Controls around it.
  335. progress->set_modulate(Color(0, 0, 0, 0));
  336. set_process(false);
  337. // Automatically prompt for installation once the download is completed.
  338. install();
  339. }
  340. 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) {
  341. title->set_text(p_title);
  342. icon->set_texture(p_preview);
  343. asset_id = p_asset_id;
  344. if (!p_preview.is_valid()) {
  345. icon->set_texture(get_theme_icon(SNAME("FileBrokenBigThumb"), SNAME("EditorIcons")));
  346. }
  347. host = p_download_url;
  348. sha256 = p_sha256_hash;
  349. _make_request();
  350. }
  351. void EditorAssetLibraryItemDownload::_notification(int p_what) {
  352. switch (p_what) {
  353. case NOTIFICATION_ENTER_TREE:
  354. case NOTIFICATION_THEME_CHANGED: {
  355. panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("panel"), SNAME("AssetLib")));
  356. status->add_theme_color_override("font_color", get_theme_color(SNAME("status_color"), SNAME("AssetLib")));
  357. dismiss_button->set_normal_texture(get_theme_icon(SNAME("dismiss"), SNAME("AssetLib")));
  358. } break;
  359. case NOTIFICATION_PROCESS: {
  360. // Make the progress bar visible again when retrying the download.
  361. progress->set_modulate(Color(1, 1, 1, 1));
  362. if (download->get_downloaded_bytes() > 0) {
  363. progress->set_max(download->get_body_size());
  364. progress->set_value(download->get_downloaded_bytes());
  365. }
  366. int cstatus = download->get_http_client_status();
  367. if (cstatus == HTTPClient::STATUS_BODY) {
  368. if (download->get_body_size() > 0) {
  369. status->set_text(vformat(
  370. TTR("Downloading (%s / %s)..."),
  371. String::humanize_size(download->get_downloaded_bytes()),
  372. String::humanize_size(download->get_body_size())));
  373. } else {
  374. // Total file size is unknown, so it cannot be displayed.
  375. progress->set_modulate(Color(0, 0, 0, 0));
  376. status->set_text(vformat(
  377. TTR("Downloading...") + " (%s)",
  378. String::humanize_size(download->get_downloaded_bytes())));
  379. }
  380. }
  381. if (cstatus != prev_status) {
  382. switch (cstatus) {
  383. case HTTPClient::STATUS_RESOLVING: {
  384. status->set_text(TTR("Resolving..."));
  385. progress->set_max(1);
  386. progress->set_value(0);
  387. } break;
  388. case HTTPClient::STATUS_CONNECTING: {
  389. status->set_text(TTR("Connecting..."));
  390. progress->set_max(1);
  391. progress->set_value(0);
  392. } break;
  393. case HTTPClient::STATUS_REQUESTING: {
  394. status->set_text(TTR("Requesting..."));
  395. progress->set_max(1);
  396. progress->set_value(0);
  397. } break;
  398. default: {
  399. }
  400. }
  401. prev_status = cstatus;
  402. }
  403. } break;
  404. }
  405. }
  406. void EditorAssetLibraryItemDownload::_close() {
  407. // Clean up downloaded file.
  408. DirAccess::remove_file_or_error(download->get_download_file());
  409. queue_delete();
  410. }
  411. bool EditorAssetLibraryItemDownload::can_install() const {
  412. return !install_button->is_disabled();
  413. }
  414. void EditorAssetLibraryItemDownload::install() {
  415. String file = download->get_download_file();
  416. if (external_install) {
  417. emit_signal(SNAME("install_asset"), file, title->get_text());
  418. return;
  419. }
  420. asset_installer->set_asset_name(title->get_text());
  421. asset_installer->open(file, 1);
  422. }
  423. void EditorAssetLibraryItemDownload::_make_request() {
  424. // Hide the Retry button if we've just pressed it.
  425. retry_button->hide();
  426. download->cancel_request();
  427. download->set_download_file(EditorPaths::get_singleton()->get_cache_dir().path_join("tmp_asset_" + itos(asset_id)) + ".zip");
  428. Error err = download->request(host);
  429. if (err != OK) {
  430. status->set_text(TTR("Error making request"));
  431. } else {
  432. set_process(true);
  433. }
  434. }
  435. void EditorAssetLibraryItemDownload::_bind_methods() {
  436. ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
  437. }
  438. EditorAssetLibraryItemDownload::EditorAssetLibraryItemDownload() {
  439. panel = memnew(PanelContainer);
  440. add_child(panel);
  441. HBoxContainer *hb = memnew(HBoxContainer);
  442. panel->add_child(hb);
  443. icon = memnew(TextureRect);
  444. icon->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED);
  445. icon->set_v_size_flags(0);
  446. hb->add_child(icon);
  447. VBoxContainer *vb = memnew(VBoxContainer);
  448. hb->add_child(vb);
  449. vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  450. HBoxContainer *title_hb = memnew(HBoxContainer);
  451. vb->add_child(title_hb);
  452. title = memnew(Label);
  453. title_hb->add_child(title);
  454. title->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  455. dismiss_button = memnew(TextureButton);
  456. dismiss_button->connect("pressed", callable_mp(this, &EditorAssetLibraryItemDownload::_close));
  457. title_hb->add_child(dismiss_button);
  458. title->set_clip_text(true);
  459. vb->add_spacer();
  460. status = memnew(Label(TTR("Idle")));
  461. vb->add_child(status);
  462. progress = memnew(ProgressBar);
  463. vb->add_child(progress);
  464. HBoxContainer *hb2 = memnew(HBoxContainer);
  465. vb->add_child(hb2);
  466. hb2->add_spacer();
  467. install_button = memnew(Button);
  468. install_button->set_text(TTR("Install..."));
  469. install_button->set_disabled(true);
  470. install_button->connect("pressed", callable_mp(this, &EditorAssetLibraryItemDownload::install));
  471. retry_button = memnew(Button);
  472. retry_button->set_text(TTR("Retry"));
  473. retry_button->connect("pressed", callable_mp(this, &EditorAssetLibraryItemDownload::_make_request));
  474. // Only show the Retry button in case of a failure.
  475. retry_button->hide();
  476. hb2->add_child(retry_button);
  477. hb2->add_child(install_button);
  478. set_custom_minimum_size(Size2(310, 0) * EDSCALE);
  479. download = memnew(HTTPRequest);
  480. panel->add_child(download);
  481. download->connect("request_completed", callable_mp(this, &EditorAssetLibraryItemDownload::_http_download_completed));
  482. setup_http_request(download);
  483. download_error = memnew(AcceptDialog);
  484. panel->add_child(download_error);
  485. download_error->set_title(TTR("Download Error"));
  486. asset_installer = memnew(EditorAssetInstaller);
  487. panel->add_child(asset_installer);
  488. asset_installer->connect("confirmed", callable_mp(this, &EditorAssetLibraryItemDownload::_close));
  489. prev_status = -1;
  490. external_install = false;
  491. }
  492. ////////////////////////////////////////////////////////////////////////////////
  493. void EditorAssetLibrary::_notification(int p_what) {
  494. switch (p_what) {
  495. case NOTIFICATION_READY: {
  496. add_theme_style_override("panel", get_theme_stylebox(SNAME("bg"), SNAME("AssetLib")));
  497. error_label->raise();
  498. } break;
  499. case NOTIFICATION_ENTER_TREE:
  500. case NOTIFICATION_THEME_CHANGED: {
  501. error_tr->set_texture(get_theme_icon(SNAME("Error"), SNAME("EditorIcons")));
  502. filter->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
  503. library_scroll_bg->add_theme_style_override("panel", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
  504. downloads_scroll->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
  505. error_label->add_theme_color_override("color", get_theme_color(SNAME("error_color"), SNAME("Editor")));
  506. } break;
  507. case NOTIFICATION_VISIBILITY_CHANGED: {
  508. if (is_visible()) {
  509. // Focus the search box automatically when switching to the Templates tab (in the Project Manager)
  510. // or switching to the AssetLib tab (in the editor).
  511. // The Project Manager's project filter box is automatically focused in the project manager code.
  512. filter->grab_focus();
  513. if (initial_loading) {
  514. _repository_changed(0); // Update when shown for the first time.
  515. }
  516. }
  517. } break;
  518. case NOTIFICATION_PROCESS: {
  519. HTTPClient::Status s = request->get_http_client_status();
  520. const bool loading = s != HTTPClient::STATUS_DISCONNECTED;
  521. if (loading) {
  522. library_scroll->set_modulate(Color(1, 1, 1, 0.5));
  523. } else {
  524. library_scroll->set_modulate(Color(1, 1, 1, 1));
  525. }
  526. const bool no_downloads = downloads_hb->get_child_count() == 0;
  527. if (no_downloads == downloads_scroll->is_visible()) {
  528. downloads_scroll->set_visible(!no_downloads);
  529. }
  530. } break;
  531. case NOTIFICATION_RESIZED: {
  532. _update_asset_items_columns();
  533. } break;
  534. case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
  535. _update_repository_options();
  536. setup_http_request(request);
  537. } break;
  538. }
  539. }
  540. void EditorAssetLibrary::_update_repository_options() {
  541. Dictionary default_urls;
  542. default_urls["godotengine.org (Official)"] = "https://godotengine.org/asset-library/api";
  543. Dictionary available_urls = _EDITOR_DEF("asset_library/available_urls", default_urls, true);
  544. repository->clear();
  545. Array keys = available_urls.keys();
  546. for (int i = 0; i < keys.size(); i++) {
  547. String key = keys[i];
  548. repository->add_item(key);
  549. repository->set_item_metadata(i, available_urls[key]);
  550. }
  551. }
  552. void EditorAssetLibrary::shortcut_input(const Ref<InputEvent> &p_event) {
  553. ERR_FAIL_COND(p_event.is_null());
  554. const Ref<InputEventKey> key = p_event;
  555. if (key.is_valid() && key->is_pressed()) {
  556. if (key->get_keycode_with_modifiers() == (KeyModifierMask::CMD | Key::F) && is_visible_in_tree()) {
  557. filter->grab_focus();
  558. filter->select_all();
  559. accept_event();
  560. }
  561. }
  562. }
  563. void EditorAssetLibrary::_install_asset() {
  564. ERR_FAIL_COND(!description);
  565. EditorAssetLibraryItemDownload *d = _get_asset_in_progress(description->get_asset_id());
  566. if (d) {
  567. d->install();
  568. return;
  569. }
  570. EditorAssetLibraryItemDownload *download = memnew(EditorAssetLibraryItemDownload);
  571. downloads_hb->add_child(download);
  572. download->configure(description->get_title(), description->get_asset_id(), description->get_preview_icon(), description->get_download_url(), description->get_sha256());
  573. if (templates_only) {
  574. download->set_external_install(true);
  575. download->connect("install_asset", callable_mp(this, &EditorAssetLibrary::_install_external_asset));
  576. }
  577. }
  578. const char *EditorAssetLibrary::sort_key[SORT_MAX] = {
  579. "updated",
  580. "updated",
  581. "name",
  582. "name",
  583. "cost",
  584. "cost",
  585. };
  586. const char *EditorAssetLibrary::sort_text[SORT_MAX] = {
  587. TTRC("Recently Updated"),
  588. TTRC("Least Recently Updated"),
  589. TTRC("Name (A-Z)"),
  590. TTRC("Name (Z-A)"),
  591. TTRC("License (A-Z)"), // "cost" stores the SPDX license name in the Godot Asset Library.
  592. TTRC("License (Z-A)"), // "cost" stores the SPDX license name in the Godot Asset Library.
  593. };
  594. const char *EditorAssetLibrary::support_key[SUPPORT_MAX] = {
  595. "official",
  596. "community",
  597. "testing",
  598. };
  599. void EditorAssetLibrary::_select_author(int p_id) {
  600. // Open author window.
  601. }
  602. void EditorAssetLibrary::_select_category(int p_id) {
  603. for (int i = 0; i < categories->get_item_count(); i++) {
  604. if (i == 0) {
  605. continue;
  606. }
  607. int id = categories->get_item_metadata(i);
  608. if (id == p_id) {
  609. categories->select(i);
  610. _search();
  611. break;
  612. }
  613. }
  614. }
  615. void EditorAssetLibrary::_select_asset(int p_id) {
  616. _api_request("asset/" + itos(p_id), REQUESTING_ASSET);
  617. }
  618. void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PackedByteArray &p_data, int p_queue_id) {
  619. Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
  620. if (obj) {
  621. bool image_set = false;
  622. PackedByteArray image_data = p_data;
  623. if (use_cache) {
  624. String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
  625. Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".data", FileAccess::READ);
  626. if (file.is_valid()) {
  627. PackedByteArray cached_data;
  628. int len = file->get_32();
  629. cached_data.resize(len);
  630. uint8_t *w = cached_data.ptrw();
  631. file->get_buffer(w, len);
  632. image_data = cached_data;
  633. }
  634. }
  635. int len = image_data.size();
  636. const uint8_t *r = image_data.ptr();
  637. Ref<Image> image = Ref<Image>(memnew(Image));
  638. uint8_t png_signature[8] = { 137, 80, 78, 71, 13, 10, 26, 10 };
  639. uint8_t jpg_signature[3] = { 255, 216, 255 };
  640. if (r) {
  641. if ((memcmp(&r[0], &png_signature[0], 8) == 0) && Image::_png_mem_loader_func) {
  642. image->copy_internals_from(Image::_png_mem_loader_func(r, len));
  643. } else if ((memcmp(&r[0], &jpg_signature[0], 3) == 0) && Image::_jpg_mem_loader_func) {
  644. image->copy_internals_from(Image::_jpg_mem_loader_func(r, len));
  645. }
  646. }
  647. if (!image->is_empty()) {
  648. switch (image_queue[p_queue_id].image_type) {
  649. case IMAGE_QUEUE_ICON:
  650. image->resize(64 * EDSCALE, 64 * EDSCALE, Image::INTERPOLATE_LANCZOS);
  651. break;
  652. case IMAGE_QUEUE_THUMBNAIL: {
  653. float max_height = 85 * EDSCALE;
  654. float scale_ratio = max_height / (image->get_height() * EDSCALE);
  655. if (scale_ratio < 1) {
  656. image->resize(image->get_width() * EDSCALE * scale_ratio, image->get_height() * EDSCALE * scale_ratio, Image::INTERPOLATE_LANCZOS);
  657. }
  658. } break;
  659. case IMAGE_QUEUE_SCREENSHOT: {
  660. float max_height = 397 * EDSCALE;
  661. float scale_ratio = max_height / (image->get_height() * EDSCALE);
  662. if (scale_ratio < 1) {
  663. image->resize(image->get_width() * EDSCALE * scale_ratio, image->get_height() * EDSCALE * scale_ratio, Image::INTERPOLATE_LANCZOS);
  664. }
  665. } break;
  666. }
  667. Ref<ImageTexture> tex = ImageTexture::create_from_image(image);
  668. obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, tex);
  669. image_set = true;
  670. }
  671. if (!image_set && final) {
  672. obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_theme_icon(SNAME("FileBrokenBigThumb"), SNAME("EditorIcons")));
  673. }
  674. }
  675. }
  676. void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data, int p_queue_id) {
  677. ERR_FAIL_COND(!image_queue.has(p_queue_id));
  678. if (p_status == HTTPRequest::RESULT_SUCCESS && p_code < HTTPClient::RESPONSE_BAD_REQUEST) {
  679. if (p_code != HTTPClient::RESPONSE_NOT_MODIFIED) {
  680. for (int i = 0; i < headers.size(); i++) {
  681. if (headers[i].findn("ETag:") == 0) { // Save etag
  682. String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
  683. String new_etag = headers[i].substr(headers[i].find(":") + 1, headers[i].length()).strip_edges();
  684. Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::WRITE);
  685. if (file.is_valid()) {
  686. file->store_line(new_etag);
  687. }
  688. int len = p_data.size();
  689. const uint8_t *r = p_data.ptr();
  690. file = FileAccess::open(cache_filename_base + ".data", FileAccess::WRITE);
  691. if (file.is_valid()) {
  692. file->store_32(len);
  693. file->store_buffer(r, len);
  694. }
  695. break;
  696. }
  697. }
  698. }
  699. _image_update(p_code == HTTPClient::RESPONSE_NOT_MODIFIED, true, p_data, p_queue_id);
  700. } else {
  701. WARN_PRINT("Error getting image file from URL: " + image_queue[p_queue_id].image_url);
  702. Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
  703. if (obj) {
  704. obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_theme_icon(SNAME("FileBrokenBigThumb"), SNAME("EditorIcons")));
  705. }
  706. }
  707. image_queue[p_queue_id].request->queue_delete();
  708. image_queue.erase(p_queue_id);
  709. _update_image_queue();
  710. }
  711. void EditorAssetLibrary::_update_image_queue() {
  712. const int max_images = 6;
  713. int current_images = 0;
  714. List<int> to_delete;
  715. for (KeyValue<int, ImageQueue> &E : image_queue) {
  716. if (!E.value.active && current_images < max_images) {
  717. String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().path_join("assetimage_" + E.value.image_url.md5_text());
  718. Vector<String> headers;
  719. if (FileAccess::exists(cache_filename_base + ".etag") && FileAccess::exists(cache_filename_base + ".data")) {
  720. Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::READ);
  721. if (file.is_valid()) {
  722. headers.push_back("If-None-Match: " + file->get_line());
  723. }
  724. }
  725. Error err = E.value.request->request(E.value.image_url, headers);
  726. if (err != OK) {
  727. to_delete.push_back(E.key);
  728. } else {
  729. E.value.active = true;
  730. }
  731. current_images++;
  732. } else if (E.value.active) {
  733. current_images++;
  734. }
  735. }
  736. while (to_delete.size()) {
  737. image_queue[to_delete.front()->get()].request->queue_delete();
  738. image_queue.erase(to_delete.front()->get());
  739. to_delete.pop_front();
  740. }
  741. }
  742. void EditorAssetLibrary::_request_image(ObjectID p_for, String p_image_url, ImageType p_type, int p_image_index) {
  743. ImageQueue iq;
  744. iq.image_url = p_image_url;
  745. iq.image_index = p_image_index;
  746. iq.image_type = p_type;
  747. iq.request = memnew(HTTPRequest);
  748. setup_http_request(iq.request);
  749. iq.target = p_for;
  750. iq.queue_id = ++last_queue_id;
  751. iq.active = false;
  752. iq.request->connect("request_completed", callable_mp(this, &EditorAssetLibrary::_image_request_completed).bind(iq.queue_id));
  753. image_queue[iq.queue_id] = iq;
  754. add_child(iq.request);
  755. _image_update(true, false, PackedByteArray(), iq.queue_id);
  756. _update_image_queue();
  757. }
  758. void EditorAssetLibrary::_repository_changed(int p_repository_id) {
  759. library_error->hide();
  760. library_info->set_text(TTR("Loading..."));
  761. library_info->show();
  762. asset_top_page->hide();
  763. asset_bottom_page->hide();
  764. asset_items->hide();
  765. filter->set_editable(false);
  766. sort->set_disabled(true);
  767. categories->set_disabled(true);
  768. support->set_disabled(true);
  769. host = repository->get_item_metadata(p_repository_id);
  770. if (templates_only) {
  771. _api_request("configure", REQUESTING_CONFIG, "?type=project");
  772. } else {
  773. _api_request("configure", REQUESTING_CONFIG);
  774. }
  775. }
  776. void EditorAssetLibrary::_support_toggled(int p_support) {
  777. support->get_popup()->set_item_checked(p_support, !support->get_popup()->is_item_checked(p_support));
  778. _search();
  779. }
  780. void EditorAssetLibrary::_rerun_search(int p_ignore) {
  781. _search();
  782. }
  783. void EditorAssetLibrary::_search(int p_page) {
  784. String args;
  785. if (templates_only) {
  786. args += "?type=project&";
  787. } else {
  788. args += "?";
  789. }
  790. args += String() + "sort=" + sort_key[sort->get_selected()];
  791. // We use the "branch" version, i.e. major.minor, as patch releases should be compatible
  792. args += "&godot_version=" + String(VERSION_BRANCH);
  793. String support_list;
  794. for (int i = 0; i < SUPPORT_MAX; i++) {
  795. if (support->get_popup()->is_item_checked(i)) {
  796. support_list += String(support_key[i]) + "+";
  797. }
  798. }
  799. if (!support_list.is_empty()) {
  800. args += "&support=" + support_list.substr(0, support_list.length() - 1);
  801. }
  802. if (categories->get_selected() > 0) {
  803. args += "&category=" + itos(categories->get_item_metadata(categories->get_selected()));
  804. }
  805. // Sorting options with an odd index are always the reverse of the previous one
  806. if (sort->get_selected() % 2 == 1) {
  807. args += "&reverse=true";
  808. }
  809. if (!filter->get_text().is_empty()) {
  810. args += "&filter=" + filter->get_text().uri_encode();
  811. }
  812. if (p_page > 0) {
  813. args += "&page=" + itos(p_page);
  814. }
  815. _api_request("asset", REQUESTING_SEARCH, args);
  816. }
  817. void EditorAssetLibrary::_search_text_changed(const String &p_text) {
  818. filter_debounce_timer->start();
  819. }
  820. void EditorAssetLibrary::_filter_debounce_timer_timeout() {
  821. _search();
  822. }
  823. void EditorAssetLibrary::_request_current_config() {
  824. _repository_changed(repository->get_selected());
  825. }
  826. HBoxContainer *EditorAssetLibrary::_make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items) {
  827. HBoxContainer *hbc = memnew(HBoxContainer);
  828. if (p_page_count < 2) {
  829. return hbc;
  830. }
  831. //do the mario
  832. int from = p_page - 5;
  833. if (from < 0) {
  834. from = 0;
  835. }
  836. int to = from + 10;
  837. if (to > p_page_count) {
  838. to = p_page_count;
  839. }
  840. hbc->add_spacer();
  841. hbc->add_theme_constant_override("separation", 5 * EDSCALE);
  842. Button *first = memnew(Button);
  843. first->set_text(TTR("First", "Pagination"));
  844. if (p_page != 0) {
  845. first->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search).bind(0));
  846. } else {
  847. first->set_disabled(true);
  848. first->set_focus_mode(Control::FOCUS_NONE);
  849. }
  850. hbc->add_child(first);
  851. Button *prev = memnew(Button);
  852. prev->set_text(TTR("Previous", "Pagination"));
  853. if (p_page > 0) {
  854. prev->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search).bind(p_page - 1));
  855. } else {
  856. prev->set_disabled(true);
  857. prev->set_focus_mode(Control::FOCUS_NONE);
  858. }
  859. hbc->add_child(prev);
  860. hbc->add_child(memnew(VSeparator));
  861. for (int i = from; i < to; i++) {
  862. if (i == p_page) {
  863. Button *current = memnew(Button);
  864. // Keep the extended padding for the currently active page (see below).
  865. current->set_text(vformat(" %d ", i + 1));
  866. current->set_disabled(true);
  867. current->set_focus_mode(Control::FOCUS_NONE);
  868. hbc->add_child(current);
  869. } else {
  870. Button *current = memnew(Button);
  871. // Add padding to make page number buttons easier to click.
  872. current->set_text(vformat(" %d ", i + 1));
  873. current->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search).bind(i));
  874. hbc->add_child(current);
  875. }
  876. }
  877. Button *next = memnew(Button);
  878. next->set_text(TTR("Next", "Pagination"));
  879. if (p_page < p_page_count - 1) {
  880. next->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search).bind(p_page + 1));
  881. } else {
  882. next->set_disabled(true);
  883. next->set_focus_mode(Control::FOCUS_NONE);
  884. }
  885. hbc->add_child(memnew(VSeparator));
  886. hbc->add_child(next);
  887. Button *last = memnew(Button);
  888. last->set_text(TTR("Last", "Pagination"));
  889. if (p_page != p_page_count - 1) {
  890. last->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search).bind(p_page_count - 1));
  891. } else {
  892. last->set_disabled(true);
  893. last->set_focus_mode(Control::FOCUS_NONE);
  894. }
  895. hbc->add_child(last);
  896. hbc->add_spacer();
  897. return hbc;
  898. }
  899. void EditorAssetLibrary::_api_request(const String &p_request, RequestType p_request_type, const String &p_arguments) {
  900. if (requesting != REQUESTING_NONE) {
  901. request->cancel_request();
  902. }
  903. requesting = p_request_type;
  904. error_hb->hide();
  905. request->request(host + "/" + p_request + p_arguments);
  906. }
  907. void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data) {
  908. String str;
  909. {
  910. int datalen = p_data.size();
  911. const uint8_t *r = p_data.ptr();
  912. str.parse_utf8((const char *)r, datalen);
  913. }
  914. bool error_abort = true;
  915. switch (p_status) {
  916. case HTTPRequest::RESULT_CANT_RESOLVE: {
  917. error_label->set_text(TTR("Can't resolve hostname:") + " " + host);
  918. } break;
  919. case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
  920. case HTTPRequest::RESULT_CONNECTION_ERROR:
  921. case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH: {
  922. error_label->set_text(TTR("Connection error, please try again."));
  923. } break;
  924. case HTTPRequest::RESULT_SSL_HANDSHAKE_ERROR:
  925. case HTTPRequest::RESULT_CANT_CONNECT: {
  926. error_label->set_text(TTR("Can't connect to host:") + " " + host);
  927. } break;
  928. case HTTPRequest::RESULT_NO_RESPONSE: {
  929. error_label->set_text(TTR("No response from host:") + " " + host);
  930. } break;
  931. case HTTPRequest::RESULT_REQUEST_FAILED: {
  932. error_label->set_text(TTR("Request failed, return code:") + " " + itos(p_code));
  933. } break;
  934. case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
  935. error_label->set_text(TTR("Request failed, too many redirects"));
  936. } break;
  937. default: {
  938. if (p_code != 200) {
  939. error_label->set_text(TTR("Request failed, return code:") + " " + itos(p_code));
  940. } else {
  941. error_abort = false;
  942. }
  943. } break;
  944. }
  945. if (error_abort) {
  946. if (requesting == REQUESTING_CONFIG) {
  947. library_info->hide();
  948. library_error->show();
  949. }
  950. error_hb->show();
  951. return;
  952. }
  953. Dictionary d;
  954. {
  955. JSON json;
  956. json.parse(str);
  957. d = json.get_data();
  958. }
  959. RequestType requested = requesting;
  960. requesting = REQUESTING_NONE;
  961. switch (requested) {
  962. case REQUESTING_CONFIG: {
  963. categories->clear();
  964. categories->add_item(TTR("All"));
  965. categories->set_item_metadata(0, 0);
  966. if (d.has("categories")) {
  967. Array clist = d["categories"];
  968. for (int i = 0; i < clist.size(); i++) {
  969. Dictionary cat = clist[i];
  970. if (!cat.has("name") || !cat.has("id")) {
  971. continue;
  972. }
  973. String name = cat["name"];
  974. int id = cat["id"];
  975. categories->add_item(name);
  976. categories->set_item_metadata(-1, id);
  977. category_map[cat["id"]] = name;
  978. }
  979. }
  980. filter->set_editable(true);
  981. sort->set_disabled(false);
  982. categories->set_disabled(false);
  983. support->set_disabled(false);
  984. _search();
  985. } break;
  986. case REQUESTING_SEARCH: {
  987. initial_loading = false;
  988. if (asset_items) {
  989. memdelete(asset_items);
  990. }
  991. if (asset_top_page) {
  992. memdelete(asset_top_page);
  993. }
  994. if (asset_bottom_page) {
  995. memdelete(asset_bottom_page);
  996. }
  997. int page = 0;
  998. int pages = 1;
  999. int page_len = 10;
  1000. int total_items = 1;
  1001. Array result;
  1002. if (d.has("page")) {
  1003. page = d["page"];
  1004. }
  1005. if (d.has("pages")) {
  1006. pages = d["pages"];
  1007. }
  1008. if (d.has("page_length")) {
  1009. page_len = d["page_length"];
  1010. }
  1011. if (d.has("total")) {
  1012. total_items = d["total"];
  1013. }
  1014. if (d.has("result")) {
  1015. result = d["result"];
  1016. }
  1017. asset_top_page = _make_pages(page, pages, page_len, total_items, result.size());
  1018. library_vb->add_child(asset_top_page);
  1019. asset_items = memnew(GridContainer);
  1020. _update_asset_items_columns();
  1021. asset_items->add_theme_constant_override("h_separation", 10 * EDSCALE);
  1022. asset_items->add_theme_constant_override("v_separation", 10 * EDSCALE);
  1023. library_vb->add_child(asset_items);
  1024. asset_bottom_page = _make_pages(page, pages, page_len, total_items, result.size());
  1025. library_vb->add_child(asset_bottom_page);
  1026. if (result.is_empty()) {
  1027. if (!filter->get_text().is_empty()) {
  1028. library_info->set_text(
  1029. vformat(TTR("No results for \"%s\"."), filter->get_text()));
  1030. } else {
  1031. // No results, even though the user didn't search for anything specific.
  1032. // This is typically because the version number changed recently
  1033. // and no assets compatible with the new version have been published yet.
  1034. library_info->set_text(
  1035. vformat(TTR("No results compatible with %s %s."), String(VERSION_SHORT_NAME).capitalize(), String(VERSION_BRANCH)));
  1036. }
  1037. library_info->show();
  1038. } else {
  1039. library_info->hide();
  1040. }
  1041. for (int i = 0; i < result.size(); i++) {
  1042. Dictionary r = result[i];
  1043. ERR_CONTINUE(!r.has("title"));
  1044. ERR_CONTINUE(!r.has("asset_id"));
  1045. ERR_CONTINUE(!r.has("author"));
  1046. ERR_CONTINUE(!r.has("author_id"));
  1047. ERR_CONTINUE(!r.has("category_id"));
  1048. ERR_FAIL_COND(!category_map.has(r["category_id"]));
  1049. ERR_CONTINUE(!r.has("cost"));
  1050. EditorAssetLibraryItem *item = memnew(EditorAssetLibraryItem);
  1051. asset_items->add_child(item);
  1052. item->configure(r["title"], r["asset_id"], category_map[r["category_id"]], r["category_id"], r["author"], r["author_id"], r["cost"]);
  1053. item->connect("asset_selected", callable_mp(this, &EditorAssetLibrary::_select_asset));
  1054. item->connect("author_selected", callable_mp(this, &EditorAssetLibrary::_select_author));
  1055. item->connect("category_selected", callable_mp(this, &EditorAssetLibrary::_select_category));
  1056. if (r.has("icon_url") && !r["icon_url"].operator String().is_empty()) {
  1057. _request_image(item->get_instance_id(), r["icon_url"], IMAGE_QUEUE_ICON, 0);
  1058. }
  1059. }
  1060. if (!result.is_empty()) {
  1061. library_scroll->set_v_scroll(0);
  1062. }
  1063. } break;
  1064. case REQUESTING_ASSET: {
  1065. Dictionary r = d;
  1066. ERR_FAIL_COND(!r.has("title"));
  1067. ERR_FAIL_COND(!r.has("asset_id"));
  1068. ERR_FAIL_COND(!r.has("author"));
  1069. ERR_FAIL_COND(!r.has("author_id"));
  1070. ERR_FAIL_COND(!r.has("version"));
  1071. ERR_FAIL_COND(!r.has("version_string"));
  1072. ERR_FAIL_COND(!r.has("category_id"));
  1073. ERR_FAIL_COND(!category_map.has(r["category_id"]));
  1074. ERR_FAIL_COND(!r.has("cost"));
  1075. ERR_FAIL_COND(!r.has("description"));
  1076. ERR_FAIL_COND(!r.has("download_url"));
  1077. ERR_FAIL_COND(!r.has("download_hash"));
  1078. ERR_FAIL_COND(!r.has("browse_url"));
  1079. if (description) {
  1080. memdelete(description);
  1081. }
  1082. description = memnew(EditorAssetLibraryItemDescription);
  1083. add_child(description);
  1084. description->popup_centered();
  1085. description->connect("confirmed", callable_mp(this, &EditorAssetLibrary::_install_asset));
  1086. 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"]);
  1087. EditorAssetLibraryItemDownload *download_item = _get_asset_in_progress(description->get_asset_id());
  1088. if (download_item) {
  1089. if (download_item->can_install()) {
  1090. description->set_ok_button_text(TTR("Install"));
  1091. description->get_ok_button()->set_disabled(false);
  1092. } else {
  1093. description->set_ok_button_text(TTR("Downloading..."));
  1094. description->get_ok_button()->set_disabled(true);
  1095. }
  1096. } else {
  1097. description->set_ok_button_text(TTR("Download"));
  1098. description->get_ok_button()->set_disabled(false);
  1099. }
  1100. if (r.has("icon_url") && !r["icon_url"].operator String().is_empty()) {
  1101. _request_image(description->get_instance_id(), r["icon_url"], IMAGE_QUEUE_ICON, 0);
  1102. }
  1103. if (d.has("previews")) {
  1104. Array previews = d["previews"];
  1105. for (int i = 0; i < previews.size(); i++) {
  1106. Dictionary p = previews[i];
  1107. ERR_CONTINUE(!p.has("type"));
  1108. ERR_CONTINUE(!p.has("link"));
  1109. bool is_video = p.has("type") && String(p["type"]) == "video";
  1110. String video_url;
  1111. if (is_video && p.has("link")) {
  1112. video_url = p["link"];
  1113. }
  1114. description->add_preview(i, is_video, video_url);
  1115. if (p.has("thumbnail")) {
  1116. _request_image(description->get_instance_id(), p["thumbnail"], IMAGE_QUEUE_THUMBNAIL, i);
  1117. }
  1118. if (!is_video) {
  1119. _request_image(description->get_instance_id(), p["link"], IMAGE_QUEUE_SCREENSHOT, i);
  1120. }
  1121. }
  1122. }
  1123. } break;
  1124. default:
  1125. break;
  1126. }
  1127. }
  1128. void EditorAssetLibrary::_asset_file_selected(const String &p_file) {
  1129. if (asset_installer) {
  1130. memdelete(asset_installer);
  1131. asset_installer = nullptr;
  1132. }
  1133. asset_installer = memnew(EditorAssetInstaller);
  1134. asset_installer->set_asset_name(p_file.get_basename());
  1135. add_child(asset_installer);
  1136. asset_installer->open(p_file);
  1137. }
  1138. void EditorAssetLibrary::_asset_open() {
  1139. asset_open->popup_file_dialog();
  1140. }
  1141. void EditorAssetLibrary::_manage_plugins() {
  1142. ProjectSettingsEditor::get_singleton()->popup_project_settings();
  1143. ProjectSettingsEditor::get_singleton()->set_plugins_page();
  1144. }
  1145. EditorAssetLibraryItemDownload *EditorAssetLibrary::_get_asset_in_progress(int p_asset_id) const {
  1146. for (int i = 0; i < downloads_hb->get_child_count(); i++) {
  1147. EditorAssetLibraryItemDownload *d = Object::cast_to<EditorAssetLibraryItemDownload>(downloads_hb->get_child(i));
  1148. if (d && d->get_asset_id() == p_asset_id) {
  1149. return d;
  1150. }
  1151. }
  1152. return nullptr;
  1153. }
  1154. void EditorAssetLibrary::_install_external_asset(String p_zip_path, String p_title) {
  1155. emit_signal(SNAME("install_asset"), p_zip_path, p_title);
  1156. }
  1157. void EditorAssetLibrary::_update_asset_items_columns() {
  1158. int new_columns = get_size().x / (450.0 * EDSCALE);
  1159. new_columns = MAX(1, new_columns);
  1160. if (new_columns != asset_items->get_columns()) {
  1161. asset_items->set_columns(new_columns);
  1162. }
  1163. }
  1164. void EditorAssetLibrary::disable_community_support() {
  1165. support->get_popup()->set_item_checked(SUPPORT_COMMUNITY, false);
  1166. }
  1167. void EditorAssetLibrary::_bind_methods() {
  1168. ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
  1169. }
  1170. EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
  1171. requesting = REQUESTING_NONE;
  1172. templates_only = p_templates_only;
  1173. initial_loading = true;
  1174. VBoxContainer *library_main = memnew(VBoxContainer);
  1175. add_child(library_main);
  1176. HBoxContainer *search_hb = memnew(HBoxContainer);
  1177. library_main->add_child(search_hb);
  1178. library_main->add_theme_constant_override("separation", 10 * EDSCALE);
  1179. filter = memnew(LineEdit);
  1180. if (templates_only) {
  1181. filter->set_placeholder(TTR("Search Templates, Projects, and Demos"));
  1182. } else {
  1183. filter->set_placeholder(TTR("Search Assets (Excluding Templates, Projects, and Demos)"));
  1184. }
  1185. filter->set_clear_button_enabled(true);
  1186. search_hb->add_child(filter);
  1187. filter->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1188. filter->connect("text_changed", callable_mp(this, &EditorAssetLibrary::_search_text_changed));
  1189. // Perform a search automatically if the user hasn't entered any text for a certain duration.
  1190. // This way, the user doesn't need to press Enter to initiate their search.
  1191. filter_debounce_timer = memnew(Timer);
  1192. filter_debounce_timer->set_one_shot(true);
  1193. filter_debounce_timer->set_wait_time(0.25);
  1194. filter_debounce_timer->connect("timeout", callable_mp(this, &EditorAssetLibrary::_filter_debounce_timer_timeout));
  1195. search_hb->add_child(filter_debounce_timer);
  1196. if (!p_templates_only) {
  1197. search_hb->add_child(memnew(VSeparator));
  1198. }
  1199. Button *open_asset = memnew(Button);
  1200. open_asset->set_text(TTR("Import..."));
  1201. search_hb->add_child(open_asset);
  1202. open_asset->connect("pressed", callable_mp(this, &EditorAssetLibrary::_asset_open));
  1203. Button *plugins = memnew(Button);
  1204. plugins->set_text(TTR("Plugins..."));
  1205. search_hb->add_child(plugins);
  1206. plugins->connect("pressed", callable_mp(this, &EditorAssetLibrary::_manage_plugins));
  1207. if (p_templates_only) {
  1208. open_asset->hide();
  1209. plugins->hide();
  1210. }
  1211. HBoxContainer *search_hb2 = memnew(HBoxContainer);
  1212. library_main->add_child(search_hb2);
  1213. search_hb2->add_child(memnew(Label(TTR("Sort:") + " ")));
  1214. sort = memnew(OptionButton);
  1215. for (int i = 0; i < SORT_MAX; i++) {
  1216. sort->add_item(TTRGET(sort_text[i]));
  1217. }
  1218. search_hb2->add_child(sort);
  1219. sort->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1220. sort->set_clip_text(true);
  1221. sort->connect("item_selected", callable_mp(this, &EditorAssetLibrary::_rerun_search));
  1222. search_hb2->add_child(memnew(VSeparator));
  1223. search_hb2->add_child(memnew(Label(TTR("Category:") + " ")));
  1224. categories = memnew(OptionButton);
  1225. categories->add_item(TTR("All"));
  1226. search_hb2->add_child(categories);
  1227. categories->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1228. categories->set_clip_text(true);
  1229. categories->connect("item_selected", callable_mp(this, &EditorAssetLibrary::_rerun_search));
  1230. search_hb2->add_child(memnew(VSeparator));
  1231. search_hb2->add_child(memnew(Label(TTR("Site:") + " ")));
  1232. repository = memnew(OptionButton);
  1233. _update_repository_options();
  1234. repository->connect("item_selected", callable_mp(this, &EditorAssetLibrary::_repository_changed));
  1235. search_hb2->add_child(repository);
  1236. repository->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1237. repository->set_clip_text(true);
  1238. search_hb2->add_child(memnew(VSeparator));
  1239. support = memnew(MenuButton);
  1240. search_hb2->add_child(support);
  1241. support->set_text(TTR("Support"));
  1242. support->get_popup()->set_hide_on_checkable_item_selection(false);
  1243. support->get_popup()->add_check_item(TTR("Official"), SUPPORT_OFFICIAL);
  1244. support->get_popup()->add_check_item(TTR("Community"), SUPPORT_COMMUNITY);
  1245. support->get_popup()->add_check_item(TTR("Testing"), SUPPORT_TESTING);
  1246. support->get_popup()->set_item_checked(SUPPORT_OFFICIAL, true);
  1247. support->get_popup()->set_item_checked(SUPPORT_COMMUNITY, true);
  1248. support->get_popup()->connect("id_pressed", callable_mp(this, &EditorAssetLibrary::_support_toggled));
  1249. /////////
  1250. library_scroll_bg = memnew(PanelContainer);
  1251. library_main->add_child(library_scroll_bg);
  1252. library_scroll_bg->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  1253. library_scroll = memnew(ScrollContainer);
  1254. library_scroll->set_horizontal_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
  1255. library_scroll_bg->add_child(library_scroll);
  1256. Ref<StyleBoxEmpty> border2;
  1257. border2.instantiate();
  1258. border2->set_default_margin(SIDE_LEFT, 15 * EDSCALE);
  1259. border2->set_default_margin(SIDE_RIGHT, 35 * EDSCALE);
  1260. border2->set_default_margin(SIDE_BOTTOM, 15 * EDSCALE);
  1261. border2->set_default_margin(SIDE_TOP, 15 * EDSCALE);
  1262. PanelContainer *library_vb_border = memnew(PanelContainer);
  1263. library_scroll->add_child(library_vb_border);
  1264. library_vb_border->add_theme_style_override("panel", border2);
  1265. library_vb_border->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1266. library_vb = memnew(VBoxContainer);
  1267. library_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
  1268. library_vb_border->add_child(library_vb);
  1269. library_info = memnew(Label);
  1270. library_info->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  1271. library_vb->add_child(library_info);
  1272. library_error = memnew(VBoxContainer);
  1273. library_error->hide();
  1274. library_vb->add_child(library_error);
  1275. library_error_label = memnew(Label(TTR("Failed to get repository configuration.")));
  1276. library_error_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
  1277. library_error->add_child(library_error_label);
  1278. library_error_retry = memnew(Button(TTR("Retry")));
  1279. library_error_retry->set_h_size_flags(SIZE_SHRINK_CENTER);
  1280. library_error_retry->connect("pressed", callable_mp(this, &EditorAssetLibrary::_request_current_config));
  1281. library_error->add_child(library_error_retry);
  1282. asset_top_page = memnew(HBoxContainer);
  1283. library_vb->add_child(asset_top_page);
  1284. asset_items = memnew(GridContainer);
  1285. _update_asset_items_columns();
  1286. asset_items->add_theme_constant_override("h_separation", 10 * EDSCALE);
  1287. asset_items->add_theme_constant_override("v_separation", 10 * EDSCALE);
  1288. library_vb->add_child(asset_items);
  1289. asset_bottom_page = memnew(HBoxContainer);
  1290. library_vb->add_child(asset_bottom_page);
  1291. request = memnew(HTTPRequest);
  1292. add_child(request);
  1293. setup_http_request(request);
  1294. request->connect("request_completed", callable_mp(this, &EditorAssetLibrary::_http_request_completed));
  1295. last_queue_id = 0;
  1296. library_vb->add_theme_constant_override("separation", 20 * EDSCALE);
  1297. error_hb = memnew(HBoxContainer);
  1298. library_main->add_child(error_hb);
  1299. error_label = memnew(Label);
  1300. error_hb->add_child(error_label);
  1301. error_tr = memnew(TextureRect);
  1302. error_tr->set_v_size_flags(Control::SIZE_SHRINK_CENTER);
  1303. error_hb->add_child(error_tr);
  1304. description = nullptr;
  1305. set_process(true);
  1306. set_process_shortcut_input(true); // Global shortcuts since there is no main element to be focused.
  1307. downloads_scroll = memnew(ScrollContainer);
  1308. downloads_scroll->set_vertical_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
  1309. library_main->add_child(downloads_scroll);
  1310. downloads_hb = memnew(HBoxContainer);
  1311. downloads_scroll->add_child(downloads_hb);
  1312. asset_open = memnew(EditorFileDialog);
  1313. asset_open->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
  1314. asset_open->add_filter("*.zip", TTR("Assets ZIP File"));
  1315. asset_open->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
  1316. add_child(asset_open);
  1317. asset_open->connect("file_selected", callable_mp(this, &EditorAssetLibrary::_asset_file_selected));
  1318. asset_installer = nullptr;
  1319. }
  1320. ///////
  1321. bool AssetLibraryEditorPlugin::is_available() {
  1322. #ifdef WEB_ENABLED
  1323. // Asset Library can't work on Web editor for now as most assets are sourced
  1324. // directly from GitHub which does not set CORS.
  1325. return false;
  1326. #else
  1327. return StreamPeerSSL::is_available();
  1328. #endif
  1329. }
  1330. void AssetLibraryEditorPlugin::make_visible(bool p_visible) {
  1331. if (p_visible) {
  1332. addon_library->show();
  1333. } else {
  1334. addon_library->hide();
  1335. }
  1336. }
  1337. AssetLibraryEditorPlugin::AssetLibraryEditorPlugin() {
  1338. addon_library = memnew(EditorAssetLibrary);
  1339. addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL);
  1340. EditorNode::get_singleton()->get_main_control()->add_child(addon_library);
  1341. addon_library->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
  1342. addon_library->hide();
  1343. }
  1344. AssetLibraryEditorPlugin::~AssetLibraryEditorPlugin() {
  1345. }