Skip to content

Commit

Permalink
[Refactor] Desktop core features (#8709)
Browse files Browse the repository at this point in the history
* refactor: window management and electron store

Moves window management related code into a dedicated directory.

Removes electron-log and type definitions for electron store.  Electron store is now handled globally in a dedicated module.  Console logging will be handled by the renderer process.

* refactor: store and adds logger utility

Moves store related services into a dedicated store directory.

Introduces a new logger utility for better logging and debugging.  The logger is initialized and setup for Electron.

* refactor: desktop store to use core services

Replaces direct `electron-store` usage with core services for managing application settings, configurations, authentication, and project information.

This change improves code organization, reduces redundancy, and promotes consistency with the core application logic. It centralizes data management and simplifies updates to the stored data.

* refactor: config management and logging

Centralizes environment variable assignment to `environment.ts`.

Improves theme preference handling by simplifying the logic and setting a default theme if no setting exists.

Updates server start logic to directly update config store instead of using a temporary object.

Moves logging setup and node modules path output to after environment setup.

Removes redundant `electron-log` imports and uses `@gauzy/desktop-core` logger.

Refactors and simplifies setting default config by using `LocalStore.setAllDefaultConfig`.

Simplifies timer duration update logging.

* feat(desktop-core): add optional db field to IConfig interface

- Introduced an optional `db` property to the `IConfig` interface to allow for database configuration specifications.
- This change enables more flexible configurations within the desktop core setup.
  • Loading branch information
adkif authored Jan 7, 2025
1 parent e9888d2 commit c653000
Show file tree
Hide file tree
Showing 50 changed files with 1,135 additions and 942 deletions.
94 changes: 42 additions & 52 deletions apps/desktop-timer/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
// Adapted from https://github.com/maximegris/angular-electron/blob/master/main.ts

import { environment } from './environments/environment';
// Assign environment variables
Object.assign(process.env, environment);
// Import logging for electron and override default console logging
import log from 'electron-log';
console.log = log.log;
Object.assign(console, log.functions);

import * as remoteMain from '@electron/remote/main';
import { logger as log, store } from '@gauzy/desktop-core';
import * as Sentry from '@sentry/electron';
import { setupTitlebar } from 'custom-electron-titlebar/main';
import { app, BrowserWindow, ipcMain, Menu, MenuItemConstructorOptions, nativeTheme, shell } from 'electron';
import * as Store from 'electron-store';
import * as path from 'path';
import * as Url from 'url';
import { environment } from './environments/environment';
import { initSentry } from './sentry';

require('module').globalPaths.push(path.join(__dirname, 'node_modules'));

process.env = Object.assign(process.env, environment);

app.setName(process.env.NAME);

log.log('Desktop Timer Node Modules Path', path.join(__dirname, 'node_modules'));
// Initialize logging
log.setup();

// Add node modules path
log.info('Desktop Timer Node Modules Path', path.join(__dirname, 'node_modules'));

// Initialize Sentry
initSentry();

remoteMain.initialize();

import { fork } from 'child_process';
import { autoUpdater } from 'electron-updater';
import {
AppError,
AppMenu,
Expand Down Expand Up @@ -59,11 +60,8 @@ import {
SplashScreen,
timeTrackerPage
} from '@gauzy/desktop-window';
import { initSentry } from './sentry';

// Can be like this: import fetch from '@gauzy/desktop-lib' for v3 of node-fetch;

initSentry();
import { fork } from 'child_process';
import { autoUpdater } from 'electron-updater';

// the folder where all app data will be stored (e.g. sqlite DB, settings, cache, etc)
// C:\Users\USERNAME\AppData\Roaming\gauzy-desktop-timer
Expand All @@ -79,7 +77,6 @@ const knex = provider.connection;

const exeName = path.basename(process.execPath);
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
const store = new Store();

const args = process.argv.slice(1);
const serverGauzy = null;
Expand All @@ -94,14 +91,7 @@ args.some((val) => val === '--serve');

ipcMain.handle('PREFERRED_THEME', () => {
const setting = LocalStore.getStore('appSetting');
if (!setting) {
LocalStore.setDefaultApplicationSetting();
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
LocalStore.updateApplicationSetting({ theme });
return theme;
} else {
return setting.theme;
}
return !setting ? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light') : setting.theme;
});

let notificationWindow = null;
Expand Down Expand Up @@ -235,26 +225,25 @@ eventErrorManager.onShowError(async (message) => {

async function startServer(value, restart = false) {
try {
const config: any = {
...value,
isSetup: true
};
const project = LocalStore.getStore('project') || {};
// Ensure that project.aw exists before spreading it
if (!project.aw) {
project.aw = {};
}

// Update the aw object
const aw = {
host: value.awHost,
isAw: !!value.aw?.isAw
...project.aw,
host: value.awHost
};
const projectConfig = store.get('project');
store.set({
configs: config,
project: projectConfig
? projectConfig
: {
projectId: null,
taskId: null,
note: null,
aw,
organizationContactId: null
}

// Update the project
LocalStore.updateConfigProject({ aw });

// Update the setting
LocalStore.updateConfigSetting({
...value,
isSetup: true
});
} catch (error) {
throw new AppError('MAINSTRSERVER', error);
Expand Down Expand Up @@ -356,6 +345,12 @@ const getApiBaseUrl = (configs) => {
app.on('ready', async () => {
const configs: any = store.get('configs');
const settings: any = store.get('appSetting');

if (!settings) {
launchAtStartup(true, false);
LocalStore.setAllDefaultConfig();
}

// Set up theme listener for desktop windows
new DesktopThemeListener();
// default global
Expand All @@ -370,9 +365,7 @@ app.on('ready', async () => {
} catch (error) {
console.error(error);
}
if (!settings) {
launchAtStartup(true, false);
}

if (['sqlite', 'better-sqlite', 'better-sqlite3'].includes(provider.dialect)) {
try {
const res = await knex.raw(`pragma journal_mode = WAL;`);
Expand Down Expand Up @@ -455,13 +448,10 @@ app.on('window-all-closed', () => {
app.commandLine.appendSwitch('disable-http2');

ipcMain.on('server_is_ready', async () => {
console.log('Server is ready event received');
LocalStore.setDefaultApplicationSetting();
log.info('Server is ready event received');
const appConfig = LocalStore.getStore('configs');
appConfig.serverConfigConnected = true;
store.set({
configs: appConfig
});
LocalStore.updateConfigSetting(appConfig);
onWaitingServer = false;
if (!isAlreadyRun) {
console.log('Server is ready, starting the Desktop API...');
Expand Down
24 changes: 9 additions & 15 deletions apps/desktop/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,7 @@ ipcMain.removeHandler('PREFERRED_LANGUAGE');

ipcMain.handle('PREFERRED_THEME', () => {
const setting = LocalStore.getStore('appSetting');
if (!setting) {
LocalStore.setDefaultApplicationSetting();
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
LocalStore.updateApplicationSetting({ theme });
return theme;
} else {
return setting.theme;
}
return !setting ? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light') : setting.theme;
});

// setup logger to catch all unhandled errors and submit as bug reports to our repo
Expand Down Expand Up @@ -468,7 +461,7 @@ const closeSplashScreen = () => {
splashScreen.close();
splashScreen = null;
}
}
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
Expand All @@ -482,6 +475,11 @@ app.on('ready', async () => {
const configs: any = store.get('configs');
const settings: any = store.get('appSetting');

if (!settings) {
launchAtStartup(true, false);
LocalStore.setAllDefaultConfig();
}

// default global
global.variableGlobal = {
API_BASE_URL: getApiBaseUrl(configs || {}),
Expand Down Expand Up @@ -514,10 +512,6 @@ app.on('ready', async () => {
throw new AppError('MAINDB', error);
}

if (!settings) {
launchAtStartup(true, false);
}

const menu: MenuItemConstructorOptions[] = [
{
label: app.getName(),
Expand Down Expand Up @@ -553,7 +547,7 @@ app.on('ready', async () => {
if (!configs.serverConfigConnected && !configs?.isLocalServer) {
setupWindow = await createSetupWindow(setupWindow, false, pathWindow.timeTrackerUi);
setupWindow.show();
closeSplashScreen()
closeSplashScreen();
setupWindow.webContents.send('setup-data', {
...configs
});
Expand Down Expand Up @@ -615,7 +609,7 @@ app.commandLine.appendSwitch('disable-http2');
ipcMain.on('server_is_ready', async () => {
console.log('Server is ready event received');

LocalStore.setDefaultApplicationSetting();
LocalStore.setAllDefaultConfig();

const appConfig = LocalStore.getStore('configs');

Expand Down
11 changes: 2 additions & 9 deletions apps/server-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,7 @@ ipcMain.removeHandler('PREFERRED_LANGUAGE');

ipcMain.handle('PREFERRED_THEME', () => {
const setting = LocalStore.getStore('appSetting');
if (!setting) {
LocalStore.setDefaultApplicationSetting();
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
LocalStore.updateApplicationSetting({ theme });
return theme;
} else {
return setting.theme;
}
return !setting ? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light') : setting.theme;
});

// setup logger to catch all unhandled errors and submit as bug reports to our repo
Expand Down Expand Up @@ -243,7 +236,7 @@ const closeSplashScreen = () => {
splashScreen.close();
splashScreen = null;
}
}
};

const runSetup = async () => {
// Set default configuration
Expand Down
11 changes: 2 additions & 9 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,7 @@ ipcMain.removeHandler('PREFERRED_LANGUAGE');

ipcMain.handle('PREFERRED_THEME', () => {
const setting = LocalStore.getStore('appSetting');
if (!setting) {
LocalStore.setDefaultApplicationSetting();
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
LocalStore.updateApplicationSetting({ theme });
return theme;
} else {
return setting.theme;
}
return !setting ? (nativeTheme.shouldUseDarkColors ? 'dark' : 'light') : setting.theme;
});

// setup logger to catch all unhandled errors and submit as bug reports to our repo
Expand Down Expand Up @@ -252,7 +245,7 @@ const closeSplashScreen = () => {
splashScreen.close();
splashScreen = null;
}
}
};

const runSetup = async () => {
// Set default configuration
Expand Down
21 changes: 12 additions & 9 deletions packages/desktop-core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
export * from './lib/concretes/default-window';
export * from './lib/concretes/window-config';
export * from './lib/concretes/window.manager';
export * from './lib/interfaces/base-window';
export * from './lib/interfaces/ibase-window';
export * from './lib/interfaces/iwindow-config';
export * from './lib/interfaces/iwindow.manager';
export * from './lib/electron-helpers';
export * from './lib/interfaces/types';
export * from './lib/window-manager/concretes/default-window';
export * from './lib/window-manager/concretes/window-config';
export * from './lib/window-manager/concretes/window.manager';
export * from './lib/window-manager/interfaces/base-window';
export * from './lib/window-manager/interfaces/ibase-window';
export * from './lib/window-manager/interfaces/iwindow-config';
export * from './lib/window-manager/interfaces/iwindow.manager';
export * from './lib/store/electron-helpers';
export * from './lib/store/local.store';
export * from './lib/store/types';
export * from './lib/logger/logger';
export * from './lib/logger/types';
18 changes: 0 additions & 18 deletions packages/desktop-core/src/lib/electron-helpers.ts

This file was deleted.

47 changes: 0 additions & 47 deletions packages/desktop-core/src/lib/interfaces/types.ts

This file was deleted.

Loading

0 comments on commit c653000

Please sign in to comment.