editor_export_platform.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545
  1. /**************************************************************************/
  2. /* editor_export_platform.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 "editor_export_platform.h"
  31. #include "editor_export_platform.compat.inc"
  32. #include "core/config/project_settings.h"
  33. #include "core/crypto/crypto_core.h"
  34. #include "core/extension/gdextension.h"
  35. #include "core/io/file_access_encrypted.h"
  36. #include "core/io/file_access_pack.h" // PACK_HEADER_MAGIC, PACK_FORMAT_VERSION
  37. #include "core/io/image_loader.h"
  38. #include "core/io/resource_uid.h"
  39. #include "core/io/zip_io.h"
  40. #include "core/math/random_pcg.h"
  41. #include "core/version.h"
  42. #include "editor/editor_node.h"
  43. #include "editor/editor_string_names.h"
  44. #include "editor/export/editor_export.h"
  45. #include "editor/file_system/editor_file_system.h"
  46. #include "editor/file_system/editor_paths.h"
  47. #include "editor/script/script_editor_plugin.h"
  48. #include "editor/settings/editor_settings.h"
  49. #include "editor/themes/editor_scale.h"
  50. #include "editor_export_plugin.h"
  51. #include "scene/resources/image_texture.h"
  52. #include "scene/resources/packed_scene.h"
  53. class EditorExportSaveProxy {
  54. HashSet<String> saved_paths;
  55. EditorExportPlatform::EditorExportSaveFunction save_func;
  56. bool tracking_saves = false;
  57. public:
  58. bool has_saved(const String &p_path) const { return saved_paths.has(p_path); }
  59. Error save_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  60. if (tracking_saves) {
  61. saved_paths.insert(p_path.simplify_path().trim_prefix("res://"));
  62. }
  63. return save_func(p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed);
  64. }
  65. EditorExportSaveProxy(EditorExportPlatform::EditorExportSaveFunction p_save_func, bool p_track_saves) :
  66. save_func(p_save_func), tracking_saves(p_track_saves) {}
  67. };
  68. static int _get_pad(int p_alignment, int p_n) {
  69. int rest = p_n % p_alignment;
  70. int pad = 0;
  71. if (rest > 0) {
  72. pad = p_alignment - rest;
  73. };
  74. return pad;
  75. }
  76. #define PCK_PADDING 16
  77. Ref<Image> EditorExportPlatform::_load_icon_or_splash_image(const String &p_path, Error *r_error) const {
  78. Ref<Image> image;
  79. if (!p_path.is_empty() && ResourceLoader::exists(p_path) && !ResourceLoader::get_resource_type(p_path).is_empty()) {
  80. Ref<Texture2D> texture = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, r_error);
  81. if (texture.is_valid()) {
  82. image = texture->get_image();
  83. if (image.is_valid() && image->is_compressed()) {
  84. image->decompress();
  85. }
  86. }
  87. }
  88. if (image.is_null()) {
  89. image.instantiate();
  90. Error err = ImageLoader::load_image(p_path, image);
  91. if (r_error) {
  92. *r_error = err;
  93. }
  94. }
  95. return image;
  96. }
  97. bool EditorExportPlatform::fill_log_messages(RichTextLabel *p_log, Error p_err) {
  98. bool has_messages = false;
  99. int msg_count = get_message_count();
  100. p_log->add_text(TTR("Project export for platform:") + " ");
  101. p_log->add_image(get_logo(), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
  102. p_log->add_text(" ");
  103. p_log->add_text(get_name());
  104. p_log->add_text(" - ");
  105. if (p_err == OK && get_worst_message_type() < EditorExportPlatform::EXPORT_MESSAGE_ERROR) {
  106. if (get_worst_message_type() >= EditorExportPlatform::EXPORT_MESSAGE_WARNING) {
  107. p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusWarning")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
  108. p_log->add_text(" ");
  109. p_log->add_text(TTR("Completed with warnings."));
  110. has_messages = true;
  111. } else {
  112. p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusSuccess")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
  113. p_log->add_text(" ");
  114. p_log->add_text(TTR("Completed successfully."));
  115. if (msg_count > 0) {
  116. has_messages = true;
  117. }
  118. }
  119. } else {
  120. p_log->add_image(p_log->get_editor_theme_icon(SNAME("StatusError")), 16 * EDSCALE, 16 * EDSCALE, Color(1.0, 1.0, 1.0), INLINE_ALIGNMENT_CENTER);
  121. p_log->add_text(" ");
  122. p_log->add_text(TTR("Failed."));
  123. has_messages = true;
  124. }
  125. p_log->add_newline();
  126. if (msg_count > 0) {
  127. p_log->push_table(2);
  128. p_log->set_table_column_expand(0, false);
  129. p_log->set_table_column_expand(1, true);
  130. for (int m = 0; m < msg_count; m++) {
  131. EditorExportPlatform::ExportMessage msg = get_message(m);
  132. Color color = p_log->get_theme_color(SceneStringName(font_color), SNAME("Label"));
  133. Ref<Texture> icon;
  134. switch (msg.msg_type) {
  135. case EditorExportPlatform::EXPORT_MESSAGE_INFO: {
  136. color = p_log->get_theme_color(SceneStringName(font_color), EditorStringName(Editor)) * Color(1, 1, 1, 0.6);
  137. } break;
  138. case EditorExportPlatform::EXPORT_MESSAGE_WARNING: {
  139. icon = p_log->get_editor_theme_icon(SNAME("Warning"));
  140. color = p_log->get_theme_color(SNAME("warning_color"), EditorStringName(Editor));
  141. } break;
  142. case EditorExportPlatform::EXPORT_MESSAGE_ERROR: {
  143. icon = p_log->get_editor_theme_icon(SNAME("Error"));
  144. color = p_log->get_theme_color(SNAME("error_color"), EditorStringName(Editor));
  145. } break;
  146. default:
  147. break;
  148. }
  149. p_log->push_cell();
  150. p_log->add_text("\t");
  151. if (icon.is_valid()) {
  152. p_log->add_image(icon);
  153. }
  154. p_log->pop();
  155. p_log->push_cell();
  156. p_log->push_color(color);
  157. p_log->add_text(vformat("[%s]: %s", msg.category, msg.text));
  158. p_log->pop();
  159. p_log->pop();
  160. }
  161. p_log->pop();
  162. p_log->add_newline();
  163. } else if (p_err != OK) {
  164. // We failed but don't show any user-facing messages. This is bad and should not
  165. // be allowed, but just in case this happens, let's give the user something at least.
  166. p_log->push_table(2);
  167. p_log->set_table_column_expand(0, false);
  168. p_log->set_table_column_expand(1, true);
  169. {
  170. Color color = p_log->get_theme_color(SNAME("error_color"), EditorStringName(Editor));
  171. Ref<Texture> icon = p_log->get_editor_theme_icon(SNAME("Error"));
  172. p_log->push_cell();
  173. p_log->add_text("\t");
  174. if (icon.is_valid()) {
  175. p_log->add_image(icon);
  176. }
  177. p_log->pop();
  178. p_log->push_cell();
  179. p_log->push_color(color);
  180. p_log->add_text(vformat("[%s]: %s", TTR("Unknown Error"), vformat(TTR("Export failed with error code %d."), p_err)));
  181. p_log->pop();
  182. p_log->pop();
  183. }
  184. p_log->pop();
  185. p_log->add_newline();
  186. }
  187. p_log->add_newline();
  188. return has_messages;
  189. }
  190. bool EditorExportPlatform::_check_hash(const uint8_t *p_hash, const Vector<uint8_t> &p_data) {
  191. if (p_hash == nullptr) {
  192. return false;
  193. }
  194. unsigned char hash[16];
  195. Error err = CryptoCore::md5(p_data.ptr(), p_data.size(), hash);
  196. if (err != OK) {
  197. return false;
  198. }
  199. for (int i = 0; i < 16; i++) {
  200. if (p_hash[i] != hash[i]) {
  201. return false;
  202. }
  203. }
  204. return true;
  205. }
  206. Error EditorExportPlatform::_load_patches(const Vector<String> &p_patches) {
  207. Error err = OK;
  208. if (!p_patches.is_empty()) {
  209. for (const String &path : p_patches) {
  210. err = PackedData::get_singleton()->add_pack(path, true, 0);
  211. if (err != OK) {
  212. add_message(EXPORT_MESSAGE_ERROR, TTR("Patch Creation"), vformat(TTR("Could not load patch pack with path \"%s\"."), path));
  213. return err;
  214. }
  215. }
  216. }
  217. return err;
  218. }
  219. void EditorExportPlatform::_unload_patches() {
  220. PackedData::get_singleton()->clear();
  221. }
  222. Error EditorExportPlatform::_encrypt_and_store_data(Ref<FileAccess> p_fd, const String &p_path, const Vector<uint8_t> &p_data, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed, bool &r_encrypt) {
  223. r_encrypt = false;
  224. for (int i = 0; i < p_enc_in_filters.size(); ++i) {
  225. if (p_path.matchn(p_enc_in_filters[i]) || p_path.trim_prefix("res://").matchn(p_enc_in_filters[i])) {
  226. r_encrypt = true;
  227. break;
  228. }
  229. }
  230. for (int i = 0; i < p_enc_ex_filters.size(); ++i) {
  231. if (p_path.matchn(p_enc_ex_filters[i]) || p_path.trim_prefix("res://").matchn(p_enc_ex_filters[i])) {
  232. r_encrypt = false;
  233. break;
  234. }
  235. }
  236. Ref<FileAccessEncrypted> fae;
  237. Ref<FileAccess> ftmp = p_fd;
  238. if (r_encrypt) {
  239. Vector<uint8_t> iv;
  240. if (p_seed != 0) {
  241. uint64_t seed = p_seed;
  242. const uint8_t *ptr = p_data.ptr();
  243. int64_t len = p_data.size();
  244. for (int64_t i = 0; i < len; i++) {
  245. seed = ((seed << 5) + seed) ^ ptr[i];
  246. }
  247. RandomPCG rng = RandomPCG(seed);
  248. iv.resize(16);
  249. for (int i = 0; i < 16; i++) {
  250. iv.write[i] = rng.rand() % 256;
  251. }
  252. }
  253. fae.instantiate();
  254. ERR_FAIL_COND_V(fae.is_null(), ERR_FILE_CANT_OPEN);
  255. Error err = fae->open_and_parse(ftmp, p_key, FileAccessEncrypted::MODE_WRITE_AES256, false, iv);
  256. ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
  257. ftmp = fae;
  258. }
  259. // Store file content.
  260. ftmp->store_buffer(p_data.ptr(), p_data.size());
  261. if (fae.is_valid()) {
  262. ftmp.unref();
  263. fae.unref();
  264. }
  265. return OK;
  266. }
  267. Error EditorExportPlatform::_save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  268. ERR_FAIL_COND_V_MSG(p_total < 1, ERR_PARAMETER_RANGE_ERROR, "Must select at least one file to export.");
  269. PackData *pd = (PackData *)p_userdata;
  270. String simplified_path = p_path.simplify_path();
  271. if (simplified_path.begins_with("uid://")) {
  272. simplified_path = ResourceUID::uid_to_path(simplified_path).simplify_path();
  273. print_verbose(vformat(R"(UID referenced exported file name "%s" was replaced with "%s".)", p_path, simplified_path));
  274. }
  275. Ref<FileAccess> ftmp;
  276. if (pd->use_sparse_pck) {
  277. ftmp = FileAccess::open(pd->path.get_base_dir().path_join(simplified_path.trim_prefix("res://")), FileAccess::WRITE);
  278. } else {
  279. ftmp = pd->f;
  280. }
  281. SavedData sd;
  282. sd.path_utf8 = simplified_path.trim_prefix("res://").utf8();
  283. sd.ofs = (pd->use_sparse_pck) ? 0 : pd->f->get_position();
  284. sd.size = p_data.size();
  285. Error err = _encrypt_and_store_data(ftmp, simplified_path, p_data, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed, sd.encrypted);
  286. if (err != OK) {
  287. return err;
  288. }
  289. if (!pd->use_sparse_pck) {
  290. ERR_FAIL_COND_V(pd->f->get_position() - sd.ofs < (uint64_t)p_data.size(), ERR_FILE_CANT_WRITE);
  291. }
  292. if (!pd->use_sparse_pck) {
  293. int pad = _get_pad(PCK_PADDING, pd->f->get_position());
  294. for (int i = 0; i < pad; i++) {
  295. pd->f->store_8(0);
  296. }
  297. }
  298. // Store MD5 of original file.
  299. {
  300. unsigned char hash[16];
  301. CryptoCore::md5(p_data.ptr(), p_data.size(), hash);
  302. sd.md5.resize(16);
  303. for (int i = 0; i < 16; i++) {
  304. sd.md5.write[i] = hash[i];
  305. }
  306. }
  307. pd->file_ofs.push_back(sd);
  308. // TRANSLATORS: This is an editor progress label describing the storing of a file.
  309. if (pd->ep->step(vformat(TTR("Storing File: %s"), p_path), 2 + p_file * 100 / p_total, false)) {
  310. return ERR_SKIP;
  311. }
  312. return OK;
  313. }
  314. Error EditorExportPlatform::_save_pack_patch_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  315. if (_check_hash(PackedData::get_singleton()->get_file_hash(p_path), p_data)) {
  316. return OK;
  317. }
  318. return _save_pack_file(p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed);
  319. }
  320. Error EditorExportPlatform::_save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  321. ERR_FAIL_COND_V_MSG(p_total < 1, ERR_PARAMETER_RANGE_ERROR, "Must select at least one file to export.");
  322. String path = p_path.simplify_path();
  323. if (path.begins_with("uid://")) {
  324. path = ResourceUID::uid_to_path(path).simplify_path();
  325. print_verbose(vformat(R"(UID referenced exported file name "%s" was replaced with "%s".)", p_path, path));
  326. }
  327. path = path.replace_first("res://", "");
  328. ZipData *zd = (ZipData *)p_userdata;
  329. zipFile zip = (zipFile)zd->zip;
  330. zipOpenNewFileInZip(zip,
  331. path.utf8().get_data(),
  332. nullptr,
  333. nullptr,
  334. 0,
  335. nullptr,
  336. 0,
  337. nullptr,
  338. Z_DEFLATED,
  339. Z_DEFAULT_COMPRESSION);
  340. zipWriteInFileInZip(zip, p_data.ptr(), p_data.size());
  341. zipCloseFileInZip(zip);
  342. zd->file_count += 1;
  343. if (zd->ep->step(TTR("Storing File:") + " " + p_path, 2 + p_file * 100 / p_total, false)) {
  344. return ERR_SKIP;
  345. }
  346. return OK;
  347. }
  348. Error EditorExportPlatform::_save_zip_patch_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  349. if (_check_hash(PackedData::get_singleton()->get_file_hash(p_path), p_data)) {
  350. return OK;
  351. }
  352. return _save_zip_file(p_userdata, p_path, p_data, p_file, p_total, p_enc_in_filters, p_enc_ex_filters, p_key, p_seed);
  353. }
  354. Ref<ImageTexture> EditorExportPlatform::get_option_icon(int p_index) const {
  355. Ref<Theme> theme = EditorNode::get_singleton()->get_editor_theme();
  356. ERR_FAIL_COND_V(theme.is_null(), Ref<ImageTexture>());
  357. return theme->get_icon(SNAME("Play"), EditorStringName(EditorIcons));
  358. }
  359. String EditorExportPlatform::find_export_template(const String &template_file_name, String *err) const {
  360. String current_version = GODOT_VERSION_FULL_CONFIG;
  361. String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(current_version).path_join(template_file_name);
  362. if (FileAccess::exists(template_path)) {
  363. return template_path;
  364. }
  365. // Not found
  366. if (err) {
  367. *err += TTR("No export template found at the expected path:") + "\n" + template_path + "\n";
  368. }
  369. return String();
  370. }
  371. bool EditorExportPlatform::exists_export_template(const String &template_file_name, String *err) const {
  372. return find_export_template(template_file_name, err) != "";
  373. }
  374. Ref<EditorExportPreset> EditorExportPlatform::create_preset() {
  375. Ref<EditorExportPreset> preset;
  376. preset.instantiate();
  377. preset->platform = Ref<EditorExportPlatform>(this);
  378. List<ExportOption> options;
  379. get_export_options(&options);
  380. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  381. for (int i = 0; i < export_plugins.size(); i++) {
  382. export_plugins.write[i]->_get_export_options(Ref<EditorExportPlatform>(this), &options);
  383. }
  384. for (const ExportOption &E : options) {
  385. StringName option_name = E.option.name;
  386. preset->properties[option_name] = E.option;
  387. preset->values[option_name] = E.default_value;
  388. preset->update_visibility[option_name] = E.update_visibility;
  389. }
  390. return preset;
  391. }
  392. void EditorExportPlatform::_export_find_resources(EditorFileSystemDirectory *p_dir, HashSet<String> &p_paths) {
  393. for (int i = 0; i < p_dir->get_subdir_count(); i++) {
  394. _export_find_resources(p_dir->get_subdir(i), p_paths);
  395. }
  396. for (int i = 0; i < p_dir->get_file_count(); i++) {
  397. if (p_dir->get_file_type(i) == "TextFile") {
  398. continue;
  399. }
  400. p_paths.insert(p_dir->get_file_path(i));
  401. }
  402. }
  403. void EditorExportPlatform::_export_find_customized_resources(const Ref<EditorExportPreset> &p_preset, EditorFileSystemDirectory *p_dir, EditorExportPreset::FileExportMode p_mode, HashSet<String> &p_paths) {
  404. for (int i = 0; i < p_dir->get_subdir_count(); i++) {
  405. EditorFileSystemDirectory *subdir = p_dir->get_subdir(i);
  406. _export_find_customized_resources(p_preset, subdir, p_preset->get_file_export_mode(subdir->get_path(), p_mode), p_paths);
  407. }
  408. for (int i = 0; i < p_dir->get_file_count(); i++) {
  409. if (p_dir->get_file_type(i) == "TextFile") {
  410. continue;
  411. }
  412. String path = p_dir->get_file_path(i);
  413. EditorExportPreset::FileExportMode file_mode = p_preset->get_file_export_mode(path, p_mode);
  414. if (file_mode != EditorExportPreset::MODE_FILE_REMOVE) {
  415. p_paths.insert(path);
  416. }
  417. }
  418. }
  419. void EditorExportPlatform::_export_find_dependencies(const String &p_path, HashSet<String> &p_paths) {
  420. if (p_paths.has(p_path)) {
  421. return;
  422. }
  423. p_paths.insert(p_path);
  424. EditorFileSystemDirectory *dir;
  425. int file_idx;
  426. dir = EditorFileSystem::get_singleton()->find_file(p_path, &file_idx);
  427. if (!dir) {
  428. return;
  429. }
  430. Vector<String> deps = dir->get_file_deps(file_idx);
  431. for (int i = 0; i < deps.size(); i++) {
  432. _export_find_dependencies(deps[i], p_paths);
  433. }
  434. }
  435. void EditorExportPlatform::_edit_files_with_filter(Ref<DirAccess> &da, const Vector<String> &p_filters, HashSet<String> &r_list, bool exclude) {
  436. da->list_dir_begin();
  437. String cur_dir = da->get_current_dir().replace_char('\\', '/');
  438. if (!cur_dir.ends_with("/")) {
  439. cur_dir += "/";
  440. }
  441. String cur_dir_no_prefix = cur_dir.replace("res://", "");
  442. Vector<String> dirs;
  443. String f = da->get_next();
  444. while (!f.is_empty()) {
  445. if (da->current_is_dir()) {
  446. dirs.push_back(f);
  447. } else {
  448. String fullpath = cur_dir + f;
  449. // Test also against path without res:// so that filters like `file.txt` can work.
  450. String fullpath_no_prefix = cur_dir_no_prefix + f;
  451. for (int i = 0; i < p_filters.size(); ++i) {
  452. if (fullpath.matchn(p_filters[i]) || fullpath_no_prefix.matchn(p_filters[i])) {
  453. if (!exclude) {
  454. r_list.insert(fullpath);
  455. } else {
  456. r_list.erase(fullpath);
  457. }
  458. }
  459. }
  460. }
  461. f = da->get_next();
  462. }
  463. da->list_dir_end();
  464. for (int i = 0; i < dirs.size(); ++i) {
  465. const String &dir = dirs[i];
  466. if (dir.begins_with(".")) {
  467. continue;
  468. }
  469. if (EditorFileSystem::_should_skip_directory(cur_dir + dir)) {
  470. continue;
  471. }
  472. da->change_dir(dir);
  473. _edit_files_with_filter(da, p_filters, r_list, exclude);
  474. da->change_dir("..");
  475. }
  476. }
  477. void EditorExportPlatform::_edit_filter_list(HashSet<String> &r_list, const String &p_filter, bool exclude) {
  478. if (p_filter.is_empty()) {
  479. return;
  480. }
  481. Vector<String> split = p_filter.split(",");
  482. Vector<String> filters;
  483. for (int i = 0; i < split.size(); i++) {
  484. String f = split[i].strip_edges();
  485. if (f.is_empty()) {
  486. continue;
  487. }
  488. filters.push_back(f);
  489. }
  490. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  491. ERR_FAIL_COND(da.is_null());
  492. _edit_files_with_filter(da, filters, r_list, exclude);
  493. }
  494. HashSet<String> EditorExportPlatform::get_features(const Ref<EditorExportPreset> &p_preset, bool p_debug) const {
  495. Ref<EditorExportPlatform> platform = p_preset->get_platform();
  496. List<String> feature_list;
  497. platform->get_platform_features(&feature_list);
  498. platform->get_preset_features(p_preset, &feature_list);
  499. HashSet<String> result;
  500. for (const String &E : feature_list) {
  501. result.insert(E);
  502. }
  503. result.insert("template");
  504. if (p_debug) {
  505. result.insert("debug");
  506. result.insert("template_debug");
  507. } else {
  508. result.insert("release");
  509. result.insert("template_release");
  510. }
  511. #ifdef REAL_T_IS_DOUBLE
  512. result.insert("double");
  513. #else
  514. result.insert("single");
  515. #endif // REAL_T_IS_DOUBLE
  516. if (!p_preset->get_custom_features().is_empty()) {
  517. Vector<String> tmp_custom_list = p_preset->get_custom_features().split(",");
  518. for (int i = 0; i < tmp_custom_list.size(); i++) {
  519. String f = tmp_custom_list[i].strip_edges();
  520. if (!f.is_empty()) {
  521. result.insert(f);
  522. }
  523. }
  524. }
  525. return result;
  526. }
  527. EditorExportPlatform::ExportNotifier::ExportNotifier(EditorExportPlatform &p_platform, const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  528. HashSet<String> features = p_platform.get_features(p_preset, p_debug);
  529. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  530. //initial export plugin callback
  531. for (int i = 0; i < export_plugins.size(); i++) {
  532. export_plugins.write[i]->set_export_preset(p_preset);
  533. if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_begin)) {
  534. PackedStringArray features_psa;
  535. for (const String &feature : features) {
  536. features_psa.push_back(feature);
  537. }
  538. export_plugins.write[i]->_export_begin_script(features_psa, p_debug, p_path, p_flags);
  539. } else {
  540. export_plugins.write[i]->_export_begin(features, p_debug, p_path, p_flags);
  541. }
  542. }
  543. }
  544. EditorExportPlatform::ExportNotifier::~ExportNotifier() {
  545. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  546. for (int i = 0; i < export_plugins.size(); i++) {
  547. if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_end)) {
  548. export_plugins.write[i]->_export_end_script();
  549. } else {
  550. export_plugins.write[i]->_export_end();
  551. }
  552. export_plugins.write[i]->_export_end_clear();
  553. export_plugins.write[i]->set_export_preset(Ref<EditorExportPlugin>());
  554. }
  555. }
  556. bool EditorExportPlatform::_export_customize_dictionary(Dictionary &dict, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
  557. bool changed = false;
  558. for (const Variant &K : dict.get_key_list()) {
  559. Variant v = dict[K];
  560. switch (v.get_type()) {
  561. case Variant::OBJECT: {
  562. Ref<Resource> res = v;
  563. if (res.is_valid()) {
  564. for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
  565. Ref<Resource> new_res = plugin->_customize_resource(res, "");
  566. if (new_res.is_valid()) {
  567. changed = true;
  568. if (new_res != res) {
  569. dict[K] = new_res;
  570. res = new_res;
  571. }
  572. break;
  573. }
  574. }
  575. // If it was not replaced, go through and see if there is something to replace.
  576. if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins), true) {
  577. changed = true;
  578. }
  579. }
  580. } break;
  581. case Variant::DICTIONARY: {
  582. Dictionary d = v;
  583. if (_export_customize_dictionary(d, customize_resources_plugins)) {
  584. changed = true;
  585. }
  586. } break;
  587. case Variant::ARRAY: {
  588. Array a = v;
  589. if (_export_customize_array(a, customize_resources_plugins)) {
  590. changed = true;
  591. }
  592. } break;
  593. default: {
  594. }
  595. }
  596. }
  597. return changed;
  598. }
  599. bool EditorExportPlatform::_export_customize_array(Array &arr, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
  600. bool changed = false;
  601. for (int i = 0; i < arr.size(); i++) {
  602. Variant v = arr.get(i);
  603. switch (v.get_type()) {
  604. case Variant::OBJECT: {
  605. Ref<Resource> res = v;
  606. if (res.is_valid()) {
  607. for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
  608. Ref<Resource> new_res = plugin->_customize_resource(res, "");
  609. if (new_res.is_valid()) {
  610. changed = true;
  611. if (new_res != res) {
  612. arr.set(i, new_res);
  613. res = new_res;
  614. }
  615. break;
  616. }
  617. }
  618. // If it was not replaced, go through and see if there is something to replace.
  619. if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins), true) {
  620. changed = true;
  621. }
  622. }
  623. } break;
  624. case Variant::DICTIONARY: {
  625. Dictionary d = v;
  626. if (_export_customize_dictionary(d, customize_resources_plugins)) {
  627. changed = true;
  628. }
  629. } break;
  630. case Variant::ARRAY: {
  631. Array a = v;
  632. if (_export_customize_array(a, customize_resources_plugins)) {
  633. changed = true;
  634. }
  635. } break;
  636. default: {
  637. }
  638. }
  639. }
  640. return changed;
  641. }
  642. bool EditorExportPlatform::_export_customize_object(Object *p_object, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
  643. bool changed = false;
  644. List<PropertyInfo> props;
  645. p_object->get_property_list(&props);
  646. for (const PropertyInfo &E : props) {
  647. switch (E.type) {
  648. case Variant::OBJECT: {
  649. Ref<Resource> res = p_object->get(E.name);
  650. if (res.is_valid()) {
  651. for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
  652. Ref<Resource> new_res = plugin->_customize_resource(res, "");
  653. if (new_res.is_valid()) {
  654. changed = true;
  655. if (new_res != res) {
  656. p_object->set(E.name, new_res);
  657. res = new_res;
  658. }
  659. break;
  660. }
  661. }
  662. // If it was not replaced, go through and see if there is something to replace.
  663. if (res.is_valid() && !res->get_path().is_resource_file() && _export_customize_object(res.ptr(), customize_resources_plugins), true) {
  664. changed = true;
  665. }
  666. }
  667. } break;
  668. case Variant::DICTIONARY: {
  669. Dictionary d = p_object->get(E.name);
  670. if (_export_customize_dictionary(d, customize_resources_plugins)) {
  671. // May have been generated, so set back just in case
  672. p_object->set(E.name, d);
  673. changed = true;
  674. }
  675. } break;
  676. case Variant::ARRAY: {
  677. Array a = p_object->get(E.name);
  678. if (_export_customize_array(a, customize_resources_plugins)) {
  679. // May have been generated, so set back just in case
  680. p_object->set(E.name, a);
  681. changed = true;
  682. }
  683. } break;
  684. default: {
  685. }
  686. }
  687. }
  688. return changed;
  689. }
  690. bool EditorExportPlatform::_is_editable_ancestor(Node *p_root, Node *p_node) {
  691. while (p_node != nullptr && p_node != p_root) {
  692. if (p_root->is_editable_instance(p_node)) {
  693. return true;
  694. }
  695. p_node = p_node->get_owner();
  696. }
  697. return false;
  698. }
  699. bool EditorExportPlatform::_export_customize_scene_resources(Node *p_root, Node *p_node, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins) {
  700. bool changed = false;
  701. if (p_root == p_node || p_node->get_owner() == p_root || _is_editable_ancestor(p_root, p_node)) {
  702. if (_export_customize_object(p_node, customize_resources_plugins)) {
  703. changed = true;
  704. }
  705. }
  706. for (int i = 0; i < p_node->get_child_count(); i++) {
  707. if (_export_customize_scene_resources(p_root, p_node->get_child(i), customize_resources_plugins)) {
  708. changed = true;
  709. }
  710. }
  711. return changed;
  712. }
  713. String EditorExportPlatform::_export_customize(const String &p_path, LocalVector<Ref<EditorExportPlugin>> &customize_resources_plugins, LocalVector<Ref<EditorExportPlugin>> &customize_scenes_plugins, HashMap<String, FileExportCache> &export_cache, const String &export_base_path, bool p_force_save) {
  714. if (!p_force_save && customize_resources_plugins.is_empty() && customize_scenes_plugins.is_empty()) {
  715. return p_path; // do none
  716. }
  717. // Check if a cache exists
  718. if (export_cache.has(p_path)) {
  719. FileExportCache &fec = export_cache[p_path];
  720. if (fec.saved_path.is_empty() || FileAccess::exists(fec.saved_path)) {
  721. // Destination file exists (was not erased) or not needed
  722. uint64_t mod_time = FileAccess::get_modified_time(p_path);
  723. if (fec.source_modified_time == mod_time) {
  724. // Cached (modified time matches).
  725. fec.used = true;
  726. return fec.saved_path.is_empty() ? p_path : fec.saved_path;
  727. }
  728. String md5 = FileAccess::get_md5(p_path);
  729. if (FileAccess::exists(p_path + ".import")) {
  730. // Also consider the import file in the string
  731. md5 += FileAccess::get_md5(p_path + ".import");
  732. }
  733. if (fec.source_md5 == md5) {
  734. // Cached (md5 matches).
  735. fec.source_modified_time = mod_time;
  736. fec.used = true;
  737. return fec.saved_path.is_empty() ? p_path : fec.saved_path;
  738. }
  739. }
  740. }
  741. FileExportCache fec;
  742. fec.used = true;
  743. fec.source_modified_time = FileAccess::get_modified_time(p_path);
  744. String md5 = FileAccess::get_md5(p_path);
  745. if (FileAccess::exists(p_path + ".import")) {
  746. // Also consider the import file in the string
  747. md5 += FileAccess::get_md5(p_path + ".import");
  748. }
  749. fec.source_md5 = md5;
  750. // Check if it should convert
  751. String type = ResourceLoader::get_resource_type(p_path);
  752. bool modified = false;
  753. String save_path;
  754. if (type == "PackedScene") { // Its a scene.
  755. Ref<PackedScene> ps = ResourceLoader::load(p_path, "PackedScene", ResourceFormatLoader::CACHE_MODE_IGNORE);
  756. ERR_FAIL_COND_V(ps.is_null(), p_path);
  757. Node *node = ps->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE); // Make sure the child scene root gets the correct inheritance chain.
  758. ERR_FAIL_NULL_V(node, p_path);
  759. if (!customize_scenes_plugins.is_empty()) {
  760. for (Ref<EditorExportPlugin> &plugin : customize_scenes_plugins) {
  761. Node *customized = plugin->_customize_scene(node, p_path);
  762. if (customized != nullptr) {
  763. node = customized;
  764. modified = true;
  765. }
  766. }
  767. }
  768. if (!customize_resources_plugins.is_empty()) {
  769. if (_export_customize_scene_resources(node, node, customize_resources_plugins)) {
  770. modified = true;
  771. }
  772. }
  773. if (modified || p_force_save) {
  774. // If modified, save it again. This is also used for TSCN -> SCN conversion on export.
  775. String base_file = p_path.get_file().get_basename() + ".scn"; // use SCN for saving (binary) and repack (If conversting, TSCN PackedScene representation is inefficient, so repacking is also desired).
  776. save_path = export_base_path.path_join("export-" + p_path.md5_text() + "-" + base_file);
  777. Ref<PackedScene> s;
  778. s.instantiate();
  779. s->pack(node);
  780. Error err = ResourceSaver::save(s, save_path);
  781. ERR_FAIL_COND_V_MSG(err != OK, p_path, "Unable to save export scene file to: " + save_path);
  782. }
  783. node->queue_free();
  784. } else {
  785. Ref<Resource> res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_IGNORE);
  786. ERR_FAIL_COND_V(res.is_null(), p_path);
  787. if (!customize_resources_plugins.is_empty()) {
  788. for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
  789. Ref<Resource> new_res = plugin->_customize_resource(res, p_path);
  790. if (new_res.is_valid()) {
  791. modified = true;
  792. if (new_res != res) {
  793. res = new_res;
  794. }
  795. break;
  796. }
  797. }
  798. if (_export_customize_object(res.ptr(), customize_resources_plugins)) {
  799. modified = true;
  800. }
  801. }
  802. if (modified || p_force_save) {
  803. // If modified, save it again. This is also used for TRES -> RES conversion on export.
  804. String base_file = p_path.get_file().get_basename() + ".res"; // use RES for saving (binary)
  805. save_path = export_base_path.path_join("export-" + p_path.md5_text() + "-" + base_file);
  806. Error err = ResourceSaver::save(res, save_path);
  807. ERR_FAIL_COND_V_MSG(err != OK, p_path, "Unable to save export resource file to: " + save_path);
  808. }
  809. }
  810. fec.saved_path = save_path;
  811. export_cache[p_path] = fec;
  812. return save_path.is_empty() ? p_path : save_path;
  813. }
  814. String EditorExportPlatform::_get_script_encryption_key(const Ref<EditorExportPreset> &p_preset) const {
  815. const String from_env = OS::get_singleton()->get_environment(ENV_SCRIPT_ENCRYPTION_KEY);
  816. if (!from_env.is_empty()) {
  817. return from_env.to_lower();
  818. }
  819. return p_preset->get_script_encryption_key().to_lower();
  820. }
  821. Dictionary EditorExportPlatform::get_internal_export_files(const Ref<EditorExportPreset> &p_preset, bool p_debug) {
  822. Dictionary files;
  823. // Text server support data.
  824. if (TS->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA) && (bool)get_project_setting(p_preset, "internationalization/locale/include_text_server_data")) {
  825. String ts_name = TS->get_support_data_filename();
  826. String ts_target = "res://" + ts_name;
  827. if (!ts_name.is_empty()) {
  828. bool export_ok = false;
  829. if (FileAccess::exists(ts_target)) { // Include user supplied data file.
  830. const PackedByteArray &ts_data = FileAccess::get_file_as_bytes(ts_target);
  831. if (!ts_data.is_empty()) {
  832. add_message(EXPORT_MESSAGE_INFO, TTR("Export"), TTR("Using user provided text server data, text display in the exported project might be broken if export template was built with different ICU version!"));
  833. files[ts_target] = ts_data;
  834. export_ok = true;
  835. }
  836. } else {
  837. String current_version = GODOT_VERSION_FULL_CONFIG;
  838. String template_path = EditorPaths::get_singleton()->get_export_templates_dir().path_join(current_version);
  839. if (p_debug && p_preset->has("custom_template/debug") && p_preset->get("custom_template/debug") != "") {
  840. template_path = p_preset->get("custom_template/debug").operator String().get_base_dir();
  841. } else if (!p_debug && p_preset->has("custom_template/release") && p_preset->get("custom_template/release") != "") {
  842. template_path = p_preset->get("custom_template/release").operator String().get_base_dir();
  843. }
  844. String data_file_name = template_path.path_join(ts_name);
  845. if (FileAccess::exists(data_file_name)) {
  846. const PackedByteArray &ts_data = FileAccess::get_file_as_bytes(data_file_name);
  847. if (!ts_data.is_empty()) {
  848. print_line("Using text server data from export templates.");
  849. files[ts_target] = ts_data;
  850. export_ok = true;
  851. }
  852. } else {
  853. const PackedByteArray &ts_data = TS->get_support_data();
  854. if (!ts_data.is_empty()) {
  855. add_message(EXPORT_MESSAGE_INFO, TTR("Export"), TTR("Using editor embedded text server data, text display in the exported project might be broken if export template was built with different ICU version!"));
  856. files[ts_target] = ts_data;
  857. export_ok = true;
  858. }
  859. }
  860. }
  861. if (!export_ok) {
  862. add_message(EXPORT_MESSAGE_WARNING, TTR("Export"), TTR("Missing text server data, text display in the exported project might be broken!"));
  863. }
  864. }
  865. }
  866. return files;
  867. }
  868. Vector<String> EditorExportPlatform::get_forced_export_files(const Ref<EditorExportPreset> &p_preset) {
  869. Vector<String> files;
  870. files.push_back(ProjectSettings::get_singleton()->get_global_class_list_path());
  871. String icon = ResourceUID::ensure_path(get_project_setting(p_preset, "application/config/icon"));
  872. String splash = ResourceUID::ensure_path(get_project_setting(p_preset, "application/boot_splash/image"));
  873. if (!icon.is_empty() && FileAccess::exists(icon)) {
  874. files.push_back(icon);
  875. }
  876. if (!splash.is_empty() && FileAccess::exists(splash) && icon != splash) {
  877. files.push_back(splash);
  878. }
  879. String resource_cache_file = ResourceUID::get_cache_file();
  880. if (FileAccess::exists(resource_cache_file)) {
  881. files.push_back(resource_cache_file);
  882. }
  883. String extension_list_config_file = GDExtension::get_extension_list_config_file();
  884. if (FileAccess::exists(extension_list_config_file)) {
  885. files.push_back(extension_list_config_file);
  886. }
  887. return files;
  888. }
  889. Error EditorExportPlatform::_script_save_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key, uint64_t p_seed) {
  890. Callable cb = ((ScriptCallbackData *)p_userdata)->file_cb;
  891. ERR_FAIL_COND_V(!cb.is_valid(), FAILED);
  892. String simplified_path = p_path.simplify_path();
  893. if (simplified_path.begins_with("uid://")) {
  894. simplified_path = ResourceUID::uid_to_path(simplified_path).simplify_path();
  895. print_verbose(vformat(R"(UID referenced exported file name "%s" was replaced with "%s".)", p_path, simplified_path));
  896. }
  897. Variant path = simplified_path;
  898. Variant data = p_data;
  899. Variant file = p_file;
  900. Variant total = p_total;
  901. Variant enc_in = p_enc_in_filters;
  902. Variant enc_ex = p_enc_ex_filters;
  903. Variant enc_key = p_key;
  904. Variant ret;
  905. Callable::CallError ce;
  906. const Variant *args[7] = { &path, &data, &file, &total, &enc_in, &enc_ex, &enc_key };
  907. cb.callp(args, 7, ret, ce);
  908. ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, FAILED, vformat("Failed to execute file save callback: %s.", Variant::get_callable_error_text(cb, args, 7, ce)));
  909. return (Error)ret.operator int();
  910. }
  911. Error EditorExportPlatform::_script_add_shared_object(void *p_userdata, const SharedObject &p_so) {
  912. Callable cb = ((ScriptCallbackData *)p_userdata)->so_cb;
  913. if (!cb.is_valid()) {
  914. return OK; // Optional.
  915. }
  916. Variant path = p_so.path;
  917. Variant tags = p_so.tags;
  918. Variant target = p_so.target;
  919. Variant ret;
  920. Callable::CallError ce;
  921. const Variant *args[3] = { &path, &tags, &target };
  922. cb.callp(args, 3, ret, ce);
  923. ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, FAILED, vformat("Failed to execute shared object save callback: %s.", Variant::get_callable_error_text(cb, args, 3, ce)));
  924. return (Error)ret.operator int();
  925. }
  926. Error EditorExportPlatform::_export_project_files(const Ref<EditorExportPreset> &p_preset, bool p_debug, const Callable &p_save_func, const Callable &p_so_func) {
  927. ScriptCallbackData data;
  928. data.file_cb = p_save_func;
  929. data.so_cb = p_so_func;
  930. return export_project_files(p_preset, p_debug, _script_save_file, nullptr, &data, _script_add_shared_object);
  931. }
  932. Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &p_preset, bool p_debug, EditorExportSaveFunction p_save_func, EditorExportRemoveFunction p_remove_func, void *p_udata, EditorExportSaveSharedObject p_so_func) {
  933. //figure out paths of files that will be exported
  934. HashSet<String> paths;
  935. Vector<String> path_remaps;
  936. if (p_preset->get_export_filter() == EditorExportPreset::EXPORT_ALL_RESOURCES) {
  937. //find stuff
  938. _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(), paths);
  939. } else if (p_preset->get_export_filter() == EditorExportPreset::EXCLUDE_SELECTED_RESOURCES) {
  940. _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(), paths);
  941. Vector<String> files = p_preset->get_files_to_export();
  942. for (int i = 0; i < files.size(); i++) {
  943. paths.erase(files[i]);
  944. }
  945. } else if (p_preset->get_export_filter() == EditorExportPreset::EXPORT_CUSTOMIZED) {
  946. _export_find_customized_resources(p_preset, EditorFileSystem::get_singleton()->get_filesystem(), p_preset->get_file_export_mode("res://"), paths);
  947. } else {
  948. bool scenes_only = p_preset->get_export_filter() == EditorExportPreset::EXPORT_SELECTED_SCENES;
  949. Vector<String> files = p_preset->get_files_to_export();
  950. for (int i = 0; i < files.size(); i++) {
  951. if (scenes_only && ResourceLoader::get_resource_type(files[i]) != "PackedScene") {
  952. continue;
  953. }
  954. _export_find_dependencies(files[i], paths);
  955. }
  956. // Add autoload resources and their dependencies
  957. List<PropertyInfo> props;
  958. ProjectSettings::get_singleton()->get_property_list(&props);
  959. for (const PropertyInfo &pi : props) {
  960. if (!pi.name.begins_with("autoload/")) {
  961. continue;
  962. }
  963. String autoload_path = get_project_setting(p_preset, pi.name);
  964. if (autoload_path.begins_with("*")) {
  965. autoload_path = autoload_path.substr(1);
  966. }
  967. _export_find_dependencies(autoload_path, paths);
  968. }
  969. }
  970. //add native icons to non-resource include list
  971. _edit_filter_list(paths, String("*.icns"), false);
  972. _edit_filter_list(paths, String("*.ico"), false);
  973. _edit_filter_list(paths, p_preset->get_include_filter(), false);
  974. _edit_filter_list(paths, p_preset->get_exclude_filter(), true);
  975. // Ignore import files, since these are automatically added to the jar later with the resources
  976. _edit_filter_list(paths, String("*.import"), true);
  977. // Get encryption filters.
  978. bool enc_pck = p_preset->get_enc_pck();
  979. Vector<String> enc_in_filters;
  980. Vector<String> enc_ex_filters;
  981. Vector<uint8_t> key;
  982. uint64_t seed = 0;
  983. if (enc_pck) {
  984. seed = p_preset->get_seed();
  985. Vector<String> enc_in_split = p_preset->get_enc_in_filter().split(",");
  986. for (int i = 0; i < enc_in_split.size(); i++) {
  987. String f = enc_in_split[i].strip_edges();
  988. if (f.is_empty()) {
  989. continue;
  990. }
  991. enc_in_filters.push_back(f);
  992. }
  993. Vector<String> enc_ex_split = p_preset->get_enc_ex_filter().split(",");
  994. for (int i = 0; i < enc_ex_split.size(); i++) {
  995. String f = enc_ex_split[i].strip_edges();
  996. if (f.is_empty()) {
  997. continue;
  998. }
  999. enc_ex_filters.push_back(f);
  1000. }
  1001. // Get encryption key.
  1002. String script_key = _get_script_encryption_key(p_preset);
  1003. key.resize(32);
  1004. if (script_key.length() == 64) {
  1005. for (int i = 0; i < 32; i++) {
  1006. int v = 0;
  1007. if (i * 2 < script_key.length()) {
  1008. char32_t ct = script_key[i * 2];
  1009. if (is_digit(ct)) {
  1010. ct = ct - '0';
  1011. } else if (ct >= 'a' && ct <= 'f') {
  1012. ct = 10 + ct - 'a';
  1013. }
  1014. v |= ct << 4;
  1015. }
  1016. if (i * 2 + 1 < script_key.length()) {
  1017. char32_t ct = script_key[i * 2 + 1];
  1018. if (is_digit(ct)) {
  1019. ct = ct - '0';
  1020. } else if (ct >= 'a' && ct <= 'f') {
  1021. ct = 10 + ct - 'a';
  1022. }
  1023. v |= ct;
  1024. }
  1025. key.write[i] = v;
  1026. }
  1027. }
  1028. }
  1029. EditorExportSaveProxy save_proxy(p_save_func, p_remove_func != nullptr);
  1030. Error err = OK;
  1031. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  1032. struct SortByName {
  1033. bool operator()(const Ref<EditorExportPlugin> &left, const Ref<EditorExportPlugin> &right) const {
  1034. return left->get_name() < right->get_name();
  1035. }
  1036. };
  1037. auto add_shared_objects_and_extra_files_from_export_plugins = [&]() {
  1038. for (int i = 0; i < export_plugins.size(); i++) {
  1039. if (p_so_func) {
  1040. for (int j = 0; j < export_plugins[i]->shared_objects.size(); j++) {
  1041. err = p_so_func(p_udata, export_plugins[i]->shared_objects[j]);
  1042. if (err != OK) {
  1043. return err;
  1044. }
  1045. }
  1046. }
  1047. for (int j = 0; j < export_plugins[i]->extra_files.size(); j++) {
  1048. err = save_proxy.save_file(p_udata, export_plugins[i]->extra_files[j].path, export_plugins[i]->extra_files[j].data, 0, paths.size(), enc_in_filters, enc_ex_filters, key, seed);
  1049. if (err != OK) {
  1050. return err;
  1051. }
  1052. }
  1053. export_plugins.write[i]->_clear();
  1054. }
  1055. return OK;
  1056. };
  1057. // Always sort by name, to so if for some reason they are re-arranged, it still works.
  1058. export_plugins.sort_custom<SortByName>();
  1059. HashSet<String> features = get_features(p_preset, p_debug);
  1060. PackedStringArray features_psa;
  1061. for (const String &feature : features) {
  1062. features_psa.push_back(feature);
  1063. }
  1064. // Check if custom processing is needed
  1065. uint32_t custom_resources_hash = HASH_MURMUR3_SEED;
  1066. uint32_t custom_scene_hash = HASH_MURMUR3_SEED;
  1067. LocalVector<Ref<EditorExportPlugin>> customize_resources_plugins;
  1068. LocalVector<Ref<EditorExportPlugin>> customize_scenes_plugins;
  1069. for (int i = 0; i < export_plugins.size(); i++) {
  1070. if (export_plugins.write[i]->_begin_customize_resources(Ref<EditorExportPlatform>(this), features_psa)) {
  1071. customize_resources_plugins.push_back(export_plugins[i]);
  1072. custom_resources_hash = hash_murmur3_one_64(export_plugins[i]->get_name().hash64(), custom_resources_hash);
  1073. uint64_t hash = export_plugins[i]->_get_customization_configuration_hash();
  1074. custom_resources_hash = hash_murmur3_one_64(hash, custom_resources_hash);
  1075. }
  1076. if (export_plugins.write[i]->_begin_customize_scenes(Ref<EditorExportPlatform>(this), features_psa)) {
  1077. customize_scenes_plugins.push_back(export_plugins[i]);
  1078. custom_resources_hash = hash_murmur3_one_64(export_plugins[i]->get_name().hash64(), custom_resources_hash);
  1079. uint64_t hash = export_plugins[i]->_get_customization_configuration_hash();
  1080. custom_scene_hash = hash_murmur3_one_64(hash, custom_scene_hash);
  1081. }
  1082. }
  1083. // Add any files that might've been defined during the initial steps of the export plugins.
  1084. err = add_shared_objects_and_extra_files_from_export_plugins();
  1085. if (err != OK) {
  1086. return err;
  1087. }
  1088. HashMap<String, FileExportCache> export_cache;
  1089. String export_base_path = ProjectSettings::get_singleton()->get_project_data_path().path_join("exported/") + itos(custom_resources_hash);
  1090. bool convert_text_to_binary = get_project_setting(p_preset, "editor/export/convert_text_resources_to_binary");
  1091. if (convert_text_to_binary || !customize_resources_plugins.is_empty() || !customize_scenes_plugins.is_empty()) {
  1092. // See if we have something to open
  1093. Ref<FileAccess> f = FileAccess::open(export_base_path.path_join("file_cache"), FileAccess::READ);
  1094. if (f.is_valid()) {
  1095. String l = f->get_line();
  1096. while (l != String()) {
  1097. Vector<String> fields = l.split("::");
  1098. if (fields.size() == 4) {
  1099. FileExportCache fec;
  1100. const String &path = fields[0];
  1101. fec.source_md5 = fields[1].strip_edges();
  1102. fec.source_modified_time = fields[2].strip_edges().to_int();
  1103. fec.saved_path = fields[3];
  1104. fec.used = false; // Assume unused until used.
  1105. export_cache[path] = fec;
  1106. }
  1107. l = f->get_line();
  1108. }
  1109. } else {
  1110. // create the path
  1111. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1112. d->change_dir(ProjectSettings::get_singleton()->get_project_data_path());
  1113. d->make_dir_recursive("exported/" + itos(custom_resources_hash));
  1114. }
  1115. }
  1116. for (int i = 0; i < export_plugins.size(); i++) {
  1117. export_plugins.write[i]->set_export_base_path(export_base_path);
  1118. }
  1119. //store everything in the export medium
  1120. int total = paths.size();
  1121. // idx is incremented at the beginning of the paths loop to easily allow
  1122. // for continue statements without accidentally skipping an increment.
  1123. int idx = total > 0 ? -1 : 0;
  1124. for (const String &E : paths) {
  1125. idx++;
  1126. String path = E;
  1127. String type = ResourceLoader::get_resource_type(path);
  1128. bool has_import_file = FileAccess::exists(path + ".import");
  1129. Ref<ConfigFile> config;
  1130. if (has_import_file) {
  1131. config.instantiate();
  1132. err = config->load(path + ".import");
  1133. if (err != OK) {
  1134. ERR_PRINT("Could not parse: '" + path + "', not exported.");
  1135. continue;
  1136. }
  1137. String importer_type = config->get_value("remap", "importer");
  1138. if (importer_type == "skip") {
  1139. // Skip file.
  1140. continue;
  1141. }
  1142. }
  1143. bool do_export = true;
  1144. for (int i = 0; i < export_plugins.size(); i++) {
  1145. if (GDVIRTUAL_IS_OVERRIDDEN_PTR(export_plugins[i], _export_file)) {
  1146. export_plugins.write[i]->_export_file_script(path, type, features_psa);
  1147. } else {
  1148. export_plugins.write[i]->_export_file(path, type, features);
  1149. }
  1150. if (p_so_func) {
  1151. for (int j = 0; j < export_plugins[i]->shared_objects.size(); j++) {
  1152. err = p_so_func(p_udata, export_plugins[i]->shared_objects[j]);
  1153. if (err != OK) {
  1154. return err;
  1155. }
  1156. }
  1157. }
  1158. for (int j = 0; j < export_plugins[i]->extra_files.size(); j++) {
  1159. err = save_proxy.save_file(p_udata, export_plugins[i]->extra_files[j].path, export_plugins[i]->extra_files[j].data, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1160. if (err != OK) {
  1161. return err;
  1162. }
  1163. if (export_plugins[i]->extra_files[j].remap) {
  1164. do_export = false; // If remap, do not.
  1165. path_remaps.push_back(path);
  1166. path_remaps.push_back(export_plugins[i]->extra_files[j].path);
  1167. }
  1168. }
  1169. if (export_plugins[i]->skipped) {
  1170. do_export = false;
  1171. }
  1172. export_plugins.write[i]->_clear();
  1173. if (!do_export) {
  1174. break;
  1175. }
  1176. }
  1177. if (!do_export) {
  1178. continue;
  1179. }
  1180. if (has_import_file) {
  1181. String importer_type = config->get_value("remap", "importer");
  1182. if (importer_type == "keep") {
  1183. // Just keep file as-is.
  1184. Vector<uint8_t> array = FileAccess::get_file_as_bytes(path);
  1185. err = save_proxy.save_file(p_udata, path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1186. if (err != OK) {
  1187. return err;
  1188. }
  1189. continue;
  1190. }
  1191. // Before doing this, try to see if it can be customized.
  1192. String export_path = _export_customize(path, customize_resources_plugins, customize_scenes_plugins, export_cache, export_base_path, false);
  1193. if (export_path != path) {
  1194. // It was actually customized.
  1195. // Since the original file is likely not recognized, just use the import system.
  1196. config->set_value("remap", "type", ResourceLoader::get_resource_type(export_path));
  1197. // Erase all Paths.
  1198. Vector<String> keys = config->get_section_keys("remap");
  1199. for (const String &K : keys) {
  1200. if (K.begins_with("path")) {
  1201. config->erase_section_key("remap", K);
  1202. }
  1203. }
  1204. // Set actual converted path.
  1205. config->set_value("remap", "path", export_path);
  1206. // Erase useless sections.
  1207. if (config->has_section("deps")) {
  1208. config->erase_section("deps");
  1209. }
  1210. if (config->has_section("params")) {
  1211. config->erase_section("params");
  1212. }
  1213. String import_text = config->encode_to_text();
  1214. CharString cs = import_text.utf8();
  1215. Vector<uint8_t> sarr;
  1216. sarr.resize(cs.size());
  1217. memcpy(sarr.ptrw(), cs.ptr(), sarr.size());
  1218. err = save_proxy.save_file(p_udata, path + ".import", sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1219. if (err != OK) {
  1220. return err;
  1221. }
  1222. // Now actual remapped file:
  1223. sarr = FileAccess::get_file_as_bytes(export_path);
  1224. err = save_proxy.save_file(p_udata, export_path, sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1225. if (err != OK) {
  1226. return err;
  1227. }
  1228. } else {
  1229. // File is imported and not customized, replace by what it imports.
  1230. Vector<String> remaps = config->get_section_keys("remap");
  1231. HashSet<String> remap_features;
  1232. for (const String &F : remaps) {
  1233. String remap = F;
  1234. String feature = remap.get_slicec('.', 1);
  1235. if (features.has(feature)) {
  1236. remap_features.insert(feature);
  1237. }
  1238. }
  1239. if (remap_features.size() > 1) {
  1240. resolve_platform_feature_priorities(p_preset, remap_features);
  1241. }
  1242. err = OK;
  1243. for (const String &F : remaps) {
  1244. String remap = F;
  1245. if (remap == "path") {
  1246. String remapped_path = config->get_value("remap", remap);
  1247. Vector<uint8_t> array = FileAccess::get_file_as_bytes(remapped_path);
  1248. err = save_proxy.save_file(p_udata, remapped_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1249. } else if (remap.begins_with("path.")) {
  1250. String feature = remap.get_slicec('.', 1);
  1251. if (remap_features.has(feature)) {
  1252. String remapped_path = config->get_value("remap", remap);
  1253. Vector<uint8_t> array = FileAccess::get_file_as_bytes(remapped_path);
  1254. err = save_proxy.save_file(p_udata, remapped_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1255. } else {
  1256. // Remove paths if feature not enabled.
  1257. config->erase_section_key("remap", remap);
  1258. }
  1259. }
  1260. }
  1261. if (err != OK) {
  1262. return err;
  1263. }
  1264. // Erase useless sections.
  1265. if (config->has_section("deps")) {
  1266. config->erase_section("deps");
  1267. }
  1268. if (config->has_section("params")) {
  1269. config->erase_section("params");
  1270. }
  1271. String import_text = config->encode_to_text();
  1272. CharString cs = import_text.utf8();
  1273. Vector<uint8_t> sarr;
  1274. sarr.resize(cs.size());
  1275. memcpy(sarr.ptrw(), cs.ptr(), sarr.size());
  1276. err = save_proxy.save_file(p_udata, path + ".import", sarr, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1277. if (err != OK) {
  1278. return err;
  1279. }
  1280. }
  1281. } else {
  1282. // Just store it as it comes.
  1283. // Customization only happens if plugins did not take care of it before.
  1284. bool force_binary = convert_text_to_binary && (path.get_extension().to_lower() == "tres" || path.get_extension().to_lower() == "tscn");
  1285. String export_path = _export_customize(path, customize_resources_plugins, customize_scenes_plugins, export_cache, export_base_path, force_binary);
  1286. if (export_path != path) {
  1287. // Add a remap entry.
  1288. path_remaps.push_back(path);
  1289. path_remaps.push_back(export_path);
  1290. }
  1291. Vector<uint8_t> array = FileAccess::get_file_as_bytes(export_path);
  1292. err = save_proxy.save_file(p_udata, export_path, array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1293. if (err != OK) {
  1294. return err;
  1295. }
  1296. }
  1297. }
  1298. if (convert_text_to_binary || !customize_resources_plugins.is_empty() || !customize_scenes_plugins.is_empty()) {
  1299. // End scene customization
  1300. String fcache = export_base_path.path_join("file_cache");
  1301. Ref<FileAccess> f = FileAccess::open(fcache, FileAccess::WRITE);
  1302. if (f.is_valid()) {
  1303. for (const KeyValue<String, FileExportCache> &E : export_cache) {
  1304. if (E.value.used) { // May be old, unused
  1305. String l = E.key + "::" + E.value.source_md5 + "::" + itos(E.value.source_modified_time) + "::" + E.value.saved_path;
  1306. f->store_line(l);
  1307. }
  1308. }
  1309. } else {
  1310. ERR_PRINT("Error opening export file cache: " + fcache);
  1311. }
  1312. for (Ref<EditorExportPlugin> &plugin : customize_resources_plugins) {
  1313. plugin->_end_customize_resources();
  1314. }
  1315. for (Ref<EditorExportPlugin> &plugin : customize_scenes_plugins) {
  1316. plugin->_end_customize_scenes();
  1317. }
  1318. }
  1319. // Add any files that might've been defined during the final steps of the export plugins.
  1320. err = add_shared_objects_and_extra_files_from_export_plugins();
  1321. if (err != OK) {
  1322. return err;
  1323. }
  1324. //save config!
  1325. Vector<String> custom_list;
  1326. if (!p_preset->get_custom_features().is_empty()) {
  1327. Vector<String> tmp_custom_list = p_preset->get_custom_features().split(",");
  1328. for (int i = 0; i < tmp_custom_list.size(); i++) {
  1329. String f = tmp_custom_list[i].strip_edges();
  1330. if (!f.is_empty()) {
  1331. custom_list.push_back(f);
  1332. }
  1333. }
  1334. }
  1335. for (int i = 0; i < export_plugins.size(); i++) {
  1336. custom_list.append_array(export_plugins[i]->_get_export_features(Ref<EditorExportPlatform>(this), p_debug));
  1337. }
  1338. if (path_remaps.size()) {
  1339. for (int i = 0; i < path_remaps.size(); i += 2) {
  1340. const String &from = path_remaps[i];
  1341. const String &to = path_remaps[i + 1];
  1342. String remap_file = "[remap]\n\npath=\"" + to.c_escape() + "\"\n";
  1343. CharString utf8 = remap_file.utf8();
  1344. Vector<uint8_t> new_file;
  1345. new_file.resize(utf8.length());
  1346. for (int j = 0; j < utf8.length(); j++) {
  1347. new_file.write[j] = utf8[j];
  1348. }
  1349. err = save_proxy.save_file(p_udata, from + ".remap", new_file, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1350. if (err != OK) {
  1351. return err;
  1352. }
  1353. }
  1354. }
  1355. Vector<String> forced_export = get_forced_export_files(p_preset);
  1356. for (int i = 0; i < forced_export.size(); i++) {
  1357. Vector<uint8_t> array;
  1358. if (GDExtension::get_extension_list_config_file() == forced_export[i]) {
  1359. array = _filter_extension_list_config_file(forced_export[i], paths);
  1360. if (array.is_empty()) {
  1361. continue;
  1362. }
  1363. } else {
  1364. array = FileAccess::get_file_as_bytes(forced_export[i]);
  1365. }
  1366. err = save_proxy.save_file(p_udata, forced_export[i], array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1367. if (err != OK) {
  1368. return err;
  1369. }
  1370. }
  1371. Dictionary int_export = get_internal_export_files(p_preset, p_debug);
  1372. for (const KeyValue<Variant, Variant> &int_export_kv : int_export) {
  1373. const PackedByteArray &array = int_export_kv.value;
  1374. err = save_proxy.save_file(p_udata, int_export_kv.key, array, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1375. if (err != OK) {
  1376. return err;
  1377. }
  1378. }
  1379. String config_file = "project.binary";
  1380. String engine_cfb = EditorPaths::get_singleton()->get_temp_dir().path_join("tmp" + config_file);
  1381. ProjectSettings::CustomMap custom_map = get_custom_project_settings(p_preset);
  1382. ProjectSettings::get_singleton()->save_custom(engine_cfb, custom_map, custom_list);
  1383. Vector<uint8_t> data = FileAccess::get_file_as_bytes(engine_cfb);
  1384. DirAccess::remove_file_or_error(engine_cfb);
  1385. err = save_proxy.save_file(p_udata, "res://" + config_file, data, idx, total, enc_in_filters, enc_ex_filters, key, seed);
  1386. if (err != OK) {
  1387. return err;
  1388. }
  1389. if (p_remove_func) {
  1390. HashSet<String> currently_loaded_paths = PackedData::get_singleton()->get_file_paths();
  1391. for (const String &path : currently_loaded_paths) {
  1392. if (!save_proxy.has_saved(path)) {
  1393. err = p_remove_func(p_udata, path);
  1394. if (err != OK) {
  1395. return err;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. return OK;
  1401. }
  1402. Vector<uint8_t> EditorExportPlatform::_filter_extension_list_config_file(const String &p_config_path, const HashSet<String> &p_paths) {
  1403. Ref<FileAccess> f = FileAccess::open(p_config_path, FileAccess::READ);
  1404. if (f.is_null()) {
  1405. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Can't open file from path '" + String(p_config_path) + "'.");
  1406. }
  1407. Vector<uint8_t> data;
  1408. while (!f->eof_reached()) {
  1409. String l = f->get_line().strip_edges();
  1410. if (p_paths.has(l)) {
  1411. data.append_array(l.to_utf8_buffer());
  1412. data.append('\n');
  1413. }
  1414. }
  1415. return data;
  1416. }
  1417. Error EditorExportPlatform::_pack_add_shared_object(void *p_userdata, const SharedObject &p_so) {
  1418. PackData *pack_data = (PackData *)p_userdata;
  1419. if (pack_data->so_files) {
  1420. pack_data->so_files->push_back(p_so);
  1421. }
  1422. return OK;
  1423. }
  1424. Error EditorExportPlatform::_remove_pack_file(void *p_userdata, const String &p_path) {
  1425. PackData *pd = (PackData *)p_userdata;
  1426. SavedData sd;
  1427. sd.path_utf8 = p_path.utf8();
  1428. sd.ofs = pd->f->get_position();
  1429. sd.size = 0;
  1430. sd.removal = true;
  1431. // This padding will likely never be added, as we should already be aligned when removals are added.
  1432. int pad = _get_pad(PCK_PADDING, pd->f->get_position());
  1433. for (int i = 0; i < pad; i++) {
  1434. pd->f->store_8(0);
  1435. }
  1436. sd.md5.resize_initialized(16);
  1437. pd->file_ofs.push_back(sd);
  1438. return OK;
  1439. }
  1440. Error EditorExportPlatform::_zip_add_shared_object(void *p_userdata, const SharedObject &p_so) {
  1441. ZipData *zip_data = (ZipData *)p_userdata;
  1442. if (zip_data->so_files) {
  1443. zip_data->so_files->push_back(p_so);
  1444. }
  1445. return OK;
  1446. }
  1447. void EditorExportPlatform::zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name) {
  1448. String dir = p_folder.is_empty() ? p_root_path : p_root_path.path_join(p_folder);
  1449. Ref<DirAccess> da = DirAccess::open(dir);
  1450. ERR_FAIL_COND(da.is_null());
  1451. da->list_dir_begin();
  1452. String f = da->get_next();
  1453. while (!f.is_empty()) {
  1454. if (f == "." || f == "..") {
  1455. f = da->get_next();
  1456. continue;
  1457. }
  1458. if (da->is_link(f)) {
  1459. OS::DateTime dt = OS::get_singleton()->get_datetime();
  1460. zip_fileinfo zipfi;
  1461. zipfi.tmz_date.tm_year = dt.year;
  1462. zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/
  1463. zipfi.tmz_date.tm_mday = dt.day;
  1464. zipfi.tmz_date.tm_hour = dt.hour;
  1465. zipfi.tmz_date.tm_min = dt.minute;
  1466. zipfi.tmz_date.tm_sec = dt.second;
  1467. zipfi.dosDate = 0;
  1468. // 0120000: symbolic link type
  1469. // 0000755: permissions rwxr-xr-x
  1470. // 0000644: permissions rw-r--r--
  1471. uint32_t _mode = 0120644;
  1472. zipfi.external_fa = (_mode << 16L) | !(_mode & 0200);
  1473. zipfi.internal_fa = 0;
  1474. zipOpenNewFileInZip4(p_zip,
  1475. p_folder.path_join(f).utf8().get_data(),
  1476. &zipfi,
  1477. nullptr,
  1478. 0,
  1479. nullptr,
  1480. 0,
  1481. nullptr,
  1482. Z_DEFLATED,
  1483. Z_DEFAULT_COMPRESSION,
  1484. 0,
  1485. -MAX_WBITS,
  1486. DEF_MEM_LEVEL,
  1487. Z_DEFAULT_STRATEGY,
  1488. nullptr,
  1489. 0,
  1490. 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions
  1491. 1 << 11); // Bit 11 is the language encoding flag. When set, filename and comment fields must be encoded using UTF-8.
  1492. const CharString target_utf8 = da->read_link(f).utf8();
  1493. zipWriteInFileInZip(p_zip, target_utf8.get_data(), target_utf8.size());
  1494. zipCloseFileInZip(p_zip);
  1495. } else if (da->current_is_dir()) {
  1496. zip_folder_recursive(p_zip, p_root_path, p_folder.path_join(f), p_pkg_name);
  1497. } else {
  1498. bool _is_executable = is_executable(dir.path_join(f));
  1499. OS::DateTime dt = OS::get_singleton()->get_datetime();
  1500. zip_fileinfo zipfi;
  1501. zipfi.tmz_date.tm_year = dt.year;
  1502. zipfi.tmz_date.tm_mon = dt.month - 1; // Note: "tm" month range - 0..11, Godot month range - 1..12, https://www.cplusplus.com/reference/ctime/tm/
  1503. zipfi.tmz_date.tm_mday = dt.day;
  1504. zipfi.tmz_date.tm_hour = dt.hour;
  1505. zipfi.tmz_date.tm_min = dt.minute;
  1506. zipfi.tmz_date.tm_sec = dt.second;
  1507. zipfi.dosDate = 0;
  1508. // 0100000: regular file type
  1509. // 0000755: permissions rwxr-xr-x
  1510. // 0000644: permissions rw-r--r--
  1511. uint32_t _mode = (_is_executable ? 0100755 : 0100644);
  1512. zipfi.external_fa = (_mode << 16L) | !(_mode & 0200);
  1513. zipfi.internal_fa = 0;
  1514. zipOpenNewFileInZip4(p_zip,
  1515. p_folder.path_join(f).utf8().get_data(),
  1516. &zipfi,
  1517. nullptr,
  1518. 0,
  1519. nullptr,
  1520. 0,
  1521. nullptr,
  1522. Z_DEFLATED,
  1523. Z_DEFAULT_COMPRESSION,
  1524. 0,
  1525. -MAX_WBITS,
  1526. DEF_MEM_LEVEL,
  1527. Z_DEFAULT_STRATEGY,
  1528. nullptr,
  1529. 0,
  1530. 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions
  1531. 1 << 11); // Bit 11 is the language encoding flag. When set, filename and comment fields must be encoded using UTF-8.
  1532. Ref<FileAccess> fa = FileAccess::open(dir.path_join(f), FileAccess::READ);
  1533. if (fa.is_null()) {
  1534. add_message(EXPORT_MESSAGE_ERROR, TTR("ZIP Creation"), vformat(TTR("Could not open file to read from path \"%s\"."), dir.path_join(f)));
  1535. return;
  1536. }
  1537. const int bufsize = 16384;
  1538. uint8_t buf[bufsize];
  1539. while (true) {
  1540. uint64_t got = fa->get_buffer(buf, bufsize);
  1541. if (got == 0) {
  1542. break;
  1543. }
  1544. zipWriteInFileInZip(p_zip, buf, got);
  1545. }
  1546. zipCloseFileInZip(p_zip);
  1547. }
  1548. f = da->get_next();
  1549. }
  1550. da->list_dir_end();
  1551. }
  1552. Dictionary EditorExportPlatform::_save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, bool p_embed) {
  1553. Vector<SharedObject> so_files;
  1554. int64_t embedded_start = 0;
  1555. int64_t embedded_size = 0;
  1556. Error err_code = save_pack(p_preset, p_debug, p_path, &so_files, nullptr, nullptr, p_embed, &embedded_start, &embedded_size);
  1557. Dictionary ret;
  1558. ret["result"] = err_code;
  1559. if (err_code == OK) {
  1560. Array arr;
  1561. for (const SharedObject &E : so_files) {
  1562. Dictionary so;
  1563. so["path"] = E.path;
  1564. so["tags"] = E.tags;
  1565. so["target_folder"] = E.target;
  1566. arr.push_back(so);
  1567. }
  1568. ret["so_files"] = arr;
  1569. if (p_embed) {
  1570. ret["embedded_start"] = embedded_start;
  1571. ret["embedded_size"] = embedded_size;
  1572. }
  1573. }
  1574. return ret;
  1575. }
  1576. Dictionary EditorExportPlatform::_save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
  1577. Vector<SharedObject> so_files;
  1578. Error err_code = save_zip(p_preset, p_debug, p_path, &so_files);
  1579. Dictionary ret;
  1580. ret["result"] = err_code;
  1581. if (err_code == OK) {
  1582. Array arr;
  1583. for (const SharedObject &E : so_files) {
  1584. Dictionary so;
  1585. so["path"] = E.path;
  1586. so["tags"] = E.tags;
  1587. so["target_folder"] = E.target;
  1588. arr.push_back(so);
  1589. }
  1590. ret["so_files"] = arr;
  1591. }
  1592. return ret;
  1593. }
  1594. Dictionary EditorExportPlatform::_save_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
  1595. Vector<SharedObject> so_files;
  1596. Error err_code = save_pack_patch(p_preset, p_debug, p_path, &so_files);
  1597. Dictionary ret;
  1598. ret["result"] = err_code;
  1599. if (err_code == OK) {
  1600. Array arr;
  1601. for (const SharedObject &E : so_files) {
  1602. Dictionary so;
  1603. so["path"] = E.path;
  1604. so["tags"] = E.tags;
  1605. so["target_folder"] = E.target;
  1606. arr.push_back(so);
  1607. }
  1608. ret["so_files"] = arr;
  1609. }
  1610. return ret;
  1611. }
  1612. Dictionary EditorExportPlatform::_save_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) {
  1613. Vector<SharedObject> so_files;
  1614. Error err_code = save_zip_patch(p_preset, p_debug, p_path, &so_files);
  1615. Dictionary ret;
  1616. ret["result"] = err_code;
  1617. if (err_code == OK) {
  1618. Array arr;
  1619. for (const SharedObject &E : so_files) {
  1620. Dictionary so;
  1621. so["path"] = E.path;
  1622. so["tags"] = E.tags;
  1623. so["target_folder"] = E.target;
  1624. arr.push_back(so);
  1625. }
  1626. ret["so_files"] = arr;
  1627. }
  1628. return ret;
  1629. }
  1630. bool EditorExportPlatform::_store_header(Ref<FileAccess> p_fd, bool p_enc, bool p_sparse, uint64_t &r_file_base_ofs, uint64_t &r_dir_base_ofs) {
  1631. p_fd->store_32(PACK_HEADER_MAGIC);
  1632. p_fd->store_32(PACK_FORMAT_VERSION);
  1633. p_fd->store_32(GODOT_VERSION_MAJOR);
  1634. p_fd->store_32(GODOT_VERSION_MINOR);
  1635. p_fd->store_32(GODOT_VERSION_PATCH);
  1636. uint32_t pack_flags = PACK_REL_FILEBASE;
  1637. if (p_enc) {
  1638. pack_flags |= PACK_DIR_ENCRYPTED;
  1639. }
  1640. if (p_sparse) {
  1641. pack_flags |= PACK_SPARSE_BUNDLE;
  1642. }
  1643. p_fd->store_32(pack_flags); // Flags.
  1644. r_file_base_ofs = p_fd->get_position();
  1645. p_fd->store_64(0); // Files base offset.
  1646. r_dir_base_ofs = p_fd->get_position();
  1647. p_fd->store_64(0); // Directory offset.
  1648. for (int i = 0; i < 16; i++) {
  1649. //reserved
  1650. p_fd->store_32(0);
  1651. }
  1652. return true;
  1653. }
  1654. bool EditorExportPlatform::_encrypt_and_store_directory(Ref<FileAccess> p_fd, PackData &p_pack_data, const Vector<uint8_t> &p_key, uint64_t p_seed, uint64_t p_file_base) {
  1655. Ref<FileAccessEncrypted> fae;
  1656. Ref<FileAccess> fhead = p_fd;
  1657. fhead->store_32(p_pack_data.file_ofs.size()); //amount of files
  1658. if (!p_key.is_empty()) {
  1659. uint64_t seed = p_seed;
  1660. fae.instantiate();
  1661. if (fae.is_null()) {
  1662. return false;
  1663. }
  1664. Vector<uint8_t> iv;
  1665. if (seed != 0) {
  1666. for (int i = 0; i < p_pack_data.file_ofs.size(); i++) {
  1667. for (int64_t j = 0; j < p_pack_data.file_ofs[i].path_utf8.length(); j++) {
  1668. seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].path_utf8.get_data()[j];
  1669. }
  1670. for (int64_t j = 0; j < p_pack_data.file_ofs[i].md5.size(); j++) {
  1671. seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].md5[j];
  1672. }
  1673. seed = ((seed << 5) + seed) ^ (p_pack_data.file_ofs[i].ofs - p_file_base);
  1674. seed = ((seed << 5) + seed) ^ p_pack_data.file_ofs[i].size;
  1675. }
  1676. RandomPCG rng = RandomPCG(seed);
  1677. iv.resize(16);
  1678. for (int i = 0; i < 16; i++) {
  1679. iv.write[i] = rng.rand() % 256;
  1680. }
  1681. }
  1682. Error err = fae->open_and_parse(fhead, p_key, FileAccessEncrypted::MODE_WRITE_AES256, false, iv);
  1683. if (err != OK) {
  1684. return false;
  1685. }
  1686. fhead = fae;
  1687. }
  1688. for (int i = 0; i < p_pack_data.file_ofs.size(); i++) {
  1689. uint32_t string_len = p_pack_data.file_ofs[i].path_utf8.length();
  1690. uint32_t pad = _get_pad(4, string_len);
  1691. fhead->store_32(string_len + pad);
  1692. fhead->store_buffer((const uint8_t *)p_pack_data.file_ofs[i].path_utf8.get_data(), string_len);
  1693. for (uint32_t j = 0; j < pad; j++) {
  1694. fhead->store_8(0);
  1695. }
  1696. fhead->store_64(p_pack_data.file_ofs[i].ofs - p_file_base);
  1697. fhead->store_64(p_pack_data.file_ofs[i].size); // pay attention here, this is where file is
  1698. fhead->store_buffer(p_pack_data.file_ofs[i].md5.ptr(), 16); //also save md5 for file
  1699. uint32_t flags = 0;
  1700. if (p_pack_data.file_ofs[i].encrypted) {
  1701. flags |= PACK_FILE_ENCRYPTED;
  1702. }
  1703. if (p_pack_data.file_ofs[i].removal) {
  1704. flags |= PACK_FILE_REMOVAL;
  1705. }
  1706. fhead->store_32(flags);
  1707. }
  1708. if (fae.is_valid()) {
  1709. fhead.unref();
  1710. fae.unref();
  1711. }
  1712. return true;
  1713. }
  1714. Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, EditorExportSaveFunction p_save_func, EditorExportRemoveFunction p_remove_func, bool p_embed, int64_t *r_embedded_start, int64_t *r_embedded_size) {
  1715. EditorProgress ep("savepack", TTR("Packing"), 102, true);
  1716. if (p_save_func == nullptr) {
  1717. p_save_func = _save_pack_file;
  1718. }
  1719. // Create the temporary export directory if it doesn't exist.
  1720. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1721. da->make_dir_recursive(EditorPaths::get_singleton()->get_temp_dir());
  1722. Ref<FileAccess> f;
  1723. int64_t embed_pos = 0;
  1724. if (!p_embed) {
  1725. // Regular output to separate PCK file.
  1726. f = FileAccess::open(p_path, FileAccess::WRITE);
  1727. if (f.is_null()) {
  1728. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), vformat(TTR("Can't open file for writing at path \"%s\"."), p_path));
  1729. return ERR_CANT_CREATE;
  1730. }
  1731. } else {
  1732. // Append to executable.
  1733. f = FileAccess::open(p_path, FileAccess::READ_WRITE);
  1734. if (f.is_null()) {
  1735. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), vformat(TTR("Can't open file for reading-writing at path \"%s\"."), p_path));
  1736. return ERR_FILE_CANT_OPEN;
  1737. }
  1738. f->seek_end();
  1739. embed_pos = f->get_position();
  1740. if (r_embedded_start) {
  1741. *r_embedded_start = embed_pos;
  1742. }
  1743. // Ensure embedded PCK starts at a 64-bit multiple
  1744. int pad = f->get_position() % 8;
  1745. for (int i = 0; i < pad; i++) {
  1746. f->store_8(0);
  1747. }
  1748. }
  1749. int64_t pck_start_pos = f->get_position();
  1750. uint64_t file_base_ofs = 0;
  1751. uint64_t dir_base_ofs = 0;
  1752. _store_header(f, p_preset->get_enc_pck() && p_preset->get_enc_directory(), false, file_base_ofs, dir_base_ofs);
  1753. // Align for first file.
  1754. int file_padding = _get_pad(PCK_PADDING, f->get_position());
  1755. for (int i = 0; i < file_padding; i++) {
  1756. f->store_8(0);
  1757. }
  1758. uint64_t file_base = f->get_position();
  1759. f->seek(file_base_ofs);
  1760. f->store_64(file_base - pck_start_pos); // Update files base.
  1761. f->seek(file_base);
  1762. // Write files.
  1763. PackData pd;
  1764. pd.ep = &ep;
  1765. pd.f = f;
  1766. pd.so_files = p_so_files;
  1767. pd.path = p_path;
  1768. Error err = export_project_files(p_preset, p_debug, p_save_func, p_remove_func, &pd, _pack_add_shared_object);
  1769. if (err != OK) {
  1770. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Failed to export project files."));
  1771. return err;
  1772. }
  1773. if (pd.file_ofs.is_empty()) {
  1774. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("No files or changes to export."));
  1775. return FAILED;
  1776. }
  1777. pd.file_ofs.sort(); // Do sort, so we can do binary search later (where ?).
  1778. int dir_padding = _get_pad(PCK_PADDING, f->get_position());
  1779. for (int i = 0; i < dir_padding; i++) {
  1780. f->store_8(0);
  1781. }
  1782. // Write directory.
  1783. uint64_t dir_offset = f->get_position();
  1784. f->seek(dir_base_ofs);
  1785. f->store_64(dir_offset - pck_start_pos);
  1786. f->seek(dir_offset);
  1787. Vector<uint8_t> key;
  1788. if (p_preset->get_enc_pck() && p_preset->get_enc_directory()) {
  1789. String script_key = _get_script_encryption_key(p_preset);
  1790. key.resize(32);
  1791. if (script_key.length() == 64) {
  1792. for (int i = 0; i < 32; i++) {
  1793. int v = 0;
  1794. if (i * 2 < script_key.length()) {
  1795. char32_t ct = script_key[i * 2];
  1796. if (is_digit(ct)) {
  1797. ct = ct - '0';
  1798. } else if (ct >= 'a' && ct <= 'f') {
  1799. ct = 10 + ct - 'a';
  1800. }
  1801. v |= ct << 4;
  1802. }
  1803. if (i * 2 + 1 < script_key.length()) {
  1804. char32_t ct = script_key[i * 2 + 1];
  1805. if (is_digit(ct)) {
  1806. ct = ct - '0';
  1807. } else if (ct >= 'a' && ct <= 'f') {
  1808. ct = 10 + ct - 'a';
  1809. }
  1810. v |= ct;
  1811. }
  1812. key.write[i] = v;
  1813. }
  1814. }
  1815. }
  1816. if (!_encrypt_and_store_directory(f, pd, key, p_preset->get_seed(), file_base)) {
  1817. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("Can't create encrypted file."));
  1818. return ERR_CANT_CREATE;
  1819. }
  1820. if (p_embed) {
  1821. // Ensure embedded data ends at a 64-bit multiple.
  1822. uint64_t embed_end = f->get_position() - embed_pos + 12;
  1823. uint64_t pad = embed_end % 8;
  1824. for (uint64_t i = 0; i < pad; i++) {
  1825. f->store_8(0);
  1826. }
  1827. uint64_t pck_size = f->get_position() - pck_start_pos;
  1828. f->store_64(pck_size);
  1829. f->store_32(PACK_HEADER_MAGIC);
  1830. if (r_embedded_size) {
  1831. *r_embedded_size = f->get_position() - embed_pos;
  1832. }
  1833. }
  1834. f->close();
  1835. return OK;
  1836. }
  1837. Error EditorExportPlatform::save_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, bool p_embed, int64_t *r_embedded_start, int64_t *r_embedded_size) {
  1838. return save_pack(p_preset, p_debug, p_path, p_so_files, _save_pack_patch_file, _remove_pack_file, p_embed, r_embedded_start, r_embedded_size);
  1839. }
  1840. Error EditorExportPlatform::save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files, EditorExportSaveFunction p_save_func) {
  1841. EditorProgress ep("savezip", TTR("Packing"), 102, true);
  1842. if (p_save_func == nullptr) {
  1843. p_save_func = _save_zip_file;
  1844. }
  1845. String tmppath = EditorPaths::get_singleton()->get_temp_dir().path_join("packtmp");
  1846. Ref<FileAccess> io_fa;
  1847. zlib_filefunc_def io = zipio_create_io(&io_fa);
  1848. zipFile zip = zipOpen2(tmppath.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io);
  1849. ZipData zd;
  1850. zd.ep = &ep;
  1851. zd.zip = zip;
  1852. zd.so_files = p_so_files;
  1853. Error err = export_project_files(p_preset, p_debug, p_save_func, nullptr, &zd, _zip_add_shared_object);
  1854. if (err != OK && err != ERR_SKIP) {
  1855. add_message(EXPORT_MESSAGE_ERROR, TTR("Save ZIP"), TTR("Failed to export project files."));
  1856. }
  1857. zipClose(zip, nullptr);
  1858. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1859. if (zd.file_count == 0) {
  1860. da->remove(tmppath);
  1861. add_message(EXPORT_MESSAGE_ERROR, TTR("Save PCK"), TTR("No files or changes to export."));
  1862. return FAILED;
  1863. }
  1864. err = da->rename(tmppath, p_path);
  1865. if (err != OK) {
  1866. da->remove(tmppath);
  1867. add_message(EXPORT_MESSAGE_ERROR, TTR("Save ZIP"), vformat(TTR("Failed to move temporary file \"%s\" to \"%s\"."), tmppath, p_path));
  1868. }
  1869. return OK;
  1870. }
  1871. Error EditorExportPlatform::save_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, Vector<SharedObject> *p_so_files) {
  1872. return save_zip(p_preset, p_debug, p_path, p_so_files, _save_zip_patch_file);
  1873. }
  1874. Error EditorExportPlatform::export_pack(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  1875. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1876. return save_pack(p_preset, p_debug, p_path);
  1877. }
  1878. Error EditorExportPlatform::export_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  1879. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1880. return save_zip(p_preset, p_debug, p_path);
  1881. }
  1882. Error EditorExportPlatform::export_pack_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, const Vector<String> &p_patches, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  1883. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1884. Error err = _load_patches(p_patches.is_empty() ? p_preset->get_patches() : p_patches);
  1885. if (err != OK) {
  1886. return err;
  1887. }
  1888. err = save_pack_patch(p_preset, p_debug, p_path);
  1889. _unload_patches();
  1890. return err;
  1891. }
  1892. Error EditorExportPlatform::export_zip_patch(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, const Vector<String> &p_patches, BitField<EditorExportPlatform::DebugFlags> p_flags) {
  1893. ExportNotifier notifier(*this, p_preset, p_debug, p_path, p_flags);
  1894. Error err = _load_patches(p_patches.is_empty() ? p_preset->get_patches() : p_patches);
  1895. if (err != OK) {
  1896. return err;
  1897. }
  1898. err = save_zip_patch(p_preset, p_debug, p_path);
  1899. _unload_patches();
  1900. return err;
  1901. }
  1902. Vector<String> EditorExportPlatform::gen_export_flags(BitField<EditorExportPlatform::DebugFlags> p_flags) {
  1903. Vector<String> ret;
  1904. String host = EDITOR_GET("network/debug/remote_host");
  1905. int remote_port = (int)EDITOR_GET("network/debug/remote_port");
  1906. if (get_name() == "Android" && EditorSettings::get_singleton()->has_setting("export/android/use_wifi_for_remote_debug") && EDITOR_GET("export/android/use_wifi_for_remote_debug")) {
  1907. host = EDITOR_GET("export/android/wifi_remote_debug_host");
  1908. } else if (p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST)) {
  1909. host = "localhost";
  1910. }
  1911. if (p_flags.has_flag(DEBUG_FLAG_DUMB_CLIENT)) {
  1912. int port = EDITOR_GET("filesystem/file_server/port");
  1913. String passwd = EDITOR_GET("filesystem/file_server/password");
  1914. ret.push_back("--remote-fs");
  1915. ret.push_back(host + ":" + itos(port));
  1916. if (!passwd.is_empty()) {
  1917. ret.push_back("--remote-fs-password");
  1918. ret.push_back(passwd);
  1919. }
  1920. }
  1921. if (p_flags.has_flag(DEBUG_FLAG_REMOTE_DEBUG)) {
  1922. ret.push_back("--remote-debug");
  1923. ret.push_back(get_debug_protocol() + host + ":" + String::num_int64(remote_port));
  1924. List<String> breakpoints;
  1925. ScriptEditor::get_singleton()->get_breakpoints(&breakpoints);
  1926. if (breakpoints.size()) {
  1927. ret.push_back("--breakpoints");
  1928. String bpoints;
  1929. for (List<String>::Element *E = breakpoints.front(); E; E = E->next()) {
  1930. bpoints += E->get().replace(" ", "%20");
  1931. if (E->next()) {
  1932. bpoints += ",";
  1933. }
  1934. }
  1935. ret.push_back(bpoints);
  1936. }
  1937. }
  1938. if (p_flags.has_flag(DEBUG_FLAG_VIEW_COLLISIONS)) {
  1939. ret.push_back("--debug-collisions");
  1940. }
  1941. if (p_flags.has_flag(DEBUG_FLAG_VIEW_NAVIGATION)) {
  1942. ret.push_back("--debug-navigation");
  1943. }
  1944. return ret;
  1945. }
  1946. bool EditorExportPlatform::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates, bool p_debug) const {
  1947. bool valid = true;
  1948. String templates_error;
  1949. valid = valid && has_valid_export_configuration(p_preset, templates_error, r_missing_templates, p_debug);
  1950. if (!templates_error.is_empty()) {
  1951. r_error += templates_error;
  1952. }
  1953. String export_plugins_warning;
  1954. Vector<Ref<EditorExportPlugin>> export_plugins = EditorExport::get_singleton()->get_export_plugins();
  1955. for (int i = 0; i < export_plugins.size(); i++) {
  1956. Ref<EditorExportPlatform> export_platform = Ref<EditorExportPlatform>(this);
  1957. if (!export_plugins[i]->supports_platform(export_platform)) {
  1958. continue;
  1959. }
  1960. String plugin_warning = export_plugins.write[i]->_has_valid_export_configuration(export_platform, p_preset);
  1961. if (!plugin_warning.is_empty()) {
  1962. export_plugins_warning += plugin_warning;
  1963. }
  1964. }
  1965. if (!export_plugins_warning.is_empty()) {
  1966. r_error += export_plugins_warning;
  1967. }
  1968. String project_configuration_error;
  1969. valid = valid && has_valid_project_configuration(p_preset, project_configuration_error);
  1970. if (!project_configuration_error.is_empty()) {
  1971. r_error += project_configuration_error;
  1972. }
  1973. return valid;
  1974. }
  1975. Error EditorExportPlatform::ssh_run_on_remote(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, String *r_out, int p_port_fwd) const {
  1976. String ssh_path = EDITOR_GET("export/ssh/ssh");
  1977. if (ssh_path.is_empty()) {
  1978. ssh_path = "ssh";
  1979. }
  1980. List<String> args;
  1981. args.push_back("-p");
  1982. args.push_back(p_port);
  1983. args.push_back("-q");
  1984. args.push_back("-o");
  1985. args.push_back("LogLevel=error");
  1986. args.push_back("-o");
  1987. args.push_back("BatchMode=yes");
  1988. args.push_back("-o");
  1989. args.push_back("StrictHostKeyChecking=no");
  1990. for (const String &E : p_ssh_args) {
  1991. args.push_back(E);
  1992. }
  1993. if (p_port_fwd > 0) {
  1994. args.push_back("-R");
  1995. args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd));
  1996. }
  1997. args.push_back(p_host);
  1998. args.push_back(p_cmd_args);
  1999. String out;
  2000. int exit_code = -1;
  2001. if (OS::get_singleton()->is_stdout_verbose()) {
  2002. OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data());
  2003. for (const String &arg : args) {
  2004. OS::get_singleton()->print(" %s", arg.utf8().get_data());
  2005. }
  2006. OS::get_singleton()->print("\n");
  2007. }
  2008. Error err = OS::get_singleton()->execute(ssh_path, args, &out, &exit_code, true);
  2009. if (out.is_empty()) {
  2010. print_verbose(vformat("Exit code: %d", exit_code));
  2011. } else {
  2012. print_verbose(vformat("Exit code: %d, Output: %s", exit_code, out.replace("\r\n", "\n")));
  2013. }
  2014. if (r_out) {
  2015. *r_out = out.replace("\r\n", "\n").get_slicec('\n', 0);
  2016. }
  2017. if (err != OK) {
  2018. return err;
  2019. } else if (exit_code != 0) {
  2020. if (!out.is_empty()) {
  2021. print_line(out);
  2022. }
  2023. return FAILED;
  2024. }
  2025. return OK;
  2026. }
  2027. Error EditorExportPlatform::ssh_run_on_remote_no_wait(const String &p_host, const String &p_port, const Vector<String> &p_ssh_args, const String &p_cmd_args, OS::ProcessID *r_pid, int p_port_fwd) const {
  2028. String ssh_path = EDITOR_GET("export/ssh/ssh");
  2029. if (ssh_path.is_empty()) {
  2030. ssh_path = "ssh";
  2031. }
  2032. List<String> args;
  2033. args.push_back("-p");
  2034. args.push_back(p_port);
  2035. args.push_back("-q");
  2036. args.push_back("-o");
  2037. args.push_back("LogLevel=error");
  2038. args.push_back("-o");
  2039. args.push_back("BatchMode=yes");
  2040. args.push_back("-o");
  2041. args.push_back("StrictHostKeyChecking=no");
  2042. for (const String &E : p_ssh_args) {
  2043. args.push_back(E);
  2044. }
  2045. if (p_port_fwd > 0) {
  2046. args.push_back("-R");
  2047. args.push_back(vformat("%d:localhost:%d", p_port_fwd, p_port_fwd));
  2048. }
  2049. args.push_back(p_host);
  2050. args.push_back(p_cmd_args);
  2051. if (OS::get_singleton()->is_stdout_verbose()) {
  2052. OS::get_singleton()->print("Executing: %s", ssh_path.utf8().get_data());
  2053. for (const String &arg : args) {
  2054. OS::get_singleton()->print(" %s", arg.utf8().get_data());
  2055. }
  2056. OS::get_singleton()->print("\n");
  2057. }
  2058. return OS::get_singleton()->create_process(ssh_path, args, r_pid);
  2059. }
  2060. Error EditorExportPlatform::ssh_push_to_remote(const String &p_host, const String &p_port, const Vector<String> &p_scp_args, const String &p_src_file, const String &p_dst_file) const {
  2061. String scp_path = EDITOR_GET("export/ssh/scp");
  2062. if (scp_path.is_empty()) {
  2063. scp_path = "scp";
  2064. }
  2065. List<String> args;
  2066. args.push_back("-P");
  2067. args.push_back(p_port);
  2068. args.push_back("-q");
  2069. args.push_back("-o");
  2070. args.push_back("LogLevel=error");
  2071. args.push_back("-o");
  2072. args.push_back("BatchMode=yes");
  2073. args.push_back("-o");
  2074. args.push_back("StrictHostKeyChecking=no");
  2075. for (const String &E : p_scp_args) {
  2076. args.push_back(E);
  2077. }
  2078. args.push_back(p_src_file);
  2079. args.push_back(vformat("%s:%s", p_host, p_dst_file));
  2080. String out;
  2081. int exit_code = -1;
  2082. if (OS::get_singleton()->is_stdout_verbose()) {
  2083. OS::get_singleton()->print("Executing: %s", scp_path.utf8().get_data());
  2084. for (const String &arg : args) {
  2085. OS::get_singleton()->print(" %s", arg.utf8().get_data());
  2086. }
  2087. OS::get_singleton()->print("\n");
  2088. }
  2089. Error err = OS::get_singleton()->execute(scp_path, args, &out, &exit_code, true);
  2090. if (err != OK) {
  2091. return err;
  2092. } else if (exit_code != 0) {
  2093. if (!out.is_empty()) {
  2094. print_line(out);
  2095. }
  2096. return FAILED;
  2097. }
  2098. return OK;
  2099. }
  2100. Array EditorExportPlatform::get_current_presets() const {
  2101. Array ret;
  2102. for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
  2103. Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
  2104. if (ep->get_platform() == this) {
  2105. ret.push_back(ep);
  2106. }
  2107. }
  2108. return ret;
  2109. }
  2110. Variant EditorExportPlatform::get_project_setting(const Ref<EditorExportPreset> &p_preset, const StringName &p_name) {
  2111. if (p_preset.is_valid()) {
  2112. return p_preset->get_project_setting(p_name);
  2113. } else {
  2114. return GLOBAL_GET(p_name);
  2115. }
  2116. }
  2117. void EditorExportPlatform::_bind_methods() {
  2118. ClassDB::bind_method(D_METHOD("get_os_name"), &EditorExportPlatform::get_os_name);
  2119. ClassDB::bind_method(D_METHOD("create_preset"), &EditorExportPlatform::create_preset);
  2120. ClassDB::bind_method(D_METHOD("find_export_template", "template_file_name"), &EditorExportPlatform::_find_export_template);
  2121. ClassDB::bind_method(D_METHOD("get_current_presets"), &EditorExportPlatform::get_current_presets);
  2122. ClassDB::bind_method(D_METHOD("save_pack", "preset", "debug", "path", "embed"), &EditorExportPlatform::_save_pack, DEFVAL(false));
  2123. ClassDB::bind_method(D_METHOD("save_zip", "preset", "debug", "path"), &EditorExportPlatform::_save_zip);
  2124. ClassDB::bind_method(D_METHOD("save_pack_patch", "preset", "debug", "path"), &EditorExportPlatform::_save_pack_patch);
  2125. ClassDB::bind_method(D_METHOD("save_zip_patch", "preset", "debug", "path"), &EditorExportPlatform::_save_zip_patch);
  2126. ClassDB::bind_method(D_METHOD("gen_export_flags", "flags"), &EditorExportPlatform::gen_export_flags);
  2127. ClassDB::bind_method(D_METHOD("export_project_files", "preset", "debug", "save_cb", "shared_cb"), &EditorExportPlatform::_export_project_files, DEFVAL(Callable()));
  2128. ClassDB::bind_method(D_METHOD("export_project", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_project, DEFVAL(0));
  2129. ClassDB::bind_method(D_METHOD("export_pack", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_pack, DEFVAL(0));
  2130. ClassDB::bind_method(D_METHOD("export_zip", "preset", "debug", "path", "flags"), &EditorExportPlatform::export_zip, DEFVAL(0));
  2131. ClassDB::bind_method(D_METHOD("export_pack_patch", "preset", "debug", "path", "patches", "flags"), &EditorExportPlatform::export_pack_patch, DEFVAL(PackedStringArray()), DEFVAL(0));
  2132. ClassDB::bind_method(D_METHOD("export_zip_patch", "preset", "debug", "path", "patches", "flags"), &EditorExportPlatform::export_zip_patch, DEFVAL(PackedStringArray()), DEFVAL(0));
  2133. ClassDB::bind_method(D_METHOD("clear_messages"), &EditorExportPlatform::clear_messages);
  2134. ClassDB::bind_method(D_METHOD("add_message", "type", "category", "message"), &EditorExportPlatform::add_message);
  2135. ClassDB::bind_method(D_METHOD("get_message_count"), &EditorExportPlatform::get_message_count);
  2136. ClassDB::bind_method(D_METHOD("get_message_type", "index"), &EditorExportPlatform::_get_message_type);
  2137. ClassDB::bind_method(D_METHOD("get_message_category", "index"), &EditorExportPlatform::_get_message_category);
  2138. ClassDB::bind_method(D_METHOD("get_message_text", "index"), &EditorExportPlatform::_get_message_text);
  2139. ClassDB::bind_method(D_METHOD("get_worst_message_type"), &EditorExportPlatform::get_worst_message_type);
  2140. ClassDB::bind_method(D_METHOD("ssh_run_on_remote", "host", "port", "ssh_arg", "cmd_args", "output", "port_fwd"), &EditorExportPlatform::_ssh_run_on_remote, DEFVAL(Array()), DEFVAL(-1));
  2141. ClassDB::bind_method(D_METHOD("ssh_run_on_remote_no_wait", "host", "port", "ssh_args", "cmd_args", "port_fwd"), &EditorExportPlatform::_ssh_run_on_remote_no_wait, DEFVAL(-1));
  2142. ClassDB::bind_method(D_METHOD("ssh_push_to_remote", "host", "port", "scp_args", "src_file", "dst_file"), &EditorExportPlatform::ssh_push_to_remote);
  2143. ClassDB::bind_method(D_METHOD("get_internal_export_files", "preset", "debug"), &EditorExportPlatform::get_internal_export_files);
  2144. ClassDB::bind_static_method("EditorExportPlatform", D_METHOD("get_forced_export_files", "preset"), &EditorExportPlatform::get_forced_export_files);
  2145. BIND_ENUM_CONSTANT(EXPORT_MESSAGE_NONE);
  2146. BIND_ENUM_CONSTANT(EXPORT_MESSAGE_INFO);
  2147. BIND_ENUM_CONSTANT(EXPORT_MESSAGE_WARNING);
  2148. BIND_ENUM_CONSTANT(EXPORT_MESSAGE_ERROR);
  2149. BIND_BITFIELD_FLAG(DEBUG_FLAG_DUMB_CLIENT);
  2150. BIND_BITFIELD_FLAG(DEBUG_FLAG_REMOTE_DEBUG);
  2151. BIND_BITFIELD_FLAG(DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST);
  2152. BIND_BITFIELD_FLAG(DEBUG_FLAG_VIEW_COLLISIONS);
  2153. BIND_BITFIELD_FLAG(DEBUG_FLAG_VIEW_NAVIGATION);
  2154. }