Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MLC-31] Add in settings page with storage #16

Merged
merged 2 commits into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added app/assets/IconTemplate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added app/assets/icon.icns
Binary file not shown.
166 changes: 139 additions & 27 deletions app/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
nativeImage,
Tray,
} from 'electron';

import Store from 'electron-store';
import * as net from 'net';

const path = require('path');
Expand Down Expand Up @@ -72,6 +72,16 @@ class ServerManager {
console.log(`Starting server for model: ${model} on port: ${port}`);
this.serverProcess = this.runPythonServer(model, port);

this.serverProcess.stdout.on('data', (data: Buffer) => {
const output = data.toString('utf8');
console.log('Server output:', output);

// Check if the server is ready
if (output.includes('starting server on')) {
resolve(); // Resolve the promise when the server is ready
}
});

this.serverProcess.on('close', (code: number | null) => {
console.log(`Server process exited with code ${code}`);
this.serverProcess = null;
Expand All @@ -82,8 +92,6 @@ class ServerManager {
this.serverProcess = null;
reject(err);
});

resolve();
});
});
}
Expand Down Expand Up @@ -130,12 +138,52 @@ if (isProd) {
app.setPath('userData', `${app.getPath('userData')} (development)`);
}

let directoryOpen = false;
let openModal: 'settings' | 'directory' | null = null;

let globalWindow: BrowserWindow | null = null;

const triggerShortcut = () => {
if (openModal || !globalWindow) {
return;
}
if (globalWindow.isFocused()) {
globalWindow.blur();
return;
}
globalWindow.show();
};

const store = new Store({
schema: {
keybind: {
type: 'string',
default: 'Cmd+O',
},
model: {
type: 'string',
default: 'mlx-community/quantized-gemma-7b-it',
},
customInstructions: {
type: 'string',
default: '',
},
},
});

const serverManager = new ServerManager();

const createWindow = () => {
const icon = nativeImage.createFromPath('path/to/asset.png');
let tray = new Tray(icon);
tray.setTitle('M');
const icon = nativeImage.createFromPath(
!isProd
? '../assets/IconTemplate.png'
: path.join(process.resourcesPath, 'IconTemplate.png'),
);
// if you want to resize it, be careful, it creates a copy
const trayIcon = icon.resize({ width: 16 });
// here is the important part (has to be set on the resized version)
trayIcon.setTemplateImage(true);
let tray = new Tray(trayIcon);
tray.setTitle(isProd ? '' : 'M');

const win = new BrowserWindow({
webPreferences: {
Expand All @@ -152,14 +200,13 @@ const createWindow = () => {
autoHideMenuBar: true,
vibrancy: 'under-window', // on MacOS
backgroundMaterial: 'acrylic',
icon: __dirname + '../../assets/public/icon.icns',
});
app.dock.hide();
globalWindow = win;
win.setWindowButtonVisibility(false);
win.setAlwaysOnTop(true, 'floating');
win.setVisibleOnAllWorkspaces(true);

// win.webContents.openDevTools();

// Expose URL
if (isProd) {
win.loadURL('app://./home.html');
Expand All @@ -176,30 +223,30 @@ const createWindow = () => {
win.show();
});

win.webContents.on('did-finish-load', () => {
win.webContents.on('did-finish-load', async () => {
await serverManager.start(store.get('model') as string);
/// then close the loading screen window and show the main window
if (splash) {
splash.close();
}
win.show();
globalShortcut.register('Cmd+O', () => {
if (win.isFocused()) {
win.blur();
return;
}
win.show();
});
globalShortcut.register(store.get('keybind') as string, triggerShortcut.bind(null));
});

// @ts-expect-error -- We don't have types for electron
win.on('blur', (event) => {
if (directoryOpen) {
if (openModal) {
win.setAlwaysOnTop(false);
}
if (openModal === 'directory') {
return;
}

globalShortcut.unregister('Escape');
win.hide();
if (openModal) {
return;
}

Menu.sendActionToFirstResponder('hide:');
});

Expand All @@ -216,26 +263,79 @@ const createWindow = () => {
event.preventDefault();
win.hide();
});
let settingsModal: BrowserWindow | null = null;

const createSettings = () => {
settingsModal = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
width: 500,
height: 500,
resizable: false,
minimizable: false,
titleBarStyle: 'hidden',
show: false,
backgroundColor: '#000',
});

if (isProd) {
settingsModal.loadURL('app://./home.html');
} else {
// const port = process.argv[2];
settingsModal.loadURL('http://localhost:3000/settings');
}

settingsModal.on('closed', () => {
openModal = null;
settingsModal?.destroy();
settingsModal = null;
});

settingsModal.on('ready-to-show', () => {
settingsModal?.show();
});

return settingsModal;
};

const nativeMenus: (Electron.MenuItemConstructorOptions | Electron.MenuItem)[] = [
{
label: 'MLX Chat',
submenu: [
{
label: 'Settings',
click() {
openModal = 'settings';
if (settingsModal !== null) {
settingsModal.close();
}
createSettings();
},
accelerator: 'Cmd+,',
},
],
},
];

const menu = Menu.buildFromTemplate(nativeMenus);
Menu.setApplicationMenu(menu);
};

app.whenReady().then(() => {
if (process.platform == 'darwin') {
app.dock.hide();
}
ipcMain.on('set-title', handleSetTitle);
ipcMain.on('select-directory', (event: any) => {
directoryOpen = true;
openModal = 'directory';
dialog.showOpenDialog({ properties: ['openDirectory'] }).then((result: any) => {
const win = BrowserWindow.fromWebContents(event.sender);
// Weird hack to bring the window to the front after allowing windows in front of it
win?.setAlwaysOnTop(true, 'floating');

directoryOpen = false;
openModal = null;
event.sender.send('selected-directory', result.filePaths);
});
});

const serverManager = new ServerManager();
ipcMain.on('start-server', (event: any, model: string) => {
event;
serverManager.start(model)
Expand All @@ -254,11 +354,23 @@ app.whenReady().then(() => {
win.center();
});

ipcMain.on('fetch-setting', (event, arg) => {
event.returnValue = store.get(arg);
});

ipcMain.on('update-setting', (_event, arg) => {
if (arg.key === 'keybind') {
globalShortcut.unregister(store.get('keybind') as string);
globalShortcut.register(arg.value, triggerShortcut.bind(null));
}
store.set(arg.key, arg.value);
});

createSplashScreen();

setTimeout(() => {
createWindow();
}, 2000);
}, 500);

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) { createWindow(); }
Expand Down
2 changes: 2 additions & 0 deletions app/main/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const electronAPI = {
},
startServer: (model: string) => ipcRenderer.send('start-server', model),
resizeWindow: (height: number) => ipcRenderer.send('resize-window', { height }),
fetchSetting: (key: string) => ipcRenderer.sendSync('fetch-setting', key),
updateSetting: (key: string, value: any) => ipcRenderer.send('update-setting', { key, value }),
};

contextBridge.exposeInMainWorld('electronAPI', electronAPI);
Binary file added app/main/public/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions app/main/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
"skipLibCheck": true,
"strict": true,
"target": "esnext",
"outDir": "./out"
"outDir": "./out",
},
"compileOnSave": true,
"exclude": ["node_modules", "./out/**/*"],
"include": ["**/*.ts", "**/*.tsx", "**/*.js"]
"include": ["**/*.ts", "**/*.tsx", "**/*.js", "public/**.icns"],
}
Loading
Loading