Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

web: Fix files_dropped implementation

Fabio Alessandrellidba1eec772ed
diff --git a/doc/classes/DisplayServer.xml b/doc/classes/DisplayServer.xml
index 8de0cf7234e..bdec2b5113b 100644
--- a/doc/classes/DisplayServer.xml
+++ b/doc/classes/DisplayServer.xml
@@ -2428,6 +2428,7 @@
Sets the [param callback] that should be called when files are dropped from the operating system's file manager to the window specified by [param window_id]. [param callback] should take one [PackedStringArray] argument, which is the list of dropped files.
[b]Warning:[/b] Advanced users only! Adding such a callback to a [Window] node will override its default implementation, which can introduce bugs.
[b]Note:[/b] This method is implemented on Windows, macOS, Linux (X11/Wayland), and Web.
+ [b]Note:[/b] On the web platform, the files are dropped to a temporary folder and will be removed automatically after the callback.
</description>
</method>
<method name="window_set_exclusive">
diff --git a/doc/classes/Window.xml b/doc/classes/Window.xml
index 967cbdc78ef..f41cabc5d26 100644
--- a/doc/classes/Window.xml
+++ b/doc/classes/Window.xml
@@ -881,6 +881,7 @@
print(files)
[/codeblock]
[b]Note:[/b] This signal only works with native windows, i.e. the main window and [Window]-derived nodes when [member Viewport.gui_embed_subwindows] is disabled in the main viewport.
+ [b]Note:[/b] On the web platform, the files are dropped to a temporary folder and will be removed automatically after the signal is emitted. Process them immediately, or move them to a separate possibly persistent location (e.g. [code]user://[/code]) to preserve them.
</description>
</signal>
<signal name="focus_entered">
diff --git a/editor/project_manager/project_manager.cpp b/editor/project_manager/project_manager.cpp
index aa137b9c302..b3537271ecb 100644
--- a/editor/project_manager/project_manager.cpp
+++ b/editor/project_manager/project_manager.cpp
@@ -1324,6 +1324,84 @@ void ProjectManager::shortcut_input(const Ref<InputEvent> &p_ev) {
}
void ProjectManager::_files_dropped(PackedStringArray p_files) {
+#ifdef WEB_ENABLED
+ if (p_files.size() == 1 && p_files[0].ends_with(".zip")) {
+ const String &file = p_files[0];
+ Error err = DirAccess::rename_absolute(file, "/tmp/install.zip"); // Cleaned up at shutdown.
+ if (err) {
+ _show_error(vformat("Error importing the ZIP file: %d", err));
+ return;
+ }
+ _install_project("/tmp/install.zip", file.get_file().get_basename().capitalize());
+ return;
+ }
+
+ Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ PackedStringArray errors;
+ PackedStringArray folders;
+ const String home = "/home/web_user";
+ for (const String &folder : p_files) {
+ if (!da->dir_exists(folder)) {
+ if (folder.ends_with(".zip")) {
+ errors.push_back("Importing multiple ZIP projects is not supported.");
+ } else {
+ errors.push_back(vformat("Unrecognized file: %s", folder.get_file()));
+ }
+ continue;
+ }
+ const String &name = folder.get_file();
+ const String base = folder.get_base_dir();
+ const String dest = home + "/" + name;
+ if (da->dir_exists(dest)) {
+ errors.push_back(vformat("Cannot import folder '%s', path already exists.", name));
+ continue;
+ }
+ // Move dropped folder to the home folder destination
+ List<String> dirs;
+ dirs.push_back(name);
+ Error err = OK;
+ while (dirs.size()) {
+ const String cur = dirs.front()->get();
+ dirs.pop_front();
+ err = DirAccess::make_dir_absolute(home + "/" + cur);
+ if (err != OK) {
+ errors.push_back(vformat("Failed to create folder: '%s/%s'", home, cur));
+ break;
+ }
+ for (const String &F : DirAccess::get_files_at(base + "/" + cur)) {
+ const String src = base + "/" + cur + "/" + F;
+ const String dst = home + "/" + cur + "/" + F;
+ err = DirAccess::rename_absolute(src, dst);
+ if (err != OK) {
+ errors.push_back(vformat("Failed to move file: '%s' to '%s'", src, dst));
+ break;
+ }
+ }
+ if (err != OK) {
+ break;
+ }
+ for (const String &D : DirAccess::get_directories_at(base + "/" + cur)) {
+ dirs.push_back(cur + "/" + D);
+ }
+ }
+ if (err != OK) {
+ // Try removing the import destination.
+ Ref<DirAccess> dab = DirAccess::open(dest);
+ if (dab.is_valid()) {
+ dab->erase_contents_recursive();
+ dab.unref();
+ DirAccess::remove_absolute(dest);
+ }
+ } else {
+ folders.push_back(dest);
+ }
+ }
+
+ if (errors.size()) {
+ _show_error(String("\n").join(errors));
+ }
+ project_list->find_projects_multiple(folders);
+#else
// TODO: Support installing multiple ZIPs at the same time?
if (p_files.size() == 1 && p_files[0].ends_with(".zip")) {
const String &file = p_files[0];
@@ -1344,6 +1422,7 @@ void ProjectManager::_files_dropped(PackedStringArray p_files) {
folders.push_back(E);
}
project_list->find_projects_multiple(folders);
+#endif // WEB_ENABLED
}
void ProjectManager::_titlebar_resized() {
diff --git a/platform/web/display_server_web.cpp b/platform/web/display_server_web.cpp
index 496bf898268..3a5a8c38784 100644
--- a/platform/web/display_server_web.cpp
+++ b/platform/web/display_server_web.cpp
@@ -37,6 +37,7 @@
#include "core/config/project_settings.h"
#include "core/input/input.h"
#include "core/input/input_event.h"
+#include "core/io/dir_access.h"
#include "core/os/main_loop.h"
#include "core/os/os.h"
#include "servers/display/native_menu.h"
@@ -113,21 +114,26 @@ void DisplayServerWeb::drop_files_js_callback(const char **p_filev, int p_filec)
}
void DisplayServerWeb::_drop_files_js_callback(const Vector<String> &p_files) {
+ // Dropped files on the web are copied in memory, into a temporary folder.
+ // The first element from the callback is expected to be the temporary folder.
+ ERR_FAIL_COND(p_files.is_empty());
DisplayServerWeb *ds = get_singleton();
- if (!ds) {
- ERR_FAIL_MSG("Unable to drop files because the DisplayServer is not active");
- }
- if (!ds->drop_files_callback.is_valid()) {
- return;
- }
- Variant v_files = p_files;
- const Variant *v_args[1] = { &v_files };
- Variant ret;
- Callable::CallError ce;
- ds->drop_files_callback.callp((const Variant **)&v_args, 1, ret, ce);
- if (ce.error != Callable::CallError::CALL_OK) {
- ERR_PRINT(vformat("Failed to execute drop files callback: %s.", Variant::get_callable_error_text(ds->drop_files_callback, v_args, 1, ce)));
+ if (likely(ds && ds->drop_files_callback.is_valid())) {
+ Variant v_files = p_files.slice(1); // Without the temporary folder name.
+ const Variant *v_args[1] = { &v_files };
+ Variant ret;
+ Callable::CallError ce;
+ ds->drop_files_callback.callp((const Variant **)&v_args, 1, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_PRINT(vformat("Failed to execute drop files callback: %s.", Variant::get_callable_error_text(ds->drop_files_callback, v_args, 1, ce)));
+ }
}
+ // Remove the temporary folder recursively.
+ Ref<DirAccess> dir = DirAccess::open(p_files[0]);
+ ERR_FAIL_COND(dir.is_null());
+ dir->erase_contents_recursive();
+ dir.unref();
+ DirAccess::remove_absolute(p_files[0]);
}
// Web quit request callback.
diff --git a/platform/web/js/engine/config.js b/platform/web/js/engine/config.js
index 14b81ed58cf..b800a948fde 100644
--- a/platform/web/js/engine/config.js
+++ b/platform/web/js/engine/config.js
@@ -118,11 +118,6 @@ const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-
* @type {Array.<string>}
*/
persistentPaths: ['/userfs'],
- /**
- * @ignore
- * @type {boolean}
- */
- persistentDrops: false,
/**
* @ignore
* @type {Array.<string>}
@@ -270,7 +265,6 @@ const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-
this.locale = parse('locale', this.locale);
this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
this.persistentPaths = parse('persistentPaths', this.persistentPaths);
- this.persistentDrops = parse('persistentDrops', this.persistentDrops);
this.experimentalVK = parse('experimentalVK', this.experimentalVK);
this.focusCanvas = parse('focusCanvas', this.focusCanvas);
this.serviceWorker = parse('serviceWorker', this.serviceWorker);
@@ -369,7 +363,6 @@ const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-
'canvas': this.canvas,
'canvasResizePolicy': this.canvasResizePolicy,
'locale': locale,
- 'persistentDrops': this.persistentDrops,
'virtualKeyboard': this.experimentalVK,
'godotPoolSize': this.godotPoolSize,
'focusCanvas': this.focusCanvas,
diff --git a/platform/web/js/libs/library_godot_input.js b/platform/web/js/libs/library_godot_input.js
index fce4141a0f3..cc7439be421 100644
--- a/platform/web/js/libs/library_godot_input.js
+++ b/platform/web/js/libs/library_godot_input.js
@@ -314,75 +314,84 @@ mergeInto(LibraryManager.library, GodotInputGamepads);
const GodotInputDragDrop = {
$GodotInputDragDrop__deps: ['$FS', '$GodotFS'],
$GodotInputDragDrop: {
- promises: [],
- pending_files: [],
-
- add_entry: function (entry) {
- if (entry.isDirectory) {
- GodotInputDragDrop.add_dir(entry);
- } else if (entry.isFile) {
- GodotInputDragDrop.add_file(entry);
- } else {
- GodotRuntime.error('Unrecognized entry...', entry);
- }
- },
-
- add_dir: function (entry) {
- GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
- const reader = entry.createReader();
- reader.readEntries(function (entries) {
- for (let i = 0; i < entries.length; i++) {
- GodotInputDragDrop.add_entry(entries[i]);
- }
- resolve();
- });
- }));
- },
-
- add_file: function (entry) {
- GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
- entry.file(function (file) {
- const reader = new FileReader();
- reader.onload = function () {
- const f = {
- 'path': file.relativePath || file.webkitRelativePath,
- 'name': file.name,
- 'type': file.type,
- 'size': file.size,
- 'data': reader.result,
- };
- if (!f['path']) {
- f['path'] = f['name'];
+ MAX_DROP_SIZE: 200 * 1024 * 1024,
+ create_drop: function () {
+ const drop = {};
+ drop.pending = [];
+ drop.dirs = [];
+ drop.files = [];
+ drop.size = 0;
+ drop.add_entry = function (entry, path) {
+ if (entry.isDirectory) {
+ drop.add_dir(entry, path);
+ } else if (entry.isFile) {
+ drop.add_file(entry, path);
+ } else {
+ GodotRuntime.error('Unrecognized entry...', entry);
+ }
+ };
+ drop.add_dir = function (entry, path) {
+ const next = `${path}/${entry.name}`;
+ drop.pending.push(() => new Promise(function (resolve, reject) {
+ const reader = entry.createReader();
+ reader.readEntries(function (entries) {
+ drop.dirs.push(next);
+ for (let i = 0; i < entries.length; i++) {
+ drop.add_entry(entries[i], next);
}
- GodotInputDragDrop.pending_files.push(f);
resolve();
- };
- reader.onerror = function () {
- GodotRuntime.print('Error reading file');
- reject();
- };
- reader.readAsArrayBuffer(file);
- }, function (err) {
- GodotRuntime.print('Error!');
- reject();
- });
- }));
+ });
+ }));
+ };
+ drop.add_file = function (entry, path) {
+ drop.pending.push(() => new Promise(function (resolve, reject) {
+ entry.file(function (file) {
+ drop.size += file.size ?? 0;
+ if (drop.size > GodotInputDragDrop.MAX_DROP_SIZE) {
+ reject(new Error('Drop size limit reached.'));
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = function () {
+ const f = {
+ 'path': `${path}/${file.name}`,
+ 'name': file.name,
+ 'type': file.type,
+ 'size': file.size,
+ 'data': reader.result,
+ };
+ drop.files.push(f);
+ resolve();
+ };
+ reader.onerror = function (err) {
+ reject(err);
+ };
+ reader.readAsArrayBuffer(file);
+ }, function (err) {
+ reject(err);
+ });
+ }));
+ };
+ return drop;
},
- process: function (resolve, reject) {
- if (GodotInputDragDrop.promises.length === 0) {
- resolve();
- return;
+ process: function (drop) {
+ if (drop.pending.length === 0) {
+ return Promise.resolve();
}
- GodotInputDragDrop.promises.pop().then(function () {
- setTimeout(function () {
- GodotInputDragDrop.process(resolve, reject);
- }, 0);
+ // Execute pending operations.
+ return drop.pending.splice(0).reduce(function (a, b) {
+ return a.then(b);
+ }, Promise.resolve()).then(function (result) {
+ // Will check if new operations have been queued or resolve.
+ return GodotInputDragDrop.process(drop);
});
},
_process_event: function (ev, callback) {
ev.preventDefault();
+ const ROOT = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}`;
+ const drop = GodotInputDragDrop.create_drop();
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (let i = 0; i < ev.dataTransfer.items.length; i++) {
@@ -394,76 +403,34 @@ const GodotInputDragDrop = {
entry = item.webkitGetAsEntry();
}
if (entry) {
- GodotInputDragDrop.add_entry(entry);
+ drop.add_entry(entry, ROOT);
}
}
} else {
GodotRuntime.error('File upload not supported');
}
- new Promise(GodotInputDragDrop.process).then(function () {
- const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
- const drops = [];
- const files = [];
- FS.mkdir(DROP.slice(0, -1)); // Without trailing slash
- GodotInputDragDrop.pending_files.forEach((elem) => {
- const path = elem['path'];
- GodotFS.copy_to_fs(DROP + path, elem['data']);
- let idx = path.indexOf('/');
+ GodotInputDragDrop.process(drop).then(function () {
+ const out = [ROOT];
+ drop.dirs.forEach((path) => {
+ FS.mkdirTree(path);
+ // Add dirs to the string array if in the drop root.
+ const idx = path.indexOf('/', ROOT.length + 1);
if (idx === -1) {
- // Root file
- drops.push(DROP + path);
- } else {
- // Subdir
- const sub = path.substr(0, idx);
- idx = sub.indexOf('/');
- if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
- drops.push(DROP + sub);
- }
+ out.push(path);
}
- files.push(DROP + path);
});
- GodotInputDragDrop.promises = [];
- GodotInputDragDrop.pending_files = [];
- callback(drops);
- if (GodotConfig.persistent_drops) {
- // Delay removal at exit.
- GodotOS.atexit(function (resolve, reject) {
- GodotInputDragDrop.remove_drop(files, DROP);
- resolve();
- });
- } else {
- GodotInputDragDrop.remove_drop(files, DROP);
- }
- });
- },
-
- remove_drop: function (files, drop_path) {
- const dirs = [drop_path.substr(0, drop_path.length - 1)];
- // Remove temporary files
- files.forEach(function (file) {
- FS.unlink(file);
- let dir = file.replace(drop_path, '');
- let idx = dir.lastIndexOf('/');
- while (idx > 0) {
- dir = dir.substr(0, idx);
- if (dirs.indexOf(drop_path + dir) === -1) {
- dirs.push(drop_path + dir);
+ drop.files.forEach((elem) => {
+ const path = elem['path'];
+ GodotFS.copy_to_fs(path, elem['data']);
+ // Add file to the string array if in the drop root.
+ const idx = path.indexOf('/', ROOT.length + 1);
+ if (idx === -1) {
+ out.push(path);
}
- idx = dir.lastIndexOf('/');
- }
- });
- // Remove dirs.
- dirs.sort(function (a, b) {
- const al = (a.match(/\//g) || []).length;
- const bl = (b.match(/\//g) || []).length;
- if (al > bl) {
- return -1;
- } else if (al < bl) {
- return 1;
- }
- return 0;
- }).forEach(function (dir) {
- FS.rmdir(dir);
+ });
+ callback(out);
+ }).catch(function (err) {
+ GodotRuntime.error(err);
});
},
diff --git a/platform/web/js/libs/library_godot_os.js b/platform/web/js/libs/library_godot_os.js
index a147554cb1a..9898ea9fa44 100644
--- a/platform/web/js/libs/library_godot_os.js
+++ b/platform/web/js/libs/library_godot_os.js
@@ -60,7 +60,6 @@ const GodotConfig = {
locale: 'en',
canvas_resize_policy: 2, // Adaptive
virtual_keyboard: false,
- persistent_drops: false,
godot_pool_size: 4,
debug_port: null,
on_execute: null,
@@ -71,7 +70,6 @@ const GodotConfig = {
GodotConfig.canvas = p_opts['canvas'];
GodotConfig.locale = p_opts['locale'] || GodotConfig.locale;
GodotConfig.virtual_keyboard = p_opts['virtualKeyboard'];
- GodotConfig.persistent_drops = !!p_opts['persistentDrops'];
GodotConfig.godot_pool_size = p_opts['godotPoolSize'];
GodotConfig.debug_port = p_opts['debugPort'];
GodotConfig.on_execute = p_opts['onExecute'];
@@ -90,7 +88,6 @@ const GodotConfig = {
GodotConfig.locale = 'en';
GodotConfig.canvas_resize_policy = 2;
GodotConfig.virtual_keyboard = false;
- GodotConfig.persistent_drops = false;
GodotConfig.debug_port = null;
GodotConfig.on_execute = null;
GodotConfig.on_exit = null;