diff --git a/drag-drop-main.js b/drag-drop-main.js new file mode 100644 index 0000000..2dc802d --- /dev/null +++ b/drag-drop-main.js @@ -0,0 +1,55 @@ +var electron = require('electron'); +var app = electron.app; +var ipc = electron.ipcMain; + +var argv = sliceArgv(process.argv); +var win; +function init(window) { + if (win) { + console.error("can't initiliaze drag-and-drop multiple times"); + return; + } + win = window; + + ipc.once('ipcReady', function () { + app.ipcReady = true; + processArgv(argv); + }); +} + +app.on('open-file', onOpen); +app.on('open-url', onOpen); +function onOpen(e, filename) { + e.preventDefault(); + + if (app.ipcReady) { + processArgv([ filename ]); + } else { + argv.push(filename); + } +} +function sliceArgv(argv) { + var count = 1; + // We need to determine if we were run using electron or as a system installed app. + if (argv[0].search('electron') >= 0) { + count += 1; + } + return argv.slice(count); +} + +function processArgv(argv) { + var files = []; + argv.forEach(function(arg) { + if (arg.substr(0 ,2) == '--') { + console.log('received argument', arg); + } else { + files.push(arg); + } + }); + + if (files.length > 0) { + win.webContents.send('files', files); + } +} + +module.exports.init = init; diff --git a/drag-drop-render.js b/drag-drop-render.js new file mode 100644 index 0000000..642ee05 --- /dev/null +++ b/drag-drop-render.js @@ -0,0 +1,43 @@ +var electron = require('electron'); +var ipc = electron.ipcRenderer; + +function handleFiles(files) { + if (!Array.isArray(files)) { + files = [ files ]; + } + + document.body.appendChild(document.createElement('br')); + files.forEach(function (name) { + var div = document.createElement('div'); + div.innerHTML = name; + document.body.appendChild(div); + }); +} + +// Need to prevent default for some of the document drag-and-drop events to be able +// to properly get events. This doesn't explain why I need to preventDefault on all +// the events (or whichever combination is actually needed - haven't really spent +// time trying different combinations), but it is what put me down this path. +// https://discuss.atom.io/t/possible-to-get-local-filesystem-path-from-drag-and-drop-file/28858 +function preventDefault(ev) { + ev.preventDefault(); +} +var events = ['drag','dragend','dragenter','dragexit','dragleave','dragover','dragstart','drop']; +events.forEach(function (event) { + document.addEventListener(event, preventDefault); +}); + +document.body.addEventListener('drop', function (ev) { + var files = Array.prototype.map.call(ev.dataTransfer.files, function (file) { + return file.path; + }); + + if (files.length > 0) { + handleFiles(files); + } +}); + +ipc.on('files', function (e, files) { + handleFiles(files); +}); +ipc.send('ipcReady'); diff --git a/index.html b/index.html index ef06b98..3b96b30 100644 --- a/index.html +++ b/index.html @@ -4,11 +4,14 @@
-