فهرست منبع

Add Application class in app.js

Lutz Roeder 8 سال پیش
والد
کامیت
b1f42f249b
2فایلهای تغییر یافته به همراه301 افزوده شده و 299 حذف شده
  1. 293 291
      src/app.js
  2. 8 8
      src/view-electron.js

+ 293 - 291
src/app.js

@@ -8,352 +8,354 @@ const path = require('path');
 const process = require('process');
 const url = require('url');
 
-electron.app.setAppUserModelId('com.lutzroeder.netron');
+class Application {
 
-var views = [];
+    constructor() {
+        this._views = [];
+        this._openFileQueue = [];
+        this._configuration = null;
 
-const quit = electron.app.makeSingleInstance(() => {
-    if (views.length > 0) {
-        var view = views[0];
-        if (view && view.window) { 
-            if (view.window.isMinimized()) {
-                view.window.restore();
-            }
-            view.window.show();
+        electron.app.setAppUserModelId('com.lutzroeder.netron');
+
+        var application = this;
+        if (electron.app.makeSingleInstance(() => { application.restoreWindow(); })) {
+            electron.app.quit();
         }
-    }
-});
 
-if (quit) {
-    electron.app.quit();
-}
+        electron.ipcMain.on('open-file-dialog', (e, data) => {
+            this.openFileDialog();
+        });
+
+        electron.ipcMain.on('drop-file', (e, data) => {
+            application.dropFile(data.file, data.windowId);
+        });
 
-function openFileDialog() {
-    var showOpenDialogOptions = { 
-        properties: [ 'openFile' ], 
-        filters: [
-            { name: 'ONNX Model', extensions: [ 'onnx', 'pb' ] },
-            { name: 'TensorFlow Saved Model', extensions: [ 'saved_model.pb' ] },
-            { name: 'TensorFlow Graph', extensions: [ 'pb', 'meta' ] },
-            { name: 'TensorFlow Lite Model', extensions: [ 'tflite' ] },
-            { name: 'Keras Model', extension: [ 'json', 'keras', 'h5' ] }
-        ]
-    };
-    electron.dialog.showOpenDialog(showOpenDialogOptions, (selectedFiles) => {
-        if (selectedFiles) {
-            selectedFiles.forEach((selectedFile) => {
-                openFile(selectedFile);
+        electron.app.on('will-finish-launching', () => {
+            electron.app.on('open-file', (e, path) => {
+                application.openFile(path);
             });
-        }
-    });
-}
+        });
+
+        electron.app.on('ready', () => {
+            application.ready();
+        });
 
-function openFile(file) {
-    if (file && file.length > 0 && fs.existsSync(file))
-    {
-        // find existing view for this file
-        var view = views.find(view => view.path && view.path == file);
-        // find empty welcome window
-        if (view == null) {
-            view = views.find(view => !view.path || view.path.length == 0);
+        electron.app.on('window-all-closed', () => {
+            if (process.platform !== 'darwin') {
+                electron.app.quit();
+            }
+        });
+
+        electron.app.on('will-quit', () => {
+            application.saveConfiguration();
+        });
+
+        this.update();
+    }
+
+    ready() {
+        this.loadConfiguration();
+        this.updateMenu();
+        while (this._openFileQueue.length > 0) {
+            var file = this._openFileQueue.shift();
+            this.openFile(file);
         }
-        // create new window
-        if (view == null) {
-            view = openView();
+        this._openFileQueue = null;
+        if (this._views.length == 0) {
+            this.openView();
         }
-        loadFile(file, view);
     }
-}
 
-function loadFile(file, view) {
-    configuration.recents = configuration.recents.filter(recent => file != recent.path);
-    var title = minimizePath(file);
-    if (process.platform !== 'darwin') {
-        title = file + ' - ' + electron.app.getName();
-    }
-    var window = view.window;
-    window.setTitle(title);
-    view.path = file;
-    if (view.ready) {
-        window.webContents.send("open-file", { file: file });
-    }
-    else {
-        window.webContents.on('dom-ready', () => {
-            window.webContents.send("open-file", { file: file });
-        });
-        var location = url.format({
-            pathname: path.join(__dirname, 'view-electron.html'),
-            protocol: 'file:',
-            slashes: true
+    openFileDialog() {
+        var showOpenDialogOptions = { 
+            properties: [ 'openFile' ], 
+            filters: [
+                { name: 'ONNX Model', extensions: [ 'onnx', 'pb' ] },
+                { name: 'TensorFlow Saved Model', extensions: [ 'saved_model.pb' ] },
+                { name: 'TensorFlow Graph', extensions: [ 'pb', 'meta' ] },
+                { name: 'TensorFlow Lite Model', extensions: [ 'tflite' ] },
+                { name: 'Keras Model', extension: [ 'json', 'keras', 'h5' ] }
+            ]
+        };
+        electron.dialog.showOpenDialog(showOpenDialogOptions, (selectedFiles) => {
+            if (selectedFiles) {
+                selectedFiles.forEach((selectedFile) => {
+                    this.openFile(selectedFile);
+                });
+            }
         });
-        window.loadURL(location);
-    }
-    configuration.recents.unshift({ path: file });
-    if (configuration.recents.length > 10) {
-        configuration.recents.splice(10);
     }
-    updateMenu();
-}
 
-electron.ipcMain.on('open-file-dialog', (e, data) => {
-    openFileDialog();
-});
-
-electron.ipcMain.on('open-file', (e, data) => {
-    var file = data.file;
-    if (file) { 
-        var view = null;
-        if (data.window) {
-            var window = electron.BrowserWindow.fromId(data.window);
-            if (window) {
-                view = views.find(view => view.window == window);
+    openFile(file) {
+        if (this._openFileQueue) {
+            this._openFileQueue.push(path);
+            return;
+        }
+        if (file && file.length > 0 && fs.existsSync(file))
+        {
+            // find existing view for this file
+            var view = this._views.find(view => view.path && view.path == file);
+            // find empty welcome window
+            if (view == null) {
+                view = this._views.find(view => !view.path || view.path.length == 0);
+            }
+            // create new window
+            if (view == null) {
+                view = this.openView();
             }
+            this.loadFile(file, view);
+        }
+    }
+
+    loadFile(file, view) {
+        this._configuration.recents = this._configuration.recents.filter(recent => file != recent.path);
+        var title = Application.minimizePath(file);
+        if (process.platform !== 'darwin') {
+            title = file + ' - ' + electron.app.getName();
         }
-        if (view) {
-            loadFile(file, view);
+        var window = view.window;
+        window.setTitle(title);
+        view.path = file;
+        if (view.ready) {
+            window.webContents.send("open-file", { file: file });
         }
         else {
-            openFile(file);
+            window.webContents.on('dom-ready', () => {
+                window.webContents.send("open-file", { file: file });
+            });
+            var location = url.format({
+                pathname: path.join(__dirname, 'view-electron.html'),
+                protocol: 'file:',
+                slashes: true
+            });
+            window.loadURL(location);
         }
-    }
-});
-
-Array.prototype.remove = function(obj) {
-    var index = this.length;
-    while (index--) {
-        if (this[index] == obj) {
-            this.splice(index, 1);
+        this._configuration.recents.unshift({ path: file });
+        if (this._configuration.recents.length > 10) {
+            this._configuration.recents.splice(10);
         }
+        this.updateMenu();
     }
-};
 
-function openView() {
-    const title = electron.app.getName();
-    const size = electron.screen.getPrimaryDisplay().workAreaSize;
-    if (size.width > 1024) {
-        size.width = 1024;
-    }
-    if (size.height > 768) {
-        size.height = 768;
-    }
-    var window = new electron.BrowserWindow({ 
-        title: title,
-        // backgroundColor: '#f0fcfe',
-        backgroundColor: '#eeeeee',
-        minWidth: 600,
-        minHeight: 400,
-        width: size.width,
-        height: size.height,
-        icon: electron.nativeImage.createFromPath(path.join(__dirname, 'icon.png'))
-    });
-    
-    window.on('closed', function () {
-        for (var i = views.length - 1; i >= 0; i--) {
-            if (views[i].window == window) {
-                views.splice(i, 1);
-            }   
+    dropFile(file, windowId) {
+        if (file) { 
+            var view = null;
+            if (windowId) {
+                var window = electron.BrowserWindow.fromId(windowId);
+                if (window) {
+                    view = this._views.find(view => view.window == window);
+                }
+            }
+            if (view) {
+                this.loadFile(file, view);
+            }
+            else {
+                this.openFile(file);
+            }
         }
-    });
-    var view = { 
-        window: window,
-        ready: false
-    };
-    window.webContents.on('dom-ready', function() {
-        view.ready = true;
-    });        
-    window.loadURL(url.format({
-        pathname: path.join(__dirname, 'view-electron.html'),
-        protocol: 'file:',
-        slashes: true
-    }));
-    views.push(view);
-    return view;
-}
-
-update();
+    }
 
-electron.app.on('will-finish-launching', () => {
-    electron.app.on('open-file', (e, path) => {
-        if (openFileQueue) {
-            openFileQueue.push(path);
+    openView() {
+        const title = electron.app.getName();
+        const size = electron.screen.getPrimaryDisplay().workAreaSize;
+        if (size.width > 1024) {
+            size.width = 1024;
         }
-        else {
-            openFile(path);
+        if (size.height > 768) {
+            size.height = 768;
         }
-    });
-});
-
-var openFileQueue = [];
-
-electron.app.on('ready', () => {
-    loadConfiguration();
-    updateMenu();
-    
-    while (openFileQueue.length > 0) {
-        var file = openFileQueue.shift();
-        openFile(file);
+        var window = new electron.BrowserWindow({ 
+            title: title,
+            backgroundColor: '#eeeeee',
+            minWidth: 600,
+            minHeight: 400,
+            width: size.width,
+            height: size.height,
+            icon: electron.nativeImage.createFromPath(path.join(__dirname, 'icon.png'))
+        });
+        var application = this;
+        window.on('closed', function () {
+            application.closeWindow(this);
+        });
+        var view = { 
+            window: window,
+            ready: false
+        };
+        window.webContents.on('dom-ready', function() {
+            view.ready = true;
+        });
+        var location = url.format({ pathname: path.join(__dirname, 'view-electron.html'), protocol: 'file:', slashes: true });
+        window.loadURL(location);
+        this._views.push(view);
+        return view;
     }
-    openFileQueue = null;
 
-    if (views.length == 0) {
-        openView();
+    closeWindow(window) {
+        for (var i = this._views.length - 1; i >= 0; i--) {
+            if (this._views[i].window == window) {
+                this._views.splice(i, 1);
+            }   
+        }
     }
-});
 
-electron.app.on('window-all-closed', () => {
-    if (process.platform !== 'darwin') {
-        electron.app.quit();
-    }
-});
-
-electron.app.on('will-quit', () => {
-    saveConfiguration();
-});
-
-function update() {
-    var isDev = ('ELECTRON_IS_DEV' in process.env) ?
-        (parseInt(process.env.ELECTRON_IS_DEV, 10) === 1) :
-        (process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath));
-    if (!isDev) {
-        updater.autoUpdater.checkForUpdatesAndNotify();
+    restoreWindow() {
+        if (this._views.length > 0) {
+            var view = this._views[0];
+            if (view && view.window) { 
+                if (view.window.isMinimized()) {
+                    view.window.restore();
+                }
+                view.window.show();
+            }
+        }
     }
-}
 
-var configuration = null;
+    update() {
+        var isDev = ('ELECTRON_IS_DEV' in process.env) ?
+            (parseInt(process.env.ELECTRON_IS_DEV, 10) === 1) :
+            (process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath));
+        if (!isDev) {
+            updater.autoUpdater.checkForUpdatesAndNotify();
+        }
+    }
 
-function loadConfiguration() {
-    var dir = electron.app.getPath('userData');
-    if (dir && dir.length > 0) {
-        var file = path.join(dir, 'configuration.json'); 
-        if (fs.existsSync(file)) {
-            var data = fs.readFileSync(file);
-            if (data) {
-                configuration = JSON.parse(data);
+    loadConfiguration() {
+        var dir = electron.app.getPath('userData');
+        if (dir && dir.length > 0) {
+            var file = path.join(dir, 'configuration.json'); 
+            if (fs.existsSync(file)) {
+                var data = fs.readFileSync(file);
+                if (data) {
+                    this._configuration = JSON.parse(data);
+                }
             }
         }
+        if (!this._configuration) {
+            this._configuration = {
+                'recents': []
+            };
+        }
     }
-    if (!configuration) {
-        configuration = {
-            'recents': []
-        };
-    }
-}
 
-function saveConfiguration() {
-    if (configuration) {
-        var data = JSON.stringify(configuration);
-        if (data) {
-            var dir = electron.app.getPath('userData');
-            if (dir && dir.length > 0) {
-                var file = path.join(dir, 'configuration.json'); 
-                fs.writeFileSync(file, data);          
+    saveConfiguration() {
+        if (this._configuration) {
+            var data = JSON.stringify(this._configuration);
+            if (data) {
+                var dir = electron.app.getPath('userData');
+                if (dir && dir.length > 0) {
+                    var file = path.join(dir, 'configuration.json'); 
+                    fs.writeFileSync(file, data);          
+                }
             }
         }
     }
-}
 
-function updateMenu() {
+    updateMenu() {
 
-    var menuRecentsTemplate = [];
-    if (configuration && configuration.recents) {
-        configuration.recents = configuration.recents.filter(recent => fs.existsSync(recent.path));
-        configuration.recents.forEach((recent) => {
-            var file = recent.path;
-            menuRecentsTemplate.push({ 
-                label: minimizePath(recent.path),
-                click: () => { openFile(file); }
+        var menuRecentsTemplate = [];
+        if (this._configuration && this._configuration.recents) {
+            this._configuration.recents = this._configuration.recents.filter(recent => fs.existsSync(recent.path));
+            this._configuration.recents.forEach((recent) => {
+                var file = recent.path;
+                menuRecentsTemplate.push({ 
+                    label: Application.minimizePath(recent.path),
+                    click: () => { this.openFile(file); }
+                });
             });
-        });
-    }
+        }
 
-    var menuTemplate = [];
-    
-    if (process.platform === 'darwin') {
-        menuTemplate.unshift({
-            label: electron.app.getName(),
+        var menuTemplate = [];
+        
+        if (process.platform === 'darwin') {
+            menuTemplate.unshift({
+                label: electron.app.getName(),
+                submenu: [
+                    { role: "about" },
+                    { type: 'separator' },
+                    { role: 'hide' },
+                    { role: 'hideothers' },
+                    { role: 'unhide' },
+                    { type: 'separator' },
+                    { role: "quit" }
+                ]
+            });
+        }
+        
+        menuTemplate.push({
+            label: '&File',
             submenu: [
-                { role: "about" },
-                { type: 'separator' },
-                { role: 'hide' },
-                { role: 'hideothers' },
-                { role: 'unhide' },
+                {
+                    label: '&Open...',
+                    accelerator: 'CmdOrCtrl+O',
+                    click: () => { this.openFileDialog(); }
+                },
+                {
+                    label: 'Open &Recent',
+                    submenu: menuRecentsTemplate
+                },
                 { type: 'separator' },
-                { role: "quit" }
+                { role: 'close' },
             ]
         });
-    }
-    
-    menuTemplate.push({
-        label: '&File',
-        submenu: [
-            {
-                label: '&Open...',
-                accelerator: 'CmdOrCtrl+O',
-                click: () => { openFileDialog(); }
-            },
-            {
-                label: 'Open &Recent',
-                submenu: menuRecentsTemplate
-            },
-            { type: 'separator' },
-            { role: 'close' },
-        ]
-    });
-    
-    if (process.platform !== 'darwin') {
-        menuTemplate.slice(-1)[0].submenu.push(
-            { type: 'separator' },
-            { role: 'quit' }
-        );
-    }
-    
-    if (process.platform == 'darwin') {
-        electron.systemPreferences.setUserDefault('NSDisabledDictationMenuItem', 'boolean', true);
-        electron.systemPreferences.setUserDefault('NSDisabledCharacterPaletteMenuItem', 'boolean', true);
-    }
+        
+        if (process.platform !== 'darwin') {
+            menuTemplate.slice(-1)[0].submenu.push(
+                { type: 'separator' },
+                { role: 'quit' }
+            );
+        }
+        
+        if (process.platform == 'darwin') {
+            electron.systemPreferences.setUserDefault('NSDisabledDictationMenuItem', 'boolean', true);
+            electron.systemPreferences.setUserDefault('NSDisabledCharacterPaletteMenuItem', 'boolean', true);
+        }
 
-    menuTemplate.push({
-        label: '&Edit',
-        submenu: [
-            { role: 'copy' }
-        ]
-    });
+        menuTemplate.push({
+            label: '&Edit',
+            submenu: [
+                { role: 'copy' }
+            ]
+        });
 
-    if (process.platform === 'darwin') {
+        if (process.platform === 'darwin') {
+            menuTemplate.push({
+                role: 'window',
+                submenu: [
+                    { role: 'minimize' },
+                    { role: 'zoom' },
+                    { type: 'separator' },
+                    { role: 'front'}
+                ]
+            });
+        }    
+        
         menuTemplate.push({
-            role: 'window',
+            role: 'help',
             submenu: [
-                { role: 'minimize' },
-                { role: 'zoom' },
-                { type: 'separator' },
-                { role: 'front'}
+                {
+                    label: '&Search Feature Requests',
+                    click: () => { electron.shell.openExternal('https://www.github.com/lutzroeder/Netron/issues'); }
+                },
+                {
+                    label: 'Report &Issues',
+                    click: () => { electron.shell.openExternal('https://www.github.com/lutzroeder/Netron/issues/new'); }
+                }
             ]
         });
-    }    
-    
-    menuTemplate.push({
-        role: 'help',
-        submenu: [
-            {
-                label: '&Search Feature Requests',
-                click: () => { electron.shell.openExternal('https://www.github.com/lutzroeder/Netron/issues'); }
-            },
-            {
-                label: 'Report &Issues',
-                click: () => { electron.shell.openExternal('https://www.github.com/lutzroeder/Netron/issues/new'); }
-            }
-        ]
-    });
 
-    var menu = electron.Menu.buildFromTemplate(menuTemplate);
-    electron.Menu.setApplicationMenu(menu);
-}
+        var menu = electron.Menu.buildFromTemplate(menuTemplate);
+        electron.Menu.setApplicationMenu(menu);
+    }
 
-function minimizePath(file) {
-    var home = os.homedir();
-    if (file.startsWith(home))
-    {
-        return '~' + file.substring(home.length);
+    static minimizePath(file) {
+        var home = os.homedir();
+        if (file.startsWith(home))
+        {
+            return '~' + file.substring(home.length);
+        }
+        return file;
     }
-    return file;
+
 }
+
+var application = new Application();

+ 8 - 8
src/view-electron.js

@@ -30,7 +30,7 @@ class ElectronHostService {
                 electron.ipcRenderer.send('open-file-dialog', {});
             });
         }
-    
+
         document.addEventListener('dragover', (e) => {
             e.preventDefault();
         });
@@ -41,11 +41,11 @@ class ElectronHostService {
             e.preventDefault();
             var files = e.dataTransfer.files;
             for (var i = 0; i < files.length; i++) {
-                this.openFile(files[i].path, i == 0);
+                this.dropFile(files[i].path, i == 0);
             }
             return false;
-        });  
-        
+        });
+
         document.addEventListener('keydown', function(e) {
             if (e.which == 123) {
                 electron.remote.getCurrentWindow().toggleDevTools();
@@ -53,12 +53,12 @@ class ElectronHostService {
         });
     }
 
-    openFile(file, drop) {
+    dropFile(file, drop) {
         var data = { file: file };
         if (drop) {
-            data.window = electron.remote.getCurrentWindow().id;
-        } 
-        electron.ipcRenderer.send('open-file', data);
+            data.windowId = electron.remote.getCurrentWindow().id;
+        }
+        electron.ipcRenderer.send('drop-file', data);
     }
 
     showError(message) {