Skip to content

Commit

Permalink
fix: linux clipboard working
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisTowles committed Sep 25, 2022
1 parent 5f25b75 commit a9aa08a
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 66 deletions.
13 changes: 7 additions & 6 deletions res/linux.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@

echo "imagePath = $1"


# require xclip(see http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212)
command -v xclip >/dev/null 2>&1 || { echo >&1 "error: no xclip found"; exit 0; }
command -v xclip >/dev/null 2>&1 || { echo >&1 "error: no xclip found"; exit 1; }

# write image in clipboard to file (see http://unix.stackexchange.com/questions/145131/copy-image-from-clipboard-to-file)
if xclip -selection clipboard -target image/png -o >/dev/null 2>&1 then
xclip -selection clipboard -target image/png -o >$1 2>/dev/null
echo "image writen to: $1"
if ( xclip -selection clipboard -target image/png -o > /dev/null 2>&1) then
# image in clipboard, let's save it
xclip -selection clipboard -target image/png -o > $1 2>/dev/null
echo "image writen to: $1"
else
echo "no image in clipboard"
echo "warning: no image in clipboard"
exit 1;
fi
9 changes: 4 additions & 5 deletions src/dto/SaveClipboardImageToFileResult.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@

export interface SaveClipboardImageToFileResult {
success: boolean;
paths?: {
imagePath: string;
imagePathFromScript: string;
}

noImageInClipboard?: boolean;
imagePath?: string;
scriptOutput?: string[];

}
52 changes: 35 additions & 17 deletions src/osTools/linux.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import * as fse from 'fs-extra';
import { ILogger } from "../logger";
import { SaveClipboardImageToFileResult } from "../dto/SaveClipboardImageToFileResult";



export const linuxCreateImageWithXClip = async ({ imagePath, logger }: { imagePath: string; logger: ILogger; }): Promise<SaveClipboardImageToFileResult> =>{
let scriptPath = path.join(__dirname, '../res/linux.sh');

Expand All @@ -12,30 +14,46 @@ export const linuxCreateImageWithXClip = async ({ imagePath, logger }: { imagePa
}
return new Promise<SaveClipboardImageToFileResult>((resolve, reject) => {

let ascript = spawn('sh', [scriptPath, imagePath]);
ascript.on('error', function (e) {
let outputData: string = '';

let shellScript = spawn('sh', [scriptPath, imagePath]);
shellScript.on('error', function (e) {
logger.showErrorMessage(e.message);
});
ascript.on('exit', function (code, signal) {
shellScript.on('exit', async function (code, signal) {
logger.log(`scriptPath: "${scriptPath}" exit code: ${code} signal: ${signal}`);
});
ascript.stdout.on('data', function (data: Buffer) {
let result = data.toString().trim();
logger.log(`script result data: ${data}`);
if (result.includes("no xclip found")) {
logger.showInformationMessage('You need to install "xclip" command app first.');

if(code === 0) {
resolve({
success: true,
imagePath: imagePath,
noImageInClipboard: false,
scriptOutput: outputData.split('\n'),
});

} else {

outputData.split('\n').forEach(line => {
logger.log(`script result data: ${line}`);
});

if (outputData.includes("error: no xclip found")) {
await logger.showInformationMessage('You need to install "xclip" command app first.');
}

resolve({
success: false,
noImageInClipboard: outputData.includes("warning: no image in clipboard"),
scriptOutput: outputData.split('\n'),
});
}

resolve({
success: true,
paths: {
imagePath: imagePath,
imagePathFromScript: result,
}
});


});

shellScript.stdout.on('data', async function (data: Buffer) {
// save all the output till exit
outputData += data.toString().trim() + '\n';
});
});
}
8 changes: 4 additions & 4 deletions src/osTools/mac-os.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ export const macCreateImageWithAppleScript = async ({ imagePath, logger }: { ima

resolve({
success: true,
paths: {
imagePath: imagePath,
imagePathFromScript: data.toString().trim(),
}
noImageInClipboard: false,
imagePath: imagePath,
scriptOutput: [data.toString().trim()],

});
});

Expand Down
8 changes: 4 additions & 4 deletions src/osTools/win32.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ export const win32CreateImageWithPowershell = async ({ imagePath, logger }: { im

resolve({
success: true,
paths: {
imagePath: imagePath,
imagePathFromScript: data.toString().trim(),
}
noImageInClipboard: false,
imagePath: imagePath,
scriptOutput: [data.toString().trim()],

});
});

Expand Down
52 changes: 22 additions & 30 deletions src/paster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { DateTime } from 'luxon';
import { win32CreateImageWithPowershell } from './osTools/win32';
import { macCreateImageWithAppleScript } from './osTools/mac-os';
import { SaveClipboardImageToFileResult } from './dto/SaveClipboardImageToFileResult';
import util from 'util';


export class Paster {
Expand Down Expand Up @@ -61,7 +60,7 @@ export class Paster {

logger.log(`projectPath = ${projectPath}`);
logger.log(`fileUri = ${fileUri}`);
if (projectPath === '')
if (projectPath === '')
return;


Expand Down Expand Up @@ -119,10 +118,6 @@ export class Paster {
this.nameSuffixConfig = this.replacePathVariable(this.nameSuffixConfig, projectPath, filePath);
this.insertPatternConfig = this.replacePathVariable(this.insertPatternConfig, projectPath, filePath);

// "this" is lost when coming back from the callback, thus we need to store it here.
const instance = this;



try {
const imagePath = await this.getImagePath({ filePath, selectText, folderPathFromConfig: this.folderPathConfig, showFilePathConfirmInputBox: this.showFilePathConfirmInputBox, filePathConfirmInputBoxMode: this.filePathConfirmInputBoxMode, logger })
Expand All @@ -134,11 +129,9 @@ export class Paster {

if (choose != 'Replace')
return;

await instance.saveAndPaste({ editor, imagePath, logger });
} else {
await instance.saveAndPaste({ editor, imagePath, logger });
}
await this.saveAndPaste({ editor, imagePath, logger });

} catch (err) {
logger.showErrorMessage(`fs.existsSync(${filePath}) fail. message=${(err as Error).message}`);
return;
Expand All @@ -150,26 +143,22 @@ export class Paster {

public static async saveAndPaste({ editor, imagePath, logger }: { editor: vscode.TextEditor; imagePath: string; logger: ILogger; }): Promise<void> {

logger.debug('saveAndPaste Start');
logger.debug(`saveAndPaste Start, imagePath = ${imagePath}`);

try {
imagePath = await createImageDirWithImagePath(imagePath)
const imageFolder = await createImageDirWithImagePath(imagePath)
logger.debug(`imageFolder = ${imageFolder}`);

logger.debug('createImageDirWithImagePath: ' + imagePath);
// save image and insert to current edit file
const result = await this.saveClipboardImageToFileAndGetPath({ imagePath, logger });


if (result.success) {
logger.debug(`saveClipboardImageToFileAndGetPath - ${imagePath} - imagePath: ${result.paths?.imagePath}`);
logger.debug(`saveClipboardImageToFileAndGetPath - ${imagePath} }`);
} else {
logger.debug('There is not an image path returned By script.');
return;
}

// TODO this includes is wrong.
if (result.paths?.imagePathFromScript.includes('no image')) {
logger.showInformationMessage('There is not an image in the clipboard.');
if (result.noImageInClipboard) {
await logger.showErrorMessage('No Image was found in the clipboard.');
}
return;
}

Expand All @@ -187,27 +176,25 @@ export class Paster {

}
catch (err) {

logger.showErrorMessage((err as Error).message);

}

logger.debug('saveAndPaste end');
}

public static async getImagePath({ filePath, selectText, folderPathFromConfig, showFilePathConfirmInputBox, filePathConfirmInputBoxMode, logger }: { filePath: string; selectText: string; folderPathFromConfig: string; showFilePathConfirmInputBox: boolean; filePathConfirmInputBoxMode: string; logger: ILogger }): Promise<string> {

logger.debug('getImagePath start');

logger.debug('getImagePath start');

// image file name
let imageFileName = "";
if (!selectText) {
imageFileName = this.namePrefixConfig + DateTime.now().toFormat(this.defaultNameConfig) + this.nameSuffixConfig + ".png";

} else {
imageFileName = this.namePrefixConfig + selectText + this.nameSuffixConfig + ".png";
imageFileName = this.namePrefixConfig + selectText + this.nameSuffixConfig;
}
imageFileName = Paster.ensurePngAddedToFileName(imageFileName);

let filePathOrName;
if (filePathConfirmInputBoxMode == Paster.FILE_PATH_CONFIRM_INPUT_BOX_MODE_PULL_PATH) {
Expand All @@ -224,8 +211,7 @@ export class Paster {
});

if (userEnteredFileName) {
if (!userEnteredFileName.toLowerCase().endsWith('.png'))
userEnteredFileName += '.png';
userEnteredFileName = Paster.ensurePngAddedToFileName(userEnteredFileName);

if (filePathConfirmInputBoxMode == Paster.FILE_PATH_CONFIRM_INPUT_BOX_MODE_ONLY_NAME) {
filePathOrName = makeImagePath({ fileName: userEnteredFileName, folderPathFromConfig: folderPathFromConfig, filePath: filePath });
Expand All @@ -249,7 +235,13 @@ export class Paster {
return filePathOrName;
}

private static async saveClipboardImageToFileAndGetPath({ imagePath, logger }: { imagePath: string; logger: ILogger}): Promise<SaveClipboardImageToFileResult> {
private static ensurePngAddedToFileName(userEnteredFileName: string) {
if (!userEnteredFileName.toLowerCase().endsWith('.png'))
userEnteredFileName += '.png';
return userEnteredFileName;
}

private static async saveClipboardImageToFileAndGetPath({ imagePath, logger }: { imagePath: string; logger: ILogger }): Promise<SaveClipboardImageToFileResult> {
if (!imagePath) {
logger.log('imagePath is empty');
return { success: false };
Expand All @@ -267,7 +259,7 @@ export class Paster {
// Linux
result = await linuxCreateImageWithXClip({ imagePath, logger });
}
logger.log(`createImage result = ${util.inspect(result, { showHidden: false, depth: null, colors: true })}`);
logger.log(`createImage result = ${JSON.stringify(result, null, 2)}`);
return result;
}

Expand Down

0 comments on commit a9aa08a

Please sign in to comment.