editor_export_platform.cpp 83 KB

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