import { Screenshot } from '../Screenshot' ; import { ScreenshotRequest } from '../Screenshot' ; import { webContents } from 'electron' ; import { Logger } from 'polar-shared/src/logger/Logger' ; import { Stopwatches } from 'polar-shared/src/util/Stopwatches' ; const log = Logger . create ( ) ; /**
 * Handles the actual screenshots
 */ export class ScreenshotDelegate implements IScreenshotDelegate { public static DELEGATE_NAME = "screenshotDelegate" ; public async capture ( id , screenshotRequest ) { const nativeImage = await Stopwatches . withStopwatchAsync ( ( ) => this . captureNativeImage ( id , screenshotRequest ) , stopwatch => log . debug ( "captureNativeImage took: " + stopwatch ) ) ; return Stopwatches . withStopwatch ( ( ) => this . toCapturedScreenshot ( nativeImage , screenshotRequest ) , stopwatch => log . debug ( "toCapturedScreenshot took: " + stopwatch ) ) ; } param id param screenshotRequest return { Promise } private async captureNativeImage ( id , screenshotRequest ) { const webContentsInstance = webContents . fromId ( id ) ; if ( ! screenshotRequest ) { throw new Error ( "screenshotRequest required" ) ; } let rect = screenshotRequest . rect ; if ( ! rect ) { throw new Error ( "No rect" ) ; } rect = { x : Math . round ( screenshotRequest . rect . x ) , y : Math . round ( screenshotRequest . rect . y ) , width : Math . round ( screenshotRequest . rect . width ) , height : Math . round ( screenshotRequest . rect . height ) } ; let image = await webContentsInstance . capturePage ( rect ) ; if ( screenshotRequest . resize ) { if ( screenshotRequest . resize . width !== undefined || screenshotRequest . resize . height !== undefined ) { log . info ( "Resizing image to: " , screenshotRequest . resize ) ; image = image . resize ( screenshotRequest . resize ) ; } } if ( screenshotRequest . crop ) { log . info ( "Cropping image to: " , screenshotRequest . resize ) ; image = image . crop ( screenshotRequest . crop ) ; } return image ; } private toCapturedScreenshot ( image , screenshotRequest ) { const toData = ( ) => { switch ( screenshotRequest . type ) { case 'data-url' : return image . toDataURL ( ) ; case 'png' : return image . toPNG ( ) ; } } ; const data = toData ( ) ; const size = image . getSize ( ) ; const capturedScreenshot = { data , dimensions : { width : size . width , height : size . height } , type : screenshotRequest . type } ; return capturedScreenshot ; } } export interface IScreenshotDelegate { capture ( id , screenshotRequest ) : Promise < Screenshot > ; } export type WebContentsID = number ;