asset_library_editor_plugin.cpp 53 KB

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