import * as path from 'path'; import * as sharp from 'sharp'; import * as electron from 'electron'; import BaseElements from './require/base-elements'; import ElementsUtil from './require/elements-util'; import ClientController from '../client-controller'; import Q from '../q-module'; export default function createImageContextMenu( document: Document, q: Q, guild: CombinedGuild, resourceName: string, buffer: Buffer, mime: string, ext: string, isPreview: boolean ): HTMLElement { // TODO: try/catch around sharp? let contextMenu = BaseElements.createContextMenu(document, { class: 'image', content: [ { class: 'item copy-image', content: 'Copy Image' + (isPreview ? ' Preview' : '') }, { class: 'item save-image', content: 'Save Image' + (isPreview ? ' Preview' : '') }, ] }); q.$$$(contextMenu, '.copy-image').addEventListener('click', async () => { q.$$$(contextMenu, '.copy-image').innerText = 'Copying...'; let nativeImage: electron.NativeImage; if (mime != 'image/png' && mime != 'image/jpeg' && mime != 'image/jpg') { // use sharp to convert to png since nativeImage only supports jpeg/png nativeImage = electron.nativeImage.createFromBuffer(await sharp(buffer).png().toBuffer()); } else { nativeImage = electron.nativeImage.createFromBuffer(buffer); } electron.clipboard.writeImage(nativeImage); q.$$$(contextMenu, '.copy-image').innerText = 'Copied to Clipboard'; }); q.$$$(contextMenu, '.save-image').addEventListener('click', ElementsUtil.createDownloadListener({ downloadBuff: buffer, server: server, resourceName: path.basename(resourceName, '.' + ext) + (isPreview ? '-preview.' : '.') + ext, downloadStartFunc: () => {}, writeStartFunc: () => { q.$$$(contextMenu, '.save-image').innerText = 'Writing...'; }, writeFailFunc: () => { q.$$$(contextMenu, '.save-image').innerText = 'Write Failed. Click to Try Again'; }, successFunc: () => { q.$$$(contextMenu, '.save-image').innerText = 'Reveal' + (isPreview ? ' Preview' : '') + ' in Explorer'; } })); return contextMenu; }