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

Скриншот редактора по нажатию Ctrl + P #353

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
45 changes: 45 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"fast-xml-parser": "^4.3.2",
"find-free-port": "^2.0.0",
"fix-path": "^3.0.0",
"html2canvas": "^1.4.1",
"isomorphic-ws": "^5.0.0",
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1",
Expand Down
63 changes: 63 additions & 0 deletions src/main/file-handlers/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
HandleSaveIntoFolderReturn,
HandleFileSaveReturn,
HandleFileSaveAsReturn,
HandleScreenShotSaveAsReturn,
HandleBinFileOpenReturn,
} from './handlersTypes';

Expand Down Expand Up @@ -214,6 +215,68 @@ export async function handleFileSaveAs(filename: string, data: string): HandleFi
});
}

/**
* Асинхронный диалог сохранения скриншота.
*/
export async function handleScreenShotSaveAs(
filename: string,
dataUrl: string
): HandleScreenShotSaveAsReturn {
return new Promise((resolve) => {
dialog
.showSaveDialog({
title: 'Выберите путь к файлу для сохранения',
defaultPath: filename ? filename : __dirname,
buttonLabel: 'Сохранить',
filters: [
{ name: 'png', extensions: ['png'] },
// { name: 'jpeg', extensions: ['jpeg'] },
// { name: 'svg', extensions: ['svg'] },
{ name: 'All Files', extensions: ['*'] },
],
})
.then(async (file) => {
if (file.canceled) {
resolve([false, null, null]);
} else {
// По умолчанию сохраняем в PNG
let extension = 'png';
if (file.filePath) {
// Получаем расширение файла из пути
const extensionMatch = file.filePath.match(/\.([^.]+)$/);
if (extensionMatch) {
extension = extensionMatch[1].toLowerCase();
}
//['png', 'jpeg', 'svg']
if (!['png'].includes(extension)) {
console.error('Неподдерживаемое расширение файла:', extension);
resolve([false, null, 'Неподдерживаемое расширение файла']);
return;
}

const base64Data = dataUrl.replace(new RegExp(`^data:image/${extension};base64,`), '');
fs.writeFile(file.filePath, base64Data, 'base64', (err) => {
if (err) {
console.error('Ошибка сохранения скриншота:', err);
resolve([false, file.filePath!, err.message]);
} else {
resolve([true, file.filePath!, basename(file.filePath!)]);
console.log('Сохранено!');
console.log(file.filePath);
}
});
} else {
resolve([false, null, null]);
}
}
})
.catch((err) => {
console.log(err);
resolve([false, null, err.message]);
});
});
}

/**
* Асинхронный диалог открытия файла прошивки.
*/
Expand Down
1 change: 1 addition & 0 deletions src/main/file-handlers/handlersTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type SearchPlatformsReturn = Promise<[boolean, string[]]>;
export type HandleSaveIntoFolderReturn = Promise<[boolean, string | null, string]>;
export type HandleFileSaveReturn = Promise<[boolean, string, string]>;
export type HandleFileSaveAsReturn = Promise<[boolean, string | null, string | null]>;
export type HandleScreenShotSaveAsReturn = Promise<[boolean, string | null, string | null]>;
export type HandleBinFileOpenReturn = Promise<
[boolean, string | null, string | null, string | Buffer]
>;
2 changes: 2 additions & 0 deletions src/main/file-handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
handleFileOpen,
handleFileSave,
handleFileSaveAs,
handleScreenShotSaveAs,
handleBinFileOpen,
searchPlatforms,
handleOpenPlatformFile,
Expand All @@ -22,6 +23,7 @@ const handlers = {
openFile: handleFileOpen,
saveFile: handleFileSave,
saveAsFile: handleFileSaveAs,
saveAsScreenShot: handleScreenShotSaveAs,
openBinFile: handleBinFileOpen,
getPlatforms: searchPlatforms,
openPlatformFile: handleOpenPlatformFile,
Expand Down
4 changes: 2 additions & 2 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function createWindow(): BrowserWindow {
});

//Получаем ответ из рендера и закрываем приложение
ipcMain.on('closed', (_) => {
ipcMain.on('closed', () => {
XidFanSan marked this conversation as resolved.
Show resolved Hide resolved
ModuleManager.stopModule('lapki-flasher');
app.exit(0);
});
Expand All @@ -77,7 +77,7 @@ function createWindow(): BrowserWindow {
return { action: 'deny' };
});

ipcMain.handle('devtools', (_event) => {
ipcMain.handle('devtools', () => {
mainWindow.webContents.openDevTools();
});

Expand Down
8 changes: 8 additions & 0 deletions src/renderer/src/lib/basic/EditorView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export class EditorView extends EventEmitter<EditorViewEvents> implements Drawab
this.app.keyboard.on('ctrld', this.app.controller.duplicateSelected);
this.app.keyboard.on('ctrls', this.app.model.files.save);
this.app.keyboard.on('ctrlshifta', this.app.model.files.saveAs);
this.app.keyboard.on(
'ctrlp',
this.app.model.files.saveAsScreenShot.bind(this, this.app.canvas.element)
);

this.app.mouse.on('mousedown', this.handleMouseDown);
this.app.mouse.on('mouseup', this.handleMouseUp);
Expand All @@ -67,6 +71,10 @@ export class EditorView extends EventEmitter<EditorViewEvents> implements Drawab
this.app.keyboard.off('ctrld', this.app.controller.duplicateSelected);
this.app.keyboard.off('ctrls', this.app.model.files.save);
this.app.keyboard.off('ctrlshifta', this.app.model.files.saveAs);
this.app.keyboard.off(
'ctrlp',
this.app.model.files.saveAsScreenShot.bind(this, this.app.canvas.element)
);

this.app.mouse.off('mousedown', this.handleMouseDown);
this.app.mouse.off('mouseup', this.handleMouseUp);
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/lib/basic/Keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ interface KeyboardEvents {
shiftdown: KeyboardEvent;
shiftup: KeyboardEvent;
delete: KeyboardEvent;
ctrlp: KeyboardEvent;
ctrlz: KeyboardEvent;
ctrly: KeyboardEvent;
ctrlc: KeyboardEvent;
Expand Down Expand Up @@ -79,6 +80,10 @@ export class Keyboard extends EventEmitter<KeyboardEvents> {
}

if (e.ctrlKey) {
if (e.code === 'KeyP') {
this.emit('ctrlp', e);
return;
}
if (e.code === 'KeyZ') {
this.emit('ctrlz', e);
return;
Expand Down
21 changes: 21 additions & 0 deletions src/renderer/src/lib/data/EditorModel/FilesManager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Dispatch } from 'react';

import html2canvas from 'html2canvas';

import { Compiler } from '@renderer/components/Modules/Compiler';
import { Binary, SourceFile } from '@renderer/types/CompilerTypes';
import { Elements, emptyElements } from '@renderer/types/diagram';
Expand Down Expand Up @@ -163,6 +165,25 @@ export class FilesManager {
return makeLeft(null);
};

saveAsScreenShot = async (element: HTMLElement) => {
if (!this.data.isInitialized) return makeLeft(null);
const screenshotDataUrl = await this.createScreenshot(element);

//Берём имя файла и убираем его расширение в наименовании и меняем на расширение сохраняемого изображения
const nameFile = this.data.basename?.replace('.graphml', '.png') as string;

return await window.api.fileHandlers.saveAsScreenShot(nameFile, screenshotDataUrl);
};

private createScreenshot = async (element: HTMLElement | null): Promise<string> => {
if (element) {
const canvas = await html2canvas(element);
return canvas.toDataURL('image/png');
} else {
throw new Error('Элемент отсутствует!');
}
};

async saveIntoFolder(data: Array<SourceFile | Binary>) {
await window.api.fileHandlers.saveIntoFolder(data);
}
Expand Down
Loading