Skip to content

Commit

Permalink
feat: remember last window size and maximized state
Browse files Browse the repository at this point in the history
  • Loading branch information
dominiksta committed Aug 16, 2024
1 parent f5e7468 commit b5ea5ac
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 10 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ Changelog
`0.0.7` - _unreleased_
----------------------------------------------------------------------

### Added

- When closing Wournal, it will now remember the size and maximized state and
apply that to any new windows.

### Fixed

- Autosave on Windows
- Opening the autosave directory from settings would throw an error
- Links and other annotations where active even without the text selection tool

`0.0.6` - _2024-08-08_
----------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/main/api-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export function registerApiHandlers() {
return fs.readdirSync(dirName);
},
'file:rm': async (_, fileName) => {
if (!fileName.startsWith(APP_CACHE_DIR))
if (!fileName.startsWith(`${APP_CACHE_DIR}/`))
throw new Error(
`Cannot rm in dir: ${fileName}, allowed is ${APP_CACHE_DIR}`
);
Expand Down
23 changes: 20 additions & 3 deletions src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { app, BrowserWindow, shell, WebContents } from 'electron';
import path from 'node:path';
import environment from 'Shared/environment';
import { loggingOverwriteConsoleLogFunctions } from 'Shared/logging';
import { getTempConfig, TEMP_CONFIG_CURRENT_VERSION, writeTempConfig } from './temp-config';

{
loggingOverwriteConsoleLogFunctions();
Expand All @@ -29,14 +30,17 @@ export const instances: Map<WebContents, {
}> = new Map();

function createWindow(argv: string[], pwd: string) {
const tempCfg = getTempConfig();
const win = new BrowserWindow({
// width: 1200,
// height: 800,
width: tempCfg.windowWidth,
height: tempCfg.windowHeight,
webPreferences: {
preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
},
})
win.setMenu(null);
if (tempCfg.maximized) win.maximize();


if (!app.isPackaged) win.webContents.openDevTools();
if (process.argv.indexOf('--dev-tools') !== -1)
Expand All @@ -56,6 +60,16 @@ function createWindow(argv: string[], pwd: string) {
}

instances.set(win.webContents, { win, argv, pwd });

win.on('close', () => {
writeTempConfig({
version: TEMP_CONFIG_CURRENT_VERSION,
windowHeight: win.getBounds().height,
windowWidth: win.getBounds().width,
maximized: win.isMaximized(),
})
});

win.show();
}

Expand All @@ -66,5 +80,8 @@ if (!gotTheLock) {
registerApiHandlers();
app.whenReady().then(() => createWindow(process.argv, process.cwd()));
app.on('second-instance', (_, argv, pwd) => createWindow(argv, pwd));
app.on('window-all-closed', () => app.quit());
app.on('window-all-closed', () => {
app.quit();

});
}
71 changes: 71 additions & 0 deletions src/main/temp-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import DTOVersioner from "Shared/dto-versioner";
import Ajv, { JTDDataType } from 'ajv/dist/jtd';
import fs from 'fs';
import { APP_CACHE_DIR } from "Shared/const";
import { getLogger } from "Shared/logging";
import { homedir } from 'os';

const LOG = getLogger(__filename);
const ajv = new Ajv();

const TempConfigSchema = {
properties: {
version: { type: 'float32' },
windowHeight: { type: 'int32' },
windowWidth: { type: 'int32' },
maximized: { type: 'boolean' },
},
} as const;
export type TempConfig = JTDDataType<typeof TempConfigSchema>;

export const TempConfigVersioner = new DTOVersioner<TempConfig>({
name: 'TempConfig',
validator: ((() => {
const validate = ajv.compile(TempConfigSchema);
return obj => {
const res = validate(obj);
return { success: res, error: JSON.stringify(validate.errors) };
}
}))(),
getVersion: obj => obj.version,
updateFunctions: {

}
});

const TEMP_CONFIG_FILE =
`${APP_CACHE_DIR}/tmp-config.json`.replace(/^~/, homedir);

export const TEMP_CONFIG_CURRENT_VERSION = TempConfigVersioner.maxVersion();

const defaultTempConfig = (): TempConfig => ({
version: TEMP_CONFIG_CURRENT_VERSION,
windowHeight: 600,
windowWidth: 800,
maximized: false,
});

export function getTempConfig(): TempConfig {
try {
if (!fs.existsSync(TEMP_CONFIG_FILE)) {
LOG.info('Was not created yet, using default');
return defaultTempConfig();
}
const file = fs.readFileSync(TEMP_CONFIG_FILE, { encoding: 'utf-8' });
const ret = TempConfigVersioner.updateToCurrent(JSON.parse(file));
LOG.info('Found and parsed, using existing', ret);
return ret;
} catch (e) {
LOG.warn('Could not read, using default', e);
return defaultTempConfig();
}
}

export function writeTempConfig(cfg: TempConfig): void {
TempConfigVersioner.validate(cfg);
fs.writeFileSync(
TEMP_CONFIG_FILE, JSON.stringify(cfg, null, 2),
{ encoding: 'utf-8' }
);
LOG.info('Wrote', cfg);
}
4 changes: 2 additions & 2 deletions src/renderer/document/autosave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default function setupAutosave(
}
for (const f of sorted.slice(0, sorted.length - cfg.keepFiles)) {
LOG.info(`Deleting autosave ${f.fileName}`)
await fs.rm(AUTOSAVE_DIR + f.fileName);
await fs.rm(`${AUTOSAVE_DIR}/${f.fileName}`);
}
}
} catch(e) {
Expand All @@ -92,7 +92,7 @@ export default function setupAutosave(
const fileName = autosaveFileName(doc);
LOG.info(`Saving autosave ${fileName}`);
try {
fs.write(AUTOSAVE_DIR + fileName, await doc.toFile());
fs.write(`${AUTOSAVE_DIR}/${fileName}`, await doc.toFile());
} catch (e) {
const msg = 'Could not write autosave';
notify(`${msg}. Error: ${DSUtils.trySerialize(e)}`);
Expand Down
6 changes: 3 additions & 3 deletions src/shared/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import environment from "./environment";
import { HOST_OS, runningInElectronMain, runningInElectronRenderer } from "./util";

export const APP_CACHE_DIR = HOST_OS === 'windows'
? '~/AppData/Roaming/Wournal/'
: '~/.cache/Wournal/'
? '~/AppData/Roaming/Wournal'
: '~/.cache/Wournal'

export const AUTOSAVE_DIR = APP_CACHE_DIR + 'autosave/';
export const AUTOSAVE_DIR = APP_CACHE_DIR + '/autosave';

export async function getAppDir(): Promise<string> {
if (runningInElectronRenderer()) {
Expand Down
3 changes: 2 additions & 1 deletion src/shared/dto-versioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default class DTOVersioner<T> {

public maxVersion() {
const versions = Object.keys(this.props.updateFunctions).map(parseFloat);
if (versions.length === 0) return 0.0;
return Math.max(...versions);
}

Expand All @@ -39,7 +40,7 @@ export default class DTOVersioner<T> {
this.props;

const versions = Object.keys(updateFunctions).map(parseFloat);
const maxVersion = Math.max(...versions);
const maxVersion = this.maxVersion();
if (toVersion === -1) toVersion = maxVersion;

const startingVersion = getVersion(obj);
Expand Down

0 comments on commit b5ea5ac

Please sign in to comment.