asset_library_editor_plugin.cpp 53 KB

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