本文整理汇总了TypeScript中vscode.window.withProgress方法的典型用法代码示例。如果您正苦于以下问题:TypeScript window.withProgress方法的具体用法?TypeScript window.withProgress怎么用?TypeScript window.withProgress使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类vscode.window
的用法示例。
在下文中一共展示了window.withProgress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: clone
@command('git.clone')
async clone(): Promise<void> {
const url = await window.showInputBox({
prompt: localize('repourl', "Repository URL"),
ignoreFocusOut: true
});
if (!url) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_URL' });
return;
}
const config = workspace.getConfiguration('git');
const value = config.get<string>('defaultCloneDirectory') || os.homedir();
const parentPath = await window.showInputBox({
prompt: localize('parent', "Parent Directory"),
value,
ignoreFocusOut: true
});
if (!parentPath) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'no_directory' });
return;
}
const clonePromise = this.git.clone(url, parentPath);
try {
window.withProgress({ location: ProgressLocation.SourceControl, title: localize('cloning', "Cloning git repository...") }, () => clonePromise);
window.withProgress({ location: ProgressLocation.Window, title: localize('cloning', "Cloning git repository...") }, () => clonePromise);
const repositoryPath = await clonePromise;
const open = localize('openrepo', "Open Repository");
const result = await window.showInformationMessage(localize('proposeopen', "Would you like to open the cloned repository?"), open);
const openFolder = result === open;
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'success' }, { openFolder: openFolder ? 1 : 0 });
if (openFolder) {
commands.executeCommand('vscode.openFolder', Uri.file(repositoryPath));
}
} catch (err) {
if (/already exists and is not an empty directory/.test(err && err.stderr || '')) {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'directory_not_empty' });
} else {
this.telemetryReporter.sendTelemetryEvent('clone', { outcome: 'error' });
}
throw err;
}
}
示例2: Promise
context.subscriptions.push(commands.registerCommand('extension.startTask', () => {
window.withProgress({
location: ProgressLocation.Notification,
title: "I am long running!",
cancellable: true
}, (progress, token) => {
token.onCancellationRequested(() => {
console.log("User canceled the long running operation")
});
progress.report({ increment: 0 });
setTimeout(() => {
progress.report({ increment: 10, message: "I am long running! - still going..." });
}, 1000);
setTimeout(() => {
progress.report({ increment: 40, message: "I am long running! - still going even more..." });
}, 2000);
setTimeout(() => {
progress.report({ increment: 50, message: "I am long running! - almost there..." });
}, 3000);
var p = new Promise(resolve => {
setTimeout(() => {
resolve();
}, 5000);
});
return p;
});
}));
示例3: createResourceGroup
private async createResourceGroup(subscriptionItem: SubscriptionItem): Promise<ResourceGroupItem> {
const resourceGroupName = await showInputBox({
ignoreFocusOut: true,
placeHolder: 'Resource Group Name',
prompt: 'Provide a resource group name',
validateInput: WestlakeInputValidator.validateNames,
});
const locationItem = await showQuickPick(
this.getLocationItems(subscriptionItem),
{ placeHolder: 'Select a location to create your Resource Group in...', ignoreFocusOut: true },
);
return window.withProgress({
location: ProgressLocation.Notification,
title: `Creating resource group '${resourceGroupName}'`,
}, async () => {
if (subscriptionItem.subscriptionId === undefined) {
throw new Error(Constants.errorMessageStrings.NoSubscriptionFound);
} else {
const resourceManagementClient = await this.getResourceClient(subscriptionItem);
const resourceGroup = await resourceManagementClient.resourceGroups.createOrUpdate(
resourceGroupName,
{ location: locationItem.description },
);
return new ResourceGroupItem(resourceGroup.name, resourceGroup.location);
}
});
}
示例4: fetchWithCoursier
function fetchWithCoursier(coursierPath: string, artifact: string, extra: string[] = []) {
return vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: `Fetching ${ artifact }`
}, _ => {
const args = [
"-jar", coursierPath,
"fetch",
"-p",
artifact
].concat(extra)
const coursierProc = pcp.spawn("java", args)
let classPath = ""
coursierProc.stdout.on('data', (data: Buffer) => {
classPath += data.toString().trim()
})
coursierProc.stderr.on('data', (data: Buffer) => {
let msg = data.toString().trim()
outputChannel.appendLine(msg)
})
coursierProc.on('close', (code: number) => {
if (code != 0) {
let msg = `Couldn't fetch '${ artifact }' (exit code ${ code }).`
outputChannel.appendLine(msg)
throw new Error(msg)
}
})
return coursierProc.then(() => { return classPath })
})
}
示例5: localize
this._register(vscode.workspace.onDidRenameFile(e => {
vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: localize('renameProgress.title', "Checking for update of JS/TS imports")
}, () => {
return this.doRename(e.oldUri, e.newUri);
});
}));
示例6: startProgress
startProgress(message: string) {
if (this.progress != null)
this.endProgress();
window.withProgress({title: message, location: ProgressLocation.Notification}, progress => new Promise((resolve, _reject) => {
this.progress = progress;
this.resolve = resolve;
}));
}
示例7: installLinux
async function installLinux(url: string) {
const pkexec = await paths.which('pkexec');
if (!pkexec) {
vscode.window.showErrorMessage('CMake Tools needs `pkexec` program to run the CMake installer');
return;
}
const filename = path.basename(url, '.sh');
const installerPath = await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Downloading ${filename}`,
},
pr => downloadFile(url, {prefix: filename, postfix: '.sh'}, pr),
);
const res = await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Running CMake Installer',
},
() => {
const proc = execute(pkexec, [installerPath, '--exclude-subdir', '--prefix=/usr/local']);
return proc.result;
},
);
if (res.retc === 127) {
vscode.window.showErrorMessage('Failed to authorize for running the CMake installation.');
} else if (res.retc === 126) {
vscode.window.showErrorMessage('You dismissed the request for permission to perform the CMake installation.');
} else if (res.retc !== 0) {
log.error(`The CMake installer returned non-zero [${res.retc}]: `, res.stderr);
vscode.window.showErrorMessage(
'The CMake installer exited with non-zero. Check the output panel for more information');
} else {
const restartNow = 'Restart Now';
const chosen = await vscode.window.showInformationMessage(
'The new CMake is successfull installed to /usr/local/bin/cmake. Reload VSCode to complete changes.',
restartNow,
);
if (chosen === restartNow) {
vscode.commands.executeCommand('workbench.action.reloadWindow');
}
}
}
示例8: waitForServer
async function waitForServer(): Promise<net.Socket> {
let socket: net.Socket
return vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: "Connecting to sbt server..."
}, async _ => {
let retries = 60;
while (!socket && retries > 0) {
try { socket = connectSocket(new net.Socket()) }
catch (e) {
retries--;
await delay(1000);
}
}
if (socket) return Promise.resolve(socket)
else return Promise.reject()
})
}
示例9: configureIDE
function configureIDE(sbtClasspath: string, languageServerScalaVersion: string, dottyPluginSbtFile: string) {
return vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: 'Configuring the IDE for Dotty...'
}, (progress) => {
// Run sbt to configure the IDE. If the `DottyPlugin` is not present, dynamically load it and
// eventually run `configureIDE`.
const sbtPromise =
cpp.spawn("java", [
"-Dsbt.log.noformat=true",
"-classpath", sbtClasspath,
"xsbt.boot.Boot",
`--addPluginSbtFile=${dottyPluginSbtFile}`,
`set every scalaVersion := "${languageServerScalaVersion}"`,
"configureIDE"
])
const sbtProc = sbtPromise.childProcess
// Close stdin, otherwise in case of error sbt will block waiting for the
// user input to reload or exit the build.
sbtProc.stdin.end()
sbtProc.stdout.on('data', (data: Buffer) => {
let msg = data.toString().trim()
outputChannel.appendLine(msg)
})
sbtProc.stderr.on('data', (data: Buffer) => {
let msg = data.toString().trim()
outputChannel.appendLine(msg)
})
sbtProc.on('close', (code: number) => {
if (code != 0) {
const msg = "Configuring the IDE failed."
outputChannel.appendLine(msg)
throw new Error(msg)
}
})
return sbtPromise
})
}
示例10: fetchAndRun
function fetchAndRun(artifact: string) {
const coursierPath = path.join(extensionContext.extensionPath, './out/coursier');
vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: 'Fetching the Dotty Language Server'
}, (progress) => {
const coursierPromise =
cpp.spawn("java", [
"-jar", coursierPath,
"fetch",
"-p",
artifact
])
const coursierProc = coursierPromise.childProcess
let classPath = ""
coursierProc.stdout.on('data', (data: Buffer) => {
classPath += data.toString().trim()
})
coursierProc.stderr.on('data', (data: Buffer) => {
let msg = data.toString()
outputChannel.append(msg)
})
coursierProc.on('close', (code: number) => {
if (code != 0) {
let msg = "Fetching the language server failed."
outputChannel.append(msg)
throw new Error(msg)
}
run({
command: "java",
args: ["-classpath", classPath, "dotty.tools.languageserver.Main", "-stdio"]
})
})
return coursierPromise
})
}
示例11: downloadAndInstallPackages
async function downloadAndInstallPackages(info: PlatformInformation): Promise<void> {
let outputChannelLogger: Logger = getOutputChannelLogger();
outputChannelLogger.appendLine("Updating C/C++ dependencies...");
let packageManager: PackageManager = new PackageManager(info, outputChannelLogger);
return vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "C/C++ Extension",
cancellable: false
}, async (progress, token) => {
outputChannelLogger.appendLine('');
setInstallationStage('downloadPackages');
await packageManager.DownloadPackages(progress);
outputChannelLogger.appendLine('');
setInstallationStage('installPackages');
await packageManager.InstallPackages(progress);
});
}
示例12: scanForKits
export async function scanForKits(opt?: KitScanOptions) {
const kit_options = opt || {};
log.debug('Scanning for Kits on system');
const prog = {
location: vscode.ProgressLocation.Notification,
title: 'Scanning for kits',
};
return vscode.window.withProgress(prog, async pr => {
const isWin32 = process.platform === 'win32';
pr.report({message: 'Scanning for CMake kits...'});
let scanPaths: string[] = [];
// Search directories on `PATH` for compiler binaries
const pathvar = process.env['PATH']!;
if (pathvar) {
const sep = isWin32 ? ';' : ':';
scanPaths = scanPaths.concat(pathvar.split(sep));
}
// Search them all in parallel
let prs = [] as Promise<Kit[]>[];
if (isWin32 && kit_options.minGWSearchDirs) {
scanPaths = scanPaths.concat(convertMingwDirsToSearchPaths(kit_options.minGWSearchDirs));
}
const compiler_kits = scanPaths.map(path_el => scanDirForCompilerKits(path_el, pr));
prs = prs.concat(compiler_kits);
if (isWin32) {
const vs_kits = scanForVSKits(pr);
const clang_cl_path = ['C:\\Program Files (x86)\\LLVM\\bin', 'C:\\Program Files\\LLVM\\bin', ...scanPaths];
const clang_cl_kits = await scanForClangCLKits(clang_cl_path);
prs.push(vs_kits);
prs = prs.concat(clang_cl_kits);
}
const arrays = await Promise.all(prs);
const kits = ([] as Kit[]).concat(...arrays);
kits.map(k => log.info(`Found Kit: ${k.name}`));
return kits;
});
}
示例13: promptToInstallFlutterExtension
async function promptToInstallFlutterExtension(): Promise<boolean> {
const installExtension = "Install Flutter Extension";
const res = await vs.window.showInformationMessage(
"Working on a Flutter project? Install the Flutter extension for additional functionality.",
installExtension,
doNotAskAgainAction,
);
if (res === installExtension) {
await vs.window.withProgress({ location: vs.ProgressLocation.Notification },
(progress) => {
progress.report({ message: "Installing Flutter extension" });
return new Promise((resolve) => {
vs.extensions.onDidChange((e) => resolve());
vs.commands.executeCommand("workbench.extensions.installExtension", flutterExtensionIdentifier);
});
},
);
reloadExtension();
}
return res === doNotAskAgainAction;
}
示例14: activate
export function activate(context: vscode.ExtensionContext) {
function doResolve(_authority: string, progress: vscode.Progress<{ message?: string; increment?: number }>): Promise<vscode.ResolvedAuthority> {
return new Promise(async (res, rej) => {
progress.report({ message: 'Starting Test Resolver' });
outputChannel = vscode.window.createOutputChannel('TestResolver');
let isResolved = false;
async function processError(message: string) {
outputChannel.appendLine(message);
if (!isResolved) {
isResolved = true;
outputChannel.show();
const result = await vscode.window.showErrorMessage(message, { modal: true }, ...getActions());
if (result) {
await result.execute();
}
rej(vscode.RemoteAuthorityResolverError.NotAvailable(message, true));
}
}
let lastProgressLine = '';
function processOutput(output: string) {
outputChannel.append(output);
for (let i = 0; i < output.length; i++) {
const chr = output.charCodeAt(i);
if (chr === CharCode.LineFeed) {
const match = lastProgressLine.match(/Extension host agent listening on (\d+)/);
if (match) {
isResolved = true;
res(new vscode.ResolvedAuthority('localhost', parseInt(match[1], 10))); // success!
}
lastProgressLine = '';
} else if (chr === CharCode.Backspace) {
lastProgressLine = lastProgressLine.substr(0, lastProgressLine.length - 1);
} else {
lastProgressLine += output.charAt(i);
}
}
}
if (_authority === 'test+error' || vscode.workspace.getConfiguration('testresolver').get('error') === true) {
processError('Unable to start the Test Resolver.');
return;
}
const { updateUrl, commit, quality, serverDataFolderName, dataFolderName } = getProductConfiguration();
const serverCommand = process.platform === 'win32' ? 'server.bat' : 'server.sh';
const commandArgs = ['--port=0', '--disable-telemetry'];
const env = getNewEnv();
const remoteDataDir = process.env['TESTRESOLVER_DATA_FOLDER'] || path.join(os.homedir(), serverDataFolderName || `${dataFolderName}-testresolver`);
env['VSCODE_AGENT_FOLDER'] = remoteDataDir;
outputChannel.appendLine(`Using data folder at ${remoteDataDir}`);
if (!commit) { // dev mode
const vscodePath = path.resolve(path.join(context.extensionPath, '..', '..'));
const serverCommandPath = path.join(vscodePath, 'resources', 'server', 'bin-dev', serverCommand);
extHostProcess = cp.spawn(serverCommandPath, commandArgs, { env, cwd: vscodePath });
} else {
const serverBin = path.join(remoteDataDir, 'bin');
progress.report({ message: 'Installing VSCode Server' });
const serverLocation = await downloadAndUnzipVSCodeServer(updateUrl, commit, quality, serverBin);
outputChannel.appendLine(`Using server build at ${serverLocation}`);
extHostProcess = cp.spawn(path.join(serverLocation, serverCommand), commandArgs, { env, cwd: serverLocation });
}
extHostProcess.stdout.on('data', (data: Buffer) => processOutput(data.toString()));
extHostProcess.stderr.on('data', (data: Buffer) => processOutput(data.toString()));
extHostProcess.on('error', (error: Error) => processError(`server failed with error:\n${error.message}`));
extHostProcess.on('close', (code: number) => processError(`server closed unexpectedly.\nError code: ${code}`));
});
}
vscode.workspace.registerRemoteAuthorityResolver('test', {
resolve(_authority: string): Thenable<vscode.ResolvedAuthority> {
if (!startPromise) {
startPromise = vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Open TestResolver Remote ([details](command:remote-testresolver.showLog))',
cancellable: false
}, (progress) => doResolve(_authority, progress));
}
return startPromise;
}
});
vscode.commands.registerCommand('vscode-testresolver.newWindow', () => {
return vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+test' });
});
vscode.commands.registerCommand('vscode-testresolver.newWindowWithError', () => {
return vscode.commands.executeCommand('vscode.newWindow', { remoteAuthority: 'test+error' });
});
vscode.commands.registerCommand('vscode-testresolver.showLog', () => {
if (outputChannel) {
outputChannel.show();
}
});
}
示例15:
/**
* Display a progress bar with title `title` while `op` completes.
*
* @param title The title of the progress bar
* @param op The thenable that is monitored by the progress bar.
*/
function withProgress<T>(title: string, op: Thenable<T>): Thenable<T> {
return vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
title: title
}, _ => op)
}