editor_export_platform.cpp 83 KB

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