editor_export_platform.cpp 82 KB

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