hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "\tmax-width: var(--vscode-editor-dictation-widget-width);\n", "}\n", "\n", ".monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled {\n", "\tdisplay: flex;\n", "\talign-items: center;\n", "\twidth: 16px;\n", "\theight: 16px;\n", "}\n", "\n", ".monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled {\n", "\tcolor: var(--vscode-activityBarBadge-background);\n", "\tanimation: editor-dictation-animation 1s infinite;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css", "type": "replace", "edit_start_line_idx": 18 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use super::paths::{InstalledServer, ServerPaths}; use crate::async_pipe::get_socket_name; use crate::constants::{ APPLICATION_NAME, EDITOR_WEB_URL, QUALITYLESS_PRODUCT_NAME, QUALITYLESS_SERVER_NAME, }; use crate::download_cache::DownloadCache; use crate::options::{Quality, TelemetryLevel}; use crate::state::LauncherPaths; use crate::tunnels::paths::{get_server_folder_name, SERVER_FOLDER_NAME}; use crate::update_service::{ unzip_downloaded_release, Platform, Release, TargetKind, UpdateService, }; use crate::util::command::{ capture_command, capture_command_and_check_status, kill_tree, new_script_command, }; use crate::util::errors::{wrap, AnyError, CodeError, ExtensionInstallFailed, WrappedError}; use crate::util::http::{self, BoxedHttp}; use crate::util::io::SilentCopyProgress; use crate::util::machine::process_exists; use crate::util::prereqs::skip_requirements_check; use crate::{debug, info, log, spanf, trace, warning}; use lazy_static::lazy_static; use opentelemetry::KeyValue; use regex::Regex; use serde::Deserialize; use std::fs; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use tokio::fs::remove_file; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::{Child, Command}; use tokio::sync::oneshot::Receiver; use tokio::time::{interval, timeout}; lazy_static! { static ref LISTENING_PORT_RE: Regex = Regex::new(r"Extension host agent listening on (.+)").unwrap(); static ref WEB_UI_RE: Regex = Regex::new(r"Web UI available at (.+)").unwrap(); } #[derive(Clone, Debug, Default)] pub struct CodeServerArgs { pub host: Option<String>, pub port: Option<u16>, pub socket_path: Option<String>, // common argument pub telemetry_level: Option<TelemetryLevel>, pub log: Option<log::Level>, pub accept_server_license_terms: bool, pub verbose: bool, // extension management pub install_extensions: Vec<String>, pub uninstall_extensions: Vec<String>, pub update_extensions: bool, pub list_extensions: bool, pub show_versions: bool, pub category: Option<String>, pub pre_release: bool, pub force: bool, pub start_server: bool, // connection tokens pub connection_token: Option<String>, pub connection_token_file: Option<String>, pub without_connection_token: bool, } impl CodeServerArgs { pub fn log_level(&self) -> log::Level { if self.verbose { log::Level::Trace } else { self.log.unwrap_or(log::Level::Info) } } pub fn telemetry_disabled(&self) -> bool { self.telemetry_level == Some(TelemetryLevel::Off) } pub fn command_arguments(&self) -> Vec<String> { let mut args = Vec::new(); if let Some(i) = &self.socket_path { args.push(format!("--socket-path={}", i)); } else { if let Some(i) = &self.host { args.push(format!("--host={}", i)); } if let Some(i) = &self.port { args.push(format!("--port={}", i)); } } if let Some(i) = &self.connection_token { args.push(format!("--connection-token={}", i)); } if let Some(i) = &self.connection_token_file { args.push(format!("--connection-token-file={}", i)); } if self.without_connection_token { args.push(String::from("--without-connection-token")); } if self.accept_server_license_terms { args.push(String::from("--accept-server-license-terms")); } if let Some(i) = self.telemetry_level { args.push(format!("--telemetry-level={}", i)); } if let Some(i) = self.log { args.push(format!("--log={}", i)); } for extension in &self.install_extensions { args.push(format!("--install-extension={}", extension)); } if !&self.install_extensions.is_empty() { if self.pre_release { args.push(String::from("--pre-release")); } if self.force { args.push(String::from("--force")); } } for extension in &self.uninstall_extensions { args.push(format!("--uninstall-extension={}", extension)); } if self.update_extensions { args.push(String::from("--update-extensions")); } if self.list_extensions { args.push(String::from("--list-extensions")); if self.show_versions { args.push(String::from("--show-versions")); } if let Some(i) = &self.category { args.push(format!("--category={}", i)); } } if self.start_server { args.push(String::from("--start-server")); } args } } /// Base server params that can be `resolve()`d to a `ResolvedServerParams`. /// Doing so fetches additional information like a commit ID if previously /// unspecified. pub struct ServerParamsRaw { pub commit_id: Option<String>, pub quality: Quality, pub code_server_args: CodeServerArgs, pub headless: bool, pub platform: Platform, } /// Server params that can be used to start a VS Code server. pub struct ResolvedServerParams { pub release: Release, pub code_server_args: CodeServerArgs, } impl ResolvedServerParams { fn as_installed_server(&self) -> InstalledServer { InstalledServer { commit: self.release.commit.clone(), quality: self.release.quality, headless: self.release.target == TargetKind::Server, } } } impl ServerParamsRaw { pub async fn resolve( self, log: &log::Logger, http: BoxedHttp, ) -> Result<ResolvedServerParams, AnyError> { Ok(ResolvedServerParams { release: self.get_or_fetch_commit_id(log, http).await?, code_server_args: self.code_server_args, }) } async fn get_or_fetch_commit_id( &self, log: &log::Logger, http: BoxedHttp, ) -> Result<Release, AnyError> { let target = match self.headless { true => TargetKind::Server, false => TargetKind::Web, }; if let Some(c) = &self.commit_id { return Ok(Release { commit: c.clone(), quality: self.quality, target, name: String::new(), platform: self.platform, }); } UpdateService::new(log.clone(), http) .get_latest_commit(self.platform, target, self.quality) .await } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[allow(dead_code)] struct UpdateServerVersion { pub name: String, pub version: String, pub product_version: String, pub timestamp: i64, } /// Code server listening on a port address. #[derive(Clone)] pub struct SocketCodeServer { pub commit_id: String, pub socket: PathBuf, pub origin: Arc<CodeServerOrigin>, } /// Code server listening on a socket address. #[derive(Clone)] pub struct PortCodeServer { pub commit_id: String, pub port: u16, pub origin: Arc<CodeServerOrigin>, } /// A server listening on any address/location. pub enum AnyCodeServer { Socket(SocketCodeServer), Port(PortCodeServer), } pub enum CodeServerOrigin { /// A new code server, that opens the barrier when it exits. New(Box<Child>), /// An existing code server with a PID. Existing(u32), } impl CodeServerOrigin { pub async fn wait_for_exit(&mut self) { match self { CodeServerOrigin::New(child) => { child.wait().await.ok(); } CodeServerOrigin::Existing(pid) => { let mut interval = interval(Duration::from_secs(30)); while process_exists(*pid) { interval.tick().await; } } } } pub async fn kill(&mut self) { match self { CodeServerOrigin::New(child) => { child.kill().await.ok(); } CodeServerOrigin::Existing(pid) => { kill_tree(*pid).await.ok(); } } } } /// Ensures the given list of extensions are installed on the running server. async fn do_extension_install_on_running_server( start_script_path: &Path, extensions: &[String], log: &log::Logger, ) -> Result<(), AnyError> { if extensions.is_empty() { return Ok(()); } debug!(log, "Installing extensions..."); let command = format!( "{} {}", start_script_path.display(), extensions .iter() .map(|s| get_extensions_flag(s)) .collect::<Vec<String>>() .join(" ") ); let result = capture_command("bash", &["-c", &command]).await?; if !result.status.success() { Err(AnyError::from(ExtensionInstallFailed( String::from_utf8_lossy(&result.stderr).to_string(), ))) } else { Ok(()) } } pub struct ServerBuilder<'a> { logger: &'a log::Logger, server_params: &'a ResolvedServerParams, launcher_paths: &'a LauncherPaths, server_paths: ServerPaths, http: BoxedHttp, } impl<'a> ServerBuilder<'a> { pub fn new( logger: &'a log::Logger, server_params: &'a ResolvedServerParams, launcher_paths: &'a LauncherPaths, http: BoxedHttp, ) -> Self { Self { logger, server_params, launcher_paths, server_paths: server_params .as_installed_server() .server_paths(launcher_paths), http, } } /// Gets any already-running server from this directory. pub async fn get_running(&self) -> Result<Option<AnyCodeServer>, AnyError> { info!( self.logger, "Checking {} and {} for a running server...", self.server_paths.logfile.display(), self.server_paths.pidfile.display() ); let pid = match self.server_paths.get_running_pid() { Some(pid) => pid, None => return Ok(None), }; info!(self.logger, "Found running server (pid={})", pid); if !Path::new(&self.server_paths.logfile).exists() { warning!(self.logger, "{} Server is running but its logfile is missing. Don't delete the {} Server manually, run the command '{} prune'.", QUALITYLESS_PRODUCT_NAME, QUALITYLESS_PRODUCT_NAME, APPLICATION_NAME); return Ok(None); } do_extension_install_on_running_server( &self.server_paths.executable, &self.server_params.code_server_args.install_extensions, self.logger, ) .await?; let origin = Arc::new(CodeServerOrigin::Existing(pid)); let contents = fs::read_to_string(&self.server_paths.logfile) .expect("Something went wrong reading log file"); if let Some(port) = parse_port_from(&contents) { Ok(Some(AnyCodeServer::Port(PortCodeServer { commit_id: self.server_params.release.commit.to_owned(), port, origin, }))) } else if let Some(socket) = parse_socket_from(&contents) { Ok(Some(AnyCodeServer::Socket(SocketCodeServer { commit_id: self.server_params.release.commit.to_owned(), socket, origin, }))) } else { Ok(None) } } /// Ensures the server is set up in the configured directory. pub async fn setup(&self) -> Result<(), AnyError> { debug!( self.logger, "Installing and setting up {}...", QUALITYLESS_SERVER_NAME ); let update_service = UpdateService::new(self.logger.clone(), self.http.clone()); let name = get_server_folder_name( self.server_params.release.quality, &self.server_params.release.commit, ); self.launcher_paths .server_cache .create(name, |target_dir| async move { let tmpdir = tempfile::tempdir().map_err(|e| wrap(e, "error creating temp download dir"))?; let response = update_service .get_download_stream(&self.server_params.release) .await?; let archive_path = tmpdir.path().join(response.url_path_basename().unwrap()); info!( self.logger, "Downloading {} server -> {}", QUALITYLESS_PRODUCT_NAME, archive_path.display() ); http::download_into_file( &archive_path, self.logger.get_download_logger("server download progress:"), response, ) .await?; let server_dir = target_dir.join(SERVER_FOLDER_NAME); unzip_downloaded_release(&archive_path, &server_dir, SilentCopyProgress())?; if !skip_requirements_check().await { let output = capture_command_and_check_status( server_dir .join("bin") .join(self.server_params.release.quality.server_entrypoint()), &["--version"], ) .await .map_err(|e| wrap(e, "error checking server integrity"))?; trace!( self.logger, "Server integrity verified, version: {}", String::from_utf8_lossy(&output.stdout).replace('\n', " / ") ); } else { info!(self.logger, "Skipping server integrity check"); } Ok(()) }) .await?; debug!(self.logger, "Server setup complete"); Ok(()) } pub async fn listen_on_port(&self, port: u16) -> Result<PortCodeServer, AnyError> { let mut cmd = self.get_base_command(); cmd.arg("--start-server") .arg("--enable-remote-auto-shutdown") .arg(format!("--port={}", port)); let child = self.spawn_server_process(cmd)?; let log_file = self.get_logfile()?; let plog = self.logger.prefixed(&log::new_code_server_prefix()); let (mut origin, listen_rx) = monitor_server::<PortMatcher, u16>(child, Some(log_file), plog, false); let port = match timeout(Duration::from_secs(8), listen_rx).await { Err(e) => { origin.kill().await; Err(wrap(e, "timed out looking for port")) } Ok(Err(e)) => { origin.kill().await; Err(wrap(e, "server exited without writing port")) } Ok(Ok(p)) => Ok(p), }?; info!(self.logger, "Server started"); Ok(PortCodeServer { commit_id: self.server_params.release.commit.to_owned(), port, origin: Arc::new(origin), }) } pub async fn listen_on_default_socket(&self) -> Result<SocketCodeServer, AnyError> { let requested_file = get_socket_name(); self.listen_on_socket(&requested_file).await } pub async fn listen_on_socket(&self, socket: &Path) -> Result<SocketCodeServer, AnyError> { Ok(spanf!( self.logger, self.logger.span("server.start").with_attributes(vec! { KeyValue::new("commit_id", self.server_params.release.commit.to_string()), KeyValue::new("quality", format!("{}", self.server_params.release.quality)), }), self._listen_on_socket(socket) )?) } async fn _listen_on_socket(&self, socket: &Path) -> Result<SocketCodeServer, AnyError> { remove_file(&socket).await.ok(); // ignore any error if it doesn't exist let mut cmd = self.get_base_command(); cmd.arg("--start-server") .arg("--enable-remote-auto-shutdown") .arg(format!("--socket-path={}", socket.display())); let child = self.spawn_server_process(cmd)?; let log_file = self.get_logfile()?; let plog = self.logger.prefixed(&log::new_code_server_prefix()); let (mut origin, listen_rx) = monitor_server::<SocketMatcher, PathBuf>(child, Some(log_file), plog, false); let socket = match timeout(Duration::from_secs(30), listen_rx).await { Err(e) => { origin.kill().await; Err(wrap(e, "timed out looking for socket")) } Ok(Err(e)) => { origin.kill().await; Err(wrap(e, "server exited without writing socket")) } Ok(Ok(socket)) => Ok(socket), }?; info!(self.logger, "Server started"); Ok(SocketCodeServer { commit_id: self.server_params.release.commit.to_owned(), socket, origin: Arc::new(origin), }) } /// Starts with a given opaque set of args. Does not set up any port or /// socket, but does return one if present, in the form of a channel. pub async fn start_opaque_with_args<M, R>( &self, args: &[String], ) -> Result<(CodeServerOrigin, Receiver<R>), AnyError> where M: ServerOutputMatcher<R>, R: 'static + Send + std::fmt::Debug, { let mut cmd = self.get_base_command(); cmd.args(args); let child = self.spawn_server_process(cmd)?; let plog = self.logger.prefixed(&log::new_code_server_prefix()); Ok(monitor_server::<M, R>(child, None, plog, true)) } fn spawn_server_process(&self, mut cmd: Command) -> Result<Child, AnyError> { info!(self.logger, "Starting server..."); debug!(self.logger, "Starting server with command... {:?}", cmd); // On Windows spawning a code-server binary will run cmd.exe /c C:\path\to\code-server.cmd... // This spawns a cmd.exe window for the user, which if they close will kill the code-server process // and disconnect the tunnel. To prevent this, pass the CREATE_NO_WINDOW flag to the Command // only on Windows. // Original issue: https://github.com/microsoft/vscode/issues/184058 // Partial fix: https://github.com/microsoft/vscode/pull/184621 #[cfg(target_os = "windows")] let cmd = cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW); let child = cmd .stderr(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .spawn() .map_err(|e| wrap(e, "error spawning server"))?; self.server_paths .write_pid(child.id().expect("expected server to have pid"))?; Ok(child) } fn get_logfile(&self) -> Result<File, WrappedError> { File::create(&self.server_paths.logfile).map_err(|e| { wrap( e, format!( "error creating log file {}", self.server_paths.logfile.display() ), ) }) } fn get_base_command(&self) -> Command { let mut cmd = new_script_command(&self.server_paths.executable); cmd.stdin(std::process::Stdio::null()) .args(self.server_params.code_server_args.command_arguments()); cmd } } fn monitor_server<M, R>( mut child: Child, log_file: Option<File>, plog: log::Logger, write_directly: bool, ) -> (CodeServerOrigin, Receiver<R>) where M: ServerOutputMatcher<R>, R: 'static + Send + std::fmt::Debug, { let stdout = child .stdout .take() .expect("child did not have a handle to stdout"); let stderr = child .stderr .take() .expect("child did not have a handle to stdout"); let (listen_tx, listen_rx) = tokio::sync::oneshot::channel(); // Handle stderr and stdout in a separate task. Initially scan lines looking // for the listening port. Afterwards, just scan and write out to the file. tokio::spawn(async move { let mut stdout_reader = BufReader::new(stdout).lines(); let mut stderr_reader = BufReader::new(stderr).lines(); let write_line = |line: &str| -> std::io::Result<()> { if let Some(mut f) = log_file.as_ref() { f.write_all(line.as_bytes())?; f.write_all(&[b'\n'])?; } if write_directly { println!("{}", line); } else { trace!(plog, line); } Ok(()) }; loop { let line = tokio::select! { l = stderr_reader.next_line() => l, l = stdout_reader.next_line() => l, }; match line { Err(e) => { trace!(plog, "error reading from stdout/stderr: {}", e); return; } Ok(None) => break, Ok(Some(l)) => { write_line(&l).ok(); if let Some(listen_on) = M::match_line(&l) { trace!(plog, "parsed location: {:?}", listen_on); listen_tx.send(listen_on).ok(); break; } } } } loop { let line = tokio::select! { l = stderr_reader.next_line() => l, l = stdout_reader.next_line() => l, }; match line { Err(e) => { trace!(plog, "error reading from stdout/stderr: {}", e); break; } Ok(None) => break, Ok(Some(l)) => { write_line(&l).ok(); } } } }); let origin = CodeServerOrigin::New(Box::new(child)); (origin, listen_rx) } fn get_extensions_flag(extension_id: &str) -> String { format!("--install-extension={}", extension_id) } /// A type that can be used to scan stdout from the VS Code server. Returns /// some other type that, in turn, is returned from starting the server. pub trait ServerOutputMatcher<R> where R: Send, { fn match_line(line: &str) -> Option<R>; } /// Parses a line like "Extension host agent listening on /tmp/foo.sock" struct SocketMatcher(); impl ServerOutputMatcher<PathBuf> for SocketMatcher { fn match_line(line: &str) -> Option<PathBuf> { parse_socket_from(line) } } /// Parses a line like "Extension host agent listening on 9000" pub struct PortMatcher(); impl ServerOutputMatcher<u16> for PortMatcher { fn match_line(line: &str) -> Option<u16> { parse_port_from(line) } } /// Parses a line like "Web UI available at http://localhost:9000/?tkn=..." pub struct WebUiMatcher(); impl ServerOutputMatcher<reqwest::Url> for WebUiMatcher { fn match_line(line: &str) -> Option<reqwest::Url> { WEB_UI_RE.captures(line).and_then(|cap| { cap.get(1) .and_then(|uri| reqwest::Url::parse(uri.as_str()).ok()) }) } } /// Does not do any parsing and just immediately returns an empty result. pub struct NoOpMatcher(); impl ServerOutputMatcher<()> for NoOpMatcher { fn match_line(_: &str) -> Option<()> { Some(()) } } fn parse_socket_from(text: &str) -> Option<PathBuf> { LISTENING_PORT_RE .captures(text) .and_then(|cap| cap.get(1).map(|path| PathBuf::from(path.as_str()))) } fn parse_port_from(text: &str) -> Option<u16> { LISTENING_PORT_RE.captures(text).and_then(|cap| { cap.get(1) .and_then(|path| path.as_str().parse::<u16>().ok()) }) } pub fn print_listening(log: &log::Logger, tunnel_name: &str) { debug!( log, "{} is listening for incoming connections", QUALITYLESS_SERVER_NAME ); let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("")); let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("")); let dir = if home_dir == current_dir { PathBuf::from("") } else { current_dir }; let base_web_url = match EDITOR_WEB_URL { Some(u) => u, None => return, }; let mut addr = url::Url::parse(base_web_url).unwrap(); { let mut ps = addr.path_segments_mut().unwrap(); ps.push("tunnel"); ps.push(tunnel_name); for segment in &dir { let as_str = segment.to_string_lossy(); if !(as_str.len() == 1 && as_str.starts_with(std::path::MAIN_SEPARATOR)) { ps.push(as_str.as_ref()); } } } let message = &format!("\nOpen this link in your browser {}\n", addr); log.result(message); } pub async fn download_cli_into_cache( cache: &DownloadCache, release: &Release, update_service: &UpdateService, ) -> Result<PathBuf, AnyError> { let cache_name = format!( "{}-{}-{}", release.quality, release.commit, release.platform ); let cli_dir = cache .create(&cache_name, |target_dir| async move { let tmpdir = tempfile::tempdir().map_err(|e| wrap(e, "error creating temp download dir"))?; let response = update_service.get_download_stream(release).await?; let name = response.url_path_basename().unwrap(); let archive_path = tmpdir.path().join(name); http::download_into_file(&archive_path, SilentCopyProgress(), response).await?; unzip_downloaded_release(&archive_path, &target_dir, SilentCopyProgress())?; Ok(()) }) .await?; let cli = std::fs::read_dir(cli_dir) .map_err(|_| CodeError::CorruptDownload("could not read cli folder contents"))? .next(); match cli { Some(Ok(cli)) => Ok(cli.path()), _ => { let _ = cache.delete(&cache_name); Err(CodeError::CorruptDownload("cli directory is empty").into()) } } }
cli/src/tunnels/code_server.rs
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0002103542792610824, 0.00017028930597007275, 0.00016202400729525834, 0.0001703230373095721, 0.000004901698957837652 ]
{ "id": 0, "code_window": [ "\tmax-width: var(--vscode-editor-dictation-widget-width);\n", "}\n", "\n", ".monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled {\n", "\tdisplay: flex;\n", "\talign-items: center;\n", "\twidth: 16px;\n", "\theight: 16px;\n", "}\n", "\n", ".monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled {\n", "\tcolor: var(--vscode-activityBarBadge-background);\n", "\tanimation: editor-dictation-animation 1s infinite;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css", "type": "replace", "edit_start_line_idx": 18 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IFileService } from 'vs/platform/files/common/files'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { ILabelService } from 'vs/platform/label/common/label'; import { ILogService } from 'vs/platform/log/common/log'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkingCopyHistoryModelOptions, WorkingCopyHistoryService } from 'vs/workbench/services/workingCopy/common/workingCopyHistoryService'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IWorkingCopyHistoryService } from 'vs/workbench/services/workingCopy/common/workingCopyHistory'; export class BrowserWorkingCopyHistoryService extends WorkingCopyHistoryService { constructor( @IFileService fileService: IFileService, @IRemoteAgentService remoteAgentService: IRemoteAgentService, @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, @IUriIdentityService uriIdentityService: IUriIdentityService, @ILabelService labelService: ILabelService, @ILogService logService: ILogService, @IConfigurationService configurationService: IConfigurationService ) { super(fileService, remoteAgentService, environmentService, uriIdentityService, labelService, logService, configurationService); } protected getModelOptions(): IWorkingCopyHistoryModelOptions { return { flushOnChange: true /* because browsers support no long running shutdown */ }; } } // Register Service registerSingleton(IWorkingCopyHistoryService, BrowserWorkingCopyHistoryService, InstantiationType.Delayed);
src/vs/workbench/services/workingCopy/browser/workingCopyHistoryService.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017371150897815824, 0.00017016618221532553, 0.00016847804363351315, 0.00016923756629694253, 0.000002118239308401826 ]
{ "id": 1, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import 'vs/css!./editorDictation';\n", "import { localize2 } from 'vs/nls';\n", "import { IDimension, h, reset } from 'vs/base/browser/dom';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n", "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { localize, localize2 } from 'vs/nls';\n", "import { IDimension } from 'vs/base/browser/dom';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0011597533011808991, 0.00026642411830835044, 0.00016295364184770733, 0.00017325134831480682, 0.0002215679851360619 ]
{ "id": 1, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import 'vs/css!./editorDictation';\n", "import { localize2 } from 'vs/nls';\n", "import { IDimension, h, reset } from 'vs/base/browser/dom';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n", "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { localize, localize2 } from 'vs/nls';\n", "import { IDimension } from 'vs/base/browser/dom';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { TextDocument, getLanguageModes, ClientCapabilities, Range, Position } from '../modes/languageModes'; import { newSemanticTokenProvider } from '../modes/semanticTokens'; import { getNodeFileFS } from '../node/nodeFs'; interface ExpectedToken { startLine: number; character: number; length: number; tokenClassifiction: string; } async function assertTokens(lines: string[], expected: ExpectedToken[], ranges?: Range[], message?: string): Promise<void> { const document = TextDocument.create('test://foo/bar.html', 'html', 1, lines.join('\n')); const workspace = { settings: {}, folders: [{ name: 'foo', uri: 'test://foo' }] }; const languageModes = getLanguageModes({ css: true, javascript: true }, workspace, ClientCapabilities.LATEST, getNodeFileFS()); const semanticTokensProvider = newSemanticTokenProvider(languageModes); const legend = semanticTokensProvider.legend; const actual = await semanticTokensProvider.getSemanticTokens(document, ranges); const actualRanges = []; let lastLine = 0; let lastCharacter = 0; for (let i = 0; i < actual.length; i += 5) { const lineDelta = actual[i], charDelta = actual[i + 1], len = actual[i + 2], typeIdx = actual[i + 3], modSet = actual[i + 4]; const line = lastLine + lineDelta; const character = lineDelta === 0 ? lastCharacter + charDelta : charDelta; const tokenClassifiction = [legend.types[typeIdx], ...legend.modifiers.filter((_, i) => modSet & 1 << i)].join('.'); actualRanges.push(t(line, character, len, tokenClassifiction)); lastLine = line; lastCharacter = character; } assert.deepStrictEqual(actualRanges, expected, message); } function t(startLine: number, character: number, length: number, tokenClassifiction: string): ExpectedToken { return { startLine, character, length, tokenClassifiction }; } suite('HTML Semantic Tokens', () => { test('Variables', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script>', /*3*/' var x = 9, y1 = [x];', /*4*/' try {', /*5*/' for (const s of y1) { x = s }', /*6*/' } catch (e) {', /*7*/' throw y1;', /*8*/' }', /*9*/'</script>', /*10*/'</head>', /*11*/'</html>', ]; await assertTokens(input, [ t(3, 6, 1, 'variable.declaration'), t(3, 13, 2, 'variable.declaration'), t(3, 19, 1, 'variable'), t(5, 15, 1, 'variable.declaration.readonly.local'), t(5, 20, 2, 'variable'), t(5, 26, 1, 'variable'), t(5, 30, 1, 'variable.readonly.local'), t(6, 11, 1, 'variable.declaration.local'), t(7, 10, 2, 'variable') ]); }); test('Functions', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script>', /*3*/' function foo(p1) {', /*4*/' return foo(Math.abs(p1))', /*5*/' }', /*6*/' `/${window.location}`.split("/").forEach(s => foo(s));', /*7*/'</script>', /*8*/'</head>', /*9*/'</html>', ]; await assertTokens(input, [ t(3, 11, 3, 'function.declaration'), t(3, 15, 2, 'parameter.declaration'), t(4, 11, 3, 'function'), t(4, 15, 4, 'variable.defaultLibrary'), t(4, 20, 3, 'method.defaultLibrary'), t(4, 24, 2, 'parameter'), t(6, 6, 6, 'variable.defaultLibrary'), t(6, 13, 8, 'property.defaultLibrary'), t(6, 24, 5, 'method.defaultLibrary'), t(6, 35, 7, 'method.defaultLibrary'), t(6, 43, 1, 'parameter.declaration'), t(6, 48, 3, 'function'), t(6, 52, 1, 'parameter') ]); }); test('Members', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script>', /*3*/' class A {', /*4*/' static x = 9;', /*5*/' f = 9;', /*6*/' async m() { return A.x + await this.m(); };', /*7*/' get s() { return this.f; ', /*8*/' static t() { return new A().f; };', /*9*/' constructor() {}', /*10*/' }', /*11*/'</script>', /*12*/'</head>', /*13*/'</html>', ]; await assertTokens(input, [ t(3, 8, 1, 'class.declaration'), t(4, 11, 1, 'property.declaration.static'), t(5, 4, 1, 'property.declaration'), t(6, 10, 1, 'method.declaration.async'), t(6, 23, 1, 'class'), t(6, 25, 1, 'property.static'), t(6, 40, 1, 'method.async'), t(7, 8, 1, 'property.declaration'), t(7, 26, 1, 'property'), t(8, 11, 1, 'method.declaration.static'), t(8, 28, 1, 'class'), t(8, 32, 1, 'property'), ]); }); test('Interfaces', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script type="text/typescript">', /*3*/' interface Position { x: number, y: number };', /*4*/' const p = { x: 1, y: 2 } as Position;', /*5*/' const foo = (o: Position) => o.x + o.y;', /*6*/'</script>', /*7*/'</head>', /*8*/'</html>', ]; await assertTokens(input, [ t(3, 12, 8, 'interface.declaration'), t(3, 23, 1, 'property.declaration'), t(3, 34, 1, 'property.declaration'), t(4, 8, 1, 'variable.declaration.readonly'), t(4, 14, 1, 'property.declaration'), t(4, 20, 1, 'property.declaration'), t(4, 30, 8, 'interface'), t(5, 8, 3, 'function.declaration.readonly'), t(5, 15, 1, 'parameter.declaration'), t(5, 18, 8, 'interface'), t(5, 31, 1, 'parameter'), t(5, 33, 1, 'property'), t(5, 37, 1, 'parameter'), t(5, 39, 1, 'property') ]); }); test('Readonly', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script type="text/typescript">', /*3*/' const f = 9;', /*4*/' class A { static readonly t = 9; static url: URL; }', /*5*/' const enum E { A = 9, B = A + 1 }', /*6*/' console.log(f + A.t + A.url.origin);', /*7*/'</script>', /*8*/'</head>', /*9*/'</html>', ]; await assertTokens(input, [ t(3, 8, 1, 'variable.declaration.readonly'), t(4, 8, 1, 'class.declaration'), t(4, 28, 1, 'property.declaration.static.readonly'), t(4, 42, 3, 'property.declaration.static'), t(4, 47, 3, 'interface.defaultLibrary'), t(5, 13, 1, 'enum.declaration'), t(5, 17, 1, 'enumMember.declaration.readonly'), t(5, 24, 1, 'enumMember.declaration.readonly'), t(5, 28, 1, 'enumMember.readonly'), t(6, 2, 7, 'variable.defaultLibrary'), t(6, 10, 3, 'method.defaultLibrary'), t(6, 14, 1, 'variable.readonly'), t(6, 18, 1, 'class'), t(6, 20, 1, 'property.static.readonly'), t(6, 24, 1, 'class'), t(6, 26, 3, 'property.static'), t(6, 30, 6, 'property.readonly.defaultLibrary'), ]); }); test('Type aliases and type parameters', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script type="text/typescript">', /*3*/' type MyMap = Map<string, number>;', /*4*/' function f<T extends MyMap>(t: T | number) : T { ', /*5*/' return <T> <unknown> new Map<string, MyMap>();', /*6*/' }', /*7*/'</script>', /*8*/'</head>', /*9*/'</html>', ]; await assertTokens(input, [ t(3, 7, 5, 'type.declaration'), t(3, 15, 3, 'interface.defaultLibrary') /* to investiagte */, t(4, 11, 1, 'function.declaration'), t(4, 13, 1, 'typeParameter.declaration'), t(4, 23, 5, 'type'), t(4, 30, 1, 'parameter.declaration'), t(4, 33, 1, 'typeParameter'), t(4, 47, 1, 'typeParameter'), t(5, 12, 1, 'typeParameter'), t(5, 29, 3, 'class.defaultLibrary'), t(5, 41, 5, 'type'), ]); }); test('TS and JS', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script type="text/typescript">', /*3*/' function f<T>(p1: T): T[] { return [ p1 ]; }', /*4*/'</script>', /*5*/'<script>', /*6*/' window.alert("Hello");', /*7*/'</script>', /*8*/'</head>', /*9*/'</html>', ]; await assertTokens(input, [ t(3, 11, 1, 'function.declaration'), t(3, 13, 1, 'typeParameter.declaration'), t(3, 16, 2, 'parameter.declaration'), t(3, 20, 1, 'typeParameter'), t(3, 24, 1, 'typeParameter'), t(3, 39, 2, 'parameter'), t(6, 2, 6, 'variable.defaultLibrary'), t(6, 9, 5, 'method.defaultLibrary') ]); }); test('Ranges', async () => { const input = [ /*0*/'<html>', /*1*/'<head>', /*2*/'<script>', /*3*/' window.alert("Hello");', /*4*/'</script>', /*5*/'<script>', /*6*/' window.alert("World");', /*7*/'</script>', /*8*/'</head>', /*9*/'</html>', ]; await assertTokens(input, [ t(3, 2, 6, 'variable.defaultLibrary'), t(3, 9, 5, 'method.defaultLibrary') ], [Range.create(Position.create(2, 0), Position.create(4, 0))]); await assertTokens(input, [ t(6, 2, 6, 'variable.defaultLibrary'), ], [Range.create(Position.create(6, 2), Position.create(6, 8))]); }); });
extensions/html-language-features/server/src/test/semanticTokens.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001774337433744222, 0.0001743260509101674, 0.00016787124332040548, 0.0001749360526446253, 0.0000022520514448842732 ]
{ "id": 1, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import 'vs/css!./editorDictation';\n", "import { localize2 } from 'vs/nls';\n", "import { IDimension, h, reset } from 'vs/base/browser/dom';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n", "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { localize, localize2 } from 'vs/nls';\n", "import { IDimension } from 'vs/base/browser/dom';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 6 }
{ "displayName": "Seti File Icon Theme", "description": "A file icon theme made out of the Seti UI file icons", "themeLabel": "Seti (Visual Studio Code)" }
extensions/theme-seti/package.nls.json
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017502180708106607, 0.00017502180708106607, 0.00017502180708106607, 0.00017502180708106607, 0 ]
{ "id": 1, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import 'vs/css!./editorDictation';\n", "import { localize2 } from 'vs/nls';\n", "import { IDimension, h, reset } from 'vs/base/browser/dom';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';\n", "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { localize, localize2 } from 'vs/nls';\n", "import { IDimension } from 'vs/base/browser/dom';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { isLinux } from 'vs/base/common/platform'; import { stripComments } from 'vs/base/common/stripComments'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IFileService } from 'vs/platform/files/common/files'; import { Registry } from 'vs/platform/registry/common/platform'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; class EncryptionContribution implements IWorkbenchContribution { constructor( @IJSONEditingService private readonly jsonEditingService: IJSONEditingService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IFileService private readonly fileService: IFileService, @IStorageService private readonly storageService: IStorageService ) { this.migrateToGnomeLibsecret(); } /** * Migrate the user from using the gnome or gnome-keyring password-store to gnome-libsecret. * TODO@TylerLeonhardt: This migration can be removed in 3 months or so and then storage * can be cleaned up. */ private async migrateToGnomeLibsecret(): Promise<void> { if (!isLinux || this.storageService.getBoolean('encryption.migratedToGnomeLibsecret', StorageScope.APPLICATION, false)) { return; } try { const content = await this.fileService.readFile(this.environmentService.argvResource); const argv = JSON.parse(stripComments(content.value.toString())); if (argv['password-store'] === 'gnome' || argv['password-store'] === 'gnome-keyring') { this.jsonEditingService.write(this.environmentService.argvResource, [{ path: ['password-store'], value: 'gnome-libsecret' }], true); } this.storageService.store('encryption.migratedToGnomeLibsecret', true, StorageScope.APPLICATION, StorageTarget.USER); } catch (error) { console.error(error); } } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(EncryptionContribution, LifecyclePhase.Eventually);
src/vs/workbench/contrib/encryption/electron-sandbox/encryption.contribution.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017538950487505645, 0.00016916447202675045, 0.00016484854859299958, 0.00016698618128430098, 0.000003955947249778546 ]
{ "id": 2, "code_window": [ "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n", "import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n", "import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';\n", "import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n", "import { Codicon } from 'vs/base/common/codicons';\n", "import { EditorOption } from 'vs/editor/common/config/editorOptions';\n", "import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';\n", "import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.995703399181366, 0.03583836182951927, 0.00016315981338266283, 0.00017228571232408285, 0.1847265213727951 ]
{ "id": 2, "code_window": [ "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n", "import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n", "import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';\n", "import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n", "import { Codicon } from 'vs/base/common/codicons';\n", "import { EditorOption } from 'vs/editor/common/config/editorOptions';\n", "import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';\n", "import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import { SCMHistoryItemChangeTreeElement, SCMHistoryItemGroupTreeElement, SCMHistoryItemTreeElement, SCMViewSeparatorElement } from 'vs/workbench/contrib/scm/common/history'; import { ISCMResource, ISCMRepository, ISCMResourceGroup, ISCMInput, ISCMActionButton, ISCMViewService } from 'vs/workbench/contrib/scm/common/scm'; import { IMenu, MenuItemAction } from 'vs/platform/actions/common/actions'; import { ActionBar, IActionViewItemProvider } from 'vs/base/browser/ui/actionbar/actionbar'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Action, IAction } from 'vs/base/common/actions'; import { createActionViewItem, createAndFillInActionBarActions, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { equals } from 'vs/base/common/arrays'; import { ActionViewItem, IBaseActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Command } from 'vs/editor/common/languages'; import { reset } from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { URI } from 'vs/base/common/uri'; import { IResourceNode, ResourceTree } from 'vs/base/common/resourceTree'; export function isSCMRepositoryArray(element: any): element is ISCMRepository[] { return Array.isArray(element) && element.every(r => isSCMRepository(r)); } export function isSCMViewService(element: any): element is ISCMViewService { return Array.isArray((element as ISCMViewService).repositories) && Array.isArray((element as ISCMViewService).visibleRepositories); } export function isSCMRepository(element: any): element is ISCMRepository { return !!(element as ISCMRepository).provider && !!(element as ISCMRepository).input; } export function isSCMInput(element: any): element is ISCMInput { return !!(element as ISCMInput).validateInput && typeof (element as ISCMInput).value === 'string'; } export function isSCMActionButton(element: any): element is ISCMActionButton { return (element as ISCMActionButton).type === 'actionButton'; } export function isSCMResourceGroup(element: any): element is ISCMResourceGroup { return !!(element as ISCMResourceGroup).provider && !!(element as ISCMResourceGroup).resources; } export function isSCMResource(element: any): element is ISCMResource { return !!(element as ISCMResource).sourceUri && isSCMResourceGroup((element as ISCMResource).resourceGroup); } export function isSCMResourceNode(element: any): element is IResourceNode<ISCMResource, ISCMResourceGroup> { return ResourceTree.isResourceNode(element) && isSCMResourceGroup(element.context); } export function isSCMHistoryItemGroupTreeElement(element: any): element is SCMHistoryItemGroupTreeElement { return (element as SCMHistoryItemGroupTreeElement).type === 'historyItemGroup'; } export function isSCMHistoryItemTreeElement(element: any): element is SCMHistoryItemTreeElement { return (element as SCMHistoryItemTreeElement).type === 'allChanges' || (element as SCMHistoryItemTreeElement).type === 'historyItem'; } export function isSCMHistoryItemChangeTreeElement(element: any): element is SCMHistoryItemChangeTreeElement { return (element as SCMHistoryItemChangeTreeElement).type === 'historyItemChange'; } export function isSCMHistoryItemChangeNode(element: any): element is IResourceNode<SCMHistoryItemChangeTreeElement, SCMHistoryItemTreeElement> { return ResourceTree.isResourceNode(element) && isSCMHistoryItemTreeElement(element.context); } export function isSCMViewSeparator(element: any): element is SCMViewSeparatorElement { return (element as SCMViewSeparatorElement).type === 'separator'; } export function toDiffEditorArguments(uri: URI, originalUri: URI, modifiedUri: URI): unknown[] { const basename = path.basename(uri.fsPath); const originalQuery = JSON.parse(originalUri.query) as { path: string; ref: string }; const modifiedQuery = JSON.parse(modifiedUri.query) as { path: string; ref: string }; const originalShortRef = originalQuery.ref.substring(0, 8).concat(originalQuery.ref.endsWith('^') ? '^' : ''); const modifiedShortRef = modifiedQuery.ref.substring(0, 8).concat(modifiedQuery.ref.endsWith('^') ? '^' : ''); return [originalUri, modifiedUri, `${basename} (${originalShortRef}) ↔ ${basename} (${modifiedShortRef})`, null]; } const compareActions = (a: IAction, b: IAction) => { if (a instanceof MenuItemAction && b instanceof MenuItemAction) { return a.id === b.id && a.enabled === b.enabled && a.hideActions?.isHidden === b.hideActions?.isHidden; } return a.id === b.id && a.enabled === b.enabled; }; export function connectPrimaryMenu(menu: IMenu, callback: (primary: IAction[], secondary: IAction[]) => void, primaryGroup?: string): IDisposable { let cachedPrimary: IAction[] = []; let cachedSecondary: IAction[] = []; const updateActions = () => { const primary: IAction[] = []; const secondary: IAction[] = []; createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, { primary, secondary }, primaryGroup); if (equals(cachedPrimary, primary, compareActions) && equals(cachedSecondary, secondary, compareActions)) { return; } cachedPrimary = primary; cachedSecondary = secondary; callback(primary, secondary); }; updateActions(); return menu.onDidChange(updateActions); } export function connectPrimaryMenuToInlineActionBar(menu: IMenu, actionBar: ActionBar): IDisposable { return connectPrimaryMenu(menu, (primary) => { actionBar.clear(); actionBar.push(primary, { icon: true, label: false }); }, 'inline'); } export function collectContextMenuActions(menu: IMenu): IAction[] { const primary: IAction[] = []; const actions: IAction[] = []; createAndFillInContextMenuActions(menu, { shouldForwardArgs: true }, { primary, secondary: actions }, 'inline'); return actions; } export class StatusBarAction extends Action { constructor( private command: Command, private commandService: ICommandService ) { super(`statusbaraction{${command.id}}`, command.title, '', true); this.tooltip = command.tooltip || ''; } override run(): Promise<void> { return this.commandService.executeCommand(this.command.id, ...(this.command.arguments || [])); } } class StatusBarActionViewItem extends ActionViewItem { constructor(action: StatusBarAction, options: IBaseActionViewItemOptions) { super(null, action, { ...options, icon: false, label: true }); } protected override updateLabel(): void { if (this.options.label && this.label) { reset(this.label, ...renderLabelWithIcons(this.action.label)); } } } export function getActionViewItemProvider(instaService: IInstantiationService): IActionViewItemProvider { return (action, options) => { if (action instanceof StatusBarAction) { return new StatusBarActionViewItem(action, options); } return createActionViewItem(instaService, action, options); }; }
src/vs/workbench/contrib/scm/browser/util.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0002039525134023279, 0.000172432919498533, 0.0001653589279158041, 0.00017091637710109353, 0.000008973140211310238 ]
{ "id": 2, "code_window": [ "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n", "import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n", "import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';\n", "import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n", "import { Codicon } from 'vs/base/common/codicons';\n", "import { EditorOption } from 'vs/editor/common/config/editorOptions';\n", "import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';\n", "import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 14 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "textmate/markdown.tmbundle", "repositoryUrl": "https://github.com/textmate/markdown.tmbundle", "commitHash": "11cf764606cb2cde54badb5d0e5a0758a8871c4b" } }, "licenseDetail": [ "Copyright (c) markdown.tmbundle authors", "", "If not otherwise specified (see below), files in this repository fall under the following license:", "", "Permission to copy, use, modify, sell and distribute this", "software is granted. This software is provided \"as is\" without", "express or implied warranty, and with no claim as to its", "suitability for any purpose.", "", "An exception is made for files in readable text which contain their own license information,", "or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added", "to the base-name name of the original file, and an extension of txt, html, or similar. For example", "\"tidy\" is accompanied by \"tidy-license.txt\"." ], "license": "TextMate Bundle License", "version": "0.0.0" }, { "component": { "type": "git", "git": { "name": "microsoft/vscode-markdown-tm-grammar", "repositoryUrl": "https://github.com/microsoft/vscode-markdown-tm-grammar", "commitHash": "0b36cbbf917fb0188e1a1bafc8287c7abf8b0b37" } }, "license": "MIT", "version": "1.0.0" } ], "version": 1 }
extensions/markdown-basics/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017652871611062437, 0.0001736052508931607, 0.00016844367200974375, 0.00017422757809981704, 0.0000028313845632510493 ]
{ "id": 2, "code_window": [ "import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';\n", "import { IEditorContribution } from 'vs/editor/common/editorCommon';\n", "import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';\n", "import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService';\n", "import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n", "import { Codicon } from 'vs/base/common/codicons';\n", "import { EditorOption } from 'vs/editor/common/config/editorOptions';\n", "import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions';\n", "import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { CharCode } from 'vs/base/common/charCode'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; suite('CharCode', () => { ensureNoDisposablesAreLeakedInTestSuite(); test('has good values', () => { function assertValue(actual: CharCode, expected: string): void { assert.strictEqual(actual, expected.charCodeAt(0), 'char code ok for <<' + expected + '>>'); } assertValue(CharCode.Tab, '\t'); assertValue(CharCode.LineFeed, '\n'); assertValue(CharCode.CarriageReturn, '\r'); assertValue(CharCode.Space, ' '); assertValue(CharCode.ExclamationMark, '!'); assertValue(CharCode.DoubleQuote, '"'); assertValue(CharCode.Hash, '#'); assertValue(CharCode.DollarSign, '$'); assertValue(CharCode.PercentSign, '%'); assertValue(CharCode.Ampersand, '&'); assertValue(CharCode.SingleQuote, '\''); assertValue(CharCode.OpenParen, '('); assertValue(CharCode.CloseParen, ')'); assertValue(CharCode.Asterisk, '*'); assertValue(CharCode.Plus, '+'); assertValue(CharCode.Comma, ','); assertValue(CharCode.Dash, '-'); assertValue(CharCode.Period, '.'); assertValue(CharCode.Slash, '/'); assertValue(CharCode.Digit0, '0'); assertValue(CharCode.Digit1, '1'); assertValue(CharCode.Digit2, '2'); assertValue(CharCode.Digit3, '3'); assertValue(CharCode.Digit4, '4'); assertValue(CharCode.Digit5, '5'); assertValue(CharCode.Digit6, '6'); assertValue(CharCode.Digit7, '7'); assertValue(CharCode.Digit8, '8'); assertValue(CharCode.Digit9, '9'); assertValue(CharCode.Colon, ':'); assertValue(CharCode.Semicolon, ';'); assertValue(CharCode.LessThan, '<'); assertValue(CharCode.Equals, '='); assertValue(CharCode.GreaterThan, '>'); assertValue(CharCode.QuestionMark, '?'); assertValue(CharCode.AtSign, '@'); assertValue(CharCode.A, 'A'); assertValue(CharCode.B, 'B'); assertValue(CharCode.C, 'C'); assertValue(CharCode.D, 'D'); assertValue(CharCode.E, 'E'); assertValue(CharCode.F, 'F'); assertValue(CharCode.G, 'G'); assertValue(CharCode.H, 'H'); assertValue(CharCode.I, 'I'); assertValue(CharCode.J, 'J'); assertValue(CharCode.K, 'K'); assertValue(CharCode.L, 'L'); assertValue(CharCode.M, 'M'); assertValue(CharCode.N, 'N'); assertValue(CharCode.O, 'O'); assertValue(CharCode.P, 'P'); assertValue(CharCode.Q, 'Q'); assertValue(CharCode.R, 'R'); assertValue(CharCode.S, 'S'); assertValue(CharCode.T, 'T'); assertValue(CharCode.U, 'U'); assertValue(CharCode.V, 'V'); assertValue(CharCode.W, 'W'); assertValue(CharCode.X, 'X'); assertValue(CharCode.Y, 'Y'); assertValue(CharCode.Z, 'Z'); assertValue(CharCode.OpenSquareBracket, '['); assertValue(CharCode.Backslash, '\\'); assertValue(CharCode.CloseSquareBracket, ']'); assertValue(CharCode.Caret, '^'); assertValue(CharCode.Underline, '_'); assertValue(CharCode.BackTick, '`'); assertValue(CharCode.a, 'a'); assertValue(CharCode.b, 'b'); assertValue(CharCode.c, 'c'); assertValue(CharCode.d, 'd'); assertValue(CharCode.e, 'e'); assertValue(CharCode.f, 'f'); assertValue(CharCode.g, 'g'); assertValue(CharCode.h, 'h'); assertValue(CharCode.i, 'i'); assertValue(CharCode.j, 'j'); assertValue(CharCode.k, 'k'); assertValue(CharCode.l, 'l'); assertValue(CharCode.m, 'm'); assertValue(CharCode.n, 'n'); assertValue(CharCode.o, 'o'); assertValue(CharCode.p, 'p'); assertValue(CharCode.q, 'q'); assertValue(CharCode.r, 'r'); assertValue(CharCode.s, 's'); assertValue(CharCode.t, 't'); assertValue(CharCode.u, 'u'); assertValue(CharCode.v, 'v'); assertValue(CharCode.w, 'w'); assertValue(CharCode.x, 'x'); assertValue(CharCode.y, 'y'); assertValue(CharCode.z, 'z'); assertValue(CharCode.OpenCurlyBrace, '{'); assertValue(CharCode.Pipe, '|'); assertValue(CharCode.CloseCurlyBrace, '}'); assertValue(CharCode.Tilde, '~'); }); });
src/vs/base/test/common/charCode.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017478982044849545, 0.0001734056422719732, 0.00016929965931922197, 0.00017409339488949627, 0.000001432042495252972 ]
{ "id": 3, "code_window": [ "import { Range } from 'vs/editor/common/core/range';\n", "import { registerAction2 } from 'vs/platform/actions/common/actions';\n", "import { assertIsDefined } from 'vs/base/common/types';\n", "\n", "const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false);\n", "const VOICE_CATEGORY = localize2('voiceCategory', \"Voice\");\n", "\n", "export class EditorDictationStartAction extends EditorAction2 {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { toAction } from 'vs/base/common/actions';\n", "import { ThemeIcon } from 'vs/base/common/themables';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9993535876274109, 0.18064619600772858, 0.00016420705651398748, 0.00022225818247534335, 0.38170334696769714 ]
{ "id": 3, "code_window": [ "import { Range } from 'vs/editor/common/core/range';\n", "import { registerAction2 } from 'vs/platform/actions/common/actions';\n", "import { assertIsDefined } from 'vs/base/common/types';\n", "\n", "const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false);\n", "const VOICE_CATEGORY = localize2('voiceCategory', \"Voice\");\n", "\n", "export class EditorDictationStartAction extends EditorAction2 {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { toAction } from 'vs/base/common/actions';\n", "import { ThemeIcon } from 'vs/base/common/themables';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/auxiliaryBarPart'; import { localize } from 'vs/nls'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { contrastBorder } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ActiveAuxiliaryContext, AuxiliaryBarFocusContext } from 'vs/workbench/common/contextkeys'; import { ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_BADGE_FOREGROUND, PANEL_ACTIVE_TITLE_BORDER, PANEL_ACTIVE_TITLE_FOREGROUND, PANEL_DRAG_AND_DROP_BORDER, PANEL_INACTIVE_TITLE_FOREGROUND, SIDE_BAR_BACKGROUND, SIDE_BAR_BORDER, SIDE_BAR_FOREGROUND } from 'vs/workbench/common/theme'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService, Parts, Position } from 'vs/workbench/services/layout/browser/layoutService'; import { HoverPosition } from 'vs/base/browser/ui/hover/hoverWidget'; import { IAction, Separator, toAction } from 'vs/base/common/actions'; import { ToggleAuxiliaryBarAction } from 'vs/workbench/browser/parts/auxiliarybar/auxiliaryBarActions'; import { assertIsDefined } from 'vs/base/common/types'; import { LayoutPriority } from 'vs/base/browser/ui/splitview/splitview'; import { ToggleSidebarPositionAction } from 'vs/workbench/browser/actions/layoutActions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { AbstractPaneCompositePart } from 'vs/workbench/browser/parts/paneCompositePart'; import { ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; import { IPaneCompositeBarOptions } from 'vs/workbench/browser/parts/paneCompositeBar'; import { IMenuService } from 'vs/platform/actions/common/actions'; export class AuxiliaryBarPart extends AbstractPaneCompositePart { static readonly activePanelSettingsKey = 'workbench.auxiliarybar.activepanelid'; static readonly pinnedPanelsKey = 'workbench.auxiliarybar.pinnedPanels'; static readonly placeholdeViewContainersKey = 'workbench.auxiliarybar.placeholderPanels'; static readonly viewContainersWorkspaceStateKey = 'workbench.auxiliarybar.viewContainersWorkspaceState'; // Use the side bar dimensions override readonly minimumWidth: number = 170; override readonly maximumWidth: number = Number.POSITIVE_INFINITY; override readonly minimumHeight: number = 0; override readonly maximumHeight: number = Number.POSITIVE_INFINITY; get preferredHeight(): number | undefined { // Don't worry about titlebar or statusbar visibility // The difference is minimal and keeps this function clean return this.layoutService.mainContainerDimension.height * 0.4; } get preferredWidth(): number | undefined { const activeComposite = this.getActivePaneComposite(); if (!activeComposite) { return; } const width = activeComposite.getOptimalWidth(); if (typeof width !== 'number') { return; } return Math.max(width, 300); } readonly priority: LayoutPriority = LayoutPriority.Low; constructor( @INotificationService notificationService: INotificationService, @IStorageService storageService: IStorageService, @IContextMenuService contextMenuService: IContextMenuService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IExtensionService extensionService: IExtensionService, @ICommandService private commandService: ICommandService, @IMenuService menuService: IMenuService, ) { super( Parts.AUXILIARYBAR_PART, { hasTitle: true, borderWidth: () => (this.getColor(SIDE_BAR_BORDER) || this.getColor(contrastBorder)) ? 1 : 0, }, AuxiliaryBarPart.activePanelSettingsKey, ActiveAuxiliaryContext.bindTo(contextKeyService), AuxiliaryBarFocusContext.bindTo(contextKeyService), 'auxiliarybar', 'auxiliarybar', undefined, notificationService, storageService, contextMenuService, layoutService, keybindingService, instantiationService, themeService, viewDescriptorService, contextKeyService, extensionService, menuService, ); } override updateStyles(): void { super.updateStyles(); const container = assertIsDefined(this.getContainer()); container.style.backgroundColor = this.getColor(SIDE_BAR_BACKGROUND) || ''; const borderColor = this.getColor(SIDE_BAR_BORDER) || this.getColor(contrastBorder); const isPositionLeft = this.layoutService.getSideBarPosition() === Position.RIGHT; container.style.color = this.getColor(SIDE_BAR_FOREGROUND) || ''; container.style.borderLeftColor = borderColor ?? ''; container.style.borderRightColor = borderColor ?? ''; container.style.borderLeftStyle = borderColor && !isPositionLeft ? 'solid' : 'none'; container.style.borderRightStyle = borderColor && isPositionLeft ? 'solid' : 'none'; container.style.borderLeftWidth = borderColor && !isPositionLeft ? '1px' : '0px'; container.style.borderRightWidth = borderColor && isPositionLeft ? '1px' : '0px'; } protected getCompositeBarOptions(): IPaneCompositeBarOptions { return { partContainerClass: 'auxiliarybar', pinnedViewContainersKey: AuxiliaryBarPart.pinnedPanelsKey, placeholderViewContainersKey: AuxiliaryBarPart.placeholdeViewContainersKey, viewContainersWorkspaceStateKey: AuxiliaryBarPart.viewContainersWorkspaceStateKey, icon: true, orientation: ActionsOrientation.HORIZONTAL, recomputeSizes: true, activityHoverOptions: { position: () => HoverPosition.BELOW, }, fillExtraContextMenuActions: actions => this.fillExtraContextMenuActions(actions), compositeSize: 0, iconSize: 16, overflowActionSize: 44, colors: theme => ({ activeBackgroundColor: theme.getColor(SIDE_BAR_BACKGROUND), inactiveBackgroundColor: theme.getColor(SIDE_BAR_BACKGROUND), activeBorderBottomColor: theme.getColor(PANEL_ACTIVE_TITLE_BORDER), activeForegroundColor: theme.getColor(PANEL_ACTIVE_TITLE_FOREGROUND), inactiveForegroundColor: theme.getColor(PANEL_INACTIVE_TITLE_FOREGROUND), badgeBackground: theme.getColor(ACTIVITY_BAR_BADGE_BACKGROUND), badgeForeground: theme.getColor(ACTIVITY_BAR_BADGE_FOREGROUND), dragAndDropBorder: theme.getColor(PANEL_DRAG_AND_DROP_BORDER) }), compact: true }; } private fillExtraContextMenuActions(actions: IAction[]): void { const currentPositionRight = this.layoutService.getSideBarPosition() === Position.LEFT; const viewsSubmenuAction = this.getViewsSubmenuAction(); if (viewsSubmenuAction) { actions.push(new Separator()); actions.push(viewsSubmenuAction); } actions.push(...[ new Separator(), toAction({ id: ToggleSidebarPositionAction.ID, label: currentPositionRight ? localize('move second side bar left', "Move Secondary Side Bar Left") : localize('move second side bar right', "Move Secondary Side Bar Right"), run: () => this.commandService.executeCommand(ToggleSidebarPositionAction.ID) }), toAction({ id: ToggleAuxiliaryBarAction.ID, label: localize('hide second side bar', "Hide Secondary Side Bar"), run: () => this.commandService.executeCommand(ToggleAuxiliaryBarAction.ID) }) ]); } protected shouldShowCompositeBar(): boolean { return true; } override toJSON(): object { return { type: Parts.AUXILIARYBAR_PART }; } }
src/vs/workbench/browser/parts/auxiliarybar/auxiliaryBarPart.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00026192571385763586, 0.0001742615713737905, 0.00016480877820868045, 0.00016824575141072273, 0.00002115158895321656 ]
{ "id": 3, "code_window": [ "import { Range } from 'vs/editor/common/core/range';\n", "import { registerAction2 } from 'vs/platform/actions/common/actions';\n", "import { assertIsDefined } from 'vs/base/common/types';\n", "\n", "const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false);\n", "const VOICE_CATEGORY = localize2('voiceCategory', \"Voice\");\n", "\n", "export class EditorDictationStartAction extends EditorAction2 {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { toAction } from 'vs/base/common/actions';\n", "import { ThemeIcon } from 'vs/base/common/themables';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IServerChannel } from 'vs/base/parts/ipc/common/ipc'; import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider'; import { Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ILogService } from 'vs/platform/log/common/log'; import { IURITransformer } from 'vs/base/common/uriIpc'; import { URI, UriComponents } from 'vs/base/common/uri'; import { VSBuffer } from 'vs/base/common/buffer'; import { ReadableStreamEventPayload, listenStream } from 'vs/base/common/stream'; import { IStat, IFileReadStreamOptions, IFileWriteOptions, IFileOpenOptions, IFileDeleteOptions, IFileOverwriteOptions, IFileChange, IWatchOptions, FileType, IFileAtomicReadOptions } from 'vs/platform/files/common/files'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { IRecursiveWatcherOptions } from 'vs/platform/files/common/watcher'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; export interface ISessionFileWatcher extends IDisposable { watch(req: number, resource: URI, opts: IWatchOptions): IDisposable; } /** * A server implementation for a IPC based file system provider client. */ export abstract class AbstractDiskFileSystemProviderChannel<T> extends Disposable implements IServerChannel<T> { constructor( protected readonly provider: DiskFileSystemProvider, protected readonly logService: ILogService ) { super(); } call(ctx: T, command: string, arg?: any): Promise<any> { const uriTransformer = this.getUriTransformer(ctx); switch (command) { case 'stat': return this.stat(uriTransformer, arg[0]); case 'readdir': return this.readdir(uriTransformer, arg[0]); case 'open': return this.open(uriTransformer, arg[0], arg[1]); case 'close': return this.close(arg[0]); case 'read': return this.read(arg[0], arg[1], arg[2]); case 'readFile': return this.readFile(uriTransformer, arg[0], arg[1]); case 'write': return this.write(arg[0], arg[1], arg[2], arg[3], arg[4]); case 'writeFile': return this.writeFile(uriTransformer, arg[0], arg[1], arg[2]); case 'rename': return this.rename(uriTransformer, arg[0], arg[1], arg[2]); case 'copy': return this.copy(uriTransformer, arg[0], arg[1], arg[2]); case 'cloneFile': return this.cloneFile(uriTransformer, arg[0], arg[1]); case 'mkdir': return this.mkdir(uriTransformer, arg[0]); case 'delete': return this.delete(uriTransformer, arg[0], arg[1]); case 'watch': return this.watch(uriTransformer, arg[0], arg[1], arg[2], arg[3]); case 'unwatch': return this.unwatch(arg[0], arg[1]); } throw new Error(`IPC Command ${command} not found`); } listen(ctx: T, event: string, arg: any): Event<any> { const uriTransformer = this.getUriTransformer(ctx); switch (event) { case 'fileChange': return this.onFileChange(uriTransformer, arg[0]); case 'readFileStream': return this.onReadFileStream(uriTransformer, arg[0], arg[1]); } throw new Error(`Unknown event ${event}`); } protected abstract getUriTransformer(ctx: T): IURITransformer; protected abstract transformIncoming(uriTransformer: IURITransformer, _resource: UriComponents, supportVSCodeResource?: boolean): URI; //#region File Metadata Resolving private stat(uriTransformer: IURITransformer, _resource: UriComponents): Promise<IStat> { const resource = this.transformIncoming(uriTransformer, _resource, true); return this.provider.stat(resource); } private readdir(uriTransformer: IURITransformer, _resource: UriComponents): Promise<[string, FileType][]> { const resource = this.transformIncoming(uriTransformer, _resource); return this.provider.readdir(resource); } //#endregion //#region File Reading/Writing private async readFile(uriTransformer: IURITransformer, _resource: UriComponents, opts?: IFileAtomicReadOptions): Promise<VSBuffer> { const resource = this.transformIncoming(uriTransformer, _resource, true); const buffer = await this.provider.readFile(resource, opts); return VSBuffer.wrap(buffer); } private onReadFileStream(uriTransformer: IURITransformer, _resource: URI, opts: IFileReadStreamOptions): Event<ReadableStreamEventPayload<VSBuffer>> { const resource = this.transformIncoming(uriTransformer, _resource, true); const cts = new CancellationTokenSource(); const emitter = new Emitter<ReadableStreamEventPayload<VSBuffer>>({ onDidRemoveLastListener: () => { // Ensure to cancel the read operation when there is no more // listener on the other side to prevent unneeded work. cts.cancel(); } }); const fileStream = this.provider.readFileStream(resource, opts, cts.token); listenStream(fileStream, { onData: chunk => emitter.fire(VSBuffer.wrap(chunk)), onError: error => emitter.fire(error), onEnd: () => { // Forward event emitter.fire('end'); // Cleanup emitter.dispose(); cts.dispose(); } }); return emitter.event; } private writeFile(uriTransformer: IURITransformer, _resource: UriComponents, content: VSBuffer, opts: IFileWriteOptions): Promise<void> { const resource = this.transformIncoming(uriTransformer, _resource); return this.provider.writeFile(resource, content.buffer, opts); } private open(uriTransformer: IURITransformer, _resource: UriComponents, opts: IFileOpenOptions): Promise<number> { const resource = this.transformIncoming(uriTransformer, _resource, true); return this.provider.open(resource, opts); } private close(fd: number): Promise<void> { return this.provider.close(fd); } private async read(fd: number, pos: number, length: number): Promise<[VSBuffer, number]> { const buffer = VSBuffer.alloc(length); const bufferOffset = 0; // offset is 0 because we create a buffer to read into for each call const bytesRead = await this.provider.read(fd, pos, buffer.buffer, bufferOffset, length); return [buffer, bytesRead]; } private write(fd: number, pos: number, data: VSBuffer, offset: number, length: number): Promise<number> { return this.provider.write(fd, pos, data.buffer, offset, length); } //#endregion //#region Move/Copy/Delete/Create Folder private mkdir(uriTransformer: IURITransformer, _resource: UriComponents): Promise<void> { const resource = this.transformIncoming(uriTransformer, _resource); return this.provider.mkdir(resource); } protected delete(uriTransformer: IURITransformer, _resource: UriComponents, opts: IFileDeleteOptions): Promise<void> { const resource = this.transformIncoming(uriTransformer, _resource); return this.provider.delete(resource, opts); } private rename(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents, opts: IFileOverwriteOptions): Promise<void> { const source = this.transformIncoming(uriTransformer, _source); const target = this.transformIncoming(uriTransformer, _target); return this.provider.rename(source, target, opts); } private copy(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents, opts: IFileOverwriteOptions): Promise<void> { const source = this.transformIncoming(uriTransformer, _source); const target = this.transformIncoming(uriTransformer, _target); return this.provider.copy(source, target, opts); } //#endregion //#region Clone File private cloneFile(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents): Promise<void> { const source = this.transformIncoming(uriTransformer, _source); const target = this.transformIncoming(uriTransformer, _target); return this.provider.cloneFile(source, target); } //#endregion //#region File Watching private readonly sessionToWatcher = new Map<string /* session ID */, ISessionFileWatcher>(); private readonly watchRequests = new Map<string /* session ID + request ID */, IDisposable>(); private onFileChange(uriTransformer: IURITransformer, sessionId: string): Event<IFileChange[] | string> { // We want a specific emitter for the given session so that events // from the one session do not end up on the other session. As such // we create a `SessionFileWatcher` and a `Emitter` for that session. const emitter = new Emitter<IFileChange[] | string>({ onWillAddFirstListener: () => { this.sessionToWatcher.set(sessionId, this.createSessionFileWatcher(uriTransformer, emitter)); }, onDidRemoveLastListener: () => { dispose(this.sessionToWatcher.get(sessionId)); this.sessionToWatcher.delete(sessionId); } }); return emitter.event; } private async watch(uriTransformer: IURITransformer, sessionId: string, req: number, _resource: UriComponents, opts: IWatchOptions): Promise<void> { const watcher = this.sessionToWatcher.get(sessionId); if (watcher) { const resource = this.transformIncoming(uriTransformer, _resource); const disposable = watcher.watch(req, resource, opts); this.watchRequests.set(sessionId + req, disposable); } } private async unwatch(sessionId: string, req: number): Promise<void> { const id = sessionId + req; const disposable = this.watchRequests.get(id); if (disposable) { dispose(disposable); this.watchRequests.delete(id); } } protected abstract createSessionFileWatcher(uriTransformer: IURITransformer, emitter: Emitter<IFileChange[] | string>): ISessionFileWatcher; //#endregion override dispose(): void { super.dispose(); for (const [, disposable] of this.watchRequests) { disposable.dispose(); } this.watchRequests.clear(); for (const [, disposable] of this.sessionToWatcher) { disposable.dispose(); } this.sessionToWatcher.clear(); } } export abstract class AbstractSessionFileWatcher extends Disposable implements ISessionFileWatcher { private readonly watcherRequests = new Map<number, IDisposable>(); // To ensure we use one file watcher per session, we keep a // disk file system provider instantiated for this session. // The provider is cheap and only stateful when file watching // starts. // // This is important because we want to ensure that we only // forward events from the watched paths for this session and // not other clients that asked to watch other paths. private readonly fileWatcher = this._register(new DiskFileSystemProvider(this.logService, { watcher: { recursive: this.getRecursiveWatcherOptions(this.environmentService) } })); constructor( private readonly uriTransformer: IURITransformer, sessionEmitter: Emitter<IFileChange[] | string>, private readonly logService: ILogService, private readonly environmentService: IEnvironmentService ) { super(); this.registerListeners(sessionEmitter); } private registerListeners(sessionEmitter: Emitter<IFileChange[] | string>): void { const localChangeEmitter = this._register(new Emitter<readonly IFileChange[]>()); this._register(localChangeEmitter.event((events) => { sessionEmitter.fire( events.map(e => ({ resource: this.uriTransformer.transformOutgoingURI(e.resource), type: e.type, cId: e.cId })) ); })); this._register(this.fileWatcher.onDidChangeFile(events => localChangeEmitter.fire(events))); this._register(this.fileWatcher.onDidWatchError(error => sessionEmitter.fire(error))); } protected getRecursiveWatcherOptions(environmentService: IEnvironmentService): IRecursiveWatcherOptions | undefined { return undefined; // subclasses can override } protected getExtraExcludes(environmentService: IEnvironmentService): string[] | undefined { return undefined; // subclasses can override } watch(req: number, resource: URI, opts: IWatchOptions): IDisposable { const extraExcludes = this.getExtraExcludes(this.environmentService); if (Array.isArray(extraExcludes)) { opts.excludes = [...opts.excludes, ...extraExcludes]; } this.watcherRequests.set(req, this.fileWatcher.watch(resource, opts)); return toDisposable(() => { dispose(this.watcherRequests.get(req)); this.watcherRequests.delete(req); }); } override dispose(): void { for (const [, disposable] of this.watcherRequests) { disposable.dispose(); } this.watcherRequests.clear(); super.dispose(); } }
src/vs/platform/files/node/diskFileSystemProviderServer.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017674581613391638, 0.00017145866877399385, 0.00016472865536343306, 0.00017135580128524452, 0.000002911917817982612 ]
{ "id": 3, "code_window": [ "import { Range } from 'vs/editor/common/core/range';\n", "import { registerAction2 } from 'vs/platform/actions/common/actions';\n", "import { assertIsDefined } from 'vs/base/common/types';\n", "\n", "const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false);\n", "const VOICE_CATEGORY = localize2('voiceCategory', \"Voice\");\n", "\n", "export class EditorDictationStartAction extends EditorAction2 {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { toAction } from 'vs/base/common/actions';\n", "import { ThemeIcon } from 'vs/base/common/themables';\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ require('./build/gulpfile');
gulpfile.js
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017629253852646798, 0.00017629253852646798, 0.00017629253852646798, 0.00017629253852646798, 0 ]
{ "id": 4, "code_window": [ "\t}\n", "}\n", "\n", "export class EditorDictationStopAction extends EditorAction2 {\n", "\n", "\tconstructor() {\n", "\t\tsuper({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tstatic readonly ID = 'workbench.action.editorDictation.stop';\n", "\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9993200302124023, 0.0778152123093605, 0.0001656194363022223, 0.00025072196149267256, 0.2552735507488251 ]
{ "id": 4, "code_window": [ "\t}\n", "}\n", "\n", "export class EditorDictationStopAction extends EditorAction2 {\n", "\n", "\tconstructor() {\n", "\t\tsuper({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tstatic readonly ID = 'workbench.action.editorDictation.stop';\n", "\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const withDefaults = require('../shared.webpack.config'); module.exports = withDefaults({ context: __dirname, resolve: { mainFields: ['module', 'main'] }, entry: { extension: './src/extension.ts', } });
extensions/simple-browser/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017838335770647973, 0.00017549358017276973, 0.00017268562805838883, 0.0001754117402015254, 0.0000023268080440175254 ]
{ "id": 4, "code_window": [ "\t}\n", "}\n", "\n", "export class EditorDictationStopAction extends EditorAction2 {\n", "\n", "\tconstructor() {\n", "\t\tsuper({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tstatic readonly ID = 'workbench.action.editorDictation.stop';\n", "\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as glob from 'vs/base/common/glob'; import { URI, UriComponents } from 'vs/base/common/uri'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { isDocumentExcludePattern, TransientCellMetadata, TransientDocumentMetadata } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; CommandsRegistry.registerCommand('_resolveNotebookContentProvider', (accessor): { viewType: string; displayName: string; options: { transientOutputs: boolean; transientCellMetadata: TransientCellMetadata; transientDocumentMetadata: TransientDocumentMetadata }; filenamePattern: (string | glob.IRelativePattern | { include: string | glob.IRelativePattern; exclude: string | glob.IRelativePattern })[]; }[] => { const notebookService = accessor.get<INotebookService>(INotebookService); const contentProviders = notebookService.getContributedNotebookTypes(); return contentProviders.map(provider => { const filenamePatterns = provider.selectors.map(selector => { if (typeof selector === 'string') { return selector; } if (glob.isRelativePattern(selector)) { return selector; } if (isDocumentExcludePattern(selector)) { return { include: selector.include, exclude: selector.exclude }; } return null; }).filter(pattern => pattern !== null) as (string | glob.IRelativePattern | { include: string | glob.IRelativePattern; exclude: string | glob.IRelativePattern })[]; return { viewType: provider.id, displayName: provider.displayName, filenamePattern: filenamePatterns, options: { transientCellMetadata: provider.options.transientCellMetadata, transientDocumentMetadata: provider.options.transientDocumentMetadata, transientOutputs: provider.options.transientOutputs } }; }); }); CommandsRegistry.registerCommand('_resolveNotebookKernels', async (accessor, args: { viewType: string; uri: UriComponents; }): Promise<{ id?: string; label: string; description?: string; detail?: string; isPreferred?: boolean; preloads?: URI[]; }[]> => { const notebookKernelService = accessor.get(INotebookKernelService); const uri = URI.revive(args.uri as UriComponents); const kernels = notebookKernelService.getMatchingKernel({ uri, viewType: args.viewType }); return kernels.all.map(provider => ({ id: provider.id, label: provider.label, description: provider.description, detail: provider.detail, isPreferred: false, // todo@jrieken,@rebornix preloads: provider.preloadUris, })); });
src/vs/workbench/contrib/notebook/browser/controller/apiActions.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017547498282510787, 0.00017202763410750777, 0.00016856577713042498, 0.00017180862778332084, 0.000002212608023910434 ]
{ "id": 4, "code_window": [ "\t}\n", "}\n", "\n", "export class EditorDictationStopAction extends EditorAction2 {\n", "\n", "\tconstructor() {\n", "\t\tsuper({\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\tstatic readonly ID = 'workbench.action.editorDictation.stop';\n", "\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { VSDataTransfer } from 'vs/base/common/dataTransfer'; import { ITreeViewsDnDService as ITreeViewsDnDServiceCommon, TreeViewsDnDService } from 'vs/editor/common/services/treeViewsDnd'; export interface ITreeViewsDnDService extends ITreeViewsDnDServiceCommon<VSDataTransfer> { } export const ITreeViewsDnDService = createDecorator<ITreeViewsDnDService>('treeViewsDndService'); registerSingleton(ITreeViewsDnDService, TreeViewsDnDService, InstantiationType.Delayed);
src/vs/editor/common/services/treeViewsDndService.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017425947589799762, 0.00016997041529975832, 0.000165681354701519, 0.00016997041529975832, 0.000004289060598239303 ]
{ "id": 5, "code_window": [ "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.editorDictation.stop',\n", "\t\t\ttitle: localize2('stopDictation', \"Stop Dictation in Editor\"),\n", "\t\t\tcategory: VOICE_CATEGORY,\n", "\t\t\tprecondition: EDITOR_DICTATION_IN_PROGRESS,\n", "\t\t\tf1: true,\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tid: EditorDictationStopAction.ID,\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.7450531125068665, 0.027315985411405563, 0.00016399049491155893, 0.00017266534268856049, 0.13813315331935883 ]
{ "id": 5, "code_window": [ "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.editorDictation.stop',\n", "\t\t\ttitle: localize2('stopDictation', \"Stop Dictation in Editor\"),\n", "\t\t\tcategory: VOICE_CATEGORY,\n", "\t\t\tprecondition: EDITOR_DICTATION_IN_PROGRESS,\n", "\t\t\tf1: true,\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tid: EditorDictationStopAction.ID,\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getAllCodicons } from 'vs/base/common/codicons'; import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema'; import { OperatingSystem, Platform, PlatformToString } from 'vs/base/common/platform'; import { localize } from 'vs/nls'; import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { IExtensionTerminalProfile, ITerminalProfile, TerminalSettingId } from 'vs/platform/terminal/common/terminal'; import { createProfileSchemaEnums } from 'vs/platform/terminal/common/terminalProfiles'; export const terminalColorSchema: IJSONSchema = { type: ['string', 'null'], enum: [ 'terminal.ansiBlack', 'terminal.ansiRed', 'terminal.ansiGreen', 'terminal.ansiYellow', 'terminal.ansiBlue', 'terminal.ansiMagenta', 'terminal.ansiCyan', 'terminal.ansiWhite' ], default: null }; export const terminalIconSchema: IJSONSchema = { type: 'string', enum: Array.from(getAllCodicons(), icon => icon.id), markdownEnumDescriptions: Array.from(getAllCodicons(), icon => `$(${icon.id})`), }; const terminalProfileBaseProperties: IJSONSchemaMap = { args: { description: localize('terminalProfile.args', 'An optional set of arguments to run the shell executable with.'), type: 'array', items: { type: 'string' } }, overrideName: { description: localize('terminalProfile.overrideName', 'Whether or not to replace the dynamic terminal title that detects what program is running with the static profile name.'), type: 'boolean' }, icon: { description: localize('terminalProfile.icon', 'A codicon ID to associate with the terminal icon.'), ...terminalIconSchema }, color: { description: localize('terminalProfile.color', 'A theme color ID to associate with the terminal icon.'), ...terminalColorSchema }, env: { markdownDescription: localize('terminalProfile.env', "An object with environment variables that will be added to the terminal profile process. Set to `null` to delete environment variables from the base environment."), type: 'object', additionalProperties: { type: ['string', 'null'] }, default: {} } }; const terminalProfileSchema: IJSONSchema = { type: 'object', required: ['path'], properties: { path: { description: localize('terminalProfile.path', 'A single path to a shell executable or an array of paths that will be used as fallbacks when one fails.'), type: ['string', 'array'], items: { type: 'string' } }, ...terminalProfileBaseProperties } }; const terminalAutomationProfileSchema: IJSONSchema = { type: 'object', required: ['path'], properties: { path: { description: localize('terminalAutomationProfile.path', 'A single path to a shell executable.'), type: ['string'], items: { type: 'string' } }, ...terminalProfileBaseProperties } }; function createTerminalProfileMarkdownDescription(platform: Platform.Linux | Platform.Mac | Platform.Windows): string { const key = platform === Platform.Linux ? 'linux' : platform === Platform.Mac ? 'osx' : 'windows'; return localize( { key: 'terminal.integrated.profile', comment: ['{0} is the platform, {1} is a code block, {2} and {3} are a link start and end'] }, "A set of terminal profile customizations for {0} which allows adding, removing or changing how terminals are launched. Profiles are made up of a mandatory path, optional arguments and other presentation options.\n\nTo override an existing profile use its profile name as the key, for example:\n\n{1}\n\n{2}Read more about configuring profiles{3}.", PlatformToString(platform), '```json\n"terminal.integrated.profile.' + key + '": {\n "bash": null\n}\n```', '[', '](https://code.visualstudio.com/docs/terminal/profiles)' ); } const terminalPlatformConfiguration: IConfigurationNode = { id: 'terminal', order: 100, title: localize('terminalIntegratedConfigurationTitle', "Integrated Terminal"), type: 'object', properties: { [TerminalSettingId.AutomationProfileLinux]: { restricted: true, markdownDescription: localize('terminal.integrated.automationProfile.linux', "The terminal profile to use on Linux for automation-related terminal usage like tasks and debug."), type: ['object', 'null'], default: null, 'anyOf': [ { type: 'null' }, terminalAutomationProfileSchema ], defaultSnippets: [ { body: { path: '${1}', icon: '${2}' } } ] }, [TerminalSettingId.AutomationProfileMacOs]: { restricted: true, markdownDescription: localize('terminal.integrated.automationProfile.osx', "The terminal profile to use on macOS for automation-related terminal usage like tasks and debug."), type: ['object', 'null'], default: null, 'anyOf': [ { type: 'null' }, terminalAutomationProfileSchema ], defaultSnippets: [ { body: { path: '${1}', icon: '${2}' } } ] }, [TerminalSettingId.AutomationProfileWindows]: { restricted: true, markdownDescription: localize('terminal.integrated.automationProfile.windows', "The terminal profile to use for automation-related terminal usage like tasks and debug. This setting will currently be ignored if {0} (now deprecated) is set.", '`terminal.integrated.automationShell.windows`'), type: ['object', 'null'], default: null, 'anyOf': [ { type: 'null' }, terminalAutomationProfileSchema ], defaultSnippets: [ { body: { path: '${1}', icon: '${2}' } } ] }, [TerminalSettingId.ProfilesWindows]: { restricted: true, markdownDescription: createTerminalProfileMarkdownDescription(Platform.Windows), type: 'object', default: { 'PowerShell': { source: 'PowerShell', icon: 'terminal-powershell' }, 'Command Prompt': { path: [ '${env:windir}\\Sysnative\\cmd.exe', '${env:windir}\\System32\\cmd.exe' ], args: [], icon: 'terminal-cmd' }, 'Git Bash': { source: 'Git Bash' } }, additionalProperties: { 'anyOf': [ { type: 'object', required: ['source'], properties: { source: { description: localize('terminalProfile.windowsSource', 'A profile source that will auto detect the paths to the shell. Note that non-standard executable locations are not supported and must be created manually in a new profile.'), enum: ['PowerShell', 'Git Bash'] }, ...terminalProfileBaseProperties } }, { type: 'object', required: ['extensionIdentifier', 'id', 'title'], properties: { extensionIdentifier: { description: localize('terminalProfile.windowsExtensionIdentifier', 'The extension that contributed this profile.'), type: 'string' }, id: { description: localize('terminalProfile.windowsExtensionId', 'The id of the extension terminal'), type: 'string' }, title: { description: localize('terminalProfile.windowsExtensionTitle', 'The name of the extension terminal'), type: 'string' }, ...terminalProfileBaseProperties } }, { type: 'null' }, terminalProfileSchema ] } }, [TerminalSettingId.ProfilesMacOs]: { restricted: true, markdownDescription: createTerminalProfileMarkdownDescription(Platform.Mac), type: 'object', default: { 'bash': { path: 'bash', args: ['-l'], icon: 'terminal-bash' }, 'zsh': { path: 'zsh', args: ['-l'] }, 'fish': { path: 'fish', args: ['-l'] }, 'tmux': { path: 'tmux', icon: 'terminal-tmux' }, 'pwsh': { path: 'pwsh', icon: 'terminal-powershell' } }, additionalProperties: { 'anyOf': [ { type: 'object', required: ['extensionIdentifier', 'id', 'title'], properties: { extensionIdentifier: { description: localize('terminalProfile.osxExtensionIdentifier', 'The extension that contributed this profile.'), type: 'string' }, id: { description: localize('terminalProfile.osxExtensionId', 'The id of the extension terminal'), type: 'string' }, title: { description: localize('terminalProfile.osxExtensionTitle', 'The name of the extension terminal'), type: 'string' }, ...terminalProfileBaseProperties } }, { type: 'null' }, terminalProfileSchema ] } }, [TerminalSettingId.ProfilesLinux]: { restricted: true, markdownDescription: createTerminalProfileMarkdownDescription(Platform.Linux), type: 'object', default: { 'bash': { path: 'bash', icon: 'terminal-bash' }, 'zsh': { path: 'zsh' }, 'fish': { path: 'fish' }, 'tmux': { path: 'tmux', icon: 'terminal-tmux' }, 'pwsh': { path: 'pwsh', icon: 'terminal-powershell' } }, additionalProperties: { 'anyOf': [ { type: 'object', required: ['extensionIdentifier', 'id', 'title'], properties: { extensionIdentifier: { description: localize('terminalProfile.linuxExtensionIdentifier', 'The extension that contributed this profile.'), type: 'string' }, id: { description: localize('terminalProfile.linuxExtensionId', 'The id of the extension terminal'), type: 'string' }, title: { description: localize('terminalProfile.linuxExtensionTitle', 'The name of the extension terminal'), type: 'string' }, ...terminalProfileBaseProperties } }, { type: 'null' }, terminalProfileSchema ] } }, [TerminalSettingId.UseWslProfiles]: { description: localize('terminal.integrated.useWslProfiles', 'Controls whether or not WSL distros are shown in the terminal dropdown'), type: 'boolean', default: true }, [TerminalSettingId.InheritEnv]: { scope: ConfigurationScope.APPLICATION, description: localize('terminal.integrated.inheritEnv', "Whether new shells should inherit their environment from VS Code, which may source a login shell to ensure $PATH and other development variables are initialized. This has no effect on Windows."), type: 'boolean', default: true }, [TerminalSettingId.PersistentSessionScrollback]: { scope: ConfigurationScope.APPLICATION, markdownDescription: localize('terminal.integrated.persistentSessionScrollback', "Controls the maximum amount of lines that will be restored when reconnecting to a persistent terminal session. Increasing this will restore more lines of scrollback at the cost of more memory and increase the time it takes to connect to terminals on start up. This setting requires a restart to take effect and should be set to a value less than or equal to `#terminal.integrated.scrollback#`."), type: 'number', default: 100 }, [TerminalSettingId.ShowLinkHover]: { scope: ConfigurationScope.APPLICATION, description: localize('terminal.integrated.showLinkHover', "Whether to show hovers for links in the terminal output."), type: 'boolean', default: true }, [TerminalSettingId.IgnoreProcessNames]: { markdownDescription: localize('terminal.integrated.confirmIgnoreProcesses', "A set of process names to ignore when using the {0} setting.", '`#terminal.integrated.confirmOnKill#`'), type: 'array', items: { type: 'string', uniqueItems: true }, default: [ // Popular prompt programs, these should not count as child processes 'starship', 'oh-my-posh', // Git bash may runs a subprocess of itself (bin\bash.exe -> usr\bin\bash.exe) 'bash', 'zsh', ] } } }; /** * Registers terminal configurations required by shared process and remote server. */ export function registerTerminalPlatformConfiguration() { Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration(terminalPlatformConfiguration); registerTerminalDefaultProfileConfiguration(); } let defaultProfilesConfiguration: IConfigurationNode | undefined; export function registerTerminalDefaultProfileConfiguration(detectedProfiles?: { os: OperatingSystem; profiles: ITerminalProfile[] }, extensionContributedProfiles?: readonly IExtensionTerminalProfile[]) { const registry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); let profileEnum; if (detectedProfiles) { profileEnum = createProfileSchemaEnums(detectedProfiles?.profiles, extensionContributedProfiles); } const oldDefaultProfilesConfiguration = defaultProfilesConfiguration; defaultProfilesConfiguration = { id: 'terminal', order: 100, title: localize('terminalIntegratedConfigurationTitle', "Integrated Terminal"), type: 'object', properties: { [TerminalSettingId.DefaultProfileLinux]: { restricted: true, markdownDescription: localize('terminal.integrated.defaultProfile.linux', "The default terminal profile on Linux."), type: ['string', 'null'], default: null, enum: detectedProfiles?.os === OperatingSystem.Linux ? profileEnum?.values : undefined, markdownEnumDescriptions: detectedProfiles?.os === OperatingSystem.Linux ? profileEnum?.markdownDescriptions : undefined }, [TerminalSettingId.DefaultProfileMacOs]: { restricted: true, markdownDescription: localize('terminal.integrated.defaultProfile.osx', "The default terminal profile on macOS."), type: ['string', 'null'], default: null, enum: detectedProfiles?.os === OperatingSystem.Macintosh ? profileEnum?.values : undefined, markdownEnumDescriptions: detectedProfiles?.os === OperatingSystem.Macintosh ? profileEnum?.markdownDescriptions : undefined }, [TerminalSettingId.DefaultProfileWindows]: { restricted: true, markdownDescription: localize('terminal.integrated.defaultProfile.windows', "The default terminal profile on Windows."), type: ['string', 'null'], default: null, enum: detectedProfiles?.os === OperatingSystem.Windows ? profileEnum?.values : undefined, markdownEnumDescriptions: detectedProfiles?.os === OperatingSystem.Windows ? profileEnum?.markdownDescriptions : undefined }, } }; registry.updateConfigurations({ add: [defaultProfilesConfiguration], remove: oldDefaultProfilesConfiguration ? [oldDefaultProfilesConfiguration] : [] }); }
src/vs/platform/terminal/common/terminalPlatformConfiguration.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00048672608681954443, 0.0001881620701169595, 0.00016628230514470488, 0.00017175174434669316, 0.00006375204975483939 ]
{ "id": 5, "code_window": [ "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.editorDictation.stop',\n", "\t\t\ttitle: localize2('stopDictation', \"Stop Dictation in Editor\"),\n", "\t\t\tcategory: VOICE_CATEGORY,\n", "\t\t\tprecondition: EDITOR_DICTATION_IN_PROGRESS,\n", "\t\t\tf1: true,\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tid: EditorDictationStopAction.ID,\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import severity from 'vs/base/common/severity'; import { isObject, isString } from 'vs/base/common/types'; import { generateUuid } from 'vs/base/common/uuid'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDebugConfiguration, IDebugSession, IExpression, INestingReplElement, IReplElement, IReplElementSource, IStackFrame } from 'vs/workbench/contrib/debug/common/debug'; import { ExpressionContainer } from 'vs/workbench/contrib/debug/common/debugModel'; const MAX_REPL_LENGTH = 10000; let topReplElementCounter = 0; const getUniqueId = () => `topReplElement:${topReplElementCounter++}`; /** * General case of data from DAP the `output` event. {@link ReplVariableElement} * is used instead only if there is a `variablesReference` with no `output` text. */ export class ReplOutputElement implements INestingReplElement { private _count = 1; private _onDidChangeCount = new Emitter<void>(); constructor( public session: IDebugSession, private id: string, public value: string, public severity: severity, public sourceData?: IReplElementSource, public readonly expression?: IExpression, ) { } toString(includeSource = false): string { let valueRespectCount = this.value; for (let i = 1; i < this.count; i++) { valueRespectCount += (valueRespectCount.endsWith('\n') ? '' : '\n') + this.value; } const sourceStr = (this.sourceData && includeSource) ? ` ${this.sourceData.source.name}` : ''; return valueRespectCount + sourceStr; } getId(): string { return this.id; } getChildren(): Promise<IReplElement[]> { return this.expression?.getChildren() || Promise.resolve([]); } set count(value: number) { this._count = value; this._onDidChangeCount.fire(); } get count(): number { return this._count; } get onDidChangeCount(): Event<void> { return this._onDidChangeCount.event; } get hasChildren() { return !!this.expression?.hasChildren; } } /** Top-level variable logged via DAP output when there's no `output` string */ export class ReplVariableElement implements INestingReplElement { public readonly hasChildren: boolean; private readonly id = generateUuid(); constructor( public readonly expression: IExpression, public readonly severity: severity, public readonly sourceData?: IReplElementSource, ) { this.hasChildren = expression.hasChildren; } getChildren(): IReplElement[] | Promise<IReplElement[]> { return this.expression.getChildren(); } toString(): string { return this.expression.toString(); } getId(): string { return this.id; } } export class RawObjectReplElement implements IExpression, INestingReplElement { private static readonly MAX_CHILDREN = 1000; // upper bound of children per value constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { } getId(): string { return this.id; } get value(): string { if (this.valueObj === null) { return 'null'; } else if (Array.isArray(this.valueObj)) { return `Array[${this.valueObj.length}]`; } else if (isObject(this.valueObj)) { return 'Object'; } else if (isString(this.valueObj)) { return `"${this.valueObj}"`; } return String(this.valueObj) || ''; } get hasChildren(): boolean { return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0); } evaluateLazy(): Promise<void> { throw new Error('Method not implemented.'); } getChildren(): Promise<IExpression[]> { let result: IExpression[] = []; if (Array.isArray(this.valueObj)) { result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v)); } else if (isObject(this.valueObj)) { result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key])); } return Promise.resolve(result); } toString(): string { return `${this.name}\n${this.value}`; } } export class ReplEvaluationInput implements IReplElement { private id: string; constructor(public value: string) { this.id = generateUuid(); } toString(): string { return this.value; } getId(): string { return this.id; } } export class ReplEvaluationResult extends ExpressionContainer implements IReplElement { private _available = true; get available(): boolean { return this._available; } constructor(public readonly originalExpression: string) { super(undefined, undefined, 0, generateUuid()); } override async evaluateExpression(expression: string, session: IDebugSession | undefined, stackFrame: IStackFrame | undefined, context: string): Promise<boolean> { const result = await super.evaluateExpression(expression, session, stackFrame, context); this._available = result; return result; } override toString(): string { return `${this.value}`; } } export class ReplGroup implements INestingReplElement { private children: IReplElement[] = []; private id: string; private ended = false; static COUNTER = 0; constructor( public name: string, public autoExpand: boolean, public sourceData?: IReplElementSource ) { this.id = `replGroup:${ReplGroup.COUNTER++}`; } get hasChildren() { return true; } getId(): string { return this.id; } toString(includeSource = false): string { const sourceStr = (includeSource && this.sourceData) ? ` ${this.sourceData.source.name}` : ''; return this.name + sourceStr; } addChild(child: IReplElement): void { const lastElement = this.children.length ? this.children[this.children.length - 1] : undefined; if (lastElement instanceof ReplGroup && !lastElement.hasEnded) { lastElement.addChild(child); } else { this.children.push(child); } } getChildren(): IReplElement[] { return this.children; } end(): void { const lastElement = this.children.length ? this.children[this.children.length - 1] : undefined; if (lastElement instanceof ReplGroup && !lastElement.hasEnded) { lastElement.end(); } else { this.ended = true; } } get hasEnded(): boolean { return this.ended; } } function areSourcesEqual(first: IReplElementSource | undefined, second: IReplElementSource | undefined): boolean { if (!first && !second) { return true; } if (first && second) { return first.column === second.column && first.lineNumber === second.lineNumber && first.source.uri.toString() === second.source.uri.toString(); } return false; } export interface INewReplElementData { output: string; expression?: IExpression; sev: severity; source?: IReplElementSource; } export class ReplModel { private replElements: IReplElement[] = []; private readonly _onDidChangeElements = new Emitter<void>(); readonly onDidChangeElements = this._onDidChangeElements.event; constructor(private readonly configurationService: IConfigurationService) { } getReplElements(): IReplElement[] { return this.replElements; } async addReplExpression(session: IDebugSession, stackFrame: IStackFrame | undefined, name: string): Promise<void> { this.addReplElement(new ReplEvaluationInput(name)); const result = new ReplEvaluationResult(name); await result.evaluateExpression(name, session, stackFrame, 'repl'); this.addReplElement(result); } appendToRepl(session: IDebugSession, { output, expression, sev, source }: INewReplElementData): void { const clearAnsiSequence = '\u001b[2J'; const clearAnsiIndex = output.lastIndexOf(clearAnsiSequence); if (clearAnsiIndex !== -1) { // [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php this.removeReplExpressions(); this.appendToRepl(session, { output: nls.localize('consoleCleared', "Console was cleared"), sev: severity.Ignore }); output = output.substring(clearAnsiIndex + clearAnsiSequence.length); } if (expression) { // if there is an output string, prefer to show that, since the DA could // have formatted it nicely e.g. with ANSI color codes. this.addReplElement(output ? new ReplOutputElement(session, getUniqueId(), output, sev, source, expression) : new ReplVariableElement(expression, sev, source)); return; } const previousElement = this.replElements.length ? this.replElements[this.replElements.length - 1] : undefined; if (previousElement instanceof ReplOutputElement && previousElement.severity === sev) { const config = this.configurationService.getValue<IDebugConfiguration>('debug'); if (previousElement.value === output && areSourcesEqual(previousElement.sourceData, source) && config.console.collapseIdenticalLines) { previousElement.count++; // No need to fire an event, just the count updates and badge will adjust automatically return; } if (!previousElement.value.endsWith('\n') && !previousElement.value.endsWith('\r\n') && previousElement.count === 1) { this.replElements[this.replElements.length - 1] = new ReplOutputElement( session, getUniqueId(), previousElement.value + output, sev, source); this._onDidChangeElements.fire(); return; } } const element = new ReplOutputElement(session, getUniqueId(), output, sev, source); this.addReplElement(element); } startGroup(name: string, autoExpand: boolean, sourceData?: IReplElementSource): void { const group = new ReplGroup(name, autoExpand, sourceData); this.addReplElement(group); } endGroup(): void { const lastElement = this.replElements[this.replElements.length - 1]; if (lastElement instanceof ReplGroup) { lastElement.end(); } } private addReplElement(newElement: IReplElement): void { const lastElement = this.replElements.length ? this.replElements[this.replElements.length - 1] : undefined; if (lastElement instanceof ReplGroup && !lastElement.hasEnded) { lastElement.addChild(newElement); } else { this.replElements.push(newElement); if (this.replElements.length > MAX_REPL_LENGTH) { this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH); } } this._onDidChangeElements.fire(); } removeReplExpressions(): void { if (this.replElements.length > 0) { this.replElements = []; this._onDidChangeElements.fire(); } } /** Returns a new REPL model that's a copy of this one. */ clone() { const newRepl = new ReplModel(this.configurationService); newRepl.replElements = this.replElements.slice(); return newRepl; } }
src/vs/workbench/contrib/debug/common/replModel.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0007758552092127502, 0.00022214467753656209, 0.0001656491367612034, 0.00017220235895365477, 0.00014854807523079216 ]
{ "id": 5, "code_window": [ "\tconstructor() {\n", "\t\tsuper({\n", "\t\t\tid: 'workbench.action.editorDictation.stop',\n", "\t\t\ttitle: localize2('stopDictation', \"Stop Dictation in Editor\"),\n", "\t\t\tcategory: VOICE_CATEGORY,\n", "\t\t\tprecondition: EDITOR_DICTATION_IN_PROGRESS,\n", "\t\t\tf1: true,\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tid: EditorDictationStopAction.ID,\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import 'mocha'; import * as vscode from 'vscode'; import { joinLines } from './util'; const testFileA = workspaceFile('a.md'); const debug = false; function debugLog(...args: any[]) { if (debug) { console.log(...args); } } function workspaceFile(...segments: string[]) { return vscode.Uri.joinPath(vscode.workspace.workspaceFolders![0].uri, ...segments); } async function getLinksForFile(file: vscode.Uri): Promise<vscode.DocumentLink[]> { debugLog('getting links', file.toString(), Date.now()); const r = (await vscode.commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', file, /*linkResolveCount*/ 100))!; debugLog('got links', file.toString(), Date.now()); return r; } (vscode.env.uiKind === vscode.UIKind.Web ? suite.skip : suite)('Markdown Document links', () => { setup(async () => { // the tests make the assumption that link providers are already registered await vscode.extensions.getExtension('vscode.markdown-language-features')!.activate(); }); teardown(async () => { await vscode.commands.executeCommand('workbench.action.closeAllEditors'); }); test('Should navigate to markdown file', async () => { await withFileContents(testFileA, '[b](b.md)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('b.md')); }); test('Should navigate to markdown file with leading ./', async () => { await withFileContents(testFileA, '[b](./b.md)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('b.md')); }); test('Should navigate to markdown file with leading /', async () => { await withFileContents(testFileA, '[b](./b.md)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('b.md')); }); test('Should navigate to markdown file without file extension', async () => { await withFileContents(testFileA, '[b](b)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('b.md')); }); test('Should navigate to markdown file in directory', async () => { await withFileContents(testFileA, '[b](sub/c)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('sub', 'c.md')); }); test('Should navigate to fragment by title in file', async () => { await withFileContents(testFileA, '[b](sub/c#second)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('sub', 'c.md')); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1); }); test('Should navigate to fragment by line', async () => { await withFileContents(testFileA, '[b](sub/c#L2)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('sub', 'c.md')); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1); }); test('Should navigate to line number within non-md file', async () => { await withFileContents(testFileA, '[b](sub/foo.txt#L3)'); const [link] = await getLinksForFile(testFileA); await executeLink(link); assertActiveDocumentUri(workspaceFile('sub', 'foo.txt')); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2); }); test('Should navigate to fragment within current file', async () => { await withFileContents(testFileA, joinLines( '[](a#header)', '[](#header)', '# Header')); const links = await getLinksForFile(testFileA); { await executeLink(links[0]); assertActiveDocumentUri(workspaceFile('a.md')); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2); } { await executeLink(links[1]); assertActiveDocumentUri(workspaceFile('a.md')); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2); } }); test.skip('Should navigate to fragment within current untitled file', async () => { // TODO: skip for now for ls migration const testFile = workspaceFile('x.md').with({ scheme: 'untitled' }); await withFileContents(testFile, joinLines( '[](#second)', '# Second')); const [link] = await getLinksForFile(testFile); await executeLink(link); assertActiveDocumentUri(testFile); assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1); }); }); function assertActiveDocumentUri(expectedUri: vscode.Uri) { assert.strictEqual( vscode.window.activeTextEditor!.document.uri.fsPath, expectedUri.fsPath ); } async function withFileContents(file: vscode.Uri, contents: string): Promise<void> { debugLog('openTextDocument', file.toString(), Date.now()); const document = await vscode.workspace.openTextDocument(file); debugLog('showTextDocument', file.toString(), Date.now()); const editor = await vscode.window.showTextDocument(document); debugLog('editTextDocument', file.toString(), Date.now()); await editor.edit(edit => { edit.replace(new vscode.Range(0, 0, 1000, 0), contents); }); debugLog('opened done', vscode.window.activeTextEditor?.document.toString(), Date.now()); } async function executeLink(link: vscode.DocumentLink) { debugLog('executingLink', link.target?.toString(), Date.now()); await vscode.commands.executeCommand('vscode.open', link.target!); debugLog('executedLink', vscode.window.activeTextEditor?.document.toString(), Date.now()); }
extensions/markdown-language-features/src/test/documentLink.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001757393911248073, 0.00017173538799397647, 0.00016166738350875676, 0.00017288324306719005, 0.0000034058325582009275 ]
{ "id": 6, "code_window": [ "\treadonly allowEditorOverflow = true;\n", "\n", "\tprivate readonly domNode = document.createElement('div');\n", "\tprivate readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 96 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9978469610214233, 0.06770472228527069, 0.00016468421381432563, 0.0001711401273496449, 0.24366495013237 ]
{ "id": 6, "code_window": [ "\treadonly allowEditorOverflow = true;\n", "\n", "\tprivate readonly domNode = document.createElement('div');\n", "\tprivate readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 96 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { EditorService } from 'vs/workbench/services/editor/browser/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput'; import { IWorkingCopyEditorHandler, WorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService'; import { createEditorPart, registerTestResourceEditor, TestEditorService, TestServiceAccessor, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestWorkingCopy } from 'vs/workbench/test/common/workbenchTestServices'; suite('WorkingCopyEditorService', () => { const disposables = new DisposableStore(); setup(() => { disposables.add(registerTestResourceEditor()); }); teardown(() => { disposables.clear(); }); test('registry - basics', () => { const service = disposables.add(new WorkingCopyEditorService(disposables.add(new TestEditorService()))); let handlerEvent: IWorkingCopyEditorHandler | undefined = undefined; disposables.add(service.onDidRegisterHandler(handler => { handlerEvent = handler; })); const editorHandler: IWorkingCopyEditorHandler = { handles: workingCopy => false, isOpen: () => false, createEditor: workingCopy => { throw new Error(); } }; disposables.add(service.registerHandler(editorHandler)); assert.strictEqual(handlerEvent, editorHandler); }); test('findEditor', async () => { const disposables = new DisposableStore(); const instantiationService = workbenchInstantiationService(undefined, disposables); const part = await createEditorPart(instantiationService, disposables); instantiationService.stub(IEditorGroupsService, part); const editorService = disposables.add(instantiationService.createInstance(EditorService, undefined)); const accessor = instantiationService.createInstance(TestServiceAccessor); const service = disposables.add(new WorkingCopyEditorService(editorService)); const resource = URI.parse('custom://some/folder/custom.txt'); const testWorkingCopy = disposables.add(new TestWorkingCopy(resource, false, 'testWorkingCopyTypeId1')); assert.strictEqual(service.findEditor(testWorkingCopy), undefined); const editorHandler: IWorkingCopyEditorHandler = { handles: workingCopy => workingCopy === testWorkingCopy, isOpen: (workingCopy, editor) => workingCopy === testWorkingCopy, createEditor: workingCopy => { throw new Error(); } }; disposables.add(service.registerHandler(editorHandler)); const editor1 = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' }))); const editor2 = disposables.add(instantiationService.createInstance(UntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' }))); await editorService.openEditors([{ editor: editor1 }, { editor: editor2 }]); assert.ok(service.findEditor(testWorkingCopy)); disposables.dispose(); }); ensureNoDisposablesAreLeakedInTestSuite(); });
src/vs/workbench/services/workingCopy/test/browser/workingCopyEditorService.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00020093366038054228, 0.0001747849164530635, 0.00016597167996224016, 0.000168954225955531, 0.00001075649015547242 ]
{ "id": 6, "code_window": [ "\treadonly allowEditorOverflow = true;\n", "\n", "\tprivate readonly domNode = document.createElement('div');\n", "\tprivate readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 96 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/[email protected]": version "18.15.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.15.13.tgz#f64277c341150c979e42b00e4ac289290c9df469" integrity sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q== "@types/which@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/which/-/which-2.0.0.tgz#446d35586611dee657120de8e0457382a658fc25" integrity sha512-JHTNOEpZnACQdsTojWggn+SQ8IucfqEhtz7g8Z0G67WdSj4x3F0X5I2c/CVcl8z/QukGrIHeQ/N49v1au74XFQ== isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= which@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0"
extensions/php-language-features/yarn.lock
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00016870710533112288, 0.00016738359408918768, 0.00016631987818982452, 0.00016712381329853088, 9.917424677041708e-7 ]
{ "id": 6, "code_window": [ "\treadonly allowEditorOverflow = true;\n", "\n", "\tprivate readonly domNode = document.createElement('div');\n", "\tprivate readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 96 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .webview.modified { box-shadow: -6px 0 5px -5px var(--vscode-scrollbar-shadow); }
src/vs/workbench/contrib/customEditor/browser/media/customEditor.css
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017547616153024137, 0.00017547616153024137, 0.00017547616153024137, 0.00017547616153024137, 0 ]
{ "id": 7, "code_window": [ "\n", "\tconstructor(private readonly editor: ICodeEditor) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tconstructor(private readonly editor: ICodeEditor, keybindingService: IKeybindingService) {\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .editor-dictation-widget { background-color: var(--vscode-editor-background); padding: 2px; border-radius: 8px; display: flex; align-items: center; box-shadow: 0 4px 8px var(--vscode-widget-shadow); z-index: 1000; min-height: var(--vscode-editor-dictation-widget-height); line-height: var(--vscode-editor-dictation-widget-height); max-width: var(--vscode-editor-dictation-widget-width); } .monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled { display: flex; align-items: center; width: 16px; height: 16px; } .monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled { color: var(--vscode-activityBarBadge-background); animation: editor-dictation-animation 1s infinite; } @keyframes editor-dictation-animation { 0% { color: var(--vscode-editorCursor-background); } 50% { color: var(--vscode-activityBarBadge-background); } 100% { color: var(--vscode-editorCursor-background); } }
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017265880887862295, 0.00016984711692202836, 0.0001678794069448486, 0.00016907555982470512, 0.000001673604174357024 ]
{ "id": 7, "code_window": [ "\n", "\tconstructor(private readonly editor: ICodeEditor) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tconstructor(private readonly editor: ICodeEditor, keybindingService: IKeybindingService) {\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc'; import { ILogService } from 'vs/platform/log/common/log'; import { IUserDataProfilesService, reviveProfile } from 'vs/platform/userDataProfile/common/userDataProfile'; import { IUserDataManualSyncTask, IUserDataSyncResourceConflicts, IUserDataSyncResourceError, IUserDataSyncResource, ISyncResourceHandle, IUserDataSyncTask, IUserDataSyncService, SyncResource, SyncStatus, UserDataSyncError } from 'vs/platform/userDataSync/common/userDataSync'; type ManualSyncTaskEvent<T> = { manualSyncTaskId: string; data: T }; function reviewSyncResource(syncResource: IUserDataSyncResource, userDataProfilesService: IUserDataProfilesService): IUserDataSyncResource { return { ...syncResource, profile: reviveProfile(syncResource.profile, userDataProfilesService.profilesHome.scheme) }; } function reviewSyncResourceHandle(syncResourceHandle: ISyncResourceHandle): ISyncResourceHandle { return { created: syncResourceHandle.created, uri: URI.revive(syncResourceHandle.uri) }; } export class UserDataSyncServiceChannel implements IServerChannel { private readonly manualSyncTasks = new Map<string, IUserDataManualSyncTask>(); private readonly onManualSynchronizeResources = new Emitter<ManualSyncTaskEvent<[SyncResource, URI[]][]>>(); constructor( private readonly service: IUserDataSyncService, private readonly userDataProfilesService: IUserDataProfilesService, private readonly logService: ILogService ) { } listen(_: unknown, event: string): Event<any> { switch (event) { // sync case 'onDidChangeStatus': return this.service.onDidChangeStatus; case 'onDidChangeConflicts': return this.service.onDidChangeConflicts; case 'onDidChangeLocal': return this.service.onDidChangeLocal; case 'onDidChangeLastSyncTime': return this.service.onDidChangeLastSyncTime; case 'onSyncErrors': return this.service.onSyncErrors; case 'onDidResetLocal': return this.service.onDidResetLocal; case 'onDidResetRemote': return this.service.onDidResetRemote; // manual sync case 'manualSync/onSynchronizeResources': return this.onManualSynchronizeResources.event; } throw new Error(`[UserDataSyncServiceChannel] Event not found: ${event}`); } async call(context: any, command: string, args?: any): Promise<any> { try { const result = await this._call(context, command, args); return result; } catch (e) { this.logService.error(e); throw e; } } private async _call(context: any, command: string, args?: any): Promise<any> { switch (command) { // sync case '_getInitialData': return Promise.resolve([this.service.status, this.service.conflicts, this.service.lastSyncTime]); case 'reset': return this.service.reset(); case 'resetRemote': return this.service.resetRemote(); case 'resetLocal': return this.service.resetLocal(); case 'hasPreviouslySynced': return this.service.hasPreviouslySynced(); case 'hasLocalData': return this.service.hasLocalData(); case 'resolveContent': return this.service.resolveContent(URI.revive(args[0])); case 'accept': return this.service.accept(reviewSyncResource(args[0], this.userDataProfilesService), URI.revive(args[1]), args[2], args[3]); case 'replace': return this.service.replace(reviewSyncResourceHandle(args[0])); case 'cleanUpRemoteData': return this.service.cleanUpRemoteData(); case 'getRemoteActivityData': return this.service.saveRemoteActivityData(URI.revive(args[0])); case 'extractActivityData': return this.service.extractActivityData(URI.revive(args[0]), URI.revive(args[1])); case 'createManualSyncTask': return this.createManualSyncTask(); } // manual sync if (command.startsWith('manualSync/')) { const manualSyncTaskCommand = command.substring('manualSync/'.length); const manualSyncTaskId = args[0]; const manualSyncTask = this.getManualSyncTask(manualSyncTaskId); args = (<Array<any>>args).slice(1); switch (manualSyncTaskCommand) { case 'merge': return manualSyncTask.merge(); case 'apply': return manualSyncTask.apply().then(() => this.manualSyncTasks.delete(this.createKey(manualSyncTask.id))); case 'stop': return manualSyncTask.stop().finally(() => this.manualSyncTasks.delete(this.createKey(manualSyncTask.id))); } } throw new Error('Invalid call'); } private getManualSyncTask(manualSyncTaskId: string): IUserDataManualSyncTask { const manualSyncTask = this.manualSyncTasks.get(this.createKey(manualSyncTaskId)); if (!manualSyncTask) { throw new Error(`Manual sync taks not found: ${manualSyncTaskId}`); } return manualSyncTask; } private async createManualSyncTask(): Promise<string> { const manualSyncTask = await this.service.createManualSyncTask(); this.manualSyncTasks.set(this.createKey(manualSyncTask.id), manualSyncTask); return manualSyncTask.id; } private createKey(manualSyncTaskId: string): string { return `manualSyncTask-${manualSyncTaskId}`; } } export class UserDataSyncServiceChannelClient extends Disposable implements IUserDataSyncService { declare readonly _serviceBrand: undefined; private readonly channel: IChannel; private _status: SyncStatus = SyncStatus.Uninitialized; get status(): SyncStatus { return this._status; } private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>()); readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event; get onDidChangeLocal(): Event<SyncResource> { return this.channel.listen<SyncResource>('onDidChangeLocal'); } private _conflicts: IUserDataSyncResourceConflicts[] = []; get conflicts(): IUserDataSyncResourceConflicts[] { return this._conflicts; } private _onDidChangeConflicts = this._register(new Emitter<IUserDataSyncResourceConflicts[]>()); readonly onDidChangeConflicts = this._onDidChangeConflicts.event; private _lastSyncTime: number | undefined = undefined; get lastSyncTime(): number | undefined { return this._lastSyncTime; } private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>()); readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event; private _onSyncErrors = this._register(new Emitter<IUserDataSyncResourceError[]>()); readonly onSyncErrors = this._onSyncErrors.event; get onDidResetLocal(): Event<void> { return this.channel.listen<void>('onDidResetLocal'); } get onDidResetRemote(): Event<void> { return this.channel.listen<void>('onDidResetRemote'); } constructor( userDataSyncChannel: IChannel, @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService, ) { super(); this.channel = { call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { return userDataSyncChannel.call(command, arg, cancellationToken) .then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); }); }, listen<T>(event: string, arg?: any): Event<T> { return userDataSyncChannel.listen(event, arg); } }; this.channel.call<[SyncStatus, IUserDataSyncResourceConflicts[], number | undefined]>('_getInitialData').then(([status, conflicts, lastSyncTime]) => { this.updateStatus(status); this.updateConflicts(conflicts); if (lastSyncTime) { this.updateLastSyncTime(lastSyncTime); } this._register(this.channel.listen<SyncStatus>('onDidChangeStatus')(status => this.updateStatus(status))); this._register(this.channel.listen<number>('onDidChangeLastSyncTime')(lastSyncTime => this.updateLastSyncTime(lastSyncTime))); }); this._register(this.channel.listen<IUserDataSyncResourceConflicts[]>('onDidChangeConflicts')(conflicts => this.updateConflicts(conflicts))); this._register(this.channel.listen<IUserDataSyncResourceError[]>('onSyncErrors')(errors => this._onSyncErrors.fire(errors.map(syncError => ({ ...syncError, error: UserDataSyncError.toUserDataSyncError(syncError.error) }))))); } createSyncTask(): Promise<IUserDataSyncTask> { throw new Error('not supported'); } async createManualSyncTask(): Promise<IUserDataManualSyncTask> { const id = await this.channel.call<string>('createManualSyncTask'); const that = this; const manualSyncTaskChannelClient = new ManualSyncTaskChannelClient(id, { async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { return that.channel.call<T>(`manualSync/${command}`, [id, ...(Array.isArray(arg) ? arg : [arg])], cancellationToken); }, listen<T>(): Event<T> { throw new Error('not supported'); } }); return manualSyncTaskChannelClient; } reset(): Promise<void> { return this.channel.call('reset'); } resetRemote(): Promise<void> { return this.channel.call('resetRemote'); } resetLocal(): Promise<void> { return this.channel.call('resetLocal'); } hasPreviouslySynced(): Promise<boolean> { return this.channel.call('hasPreviouslySynced'); } hasLocalData(): Promise<boolean> { return this.channel.call('hasLocalData'); } accept(syncResource: IUserDataSyncResource, resource: URI, content: string | null, apply: boolean | { force: boolean }): Promise<void> { return this.channel.call('accept', [syncResource, resource, content, apply]); } resolveContent(resource: URI): Promise<string | null> { return this.channel.call('resolveContent', [resource]); } cleanUpRemoteData(): Promise<void> { return this.channel.call('cleanUpRemoteData'); } replace(syncResourceHandle: ISyncResourceHandle): Promise<void> { return this.channel.call('replace', [syncResourceHandle]); } saveRemoteActivityData(location: URI): Promise<void> { return this.channel.call('getRemoteActivityData', [location]); } extractActivityData(activityDataResource: URI, location: URI): Promise<void> { return this.channel.call('extractActivityData', [activityDataResource, location]); } private async updateStatus(status: SyncStatus): Promise<void> { this._status = status; this._onDidChangeStatus.fire(status); } private async updateConflicts(conflicts: IUserDataSyncResourceConflicts[]): Promise<void> { // Revive URIs this._conflicts = conflicts.map(syncConflict => ({ syncResource: syncConflict.syncResource, profile: reviveProfile(syncConflict.profile, this.userDataProfilesService.profilesHome.scheme), conflicts: syncConflict.conflicts.map(r => ({ ...r, baseResource: URI.revive(r.baseResource), localResource: URI.revive(r.localResource), remoteResource: URI.revive(r.remoteResource), previewResource: URI.revive(r.previewResource), })) })); this._onDidChangeConflicts.fire(this._conflicts); } private updateLastSyncTime(lastSyncTime: number): void { if (this._lastSyncTime !== lastSyncTime) { this._lastSyncTime = lastSyncTime; this._onDidChangeLastSyncTime.fire(lastSyncTime); } } } class ManualSyncTaskChannelClient extends Disposable implements IUserDataManualSyncTask { constructor( readonly id: string, private readonly channel: IChannel, ) { super(); } async merge(): Promise<void> { return this.channel.call('merge'); } async apply(): Promise<void> { return this.channel.call('apply'); } stop(): Promise<void> { return this.channel.call('stop'); } override dispose(): void { this.channel.call('dispose'); super.dispose(); } }
src/vs/platform/userDataSync/common/userDataSyncServiceIpc.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9865603446960449, 0.09809961915016174, 0.0001658974651945755, 0.00017070010653696954, 0.2936432957649231 ]
{ "id": 7, "code_window": [ "\n", "\tconstructor(private readonly editor: ICodeEditor) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tconstructor(private readonly editor: ICodeEditor, keybindingService: IKeybindingService) {\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { IStringDictionary } from 'vs/base/common/collections'; import { Event } from 'vs/base/common/event'; import { IPager } from 'vs/base/common/paging'; import { Platform } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { localize2 } from 'vs/nls'; import { ExtensionType, IExtension, IExtensionManifest, TargetPlatform } from 'vs/platform/extensions/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const EXTENSION_IDENTIFIER_PATTERN = '^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$'; export const EXTENSION_IDENTIFIER_REGEX = new RegExp(EXTENSION_IDENTIFIER_PATTERN); export const WEB_EXTENSION_TAG = '__web_extension'; export const EXTENSION_INSTALL_SKIP_WALKTHROUGH_CONTEXT = 'skipWalkthrough'; export const EXTENSION_INSTALL_SYNC_CONTEXT = 'extensionsSync'; export const EXTENSION_INSTALL_DEP_PACK_CONTEXT = 'dependecyOrPackExtensionInstall'; export function TargetPlatformToString(targetPlatform: TargetPlatform) { switch (targetPlatform) { case TargetPlatform.WIN32_X64: return 'Windows 64 bit'; case TargetPlatform.WIN32_ARM64: return 'Windows ARM'; case TargetPlatform.LINUX_X64: return 'Linux 64 bit'; case TargetPlatform.LINUX_ARM64: return 'Linux ARM 64'; case TargetPlatform.LINUX_ARMHF: return 'Linux ARM'; case TargetPlatform.ALPINE_X64: return 'Alpine Linux 64 bit'; case TargetPlatform.ALPINE_ARM64: return 'Alpine ARM 64'; case TargetPlatform.DARWIN_X64: return 'Mac'; case TargetPlatform.DARWIN_ARM64: return 'Mac Silicon'; case TargetPlatform.WEB: return 'Web'; case TargetPlatform.UNIVERSAL: return TargetPlatform.UNIVERSAL; case TargetPlatform.UNKNOWN: return TargetPlatform.UNKNOWN; case TargetPlatform.UNDEFINED: return TargetPlatform.UNDEFINED; } } export function toTargetPlatform(targetPlatform: string): TargetPlatform { switch (targetPlatform) { case TargetPlatform.WIN32_X64: return TargetPlatform.WIN32_X64; case TargetPlatform.WIN32_ARM64: return TargetPlatform.WIN32_ARM64; case TargetPlatform.LINUX_X64: return TargetPlatform.LINUX_X64; case TargetPlatform.LINUX_ARM64: return TargetPlatform.LINUX_ARM64; case TargetPlatform.LINUX_ARMHF: return TargetPlatform.LINUX_ARMHF; case TargetPlatform.ALPINE_X64: return TargetPlatform.ALPINE_X64; case TargetPlatform.ALPINE_ARM64: return TargetPlatform.ALPINE_ARM64; case TargetPlatform.DARWIN_X64: return TargetPlatform.DARWIN_X64; case TargetPlatform.DARWIN_ARM64: return TargetPlatform.DARWIN_ARM64; case TargetPlatform.WEB: return TargetPlatform.WEB; case TargetPlatform.UNIVERSAL: return TargetPlatform.UNIVERSAL; default: return TargetPlatform.UNKNOWN; } } export function getTargetPlatform(platform: Platform | 'alpine', arch: string | undefined): TargetPlatform { switch (platform) { case Platform.Windows: if (arch === 'x64') { return TargetPlatform.WIN32_X64; } if (arch === 'arm64') { return TargetPlatform.WIN32_ARM64; } return TargetPlatform.UNKNOWN; case Platform.Linux: if (arch === 'x64') { return TargetPlatform.LINUX_X64; } if (arch === 'arm64') { return TargetPlatform.LINUX_ARM64; } if (arch === 'arm') { return TargetPlatform.LINUX_ARMHF; } return TargetPlatform.UNKNOWN; case 'alpine': if (arch === 'x64') { return TargetPlatform.ALPINE_X64; } if (arch === 'arm64') { return TargetPlatform.ALPINE_ARM64; } return TargetPlatform.UNKNOWN; case Platform.Mac: if (arch === 'x64') { return TargetPlatform.DARWIN_X64; } if (arch === 'arm64') { return TargetPlatform.DARWIN_ARM64; } return TargetPlatform.UNKNOWN; case Platform.Web: return TargetPlatform.WEB; } } export function isNotWebExtensionInWebTargetPlatform(allTargetPlatforms: TargetPlatform[], productTargetPlatform: TargetPlatform): boolean { // Not a web extension in web target platform return productTargetPlatform === TargetPlatform.WEB && !allTargetPlatforms.includes(TargetPlatform.WEB); } export function isTargetPlatformCompatible(extensionTargetPlatform: TargetPlatform, allTargetPlatforms: TargetPlatform[], productTargetPlatform: TargetPlatform): boolean { // Not compatible when extension is not a web extension in web target platform if (isNotWebExtensionInWebTargetPlatform(allTargetPlatforms, productTargetPlatform)) { return false; } // Compatible when extension target platform is not defined if (extensionTargetPlatform === TargetPlatform.UNDEFINED) { return true; } // Compatible when extension target platform is universal if (extensionTargetPlatform === TargetPlatform.UNIVERSAL) { return true; } // Not compatible when extension target platform is unknown if (extensionTargetPlatform === TargetPlatform.UNKNOWN) { return false; } // Compatible when extension and product target platforms matches if (extensionTargetPlatform === productTargetPlatform) { return true; } return false; } export interface IGalleryExtensionProperties { dependencies?: string[]; extensionPack?: string[]; engine?: string; localizedLanguages?: string[]; targetPlatform: TargetPlatform; isPreReleaseVersion: boolean; } export interface IGalleryExtensionAsset { uri: string; fallbackUri: string; } export interface IGalleryExtensionAssets { manifest: IGalleryExtensionAsset | null; readme: IGalleryExtensionAsset | null; changelog: IGalleryExtensionAsset | null; license: IGalleryExtensionAsset | null; repository: IGalleryExtensionAsset | null; download: IGalleryExtensionAsset; icon: IGalleryExtensionAsset | null; signature: IGalleryExtensionAsset | null; coreTranslations: [string, IGalleryExtensionAsset][]; } export function isIExtensionIdentifier(thing: any): thing is IExtensionIdentifier { return thing && typeof thing === 'object' && typeof thing.id === 'string' && (!thing.uuid || typeof thing.uuid === 'string'); } export interface IExtensionIdentifier { id: string; uuid?: string; } export interface IGalleryExtensionIdentifier extends IExtensionIdentifier { uuid: string; } export interface IGalleryExtensionVersion { version: string; date: string; isPreReleaseVersion: boolean; } export interface IGalleryExtension { name: string; identifier: IGalleryExtensionIdentifier; version: string; displayName: string; publisherId: string; publisher: string; publisherDisplayName: string; publisherDomain?: { link: string; verified: boolean }; publisherSponsorLink?: string; description: string; installCount: number; rating: number; ratingCount: number; categories: readonly string[]; tags: readonly string[]; releaseDate: number; lastUpdated: number; preview: boolean; hasPreReleaseVersion: boolean; hasReleaseVersion: boolean; isSigned: boolean; allTargetPlatforms: TargetPlatform[]; assets: IGalleryExtensionAssets; properties: IGalleryExtensionProperties; telemetryData?: any; queryContext?: IStringDictionary<any>; supportLink?: string; } export interface IGalleryMetadata { id: string; publisherId: string; publisherDisplayName: string; isPreReleaseVersion: boolean; targetPlatform?: TargetPlatform; } export type Metadata = Partial<IGalleryMetadata & { isApplicationScoped: boolean; isMachineScoped: boolean; isBuiltin: boolean; isSystem: boolean; updated: boolean; preRelease: boolean; hasPreReleaseVersion: boolean; installedTimestamp: number; pinned: boolean; }>; export interface ILocalExtension extends IExtension { isMachineScoped: boolean; isApplicationScoped: boolean; publisherId: string | null; publisherDisplayName: string | null; installedTimestamp?: number; isPreReleaseVersion: boolean; hasPreReleaseVersion: boolean; preRelease: boolean; updated: boolean; pinned: boolean; } export const enum SortBy { NoneOrRelevance = 0, LastUpdatedDate = 1, Title = 2, PublisherName = 3, InstallCount = 4, PublishedDate = 10, AverageRating = 6, WeightedRating = 12 } export const enum SortOrder { Default = 0, Ascending = 1, Descending = 2 } export interface IQueryOptions { text?: string; ids?: string[]; names?: string[]; pageSize?: number; sortBy?: SortBy; sortOrder?: SortOrder; source?: string; includePreRelease?: boolean; } export const enum StatisticType { Install = 'install', Uninstall = 'uninstall' } export interface IDeprecationInfo { readonly disallowInstall?: boolean; readonly extension?: { readonly id: string; readonly displayName: string; readonly autoMigrate?: { readonly storage: boolean }; readonly preRelease?: boolean; }; readonly settings?: readonly string[]; readonly additionalInfo?: string; } export interface ISearchPrefferedResults { readonly query?: string; readonly preferredResults?: string[]; } export interface IExtensionsControlManifest { readonly malicious: IExtensionIdentifier[]; readonly deprecated: IStringDictionary<IDeprecationInfo>; readonly search: ISearchPrefferedResults[]; } export const enum InstallOperation { None = 1, Install, Update, Migrate, } export interface ITranslation { contents: { [key: string]: {} }; } export interface IExtensionInfo extends IExtensionIdentifier { version?: string; preRelease?: boolean; hasPreRelease?: boolean; } export interface IExtensionQueryOptions { targetPlatform?: TargetPlatform; compatible?: boolean; queryAllVersions?: boolean; source?: string; } export const IExtensionGalleryService = createDecorator<IExtensionGalleryService>('extensionGalleryService'); /** * Service to interact with the Visual Studio Code Marketplace to get extensions. * @throws Error if the Marketplace is not enabled or not reachable. */ export interface IExtensionGalleryService { readonly _serviceBrand: undefined; isEnabled(): boolean; query(options: IQueryOptions, token: CancellationToken): Promise<IPager<IGalleryExtension>>; getExtensions(extensionInfos: ReadonlyArray<IExtensionInfo>, token: CancellationToken): Promise<IGalleryExtension[]>; getExtensions(extensionInfos: ReadonlyArray<IExtensionInfo>, options: IExtensionQueryOptions, token: CancellationToken): Promise<IGalleryExtension[]>; isExtensionCompatible(extension: IGalleryExtension, includePreRelease: boolean, targetPlatform: TargetPlatform): Promise<boolean>; getCompatibleExtension(extension: IGalleryExtension, includePreRelease: boolean, targetPlatform: TargetPlatform): Promise<IGalleryExtension | null>; getAllCompatibleVersions(extension: IGalleryExtension, includePreRelease: boolean, targetPlatform: TargetPlatform): Promise<IGalleryExtensionVersion[]>; download(extension: IGalleryExtension, location: URI, operation: InstallOperation): Promise<void>; downloadSignatureArchive(extension: IGalleryExtension, location: URI): Promise<void>; reportStatistic(publisher: string, name: string, version: string, type: StatisticType): Promise<void>; getReadme(extension: IGalleryExtension, token: CancellationToken): Promise<string>; getManifest(extension: IGalleryExtension, token: CancellationToken): Promise<IExtensionManifest | null>; getChangelog(extension: IGalleryExtension, token: CancellationToken): Promise<string>; getCoreTranslation(extension: IGalleryExtension, languageId: string): Promise<ITranslation | null>; getExtensionsControlManifest(): Promise<IExtensionsControlManifest>; } export interface InstallExtensionEvent { readonly identifier: IExtensionIdentifier; readonly source: URI | IGalleryExtension; readonly profileLocation?: URI; readonly applicationScoped?: boolean; } export interface InstallExtensionResult { readonly identifier: IExtensionIdentifier; readonly operation: InstallOperation; readonly source?: URI | IGalleryExtension; readonly local?: ILocalExtension; readonly error?: Error; readonly context?: IStringDictionary<any>; readonly profileLocation?: URI; readonly applicationScoped?: boolean; } export interface UninstallExtensionEvent { readonly identifier: IExtensionIdentifier; readonly profileLocation?: URI; readonly applicationScoped?: boolean; } export interface DidUninstallExtensionEvent { readonly identifier: IExtensionIdentifier; readonly error?: string; readonly profileLocation?: URI; readonly applicationScoped?: boolean; } export enum ExtensionManagementErrorCode { Unsupported = 'Unsupported', Deprecated = 'Deprecated', Malicious = 'Malicious', Incompatible = 'Incompatible', IncompatibleTargetPlatform = 'IncompatibleTargetPlatform', ReleaseVersionNotFound = 'ReleaseVersionNotFound', Invalid = 'Invalid', Download = 'Download', DownloadSignature = 'DownloadSignature', UpdateMetadata = 'UpdateMetadata', Extract = 'Extract', Scanning = 'Scanning', Delete = 'Delete', Rename = 'Rename', CorruptZip = 'CorruptZip', IncompleteZip = 'IncompleteZip', Signature = 'Signature', NotAllowed = 'NotAllowed', Gallery = 'Gallery', Unknown = 'Unknown', Internal = 'Internal', } export enum ExtensionSignaturetErrorCode { UnknownError = 'UnknownError', PackageIsInvalidZip = 'PackageIsInvalidZip', SignatureArchiveIsInvalidZip = 'SignatureArchiveIsInvalidZip', } export class ExtensionManagementError extends Error { constructor(message: string, readonly code: ExtensionManagementErrorCode) { super(message); this.name = code; } } export enum ExtensionGalleryErrorCode { Timeout = 'Timeout', Cancelled = 'Cancelled', Failed = 'Failed' } export class ExtensionGalleryError extends Error { constructor(message: string, readonly code: ExtensionGalleryErrorCode) { super(message); this.name = code; } } export type InstallOptions = { isBuiltin?: boolean; isMachineScoped?: boolean; isApplicationScoped?: boolean; pinned?: boolean; donotIncludePackAndDependencies?: boolean; installGivenVersion?: boolean; preRelease?: boolean; installPreReleaseVersion?: boolean; donotVerifySignature?: boolean; operation?: InstallOperation; profileLocation?: URI; /** * Context passed through to InstallExtensionResult */ context?: IStringDictionary<any>; }; export type InstallVSIXOptions = InstallOptions & { installOnlyNewlyAddedFromExtensionPack?: boolean }; export type UninstallOptions = { readonly donotIncludePack?: boolean; readonly donotCheckDependents?: boolean; readonly versionOnly?: boolean; readonly remove?: boolean; readonly profileLocation?: URI }; export interface IExtensionManagementParticipant { postInstall(local: ILocalExtension, source: URI | IGalleryExtension, options: InstallOptions | InstallVSIXOptions, token: CancellationToken): Promise<void>; postUninstall(local: ILocalExtension, options: UninstallOptions, token: CancellationToken): Promise<void>; } export type InstallExtensionInfo = { readonly extension: IGalleryExtension; readonly options: InstallOptions }; export const IExtensionManagementService = createDecorator<IExtensionManagementService>('extensionManagementService'); export interface IExtensionManagementService { readonly _serviceBrand: undefined; onInstallExtension: Event<InstallExtensionEvent>; onDidInstallExtensions: Event<readonly InstallExtensionResult[]>; onUninstallExtension: Event<UninstallExtensionEvent>; onDidUninstallExtension: Event<DidUninstallExtensionEvent>; onDidUpdateExtensionMetadata: Event<ILocalExtension>; zip(extension: ILocalExtension): Promise<URI>; unzip(zipLocation: URI): Promise<IExtensionIdentifier>; getManifest(vsix: URI): Promise<IExtensionManifest>; install(vsix: URI, options?: InstallVSIXOptions): Promise<ILocalExtension>; canInstall(extension: IGalleryExtension): Promise<boolean>; installFromGallery(extension: IGalleryExtension, options?: InstallOptions): Promise<ILocalExtension>; installGalleryExtensions(extensions: InstallExtensionInfo[]): Promise<InstallExtensionResult[]>; installFromLocation(location: URI, profileLocation: URI): Promise<ILocalExtension>; installExtensionsFromProfile(extensions: IExtensionIdentifier[], fromProfileLocation: URI, toProfileLocation: URI): Promise<ILocalExtension[]>; uninstall(extension: ILocalExtension, options?: UninstallOptions): Promise<void>; toggleAppliationScope(extension: ILocalExtension, fromProfileLocation: URI): Promise<ILocalExtension>; reinstallFromGallery(extension: ILocalExtension): Promise<ILocalExtension>; getInstalled(type?: ExtensionType, profileLocation?: URI): Promise<ILocalExtension[]>; getExtensionsControlManifest(): Promise<IExtensionsControlManifest>; copyExtensions(fromProfileLocation: URI, toProfileLocation: URI): Promise<void>; updateMetadata(local: ILocalExtension, metadata: Partial<Metadata>, profileLocation?: URI): Promise<ILocalExtension>; download(extension: IGalleryExtension, operation: InstallOperation, donotVerifySignature: boolean): Promise<URI>; registerParticipant(pariticipant: IExtensionManagementParticipant): void; getTargetPlatform(): Promise<TargetPlatform>; cleanUp(): Promise<void>; } export const DISABLED_EXTENSIONS_STORAGE_PATH = 'extensionsIdentifiers/disabled'; export const ENABLED_EXTENSIONS_STORAGE_PATH = 'extensionsIdentifiers/enabled'; export const IGlobalExtensionEnablementService = createDecorator<IGlobalExtensionEnablementService>('IGlobalExtensionEnablementService'); export interface IGlobalExtensionEnablementService { readonly _serviceBrand: undefined; readonly onDidChangeEnablement: Event<{ readonly extensions: IExtensionIdentifier[]; readonly source?: string }>; getDisabledExtensions(): IExtensionIdentifier[]; enableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean>; disableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean>; } export type IConfigBasedExtensionTip = { readonly extensionId: string; readonly extensionName: string; readonly isExtensionPack: boolean; readonly configName: string; readonly important: boolean; readonly whenNotInstalled?: string[]; }; export type IExecutableBasedExtensionTip = { readonly extensionId: string; readonly extensionName: string; readonly isExtensionPack: boolean; readonly exeName: string; readonly exeFriendlyName: string; readonly windowsPath?: string; readonly whenNotInstalled?: string[]; }; export const IExtensionTipsService = createDecorator<IExtensionTipsService>('IExtensionTipsService'); export interface IExtensionTipsService { readonly _serviceBrand: undefined; getConfigBasedTips(folder: URI): Promise<IConfigBasedExtensionTip[]>; getImportantExecutableBasedTips(): Promise<IExecutableBasedExtensionTip[]>; getOtherExecutableBasedTips(): Promise<IExecutableBasedExtensionTip[]>; } export const ExtensionsLocalizedLabel = localize2('extensions', "Extensions"); export const PreferencesLocalizedLabel = localize2('preferences', 'Preferences');
src/vs/platform/extensionManagement/common/extensionManagement.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9835160374641418, 0.02197285369038582, 0.00016347202472388744, 0.00017003963876049966, 0.13396531343460083 ]
{ "id": 7, "code_window": [ "\n", "\tconstructor(private readonly editor: ICodeEditor) {\n", "\t\tsuper();\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\tconstructor(private readonly editor: ICodeEditor, keybindingService: IKeybindingService) {\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 98 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize2 } from 'vs/nls'; import { IEditorGroupsService, GroupDirection, GroupLocation, IFindGroupScope } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { Action2, IAction2Options, registerAction2 } from 'vs/platform/actions/common/actions'; import { Categories } from 'vs/platform/action/common/actionCommonCategories'; import { Direction } from 'vs/base/browser/ui/grid/grid'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IPaneComposite } from 'vs/workbench/common/panecomposite'; import { IComposite } from 'vs/workbench/common/composite'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { getActiveWindow } from 'vs/base/browser/dom'; import { isAuxiliaryWindow } from 'vs/base/browser/window'; abstract class BaseNavigationAction extends Action2 { constructor( options: IAction2Options, protected direction: Direction ) { super(options); } run(accessor: ServicesAccessor): void { const layoutService = accessor.get(IWorkbenchLayoutService); const editorGroupService = accessor.get(IEditorGroupsService); const paneCompositeService = accessor.get(IPaneCompositePartService); const isEditorFocus = layoutService.hasFocus(Parts.EDITOR_PART); const isPanelFocus = layoutService.hasFocus(Parts.PANEL_PART); const isSidebarFocus = layoutService.hasFocus(Parts.SIDEBAR_PART); const isAuxiliaryBarFocus = layoutService.hasFocus(Parts.AUXILIARYBAR_PART); let neighborPart: Parts | undefined; if (isEditorFocus) { const didNavigate = this.navigateAcrossEditorGroup(this.toGroupDirection(this.direction), editorGroupService); if (didNavigate) { return; } neighborPart = layoutService.getVisibleNeighborPart(Parts.EDITOR_PART, this.direction); } if (isPanelFocus) { neighborPart = layoutService.getVisibleNeighborPart(Parts.PANEL_PART, this.direction); } if (isSidebarFocus) { neighborPart = layoutService.getVisibleNeighborPart(Parts.SIDEBAR_PART, this.direction); } if (isAuxiliaryBarFocus) { neighborPart = neighborPart = layoutService.getVisibleNeighborPart(Parts.AUXILIARYBAR_PART, this.direction); } if (neighborPart === Parts.EDITOR_PART) { if (!this.navigateBackToEditorGroup(this.toGroupDirection(this.direction), editorGroupService)) { this.navigateToEditorGroup(this.direction === Direction.Right ? GroupLocation.FIRST : GroupLocation.LAST, editorGroupService); } } else if (neighborPart === Parts.SIDEBAR_PART) { this.navigateToSidebar(layoutService, paneCompositeService); } else if (neighborPart === Parts.PANEL_PART) { this.navigateToPanel(layoutService, paneCompositeService); } else if (neighborPart === Parts.AUXILIARYBAR_PART) { this.navigateToAuxiliaryBar(layoutService, paneCompositeService); } } private async navigateToPanel(layoutService: IWorkbenchLayoutService, paneCompositeService: IPaneCompositePartService): Promise<IComposite | boolean> { if (!layoutService.isVisible(Parts.PANEL_PART)) { return false; } const activePanel = paneCompositeService.getActivePaneComposite(ViewContainerLocation.Panel); if (!activePanel) { return false; } const activePanelId = activePanel.getId(); const res = await paneCompositeService.openPaneComposite(activePanelId, ViewContainerLocation.Panel, true); if (!res) { return false; } return res; } private async navigateToSidebar(layoutService: IWorkbenchLayoutService, paneCompositeService: IPaneCompositePartService): Promise<IPaneComposite | boolean> { if (!layoutService.isVisible(Parts.SIDEBAR_PART)) { return false; } const activeViewlet = paneCompositeService.getActivePaneComposite(ViewContainerLocation.Sidebar); if (!activeViewlet) { return false; } const activeViewletId = activeViewlet.getId(); const viewlet = await paneCompositeService.openPaneComposite(activeViewletId, ViewContainerLocation.Sidebar, true); return !!viewlet; } private async navigateToAuxiliaryBar(layoutService: IWorkbenchLayoutService, paneCompositeService: IPaneCompositePartService): Promise<IComposite | boolean> { if (!layoutService.isVisible(Parts.AUXILIARYBAR_PART)) { return false; } const activePanel = paneCompositeService.getActivePaneComposite(ViewContainerLocation.AuxiliaryBar); if (!activePanel) { return false; } const activePanelId = activePanel.getId(); const res = await paneCompositeService.openPaneComposite(activePanelId, ViewContainerLocation.AuxiliaryBar, true); if (!res) { return false; } return res; } private navigateAcrossEditorGroup(direction: GroupDirection, editorGroupService: IEditorGroupsService): boolean { return this.doNavigateToEditorGroup({ direction }, editorGroupService); } private navigateToEditorGroup(location: GroupLocation, editorGroupService: IEditorGroupsService): boolean { return this.doNavigateToEditorGroup({ location }, editorGroupService); } private navigateBackToEditorGroup(direction: GroupDirection, editorGroupService: IEditorGroupsService): boolean { if (!editorGroupService.activeGroup) { return false; } const oppositeDirection = this.toOppositeDirection(direction); // Check to see if there is a group in between the last // active group and the direction of movement const groupInBetween = editorGroupService.findGroup({ direction: oppositeDirection }, editorGroupService.activeGroup); if (!groupInBetween) { // No group in between means we can return // focus to the last active editor group editorGroupService.activeGroup.focus(); return true; } return false; } private toGroupDirection(direction: Direction): GroupDirection { switch (direction) { case Direction.Down: return GroupDirection.DOWN; case Direction.Left: return GroupDirection.LEFT; case Direction.Right: return GroupDirection.RIGHT; case Direction.Up: return GroupDirection.UP; } } private toOppositeDirection(direction: GroupDirection): GroupDirection { switch (direction) { case GroupDirection.UP: return GroupDirection.DOWN; case GroupDirection.RIGHT: return GroupDirection.LEFT; case GroupDirection.LEFT: return GroupDirection.RIGHT; case GroupDirection.DOWN: return GroupDirection.UP; } } private doNavigateToEditorGroup(scope: IFindGroupScope, editorGroupService: IEditorGroupsService): boolean { const targetGroup = editorGroupService.findGroup(scope, editorGroupService.activeGroup); if (targetGroup) { targetGroup.focus(); return true; } return false; } } registerAction2(class extends BaseNavigationAction { constructor() { super({ id: 'workbench.action.navigateLeft', title: localize2('navigateLeft', 'Navigate to the View on the Left'), category: Categories.View, f1: true }, Direction.Left); } }); registerAction2(class extends BaseNavigationAction { constructor() { super({ id: 'workbench.action.navigateRight', title: localize2('navigateRight', 'Navigate to the View on the Right'), category: Categories.View, f1: true }, Direction.Right); } }); registerAction2(class extends BaseNavigationAction { constructor() { super({ id: 'workbench.action.navigateUp', title: localize2('navigateUp', 'Navigate to the View Above'), category: Categories.View, f1: true }, Direction.Up); } }); registerAction2(class extends BaseNavigationAction { constructor() { super({ id: 'workbench.action.navigateDown', title: localize2('navigateDown', 'Navigate to the View Below'), category: Categories.View, f1: true }, Direction.Down); } }); abstract class BaseFocusAction extends Action2 { constructor( options: IAction2Options, private readonly focusNext: boolean ) { super(options); } run(accessor: ServicesAccessor): void { const layoutService = accessor.get(IWorkbenchLayoutService); const editorService = accessor.get(IEditorService); this.focusNextOrPreviousPart(layoutService, editorService, this.focusNext); } private findVisibleNeighbour(layoutService: IWorkbenchLayoutService, part: Parts, next: boolean): Parts { const activeWindow = getActiveWindow(); const windowIsAuxiliary = isAuxiliaryWindow(activeWindow); let neighbour: Parts; if (windowIsAuxiliary) { switch (part) { case Parts.EDITOR_PART: neighbour = Parts.STATUSBAR_PART; break; default: neighbour = Parts.EDITOR_PART; } } else { switch (part) { case Parts.EDITOR_PART: neighbour = next ? Parts.PANEL_PART : Parts.SIDEBAR_PART; break; case Parts.PANEL_PART: neighbour = next ? Parts.STATUSBAR_PART : Parts.EDITOR_PART; break; case Parts.STATUSBAR_PART: neighbour = next ? Parts.ACTIVITYBAR_PART : Parts.PANEL_PART; break; case Parts.ACTIVITYBAR_PART: neighbour = next ? Parts.SIDEBAR_PART : Parts.STATUSBAR_PART; break; case Parts.SIDEBAR_PART: neighbour = next ? Parts.EDITOR_PART : Parts.ACTIVITYBAR_PART; break; default: neighbour = Parts.EDITOR_PART; } } if (layoutService.isVisible(neighbour, activeWindow) || neighbour === Parts.EDITOR_PART) { return neighbour; } return this.findVisibleNeighbour(layoutService, neighbour, next); } private focusNextOrPreviousPart(layoutService: IWorkbenchLayoutService, editorService: IEditorService, next: boolean): void { let currentlyFocusedPart: Parts | undefined; if (editorService.activeEditorPane?.hasFocus() || layoutService.hasFocus(Parts.EDITOR_PART)) { currentlyFocusedPart = Parts.EDITOR_PART; } else if (layoutService.hasFocus(Parts.ACTIVITYBAR_PART)) { currentlyFocusedPart = Parts.ACTIVITYBAR_PART; } else if (layoutService.hasFocus(Parts.STATUSBAR_PART)) { currentlyFocusedPart = Parts.STATUSBAR_PART; } else if (layoutService.hasFocus(Parts.SIDEBAR_PART)) { currentlyFocusedPart = Parts.SIDEBAR_PART; } else if (layoutService.hasFocus(Parts.PANEL_PART)) { currentlyFocusedPart = Parts.PANEL_PART; } layoutService.focusPart(currentlyFocusedPart ? this.findVisibleNeighbour(layoutService, currentlyFocusedPart, next) : Parts.EDITOR_PART, getActiveWindow()); } } registerAction2(class extends BaseFocusAction { constructor() { super({ id: 'workbench.action.focusNextPart', title: localize2('focusNextPart', 'Focus Next Part'), category: Categories.View, f1: true, keybinding: { primary: KeyCode.F6, weight: KeybindingWeight.WorkbenchContrib } }, true); } }); registerAction2(class extends BaseFocusAction { constructor() { super({ id: 'workbench.action.focusPreviousPart', title: localize2('focusPreviousPart', 'Focus Previous Part'), category: Categories.View, f1: true, keybinding: { primary: KeyMod.Shift | KeyCode.F6, weight: KeybindingWeight.WorkbenchContrib } }, false); } });
src/vs/workbench/browser/actions/navigationActions.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9971413016319275, 0.19477829337120056, 0.00016633336781524122, 0.00017134657537098974, 0.38588061928749084 ]
{ "id": 8, "code_window": [ "\t\tsuper();\n", "\n", "\t\tthis.domNode.appendChild(this.elements.root);\n", "\t\tthis.domNode.style.zIndex = '1000';\n", "\n", "\t\treset(this.elements.mic, renderIcon(Codicon.micFilled));\n", "\t}\n", "\n", "\tgetId(): string {\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionBar = this._register(new ActionBar(this.domNode));\n", "\t\tconst stopActionKeybinding = keybindingService.lookupKeybinding(EditorDictationStopAction.ID)?.getLabel();\n", "\t\tactionBar.push(toAction({\n", "\t\t\tid: EditorDictationStopAction.ID,\n", "\t\t\tlabel: stopActionKeybinding ? localize('stopDictationShort1', \"Stop Dictation ({0})\", stopActionKeybinding) : localize('stopDictationShort2', \"Stop Dictation\"),\n", "\t\t\tclass: ThemeIcon.asClassName(Codicon.micFilled),\n", "\t\t\trun: () => EditorDictation.get(editor)?.stop()\n", "\t\t}), { icon: true, label: false, keybinding: stopActionKeybinding });\n", "\n", "\t\tthis.domNode.classList.add('editor-dictation-widget');\n", "\t\tthis.domNode.appendChild(actionBar.domNode);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.653857946395874, 0.023690419271588326, 0.00016312013030983508, 0.00017191759252455086, 0.12127892673015594 ]
{ "id": 8, "code_window": [ "\t\tsuper();\n", "\n", "\t\tthis.domNode.appendChild(this.elements.root);\n", "\t\tthis.domNode.style.zIndex = '1000';\n", "\n", "\t\treset(this.elements.mic, renderIcon(Codicon.micFilled));\n", "\t}\n", "\n", "\tgetId(): string {\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionBar = this._register(new ActionBar(this.domNode));\n", "\t\tconst stopActionKeybinding = keybindingService.lookupKeybinding(EditorDictationStopAction.ID)?.getLabel();\n", "\t\tactionBar.push(toAction({\n", "\t\t\tid: EditorDictationStopAction.ID,\n", "\t\t\tlabel: stopActionKeybinding ? localize('stopDictationShort1', \"Stop Dictation ({0})\", stopActionKeybinding) : localize('stopDictationShort2', \"Stop Dictation\"),\n", "\t\t\tclass: ThemeIcon.asClassName(Codicon.micFilled),\n", "\t\t\trun: () => EditorDictation.get(editor)?.stop()\n", "\t\t}), { icon: true, label: false, keybinding: stopActionKeybinding });\n", "\n", "\t\tthis.domNode.classList.add('editor-dictation-widget');\n", "\t\tthis.domNode.appendChild(actionBar.domNode);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export function disposeAll(disposables: Iterable<vscode.Disposable>) { const errors: any[] = []; for (const disposable of disposables) { try { disposable.dispose(); } catch (e) { errors.push(e); } } if (errors.length === 1) { throw errors[0]; } else if (errors.length > 1) { throw new AggregateError(errors, 'Encountered errors while disposing of store'); } } export interface IDisposable { dispose(): void; } export abstract class Disposable { private _isDisposed = false; protected _disposables: vscode.Disposable[] = []; public dispose(): any { if (this._isDisposed) { return; } this._isDisposed = true; disposeAll(this._disposables); } protected _register<T extends IDisposable>(value: T): T { if (this._isDisposed) { value.dispose(); } else { this._disposables.push(value); } return value; } protected get isDisposed() { return this._isDisposed; } }
extensions/markdown-language-features/src/util/dispose.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001745436602504924, 0.0001721890439512208, 0.00016882827912922949, 0.0001724993926472962, 0.0000020372590370243415 ]
{ "id": 8, "code_window": [ "\t\tsuper();\n", "\n", "\t\tthis.domNode.appendChild(this.elements.root);\n", "\t\tthis.domNode.style.zIndex = '1000';\n", "\n", "\t\treset(this.elements.mic, renderIcon(Codicon.micFilled));\n", "\t}\n", "\n", "\tgetId(): string {\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionBar = this._register(new ActionBar(this.domNode));\n", "\t\tconst stopActionKeybinding = keybindingService.lookupKeybinding(EditorDictationStopAction.ID)?.getLabel();\n", "\t\tactionBar.push(toAction({\n", "\t\t\tid: EditorDictationStopAction.ID,\n", "\t\t\tlabel: stopActionKeybinding ? localize('stopDictationShort1', \"Stop Dictation ({0})\", stopActionKeybinding) : localize('stopDictationShort2', \"Stop Dictation\"),\n", "\t\t\tclass: ThemeIcon.asClassName(Codicon.micFilled),\n", "\t\t\trun: () => EditorDictation.get(editor)?.stop()\n", "\t\t}), { icon: true, label: false, keybinding: stopActionKeybinding });\n", "\n", "\t\tthis.domNode.classList.add('editor-dictation-widget');\n", "\t\tthis.domNode.appendChild(actionBar.domNode);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 101 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "language-docker", "repositoryUrl": "https://github.com/moby/moby", "commitHash": "abd39744c6f3ed854500e423f5fabf952165161f" } }, "license": "Apache2", "description": "The file syntaxes/docker.tmLanguage was included from https://github.com/moby/moby/blob/master/contrib/syntax/textmate/Docker.tmbundle/Syntaxes/Dockerfile.tmLanguage.", "version": "0.0.0" } ], "version": 1 }
extensions/docker/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017442056559957564, 0.00017405636026524007, 0.00017369214037898928, 0.00017405636026524007, 3.6421261029317975e-7 ]
{ "id": 8, "code_window": [ "\t\tsuper();\n", "\n", "\t\tthis.domNode.appendChild(this.elements.root);\n", "\t\tthis.domNode.style.zIndex = '1000';\n", "\n", "\t\treset(this.elements.mic, renderIcon(Codicon.micFilled));\n", "\t}\n", "\n", "\tgetId(): string {\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionBar = this._register(new ActionBar(this.domNode));\n", "\t\tconst stopActionKeybinding = keybindingService.lookupKeybinding(EditorDictationStopAction.ID)?.getLabel();\n", "\t\tactionBar.push(toAction({\n", "\t\t\tid: EditorDictationStopAction.ID,\n", "\t\t\tlabel: stopActionKeybinding ? localize('stopDictationShort1', \"Stop Dictation ({0})\", stopActionKeybinding) : localize('stopDictationShort2', \"Stop Dictation\"),\n", "\t\t\tclass: ThemeIcon.asClassName(Codicon.micFilled),\n", "\t\t\trun: () => EditorDictation.get(editor)?.stop()\n", "\t\t}), { icon: true, label: false, keybinding: stopActionKeybinding });\n", "\n", "\t\tthis.domNode.classList.add('editor-dictation-widget');\n", "\t\tthis.domNode.appendChild(actionBar.domNode);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action } from 'vs/base/common/actions'; import { onUnexpectedError } from 'vs/base/common/errors'; import { isDefined } from 'vs/base/common/types'; import { localize } from 'vs/nls'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { Registry } from 'vs/platform/registry/common/platform'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { IExtensionsWorkbenchService } from 'vs/workbench/contrib/extensions/common/extensions'; import { EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; class DeprecatedExtensionMigratorContribution { constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService, @IStorageService private readonly storageService: IStorageService, @INotificationService private readonly notificationService: INotificationService, @IOpenerService private readonly openerService: IOpenerService ) { this.init().catch(onUnexpectedError); } private async init(): Promise<void> { const bracketPairColorizerId = 'coenraads.bracket-pair-colorizer'; await this.extensionsWorkbenchService.queryLocal(); const extension = this.extensionsWorkbenchService.installed.find(e => e.identifier.id === bracketPairColorizerId); if ( !extension || ((extension.enablementState !== EnablementState.EnabledGlobally) && (extension.enablementState !== EnablementState.EnabledWorkspace)) ) { return; } const state = await this.getState(); const disablementLogEntry = state.disablementLog.some(d => d.extensionId === bracketPairColorizerId); if (disablementLogEntry) { return; } state.disablementLog.push({ extensionId: bracketPairColorizerId, disablementDateTime: new Date().getTime() }); await this.setState(state); await this.extensionsWorkbenchService.setEnablement(extension, EnablementState.DisabledGlobally); const nativeBracketPairColorizationEnabledKey = 'editor.bracketPairColorization.enabled'; const bracketPairColorizationEnabled = !!this.configurationService.inspect(nativeBracketPairColorizationEnabledKey).user; this.notificationService.notify({ message: localize('bracketPairColorizer.notification', "The extension 'Bracket pair Colorizer' got disabled because it was deprecated."), severity: Severity.Info, actions: { primary: [ new Action('', localize('bracketPairColorizer.notification.action.uninstall', "Uninstall Extension"), undefined, undefined, () => { this.extensionsWorkbenchService.uninstall(extension); }), ], secondary: [ !bracketPairColorizationEnabled ? new Action('', localize('bracketPairColorizer.notification.action.enableNative', "Enable Native Bracket Pair Colorization"), undefined, undefined, () => { this.configurationService.updateValue(nativeBracketPairColorizationEnabledKey, true, ConfigurationTarget.USER); }) : undefined, new Action('', localize('bracketPairColorizer.notification.action.showMoreInfo', "More Info"), undefined, undefined, () => { this.openerService.open('https://github.com/microsoft/vscode/issues/155179'); }), ].filter(isDefined), } }); } private readonly storageKey = 'deprecatedExtensionMigrator.state'; private async getState(): Promise<State> { const jsonStr = await this.storageService.get(this.storageKey, StorageScope.APPLICATION, ''); if (jsonStr === '') { return { disablementLog: [] }; } return JSON.parse(jsonStr) as State; } private async setState(state: State): Promise<void> { const json = JSON.stringify(state); await this.storageService.store(this.storageKey, json, StorageScope.APPLICATION, StorageTarget.USER); } } interface State { disablementLog: { extensionId: string; disablementDateTime: number; }[]; } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(DeprecatedExtensionMigratorContribution, LifecyclePhase.Restored);
src/vs/workbench/contrib/deprecatedExtensionMigrator/browser/deprecatedExtensionMigrator.contribution.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017415713227819651, 0.00017155116074718535, 0.00016671237244736403, 0.00017192460654769093, 0.0000024164166916307295 ]
{ "id": 9, "code_window": [ "\t\tconst lineHeight = this.editor.getOption(EditorOption.lineHeight);\n", "\t\tconst width = this.editor.getLayoutInfo().contentWidth * 0.7;\n", "\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n", "\n", "\t\treturn null;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .editor-dictation-widget { background-color: var(--vscode-editor-background); padding: 2px; border-radius: 8px; display: flex; align-items: center; box-shadow: 0 4px 8px var(--vscode-widget-shadow); z-index: 1000; min-height: var(--vscode-editor-dictation-widget-height); line-height: var(--vscode-editor-dictation-widget-height); max-width: var(--vscode-editor-dictation-widget-width); } .monaco-editor .editor-dictation-widget .codicon.codicon-mic-filled { display: flex; align-items: center; width: 16px; height: 16px; } .monaco-editor .editor-dictation-widget.recording .codicon.codicon-mic-filled { color: var(--vscode-activityBarBadge-background); animation: editor-dictation-animation 1s infinite; } @keyframes editor-dictation-animation { 0% { color: var(--vscode-editorCursor-background); } 50% { color: var(--vscode-activityBarBadge-background); } 100% { color: var(--vscode-editorCursor-background); } }
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.css
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0005904872086830437, 0.0002610514929983765, 0.00016539708303753287, 0.0001733946119202301, 0.00016532311565242708 ]
{ "id": 9, "code_window": [ "\t\tconst lineHeight = this.editor.getOption(EditorOption.lineHeight);\n", "\t\tconst width = this.editor.getLayoutInfo().contentWidth * 0.7;\n", "\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n", "\n", "\t\treturn null;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { isUNC, toSlashes } from 'vs/base/common/extpath'; import * as json from 'vs/base/common/json'; import * as jsonEdit from 'vs/base/common/jsonEdit'; import { FormattingOptions } from 'vs/base/common/jsonFormatter'; import { normalizeDriveLetter } from 'vs/base/common/labels'; import { Schemas } from 'vs/base/common/network'; import { isAbsolute, posix } from 'vs/base/common/path'; import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform'; import { IExtUri, isEqualAuthority } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IWorkspaceBackupInfo, IFolderBackupInfo } from 'vs/platform/backup/common/backup'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { getRemoteAuthority } from 'vs/platform/remote/common/remoteHosts'; import { IBaseWorkspace, IRawFileWorkspaceFolder, IRawUriWorkspaceFolder, IWorkspaceIdentifier, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; export const IWorkspacesService = createDecorator<IWorkspacesService>('workspacesService'); export interface IWorkspacesService { readonly _serviceBrand: undefined; // Workspaces Management enterWorkspace(workspaceUri: URI): Promise<IEnterWorkspaceResult | undefined>; createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier>; deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void>; getWorkspaceIdentifier(workspaceUri: URI): Promise<IWorkspaceIdentifier>; // Workspaces History readonly onDidChangeRecentlyOpened: Event<void>; addRecentlyOpened(recents: IRecent[]): Promise<void>; removeRecentlyOpened(workspaces: URI[]): Promise<void>; clearRecentlyOpened(): Promise<void>; getRecentlyOpened(): Promise<IRecentlyOpened>; // Dirty Workspaces getDirtyWorkspaces(): Promise<Array<IWorkspaceBackupInfo | IFolderBackupInfo>>; } //#region Workspaces Recently Opened export interface IRecentlyOpened { workspaces: Array<IRecentWorkspace | IRecentFolder>; files: IRecentFile[]; } export type IRecent = IRecentWorkspace | IRecentFolder | IRecentFile; export interface IRecentWorkspace { readonly workspace: IWorkspaceIdentifier; label?: string; readonly remoteAuthority?: string; } export interface IRecentFolder { readonly folderUri: URI; label?: string; readonly remoteAuthority?: string; } export interface IRecentFile { readonly fileUri: URI; label?: string; readonly remoteAuthority?: string; } export function isRecentWorkspace(curr: IRecent): curr is IRecentWorkspace { return curr.hasOwnProperty('workspace'); } export function isRecentFolder(curr: IRecent): curr is IRecentFolder { return curr.hasOwnProperty('folderUri'); } export function isRecentFile(curr: IRecent): curr is IRecentFile { return curr.hasOwnProperty('fileUri'); } //#endregion //#region Workspace File Utilities export function isStoredWorkspaceFolder(obj: unknown): obj is IStoredWorkspaceFolder { return isRawFileWorkspaceFolder(obj) || isRawUriWorkspaceFolder(obj); } function isRawFileWorkspaceFolder(obj: unknown): obj is IRawFileWorkspaceFolder { const candidate = obj as IRawFileWorkspaceFolder | undefined; return typeof candidate?.path === 'string' && (!candidate.name || typeof candidate.name === 'string'); } function isRawUriWorkspaceFolder(obj: unknown): obj is IRawUriWorkspaceFolder { const candidate = obj as IRawUriWorkspaceFolder | undefined; return typeof candidate?.uri === 'string' && (!candidate.name || typeof candidate.name === 'string'); } export type IStoredWorkspaceFolder = IRawFileWorkspaceFolder | IRawUriWorkspaceFolder; export interface IStoredWorkspace extends IBaseWorkspace { folders: IStoredWorkspaceFolder[]; } export interface IWorkspaceFolderCreationData { readonly uri: URI; readonly name?: string; } export interface IUntitledWorkspaceInfo { readonly workspace: IWorkspaceIdentifier; readonly remoteAuthority?: string; } export interface IEnterWorkspaceResult { readonly workspace: IWorkspaceIdentifier; readonly backupPath?: string; } /** * Given a folder URI and the workspace config folder, computes the `IStoredWorkspaceFolder` * using a relative or absolute path or a uri. * Undefined is returned if the `folderURI` and the `targetConfigFolderURI` don't have the * same schema or authority. * * @param folderURI a workspace folder * @param forceAbsolute if set, keep the path absolute * @param folderName a workspace name * @param targetConfigFolderURI the folder where the workspace is living in */ export function getStoredWorkspaceFolder(folderURI: URI, forceAbsolute: boolean, folderName: string | undefined, targetConfigFolderURI: URI, extUri: IExtUri): IStoredWorkspaceFolder { // Scheme mismatch: use full absolute URI as `uri` if (folderURI.scheme !== targetConfigFolderURI.scheme) { return { name: folderName, uri: folderURI.toString(true) }; } // Always prefer a relative path if possible unless // prevented to make the workspace file shareable // with other users let folderPath = !forceAbsolute ? extUri.relativePath(targetConfigFolderURI, folderURI) : undefined; if (folderPath !== undefined) { if (folderPath.length === 0) { folderPath = '.'; } else { if (isWindows) { folderPath = massagePathForWindows(folderPath); } } } // We could not resolve a relative path else { // Local file: use `fsPath` if (folderURI.scheme === Schemas.file) { folderPath = folderURI.fsPath; if (isWindows) { folderPath = massagePathForWindows(folderPath); } } // Different authority: use full absolute URI else if (!extUri.isEqualAuthority(folderURI.authority, targetConfigFolderURI.authority)) { return { name: folderName, uri: folderURI.toString(true) }; } // Non-local file: use `path` of URI else { folderPath = folderURI.path; } } return { name: folderName, path: folderPath }; } function massagePathForWindows(folderPath: string) { // Drive letter should be upper case folderPath = normalizeDriveLetter(folderPath); // Always prefer slash over backslash unless // we deal with UNC paths where backslash is // mandatory. if (!isUNC(folderPath)) { folderPath = toSlashes(folderPath); } return folderPath; } export function toWorkspaceFolders(configuredFolders: IStoredWorkspaceFolder[], workspaceConfigFile: URI, extUri: IExtUri): WorkspaceFolder[] { const result: WorkspaceFolder[] = []; const seen: Set<string> = new Set(); const relativeTo = extUri.dirname(workspaceConfigFile); for (const configuredFolder of configuredFolders) { let uri: URI | undefined = undefined; if (isRawFileWorkspaceFolder(configuredFolder)) { if (configuredFolder.path) { uri = extUri.resolvePath(relativeTo, configuredFolder.path); } } else if (isRawUriWorkspaceFolder(configuredFolder)) { try { uri = URI.parse(configuredFolder.uri); if (uri.path[0] !== posix.sep) { uri = uri.with({ path: posix.sep + uri.path }); // this makes sure all workspace folder are absolute } } catch (e) { console.warn(e); // ignore } } if (uri) { // remove duplicates const comparisonKey = extUri.getComparisonKey(uri); if (!seen.has(comparisonKey)) { seen.add(comparisonKey); const name = configuredFolder.name || extUri.basenameOrAuthority(uri); result.push(new WorkspaceFolder({ uri, name, index: result.length }, configuredFolder)); } } } return result; } /** * Rewrites the content of a workspace file to be saved at a new location. * Throws an exception if file is not a valid workspace file */ export function rewriteWorkspaceFileForNewLocation(rawWorkspaceContents: string, configPathURI: URI, isFromUntitledWorkspace: boolean, targetConfigPathURI: URI, extUri: IExtUri) { const storedWorkspace = doParseStoredWorkspace(configPathURI, rawWorkspaceContents); const sourceConfigFolder = extUri.dirname(configPathURI); const targetConfigFolder = extUri.dirname(targetConfigPathURI); const rewrittenFolders: IStoredWorkspaceFolder[] = []; for (const folder of storedWorkspace.folders) { const folderURI = isRawFileWorkspaceFolder(folder) ? extUri.resolvePath(sourceConfigFolder, folder.path) : URI.parse(folder.uri); let absolute; if (isFromUntitledWorkspace) { absolute = false; // if it was an untitled workspace, try to make paths relative } else { absolute = !isRawFileWorkspaceFolder(folder) || isAbsolute(folder.path); // for existing workspaces, preserve whether a path was absolute or relative } rewrittenFolders.push(getStoredWorkspaceFolder(folderURI, absolute, folder.name, targetConfigFolder, extUri)); } // Preserve as much of the existing workspace as possible by using jsonEdit // and only changing the folders portion. const formattingOptions: FormattingOptions = { insertSpaces: false, tabSize: 4, eol: (isLinux || isMacintosh) ? '\n' : '\r\n' }; const edits = jsonEdit.setProperty(rawWorkspaceContents, ['folders'], rewrittenFolders, formattingOptions); let newContent = jsonEdit.applyEdits(rawWorkspaceContents, edits); if (isEqualAuthority(storedWorkspace.remoteAuthority, getRemoteAuthority(targetConfigPathURI))) { // unsaved remote workspaces have the remoteAuthority set. Remove it when no longer nexessary. newContent = jsonEdit.applyEdits(newContent, jsonEdit.removeProperty(newContent, ['remoteAuthority'], formattingOptions)); } return newContent; } function doParseStoredWorkspace(path: URI, contents: string): IStoredWorkspace { // Parse workspace file const storedWorkspace: IStoredWorkspace = json.parse(contents); // use fault tolerant parser // Filter out folders which do not have a path or uri set if (storedWorkspace && Array.isArray(storedWorkspace.folders)) { storedWorkspace.folders = storedWorkspace.folders.filter(folder => isStoredWorkspaceFolder(folder)); } else { throw new Error(`${path} looks like an invalid workspace file.`); } return storedWorkspace; } //#endregion //#region Workspace Storage interface ISerializedRecentWorkspace { readonly workspace: { id: string; configPath: string; }; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentFolder { readonly folderUri: string; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentFile { readonly fileUri: string; readonly label?: string; readonly remoteAuthority?: string; } interface ISerializedRecentlyOpened { readonly entries: Array<ISerializedRecentWorkspace | ISerializedRecentFolder | ISerializedRecentFile>; // since 1.55 } export type RecentlyOpenedStorageData = object; function isSerializedRecentWorkspace(data: any): data is ISerializedRecentWorkspace { return data.workspace && typeof data.workspace === 'object' && typeof data.workspace.id === 'string' && typeof data.workspace.configPath === 'string'; } function isSerializedRecentFolder(data: any): data is ISerializedRecentFolder { return typeof data.folderUri === 'string'; } function isSerializedRecentFile(data: any): data is ISerializedRecentFile { return typeof data.fileUri === 'string'; } export function restoreRecentlyOpened(data: RecentlyOpenedStorageData | undefined, logService: ILogService): IRecentlyOpened { const result: IRecentlyOpened = { workspaces: [], files: [] }; if (data) { const restoreGracefully = function <T>(entries: T[], onEntry: (entry: T, index: number) => void) { for (let i = 0; i < entries.length; i++) { try { onEntry(entries[i], i); } catch (e) { logService.warn(`Error restoring recent entry ${JSON.stringify(entries[i])}: ${e.toString()}. Skip entry.`); } } }; const storedRecents = data as ISerializedRecentlyOpened; if (Array.isArray(storedRecents.entries)) { restoreGracefully(storedRecents.entries, entry => { const label = entry.label; const remoteAuthority = entry.remoteAuthority; if (isSerializedRecentWorkspace(entry)) { result.workspaces.push({ label, remoteAuthority, workspace: { id: entry.workspace.id, configPath: URI.parse(entry.workspace.configPath) } }); } else if (isSerializedRecentFolder(entry)) { result.workspaces.push({ label, remoteAuthority, folderUri: URI.parse(entry.folderUri) }); } else if (isSerializedRecentFile(entry)) { result.files.push({ label, remoteAuthority, fileUri: URI.parse(entry.fileUri) }); } }); } } return result; } export function toStoreData(recents: IRecentlyOpened): RecentlyOpenedStorageData { const serialized: ISerializedRecentlyOpened = { entries: [] }; for (const recent of recents.workspaces) { if (isRecentFolder(recent)) { serialized.entries.push({ folderUri: recent.folderUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority }); } else { serialized.entries.push({ workspace: { id: recent.workspace.id, configPath: recent.workspace.configPath.toString() }, label: recent.label, remoteAuthority: recent.remoteAuthority }); } } for (const recent of recents.files) { serialized.entries.push({ fileUri: recent.fileUri.toString(), label: recent.label, remoteAuthority: recent.remoteAuthority }); } return serialized; } //#endregion
src/vs/platform/workspaces/common/workspaces.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017678980657365173, 0.00017275857680942863, 0.00016285748279187828, 0.0001736636331770569, 0.000003179427721988759 ]
{ "id": 9, "code_window": [ "\t\tconst lineHeight = this.editor.getOption(EditorOption.lineHeight);\n", "\t\tconst width = this.editor.getLayoutInfo().contentWidth * 0.7;\n", "\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n", "\n", "\t\treturn null;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 135 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { OperatingSystem } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { ITextEditorSelection } from 'vs/platform/editor/common/editor'; import { IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ITerminalLinkOpener, ITerminalSimpleLink } from 'vs/workbench/contrib/terminalContrib/links/browser/links'; import { osPathModule, updateLinkWithRelativeCwd } from 'vs/workbench/contrib/terminalContrib/links/browser/terminalLinkHelpers'; import { ITerminalCapabilityStore, TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { QueryBuilder } from 'vs/workbench/services/search/common/queryBuilder'; import { ISearchService } from 'vs/workbench/services/search/common/search'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { getLinkSuffix } from 'vs/workbench/contrib/terminalContrib/links/browser/terminalLinkParsing'; import { ITerminalLogService } from 'vs/platform/terminal/common/terminal'; export class TerminalLocalFileLinkOpener implements ITerminalLinkOpener { constructor( @IEditorService private readonly _editorService: IEditorService, ) { } async open(link: ITerminalSimpleLink): Promise<void> { if (!link.uri) { throw new Error('Tried to open file link without a resolved URI'); } const linkSuffix = link.parsedLink ? link.parsedLink.suffix : getLinkSuffix(link.text); let selection: ITextEditorSelection | undefined = link.selection; if (!selection) { selection = linkSuffix?.row === undefined ? undefined : { startLineNumber: linkSuffix.row ?? 1, startColumn: linkSuffix.col ?? 1, endLineNumber: linkSuffix.rowEnd, endColumn: linkSuffix.colEnd }; } await this._editorService.openEditor({ resource: link.uri, options: { pinned: true, selection, revealIfOpened: true } }); } } export class TerminalLocalFolderInWorkspaceLinkOpener implements ITerminalLinkOpener { constructor(@ICommandService private readonly _commandService: ICommandService) { } async open(link: ITerminalSimpleLink): Promise<void> { if (!link.uri) { throw new Error('Tried to open folder in workspace link without a resolved URI'); } await this._commandService.executeCommand('revealInExplorer', link.uri); } } export class TerminalLocalFolderOutsideWorkspaceLinkOpener implements ITerminalLinkOpener { constructor(@IHostService private readonly _hostService: IHostService) { } async open(link: ITerminalSimpleLink): Promise<void> { if (!link.uri) { throw new Error('Tried to open folder in workspace link without a resolved URI'); } this._hostService.openWindow([{ folderUri: link.uri }], { forceNewWindow: true }); } } export class TerminalSearchLinkOpener implements ITerminalLinkOpener { protected _fileQueryBuilder = this._instantiationService.createInstance(QueryBuilder); constructor( private readonly _capabilities: ITerminalCapabilityStore, private readonly _initialCwd: string, private readonly _localFileOpener: TerminalLocalFileLinkOpener, private readonly _localFolderInWorkspaceOpener: TerminalLocalFolderInWorkspaceLinkOpener, private readonly _getOS: () => OperatingSystem, @IFileService private readonly _fileService: IFileService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalLogService private readonly _logService: ITerminalLogService, @IQuickInputService private readonly _quickInputService: IQuickInputService, @ISearchService private readonly _searchService: ISearchService, @IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService, @IWorkbenchEnvironmentService private readonly _workbenchEnvironmentService: IWorkbenchEnvironmentService, ) { } async open(link: ITerminalSimpleLink): Promise<void> { const osPath = osPathModule(this._getOS()); const pathSeparator = osPath.sep; // Remove file:/// and any leading ./ or ../ since quick access doesn't understand that format let text = link.text.replace(/^file:\/\/\/?/, ''); text = osPath.normalize(text).replace(/^(\.+[\\/])+/, ''); // Remove `:<one or more non number characters>` from the end of the link. // Examples: // - Ruby stack traces: <link>:in ... // - Grep output: <link>:<result line> // This only happens when the colon is _not_ followed by a forward- or back-slash as that // would break absolute Windows paths (eg. `C:/Users/...`). text = text.replace(/:[^\\/\d][^\d]*$/, ''); // Remove any trailing periods after the line/column numbers, to prevent breaking the search feature, #200257 // Examples: // "Check your code Test.tsx:12:45." -> Test.tsx:12:45 // "Check your code Test.tsx:12." -> Test.tsx:12 text = text.replace(/\.$/, ''); // If any of the names of the folders in the workspace matches // a prefix of the link, remove that prefix and continue this._workspaceContextService.getWorkspace().folders.forEach((folder) => { if (text.substring(0, folder.name.length + 1) === folder.name + pathSeparator) { text = text.substring(folder.name.length + 1); return; } }); let cwdResolvedText = text; if (this._capabilities.has(TerminalCapability.CommandDetection)) { cwdResolvedText = updateLinkWithRelativeCwd(this._capabilities, link.bufferRange.start.y, text, osPath, this._logService)?.[0] || text; } // Try open the cwd resolved link first if (await this._tryOpenExactLink(cwdResolvedText, link)) { return; } // If the cwd resolved text didn't match, try find the link without the cwd resolved, for // example when a command prints paths in a sub-directory of the current cwd if (text !== cwdResolvedText) { if (await this._tryOpenExactLink(text, link)) { return; } } // Fallback to searching quick access return this._quickInputService.quickAccess.show(text); } private async _getExactMatch(sanitizedLink: string): Promise<IResourceMatch | undefined> { // Make the link relative to the cwd if it isn't absolute const os = this._getOS(); const pathModule = osPathModule(os); const isAbsolute = pathModule.isAbsolute(sanitizedLink); let absolutePath: string | undefined = isAbsolute ? sanitizedLink : undefined; if (!isAbsolute && this._initialCwd.length > 0) { absolutePath = pathModule.join(this._initialCwd, sanitizedLink); } // Try open as an absolute link let resourceMatch: IResourceMatch | undefined; if (absolutePath) { let normalizedAbsolutePath: string = absolutePath; if (os === OperatingSystem.Windows) { normalizedAbsolutePath = absolutePath.replace(/\\/g, '/'); if (normalizedAbsolutePath.match(/[a-z]:/i)) { normalizedAbsolutePath = `/${normalizedAbsolutePath}`; } } let uri: URI; if (this._workbenchEnvironmentService.remoteAuthority) { uri = URI.from({ scheme: Schemas.vscodeRemote, authority: this._workbenchEnvironmentService.remoteAuthority, path: normalizedAbsolutePath }); } else { uri = URI.file(normalizedAbsolutePath); } try { const fileStat = await this._fileService.stat(uri); resourceMatch = { uri, isDirectory: fileStat.isDirectory }; } catch { // File or dir doesn't exist, continue on } } // Search the workspace if an exact match based on the absolute path was not found if (!resourceMatch) { const results = await this._searchService.fileSearch( this._fileQueryBuilder.file(this._workspaceContextService.getWorkspace().folders, { filePattern: sanitizedLink, maxResults: 2 }) ); if (results.results.length > 0) { if (results.results.length === 1) { // If there's exactly 1 search result, return it regardless of whether it's // exact or partial. resourceMatch = { uri: results.results[0].resource }; } else if (!isAbsolute) { // For non-absolute links, exact link matching is allowed only if there is a single an exact // file match. For example searching for `foo.txt` when there is no cwd information // available (ie. only the initial cwd) should open the file directly only if there is a // single file names `foo.txt` anywhere within the folder. These same rules apply to // relative paths with folders such as `src/foo.txt`. const results = await this._searchService.fileSearch( this._fileQueryBuilder.file(this._workspaceContextService.getWorkspace().folders, { filePattern: `**/${sanitizedLink}` }) ); // Find an exact match if it exists const exactMatches = results.results.filter(e => e.resource.toString().endsWith(sanitizedLink)); if (exactMatches.length === 1) { resourceMatch = { uri: exactMatches[0].resource }; } } } } return resourceMatch; } private async _tryOpenExactLink(text: string, link: ITerminalSimpleLink): Promise<boolean> { const sanitizedLink = text.replace(/:\d+(:\d+)?$/, ''); try { const result = await this._getExactMatch(sanitizedLink); if (result) { const { uri, isDirectory } = result; const linkToOpen = { // Use the absolute URI's path here so the optional line/col get detected text: result.uri.path + (text.match(/:\d+(:\d+)?$/)?.[0] || ''), uri, bufferRange: link.bufferRange, type: link.type }; if (uri) { await (isDirectory ? this._localFolderInWorkspaceOpener.open(linkToOpen) : this._localFileOpener.open(linkToOpen)); return true; } } } catch { return false; } return false; } } interface IResourceMatch { uri: URI; isDirectory?: boolean; } export class TerminalUrlLinkOpener implements ITerminalLinkOpener { constructor( private readonly _isRemote: boolean, @IOpenerService private readonly _openerService: IOpenerService, @IConfigurationService private readonly _configurationService: IConfigurationService ) { } async open(link: ITerminalSimpleLink): Promise<void> { if (!link.uri) { throw new Error('Tried to open a url without a resolved URI'); } // It's important to use the raw string value here to avoid converting pre-encoded values // from the URL like `%2B` -> `+`. this._openerService.open(link.text, { allowTunneling: this._isRemote && this._configurationService.getValue('remote.forwardOnOpen'), allowContributedOpeners: true, openExternal: true }); } }
src/vs/workbench/contrib/terminalContrib/links/browser/terminalLinkOpeners.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017453634063713253, 0.00017140319687314332, 0.00016479856276419014, 0.00017216248670592904, 0.0000025704841846163617 ]
{ "id": 9, "code_window": [ "\t\tconst lineHeight = this.editor.getOption(EditorOption.lineHeight);\n", "\t\tconst width = this.editor.getLayoutInfo().contentWidth * 0.7;\n", "\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n", "\n", "\t\treturn null;\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`);\n", "\t\tthis.domNode.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`);\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 135 }
{ "original": { "content": "\t\tfor (extendToBottom = 0; extendToBottom < linesBelow; extendToBottom++) {\n\t\t\tconst origLine = move.original.endLineNumberExclusive + extendToBottom;\n\t\t\tconst modLine = move.modified.endLineNumberExclusive + extendToBottom;\n\t\t\tif (origLine > originalLines.length || modLine > modifiedLines.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (extendToBottom > 0) {\n\t\t\toriginalSet.addRange(new LineRange(move.original.endLineNumberExclusive, move.original.endLineNumberExclusive + extendToBottom));\n\t\t\tmodifiedSet.addRange(new LineRange(move.modified.endLineNumberExclusive, move.modified.endLineNumberExclusive + extendToBottom));\n\t\t}", "fileName": "./1.txt" }, "modified": { "content": "\t\tfor (extendToBottom = 0; extendToBottom < linesBelow; extendToBottom++) {\n\t\t\tconst origLine = move.original.endLineNumberExclusive + extendToBottom;\n\t\t\tconst modLine = move.modified.endLineNumberExclusive + extendToBottom;\n\t\t\tif (origLine > originalLines.length || modLine > modifiedLines.length) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (originalLines[origLine - 1].trim().length !== 0) {\n\t\t\t\textendToBottomWithoutEmptyLines = extendToBottom + 1;\n\t\t\t}\n\t\t}\n\n\t\tif (extendToBottomWithoutEmptyLines > 0) {\n\t\t\toriginalSet.addRange(new LineRange(move.original.endLineNumberExclusive, move.original.endLineNumberExclusive + extendToBottomWithoutEmptyLines));\n\t\t\tmodifiedSet.addRange(new LineRange(move.modified.endLineNumberExclusive, move.modified.endLineNumberExclusive + extendToBottomWithoutEmptyLines));\n\t\t}", "fileName": "./2.txt" }, "diffs": [ { "originalRange": "[13,13)", "modifiedRange": "[13,16)", "innerChanges": null }, { "originalRange": "[15,18)", "modifiedRange": "[18,21)", "innerChanges": [ { "originalRange": "[15,21 -> 15,21]", "modifiedRange": "[18,21 -> 18,38]" }, { "originalRange": "[16,130 -> 16,130]", "modifiedRange": "[19,130 -> 19,147]" }, { "originalRange": "[17,130 -> 17,130]", "modifiedRange": "[20,130 -> 20,147]" } ] } ] }
src/vs/editor/test/node/diffing/fixtures/shifting-twice/legacy.expected.diff.json
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001733203826006502, 0.00017145590391010046, 0.00016718085680622607, 0.00017266118084080517, 0.000002488850668669329 ]
{ "id": 10, "code_window": [ "\t\tthis.editor.layoutContentWidget(this);\n", "\t}\n", "\n", "\tactive(): void {\n", "\t\tthis.elements.main.classList.add('recording');\n", "\t}\n", "\n", "\thide() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.add('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 150 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.8818145394325256, 0.034158606082201004, 0.00016043380310293287, 0.0001702406443655491, 0.16354091465473175 ]
{ "id": 10, "code_window": [ "\t\tthis.editor.layoutContentWidget(this);\n", "\t}\n", "\n", "\tactive(): void {\n", "\t\tthis.elements.main.classList.add('recording');\n", "\t}\n", "\n", "\thide() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.add('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 150 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as browser from 'vs/base/browser/browser'; import { mainWindow } from 'vs/base/browser/window'; import * as platform from 'vs/base/common/platform'; export const enum KeyboardSupport { Always, FullScreen, None } /** * Browser feature we can support in current platform, browser and environment. */ export const BrowserFeatures = { clipboard: { writeText: ( platform.isNative || (document.queryCommandSupported && document.queryCommandSupported('copy')) || !!(navigator && navigator.clipboard && navigator.clipboard.writeText) ), readText: ( platform.isNative || !!(navigator && navigator.clipboard && navigator.clipboard.readText) ) }, keyboard: (() => { if (platform.isNative || browser.isStandalone()) { return KeyboardSupport.Always; } if ((<any>navigator).keyboard || browser.isSafari) { return KeyboardSupport.FullScreen; } return KeyboardSupport.None; })(), // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast touch: 'ontouchstart' in mainWindow || navigator.maxTouchPoints > 0, pointerEvents: mainWindow.PointerEvent && ('ontouchstart' in mainWindow || navigator.maxTouchPoints > 0) };
src/vs/base/browser/canIUse.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017476749781053513, 0.00017056816432159394, 0.00016520464851055294, 0.00017123305588029325, 0.000003878405095747439 ]
{ "id": 10, "code_window": [ "\t\tthis.editor.layoutContentWidget(this);\n", "\t}\n", "\n", "\tactive(): void {\n", "\t\tthis.elements.main.classList.add('recording');\n", "\t}\n", "\n", "\thide() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.add('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 150 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MainContext, MainThreadLanguagesShape, IMainContext, ExtHostLanguagesShape } from './extHost.protocol'; import type * as vscode from 'vscode'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters'; import { StandardTokenType, Range, Position, LanguageStatusSeverity } from 'vs/workbench/api/common/extHostTypes'; import Severity from 'vs/base/common/severity'; import { disposableTimeout } from 'vs/base/common/async'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { CommandsConverter } from 'vs/workbench/api/common/extHostCommands'; import { IURITransformer } from 'vs/base/common/uriIpc'; import { checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions'; export class ExtHostLanguages implements ExtHostLanguagesShape { private readonly _proxy: MainThreadLanguagesShape; private _languageIds: string[] = []; constructor( mainContext: IMainContext, private readonly _documents: ExtHostDocuments, private readonly _commands: CommandsConverter, private readonly _uriTransformer: IURITransformer | undefined ) { this._proxy = mainContext.getProxy(MainContext.MainThreadLanguages); } $acceptLanguageIds(ids: string[]): void { this._languageIds = ids; } async getLanguages(): Promise<string[]> { return this._languageIds.slice(0); } async changeLanguage(uri: vscode.Uri, languageId: string): Promise<vscode.TextDocument> { await this._proxy.$changeLanguage(uri, languageId); const data = this._documents.getDocumentData(uri); if (!data) { throw new Error(`document '${uri.toString()}' NOT found`); } return data.document; } async tokenAtPosition(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.TokenInformation> { const versionNow = document.version; const pos = typeConvert.Position.from(position); const info = await this._proxy.$tokensAtPosition(document.uri, pos); const defaultRange = { type: StandardTokenType.Other, range: document.getWordRangeAtPosition(position) ?? new Range(position.line, position.character, position.line, position.character) }; if (!info) { // no result return defaultRange; } const result = { range: typeConvert.Range.to(info.range), type: typeConvert.TokenType.to(info.type) }; if (!result.range.contains(<Position>position)) { // bogous result return defaultRange; } if (versionNow !== document.version) { // concurrent change return defaultRange; } return result; } private _handlePool: number = 0; private _ids = new Set<string>(); createLanguageStatusItem(extension: IExtensionDescription, id: string, selector: vscode.DocumentSelector): vscode.LanguageStatusItem { const handle = this._handlePool++; const proxy = this._proxy; const ids = this._ids; // enforce extension unique identifier const fullyQualifiedId = `${extension.identifier.value}/${id}`; if (ids.has(fullyQualifiedId)) { throw new Error(`LanguageStatusItem with id '${id}' ALREADY exists`); } ids.add(fullyQualifiedId); const data: Omit<vscode.LanguageStatusItem, 'dispose' | 'text2'> = { selector, id, name: extension.displayName ?? extension.name, severity: LanguageStatusSeverity.Information, command: undefined, text: '', detail: '', busy: false }; let soonHandle: IDisposable | undefined; const commandDisposables = new DisposableStore(); const updateAsync = () => { soonHandle?.dispose(); if (!ids.has(fullyQualifiedId)) { console.warn(`LanguageStatusItem (${id}) from ${extension.identifier.value} has been disposed and CANNOT be updated anymore`); return; // disposed in the meantime } soonHandle = disposableTimeout(() => { commandDisposables.clear(); this._proxy.$setLanguageStatus(handle, { id: fullyQualifiedId, name: data.name ?? extension.displayName ?? extension.name, source: extension.displayName ?? extension.name, selector: typeConvert.DocumentSelector.from(data.selector, this._uriTransformer), label: data.text, detail: data.detail ?? '', severity: data.severity === LanguageStatusSeverity.Error ? Severity.Error : data.severity === LanguageStatusSeverity.Warning ? Severity.Warning : Severity.Info, command: data.command && this._commands.toInternal(data.command, commandDisposables), accessibilityInfo: data.accessibilityInformation, busy: data.busy }); }, 0); }; const result: vscode.LanguageStatusItem = { dispose() { commandDisposables.dispose(); soonHandle?.dispose(); proxy.$removeLanguageStatus(handle); ids.delete(fullyQualifiedId); }, get id() { return data.id; }, get name() { return data.name; }, set name(value) { data.name = value; updateAsync(); }, get selector() { return data.selector; }, set selector(value) { data.selector = value; updateAsync(); }, get text() { return data.text; }, set text(value) { data.text = value; updateAsync(); }, set text2(value) { checkProposedApiEnabled(extension, 'languageStatusText'); data.text = value; updateAsync(); }, get text2() { checkProposedApiEnabled(extension, 'languageStatusText'); return data.text; }, get detail() { return data.detail; }, set detail(value) { data.detail = value; updateAsync(); }, get severity() { return data.severity; }, set severity(value) { data.severity = value; updateAsync(); }, get accessibilityInformation() { return data.accessibilityInformation; }, set accessibilityInformation(value) { data.accessibilityInformation = value; updateAsync(); }, get command() { return data.command; }, set command(value) { data.command = value; updateAsync(); }, get busy() { return data.busy; }, set busy(value: boolean) { data.busy = value; updateAsync(); } }; updateAsync(); return result; } }
src/vs/workbench/api/common/extHostLanguages.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017576033133082092, 0.0001717606937745586, 0.00016678393876645714, 0.0001719678402878344, 0.000002230682184745092 ]
{ "id": 10, "code_window": [ "\t\tthis.editor.layoutContentWidget(this);\n", "\t}\n", "\n", "\tactive(): void {\n", "\t\tthis.elements.main.classList.add('recording');\n", "\t}\n", "\n", "\thide() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.add('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 150 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as fs from 'fs'; import * as platform from 'vs/base/common/platform'; import { enumeratePowerShellInstallations, getFirstAvailablePowerShellInstallation, IPowerShellExeDetails } from 'vs/base/node/powershell'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; function checkPath(exePath: string) { // Check to see if the path exists let pathCheckResult = false; try { const stat = fs.statSync(exePath); pathCheckResult = stat.isFile(); } catch { // fs.exists throws on Windows with SymbolicLinks so we // also use lstat to try and see if the file exists. try { pathCheckResult = fs.statSync(fs.readlinkSync(exePath)).isFile(); } catch { } } assert.strictEqual(pathCheckResult, true); } if (platform.isWindows) { suite('PowerShell finder', () => { ensureNoDisposablesAreLeakedInTestSuite(); test('Can find first available PowerShell', async () => { const pwshExe = await getFirstAvailablePowerShellInstallation(); const exePath = pwshExe?.exePath; assert.notStrictEqual(exePath, null); assert.notStrictEqual(pwshExe?.displayName, null); checkPath(exePath!); }); test('Can enumerate PowerShells', async () => { const pwshs = new Array<IPowerShellExeDetails>(); for await (const p of enumeratePowerShellInstallations()) { pwshs.push(p); } const powershellLog = 'Found these PowerShells:\n' + pwshs.map(p => `${p.displayName}: ${p.exePath}`).join('\n'); assert.strictEqual(pwshs.length >= 1, true, powershellLog); for (const pwsh of pwshs) { checkPath(pwsh.exePath); } // The last one should always be Windows PowerShell. assert.strictEqual(pwshs[pwshs.length - 1].displayName, 'Windows PowerShell', powershellLog); }); }); }
src/vs/base/test/node/powershell.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001758067519403994, 0.00017246640345547348, 0.00016984129615593702, 0.00017250388918910176, 0.000001918089083119412 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\thide() {\n", "\t\tthis.elements.main.classList.remove('recording');\n", "\t\tthis.editor.removeContentWidget(this);\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.remove('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 154 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.34985223412513733, 0.021150261163711548, 0.0001630658662179485, 0.00016905867960304022, 0.07568622380495071 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\thide() {\n", "\t\tthis.elements.main.classList.remove('recording');\n", "\t\tthis.editor.removeContentWidget(this);\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.remove('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 154 }
#!/usr/bin/env bash # On Fedora $SNAP is under /var and there is some magic to map it to /snap. # We need to handle that case and reset $SNAP SNAP=$(echo "$SNAP" | sed -e "s|/var/lib/snapd||g") # # Exports are based on https://github.com/snapcore/snapcraft/blob/master/extensions/desktop/common/desktop-exports # # ensure_dir_exists calls `mkdir -p` if the given path is not a directory. # This speeds up execution time by avoiding unnecessary calls to mkdir. # # Usage: ensure_dir_exists <path> [<mkdir-options>]... # function ensure_dir_exists() { [ -d "$1" ] || mkdir -p "$@" } declare -A PIDS function async_exec() { "$@" & PIDS[$!]=$* } function wait_for_async_execs() { for pid in "${!PIDS[@]}" do wait "$pid" && continue || echo "ERROR: ${PIDS[$pid]} exited abnormally with status $?" done } function prepend_dir() { local -n var="$1" local dir="$2" # We can't check if the dir exists when the dir contains variables if [[ "$dir" == *"\$"* || -d "$dir" ]]; then export "${!var}=${dir}${var:+:$var}" fi } function append_dir() { local -n var="$1" local dir="$2" # We can't check if the dir exists when the dir contains variables if [[ "$dir" == *"\$"* || -d "$dir" ]]; then export "${!var}=${var:+$var:}${dir}" fi } function copy_env_variable() { local -n var="$1" if [[ "+$var" ]]; then export "${!var}_VSCODE_SNAP_ORIG=${var}" else export "${!var}_VSCODE_SNAP_ORIG=''" fi } # shellcheck source=/dev/null source "$SNAP_USER_DATA/.last_revision" 2>/dev/null || true if [ "$SNAP_DESKTOP_LAST_REVISION" = "$SNAP_VERSION" ]; then needs_update=false else needs_update=true fi # Set $REALHOME to the users real home directory REALHOME=$(getent passwd $UID | cut -d ':' -f 6) # Set config folder to local path ensure_dir_exists "$SNAP_USER_DATA/.config" chmod 700 "$SNAP_USER_DATA/.config" if [ "$SNAP_ARCH" == "amd64" ]; then ARCH="x86_64-linux-gnu" elif [ "$SNAP_ARCH" == "armhf" ]; then ARCH="arm-linux-gnueabihf" elif [ "$SNAP_ARCH" == "arm64" ]; then ARCH="aarch64-linux-gnu" else ARCH="$SNAP_ARCH-linux-gnu" fi export SNAP_LAUNCHER_ARCH_TRIPLET="$ARCH" function is_subpath() { dir="$(realpath "$1")" parent="$(realpath "$2")" [ "${dir##"${parent}"/}" != "${dir}" ] && return 0 || return 1 } function can_open_file() { [ -f "$1" ] && [ -r "$1" ] } # Preserve system variables that get modified below copy_env_variable XDG_CONFIG_DIRS copy_env_variable XDG_DATA_DIRS copy_env_variable LOCPATH copy_env_variable GIO_MODULE_DIR copy_env_variable GSETTINGS_SCHEMA_DIR copy_env_variable GDK_PIXBUF_MODULE_FILE copy_env_variable GDK_PIXBUF_MODULEDIR copy_env_variable GDK_BACKEND copy_env_variable GTK_PATH copy_env_variable GTK_EXE_PREFIX copy_env_variable GTK_IM_MODULE_FILE # XDG Config prepend_dir XDG_CONFIG_DIRS "$SNAP/etc/xdg" # Define snaps' own data dir prepend_dir XDG_DATA_DIRS "$SNAP/usr/share" prepend_dir XDG_DATA_DIRS "$SNAP/share" prepend_dir XDG_DATA_DIRS "$SNAP/data-dir" prepend_dir XDG_DATA_DIRS "$SNAP_USER_DATA" # Set XDG_DATA_HOME to local path ensure_dir_exists "$SNAP_USER_DATA/.local/share" # Workaround for GLib < 2.53.2 not searching for schemas in $XDG_DATA_HOME: # https://bugzilla.gnome.org/show_bug.cgi?id=741335 prepend_dir XDG_DATA_DIRS "$SNAP_USER_DATA/.local/share" # Set cache folder to local path if [[ -d "$SNAP_USER_DATA/.cache" && ! -e "$SNAP_USER_COMMON/.cache" ]]; then # the .cache directory used to be stored under $SNAP_USER_DATA, migrate it mv "$SNAP_USER_DATA/.cache" "$SNAP_USER_COMMON/" fi ensure_dir_exists "$SNAP_USER_COMMON/.cache" # Create $XDG_RUNTIME_DIR if not exists (to be removed when LP: #1656340 is fixed) # shellcheck disable=SC2174 ensure_dir_exists "$XDG_RUNTIME_DIR" -m 700 # Ensure the app finds locale definitions (requires locales-all to be installed) append_dir LOCPATH "$SNAP/usr/lib/locale" # If detect wayland server socket, then set environment so applications prefer # wayland, and setup compat symlink (until we use user mounts. Remember, # XDG_RUNTIME_DIR is /run/user/<uid>/snap.$SNAP so look in the parent directory # for the socket. For details: # https://forum.snapcraft.io/t/wayland-dconf-and-xdg-runtime-dir/186/10 # Applications that don't support wayland natively may define DISABLE_WAYLAND # (to any non-empty value) to skip that logic entirely. wayland_available=false if [[ -n "$XDG_RUNTIME_DIR" && -z "$DISABLE_WAYLAND" ]]; then wdisplay="wayland-0" if [ -n "$WAYLAND_DISPLAY" ]; then wdisplay="$WAYLAND_DISPLAY" fi wayland_sockpath="$XDG_RUNTIME_DIR/../$wdisplay" wayland_snappath="$XDG_RUNTIME_DIR/$wdisplay" if [ -S "$wayland_sockpath" ]; then # if running under wayland, use it #export WAYLAND_DEBUG=1 # shellcheck disable=SC2034 wayland_available=true # create the compat symlink for now if [ ! -e "$wayland_snappath" ]; then ln -s "$wayland_sockpath" "$wayland_snappath" fi fi fi # Keep an array of data dirs, for looping through them IFS=':' read -r -a data_dirs_array <<< "$XDG_DATA_DIRS" # Build mime.cache # needed for gtk and qt icon if [ "$needs_update" = true ]; then rm -rf "$SNAP_USER_DATA/.local/share/mime" if [ ! -f "$SNAP/usr/share/mime/mime.cache" ]; then if command -v update-mime-database >/dev/null; then cp --preserve=timestamps -dR "$SNAP/usr/share/mime" "$SNAP_USER_DATA/.local/share" async_exec update-mime-database "$SNAP_USER_DATA/.local/share/mime" fi fi fi # Gio modules and cache (including gsettings module) export GIO_MODULE_DIR="$SNAP_USER_COMMON/.cache/gio-modules" function compile_giomodules { if [ -f "$1/glib-2.0/gio-querymodules" ]; then rm -rf "$GIO_MODULE_DIR" ensure_dir_exists "$GIO_MODULE_DIR" ln -s "$SNAP"/usr/lib/"$ARCH"/gio/modules/*.so "$GIO_MODULE_DIR" "$1/glib-2.0/gio-querymodules" "$GIO_MODULE_DIR" fi } if [ "$needs_update" = true ]; then async_exec compile_giomodules "/snap/core20/current/usr/lib/$ARCH" fi # Setup compiled gsettings schema export GSETTINGS_SCHEMA_DIR="$SNAP_USER_DATA/.local/share/glib-2.0/schemas" function compile_schemas { if [ -f "$1" ]; then rm -rf "$GSETTINGS_SCHEMA_DIR" ensure_dir_exists "$GSETTINGS_SCHEMA_DIR" for ((i = 0; i < ${#data_dirs_array[@]}; i++)); do schema_dir="${data_dirs_array[$i]}/glib-2.0/schemas" if [ -f "$schema_dir/gschemas.compiled" ]; then # This directory already has compiled schemas continue fi if [ -n "$(ls -A "$schema_dir"/*.xml 2>/dev/null)" ]; then ln -s "$schema_dir"/*.xml "$GSETTINGS_SCHEMA_DIR" fi if [ -n "$(ls -A "$schema_dir"/*.override 2>/dev/null)" ]; then ln -s "$schema_dir"/*.override "$GSETTINGS_SCHEMA_DIR" fi done # Only compile schemas if we copied anything if [ -n "$(ls -A "$GSETTINGS_SCHEMA_DIR"/*.xml "$GSETTINGS_SCHEMA_DIR"/*.override 2>/dev/null)" ]; then "$1" "$GSETTINGS_SCHEMA_DIR" fi fi } if [ "$needs_update" = true ]; then async_exec compile_schemas "/snap/core20/current/usr/lib/$ARCH/glib-2.0/glib-compile-schemas" fi # Gdk-pixbuf loaders export GDK_PIXBUF_MODULE_FILE="$SNAP_USER_COMMON/.cache/gdk-pixbuf-loaders.cache" export GDK_PIXBUF_MODULEDIR="$SNAP/usr/lib/$ARCH/gdk-pixbuf-2.0/2.10.0/loaders" if [ "$needs_update" = true ] || [ ! -f "$GDK_PIXBUF_MODULE_FILE" ]; then rm -f "$GDK_PIXBUF_MODULE_FILE" if [ -f "$SNAP/usr/lib/$ARCH/gdk-pixbuf-2.0/gdk-pixbuf-query-loaders" ]; then async_exec "$SNAP/usr/lib/$ARCH/gdk-pixbuf-2.0/gdk-pixbuf-query-loaders" > "$GDK_PIXBUF_MODULE_FILE" fi fi # shellcheck disable=SC2154 if [ "$wayland_available" = true ]; then export GDK_BACKEND="wayland" fi append_dir GTK_PATH "$SNAP/usr/lib/$ARCH/gtk-3.0" append_dir GTK_PATH "$SNAP/usr/lib/gtk-3.0" # We don't have gtk libraries in this path but # enforcing this environment variable will disallow # gtk binaries like `gtk-query-immodules` to not search # in system default library paths. # Based on https://gitlab.gnome.org/GNOME/gtk/-/blob/main/gtk/gtkmodules.c#L104-136 export GTK_EXE_PREFIX="$SNAP/usr" # ibus and fcitx integration GTK_IM_MODULE_DIR="$SNAP_USER_COMMON/.cache/immodules" export GTK_IM_MODULE_FILE="$GTK_IM_MODULE_DIR/immodules.cache" # shellcheck disable=SC2154 if [ "$needs_update" = true ]; then rm -rf "$GTK_IM_MODULE_DIR" ensure_dir_exists "$GTK_IM_MODULE_DIR" ln -s "$SNAP"/usr/lib/"$ARCH"/gtk-3.0/3.0.0/immodules/*.so "$GTK_IM_MODULE_DIR" async_exec "$SNAP/usr/lib/$ARCH/libgtk-3-0/gtk-query-immodules-3.0" > "$GTK_IM_MODULE_FILE" fi # shellcheck disable=SC2154 [ "$needs_update" = true ] && echo "SNAP_DESKTOP_LAST_REVISION=$SNAP_VERSION" > "$SNAP_USER_DATA/.last_revision" wait_for_async_execs exec "$@"
resources/linux/snap/electron-launch
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001863611105363816, 0.0001698770502116531, 0.00016380890156142414, 0.00016878820315469056, 0.000004843835995416157 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\thide() {\n", "\t\tthis.elements.main.classList.remove('recording');\n", "\t\tthis.editor.removeContentWidget(this);\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.remove('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 154 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { LanguagesRegistry } from 'vs/editor/common/services/languagesRegistry'; suite('LanguagesRegistry', () => { ensureNoDisposablesAreLeakedInTestSuite(); test('output language does not have a name', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'outputLangId', extensions: [], aliases: [], mimetypes: ['outputLanguageMimeType'], }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), []); registry.dispose(); }); test('language with alias does have a name', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId', extensions: [], aliases: ['LangName'], mimetypes: ['bla'], }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'LangName', languageId: 'langId' }]); assert.deepStrictEqual(registry.getLanguageName('langId'), 'LangName'); registry.dispose(); }); test('language without alias gets a name', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId', extensions: [], mimetypes: ['bla'], }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'langId', languageId: 'langId' }]); assert.deepStrictEqual(registry.getLanguageName('langId'), 'langId'); registry.dispose(); }); test('bug #4360: f# not shown in status bar', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId', extensions: ['.ext1'], aliases: ['LangName'], mimetypes: ['bla'], }]); registry._registerLanguages([{ id: 'langId', extensions: ['.ext2'], aliases: [], mimetypes: ['bla'], }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'LangName', languageId: 'langId' }]); assert.deepStrictEqual(registry.getLanguageName('langId'), 'LangName'); registry.dispose(); }); test('issue #5278: Extension cannot override language name anymore', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId', extensions: ['.ext1'], aliases: ['LangName'], mimetypes: ['bla'], }]); registry._registerLanguages([{ id: 'langId', extensions: ['.ext2'], aliases: ['BetterLanguageName'], mimetypes: ['bla'], }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'BetterLanguageName', languageId: 'langId' }]); assert.deepStrictEqual(registry.getLanguageName('langId'), 'BetterLanguageName'); registry.dispose(); }); test('mimetypes are generated if necessary', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId' }]); assert.deepStrictEqual(registry.getMimeType('langId'), 'text/x-langId'); registry.dispose(); }); test('first mimetype wins', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId', mimetypes: ['text/langId', 'text/langId2'] }]); assert.deepStrictEqual(registry.getMimeType('langId'), 'text/langId'); registry.dispose(); }); test('first mimetype wins 2', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'langId' }]); registry._registerLanguages([{ id: 'langId', mimetypes: ['text/langId'] }]); assert.deepStrictEqual(registry.getMimeType('langId'), 'text/x-langId'); registry.dispose(); }); test('aliases', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a' }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'a', languageId: 'a' }]); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageName('a'), 'a'); registry._registerLanguages([{ id: 'a', aliases: ['A1', 'A2'] }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'A1', languageId: 'a' }]); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a1'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a2'), 'a'); assert.deepStrictEqual(registry.getLanguageName('a'), 'A1'); registry._registerLanguages([{ id: 'a', aliases: ['A3', 'A4'] }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'A3', languageId: 'a' }]); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a1'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a2'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a3'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a4'), 'a'); assert.deepStrictEqual(registry.getLanguageName('a'), 'A3'); registry.dispose(); }); test('empty aliases array means no alias', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a' }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'a', languageId: 'a' }]); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageName('a'), 'a'); registry._registerLanguages([{ id: 'b', aliases: [] }]); assert.deepStrictEqual(registry.getSortedRegisteredLanguageNames(), [{ languageName: 'a', languageId: 'a' }]); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageIdByLanguageName('b'), 'b'); assert.deepStrictEqual(registry.getLanguageName('a'), 'a'); assert.deepStrictEqual(registry.getLanguageName('b'), null); registry.dispose(); }); test('extensions', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a', aliases: ['aName'], extensions: ['aExt'] }]); assert.deepStrictEqual(registry.getExtensions('a'), ['aExt']); registry._registerLanguages([{ id: 'a', extensions: ['aExt2'] }]); assert.deepStrictEqual(registry.getExtensions('a'), ['aExt', 'aExt2']); registry.dispose(); }); test('extensions of primary language registration come first', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a', extensions: ['aExt3'] }]); assert.deepStrictEqual(registry.getExtensions('a')[0], 'aExt3'); registry._registerLanguages([{ id: 'a', configuration: URI.file('conf.json'), extensions: ['aExt'] }]); assert.deepStrictEqual(registry.getExtensions('a')[0], 'aExt'); registry._registerLanguages([{ id: 'a', extensions: ['aExt2'] }]); assert.deepStrictEqual(registry.getExtensions('a')[0], 'aExt'); registry.dispose(); }); test('filenames', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a', aliases: ['aName'], filenames: ['aFilename'] }]); assert.deepStrictEqual(registry.getFilenames('a'), ['aFilename']); registry._registerLanguages([{ id: 'a', filenames: ['aFilename2'] }]); assert.deepStrictEqual(registry.getFilenames('a'), ['aFilename', 'aFilename2']); registry.dispose(); }); test('configuration', () => { const registry = new LanguagesRegistry(false); registry._registerLanguages([{ id: 'a', aliases: ['aName'], configuration: URI.file('/path/to/aFilename') }]); assert.deepStrictEqual(registry.getConfigurationFiles('a'), [URI.file('/path/to/aFilename')]); assert.deepStrictEqual(registry.getConfigurationFiles('aname'), []); assert.deepStrictEqual(registry.getConfigurationFiles('aName'), []); registry._registerLanguages([{ id: 'a', configuration: URI.file('/path/to/aFilename2') }]); assert.deepStrictEqual(registry.getConfigurationFiles('a'), [URI.file('/path/to/aFilename'), URI.file('/path/to/aFilename2')]); assert.deepStrictEqual(registry.getConfigurationFiles('aname'), []); assert.deepStrictEqual(registry.getConfigurationFiles('aName'), []); registry.dispose(); }); });
src/vs/editor/test/common/services/languagesRegistry.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001752890384523198, 0.00017305176879744977, 0.00016908138059079647, 0.00017286519869230688, 0.0000014406816717382753 ]
{ "id": 11, "code_window": [ "\t}\n", "\n", "\thide() {\n", "\t\tthis.elements.main.classList.remove('recording');\n", "\t\tthis.editor.removeContentWidget(this);\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.domNode.classList.remove('recording');\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 154 }
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Copyright (c) 2011 Jxck // // Originally from node.js (http://nodejs.org) // Copyright Joyent, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(); // CommonJS } else { root.assert = factory(); // Global } })(this, function() { // UTILITY // Object.create compatible in IE var create = Object.create || function(p) { if (!p) throw Error('no type'); function f() {}; f.prototype = p; return new f(); }; // UTILITY var util = { inherits: function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }, isArray: function(ar) { return Array.isArray(ar); }, isBoolean: function(arg) { return typeof arg === 'boolean'; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; }, isNumber: function(arg) { return typeof arg === 'number'; }, isString: function(arg) { return typeof arg === 'string'; }, isSymbol: function(arg) { return typeof arg === 'symbol'; }, isUndefined: function(arg) { return arg === undefined; }, isRegExp: function(re) { return util.isObject(re) && util.objectToString(re) === '[object RegExp]'; }, isObject: function(arg) { return typeof arg === 'object' && arg !== null; }, isDate: function(d) { return util.isObject(d) && util.objectToString(d) === '[object Date]'; }, isError: function(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); }, isFunction: function(arg) { return typeof arg === 'function'; }, isPrimitive: function(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; }, objectToString: function(o) { return Object.prototype.toString.call(o); } }; var pSlice = Array.prototype.slice; // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys var Object_keys = typeof Object.keys === 'function' ? Object.keys : (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // try to throw an error now, and from the stack property // work out the line that called in to assert.js. try { this.stack = (new Error).stack.toString(); } catch (e) {} } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; // } else if (actual instanceof Buffer && expected instanceof Buffer) { // return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected, strict); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a), bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = Object.keys(a), kb = Object.keys(b), key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('block must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; function checkIsPromise(obj) { return (obj !== null && typeof obj === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'); } const NO_EXCEPTION_SENTINEL = {}; async function waitForActual(promiseFn) { let resultPromise; if (typeof promiseFn === 'function') { // Return a rejected promise if `promiseFn` throws synchronously. resultPromise = promiseFn(); // Fail in case no promise is returned. if (!checkIsPromise(resultPromise)) { throw new Error('ERR_INVALID_RETURN_VALUE: promiseFn did not return Promise. ' + resultPromise); } } else if (checkIsPromise(promiseFn)) { resultPromise = promiseFn; } else { throw new Error('ERR_INVALID_ARG_TYPE: promiseFn is not Function or Promise. ' + promiseFn); } try { await resultPromise; } catch (e) { return e; } return NO_EXCEPTION_SENTINEL; } function expectsError(shouldHaveError, actual, message) { if (shouldHaveError && actual === NO_EXCEPTION_SENTINEL) { fail(undefined, 'Error', `Missing expected rejection${message ? ': ' + message : ''}`) } else if (!shouldHaveError && actual !== NO_EXCEPTION_SENTINEL) { fail(actual, undefined, `Got unexpected rejection (${actual.message})${message ? ': ' + message : ''}`) } } assert.rejects = async function rejects(promiseFn, message) { expectsError(true, await waitForActual(promiseFn), message); }; assert.doesNotReject = async function doesNotReject(fn, message) { expectsError(false, await waitForActual(fn), message); }; return assert; });
test/unit/assert.js
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017718774324748665, 0.000171107763890177, 0.00016452364798169583, 0.00017127128376159817, 0.0000027552594019653043 ]
{ "id": 12, "code_window": [ "\tstatic get(editor: ICodeEditor): EditorDictation | null {\n", "\t\treturn editor.getContribution<EditorDictation>(EditorDictation.ID);\n", "\t}\n", "\n", "\tprivate readonly widget = this._register(new DictationWidget(this.editor));\n", "\tprivate readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService);\n", "\n", "\tprivate sessionDisposables = this._register(new MutableDisposable());\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly widget = this._register(new DictationWidget(this.editor, this.keybindingService));\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 167 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.9979469180107117, 0.2150229960680008, 0.00016517675248906016, 0.00045171426609158516, 0.40843069553375244 ]
{ "id": 12, "code_window": [ "\tstatic get(editor: ICodeEditor): EditorDictation | null {\n", "\t\treturn editor.getContribution<EditorDictation>(EditorDictation.ID);\n", "\t}\n", "\n", "\tprivate readonly widget = this._register(new DictationWidget(this.editor));\n", "\tprivate readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService);\n", "\n", "\tprivate sessionDisposables = this._register(new MutableDisposable());\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly widget = this._register(new DictationWidget(this.editor, this.keybindingService));\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 167 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { BrowserClipboardService as BaseBrowserClipboardService } from 'vs/platform/clipboard/browser/clipboardService'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ILogService } from 'vs/platform/log/common/log'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; export class BrowserClipboardService extends BaseBrowserClipboardService { constructor( @INotificationService private readonly notificationService: INotificationService, @IOpenerService private readonly openerService: IOpenerService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @ILogService logService: ILogService, @ILayoutService layoutService: ILayoutService ) { super(layoutService, logService); } override async readText(type?: string): Promise<string> { if (type) { return super.readText(type); } try { return await navigator.clipboard.readText(); } catch (error) { if (!!this.environmentService.extensionTestsLocationURI) { return ''; // do not ask for input in tests (https://github.com/microsoft/vscode/issues/112264) } return new Promise<string>(resolve => { // Inform user about permissions problem (https://github.com/microsoft/vscode/issues/112089) const listener = new DisposableStore(); const handle = this.notificationService.prompt( Severity.Error, localize('clipboardError', "Unable to read from the browser's clipboard. Please make sure you have granted access for this website to read from the clipboard."), [{ label: localize('retry', "Retry"), run: async () => { listener.dispose(); resolve(await this.readText(type)); } }, { label: localize('learnMore', "Learn More"), run: () => this.openerService.open('https://go.microsoft.com/fwlink/?linkid=2151362') }], { sticky: true } ); // Always resolve the promise once the notification closes listener.add(Event.once(handle.onDidClose)(() => resolve(''))); }); } } } registerSingleton(IClipboardService, BrowserClipboardService, InstantiationType.Delayed);
src/vs/workbench/services/clipboard/browser/clipboardService.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00020196587138343602, 0.00017643168393988162, 0.00017065118299797177, 0.0001731363736325875, 0.000009746471732796635 ]
{ "id": 12, "code_window": [ "\tstatic get(editor: ICodeEditor): EditorDictation | null {\n", "\t\treturn editor.getContribution<EditorDictation>(EditorDictation.ID);\n", "\t}\n", "\n", "\tprivate readonly widget = this._register(new DictationWidget(this.editor));\n", "\tprivate readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService);\n", "\n", "\tprivate sessionDisposables = this._register(new MutableDisposable());\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly widget = this._register(new DictationWidget(this.editor, this.keybindingService));\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 167 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { WellDefinedPrefixTree } from 'vs/base/common/prefixTree'; import * as assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; suite('WellDefinedPrefixTree', () => { let tree: WellDefinedPrefixTree<number>; ensureNoDisposablesAreLeakedInTestSuite(); setup(() => { tree = new WellDefinedPrefixTree<number>(); }); test('find', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'baz']; tree.insert(key1, 42); tree.insert(key2, 43); assert.strictEqual(tree.find(key1), 42); assert.strictEqual(tree.find(key2), 43); assert.strictEqual(tree.find(['foo', 'baz', 'bop']), undefined); assert.strictEqual(tree.find(['foo']), undefined); }); test('hasParentOfKey', () => { const key = ['foo', 'bar']; tree.insert(key, 42); assert.strictEqual(tree.hasKeyOrParent(['foo', 'bar', 'baz']), true); assert.strictEqual(tree.hasKeyOrParent(['foo', 'bar']), true); assert.strictEqual(tree.hasKeyOrParent(['foo']), false); assert.strictEqual(tree.hasKeyOrParent(['baz']), false); }); test('hasKeyOrChildren', () => { const key = ['foo', 'bar']; tree.insert(key, 42); assert.strictEqual(tree.hasKeyOrChildren([]), true); assert.strictEqual(tree.hasKeyOrChildren(['foo']), true); assert.strictEqual(tree.hasKeyOrChildren(['foo', 'bar']), true); assert.strictEqual(tree.hasKeyOrChildren(['foo', 'bar', 'baz']), false); }); test('hasKey', () => { const key = ['foo', 'bar']; tree.insert(key, 42); assert.strictEqual(tree.hasKey(key), true); assert.strictEqual(tree.hasKey(['foo']), false); assert.strictEqual(tree.hasKey(['baz']), false); assert.strictEqual(tree.hasKey(['foo', 'bar', 'baz']), false); }); test('size', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'baz']; assert.strictEqual(tree.size, 0); tree.insert(key1, 42); assert.strictEqual(tree.size, 1); tree.insert(key2, 43); assert.strictEqual(tree.size, 2); tree.insert(key2, 44); assert.strictEqual(tree.size, 2); }); test('mutate', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'baz']; tree.insert(key1, 42); tree.insert(key2, 43); tree.mutate(key1, (value) => { assert.strictEqual(value, 42); return 44; }); assert.strictEqual(tree.find(key1), 44); assert.strictEqual(tree.find(key2), 43); }); test('delete', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'baz']; tree.insert(key1, 42); tree.insert(key2, 43); assert.strictEqual(tree.size, 2); assert.strictEqual(tree.delete(key1), 42); assert.strictEqual(tree.size, 1); assert.strictEqual(tree.find(key1), undefined); assert.strictEqual(tree.find(key2), 43); assert.strictEqual(tree.delete(key2), 43); assert.strictEqual(tree.size, 0); assert.strictEqual(tree.find(key1), undefined); assert.strictEqual(tree.find(key2), undefined); tree.delete(key2); assert.strictEqual(tree.size, 0); }); test('delete child', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'bar', 'baz']; tree.insert(key1, 42); tree.insert(key2, 43); assert.strictEqual(tree.size, 2); assert.strictEqual(tree.delete(key2), 43); assert.strictEqual(tree.size, 1); assert.strictEqual(tree.find(key1), 42); assert.strictEqual(tree.find(key2), undefined); }); test('delete noops if deleting parent', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'bar', 'baz']; tree.insert(key2, 43); assert.strictEqual(tree.size, 1); assert.strictEqual(tree.delete(key1), undefined); assert.strictEqual(tree.size, 1); assert.strictEqual(tree.find(key2), 43); assert.strictEqual(tree.find(key1), undefined); }); test('values', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'baz']; tree.insert(key1, 42); tree.insert(key2, 43); assert.deepStrictEqual([...tree.values()], [43, 42]); }); test('delete recursive', () => { const key1 = ['foo', 'bar']; const key2 = ['foo', 'bar', 'baz']; const key3 = ['foo', 'bar', 'baz2', 'baz3']; const key4 = ['foo', 'bar2']; tree.insert(key1, 42); tree.insert(key2, 43); tree.insert(key3, 44); tree.insert(key4, 45); assert.strictEqual(tree.size, 4); assert.deepStrictEqual([...tree.deleteRecursive(key1)], [42, 44, 43]); assert.strictEqual(tree.size, 1); assert.deepStrictEqual([...tree.deleteRecursive(key1)], []); assert.strictEqual(tree.size, 1); assert.deepStrictEqual([...tree.deleteRecursive(key4)], [45]); assert.strictEqual(tree.size, 0); }); });
src/vs/base/test/common/prefixTree.test.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017847980780061334, 0.000176556539372541, 0.00017499194655101746, 0.0001765783817972988, 0.0000010492427691133344 ]
{ "id": 12, "code_window": [ "\tstatic get(editor: ICodeEditor): EditorDictation | null {\n", "\t\treturn editor.getContribution<EditorDictation>(EditorDictation.ID);\n", "\t}\n", "\n", "\tprivate readonly widget = this._register(new DictationWidget(this.editor));\n", "\tprivate readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService);\n", "\n", "\tprivate sessionDisposables = this._register(new MutableDisposable());\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly widget = this._register(new DictationWidget(this.editor, this.keybindingService));\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 167 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ProxyIdentifier, IRPCProtocol, Proxied } from 'vs/workbench/services/extensions/common/proxyIdentifier'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const IExtHostRpcService = createDecorator<IExtHostRpcService>('IExtHostRpcService'); export interface IExtHostRpcService extends IRPCProtocol { readonly _serviceBrand: undefined; } export class ExtHostRpcService implements IExtHostRpcService { readonly _serviceBrand: undefined; readonly getProxy: <T>(identifier: ProxyIdentifier<T>) => Proxied<T>; readonly set: <T, R extends T> (identifier: ProxyIdentifier<T>, instance: R) => R; readonly dispose: () => void; readonly assertRegistered: (identifiers: ProxyIdentifier<any>[]) => void; readonly drain: () => Promise<void>; constructor(rpcProtocol: IRPCProtocol) { this.getProxy = rpcProtocol.getProxy.bind(rpcProtocol); this.set = rpcProtocol.set.bind(rpcProtocol); this.dispose = rpcProtocol.dispose.bind(rpcProtocol); this.assertRegistered = rpcProtocol.assertRegistered.bind(rpcProtocol); this.drain = rpcProtocol.drain.bind(rpcProtocol); } }
src/vs/workbench/api/common/extHostRpcService.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0002550521166995168, 0.00019456208974588662, 0.00017150366329587996, 0.00017584628949407488, 0.00003497054422041401 ]
{ "id": 13, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@ISpeechService private readonly speechService: ISpeechService,\n", "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tsuper();\n", "\t}\n", "\n", "\tstart() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService,\n", "\t\t@IKeybindingService private readonly keybindingService: IKeybindingService\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 175 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./editorDictation'; import { localize2 } from 'vs/nls'; import { IDimension, h, reset } from 'vs/base/browser/dom'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { HasSpeechProvider, ISpeechService, SpeechToTextStatus } from 'vs/workbench/contrib/speech/common/speechService'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { Codicon } from 'vs/base/common/codicons'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { EditorAction2, EditorContributionInstantiation, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { assertIsDefined } from 'vs/base/common/types'; const EDITOR_DICTATION_IN_PROGRESS = new RawContextKey<boolean>('editorDictation.inProgress', false); const VOICE_CATEGORY = localize2('voiceCategory', "Voice"); export class EditorDictationStartAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.start', title: localize2('startDictation', "Start Dictation in Editor"), category: VOICE_CATEGORY, precondition: ContextKeyExpr.and(HasSpeechProvider, EDITOR_DICTATION_IN_PROGRESS.toNegated(), EditorContextKeys.readOnly.toNegated()), f1: true }); } override runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const holdMode = keybindingService.enableKeybindingHoldMode(this.desc.id); if (holdMode) { let shouldCallStop = false; const handle = setTimeout(() => { shouldCallStop = true; }, 500); holdMode.finally(() => { clearTimeout(handle); if (shouldCallStop) { EditorDictation.get(editor)?.stop(); } }); } EditorDictation.get(editor)?.start(); } } export class EditorDictationStopAction extends EditorAction2 { constructor() { super({ id: 'workbench.action.editorDictation.stop', title: localize2('stopDictation', "Stop Dictation in Editor"), category: VOICE_CATEGORY, precondition: EDITOR_DICTATION_IN_PROGRESS, f1: true, keybinding: { primary: KeyCode.Escape, weight: KeybindingWeight.WorkbenchContrib + 100 } }); } override runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { EditorDictation.get(editor)?.stop(); } } export class DictationWidget extends Disposable implements IContentWidget { readonly suppressMouseDown = true; readonly allowEditorOverflow = true; private readonly domNode = document.createElement('div'); private readonly elements = h('.editor-dictation-widget@main', [h('span@mic')]); constructor(private readonly editor: ICodeEditor) { super(); this.domNode.appendChild(this.elements.root); this.domNode.style.zIndex = '1000'; reset(this.elements.mic, renderIcon(Codicon.micFilled)); } getId(): string { return 'editorDictation'; } getDomNode(): HTMLElement { return this.domNode; } getPosition(): IContentWidgetPosition | null { if (!this.editor.hasModel()) { return null; } const selection = this.editor.getSelection(); return { position: selection.getPosition(), preference: [ selection.getPosition().equals(selection.getStartPosition()) ? ContentWidgetPositionPreference.ABOVE : ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.EXACT ] }; } beforeRender(): IDimension | null { const lineHeight = this.editor.getOption(EditorOption.lineHeight); const width = this.editor.getLayoutInfo().contentWidth * 0.7; this.elements.main.style.setProperty('--vscode-editor-dictation-widget-height', `${lineHeight}px`); this.elements.main.style.setProperty('--vscode-editor-dictation-widget-width', `${width}px`); return null; } show() { this.editor.addContentWidget(this); } layout(): void { this.editor.layoutContentWidget(this); } active(): void { this.elements.main.classList.add('recording'); } hide() { this.elements.main.classList.remove('recording'); this.editor.removeContentWidget(this); } } export class EditorDictation extends Disposable implements IEditorContribution { static readonly ID = 'editorDictation'; static get(editor: ICodeEditor): EditorDictation | null { return editor.getContribution<EditorDictation>(EditorDictation.ID); } private readonly widget = this._register(new DictationWidget(this.editor)); private readonly editorDictationInProgress = EDITOR_DICTATION_IN_PROGRESS.bindTo(this.contextKeyService); private sessionDisposables = this._register(new MutableDisposable()); constructor( private readonly editor: ICodeEditor, @ISpeechService private readonly speechService: ISpeechService, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); } start() { const disposables = new DisposableStore(); this.sessionDisposables.value = disposables; this.widget.show(); disposables.add(toDisposable(() => this.widget.hide())); this.editorDictationInProgress.set(true); disposables.add(toDisposable(() => this.editorDictationInProgress.reset())); const collection = this.editor.createDecorationsCollection(); disposables.add(toDisposable(() => collection.clear())); let previewStart: Position | undefined = undefined; let lastReplaceTextLength = 0; const replaceText = (text: string, isPreview: boolean) => { if (!previewStart) { previewStart = assertIsDefined(this.editor.getPosition()); } const endPosition = new Position(previewStart.lineNumber, previewStart.column + text.length); this.editor.executeEdits(EditorDictation.ID, [ EditOperation.replace(Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + lastReplaceTextLength)), text) ], [ Selection.fromPositions(endPosition) ]); if (isPreview) { collection.set([ { range: Range.fromPositions(previewStart, previewStart.with(undefined, previewStart.column + text.length)), options: { description: 'editor-dictation-preview', inlineClassName: 'ghost-text-decoration-preview' } } ]); } else { collection.clear(); } lastReplaceTextLength = text.length; if (!isPreview) { previewStart = undefined; lastReplaceTextLength = 0; } this.editor.revealPositionInCenterIfOutsideViewport(endPosition); this.widget.layout(); }; const cts = new CancellationTokenSource(); disposables.add(toDisposable(() => cts.dispose(true))); const session = this.speechService.createSpeechToTextSession(cts.token); disposables.add(session.onDidChange(e => { if (cts.token.isCancellationRequested) { return; } switch (e.status) { case SpeechToTextStatus.Started: this.widget.active(); break; case SpeechToTextStatus.Stopped: disposables.dispose(); break; case SpeechToTextStatus.Recognizing: { if (!e.text) { return; } replaceText(e.text, true); break; } case SpeechToTextStatus.Recognized: { if (!e.text) { return; } replaceText(`${e.text} `, false); break; } } })); } stop(): void { this.sessionDisposables.clear(); } } registerEditorContribution(EditorDictation.ID, EditorDictation, EditorContributionInstantiation.Lazy); registerAction2(EditorDictationStartAction); registerAction2(EditorDictationStopAction);
src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts
1
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.007799717132002115, 0.0005595154943875968, 0.0001651509228395298, 0.0001735141413519159, 0.0014144032029435039 ]
{ "id": 13, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@ISpeechService private readonly speechService: ISpeechService,\n", "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tsuper();\n", "\t}\n", "\n", "\tstart() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService,\n", "\t\t@IKeybindingService private readonly keybindingService: IKeybindingService\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 175 }
{ "name": "fsharp", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin ionide/ionide-fsgrammar grammars/fsharp.json ./syntaxes/fsharp.tmLanguage.json" }, "categories": ["Programming Languages"], "contributes": { "languages": [ { "id": "fsharp", "extensions": [ ".fs", ".fsi", ".fsx", ".fsscript" ], "aliases": [ "F#", "FSharp", "fsharp" ], "configuration": "./language-configuration.json" } ], "grammars": [ { "language": "fsharp", "scopeName": "source.fsharp", "path": "./syntaxes/fsharp.tmLanguage.json" } ], "snippets": [ { "language": "fsharp", "path": "./snippets/fsharp.code-snippets" } ], "configurationDefaults": { "[fsharp]": { "diffEditor.ignoreTrimWhitespace": false } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/fsharp/package.json
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.00017712033877614886, 0.000175423439941369, 0.00017315323930233717, 0.0001758419966790825, 0.0000013071340845272061 ]
{ "id": 13, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@ISpeechService private readonly speechService: ISpeechService,\n", "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tsuper();\n", "\t}\n", "\n", "\tstart() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService,\n", "\t\t@IKeybindingService private readonly keybindingService: IKeybindingService\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 175 }
import { handledConflictMinimapOverViewRulerColor, unhandledConflictMinimapOverViewRulerColor } from 'vs/workbench/contrib/mergeEditor/browser/view/colors'; import { EditorGutter, IGutterItemInfo, IGutterItemView } from '../editorGutter'; import { CodeEditorView } from './codeEditorView';
src/vs/editor/test/node/diffing/fixtures/ts-import-ws-affinity/1.tst
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.0001716819970170036, 0.0001716819970170036, 0.0001716819970170036, 0.0001716819970170036, 0 ]
{ "id": 13, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@ISpeechService private readonly speechService: ISpeechService,\n", "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService\n", "\t) {\n", "\t\tsuper();\n", "\t}\n", "\n", "\tstart() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t@IContextKeyService private readonly contextKeyService: IContextKeyService,\n", "\t\t@IKeybindingService private readonly keybindingService: IKeybindingService\n" ], "file_path": "src/vs/workbench/contrib/codeEditor/browser/dictation/editorDictation.ts", "type": "replace", "edit_start_line_idx": 175 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { ITextModel } from 'vs/editor/common/model'; import { DocumentColorProvider, IColor, IColorInformation, IColorPresentation } from 'vs/editor/common/languages'; import { EditorWorkerClient } from 'vs/editor/browser/services/editorWorkerService'; import { IModelService } from 'vs/editor/common/services/model'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { Disposable } from 'vs/base/common/lifecycle'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { registerEditorFeature } from 'vs/editor/common/editorFeatures'; export class DefaultDocumentColorProvider implements DocumentColorProvider { private _editorWorkerClient: EditorWorkerClient; constructor( modelService: IModelService, languageConfigurationService: ILanguageConfigurationService, ) { this._editorWorkerClient = new EditorWorkerClient(modelService, false, 'editorWorkerService', languageConfigurationService); } async provideDocumentColors(model: ITextModel, _token: CancellationToken): Promise<IColorInformation[] | null> { return this._editorWorkerClient.computeDefaultDocumentColors(model.uri); } provideColorPresentations(_model: ITextModel, colorInfo: IColorInformation, _token: CancellationToken): IColorPresentation[] { const range = colorInfo.range; const colorFromInfo: IColor = colorInfo.color; const alpha = colorFromInfo.alpha; const color = new Color(new RGBA(Math.round(255 * colorFromInfo.red), Math.round(255 * colorFromInfo.green), Math.round(255 * colorFromInfo.blue), alpha)); const rgb = alpha ? Color.Format.CSS.formatRGB(color) : Color.Format.CSS.formatRGBA(color); const hsl = alpha ? Color.Format.CSS.formatHSL(color) : Color.Format.CSS.formatHSLA(color); const hex = alpha ? Color.Format.CSS.formatHex(color) : Color.Format.CSS.formatHexA(color); const colorPresentations: IColorPresentation[] = []; colorPresentations.push({ label: rgb, textEdit: { range: range, text: rgb } }); colorPresentations.push({ label: hsl, textEdit: { range: range, text: hsl } }); colorPresentations.push({ label: hex, textEdit: { range: range, text: hex } }); return colorPresentations; } } class DefaultDocumentColorProviderFeature extends Disposable { constructor( @IModelService _modelService: IModelService, @ILanguageConfigurationService _languageConfigurationService: ILanguageConfigurationService, @ILanguageFeaturesService _languageFeaturesService: ILanguageFeaturesService, ) { super(); this._register(_languageFeaturesService.colorProvider.register('*', new DefaultDocumentColorProvider(_modelService, _languageConfigurationService))); } } registerEditorFeature(DefaultDocumentColorProviderFeature);
src/vs/editor/contrib/colorPicker/browser/defaultDocumentColorProvider.ts
0
https://github.com/microsoft/vscode/commit/076e9df452fa0ee71d4fb1074896f74a0266ecd7
[ 0.000223097056732513, 0.00017785257659852505, 0.00016015820438042283, 0.00017188051424454898, 0.000019036020603380166 ]
{ "id": 0, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> {\n", " render() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export class IonReactHashRouter extends React.Component<HashRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
import React from 'react'; import { BrowserRouter, BrowserRouterProps } from 'react-router-dom'; import { RouteManagerWithRouter } from './Router'; export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> { render() { const { children, ...props } = this.props; return ( <BrowserRouter {...props}> <RouteManagerWithRouter>{children}</RouteManagerWithRouter> </BrowserRouter> ); } })();
packages/react-router/src/ReactRouter/IonReactRouter.tsx
1
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.04315192997455597, 0.021686987951397896, 0.00022204534616321325, 0.021686987951397896, 0.021464942023158073 ]
{ "id": 0, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> {\n", " render() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export class IonReactHashRouter extends React.Component<HashRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
```html <ion-menu side="start" menuId="first"> <ion-header> <ion-toolbar color="primary"> <ion-title>Start Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <ion-menu side="start" menuId="custom" class="my-custom-menu"> <ion-header> <ion-toolbar color="tertiary"> <ion-title>Custom Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <ion-menu side="end" type="push"> <ion-header> <ion-toolbar color="danger"> <ion-title>End Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <ion-router-outlet main></ion-router-outlet> ``` ```typescript import { Component } from '@angular/core'; import { MenuController } from '@ionic/angular'; @Component({ selector: 'menu-example', templateUrl: 'menu-example.html', styleUrls: ['./menu-example.css'], }) export class MenuExample { constructor(private menu: MenuController) { } openFirst() { this.menu.enable(true, 'first'); this.menu.open('first'); } openEnd() { this.menu.open('end'); } openCustom() { this.menu.enable(true, 'custom'); this.menu.open('custom'); } } ``` ```css .my-custom-menu { --width: 500px; } ```
core/src/components/menu/usage/angular.md
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.0001825351791922003, 0.00017494613712187856, 0.00016936859174165875, 0.00017398336785845459, 0.000003795124712269171 ]
{ "id": 0, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> {\n", " render() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export class IonReactHashRouter extends React.Component<HashRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, State, Watch, h } from '@stencil/core'; import { getIonMode } from '../../global/ionic-global'; import { ActionSheetButton, ActionSheetOptions, AlertInput, AlertOptions, CssClassMap, OverlaySelect, PopoverOptions, SelectChangeEventDetail, SelectInterface, SelectPopoverOption, StyleEventDetail } from '../../interface'; import { findItemLabel, renderHiddenInput } from '../../utils/helpers'; import { actionSheetController, alertController, popoverController } from '../../utils/overlays'; import { hostContext } from '../../utils/theme'; import { watchForOptions } from '../../utils/watch-options'; import { SelectCompareFn } from './select-interface'; /** * @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use. */ @Component({ tag: 'ion-select', styleUrls: { ios: 'select.ios.scss', md: 'select.md.scss' }, shadow: true }) export class Select implements ComponentInterface { private inputId = `ion-sel-${selectIds++}`; private overlay?: OverlaySelect; private didInit = false; private buttonEl?: HTMLButtonElement; private mutationO?: MutationObserver; @Element() el!: HTMLIonSelectElement; @State() isExpanded = false; /** * If `true`, the user cannot interact with the select. */ @Prop() disabled = false; /** * The text to display on the cancel button. */ @Prop() cancelText = 'Cancel'; /** * The text to display on the ok button. */ @Prop() okText = 'OK'; /** * The text to display when the select is empty. */ @Prop() placeholder?: string | null; /** * The name of the control, which is submitted with the form data. */ @Prop() name: string = this.inputId; /** * The text to display instead of the selected option's value. */ @Prop() selectedText?: string | null; /** * If `true`, the select can accept multiple values. */ @Prop() multiple = false; /** * The interface the select should use: `action-sheet`, `popover` or `alert`. */ @Prop() interface: SelectInterface = 'alert'; /** * Any additional options that the `alert`, `action-sheet` or `popover` interface * can take. See the [AlertController API docs](../../alert/AlertController/#create), the * [ActionSheetController API docs](../../action-sheet/ActionSheetController/#create) and the * [PopoverController API docs](../../popover/PopoverController/#create) for the * create options for each interface. */ @Prop() interfaceOptions: any = {}; /** * A property name or function used to compare object values */ @Prop() compareWith?: string | SelectCompareFn | null; /** * the value of the select. */ @Prop({ mutable: true }) value?: any | null; /** * Emitted when the value has changed. */ @Event() ionChange!: EventEmitter<SelectChangeEventDetail>; /** * Emitted when the selection is cancelled. */ @Event() ionCancel!: EventEmitter<void>; /** * Emitted when the select has focus. */ @Event() ionFocus!: EventEmitter<void>; /** * Emitted when the select loses focus. */ @Event() ionBlur!: EventEmitter<void>; /** * Emitted when the styles change. * @internal */ @Event() ionStyle!: EventEmitter<StyleEventDetail>; @Watch('disabled') @Watch('placeholder') disabledChanged() { this.emitStyle(); } @Watch('value') valueChanged() { this.updateOptions(); this.emitStyle(); if (this.didInit) { this.ionChange.emit({ value: this.value, }); } } async connectedCallback() { if (this.value === undefined) { if (this.multiple) { // there are no values set at this point // so check to see who should be selected const checked = this.childOpts.filter(o => o.selected); this.value = checked.map(o => getOptionValue(o)); } else { const checked = this.childOpts.find(o => o.selected); if (checked) { this.value = getOptionValue(checked); } } } this.updateOptions(); this.updateOverlayOptions(); this.emitStyle(); this.mutationO = watchForOptions<HTMLIonSelectOptionElement>(this.el, 'ion-select-option', async () => { this.updateOptions(); this.updateOverlayOptions(); }); } disconnectedCallback() { if (this.mutationO) { this.mutationO.disconnect(); this.mutationO = undefined; } } componentDidLoad() { this.didInit = true; } /** * Open the select overlay. The overlay is either an alert, action sheet, or popover, * depending on the `interface` property on the `ion-select`. * * @param event The user interface event that called the open. */ @Method() async open(event?: UIEvent): Promise<any> { if (this.disabled || this.isExpanded) { return undefined; } const overlay = this.overlay = await this.createOverlay(event); this.isExpanded = true; overlay.onDidDismiss().then(() => { this.overlay = undefined; this.isExpanded = false; this.setFocus(); }); await overlay.present(); return overlay; } private createOverlay(ev?: UIEvent): Promise<OverlaySelect> { let selectInterface = this.interface; if ((selectInterface === 'action-sheet' || selectInterface === 'popover') && this.multiple) { console.warn(`Select interface cannot be "${selectInterface}" with a multi-value select. Using the "alert" interface instead.`); selectInterface = 'alert'; } if (selectInterface === 'popover' && !ev) { console.warn('Select interface cannot be a "popover" without passing an event. Using the "alert" interface instead.'); selectInterface = 'alert'; } if (selectInterface === 'popover') { return this.openPopover(ev!); } if (selectInterface === 'action-sheet') { return this.openActionSheet(); } return this.openAlert(); } private updateOverlayOptions(): void { const overlay = (this.overlay as any); if (!overlay) { return; } const childOpts = this.childOpts; switch (this.interface) { case 'action-sheet': overlay.buttons = this.createActionSheetButtons(childOpts); break; case 'popover': const popover = overlay.querySelector('ion-select-popover'); if (popover) { popover.options = this.createPopoverOptions(childOpts); } break; case 'alert': const inputType = (this.multiple ? 'checkbox' : 'radio'); overlay.inputs = this.createAlertInputs(childOpts, inputType); break; } } private createActionSheetButtons(data: any[]): ActionSheetButton[] { const actionSheetButtons = data.map(option => { return { role: (option.selected ? 'selected' : ''), text: option.textContent, handler: () => { this.value = getOptionValue(option); } } as ActionSheetButton; }); // Add "cancel" button actionSheetButtons.push({ text: this.cancelText, role: 'cancel', handler: () => { this.ionCancel.emit(); } }); return actionSheetButtons; } private createAlertInputs(data: any[], inputType: string): AlertInput[] { return data.map(o => { return { type: inputType, label: o.textContent, value: getOptionValue(o), checked: o.selected, disabled: o.disabled } as AlertInput; }); } private createPopoverOptions(data: any[]): SelectPopoverOption[] { return data.map(o => { const value = getOptionValue(o); return { text: o.textContent, value, checked: o.selected, disabled: o.disabled, handler: () => { this.value = value; this.close(); } } as SelectPopoverOption; }); } private async openPopover(ev: UIEvent) { const interfaceOptions = this.interfaceOptions; const mode = getIonMode(this); const popoverOpts: PopoverOptions = { mode, ...interfaceOptions, component: 'ion-select-popover', cssClass: ['select-popover', interfaceOptions.cssClass], event: ev, componentProps: { header: interfaceOptions.header, subHeader: interfaceOptions.subHeader, message: interfaceOptions.message, value: this.value, options: this.createPopoverOptions(this.childOpts) } }; return popoverController.create(popoverOpts); } private async openActionSheet() { const mode = getIonMode(this); const interfaceOptions = this.interfaceOptions; const actionSheetOpts: ActionSheetOptions = { mode, ...interfaceOptions, buttons: this.createActionSheetButtons(this.childOpts), cssClass: ['select-action-sheet', interfaceOptions.cssClass] }; return actionSheetController.create(actionSheetOpts); } private async openAlert() { const label = this.getLabel(); const labelText = (label) ? label.textContent : null; const interfaceOptions = this.interfaceOptions; const inputType = (this.multiple ? 'checkbox' : 'radio'); const mode = getIonMode(this); const alertOpts: AlertOptions = { mode, ...interfaceOptions, header: interfaceOptions.header ? interfaceOptions.header : labelText, inputs: this.createAlertInputs(this.childOpts, inputType), buttons: [ { text: this.cancelText, role: 'cancel', handler: () => { this.ionCancel.emit(); } }, { text: this.okText, handler: (selectedValues: any) => { this.value = selectedValues; } } ], cssClass: ['select-alert', interfaceOptions.cssClass, (this.multiple ? 'multiple-select-alert' : 'single-select-alert')] }; return alertController.create(alertOpts); } /** * Close the select interface. */ private close(): Promise<boolean> { // TODO check !this.overlay || !this.isFocus() if (!this.overlay) { return Promise.resolve(false); } return this.overlay.dismiss(); } private updateOptions() { // iterate all options, updating the selected prop let canSelect = true; const { value, childOpts, compareWith, multiple } = this; for (const selectOption of childOpts) { const optValue = getOptionValue(selectOption); const selected = canSelect && isOptionSelected(value, optValue, compareWith); selectOption.selected = selected; // if current option is selected and select is single-option, we can't select // any option more if (selected && !multiple) { canSelect = false; } } } private getLabel() { return findItemLabel(this.el); } private hasValue(): boolean { return this.getText() !== ''; } private get childOpts() { return Array.from(this.el.querySelectorAll('ion-select-option')); } private getText(): string { const selectedText = this.selectedText; if (selectedText != null && selectedText !== '') { return selectedText; } return generateText(this.childOpts, this.value, this.compareWith); } private setFocus() { if (this.buttonEl) { this.buttonEl.focus(); } } private emitStyle() { this.ionStyle.emit({ 'interactive': true, 'select': true, 'has-placeholder': this.placeholder != null, 'has-value': this.hasValue(), 'interactive-disabled': this.disabled, 'select-disabled': this.disabled }); } private onClick = (ev: UIEvent) => { this.setFocus(); this.open(ev); } private onFocus = () => { this.ionFocus.emit(); } private onBlur = () => { this.ionBlur.emit(); } render() { const { placeholder, name, disabled, isExpanded, value, el } = this; const mode = getIonMode(this); const labelId = this.inputId + '-lbl'; const label = findItemLabel(el); if (label) { label.id = labelId; } let addPlaceholderClass = false; let selectText = this.getText(); if (selectText === '' && placeholder != null) { selectText = placeholder; addPlaceholderClass = true; } renderHiddenInput(true, el, name, parseValue(value), disabled); const selectTextClasses: CssClassMap = { 'select-text': true, 'select-placeholder': addPlaceholderClass }; return ( <Host onClick={this.onClick} role="combobox" aria-haspopup="dialog" aria-disabled={disabled ? 'true' : null} aria-expanded={`${isExpanded}`} aria-labelledby={labelId} class={{ [mode]: true, 'in-item': hostContext('ion-item', el), 'select-disabled': disabled, }} > <div class={selectTextClasses}> {selectText} </div> <div class="select-icon" role="presentation"> <div class="select-icon-inner"></div> </div> <button type="button" onFocus={this.onFocus} onBlur={this.onBlur} disabled={disabled} ref={(btnEl => this.buttonEl = btnEl)} > </button> </Host> ); } } const getOptionValue = (el: HTMLIonSelectOptionElement) => { const value = el.value; return (value === undefined) ? el.textContent || '' : value; }; const parseValue = (value: any) => { if (value == null) { return undefined; } if (Array.isArray(value)) { return value.join(','); } return value.toString(); }; const isOptionSelected = (currentValue: any[] | any, compareValue: any, compareWith?: string | SelectCompareFn | null) => { if (currentValue === undefined) { return false; } if (Array.isArray(currentValue)) { return currentValue.some(val => compareOptions(val, compareValue, compareWith)); } else { return compareOptions(currentValue, compareValue, compareWith); } }; const compareOptions = (currentValue: any, compareValue: any, compareWith?: string | SelectCompareFn | null): boolean => { if (typeof compareWith === 'function') { return compareWith(currentValue, compareValue); } else if (typeof compareWith === 'string') { return currentValue[compareWith] === compareValue[compareWith]; } else { return currentValue === compareValue; } }; const generateText = (opts: HTMLIonSelectOptionElement[], value: any | any[], compareWith?: string | SelectCompareFn | null) => { if (value === undefined) { return ''; } if (Array.isArray(value)) { return value .map(v => textForValue(opts, v, compareWith)) .filter(opt => opt !== null) .join(', '); } else { return textForValue(opts, value, compareWith) || ''; } }; const textForValue = (opts: HTMLIonSelectOptionElement[], value: any, compareWith?: string | SelectCompareFn | null): string | null => { const selectOpt = opts.find(opt => { return compareOptions(getOptionValue(opt), value, compareWith); }); return selectOpt ? selectOpt.textContent : null; }; let selectIds = 0;
core/src/components/select/select.tsx
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.001439114916138351, 0.00020920940733049065, 0.0001634244981687516, 0.00017367664258927107, 0.00019370811060070992 ]
{ "id": 0, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> {\n", " render() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export class IonReactHashRouter extends React.Component<HashRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
# Contributor Code of Conduct As contributors and maintainers of the Ionic project, we pledge to respect everyone who contributes by posting issues, updating documentation, submitting pull requests, providing feedback in comments, and any other activities. Communication through any of Ionic's channels (GitHub, Slack, Forum, IRC, mailing lists, Twitter, etc.) must be constructive and never resort to personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. We promise to extend courtesy and respect to everyone involved in this project regardless of gender, gender identity, sexual orientation, disability, age, race, ethnicity, religion, or level of experience. We expect anyone contributing to the Ionic project to do the same. If any member of the community violates this code of conduct, the maintainers of the Ionic project may take action, removing issues, comments, and PRs or blocking accounts as deemed appropriate. If you are subject to or witness unacceptable behavior, or have any other concerns, please email us at [[email protected]](mailto:[email protected]).
CODE_OF_CONDUCT.md
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017511745681986213, 0.00017210119403898716, 0.0001690849312581122, 0.00017210119403898716, 0.0000030162627808749676 ]
{ "id": 1, "code_window": [ " render() {\n", " console.log('hash router in your bundle!!!');\n", " const { children, ...props } = this.props;\n", " return (\n", " <HashRouter {...props}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 7 }
import React from 'react'; import { BrowserRouter, BrowserRouterProps } from 'react-router-dom'; import { RouteManagerWithRouter } from './Router'; export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> { render() { const { children, ...props } = this.props; return ( <BrowserRouter {...props}> <RouteManagerWithRouter>{children}</RouteManagerWithRouter> </BrowserRouter> ); } })();
packages/react-router/src/ReactRouter/IonReactRouter.tsx
1
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.9948911666870117, 0.9934067726135254, 0.9919223785400391, 0.9934067726135254, 0.0014843940734863281 ]
{ "id": 1, "code_window": [ " render() {\n", " console.log('hash router in your bundle!!!');\n", " const { children, ...props } = this.props;\n", " return (\n", " <HashRouter {...props}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 7 }
import { newE2EPage } from '@stencil/core/testing'; import { checkComponentModeClasses } from '../../../../utils/test/utils'; test('footer: translucent', async () => { const page = await newE2EPage({ url: '/src/components/footer/test/translucent?ionic:_testing=true' }); const globalMode = await page.evaluate(() => document.documentElement.getAttribute('mode')); await checkComponentModeClasses(await page.find('ion-footer'), globalMode!, 'footer-translucent'); const compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); });
core/src/components/footer/test/translucent/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017722068878356367, 0.00017675166600383818, 0.00017628262867219746, 0.00017675166600383818, 4.690300556831062e-7 ]
{ "id": 1, "code_window": [ " render() {\n", " console.log('hash router in your bundle!!!');\n", " const { children, ...props } = this.props;\n", " return (\n", " <HashRouter {...props}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 7 }
{ "name": "@ionic/react-router", "version": "5.0.0-beta.0", "description": "React Router wrapper for @ionic/react", "keywords": [ "ionic", "framework", "react", "mobile", "app", "hybrid", "webapp", "cordova", "progressive web app", "pwa" ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/ionic-team/ionic.git" }, "scripts": { "build": "npm run clean && npm run compile", "clean": "rm -rf dist dist-transpiled", "compile": "npm run tsc && rollup -c", "release": "np --any-branch --no-cleanup", "lint": "tslint --project .", "lint.fix": "tslint --project . --fix", "tsc": "tsc -p .", "test.spec": "jest --ci" }, "main": "dist/index.js", "module": "dist/index.esm.js", "types": "dist/types/index.d.ts", "files": [ "dist/" ], "dependencies": { "tslib": "*" }, "peerDependencies": { "@ionic/core": "5.0.0-beta.0", "@ionic/react": "5.0.0-beta.0", "react": "^16.8.6", "react-dom": "^16.8.6", "react-router": "^5.0.1", "react-router-dom": "^5.0.1" }, "devDependencies": { "@ionic/core": "5.0.0-beta.0", "@ionic/react": "5.0.0-beta.0", "@types/jest": "^23.3.9", "@types/node": "12.6.9", "@types/react": "^16.9.2", "@types/react-dom": "^16.9.0", "@types/react-router": "^5.0.3", "@types/react-router-dom": "^4.3.1", "jest": "^24.8.0", "jest-dom": "^3.4.0", "np": "^5.0.1", "react": "^16.9.0", "react-dom": "^16.9.0", "react-router": "^5.0.1", "react-router-dom": "^5.0.1", "react-testing-library": "^7.0.0", "rollup": "^1.18.0", "rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-sourcemaps": "^0.4.2", "ts-jest": "^24.0.2", "tslint": "^5.20.0", "tslint-ionic-rules": "0.0.21", "tslint-react": "^4.1.0", "typescript": "3.5.3" }, "jest": { "preset": "ts-jest", "setupFilesAfterEnv": [ "<rootDir>/jest.setup.js" ], "testPathIgnorePatterns": [ "node_modules", "dist-transpiled", "dist" ], "modulePaths": [ "<rootDir>" ] } }
packages/react-router/package.json
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.0001731621305225417, 0.0001689227792667225, 0.0001627087767701596, 0.00017122180724982172, 0.000003988773187302286 ]
{ "id": 1, "code_window": [ " render() {\n", " console.log('hash router in your bundle!!!');\n", " const { children, ...props } = this.props;\n", " return (\n", " <HashRouter {...props}>\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 7 }
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-tabs-tab1', templateUrl: './tabs-tab1.component.html', }) export class TabsTab1Component { title = 'ERROR'; segment = 'one'; changed = 'false'; ionViewWillEnter() { NgZone.assertInAngularZone(); setTimeout(() => { NgZone.assertInAngularZone(); this.title = 'Tab 1 - Page 1'; }); } segmentChanged(ev: any) { console.log('Segment changed', ev); this.changed = 'true'; } }
angular/test/test-app/src/app/tabs-tab1/tabs-tab1.component.ts
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.0001710258366074413, 0.00017044822743628174, 0.00016932595463003963, 0.00017099289107136428, 7.936807264741219e-7 ]
{ "id": 2, "code_window": [ " </HashRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 15 }
import React from 'react'; import { HashRouter, HashRouterProps } from 'react-router-dom'; import { RouteManagerWithRouter } from './Router'; export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> { render() { console.log('hash router in your bundle!!!'); const { children, ...props } = this.props; return ( <HashRouter {...props}> <RouteManagerWithRouter>{children}</RouteManagerWithRouter> </HashRouter> ); } })();
packages/react-router/src/ReactRouter/IonReactHashRouter.tsx
1
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.02340831607580185, 0.013146898709237576, 0.0028854813426733017, 0.013146898709237576, 0.010261417366564274 ]
{ "id": 2, "code_window": [ " </HashRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 15 }
import { PopoverOptions, popoverController } from '@ionic/core'; import { createOverlayComponent } from './createOverlayComponent'; export type ReactPopoverOptions = Omit<PopoverOptions, 'component' | 'componentProps'> & { children: React.ReactNode; }; export const IonPopover = /*@__PURE__*/createOverlayComponent<ReactPopoverOptions, HTMLIonPopoverElement>('IonPopover', popoverController);
packages/react/src/components/IonPopover.tsx
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00016812080866657197, 0.00016812080866657197, 0.00016812080866657197, 0.00016812080866657197, 0 ]
{ "id": 2, "code_window": [ " </HashRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 15 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Avatar - Basic</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Avatar - Basic</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-avatar> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-chip> <ion-avatar> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label>Chip Avatar</ion-label> </ion-chip> <ion-item> <ion-avatar slot="start"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label>Item Avatar</ion-label> </ion-item> <ion-item> <ion-avatar slot="end"> <img src="/src/components/avatar/test/avatar.svg"> </ion-avatar> <ion-label>Wide Avatar</ion-label> </ion-item> </ion-content> </ion-app> </body> </html>
core/src/components/avatar/test/basic/index.html
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017372758884448558, 0.00016965869872365147, 0.00016751946532167494, 0.00016844832862261683, 0.000002449013891236973 ]
{ "id": 2, "code_window": [ " </HashRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactHashRouter.tsx", "type": "replace", "edit_start_line_idx": 15 }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ionic v4 + Vue.js - Custom transitions</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <!-- Disable Ionic transitions --> <script>window.disableIonicTransitions = true</script> <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script src="https://unpkg.com/vue-class-component@latest/dist/vue-class-component.js"></script> <script src="https://unpkg.com/vue-property-decorator@latest/lib/vue-property-decorator.umd.js"></script> <script src="https://unpkg.com/@modus/ionic-vue@latest/dist/ionic-vue.js"></script> <script src="https://unpkg.com/@ionic/core@latest/dist/ionic.js"></script> <link rel="stylesheet" href="https://unpkg.com/@ionic/core@latest/css/ionic.bundle.css"/> <style> .fade-enter-active, .fade-leave-active { transition: opacity .3s ease; } .fade-enter, .fade-leave-to { opacity: 0; } </style> </head> <body> <ion-app> <ion-vue-router></ion-vue-router> </ion-app> <script> const Toolbar = Vue.component('Toolbar', { name: 'Toolbar', props: { title: String, backURL: String }, template: `<ion-header> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button :default-href="backURL"/> </ion-buttons> <ion-title>{{ title }}</ion-title> </ion-toolbar> </ion-header>` }) const Home = { template: `<transition name="fade"> <ion-page class="ion-page"> <toolbar title="Home"/> <ion-content class="ion-content" padding> <router-link to="/page">Go to page</router-link> </ion-content> </ion-page> </transition>` } const Page = { template: `<transition name="fade"> <ion-page class="ion-page"> <toolbar title="Page" backURL="/"/> <ion-content class="ion-content" padding> <ion-button @click="goHome">Go home</ion-button> </ion-content> </ion-page> </transition>`, methods: { goHome() { this.$router.back() } } } Vue.config.ignoredElements.push(/^ion-/) new Vue({ router: new IonicVue.IonicVueRouter({ routes: [ { path: '/', component: Home }, { path: '/page', component: Page }, ], }), }).$mount('ion-app') </script> </body> </html>
vue/cookbook/custom-transitions.html
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00018771096074488014, 0.0001707787305349484, 0.00016504230734426528, 0.00016882506315596402, 0.000006423824743251316 ]
{ "id": 3, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> {\n", " render() {\n", " const { children, ...props } = this.props;\n", " return (\n", " <BrowserRouter {...props}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export class IonReactRouter extends React.Component<BrowserRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
import React from 'react'; import { BrowserRouter, BrowserRouterProps } from 'react-router-dom'; import { RouteManagerWithRouter } from './Router'; export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> { render() { const { children, ...props } = this.props; return ( <BrowserRouter {...props}> <RouteManagerWithRouter>{children}</RouteManagerWithRouter> </BrowserRouter> ); } })();
packages/react-router/src/ReactRouter/IonReactRouter.tsx
1
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.9985034465789795, 0.9977718591690063, 0.997040331363678, 0.9977718591690063, 0.0007315576076507568 ]
{ "id": 3, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> {\n", " render() {\n", " const { children, ...props } = this.props;\n", " return (\n", " <BrowserRouter {...props}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export class IonReactRouter extends React.Component<BrowserRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { isDevMode } from '../dev'; describe('isDevMode', () => { it('by default, should return false since we are in test', () => { const isDev = isDevMode(); expect(isDev).toBeFalsy(); }); it('when in dev mode, should return true', () => { process.env.NODE_ENV = 'development'; const isDev = isDevMode(); expect(isDev).toBeTruthy() }); });
packages/react-router/src/utils/__tests__/dev.spec.ts
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017915140779223293, 0.00017815190949477255, 0.0001771524257492274, 0.00017815190949477255, 9.99491021502763e-7 ]
{ "id": 3, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> {\n", " render() {\n", " const { children, ...props } = this.props;\n", " return (\n", " <BrowserRouter {...props}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export class IonReactRouter extends React.Component<BrowserRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
:root { /* Custom Toolbar CSS (optional) */ /* --ion-toolbar-background: #000; --ion-toolbar-border-color: #333; --ion-toolbar-color: limegreen; --ion-toolbar-color-activated: rgb(35, 156, 35); */ --ion-color-primary: #428CFF; --ion-color-primary-rgb: 66,140,255; --ion-color-primary-contrast: #ffffff; --ion-color-primary-contrast-rgb: 255,255,255; --ion-color-primary-shade: #3a7be0; --ion-color-primary-tint: #5598ff; --ion-color-secondary: #50C8FF; --ion-color-secondary-rgb: 80,200,255; --ion-color-secondary-contrast: #ffffff; --ion-color-secondary-contrast-rgb: 255,255,255; --ion-color-secondary-shade: #46b0e0; --ion-color-secondary-tint: #62ceff; --ion-color-tertiary: #6A64FF; --ion-color-tertiary-rgb: 106,100,255; --ion-color-tertiary-contrast: #ffffff; --ion-color-tertiary-contrast-rgb: 255,255,255; --ion-color-tertiary-shade: #5d58e0; --ion-color-tertiary-tint: #7974ff; --ion-color-success: #2FDF75; --ion-color-success-rgb: 47,223,117; --ion-color-success-contrast: #000000; --ion-color-success-contrast-rgb: 0,0,0; --ion-color-success-shade: #29c467; --ion-color-success-tint: #44e283; --ion-color-warning: #FFD534; --ion-color-warning-rgb: 255,213,52; --ion-color-warning-contrast: #000000; --ion-color-warning-contrast-rgb: 0,0,0; --ion-color-warning-shade: #e0bb2e; --ion-color-warning-tint: #ffd948; --ion-color-danger: #FF4961; --ion-color-danger-rgb: 255,73,97; --ion-color-danger-contrast: #ffffff; --ion-color-danger-contrast-rgb: 255,255,255; --ion-color-danger-shade: #e04055; --ion-color-danger-tint: #ff5b71; --ion-color-dark: #F4F5F8; --ion-color-dark-rgb: 244,245,248; --ion-color-dark-contrast: #000000; --ion-color-dark-contrast-rgb: 0,0,0; --ion-color-dark-shade: #d7d8da; --ion-color-dark-tint: #f5f6f9; --ion-color-medium: #989AA2; --ion-color-medium-rgb: 152,154,162; --ion-color-medium-contrast: #000000; --ion-color-medium-contrast-rgb: 0,0,0; --ion-color-medium-shade: #86888f; --ion-color-medium-tint: #a2a4ab; --ion-color-light: #222428; --ion-color-light-rgb: 34,36,40; --ion-color-light-contrast: #ffffff; --ion-color-light-contrast-rgb: 255,255,255; --ion-color-light-shade: #1e2023; --ion-color-light-tint: #383a3e; } /* Customize the Toolbar Segment by Mode */ .ios { --ion-background-color: #000000; --ion-background-color-rgb: 0,0,0; --ion-text-color: #ffffff; --ion-text-color-rgb: 255,255,255; --ion-color-step-50: #0d0d0d; --ion-color-step-100: #1a1a1a; --ion-color-step-150: #262626; --ion-color-step-200: #333333; --ion-color-step-250: #404040; --ion-color-step-300: #4d4d4d; --ion-color-step-350: #595959; --ion-color-step-400: #666666; --ion-color-step-450: #737373; --ion-color-step-500: #808080; --ion-color-step-550: #8c8c8c; --ion-color-step-600: #999999; --ion-color-step-650: #a6a6a6; --ion-color-step-700: #b3b3b3; --ion-color-step-750: #bfbfbf; --ion-color-step-800: #cccccc; --ion-color-step-850: #d9d9d9; --ion-color-step-900: #e6e6e6; --ion-color-step-950: #f2f2f2; --ion-item-background: #1c1c1c; --ion-item-background-activated: #313131; /* --ion-toolbar-color-unchecked: limegreen; --ion-toolbar-color-checked: limegreen; */ } .md { --ion-background-color: #121212; --ion-background-color-rgb: 18,18,18; --ion-text-color: #ffffff; --ion-text-color-rgb: 255,255,255; --ion-border-color: #222222; --ion-color-step-50: #1e1e1e; --ion-color-step-100: #2a2a2a; --ion-color-step-150: #363636; --ion-color-step-200: #414141; --ion-color-step-250: #4d4d4d; --ion-color-step-300: #595959; --ion-color-step-350: #656565; --ion-color-step-400: #717171; --ion-color-step-450: #7d7d7d; --ion-color-step-500: #898989; --ion-color-step-550: #949494; --ion-color-step-600: #a0a0a0; --ion-color-step-650: #acacac; --ion-color-step-700: #b8b8b8; --ion-color-step-750: #c4c4c4; --ion-color-step-800: #d0d0d0; --ion-color-step-850: #dbdbdb; --ion-color-step-900: #e7e7e7; --ion-color-step-950: #f3f3f3; --ion-item-background: #1A1B1E; /* --ion-toolbar-color-unchecked: rgba(255, 255, 255, .6); --ion-toolbar-color-checked: #fff; */ }
core/src/themes/test/css-variables/css/dark.css
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017953704809769988, 0.00017805445531848818, 0.00017300172476097941, 0.00017861397645901889, 0.0000015725319144621608 ]
{ "id": 3, "code_window": [ "\n", "import { RouteManagerWithRouter } from './Router';\n", "\n", "export const IonReactRouter = /*@__PURE__*/ (() => class IonReactRouterInternal extends React.Component<BrowserRouterProps> {\n", " render() {\n", " const { children, ...props } = this.props;\n", " return (\n", " <BrowserRouter {...props}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export class IonReactRouter extends React.Component<BrowserRouterProps> {\n" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 5 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Thumbnail - Basic</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Thumbnail - Basic</ion-title> </ion-toolbar> </ion-header> <ion-content id="content"> <ion-thumbnail> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label>Item Thumbnail</ion-label> </ion-item> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label>Wide Thumbnail</ion-label> </ion-item> </ion-content> </ion-app> </body> </html>
core/src/components/thumbnail/test/basic/index.html
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.0001790129317669198, 0.00017501701950095594, 0.00016676181985531002, 0.0001774640113580972, 0.0000044586540752789006 ]
{ "id": 4, "code_window": [ " <BrowserRouter {...props}>\n", " <RouteManagerWithRouter>{children}</RouteManagerWithRouter>\n", " </BrowserRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 14 }
import React from 'react'; import { HashRouter, HashRouterProps } from 'react-router-dom'; import { RouteManagerWithRouter } from './Router'; export const IonReactHashRouter = /*@__PURE__*/ (() => class IonReactHashRouterInternal extends React.Component<HashRouterProps> { render() { console.log('hash router in your bundle!!!'); const { children, ...props } = this.props; return ( <HashRouter {...props}> <RouteManagerWithRouter>{children}</RouteManagerWithRouter> </HashRouter> ); } })();
packages/react-router/src/ReactRouter/IonReactHashRouter.tsx
1
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.003438876708969474, 0.003339735558256507, 0.00324059440754354, 0.003339735558256507, 0.00009914115071296692 ]
{ "id": 4, "code_window": [ " <BrowserRouter {...props}>\n", " <RouteManagerWithRouter>{children}</RouteManagerWithRouter>\n", " </BrowserRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 14 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Nav</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script> <script> class PageOne extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Page One</ion-title> </ion-toolbar> </ion-header> <ion-content> page one <p><a href='#/two/second-page'>Go to page 2</a></p> <p><a href='#/two/three/hola'>Go to page 3 (hola)</a></p> <p><a href='#/two/three/something'>Go to page 3 (something)</a></p> </ion-content>`; } } class PageTwo extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Page Two</ion-title> </ion-toolbar> </ion-header> <ion-content> <p><a href='#/two/three/hola'>Go to page 3 (hola)</a></p> <p><a href='#/two/three/hello'>Go to page 3 (hello)</a></p> </ion-content>`; } } class PageThree extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Page 3 ${this.prop1}</ion-title> </ion-toolbar> </ion-header> <ion-content> <p><a href='#/two/three/hola'>Go to page 3 (hola)</a></p> <p><a href='#/two/three/hello'>Go to page 3 (hello)</a></p> <p><a href='#/two/second-page'>Go to page 2</a></p> <p><a href='#/two/'>Go to page 1</a></p> </ion-content>`; } } class TabOne extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Tab one</ion-title> </ion-toolbar> </ion-header> <ion-content> this is the first pahe </ion-content>`; } } class TabTwo extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Tab Two</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-nav></ion-nav> </ion-content>`; } } class TabThree extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Tab three</ion-title> </ion-toolbar> </ion-header> <ion-content> hey! this is the 3 tab </ion-content>`; } } class TabsPage extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-tabs> <ion-tab tab="tab-one" component="tab-one"></ion-tab> <ion-tab tab="tab-two" component="tab-two"></ion-tab> <ion-tab tab="tab-three" component="tab-three"></ion-tab> <ion-tab tab="tab-four"> inline tab 4 </ion-tab> <ion-tab-bar slot="bottom"> <ion-tab-button tab="tab-one"> <ion-label>Plain List</ion-label> <ion-icon name="star"></ion-icon> </ion-tab-button> <ion-tab-button tab="tab-two"> <ion-label>Schedule</ion-label> <ion-icon name="globe"></ion-icon> </ion-tab-button> <ion-tab-button tab="tab-three"> <ion-label>Stopwatch</ion-label> <ion-icon name="logo-facebook"></ion-icon> </ion-tab-button> <ion-tab-button tab="tab-four"> <ion-label>Messages</ion-label> <ion-icon name="star"></ion-icon> </ion-tab-button> </ion-tab-bar> </ion-tabs> `; } } class LoginPage extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Login Page</ion-title> </ion-toolbar> </ion-header> <ion-content> page one <p><a href='#/two/second-page'>Go to page 2</a></p> <p><a href='#/two/three/hola'>Go to page 3 (hola)</a></p> <p><a href='#/two/three/something'>Go to page 3 (something)</a></p> </ion-content>`; } } class LoginConfirmPage extends HTMLElement { connectedCallback() { this.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Login Confirm Page</ion-title> </ion-toolbar> </ion-header> <ion-content> page one <p><a href='#/two/second-page'>Go to page 2</a></p> <p><a href='#/two/three/hola'>Go to page 3 (hola)</a></p> <p><a href='#/two/three/something'>Go to page 3 (something)</a></p> </ion-content>`; } } customElements.define('page-one', PageOne); customElements.define('page-two', PageTwo); customElements.define('page-three', PageThree); customElements.define('tabs-page', TabsPage); customElements.define('tab-one', TabOne); customElements.define('tab-two', TabTwo); customElements.define('tab-three', TabThree); customElements.define('login-page', LoginPage); customElements.define('login-confirm-page', LoginConfirmPage); </script> </head> <body> <ion-app> <ion-router> <ion-route url="/login" component="login-page"></ion-route> <ion-route url="/login-confirm" component="login-confirm-page"></ion-route> <ion-route url="/" component="tabs-page"> <ion-route url="/" component="tab-one"> </ion-route> <ion-route url="/two" component="tab-two"> <ion-route component="page-one"> </ion-route> <ion-route url="/second-page" component="page-two"> </ion-route> <ion-route url="/three/:prop1" component="page-three"> </ion-route> </ion-route> <ion-route url="/three" component="tab-three"> </ion-route> <ion-route url="/four" component="tab-four"> </ion-route> </ion-route> </ion-router> <ion-nav></ion-nav> </ion-app> <style> f { display: block; margin: 15px auto; max-width: 150px; height: 150px; background: blue; } f:last-of-type { background: yellow; } </style> </body> <script> </script> </html>
core/src/components/router/test/basic/index.html
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.00017717236187309027, 0.00016940792556852102, 0.00016570347361266613, 0.0001690471253823489, 0.0000026972527393809287 ]
{ "id": 4, "code_window": [ " <BrowserRouter {...props}>\n", " <RouteManagerWithRouter>{children}</RouteManagerWithRouter>\n", " </BrowserRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 14 }
import { AnimationBuilder, Mode, SpinnerTypes } from '../../interface'; export interface LoadingOptions { spinner?: SpinnerTypes | null; message?: string; cssClass?: string | string[]; showBackdrop?: boolean; duration?: number; translucent?: boolean; animated?: boolean; backdropDismiss?: boolean; mode?: Mode; keyboardClose?: boolean; id?: string; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; }
core/src/components/loading/loading-interface.ts
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.000172052692505531, 0.00017143829609267414, 0.00017082389967981726, 0.00017143829609267414, 6.143964128568769e-7 ]
{ "id": 4, "code_window": [ " <BrowserRouter {...props}>\n", " <RouteManagerWithRouter>{children}</RouteManagerWithRouter>\n", " </BrowserRouter>\n", " );\n", " }\n", "})();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace" ], "after_edit": [ "}" ], "file_path": "packages/react-router/src/ReactRouter/IonReactRouter.tsx", "type": "replace", "edit_start_line_idx": 14 }
```tsx import React, { useState } from 'react'; import { IonToast, IonContent, IonButton } from '@ionic/react'; export const ToastExample: React.FC = () => { const [showToast1, setShowToast1] = useState(false); const [showToast2, setShowToast2] = useState(false); return ( <IonContent> <IonButton onClick={() => setShowToast1(true)} expand="block">Show Toast 1</IonButton> <IonButton onClick={() => setShowToast2(true)} expand="block">Show Toast 2</IonButton> <IonToast isOpen={showToast1} onDidDismiss={() => setShowToast1(false)} message="Your settings have been saved." duration={200} /> <IonToast isOpen={showToast2} onDidDismiss={() => setShowToast2(false)} message="Click to Close" position="top" buttons={[ { side: 'start', icon: 'star', text: 'Favorite', handler: () => { console.log('Favorite clicked'); } }, { text: 'Done', role: 'cancel', handler: () => { console.log('Cancel clicked'); } } ]} /> </IonContent> ); }; ```
core/src/components/toast/usage/react.md
0
https://github.com/ionic-team/ionic-framework/commit/ce7314db0b290ad83ec94efdf8fadec57be0062c
[ 0.0001751942909322679, 0.00017165634199045599, 0.0001679085398791358, 0.00017197051784023643, 0.0000025120366444753017 ]
{ "id": 0, "code_window": [ "\tcursor: pointer;\n", "}\n", "\n", "\n", "/* Body */\n", "\n", ".colorpicker-body {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-header.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.013657322153449059, 0.0007487605907954276, 0.0001642317947698757, 0.0001701476430753246, 0.0022091746795922518 ]
{ "id": 0, "code_window": [ "\tcursor: pointer;\n", "}\n", "\n", "\n", "/* Body */\n", "\n", ".colorpicker-body {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-header.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { fillInIncompleteTokens, renderMarkdown, renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { marked } from 'vs/base/common/marked/marked'; import { parse } from 'vs/base/common/marshalling'; import { isWeb } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; function strToNode(str: string): HTMLElement { return new DOMParser().parseFromString(str, 'text/html').body.firstChild as HTMLElement; } function assertNodeEquals(actualNode: HTMLElement, expectedHtml: string) { const expectedNode = strToNode(expectedHtml); assert.ok( actualNode.isEqualNode(expectedNode), `Expected: ${expectedNode.outerHTML}\nActual: ${actualNode.outerHTML}`); } suite('MarkdownRenderer', () => { suite('Sanitization', () => { test('Should not render images with unknown schemes', () => { const markdown = { value: `![image](no-such://example.com/cat.gif)` }; const result: HTMLElement = renderMarkdown(markdown).element; assert.strictEqual(result.innerHTML, '<p><img alt="image"></p>'); }); }); suite('Images', () => { test('image rendering conforms to default', () => { const markdown = { value: `![image](http://example.com/cat.gif 'caption')` }; const result: HTMLElement = renderMarkdown(markdown).element; assertNodeEquals(result, '<div><p><img title="caption" alt="image" src="http://example.com/cat.gif"></p></div>'); }); test('image rendering conforms to default without title', () => { const markdown = { value: `![image](http://example.com/cat.gif)` }; const result: HTMLElement = renderMarkdown(markdown).element; assertNodeEquals(result, '<div><p><img alt="image" src="http://example.com/cat.gif"></p></div>'); }); test('image width from title params', () => { const result: HTMLElement = renderMarkdown({ value: `![image](http://example.com/cat.gif|width=100px 'caption')` }).element; assertNodeEquals(result, `<div><p><img width="100" title="caption" alt="image" src="http://example.com/cat.gif"></p></div>`); }); test('image height from title params', () => { const result: HTMLElement = renderMarkdown({ value: `![image](http://example.com/cat.gif|height=100 'caption')` }).element; assertNodeEquals(result, `<div><p><img height="100" title="caption" alt="image" src="http://example.com/cat.gif"></p></div>`); }); test('image width and height from title params', () => { const result: HTMLElement = renderMarkdown({ value: `![image](http://example.com/cat.gif|height=200,width=100 'caption')` }).element; assertNodeEquals(result, `<div><p><img height="200" width="100" title="caption" alt="image" src="http://example.com/cat.gif"></p></div>`); }); test('image with file uri should render as same origin uri', () => { if (isWeb) { return; } const result: HTMLElement = renderMarkdown({ value: `![image](file:///images/cat.gif)` }).element; assertNodeEquals(result, '<div><p><img src="vscode-file://vscode-app/images/cat.gif" alt="image"></p></div>'); }); }); suite('Code block renderer', () => { const simpleCodeBlockRenderer = (lang: string, code: string): Promise<HTMLElement> => { const element = document.createElement('code'); element.textContent = code; return Promise.resolve(element); }; test('asyncRenderCallback should be invoked for code blocks', () => { const markdown = { value: '```js\n1 + 1;\n```' }; return new Promise<void>(resolve => { renderMarkdown(markdown, { asyncRenderCallback: resolve, codeBlockRenderer: simpleCodeBlockRenderer }); }); }); test('asyncRenderCallback should not be invoked if result is immediately disposed', () => { const markdown = { value: '```js\n1 + 1;\n```' }; return new Promise<void>((resolve, reject) => { const result = renderMarkdown(markdown, { asyncRenderCallback: reject, codeBlockRenderer: simpleCodeBlockRenderer }); result.dispose(); setTimeout(resolve, 50); }); }); test('asyncRenderCallback should not be invoked if dispose is called before code block is rendered', () => { const markdown = { value: '```js\n1 + 1;\n```' }; return new Promise<void>((resolve, reject) => { let resolveCodeBlockRendering: (x: HTMLElement) => void; const result = renderMarkdown(markdown, { asyncRenderCallback: reject, codeBlockRenderer: () => { return new Promise(resolve => { resolveCodeBlockRendering = resolve; }); } }); setTimeout(() => { result.dispose(); resolveCodeBlockRendering(document.createElement('code')); setTimeout(resolve, 50); }, 50); }); }); test('Code blocks should use leading language id (#157793)', async () => { const markdown = { value: '```js some other stuff\n1 + 1;\n```' }; const lang = await new Promise<string>(resolve => { renderMarkdown(markdown, { codeBlockRenderer: async (lang, value) => { resolve(lang); return simpleCodeBlockRenderer(lang, value); } }); }); assert.strictEqual(lang, 'js'); }); }); suite('ThemeIcons Support On', () => { test('render appendText', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true }); mds.appendText('$(zap) $(not a theme icon) $(add)'); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>$(zap)&nbsp;$(not&nbsp;a&nbsp;theme&nbsp;icon)&nbsp;$(add)</p>`); }); test('render appendMarkdown', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true }); mds.appendMarkdown('$(zap) $(not a theme icon) $(add)'); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p><span class="codicon codicon-zap"></span> $(not a theme icon) <span class="codicon codicon-add"></span></p>`); }); test('render appendMarkdown with escaped icon', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true }); mds.appendMarkdown('\\$(zap) $(not a theme icon) $(add)'); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>$(zap) $(not a theme icon) <span class="codicon codicon-add"></span></p>`); }); test('render icon in link', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true }); mds.appendMarkdown(`[$(zap)-link](#link)`); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p><a data-href="#link" href="" title="#link"><span class="codicon codicon-zap"></span>-link</a></p>`); }); test('render icon in table', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true }); mds.appendMarkdown(` | text | text | |--------|----------------------| | $(zap) | [$(zap)-link](#link) |`); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<table> <thead> <tr> <th>text</th> <th>text</th> </tr> </thead> <tbody><tr> <td><span class="codicon codicon-zap"></span></td> <td><a data-href="#link" href="" title="#link"><span class="codicon codicon-zap"></span>-link</a></td> </tr> </tbody></table> `); }); test('render icon in <a> without href (#152170)', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: true, supportHtml: true }); mds.appendMarkdown(`<a>$(sync)</a>`); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p><span class="codicon codicon-sync"></span></p>`); }); }); suite('ThemeIcons Support Off', () => { test('render appendText', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: false }); mds.appendText('$(zap) $(not a theme icon) $(add)'); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>$(zap)&nbsp;$(not&nbsp;a&nbsp;theme&nbsp;icon)&nbsp;$(add)</p>`); }); test('render appendMarkdown with escaped icon', () => { const mds = new MarkdownString(undefined, { supportThemeIcons: false }); mds.appendMarkdown('\\$(zap) $(not a theme icon) $(add)'); const result: HTMLElement = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>$(zap) $(not a theme icon) $(add)</p>`); }); }); test('npm Hover Run Script not working #90855', function () { const md: IMarkdownString = JSON.parse('{"value":"[Run Script](command:npm.runScriptFromHover?%7B%22documentUri%22%3A%7B%22%24mid%22%3A1%2C%22fsPath%22%3A%22c%3A%5C%5CUsers%5C%5Cjrieken%5C%5CCode%5C%5C_sample%5C%5Cfoo%5C%5Cpackage.json%22%2C%22_sep%22%3A1%2C%22external%22%3A%22file%3A%2F%2F%2Fc%253A%2FUsers%2Fjrieken%2FCode%2F_sample%2Ffoo%2Fpackage.json%22%2C%22path%22%3A%22%2Fc%3A%2FUsers%2Fjrieken%2FCode%2F_sample%2Ffoo%2Fpackage.json%22%2C%22scheme%22%3A%22file%22%7D%2C%22script%22%3A%22echo%22%7D \\"Run the script as a task\\")","supportThemeIcons":false,"isTrusted":true,"uris":{"__uri_e49443":{"$mid":1,"fsPath":"c:\\\\Users\\\\jrieken\\\\Code\\\\_sample\\\\foo\\\\package.json","_sep":1,"external":"file:///c%3A/Users/jrieken/Code/_sample/foo/package.json","path":"/c:/Users/jrieken/Code/_sample/foo/package.json","scheme":"file"},"command:npm.runScriptFromHover?%7B%22documentUri%22%3A%7B%22%24mid%22%3A1%2C%22fsPath%22%3A%22c%3A%5C%5CUsers%5C%5Cjrieken%5C%5CCode%5C%5C_sample%5C%5Cfoo%5C%5Cpackage.json%22%2C%22_sep%22%3A1%2C%22external%22%3A%22file%3A%2F%2F%2Fc%253A%2FUsers%2Fjrieken%2FCode%2F_sample%2Ffoo%2Fpackage.json%22%2C%22path%22%3A%22%2Fc%3A%2FUsers%2Fjrieken%2FCode%2F_sample%2Ffoo%2Fpackage.json%22%2C%22scheme%22%3A%22file%22%7D%2C%22script%22%3A%22echo%22%7D":{"$mid":1,"path":"npm.runScriptFromHover","scheme":"command","query":"{\\"documentUri\\":\\"__uri_e49443\\",\\"script\\":\\"echo\\"}"}}}'); const element = renderMarkdown(md).element; const anchor = element.querySelector('a')!; assert.ok(anchor); assert.ok(anchor.dataset['href']); const uri = URI.parse(anchor.dataset['href']!); const data = <{ script: string; documentUri: URI }>parse(decodeURIComponent(uri.query)); assert.ok(data); assert.strictEqual(data.script, 'echo'); assert.ok(data.documentUri.toString().startsWith('file:///c%3A/')); }); test('Should not render command links by default', () => { const md = new MarkdownString(`[command1](command:doFoo) <a href="command:doFoo">command2</a>`, { supportHtml: true }); const result: HTMLElement = renderMarkdown(md).element; assert.strictEqual(result.innerHTML, `<p>command1 command2</p>`); }); test('Should render command links in trusted strings', () => { const md = new MarkdownString(`[command1](command:doFoo) <a href="command:doFoo">command2</a>`, { isTrusted: true, supportHtml: true, }); const result: HTMLElement = renderMarkdown(md).element; assert.strictEqual(result.innerHTML, `<p><a data-href="command:doFoo" href="" title="command:doFoo">command1</a> <a data-href="command:doFoo" href="">command2</a></p>`); }); suite('PlaintextMarkdownRender', () => { test('test code, blockquote, heading, list, listitem, paragraph, table, tablerow, tablecell, strong, em, br, del, text are rendered plaintext', () => { const markdown = { value: '`code`\n>quote\n# heading\n- list\n\n\ntable | table2\n--- | --- \none | two\n\n\nbo**ld**\n_italic_\n~~del~~\nsome text' }; const expected = 'code\nquote\nheading\nlist\ntable table2 one two \nbold\nitalic\ndel\nsome text\n'; const result: string = renderMarkdownAsPlaintext(markdown); assert.strictEqual(result, expected); }); test('test html, hr, image, link are rendered plaintext', () => { const markdown = { value: '<div>html</div>\n\n---\n![image](imageLink)\n[text](textLink)' }; const expected = '\ntext\n'; const result: string = renderMarkdownAsPlaintext(markdown); assert.strictEqual(result, expected); }); }); suite('supportHtml', () => { test('supportHtml is disabled by default', () => { const mds = new MarkdownString(undefined, {}); mds.appendMarkdown('a<b>b</b>c'); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>abc</p>`); }); test('Renders html when supportHtml=true', () => { const mds = new MarkdownString(undefined, { supportHtml: true }); mds.appendMarkdown('a<b>b</b>c'); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>a<b>b</b>c</p>`); }); test('Should not include scripts even when supportHtml=true', () => { const mds = new MarkdownString(undefined, { supportHtml: true }); mds.appendMarkdown('a<b onclick="alert(1)">b</b><script>alert(2)</script>c'); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>a<b>b</b>c</p>`); }); test('Should not render html appended as text', () => { const mds = new MarkdownString(undefined, { supportHtml: true }); mds.appendText('a<b>b</b>c'); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<p>a&lt;b&gt;b&lt;/b&gt;c</p>`); }); test('Should render html images', () => { if (isWeb) { return; } const mds = new MarkdownString(undefined, { supportHtml: true }); mds.appendMarkdown(`<img src="http://example.com/cat.gif">`); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<img src="http://example.com/cat.gif">`); }); test('Should render html images with file uri as same origin uri', () => { if (isWeb) { return; } const mds = new MarkdownString(undefined, { supportHtml: true }); mds.appendMarkdown(`<img src="file:///images/cat.gif">`); const result = renderMarkdown(mds).element; assert.strictEqual(result.innerHTML, `<img src="vscode-file://vscode-app/images/cat.gif">`); }); }); suite('fillInIncompleteTokens', () => { function ignoreRaw(...tokenLists: marked.Token[][]): void { tokenLists.forEach(tokens => { tokens.forEach(t => t.raw = ''); }); } const completeTable = '| a | b |\n| --- | --- |'; test('complete table', () => { const tokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); assert.equal(newTokens, tokens); }); test('full header only', () => { const incompleteTable = '| a | b |'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header only with trailing space', () => { const incompleteTable = '| a | b | '; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); ignoreRaw(newTokens, completeTableTokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('incomplete header', () => { const incompleteTable = '| a | b'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); ignoreRaw(newTokens, completeTableTokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('incomplete header one column', () => { const incompleteTable = '| a '; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(incompleteTable + '|\n| --- |'); const newTokens = fillInIncompleteTokens(tokens); ignoreRaw(newTokens, completeTableTokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with extras', () => { const incompleteTable = '| a **bold** | b _italics_ |'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(incompleteTable + '\n| --- | --- |'); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with leading text', () => { // Parsing this gives one token and one 'text' subtoken const incompleteTable = 'here is a table\n| a | b |'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(incompleteTable + '\n| --- | --- |'); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with leading other stuff', () => { // Parsing this gives one token and one 'text' subtoken const incompleteTable = '```js\nconst xyz = 123;\n```\n| a | b |'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(incompleteTable + '\n| --- | --- |'); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with incomplete separator', () => { const incompleteTable = '| a | b |\n| ---'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with incomplete separator 2', () => { const incompleteTable = '| a | b |\n| --- |'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('full header with incomplete separator 3', () => { const incompleteTable = '| a | b |\n|'; const tokens = marked.lexer(incompleteTable); const completeTableTokens = marked.lexer(completeTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, completeTableTokens); }); test('not a table', () => { const incompleteTable = '| a | b |\nsome text'; const tokens = marked.lexer(incompleteTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, tokens); }); test('not a table 2', () => { const incompleteTable = '| a | b |\n| --- |\nsome text'; const tokens = marked.lexer(incompleteTable); const newTokens = fillInIncompleteTokens(tokens); assert.deepStrictEqual(newTokens, tokens); }); test('complete code block', () => { const completeCodeblock = '```js\nconst xyz = 123;\n```'; const tokens = marked.lexer(completeCodeblock); const newTokens = fillInIncompleteTokens(tokens); assert.equal(newTokens, tokens); }); test('code block header only', () => { const incompleteCodeblock = '```js'; const tokens = marked.lexer(incompleteCodeblock); const newTokens = fillInIncompleteTokens(tokens); const completeCodeblockTokens = marked.lexer(incompleteCodeblock + '\n```'); assert.deepStrictEqual(newTokens, completeCodeblockTokens); }); test('code block header no lang', () => { const incompleteCodeblock = '```'; const tokens = marked.lexer(incompleteCodeblock); const newTokens = fillInIncompleteTokens(tokens); const completeCodeblockTokens = marked.lexer(incompleteCodeblock + '\n```'); assert.deepStrictEqual(newTokens, completeCodeblockTokens); }); test('code block header and some code', () => { const incompleteCodeblock = '```js\nconst'; const tokens = marked.lexer(incompleteCodeblock); const newTokens = fillInIncompleteTokens(tokens); const completeCodeblockTokens = marked.lexer(incompleteCodeblock + '\n```'); assert.deepStrictEqual(newTokens, completeCodeblockTokens); }); test('code block header with leading text', () => { const incompleteCodeblock = 'some text\n```js'; const tokens = marked.lexer(incompleteCodeblock); const newTokens = fillInIncompleteTokens(tokens); const completeCodeblockTokens = marked.lexer(incompleteCodeblock + '\n```'); assert.deepStrictEqual(newTokens, completeCodeblockTokens); }); test('code block header with leading text and some code', () => { const incompleteCodeblock = 'some text\n```js\nconst'; const tokens = marked.lexer(incompleteCodeblock); const newTokens = fillInIncompleteTokens(tokens); const completeCodeblockTokens = marked.lexer(incompleteCodeblock + '\n```'); assert.deepStrictEqual(newTokens, completeCodeblockTokens); }); }); });
src/vs/base/test/browser/markdownRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0052586994133889675, 0.00027397324447520077, 0.0001643245341256261, 0.0001691127399681136, 0.0006996196461841464 ]
{ "id": 0, "code_window": [ "\tcursor: pointer;\n", "}\n", "\n", "\n", "/* Body */\n", "\n", ".colorpicker-body {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-header.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 69 }
{ "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": [ { "name": "Attach", "type": "node", "request": "attach", "port": 6045, "protocol": "inspector", "sourceMaps": true, "outFiles": ["${workspaceFolder}/out/**/*.js"] }, { "name": "Unit Tests", "type": "node", "request": "launch", "program": "${workspaceFolder}/../../../node_modules/mocha/bin/_mocha", "stopOnEntry": false, "args": [ "--timeout", "999999", "--colors" ], "cwd": "${workspaceFolder}", "runtimeExecutable": null, "runtimeArgs": [], "env": {}, "sourceMaps": true, "outFiles": ["${workspaceFolder}/out/**/*.js"] } ] }
extensions/html-language-features/server/.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017943007696885616, 0.00017100632248912007, 0.00016642299306113273, 0.00016908612451516092, 0.000004995563813281478 ]
{ "id": 0, "code_window": [ "\tcursor: pointer;\n", "}\n", "\n", "\n", "/* Body */\n", "\n", ".colorpicker-body {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-header.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 69 }
module.exports = { "parserOptions": { "tsconfigRootDir": __dirname, "project": "./tsconfig.json" }, "rules": { "@typescript-eslint/prefer-optional-chain": "warn", "@typescript-eslint/prefer-readonly": "warn" } };
extensions/typescript-language-features/web/.eslintrc.js
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017703759658616036, 0.00017385675164405257, 0.00017067590670194477, 0.00017385675164405257, 0.0000031808449421077967 ]
{ "id": 1, "code_window": [ "\tpointer-events: none;\n", "}\n", "\n", ".colorpicker-body .insert-button {\n", "\theight: 20px;\n", "\twidth: 58px;\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-body.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n", "\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.02106431871652603, 0.001703003654256463, 0.00016486567619722337, 0.00020270863024052233, 0.00401772977784276 ]
{ "id": 1, "code_window": [ "\tpointer-events: none;\n", "}\n", "\n", ".colorpicker-body .insert-button {\n", "\theight: 20px;\n", "\twidth: 58px;\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-body.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n", "\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 152 }
{ "comments": { "lineComment": "//-" }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "'", "close": "'", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["'", "'"], ["\"", "\""] ], "folding": { "offSide": true } }
extensions/pug/language-configuration.json
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001687072654021904, 0.00016669718024786562, 0.00016522983787581325, 0.00016615439380984753, 0.0000014706181445944821 ]
{ "id": 1, "code_window": [ "\tpointer-events: none;\n", "}\n", "\n", ".colorpicker-body .insert-button {\n", "\theight: 20px;\n", "\twidth: 58px;\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-body.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n", "\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { FileAccess } from 'vs/base/common/network'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { GettingStartedDetailsRenderer } from 'vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedDetailsRenderer'; import { convertInternalMediaPathToFileURI } from 'vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedService'; import { TestFileService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestExtensionService } from 'vs/workbench/test/common/workbenchTestServices'; suite('Getting Started Markdown Renderer', () => { test('renders theme picker markdown with images', async () => { const fileService = new TestFileService(); const languageService = new LanguageService(); const renderer = new GettingStartedDetailsRenderer(fileService, new TestNotificationService(), new TestExtensionService(), languageService); const mdPath = convertInternalMediaPathToFileURI('theme_picker').with({ query: JSON.stringify({ moduleId: 'vs/workbench/contrib/welcomeGettingStarted/common/media/theme_picker' }) }); const mdBase = FileAccess.asFileUri('vs/workbench/contrib/welcomeGettingStarted/common/media/'); const rendered = await renderer.renderMarkdown(mdPath, mdBase); const imageSrcs = [...rendered.matchAll(/img src="[^"]*"/g)].map(match => match[0]); for (const src of imageSrcs) { const targetSrcFormat = /^img src="https:\/\/file\+.vscode-resource.vscode-cdn.net\/.*\/vs\/workbench\/contrib\/welcomeGettingStarted\/common\/media\/.*.png"$/; assert(targetSrcFormat.test(src), `${src} didnt match regex`); } languageService.dispose(); }); });
src/vs/workbench/contrib/welcomeGettingStarted/test/browser/gettingStartedMarkdownRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00019297969993203878, 0.00017581897554919124, 0.00016797803982626647, 0.00017115907394327223, 0.000009993388630391564 ]
{ "id": 1, "code_window": [ "\tpointer-events: none;\n", "}\n", "\n", ".colorpicker-body .insert-button {\n", "\theight: 20px;\n", "\twidth: 58px;\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".colorpicker-body.standalone-color-picker {\n", "\tcolor: var(--vscode-editorHoverWidget-foreground);\n", "\tbackground-color: var(--vscode-editorHoverWidget-background);\n", "\tborder: 1px solid var(--vscode-editorHoverWidget-border);\n", "}\n", "\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPicker.css", "type": "add", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { FindMatch } from 'vs/editor/common/model'; import { CellFindMatchWithIndex, ICellViewModel, CellWebviewFindMatch } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { ISearchRange, ITextSearchPreviewOptions, TextSearchMatch } from 'vs/workbench/services/search/common/search'; import { Range } from 'vs/editor/common/core/range'; export interface NotebookMatchInfo { cellIndex: number; matchStartIndex: number; matchEndIndex: number; cell: ICellViewModel; webviewMatchInfo?: { index: number; }; } interface CellFindMatchInfoForTextModel { notebookMatchInfo: NotebookMatchInfo; matches: FindMatch[] | CellWebviewFindMatch; } export class NotebookTextSearchMatch extends TextSearchMatch { constructor(text: string, range: ISearchRange | ISearchRange[], public notebookMatchInfo: NotebookMatchInfo, previewOptions?: ITextSearchPreviewOptions) { super(text, range, previewOptions); } } function notebookEditorMatchToTextSearchResult(cellInfo: CellFindMatchInfoForTextModel, previewOptions?: ITextSearchPreviewOptions): NotebookTextSearchMatch | undefined { const matches = cellInfo.matches; if (Array.isArray(matches)) { if (matches.length > 0) { const lineTexts: string[] = []; const firstLine = matches[0].range.startLineNumber; const lastLine = matches[matches.length - 1].range.endLineNumber; for (let i = firstLine; i <= lastLine; i++) { lineTexts.push(cellInfo.notebookMatchInfo.cell.textBuffer.getLineContent(i)); } return new NotebookTextSearchMatch( lineTexts.join('\n') + '\n', matches.map(m => new Range(m.range.startLineNumber - 1, m.range.startColumn - 1, m.range.endLineNumber - 1, m.range.endColumn - 1)), cellInfo.notebookMatchInfo, previewOptions); } } else { // TODO: this is a placeholder for webview matches const searchPreviewInfo = matches.searchPreviewInfo ?? { line: '', range: { start: 0, end: 0 } }; return new NotebookTextSearchMatch( searchPreviewInfo.line, new Range(0, searchPreviewInfo.range.start, 0, searchPreviewInfo.range.end), cellInfo.notebookMatchInfo, previewOptions); } return undefined; } export function notebookEditorMatchesToTextSearchResults(cellFindMatches: CellFindMatchWithIndex[], previewOptions?: ITextSearchPreviewOptions): NotebookTextSearchMatch[] { let previousEndLine = -1; const groupedMatches: CellFindMatchInfoForTextModel[] = []; let currentMatches: FindMatch[] = []; let startIndexOfCurrentMatches = 0; cellFindMatches.forEach((cellFindMatch) => { const cellIndex = cellFindMatch.index; cellFindMatch.contentMatches.forEach((match, index) => { if (match.range.startLineNumber !== previousEndLine) { if (currentMatches.length > 0) { groupedMatches.push({ matches: [...currentMatches], notebookMatchInfo: { cellIndex, matchStartIndex: startIndexOfCurrentMatches, matchEndIndex: index, cell: cellFindMatch.cell } }); currentMatches = []; } startIndexOfCurrentMatches = cellIndex + 1; } currentMatches.push(match); previousEndLine = match.range.endLineNumber; }); if (currentMatches.length > 0) { groupedMatches.push({ matches: [...currentMatches], notebookMatchInfo: { cellIndex, matchStartIndex: startIndexOfCurrentMatches, matchEndIndex: cellFindMatch.contentMatches.length - 1, cell: cellFindMatch.cell } }); currentMatches = []; } cellFindMatch.webviewMatches.forEach((match, index) => { groupedMatches.push({ matches: match, notebookMatchInfo: { cellIndex, matchStartIndex: index, matchEndIndex: index, cell: cellFindMatch.cell, webviewMatchInfo: { index: match.index } } }); }); }); return groupedMatches.map(sameLineMatches => { return notebookEditorMatchToTextSearchResult(sameLineMatches, previewOptions); }).filter((elem): elem is NotebookTextSearchMatch => !!elem); }
src/vs/workbench/contrib/search/browser/searchNotebookHelpers.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00018432650540489703, 0.0001716064871288836, 0.0001669661287451163, 0.00016876455629244447, 0.0000054795941650809254 ]
{ "id": 2, "code_window": [ "\tprivate readonly _domNode: HTMLElement;\n", "\tprivate readonly pickedColorNode: HTMLElement;\n", "\tprivate backgroundColor: Color;\n", "\n", "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) {\n", "\t\tsuper();\n", "\n", "\t\tthis._domNode = $('.colorpicker-header');\n", "\t\tdom.append(container, this._domNode);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService, private showingStandaloneColorPicker: boolean = false) {\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.9978558421134949, 0.1720752716064453, 0.0001671735371928662, 0.0006168283871375024, 0.339119017124176 ]
{ "id": 2, "code_window": [ "\tprivate readonly _domNode: HTMLElement;\n", "\tprivate readonly pickedColorNode: HTMLElement;\n", "\tprivate backgroundColor: Color;\n", "\n", "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) {\n", "\t\tsuper();\n", "\n", "\t\tthis._domNode = $('.colorpicker-header');\n", "\t\tdom.append(container, this._domNode);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService, private showingStandaloneColorPicker: boolean = false) {\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; import { IExperimentationTelemetryReporter } from './experimentTelemetryReporter'; import { DiagnosticKind, DiagnosticsManager } from './languageFeatures/diagnostics'; import * as Proto from './protocol'; import { EventName } from './protocol.const'; import BufferSyncSupport from './tsServer/bufferSyncSupport'; import { OngoingRequestCancellerFactory } from './tsServer/cancellation'; import { ILogDirectoryProvider } from './tsServer/logDirectoryProvider'; import { ITypeScriptServer, TsServerLog, TsServerProcessFactory, TypeScriptServerExitEvent } from './tsServer/server'; import { TypeScriptServerError } from './tsServer/serverError'; import { TypeScriptServerSpawner } from './tsServer/spawner'; import { TypeScriptVersionManager } from './tsServer/versionManager'; import { ITypeScriptVersionProvider, TypeScriptVersion } from './tsServer/versionProvider'; import { ClientCapabilities, ClientCapability, ExecConfig, ITypeScriptServiceClient, ServerResponse, TypeScriptRequests } from './typescriptService'; import API from './utils/api'; import { ServiceConfigurationProvider, SyntaxServerConfiguration, TsServerLogLevel, TypeScriptServiceConfiguration, areServiceConfigurationsEqual } from './utils/configuration'; import { Disposable } from './utils/dispose'; import * as fileSchemes from './utils/fileSchemes'; import { Logger } from './utils/logger'; import { isWeb, isWebAndHasSharedArrayBuffers } from './utils/platform'; import { TypeScriptPluginPathsProvider } from './utils/pluginPathsProvider'; import { PluginManager, TypeScriptServerPlugin } from './utils/plugins'; import { TelemetryProperties, TelemetryReporter, VSCodeTelemetryReporter } from './utils/telemetry'; import Tracer from './utils/tracer'; import { ProjectType, inferredProjectCompilerOptions } from './utils/tsconfig'; export interface TsDiagnostics { readonly kind: DiagnosticKind; readonly resource: vscode.Uri; readonly diagnostics: Proto.Diagnostic[]; } interface ToCancelOnResourceChanged { readonly resource: vscode.Uri; cancel(): void; } namespace ServerState { export const enum Type { None, Running, Errored } export const None = { type: Type.None } as const; export class Running { readonly type = Type.Running; constructor( public readonly server: ITypeScriptServer, /** * API version obtained from the version picker after checking the corresponding path exists. */ public readonly apiVersion: API, /** * Version reported by currently-running tsserver. */ public tsserverVersion: string | undefined, public languageServiceEnabled: boolean, ) { } public readonly toCancelOnResourceChange = new Set<ToCancelOnResourceChanged>(); updateTsserverVersion(tsserverVersion: string) { this.tsserverVersion = tsserverVersion; } updateLanguageServiceEnabled(enabled: boolean) { this.languageServiceEnabled = enabled; } } export class Errored { readonly type = Type.Errored; constructor( public readonly error: Error, public readonly tsServerLog: TsServerLog | undefined, ) { } } export type State = typeof None | Running | Errored; } export default class TypeScriptServiceClient extends Disposable implements ITypeScriptServiceClient { private readonly emptyAuthority = 'ts-nul-authority'; private readonly inMemoryResourcePrefix = '^'; private readonly _onReady?: { promise: Promise<void>; resolve: () => void; reject: () => void }; private _configuration: TypeScriptServiceConfiguration; private readonly pluginPathsProvider: TypeScriptPluginPathsProvider; private readonly _versionManager: TypeScriptVersionManager; private readonly logger: Logger; private readonly tracer: Tracer; private readonly typescriptServerSpawner: TypeScriptServerSpawner; private serverState: ServerState.State = ServerState.None; private lastStart: number; private numberRestarts: number; private _isPromptingAfterCrash = false; private isRestarting: boolean = false; private hasServerFatallyCrashedTooManyTimes = false; private readonly loadingIndicator = new ServerInitializingIndicator(); public readonly telemetryReporter: TelemetryReporter; public readonly bufferSyncSupport: BufferSyncSupport; public readonly diagnosticsManager: DiagnosticsManager; public readonly pluginManager: PluginManager; private readonly logDirectoryProvider: ILogDirectoryProvider; private readonly cancellerFactory: OngoingRequestCancellerFactory; private readonly versionProvider: ITypeScriptVersionProvider; private readonly processFactory: TsServerProcessFactory; constructor( private readonly context: vscode.ExtensionContext, onCaseInsenitiveFileSystem: boolean, services: { pluginManager: PluginManager; logDirectoryProvider: ILogDirectoryProvider; cancellerFactory: OngoingRequestCancellerFactory; versionProvider: ITypeScriptVersionProvider; processFactory: TsServerProcessFactory; serviceConfigurationProvider: ServiceConfigurationProvider; experimentTelemetryReporter: IExperimentationTelemetryReporter | undefined; logger: Logger; }, allModeIds: readonly string[] ) { super(); this.logger = services.logger; this.tracer = new Tracer(this.logger); this.pluginManager = services.pluginManager; this.logDirectoryProvider = services.logDirectoryProvider; this.cancellerFactory = services.cancellerFactory; this.versionProvider = services.versionProvider; this.processFactory = services.processFactory; this.lastStart = Date.now(); let resolve: () => void; let reject: () => void; const p = new Promise<void>((res, rej) => { resolve = res; reject = rej; }); this._onReady = { promise: p, resolve: resolve!, reject: reject! }; this.numberRestarts = 0; this._configuration = services.serviceConfigurationProvider.loadFromWorkspace(); this.versionProvider.updateConfiguration(this._configuration); this.pluginPathsProvider = new TypeScriptPluginPathsProvider(this._configuration); this._versionManager = this._register(new TypeScriptVersionManager(this._configuration, this.versionProvider, context.workspaceState)); this._register(this._versionManager.onDidPickNewVersion(() => { this.restartTsServer(); })); this.bufferSyncSupport = new BufferSyncSupport(this, allModeIds, onCaseInsenitiveFileSystem); this.onReady(() => { this.bufferSyncSupport.listen(); }); this.diagnosticsManager = new DiagnosticsManager('typescript', onCaseInsenitiveFileSystem); this.bufferSyncSupport.onDelete(resource => { this.cancelInflightRequestsForResource(resource); this.diagnosticsManager.deleteAllDiagnosticsInFile(resource); }, null, this._disposables); this.bufferSyncSupport.onWillChange(resource => { this.cancelInflightRequestsForResource(resource); }); vscode.workspace.onDidChangeConfiguration(() => { const oldConfiguration = this._configuration; this._configuration = services.serviceConfigurationProvider.loadFromWorkspace(); this.versionProvider.updateConfiguration(this._configuration); this._versionManager.updateConfiguration(this._configuration); this.pluginPathsProvider.updateConfiguration(this._configuration); this.tracer.updateConfiguration(); if (this.serverState.type === ServerState.Type.Running) { if (!this._configuration.implicitProjectConfiguration.isEqualTo(oldConfiguration.implicitProjectConfiguration)) { this.setCompilerOptionsForInferredProjects(this._configuration); } if (!areServiceConfigurationsEqual(this._configuration, oldConfiguration)) { this.restartTsServer(); } } }, this, this._disposables); this.telemetryReporter = new VSCodeTelemetryReporter(services.experimentTelemetryReporter, () => { if (this.serverState.type === ServerState.Type.Running) { if (this.serverState.tsserverVersion) { return this.serverState.tsserverVersion; } } return this.apiVersion.fullVersionString; }); this.typescriptServerSpawner = new TypeScriptServerSpawner(this.versionProvider, this._versionManager, this.logDirectoryProvider, this.pluginPathsProvider, this.logger, this.telemetryReporter, this.tracer, this.processFactory); this._register(this.pluginManager.onDidUpdateConfig(update => { this.configurePlugin(update.pluginId, update.config); })); this._register(this.pluginManager.onDidChangePlugins(() => { this.restartTsServer(); })); } public get capabilities() { if (this._configuration.useSyntaxServer === SyntaxServerConfiguration.Always) { return new ClientCapabilities( ClientCapability.Syntax, ClientCapability.EnhancedSyntax); } if (isWeb()) { if (this.isProjectWideIntellisenseOnWebEnabled()) { return new ClientCapabilities( ClientCapability.Syntax, ClientCapability.EnhancedSyntax, ClientCapability.Semantic); } else { return new ClientCapabilities( ClientCapability.Syntax, ClientCapability.EnhancedSyntax); } } if (this.apiVersion.gte(API.v400)) { return new ClientCapabilities( ClientCapability.Syntax, ClientCapability.EnhancedSyntax, ClientCapability.Semantic); } return new ClientCapabilities( ClientCapability.Syntax, ClientCapability.Semantic); } private readonly _onDidChangeCapabilities = this._register(new vscode.EventEmitter<void>()); readonly onDidChangeCapabilities = this._onDidChangeCapabilities.event; private isProjectWideIntellisenseOnWebEnabled(): boolean { return isWebAndHasSharedArrayBuffers() && this._configuration.enableProjectWideIntellisenseOnWeb; } private cancelInflightRequestsForResource(resource: vscode.Uri): void { if (this.serverState.type !== ServerState.Type.Running) { return; } for (const request of this.serverState.toCancelOnResourceChange) { if (request.resource.toString() === resource.toString()) { request.cancel(); } } } public get configuration() { return this._configuration; } public override dispose() { super.dispose(); this.bufferSyncSupport.dispose(); if (this.serverState.type === ServerState.Type.Running) { this.serverState.server.kill(); } this.loadingIndicator.reset(); } public restartTsServer(fromUserAction = false): void { if (this.serverState.type === ServerState.Type.Running) { this.info('Killing TS Server'); this.isRestarting = true; this.serverState.server.kill(); } if (fromUserAction) { // Reset crash trackers this.hasServerFatallyCrashedTooManyTimes = false; this.numberRestarts = 0; this.lastStart = Date.now(); } this.serverState = this.startService(true); } private readonly _onTsServerStarted = this._register(new vscode.EventEmitter<{ version: TypeScriptVersion; usedApiVersion: API }>()); public readonly onTsServerStarted = this._onTsServerStarted.event; private readonly _onDiagnosticsReceived = this._register(new vscode.EventEmitter<TsDiagnostics>()); public readonly onDiagnosticsReceived = this._onDiagnosticsReceived.event; private readonly _onConfigDiagnosticsReceived = this._register(new vscode.EventEmitter<Proto.ConfigFileDiagnosticEvent>()); public readonly onConfigDiagnosticsReceived = this._onConfigDiagnosticsReceived.event; private readonly _onResendModelsRequested = this._register(new vscode.EventEmitter<void>()); public readonly onResendModelsRequested = this._onResendModelsRequested.event; private readonly _onProjectLanguageServiceStateChanged = this._register(new vscode.EventEmitter<Proto.ProjectLanguageServiceStateEventBody>()); public readonly onProjectLanguageServiceStateChanged = this._onProjectLanguageServiceStateChanged.event; private readonly _onDidBeginInstallTypings = this._register(new vscode.EventEmitter<Proto.BeginInstallTypesEventBody>()); public readonly onDidBeginInstallTypings = this._onDidBeginInstallTypings.event; private readonly _onDidEndInstallTypings = this._register(new vscode.EventEmitter<Proto.EndInstallTypesEventBody>()); public readonly onDidEndInstallTypings = this._onDidEndInstallTypings.event; private readonly _onTypesInstallerInitializationFailed = this._register(new vscode.EventEmitter<Proto.TypesInstallerInitializationFailedEventBody>()); public readonly onTypesInstallerInitializationFailed = this._onTypesInstallerInitializationFailed.event; private readonly _onSurveyReady = this._register(new vscode.EventEmitter<Proto.SurveyReadyEventBody>()); public readonly onSurveyReady = this._onSurveyReady.event; public get apiVersion(): API { if (this.serverState.type === ServerState.Type.Running) { return this.serverState.apiVersion; } return API.defaultVersion; } public onReady(f: () => void): Promise<void> { return this._onReady!.promise.then(f); } private info(message: string, data?: any): void { this.logger.info(message, data); } private error(message: string, data?: any): void { this.logger.error(message, data); } private logTelemetry(eventName: string, properties?: TelemetryProperties) { this.telemetryReporter.logTelemetry(eventName, properties); } public ensureServiceStarted() { if (this.serverState.type !== ServerState.Type.Running) { this.startService(); } } private token: number = 0; private startService(resendModels: boolean = false): ServerState.State { this.info(`Starting TS Server`); if (this.isDisposed) { this.info(`Not starting server: disposed`); return ServerState.None; } if (this.hasServerFatallyCrashedTooManyTimes) { this.info(`Not starting server: too many crashes`); return ServerState.None; } let version = this._versionManager.currentVersion; if (!version.isValid) { vscode.window.showWarningMessage(vscode.l10n.t("The path {0} doesn't point to a valid tsserver install. Falling back to bundled TypeScript version.", version.path)); this._versionManager.reset(); version = this._versionManager.currentVersion; } this.info(`Using tsserver from: ${version.path}`); const apiVersion = version.apiVersion || API.defaultVersion; const mytoken = ++this.token; const handle = this.typescriptServerSpawner.spawn(version, this.capabilities, this.configuration, this.pluginManager, this.cancellerFactory, { onFatalError: (command, err) => this.fatalError(command, err), }); this.serverState = new ServerState.Running(handle, apiVersion, undefined, true); this.lastStart = Date.now(); /* __GDPR__ "tsserver.spawned" : { "owner": "mjbvz", "${include}": [ "${TypeScriptCommonProperties}" ], "localTypeScriptVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "typeScriptVersionSource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.logTelemetry('tsserver.spawned', { localTypeScriptVersion: this.versionProvider.localVersion ? this.versionProvider.localVersion.displayName : '', typeScriptVersionSource: version.source, }); handle.onError((err: Error) => { if (this.token !== mytoken) { // this is coming from an old process return; } if (err) { vscode.window.showErrorMessage(vscode.l10n.t("TypeScript language server exited with error. Error message is: {0}", err.message || err.name)); } this.serverState = new ServerState.Errored(err, handle.tsServerLog); this.error('TSServer errored with error.', err); if (handle.tsServerLog?.type === 'file') { this.error(`TSServer log file: ${handle.tsServerLog.uri.fsPath}`); } /* __GDPR__ "tsserver.error" : { "owner": "mjbvz", "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.logTelemetry('tsserver.error'); this.serviceExited(false); }); handle.onExit((data: TypeScriptServerExitEvent) => { const { code, signal } = data; this.error(`TSServer exited. Code: ${code}. Signal: ${signal}`); // In practice, the exit code is an integer with no ties to any identity, // so it can be classified as SystemMetaData, rather than CallstackOrException. /* __GDPR__ "tsserver.exitWithCode" : { "owner": "mjbvz", "code" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }, "signal" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }, "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.logTelemetry('tsserver.exitWithCode', { code: code ?? undefined, signal: signal ?? undefined }); if (this.token !== mytoken) { // this is coming from an old process return; } if (handle.tsServerLog?.type === 'file') { this.info(`TSServer log file: ${handle.tsServerLog.uri.fsPath}`); } this.serviceExited(!this.isRestarting); this.isRestarting = false; }); handle.onEvent(event => this.dispatchEvent(event)); if (apiVersion.gte(API.v300) && this.capabilities.has(ClientCapability.Semantic)) { this.loadingIndicator.startedLoadingProject(undefined /* projectName */); } this.serviceStarted(resendModels); this._onReady!.resolve(); this._onTsServerStarted.fire({ version: version, usedApiVersion: apiVersion }); this._onDidChangeCapabilities.fire(); return this.serverState; } public async showVersionPicker(): Promise<void> { this._versionManager.promptUserForVersion(); } public async openTsServerLogFile(): Promise<boolean> { if (this._configuration.tsServerLogLevel === TsServerLogLevel.Off) { vscode.window.showErrorMessage<vscode.MessageItem>( vscode.l10n.t("TS Server logging is off. Please set 'typescript.tsserver.log' and restart the TS server to enable logging"), { title: vscode.l10n.t("Enable logging and restart TS server"), }) .then(selection => { if (selection) { return vscode.workspace.getConfiguration().update('typescript.tsserver.log', 'verbose', true).then(() => { this.restartTsServer(); }); } return undefined; }); return false; } if (this.serverState.type !== ServerState.Type.Running || !this.serverState.server.tsServerLog) { vscode.window.showWarningMessage(vscode.l10n.t("TS Server has not started logging.")); return false; } switch (this.serverState.server.tsServerLog.type) { case 'output': { this.serverState.server.tsServerLog.output.show(); return true; } case 'file': { try { const doc = await vscode.workspace.openTextDocument(this.serverState.server.tsServerLog.uri); await vscode.window.showTextDocument(doc); return true; } catch { // noop } try { await vscode.commands.executeCommand('revealFileInOS', this.serverState.server.tsServerLog.uri); return true; } catch { vscode.window.showWarningMessage(vscode.l10n.t("Could not open TS Server log file")); return false; } } } } private serviceStarted(resendModels: boolean): void { this.bufferSyncSupport.reset(); const watchOptions = this.apiVersion.gte(API.v380) ? this.configuration.watchOptions : undefined; const configureOptions: Proto.ConfigureRequestArguments = { hostInfo: 'vscode', preferences: { providePrefixAndSuffixTextForRename: true, allowRenameOfImportPath: true, includePackageJsonAutoImports: this._configuration.includePackageJsonAutoImports, }, watchOptions }; this.executeWithoutWaitingForResponse('configure', configureOptions); this.setCompilerOptionsForInferredProjects(this._configuration); if (resendModels) { this._onResendModelsRequested.fire(); this.bufferSyncSupport.reinitialize(); this.bufferSyncSupport.requestAllDiagnostics(); } // Reconfigure any plugins for (const [pluginName, config] of this.pluginManager.configurations()) { this.configurePlugin(pluginName, config); } } private setCompilerOptionsForInferredProjects(configuration: TypeScriptServiceConfiguration): void { const args: Proto.SetCompilerOptionsForInferredProjectsArgs = { options: this.getCompilerOptionsForInferredProjects(configuration) }; this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args); } private getCompilerOptionsForInferredProjects(configuration: TypeScriptServiceConfiguration): Proto.ExternalProjectCompilerOptions { return { ...inferredProjectCompilerOptions(ProjectType.TypeScript, configuration), allowJs: true, allowSyntheticDefaultImports: true, allowNonTsExtensions: true, resolveJsonModule: true, }; } private serviceExited(restart: boolean): void { this.loadingIndicator.reset(); const previousState = this.serverState; this.serverState = ServerState.None; if (restart) { const diff = Date.now() - this.lastStart; this.numberRestarts++; let startService = true; const pluginExtensionList = this.pluginManager.plugins.map(plugin => plugin.extension.id).join(', '); const reportIssueItem: vscode.MessageItem = { title: vscode.l10n.t("Report Issue"), }; let prompt: Thenable<undefined | vscode.MessageItem> | undefined = undefined; if (this.numberRestarts > 5) { this.numberRestarts = 0; if (diff < 10 * 1000 /* 10 seconds */) { this.lastStart = Date.now(); startService = false; this.hasServerFatallyCrashedTooManyTimes = true; if (this.pluginManager.plugins.length) { prompt = vscode.window.showErrorMessage<vscode.MessageItem>( vscode.l10n.t("The JS/TS language service immediately crashed 5 times. The service will not be restarted.\nThis may be caused by a plugin contributed by one of these extensions: {0}.\nPlease try disabling these extensions before filing an issue against VS Code.", pluginExtensionList)); } else { prompt = vscode.window.showErrorMessage( vscode.l10n.t("The JS/TS language service immediately crashed 5 times. The service will not be restarted."), reportIssueItem); } /* __GDPR__ "serviceExited" : { "owner": "mjbvz", "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.logTelemetry('serviceExited'); } else if (diff < 60 * 1000 * 5 /* 5 Minutes */) { this.lastStart = Date.now(); if (!this._isPromptingAfterCrash) { if (this.pluginManager.plugins.length) { prompt = vscode.window.showWarningMessage<vscode.MessageItem>( vscode.l10n.t("The JS/TS language service crashed 5 times in the last 5 Minutes.\nThis may be caused by a plugin contributed by one of these extensions: {0}\nPlease try disabling these extensions before filing an issue against VS Code.", pluginExtensionList)); } else { prompt = vscode.window.showWarningMessage( vscode.l10n.t("The JS/TS language service crashed 5 times in the last 5 Minutes."), reportIssueItem); } } } } else if (['vscode-insiders', 'code-oss'].includes(vscode.env.uriScheme)) { // Prompt after a single restart this.numberRestarts = 0; if (!this._isPromptingAfterCrash) { if (this.pluginManager.plugins.length) { prompt = vscode.window.showWarningMessage<vscode.MessageItem>( vscode.l10n.t("The JS/TS language service crashed.\nThis may be caused by a plugin contributed by one of these extensions: {0}.\nPlease try disabling these extensions before filing an issue against VS Code.", pluginExtensionList)); } else { prompt = vscode.window.showWarningMessage( vscode.l10n.t("The JS/TS language service crashed."), reportIssueItem); } } } if (prompt) { this._isPromptingAfterCrash = true; } prompt?.then(item => { this._isPromptingAfterCrash = false; if (item === reportIssueItem) { const minModernTsVersion = this.versionProvider.bundledVersion.apiVersion; if ( minModernTsVersion && previousState.type === ServerState.Type.Errored && previousState.error instanceof TypeScriptServerError && previousState.error.version.apiVersion?.lt(minModernTsVersion) ) { vscode.window.showWarningMessage( vscode.l10n.t("Please update your TypeScript version"), { modal: true, detail: vscode.l10n.t( "The workspace is using an old version of TypeScript ({0}).\n\nBefore reporting an issue, please update the workspace to use TypeScript {1} or newer to make sure the bug has not already been fixed.", previousState.error.version.apiVersion.displayName, minModernTsVersion.displayName), }); } else { const args = previousState.type === ServerState.Type.Errored && previousState.error instanceof TypeScriptServerError ? getReportIssueArgsForError(previousState.error, previousState.tsServerLog, this.pluginManager.plugins) : undefined; vscode.commands.executeCommand('workbench.action.openIssueReporter', args); } } }); if (startService) { this.startService(true); } } } public toTsFilePath(resource: vscode.Uri): string | undefined { if (fileSchemes.disabledSchemes.has(resource.scheme)) { return undefined; } if (resource.scheme === fileSchemes.file && !isWeb()) { return resource.fsPath; } return (this.isProjectWideIntellisenseOnWebEnabled() ? '' : this.inMemoryResourcePrefix) + '/' + resource.scheme + '/' + (resource.authority || this.emptyAuthority) + (resource.path.startsWith('/') ? resource.path : '/' + resource.path) + (resource.fragment ? '#' + resource.fragment : ''); } public toOpenTsFilePath(document: vscode.TextDocument, options: { suppressAlertOnFailure?: boolean } = {}): string | undefined { if (!this.bufferSyncSupport.ensureHasBuffer(document.uri)) { if (!options.suppressAlertOnFailure && !fileSchemes.disabledSchemes.has(document.uri.scheme)) { console.error(`Unexpected resource ${document.uri}`); } return undefined; } return this.toTsFilePath(document.uri); } public hasCapabilityForResource(resource: vscode.Uri, capability: ClientCapability): boolean { if (!this.capabilities.has(capability)) { return false; } switch (capability) { case ClientCapability.Semantic: { return fileSchemes.semanticSupportedSchemes.includes(resource.scheme); } case ClientCapability.Syntax: case ClientCapability.EnhancedSyntax: { return true; } } } public toResource(filepath: string): vscode.Uri { if (isWeb()) { // On web, the stdlib paths that TS return look like: '/lib.es2015.collection.d.ts' // TODO: Find out what extensionUri is when testing (should be http://localhost:8080/static/sources/extensions/typescript-language-features/) // TODO: make sure that this code path is getting hit if (filepath.startsWith('/lib.') && filepath.endsWith('.d.ts')) { return vscode.Uri.joinPath(this.context.extensionUri, 'dist', 'browser', 'typescript', filepath.slice(1)); } const parts = filepath.match(/^\/([^\/]+)\/([^\/]*)\/(.+)$/); if (parts) { const resource = vscode.Uri.parse(parts[1] + '://' + (parts[2] === this.emptyAuthority ? '' : parts[2]) + '/' + parts[3]); return this.bufferSyncSupport.toVsCodeResource(resource); } } if (filepath.startsWith(this.inMemoryResourcePrefix)) { const parts = filepath.match(/^\^\/([^\/]+)\/([^\/]*)\/(.+)$/); if (parts) { const resource = vscode.Uri.parse(parts[1] + '://' + (parts[2] === this.emptyAuthority ? '' : parts[2]) + '/' + parts[3]); return this.bufferSyncSupport.toVsCodeResource(resource); } } return this.bufferSyncSupport.toResource(filepath); } public getWorkspaceRootForResource(resource: vscode.Uri): string | undefined { const roots = vscode.workspace.workspaceFolders ? Array.from(vscode.workspace.workspaceFolders) : undefined; if (!roots?.length) { if (resource.scheme === fileSchemes.officeScript) { return '/'; } return undefined; } let tsRootPath: string | undefined; for (const root of roots.sort((a, b) => a.uri.fsPath.length - b.uri.fsPath.length)) { if (root.uri.scheme === resource.scheme && root.uri.authority === resource.authority) { if (resource.fsPath.startsWith(root.uri.fsPath + path.sep)) { tsRootPath = this.toTsFilePath(root.uri); break; } } } tsRootPath ??= this.toTsFilePath(roots[0].uri); if (!tsRootPath || tsRootPath.startsWith(this.inMemoryResourcePrefix)) { return undefined; } return tsRootPath; } public execute(command: keyof TypeScriptRequests, args: any, token: vscode.CancellationToken, config?: ExecConfig): Promise<ServerResponse.Response<Proto.Response>> { let executions: Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> | undefined; if (config?.cancelOnResourceChange) { const runningServerState = this.serverState; if (runningServerState.type === ServerState.Type.Running) { const source = new vscode.CancellationTokenSource(); token.onCancellationRequested(() => source.cancel()); const inFlight: ToCancelOnResourceChanged = { resource: config.cancelOnResourceChange, cancel: () => source.cancel(), }; runningServerState.toCancelOnResourceChange.add(inFlight); executions = this.executeImpl(command, args, { isAsync: false, token: source.token, expectsResult: true, ...config, }); executions[0]!.finally(() => { runningServerState.toCancelOnResourceChange.delete(inFlight); source.dispose(); }); } } if (!executions) { executions = this.executeImpl(command, args, { isAsync: false, token, expectsResult: true, ...config, }); } if (config?.nonRecoverable) { executions[0]!.catch(err => this.fatalError(command, err)); } if (command === 'updateOpen') { // If update open has completed, consider that the project has loaded Promise.all(executions).then(() => { this.loadingIndicator.reset(); }); } return executions[0]!; } public executeWithoutWaitingForResponse(command: keyof TypeScriptRequests, args: any): void { this.executeImpl(command, args, { isAsync: false, token: undefined, expectsResult: false }); } public executeAsync(command: keyof TypeScriptRequests, args: Proto.GeterrRequestArgs, token: vscode.CancellationToken): Promise<ServerResponse.Response<Proto.Response>> { return this.executeImpl(command, args, { isAsync: true, token, expectsResult: true })[0]!; } private executeImpl(command: keyof TypeScriptRequests, args: any, executeInfo: { isAsync: boolean; token?: vscode.CancellationToken; expectsResult: boolean; lowPriority?: boolean; requireSemantic?: boolean }): Array<Promise<ServerResponse.Response<Proto.Response>> | undefined> { const serverState = this.serverState; if (serverState.type === ServerState.Type.Running) { this.bufferSyncSupport.beforeCommand(command); return serverState.server.executeImpl(command, args, executeInfo); } else { return [Promise.resolve(ServerResponse.NoServer)]; } } public interruptGetErr<R>(f: () => R): R { return this.bufferSyncSupport.interruptGetErr(f); } private fatalError(command: string, error: unknown): void { /* __GDPR__ "fatalError" : { "owner": "mjbvz", "${include}": [ "${TypeScriptCommonProperties}", "${TypeScriptRequestErrorProperties}" ], "command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.logTelemetry('fatalError', { ...(error instanceof TypeScriptServerError ? error.telemetry : { command }) }); console.error(`A non-recoverable error occurred while executing tsserver command: ${command}`); if (error instanceof TypeScriptServerError && error.serverErrorText) { console.error(error.serverErrorText); } if (this.serverState.type === ServerState.Type.Running) { this.info('Killing TS Server'); const logfile = this.serverState.server.tsServerLog; this.serverState.server.kill(); if (error instanceof TypeScriptServerError) { this.serverState = new ServerState.Errored(error, logfile); } } } private dispatchEvent(event: Proto.Event) { switch (event.event) { case EventName.syntaxDiag: case EventName.semanticDiag: case EventName.suggestionDiag: { // This event also roughly signals that projects have been loaded successfully (since the TS server is synchronous) this.loadingIndicator.reset(); const diagnosticEvent = event as Proto.DiagnosticEvent; if (diagnosticEvent.body?.diagnostics) { this._onDiagnosticsReceived.fire({ kind: getDignosticsKind(event), resource: this.toResource(diagnosticEvent.body.file), diagnostics: diagnosticEvent.body.diagnostics }); } break; } case EventName.configFileDiag: this._onConfigDiagnosticsReceived.fire(event as Proto.ConfigFileDiagnosticEvent); break; case EventName.telemetry: { const body = (event as Proto.TelemetryEvent).body; this.dispatchTelemetryEvent(body); break; } case EventName.projectLanguageServiceState: { const body = (event as Proto.ProjectLanguageServiceStateEvent).body!; if (this.serverState.type === ServerState.Type.Running) { this.serverState.updateLanguageServiceEnabled(body.languageServiceEnabled); } this._onProjectLanguageServiceStateChanged.fire(body); break; } case EventName.projectsUpdatedInBackground: { this.loadingIndicator.reset(); const body = (event as Proto.ProjectsUpdatedInBackgroundEvent).body; const resources = body.openFiles.map(file => this.toResource(file)); this.bufferSyncSupport.getErr(resources); break; } case EventName.beginInstallTypes: this._onDidBeginInstallTypings.fire((event as Proto.BeginInstallTypesEvent).body); break; case EventName.endInstallTypes: this._onDidEndInstallTypings.fire((event as Proto.EndInstallTypesEvent).body); break; case EventName.typesInstallerInitializationFailed: this._onTypesInstallerInitializationFailed.fire((event as Proto.TypesInstallerInitializationFailedEvent).body); break; case EventName.surveyReady: this._onSurveyReady.fire((event as Proto.SurveyReadyEvent).body); break; case EventName.projectLoadingStart: this.loadingIndicator.startedLoadingProject((event as Proto.ProjectLoadingStartEvent).body.projectName); break; case EventName.projectLoadingFinish: this.loadingIndicator.finishedLoadingProject((event as Proto.ProjectLoadingFinishEvent).body.projectName); break; } } private dispatchTelemetryEvent(telemetryData: Proto.TelemetryEventBody): void { const properties: { [key: string]: string } = Object.create(null); switch (telemetryData.telemetryEventName) { case 'typingsInstalled': { const typingsInstalledPayload: Proto.TypingsInstalledTelemetryEventPayload = (telemetryData.payload as Proto.TypingsInstalledTelemetryEventPayload); properties['installedPackages'] = typingsInstalledPayload.installedPackages; if (typeof typingsInstalledPayload.installSuccess === 'boolean') { properties['installSuccess'] = typingsInstalledPayload.installSuccess.toString(); } if (typeof typingsInstalledPayload.typingsInstallerVersion === 'string') { properties['typingsInstallerVersion'] = typingsInstalledPayload.typingsInstallerVersion; } break; } default: { const payload = telemetryData.payload; if (payload) { Object.keys(payload).forEach((key) => { try { if (payload.hasOwnProperty(key)) { properties[key] = typeof payload[key] === 'string' ? payload[key] : JSON.stringify(payload[key]); } } catch (e) { // noop } }); } break; } } if (telemetryData.telemetryEventName === 'projectInfo') { if (this.serverState.type === ServerState.Type.Running) { this.serverState.updateTsserverVersion(properties['version']); } } /* __GDPR__ "typingsInstalled" : { "owner": "mjbvz", "installedPackages" : { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "installSuccess": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }, "typingsInstallerVersion": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth" }, "${include}": [ "${TypeScriptCommonProperties}" ] } */ // __GDPR__COMMENT__: Other events are defined by TypeScript. this.logTelemetry(telemetryData.telemetryEventName, properties); } private configurePlugin(pluginName: string, configuration: {}): any { if (this.apiVersion.gte(API.v314)) { this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration }); } } } function getReportIssueArgsForError( error: TypeScriptServerError, tsServerLog: TsServerLog | undefined, globalPlugins: readonly TypeScriptServerPlugin[], ): { extensionId: string; issueTitle: string; issueBody: string } | undefined { if (!error.serverStack || !error.serverMessage) { return undefined; } // Note these strings are intentionally not localized // as we want users to file issues in english const sections = [ `❗️❗️❗️ Please fill in the sections below to help us diagnose the issue ❗️❗️❗️`, `**TypeScript Version:** ${error.version.apiVersion?.fullVersionString}`, `**Steps to reproduce crash** 1. 2. 3.`, ]; if (globalPlugins.length) { sections.push( [ `**Global TypeScript Server Plugins**`, `❗️ Please test with extensions disabled. Extensions are the root cause of most TypeScript server crashes`, globalPlugins.map(plugin => `- \`${plugin.name}\` contributed by the \`${plugin.extension.id}\` extension`).join('\n') ].join('\n\n') ); } if (tsServerLog?.type === 'file') { sections.push(`**TS Server Log** ❗️ Please review and upload this log file to help us diagnose this crash: \`${tsServerLog.uri.fsPath}\` The log file may contain personal data, including full paths and source code from your workspace. You can scrub the log file to remove paths or other personal information. `); } else { sections.push(`**TS Server Log** ❗️ Server logging disabled. To help us fix crashes like this, please enable logging by setting: \`\`\`json "typescript.tsserver.log": "verbose" \`\`\` After enabling this setting, future crash reports will include the server log.`); } sections.push(`**TS Server Error Stack** Server: \`${error.serverId}\` \`\`\` ${error.serverStack} \`\`\``); return { extensionId: 'vscode.typescript-language-features', issueTitle: `TS Server fatal error: ${error.serverMessage}`, issueBody: sections.join('\n\n') }; } function getDignosticsKind(event: Proto.Event) { switch (event.event) { case 'syntaxDiag': return DiagnosticKind.Syntax; case 'semanticDiag': return DiagnosticKind.Semantic; case 'suggestionDiag': return DiagnosticKind.Suggestion; } throw new Error('Unknown dignostics kind'); } class ServerInitializingIndicator extends Disposable { private _task?: { project: string | undefined; resolve: () => void }; public reset(): void { if (this._task) { this._task.resolve(); this._task = undefined; } } /** * Signal that a project has started loading. */ public startedLoadingProject(projectName: string | undefined): void { // TS projects are loaded sequentially. Cancel existing task because it should always be resolved before // the incoming project loading task is. this.reset(); vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: vscode.l10n.t("Initializing JS/TS language features"), }, () => new Promise<void>(resolve => { this._task = { project: projectName, resolve }; })); } public finishedLoadingProject(projectName: string | undefined): void { if (this._task && this._task.project === projectName) { this._task.resolve(); this._task = undefined; } } }
extensions/typescript-language-features/src/typescriptServiceClient.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001960863301064819, 0.00017178009147755802, 0.00016539503121748567, 0.00017153832595795393, 0.0000038603920984314755 ]
{ "id": 2, "code_window": [ "\tprivate readonly _domNode: HTMLElement;\n", "\tprivate readonly pickedColorNode: HTMLElement;\n", "\tprivate backgroundColor: Color;\n", "\n", "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) {\n", "\t\tsuper();\n", "\n", "\t\tthis._domNode = $('.colorpicker-header');\n", "\t\tdom.append(container, this._domNode);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService, private showingStandaloneColorPicker: boolean = false) {\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { IProductService } from 'vs/platform/product/common/productService'; import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREFIX, CONFIGURATION_KEY_PREVENT_SLEEP, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_ID } from 'vs/platform/remoteTunnel/common/remoteTunnel'; import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticationService } from 'vs/workbench/services/authentication/common/authentication'; import { localize } from 'vs/nls'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { Registry } from 'vs/platform/registry/common/platform'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ILocalizedString } from 'vs/platform/action/common/action'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IStorageService, IStorageValueChangeEvent, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ILogger, ILoggerService, ILogService } from 'vs/platform/log/common/log'; import { INativeEnvironmentService } from 'vs/platform/environment/common/environment'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator, QuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { IOutputService } from 'vs/workbench/services/output/common/output'; import { IFileService } from 'vs/platform/files/common/files'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry'; import { IProgress, IProgressService, IProgressStep, ProgressLocation } from 'vs/platform/progress/common/progress'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { Action } from 'vs/base/common/actions'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { joinPath } from 'vs/base/common/resources'; import { ITunnelApplicationConfig } from 'vs/base/common/product'; import { isNumber, isObject, isString } from 'vs/base/common/types'; export const REMOTE_TUNNEL_CATEGORY: ILocalizedString = { original: 'Remote-Tunnels', value: localize('remoteTunnel.category', 'Remote Tunnels') }; type CONTEXT_KEY_STATES = 'connected' | 'connecting' | 'disconnected'; export const REMOTE_TUNNEL_CONNECTION_STATE_KEY = 'remoteTunnelConnection'; export const REMOTE_TUNNEL_CONNECTION_STATE = new RawContextKey<CONTEXT_KEY_STATES>(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'disconnected'); const SESSION_ID_STORAGE_KEY = 'remoteTunnelAccountPreference'; const REMOTE_TUNNEL_USED_STORAGE_KEY = 'remoteTunnelServiceUsed'; const REMOTE_TUNNEL_PROMPTED_PREVIEW_STORAGE_KEY = 'remoteTunnelServicePromptedPreview'; const REMOTE_TUNNEL_EXTENSION_RECOMMENDED_KEY = 'remoteTunnelExtensionRecommended'; const REMOTE_TUNNEL_EXTENSION_TIMEOUT = 4 * 60 * 1000; // show the recommendation that a machine started using tunnels if it joined less than 4 minutes ago interface UsedOnHostMessage { hostName: string; timeStamp: number } type ExistingSessionItem = { session: AuthenticationSession; providerId: string; label: string; description: string }; type IAuthenticationProvider = { id: string; scopes: string[] }; type AuthenticationProviderOption = IQuickPickItem & { provider: IAuthenticationProvider }; enum RemoteTunnelCommandIds { turnOn = 'workbench.remoteTunnel.actions.turnOn', turnOff = 'workbench.remoteTunnel.actions.turnOff', connecting = 'workbench.remoteTunnel.actions.connecting', manage = 'workbench.remoteTunnel.actions.manage', showLog = 'workbench.remoteTunnel.actions.showLog', configure = 'workbench.remoteTunnel.actions.configure', copyToClipboard = 'workbench.remoteTunnel.actions.copyToClipboard', learnMore = 'workbench.remoteTunnel.actions.learnMore', } // name shown in nofications namespace RemoteTunnelCommandLabels { export const turnOn = localize('remoteTunnel.actions.turnOn', 'Turn on Remote Tunnel Access...'); export const turnOff = localize('remoteTunnel.actions.turnOff', 'Turn off Remote Tunnel Access...'); export const showLog = localize('remoteTunnel.actions.showLog', 'Show Remote Tunnel Service Log'); export const configure = localize('remoteTunnel.actions.configure', 'Configure Machine Name...'); export const copyToClipboard = localize('remoteTunnel.actions.copyToClipboard', 'Copy Browser URI to Clipboard'); export const learnMore = localize('remoteTunnel.actions.learnMore', 'Get Started with Tunnels'); } export class RemoteTunnelWorkbenchContribution extends Disposable implements IWorkbenchContribution { private readonly connectionStateContext: IContextKey<CONTEXT_KEY_STATES>; private readonly serverConfiguration: ITunnelApplicationConfig; #authenticationSessionId: string | undefined; private connectionInfo: ConnectionInfo | undefined; private readonly logger: ILogger; constructor( @IAuthenticationService private readonly authenticationService: IAuthenticationService, @IDialogService private readonly dialogService: IDialogService, @IExtensionService private readonly extensionService: IExtensionService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IProductService productService: IProductService, @IStorageService private readonly storageService: IStorageService, @ILoggerService loggerService: ILoggerService, @ILogService logService: ILogService, @IQuickInputService private readonly quickInputService: IQuickInputService, @INativeEnvironmentService private environmentService: INativeEnvironmentService, @IFileService fileService: IFileService, @IRemoteTunnelService private remoteTunnelService: IRemoteTunnelService, @ICommandService private commandService: ICommandService, @IWorkspaceContextService private workspaceContextService: IWorkspaceContextService, @IProgressService private progressService: IProgressService, @INotificationService private notificationService: INotificationService ) { super(); this.logger = this._register(loggerService.createLogger(LOG_ID, { name: LOGGER_NAME })); this.connectionStateContext = REMOTE_TUNNEL_CONNECTION_STATE.bindTo(this.contextKeyService); const serverConfiguration = productService.tunnelApplicationConfig; if (!serverConfiguration || !productService.tunnelApplicationName) { this.logger.error('Missing \'tunnelApplicationConfig\' or \'tunnelApplicationName\' in product.json. Remote tunneling is not available.'); this.serverConfiguration = { authenticationProviders: {}, editorWebUrl: '', extension: { extensionId: '', friendlyName: '' } }; return; } this.serverConfiguration = serverConfiguration; this._register(this.remoteTunnelService.onDidTokenFailed(() => { this.logger.info('Clearing authentication preference because of successive token failures.'); this.clearAuthenticationPreference(); })); this._register(this.remoteTunnelService.onDidChangeTunnelStatus(status => { if (status.type === 'disconnected') { this.logger.info('Clearing authentication preference because of tunnel disconnected.'); this.clearAuthenticationPreference(); this.connectionInfo = undefined; } else if (status.type === 'connecting') { this.connectionStateContext.set('connecting'); } else if (status.type === 'connected') { this.connectionInfo = status.info; this.connectionStateContext.set('connected'); } })); // If the user signs out of the current session, reset our cached auth state in memory and on disk this._register(this.authenticationService.onDidChangeSessions((e) => this.onDidChangeSessions(e.event))); // If another window changes the preferred session storage, reset our cached auth state in memory this._register(this.storageService.onDidChangeValue(e => this.onDidChangeStorage(e))); this.registerCommands(); this.initialize(); this.recommendRemoteExtensionIfNeeded(); } private get existingSessionId() { return this.storageService.get(SESSION_ID_STORAGE_KEY, StorageScope.APPLICATION); } private set existingSessionId(sessionId: string | undefined) { this.logger.trace(`Saving authentication preference for ID ${sessionId}.`); if (sessionId === undefined) { this.storageService.remove(SESSION_ID_STORAGE_KEY, StorageScope.APPLICATION); } else { this.storageService.store(SESSION_ID_STORAGE_KEY, sessionId, StorageScope.APPLICATION, StorageTarget.MACHINE); } } private async recommendRemoteExtensionIfNeeded() { const remoteExtension = this.serverConfiguration.extension; const shouldRecommend = async () => { if (this.storageService.getBoolean(REMOTE_TUNNEL_EXTENSION_RECOMMENDED_KEY, StorageScope.APPLICATION)) { return false; } if (await this.extensionService.getExtension(remoteExtension.extensionId)) { return false; } const usedOnHostMessage = this.storageService.get(REMOTE_TUNNEL_USED_STORAGE_KEY, StorageScope.APPLICATION); if (!usedOnHostMessage) { return false; } let usedOnHost: string | undefined; try { const message = JSON.parse(usedOnHostMessage); if (!isObject(message)) { return false; } const { hostName, timeStamp } = message as UsedOnHostMessage; if (!isString(hostName)! || !isNumber(timeStamp) || new Date().getTime() > timeStamp + REMOTE_TUNNEL_EXTENSION_TIMEOUT) { return false; } usedOnHost = hostName; } catch (_) { // problems parsing the message, likly the old message format return false; } const currentHostName = await this.remoteTunnelService.getHostName(); if (!currentHostName || currentHostName === usedOnHost) { return false; } return usedOnHost; }; const recommed = async () => { const usedOnHost = await shouldRecommend(); if (!usedOnHost) { return false; } this.notificationService.notify({ severity: Severity.Info, message: localize( { key: 'recommend.remoteExtension', comment: ['{0} will be a tunnel name, {1} will the link address to the web UI, {6} an extension name. [label](command:commandId) is a markdown link. Only translate the label, do not modify the format'] }, "Tunnel '{0}' is avaiable for remote access. The {1} extension can be used to connect to it.", usedOnHost, remoteExtension.friendlyName ), actions: { primary: [ new Action('showExtension', localize('action.showExtension', "Show Extension"), undefined, true, () => { return this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', [remoteExtension.extensionId]); }), new Action('doNotShowAgain', localize('action.doNotShowAgain', "Do not show again"), undefined, true, () => { this.storageService.store(REMOTE_TUNNEL_EXTENSION_RECOMMENDED_KEY, true, StorageScope.APPLICATION, StorageTarget.USER); }), ] } }); return true; }; if (await shouldRecommend()) { const storageListener = this.storageService.onDidChangeValue(async e => { if (e.key === REMOTE_TUNNEL_USED_STORAGE_KEY) { const success = await recommed(); if (success) { storageListener.dispose(); } } }); } } private async initialize(): Promise<void> { const status = await this.remoteTunnelService.getTunnelStatus(); if (status.type === 'connected') { this.connectionInfo = status.info; this.connectionStateContext.set('connected'); return; } await this.extensionService.whenInstalledExtensionsRegistered(); await this.startTunnel(true); } private async startTunnel(silent: boolean): Promise<ConnectionInfo | undefined> { if (this.#authenticationSessionId !== undefined && this.connectionInfo) { return this.connectionInfo; } const authenticationSession = await this.getAuthenticationSession(silent); if (authenticationSession === undefined) { return undefined; } return await this.progressService.withProgress( { location: silent ? ProgressLocation.Window : ProgressLocation.Notification, title: localize({ key: 'progress.title', comment: ['Only translate \'Starting remote tunnel\', do not change the format of the rest (markdown link format)'] }, "[Starting remote tunnel](command:{0})", RemoteTunnelCommandIds.showLog), }, (progress: IProgress<IProgressStep>) => { return new Promise<ConnectionInfo | undefined>((s, e) => { let completed = false; const listener = this.remoteTunnelService.onDidChangeTunnelStatus(status => { switch (status.type) { case 'connecting': if (status.progress) { progress.report({ message: status.progress }); } break; case 'connected': listener.dispose(); completed = true; s(status.info); break; case 'disconnected': listener.dispose(); completed = true; s(undefined); break; } }); const token = authenticationSession.session.idToken ?? authenticationSession.session.accessToken; const account: IRemoteTunnelAccount = { token, providerId: authenticationSession.providerId, accountLabel: authenticationSession.session.account.label }; this.remoteTunnelService.updateAccount(account).then(status => { if (!completed && (status.type === 'connected') || status.type === 'disconnected') { listener.dispose(); s(status.type === 'connected' ? status.info : undefined); } }); }); } ); } private async getAuthenticationSession(silent: boolean): Promise<ExistingSessionItem | undefined> { // If the user signed in previously and the session is still available, reuse that without prompting the user again if (this.existingSessionId) { this.logger.info(`Searching for existing authentication session with ID ${this.existingSessionId}`); const existingSession = await this.getExistingSession(); if (existingSession) { this.logger.info(`Found existing authentication session with ID ${existingSession.session.id}`); return existingSession; } else { //this._didSignOut.fire(); } } // If we aren't supposed to prompt the user because // we're in a silent flow, just return here if (silent) { return; } // Ask the user to pick a preferred account const authenticationSession = await this.getAccountPreference(); if (authenticationSession !== undefined) { this.existingSessionId = authenticationSession.session.id; return authenticationSession; } return undefined; } private async getAccountPreference(): Promise<ExistingSessionItem | undefined> { const sessions = await this.getAllSessions(); if (sessions.length === 1) { return sessions[0]; } const quickpick = this.quickInputService.createQuickPick<ExistingSessionItem | AuthenticationProviderOption | IQuickPickItem>(); quickpick.ok = false; quickpick.placeholder = localize('accountPreference.placeholder', "Sign in to an account to enable remote access"); quickpick.ignoreFocusOut = true; quickpick.items = await this.createQuickpickItems(sessions); return new Promise((resolve, reject) => { quickpick.onDidHide((e) => { resolve(undefined); quickpick.dispose(); }); quickpick.onDidAccept(async (e) => { const selection = quickpick.selectedItems[0]; if ('provider' in selection) { const session = await this.authenticationService.createSession(selection.provider.id, selection.provider.scopes); resolve(this.createExistingSessionItem(session, selection.provider.id)); } else if ('session' in selection) { resolve(selection); } else { resolve(undefined); } quickpick.hide(); }); quickpick.show(); }); } private createExistingSessionItem(session: AuthenticationSession, providerId: string): ExistingSessionItem { return { label: session.account.label, description: this.authenticationService.getLabel(providerId), session, providerId }; } private async createQuickpickItems(sessions: ExistingSessionItem[]): Promise<(ExistingSessionItem | AuthenticationProviderOption | IQuickPickSeparator | IQuickPickItem & { canceledAuthentication: boolean })[]> { const options: (ExistingSessionItem | AuthenticationProviderOption | IQuickPickSeparator | IQuickPickItem & { canceledAuthentication: boolean })[] = []; options.push({ type: 'separator', label: localize('signed in', "Signed In") }); options.push(...sessions); options.push({ type: 'separator', label: localize('others', "Others") }); for (const authenticationProvider of (await this.getAuthenticationProviders())) { const signedInForProvider = sessions.some(account => account.providerId === authenticationProvider.id); if (!signedInForProvider || this.authenticationService.supportsMultipleAccounts(authenticationProvider.id)) { const providerName = this.authenticationService.getLabel(authenticationProvider.id); options.push({ label: localize({ key: 'sign in using account', comment: ['{0} will be a auth provider (e.g. Github)'] }, "Sign in with {0}", providerName), provider: authenticationProvider }); } } return options; } private async getExistingSession(): Promise<ExistingSessionItem | undefined> { const accounts = await this.getAllSessions(); return accounts.find((account) => account.session.id === this.existingSessionId); } private async onDidChangeStorage(e: IStorageValueChangeEvent): Promise<void> { if (e.key === SESSION_ID_STORAGE_KEY && e.scope === StorageScope.APPLICATION) { const newSessionId = this.existingSessionId; const previousSessionId = this.#authenticationSessionId; if (previousSessionId !== newSessionId) { this.logger.trace(`Resetting authentication state because authentication session ID preference changed from ${previousSessionId} to ${newSessionId}.`); this.#authenticationSessionId = undefined; } } } private clearAuthenticationPreference(): void { this.#authenticationSessionId = undefined; this.existingSessionId = undefined; this.connectionStateContext.set('disconnected'); } private onDidChangeSessions(e: AuthenticationSessionsChangeEvent): void { if (this.#authenticationSessionId && e.removed.find(session => session.id === this.#authenticationSessionId)) { this.clearAuthenticationPreference(); } } /** * Returns all authentication sessions available from {@link getAuthenticationProviders}. */ private async getAllSessions(): Promise<ExistingSessionItem[]> { const authenticationProviders = await this.getAuthenticationProviders(); const accounts = new Map<string, ExistingSessionItem>(); let currentSession: ExistingSessionItem | undefined; for (const provider of authenticationProviders) { const sessions = await this.authenticationService.getSessions(provider.id, provider.scopes); for (const session of sessions) { const item = this.createExistingSessionItem(session, provider.id); accounts.set(item.session.account.id, item); if (this.existingSessionId === session.id) { currentSession = item; } } } if (currentSession !== undefined) { accounts.set(currentSession.session.account.id, currentSession); } return [...accounts.values()]; } /** * Returns all authentication providers which can be used to authenticate * to the remote storage service, based on product.json configuration * and registered authentication providers. */ private async getAuthenticationProviders(): Promise<IAuthenticationProvider[]> { // Get the list of authentication providers configured in product.json const authenticationProviders = this.serverConfiguration.authenticationProviders; const configuredAuthenticationProviders = Object.keys(authenticationProviders).reduce<IAuthenticationProvider[]>((result, id) => { result.push({ id, scopes: authenticationProviders[id].scopes }); return result; }, []); // Filter out anything that isn't currently available through the authenticationService const availableAuthenticationProviders = this.authenticationService.declaredProviders; return configuredAuthenticationProviders.filter(({ id }) => availableAuthenticationProviders.some(provider => provider.id === id)); } private registerCommands() { const that = this; this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.turnOn, title: RemoteTunnelCommandLabels.turnOn, category: REMOTE_TUNNEL_CATEGORY, precondition: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'disconnected'), menu: [{ id: MenuId.CommandPalette, }, { id: MenuId.AccountsContext, group: '2_remoteTunnel', when: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'disconnected'), }] }); } async run(accessor: ServicesAccessor) { const notificationService = accessor.get(INotificationService); const clipboardService = accessor.get(IClipboardService); const commandService = accessor.get(ICommandService); const storageService = accessor.get(IStorageService); const dialogService = accessor.get(IDialogService); const didNotifyPreview = storageService.getBoolean(REMOTE_TUNNEL_PROMPTED_PREVIEW_STORAGE_KEY, StorageScope.APPLICATION, false); if (!didNotifyPreview) { const { confirmed } = await dialogService.confirm({ message: localize('tunnel.preview', 'Remote Tunnels is currently in preview. Please report any problems using the "Help: Report Issue" command.'), primaryButton: localize({ key: 'enable', comment: ['&& denotes a mnemonic'] }, '&&Enable') }); if (!confirmed) { return; } storageService.store(REMOTE_TUNNEL_PROMPTED_PREVIEW_STORAGE_KEY, true, StorageScope.APPLICATION, StorageTarget.USER); } const connectionInfo = await that.startTunnel(false); if (connectionInfo) { const linkToOpen = that.getLinkToOpen(connectionInfo); const remoteExtension = that.serverConfiguration.extension; const linkToOpenForMarkdown = linkToOpen.toString(false).replace(/\)/g, '%29'); await notificationService.notify({ severity: Severity.Info, message: localize( { key: 'progress.turnOn.final', comment: ['{0} will be the tunnel name, {1} will the link address to the web UI, {6} an extension name, {7} a link to the extension documentation. [label](command:commandId) is a markdown link. Only translate the label, do not modify the format'] }, "You can now access this machine anywhere via the secure tunnel [{0}](command:{4}). To connect via a different machine, use the generated [{1}]({2}) link or use the [{6}]({7}) extension in the desktop or web. You can [configure](command:{3}) or [turn off](command:{5}) this access via the VS Code Accounts menu.", connectionInfo.hostName, connectionInfo.domain, linkToOpenForMarkdown, RemoteTunnelCommandIds.manage, RemoteTunnelCommandIds.configure, RemoteTunnelCommandIds.turnOff, remoteExtension.friendlyName, 'https://code.visualstudio.com/docs/remote/tunnels' ), actions: { primary: [ new Action('copyToClipboard', localize('action.copyToClipboard', "Copy Browser Link to Clipboard"), undefined, true, () => clipboardService.writeText(linkToOpen.toString(true))), new Action('showExtension', localize('action.showExtension', "Show Extension"), undefined, true, () => { return commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', [remoteExtension.extensionId]); }) ] } }); const usedOnHostMessage: UsedOnHostMessage = { hostName: connectionInfo.hostName, timeStamp: new Date().getTime() }; storageService.store(REMOTE_TUNNEL_USED_STORAGE_KEY, JSON.stringify(usedOnHostMessage), StorageScope.APPLICATION, StorageTarget.USER); } else { await notificationService.notify({ severity: Severity.Info, message: localize('progress.turnOn.failed', "Unable to turn on the remote tunnel access. Check the Remote Tunnel Service log for details."), }); await commandService.executeCommand(RemoteTunnelCommandIds.showLog); } } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.manage, title: localize('remoteTunnel.actions.manage.on.v2', 'Remote Tunnel Access is On'), category: REMOTE_TUNNEL_CATEGORY, menu: [{ id: MenuId.AccountsContext, group: '2_remoteTunnel', when: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'connected'), }] }); } async run() { that.showManageOptions(); } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.connecting, title: localize('remoteTunnel.actions.manage.connecting', 'Remote Tunnel Access is Connecting'), category: REMOTE_TUNNEL_CATEGORY, menu: [{ id: MenuId.AccountsContext, group: '2_remoteTunnel', when: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'connecting'), }] }); } async run() { that.showManageOptions(); } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.turnOff, title: RemoteTunnelCommandLabels.turnOff, category: REMOTE_TUNNEL_CATEGORY, precondition: ContextKeyExpr.notEquals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'disconnected'), menu: [{ id: MenuId.CommandPalette, when: ContextKeyExpr.notEquals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, ''), }] }); } async run() { const { confirmed } = await that.dialogService.confirm({ message: localize('remoteTunnel.turnOff.confirm', 'Do you want to turn off Remote Tunnel Access?') }); if (confirmed) { that.clearAuthenticationPreference(); that.remoteTunnelService.updateAccount(undefined); } } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.showLog, title: RemoteTunnelCommandLabels.showLog, category: REMOTE_TUNNEL_CATEGORY, menu: [{ id: MenuId.CommandPalette, when: ContextKeyExpr.notEquals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, ''), }] }); } async run(accessor: ServicesAccessor) { const outputService = accessor.get(IOutputService); outputService.showChannel(LOG_ID); } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.configure, title: RemoteTunnelCommandLabels.configure, category: REMOTE_TUNNEL_CATEGORY, menu: [{ id: MenuId.CommandPalette, when: ContextKeyExpr.notEquals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, ''), }] }); } async run(accessor: ServicesAccessor) { const preferencesService = accessor.get(IPreferencesService); preferencesService.openSettings({ query: CONFIGURATION_KEY_PREFIX }); } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.copyToClipboard, title: RemoteTunnelCommandLabels.copyToClipboard, category: REMOTE_TUNNEL_CATEGORY, precondition: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'connected'), menu: [{ id: MenuId.CommandPalette, when: ContextKeyExpr.equals(REMOTE_TUNNEL_CONNECTION_STATE_KEY, 'connected'), }] }); } async run(accessor: ServicesAccessor) { const clipboardService = accessor.get(IClipboardService); if (that.connectionInfo) { const linkToOpen = that.getLinkToOpen(that.connectionInfo); clipboardService.writeText(linkToOpen.toString(true)); } } })); this._register(registerAction2(class extends Action2 { constructor() { super({ id: RemoteTunnelCommandIds.learnMore, title: RemoteTunnelCommandLabels.learnMore, category: REMOTE_TUNNEL_CATEGORY, menu: [] }); } async run(accessor: ServicesAccessor) { const openerService = accessor.get(IOpenerService); await openerService.open('https://aka.ms/vscode-server-doc'); } })); } private getLinkToOpen(connectionInfo: ConnectionInfo): URI { const workspace = this.workspaceContextService.getWorkspace(); const folders = workspace.folders; let resource; if (folders.length === 1) { resource = folders[0].uri; } else if (workspace.configuration) { resource = workspace.configuration; } const link = URI.parse(connectionInfo.link); if (resource?.scheme === Schemas.file) { return joinPath(link, resource.path); } return joinPath(link, this.environmentService.userHome.path); } private async showManageOptions() { const account = await this.getExistingSession(); return new Promise<void>((c, e) => { const disposables = new DisposableStore(); const quickPick = this.quickInputService.createQuickPick(); quickPick.placeholder = localize('manage.placeholder', 'Select a command to invoke'); disposables.add(quickPick); const items: Array<QuickPickItem> = []; items.push({ id: RemoteTunnelCommandIds.learnMore, label: RemoteTunnelCommandLabels.learnMore }); if (this.connectionInfo && account) { quickPick.title = localize( { key: 'manage.title.on', comment: ['{0} will be a user account name, {1} the provider name (e.g. Github), {2} is the tunnel name'] }, 'Remote Machine Access enabled for {0}({1}) as {2}', account.label, account.description, this.connectionInfo.hostName); items.push({ id: RemoteTunnelCommandIds.copyToClipboard, label: RemoteTunnelCommandLabels.copyToClipboard, description: this.connectionInfo.domain }); } else { quickPick.title = localize('manage.title.off', 'Remote Machine Access not enabled'); } items.push({ id: RemoteTunnelCommandIds.showLog, label: localize('manage.showLog', 'Show Log') }); items.push({ type: 'separator' }); items.push({ id: RemoteTunnelCommandIds.configure, label: localize('manage.machineName', 'Change Host Name'), description: this.connectionInfo?.hostName }); items.push({ id: RemoteTunnelCommandIds.turnOff, label: RemoteTunnelCommandLabels.turnOff, description: account ? `${account.label} (${account.description})` : undefined }); quickPick.items = items; disposables.add(quickPick.onDidAccept(() => { if (quickPick.selectedItems[0] && quickPick.selectedItems[0].id) { this.commandService.executeCommand(quickPick.selectedItems[0].id); } quickPick.hide(); })); disposables.add(quickPick.onDidHide(() => { disposables.dispose(); c(); })); quickPick.show(); }); } } const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(RemoteTunnelWorkbenchContribution, LifecyclePhase.Restored); Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({ type: 'object', properties: { [CONFIGURATION_KEY_HOST_NAME]: { description: localize('remoteTunnelAccess.machineName', "The name under which the remote tunnel access is registered. If not set, the host name is used."), type: 'string', scope: ConfigurationScope.MACHINE, pattern: '^(\\w[\\w-]*)?$', patternErrorMessage: localize('remoteTunnelAccess.machineNameRegex', "The name must only consist of letters, numbers, underscore and dash. It must not start with a dash."), maxLength: 20, default: '' }, [CONFIGURATION_KEY_PREVENT_SLEEP]: { description: localize('remoteTunnelAccess.preventSleep', "Prevent the computer from sleeping when remote tunnel access is turned on."), type: 'boolean', scope: ConfigurationScope.MACHINE, default: false, } } });
src/vs/workbench/contrib/remoteTunnel/electron-sandbox/remoteTunnel.contribution.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.099269337952137, 0.001637970912270248, 0.0001648153702262789, 0.00017136814130935818, 0.011094084940850735 ]
{ "id": 2, "code_window": [ "\tprivate readonly _domNode: HTMLElement;\n", "\tprivate readonly pickedColorNode: HTMLElement;\n", "\tprivate backgroundColor: Color;\n", "\n", "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) {\n", "\t\tsuper();\n", "\n", "\t\tthis._domNode = $('.colorpicker-header');\n", "\t\tdom.append(container, this._domNode);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService, private showingStandaloneColorPicker: boolean = false) {\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // FORKED FROM https://github.com/eslint/eslint/blob/b23ad0d789a909baf8d7c41a35bc53df932eaf30/lib/rules/no-unused-expressions.js // and added support for `OptionalCallExpression`, see https://github.com/facebook/create-react-app/issues/8107 and https://github.com/eslint/eslint/issues/12642 /** * @fileoverview Flag expressions in statement position that do not side effect * @author Michael Ficarra */ import * as eslint from 'eslint'; import { TSESTree } from '@typescript-eslint/experimental-utils'; import * as ESTree from 'estree'; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: 'suggestion', docs: { description: 'disallow unused expressions', category: 'Best Practices', recommended: false, url: 'https://eslint.org/docs/rules/no-unused-expressions' }, schema: [ { type: 'object', properties: { allowShortCircuit: { type: 'boolean', default: false }, allowTernary: { type: 'boolean', default: false }, allowTaggedTemplates: { type: 'boolean', default: false } }, additionalProperties: false } ] }, create(context: eslint.Rule.RuleContext) { const config = context.options[0] || {}, allowShortCircuit = config.allowShortCircuit || false, allowTernary = config.allowTernary || false, allowTaggedTemplates = config.allowTaggedTemplates || false; // eslint-disable-next-line jsdoc/require-description /** * @param node any node * @returns whether the given node structurally represents a directive */ function looksLikeDirective(node: TSESTree.Node): boolean { return node.type === 'ExpressionStatement' && node.expression.type === 'Literal' && typeof node.expression.value === 'string'; } // eslint-disable-next-line jsdoc/require-description /** * @param predicate ([a] -> Boolean) the function used to make the determination * @param list the input list * @returns the leading sequence of members in the given list that pass the given predicate */ function takeWhile<T>(predicate: (item: T) => boolean, list: T[]): T[] { for (let i = 0; i < list.length; ++i) { if (!predicate(list[i])) { return list.slice(0, i); } } return list.slice(); } // eslint-disable-next-line jsdoc/require-description /** * @param node a Program or BlockStatement node * @returns the leading sequence of directive nodes in the given node's body */ function directives(node: TSESTree.Program | TSESTree.BlockStatement): TSESTree.Node[] { return takeWhile(looksLikeDirective, node.body); } // eslint-disable-next-line jsdoc/require-description /** * @param node any node * @param ancestors the given node's ancestors * @returns whether the given node is considered a directive in its current position */ function isDirective(node: TSESTree.Node, ancestors: TSESTree.Node[]): boolean { const parent = ancestors[ancestors.length - 1], grandparent = ancestors[ancestors.length - 2]; return (parent.type === 'Program' || parent.type === 'BlockStatement' && (/Function/u.test(grandparent.type))) && directives(parent).indexOf(node) >= 0; } /** * Determines whether or not a given node is a valid expression. Recurses on short circuit eval and ternary nodes if enabled by flags. * @param node any node * @returns whether the given node is a valid expression */ function isValidExpression(node: TSESTree.Node): boolean { if (allowTernary) { // Recursive check for ternary and logical expressions if (node.type === 'ConditionalExpression') { return isValidExpression(node.consequent) && isValidExpression(node.alternate); } } if (allowShortCircuit) { if (node.type === 'LogicalExpression') { return isValidExpression(node.right); } } if (allowTaggedTemplates && node.type === 'TaggedTemplateExpression') { return true; } if (node.type === 'ExpressionStatement') { return isValidExpression(node.expression); } return /^(?:Assignment|OptionalCall|Call|New|Update|Yield|Await|Chain)Expression$/u.test(node.type) || (node.type === 'UnaryExpression' && ['delete', 'void'].indexOf(node.operator) >= 0); } return { ExpressionStatement(node: TSESTree.ExpressionStatement) { if (!isValidExpression(node.expression) && !isDirective(node, <TSESTree.Node[]>context.getAncestors())) { context.report({ node: <ESTree.Node>node, message: `Expected an assignment or function call and instead saw an expression. ${node.expression}` }); } } }; } };
.eslintplugin/code-no-unused-expressions.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001762974279699847, 0.00017162642325274646, 0.00016430918185506016, 0.00017134833615273237, 0.0000025727324555191444 ]
{ "id": 3, "code_window": [ "\t\tthis.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());\n", "\n", "\t\tthis.onDidChangeColor(this.model.color);\n", "\t}\n", "\n", "\tpublic get domNode(): HTMLElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n", "\t\t}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 56 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.998479425907135, 0.43230655789375305, 0.00016540545038878918, 0.0064756120555102825, 0.48124662041664124 ]
{ "id": 3, "code_window": [ "\t\tthis.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());\n", "\n", "\t\tthis.onDidChangeColor(this.model.color);\n", "\t}\n", "\n", "\tpublic get domNode(): HTMLElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n", "\t\t}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 56 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* eslint-disable local/code-layering, local/code-import-patterns */ // TODO@bpasero remove these once utility process is the only way import { Server as BrowserWindowMessagePortServer } from 'vs/base/parts/ipc/electron-browser/ipc.mp'; import { SharedProcessWorkerService } from 'vs/platform/sharedProcess/electron-browser/sharedProcessWorkerService'; import { ILocalPtyService } from 'vs/platform/terminal/electron-sandbox/terminal'; import { hostname, release } from 'os'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors'; import { combinedDisposable, Disposable, toDisposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { IPCServer, ProxyChannel, StaticRouter } from 'vs/base/parts/ipc/common/ipc'; import { Server as UtilityProcessMessagePortServer, once } from 'vs/base/parts/ipc/node/ipc.mp'; import { CodeCacheCleaner } from 'vs/code/node/sharedProcess/contrib/codeCacheCleaner'; import { LanguagePackCachedDataCleaner } from 'vs/code/node/sharedProcess/contrib/languagePackCachedDataCleaner'; import { LocalizationsUpdater } from 'vs/code/node/sharedProcess/contrib/localizationsUpdater'; import { LogsDataCleaner } from 'vs/code/node/sharedProcess/contrib/logsDataCleaner'; import { UnusedWorkspaceStorageDataCleaner } from 'vs/code/node/sharedProcess/contrib/storageDataCleaner'; import { IChecksumService } from 'vs/platform/checksum/common/checksumService'; import { ChecksumService } from 'vs/platform/checksum/node/checksumService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ConfigurationService } from 'vs/platform/configuration/common/configurationService'; import { IDiagnosticsService } from 'vs/platform/diagnostics/common/diagnostics'; import { DiagnosticsService } from 'vs/platform/diagnostics/node/diagnosticsService'; import { IDownloadService } from 'vs/platform/download/common/download'; import { DownloadService } from 'vs/platform/download/common/downloadService'; import { INativeEnvironmentService } from 'vs/platform/environment/common/environment'; import { SharedProcessEnvironmentService } from 'vs/platform/sharedProcess/node/sharedProcessEnvironmentService'; import { GlobalExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionEnablementService'; import { ExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionGalleryService'; import { IExtensionGalleryService, IExtensionManagementService, IExtensionTipsService, IGlobalExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ExtensionSignatureVerificationService, IExtensionSignatureVerificationService } from 'vs/platform/extensionManagement/node/extensionSignatureVerificationService'; import { ExtensionManagementChannel, ExtensionTipsChannel } from 'vs/platform/extensionManagement/common/extensionManagementIpc'; import { ExtensionManagementService, INativeServerExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService'; import { IExtensionRecommendationNotificationService } from 'vs/platform/extensionRecommendations/common/extensionRecommendations'; import { IFileService } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILanguagePackService } from 'vs/platform/languagePacks/common/languagePacks'; import { NativeLanguagePackService } from 'vs/platform/languagePacks/node/languagePacks'; import { ConsoleLogger, ILoggerService, ILogService } from 'vs/platform/log/common/log'; import { LoggerChannelClient } from 'vs/platform/log/common/logIpc'; import product from 'vs/platform/product/common/product'; import { IProductService } from 'vs/platform/product/common/productService'; import { IRequestService } from 'vs/platform/request/common/request'; import { ISharedProcessConfiguration } from 'vs/platform/sharedProcess/node/sharedProcess'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties'; import { ICustomEndpointTelemetryService, ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryAppenderChannel } from 'vs/platform/telemetry/common/telemetryIpc'; import { TelemetryLogAppender } from 'vs/platform/telemetry/common/telemetryLogAppender'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { supportsTelemetry, ITelemetryAppender, NullAppender, NullTelemetryService, getPiiPathsFromEnvironment, isInternalTelemetry } from 'vs/platform/telemetry/common/telemetryUtils'; import { CustomEndpointTelemetryService } from 'vs/platform/telemetry/node/customEndpointTelemetryService'; import { LocalReconnectConstants, TerminalIpcChannels, TerminalSettingId } from 'vs/platform/terminal/common/terminal'; import { PtyHostService } from 'vs/platform/terminal/node/ptyHostService'; import { ExtensionStorageService, IExtensionStorageService } from 'vs/platform/extensionManagement/common/extensionStorage'; import { IgnoredExtensionsManagementService, IIgnoredExtensionsManagementService } from 'vs/platform/userDataSync/common/ignoredExtensions'; import { IUserDataSyncBackupStoreService, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncService, IUserDataSyncStoreManagementService, IUserDataSyncStoreService, IUserDataSyncUtilService, registerConfiguration as registerUserDataSyncConfiguration, IUserDataSyncResourceProviderService } from 'vs/platform/userDataSync/common/userDataSync'; import { IUserDataSyncAccountService, UserDataSyncAccountService } from 'vs/platform/userDataSync/common/userDataSyncAccount'; import { UserDataSyncBackupStoreService } from 'vs/platform/userDataSync/common/userDataSyncBackupStoreService'; import { UserDataAutoSyncChannel, UserDataSyncAccountServiceChannel, UserDataSyncMachinesServiceChannel, UserDataSyncStoreManagementServiceChannel, UserDataSyncUtilServiceClient } from 'vs/platform/userDataSync/common/userDataSyncIpc'; import { UserDataSyncLogService } from 'vs/platform/userDataSync/common/userDataSyncLog'; import { IUserDataSyncMachinesService, UserDataSyncMachinesService } from 'vs/platform/userDataSync/common/userDataSyncMachines'; import { UserDataSyncEnablementService } from 'vs/platform/userDataSync/common/userDataSyncEnablementService'; import { UserDataSyncService } from 'vs/platform/userDataSync/common/userDataSyncService'; import { UserDataSyncChannel } from 'vs/platform/userDataSync/common/userDataSyncServiceIpc'; import { UserDataSyncStoreManagementService, UserDataSyncStoreService } from 'vs/platform/userDataSync/common/userDataSyncStoreService'; import { IUserDataProfileStorageService } from 'vs/platform/userDataProfile/common/userDataProfileStorageService'; import { NativeUserDataProfileStorageService } from 'vs/platform/userDataProfile/node/userDataProfileStorageService'; import { ActiveWindowManager } from 'vs/platform/windows/node/windowTracker'; import { ISignService } from 'vs/platform/sign/common/sign'; import { SignService } from 'vs/platform/sign/node/signService'; import { ISharedTunnelsService } from 'vs/platform/tunnel/common/tunnel'; import { SharedTunnelsService } from 'vs/platform/tunnel/node/tunnelService'; import { ipcSharedProcessTunnelChannelName, ISharedProcessTunnelService } from 'vs/platform/remote/common/sharedProcessTunnelService'; import { SharedProcessTunnelService } from 'vs/platform/tunnel/node/sharedProcessTunnelService'; import { ISharedProcessWorkerService } from 'vs/platform/sharedProcess/common/sharedProcessWorkerService'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { isLinux } from 'vs/base/common/platform'; import { FileUserDataProvider } from 'vs/platform/userData/common/fileUserDataProvider'; import { DiskFileSystemProviderClient, LOCAL_FILE_SYSTEM_CHANNEL_NAME } from 'vs/platform/files/common/diskFileSystemProviderClient'; import { InspectProfilingService as V8InspectProfilingService } from 'vs/platform/profiling/node/profilingService'; import { IV8InspectProfilingService } from 'vs/platform/profiling/common/profiling'; import { IExtensionsScannerService } from 'vs/platform/extensionManagement/common/extensionsScannerService'; import { ExtensionsScannerService } from 'vs/platform/extensionManagement/node/extensionsScannerService'; import { IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { IExtensionsProfileScannerService } from 'vs/platform/extensionManagement/common/extensionsProfileScannerService'; import { PolicyChannelClient } from 'vs/platform/policy/common/policyIpc'; import { IPolicyService, NullPolicyService } from 'vs/platform/policy/common/policy'; import { UserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfileIpc'; import { OneDataSystemAppender } from 'vs/platform/telemetry/node/1dsAppender'; import { UserDataProfilesCleaner } from 'vs/code/node/sharedProcess/contrib/userDataProfilesCleaner'; import { IRemoteTunnelService } from 'vs/platform/remoteTunnel/common/remoteTunnel'; import { UserDataSyncResourceProviderService } from 'vs/platform/userDataSync/common/userDataSyncResourceProvider'; import { ExtensionsContributions } from 'vs/code/node/sharedProcess/contrib/extensions'; import { localize } from 'vs/nls'; import { LogService } from 'vs/platform/log/common/logService'; import { ipcUtilityProcessWorkerChannelName, IUtilityProcessWorkerConfiguration } from 'vs/platform/utilityProcess/common/utilityProcessWorkerService'; import { isUtilityProcess } from 'vs/base/parts/sandbox/node/electronTypes'; import { ISharedProcessLifecycleService, SharedProcessLifecycleService } from 'vs/platform/lifecycle/node/sharedProcessLifecycleService'; import { RemoteTunnelService } from 'vs/platform/remoteTunnel/node/remoteTunnelService'; import { ExtensionsProfileScannerService } from 'vs/platform/extensionManagement/node/extensionsProfileScannerService'; import { RequestChannelClient } from 'vs/platform/request/common/requestIpc'; import { ExtensionRecommendationNotificationServiceChannelClient } from 'vs/platform/extensionRecommendations/common/extensionRecommendationsIpc'; import { INativeHostService } from 'vs/platform/native/common/native'; import { UserDataAutoSyncService } from 'vs/platform/userDataSync/node/userDataAutoSyncService'; import { ExtensionTipsService } from 'vs/platform/extensionManagement/node/extensionTipsService'; import { IMainProcessService, MainProcessService } from 'vs/platform/ipc/common/mainProcessService'; import { RemoteStorageService } from 'vs/platform/storage/common/storageService'; class SharedProcessMain extends Disposable { private readonly server: IPCServer; private sharedProcessWorkerService: ISharedProcessWorkerService | undefined = undefined; private lifecycleService: SharedProcessLifecycleService | undefined = undefined; constructor(private configuration: ISharedProcessConfiguration, private ipcRenderer?: typeof import('electron').ipcRenderer) { super(); if (isUtilityProcess(process)) { this.server = this._register(new UtilityProcessMessagePortServer()); } else { this.server = this._register(new BrowserWindowMessagePortServer()); } this.registerListeners(); } private registerListeners(): void { // Shared process lifecycle let didExit = false; const onExit = () => { if (!didExit) { didExit = true; this.lifecycleService?.fireOnWillShutdown(); this.dispose(); } }; process.once('exit', onExit); if (isUtilityProcess(process)) { once(process.parentPort, 'vscode:electron-main->shared-process=exit', onExit); } else { this.ipcRenderer!.once('vscode:electron-main->shared-process=exit', onExit); } if (!isUtilityProcess(process)) { // Shared process worker lifecycle // // We dispose the listener when the shared process is // disposed to avoid disposing workers when the entire // application is shutting down anyways. const eventName = 'vscode:electron-main->shared-process=disposeWorker'; const onDisposeWorker = (event: unknown, configuration: IUtilityProcessWorkerConfiguration) => { this.onDisposeWorker(configuration); }; this.ipcRenderer!.on(eventName, onDisposeWorker); this._register(toDisposable(() => this.ipcRenderer!.removeListener(eventName, onDisposeWorker))); } } private onDisposeWorker(configuration: IUtilityProcessWorkerConfiguration): void { this.sharedProcessWorkerService?.disposeWorker(configuration); } async init(): Promise<void> { // Services const instantiationService = await this.initServices(); // Config registerUserDataSyncConfiguration(); instantiationService.invokeFunction(accessor => { const logService = accessor.get(ILogService); // Log info logService.trace('sharedProcess configuration', JSON.stringify(this.configuration)); // Channels this.initChannels(accessor); // Error handler this.registerErrorHandler(logService); }); // Instantiate Contributions this._register(combinedDisposable( instantiationService.createInstance(CodeCacheCleaner, this.configuration.codeCachePath), instantiationService.createInstance(LanguagePackCachedDataCleaner), instantiationService.createInstance(UnusedWorkspaceStorageDataCleaner), instantiationService.createInstance(LogsDataCleaner), instantiationService.createInstance(LocalizationsUpdater), instantiationService.createInstance(ExtensionsContributions), instantiationService.createInstance(UserDataProfilesCleaner) )); } private async initServices(): Promise<IInstantiationService> { const services = new ServiceCollection(); // Product const productService = { _serviceBrand: undefined, ...product }; services.set(IProductService, productService); // Main Process const mainRouter = new StaticRouter(ctx => ctx === 'main'); const mainProcessService = new MainProcessService(this.server, mainRouter); services.set(IMainProcessService, mainProcessService); // Policies const policyService = this.configuration.policiesData ? new PolicyChannelClient(this.configuration.policiesData, mainProcessService.getChannel('policy')) : new NullPolicyService(); services.set(IPolicyService, policyService); // Environment const environmentService = new SharedProcessEnvironmentService(this.configuration.args, productService); services.set(INativeEnvironmentService, environmentService); // Logger const loggerService = new LoggerChannelClient(undefined, this.configuration.logLevel, environmentService.logsHome, this.configuration.loggers.map(loggerResource => ({ ...loggerResource, resource: URI.revive(loggerResource.resource) })), mainProcessService.getChannel('logger')); services.set(ILoggerService, loggerService); // Log const logger = this._register(loggerService.createLogger('sharedprocess', { name: localize('sharedLog', "Shared") })); const consoleLogger = this._register(new ConsoleLogger(logger.getLevel())); const logService = this._register(new LogService(logger, [consoleLogger])); services.set(ILogService, logService); // Lifecycle this.lifecycleService = this._register(new SharedProcessLifecycleService(logService)); services.set(ISharedProcessLifecycleService, this.lifecycleService); // Worker this.sharedProcessWorkerService = new SharedProcessWorkerService(logService); services.set(ISharedProcessWorkerService, this.sharedProcessWorkerService); // Files const fileService = this._register(new FileService(logService)); services.set(IFileService, fileService); const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService)); fileService.registerProvider(Schemas.file, diskFileSystemProvider); const userDataFileSystemProvider = this._register(new FileUserDataProvider( Schemas.file, // Specifically for user data, use the disk file system provider // from the main process to enable atomic read/write operations. // Since user data can change very frequently across multiple // processes, we want a single process handling these operations. this._register(new DiskFileSystemProviderClient(mainProcessService.getChannel(LOCAL_FILE_SYSTEM_CHANNEL_NAME), { pathCaseSensitive: isLinux })), Schemas.vscodeUserData, logService )); fileService.registerProvider(Schemas.vscodeUserData, userDataFileSystemProvider); // User Data Profiles const userDataProfilesService = this._register(new UserDataProfilesService(this.configuration.profiles.all, URI.revive(this.configuration.profiles.home).with({ scheme: environmentService.userRoamingDataHome.scheme }), mainProcessService.getChannel('userDataProfiles'))); services.set(IUserDataProfilesService, userDataProfilesService); // Configuration const configurationService = this._register(new ConfigurationService(userDataProfilesService.defaultProfile.settingsResource, fileService, policyService, logService)); services.set(IConfigurationService, configurationService); // Storage (global access only) const storageService = new RemoteStorageService(undefined, { defaultProfile: userDataProfilesService.defaultProfile, currentProfile: userDataProfilesService.defaultProfile }, mainProcessService, environmentService); services.set(IStorageService, storageService); this._register(toDisposable(() => storageService.flush())); // Initialize config & storage in parallel await Promise.all([ configurationService.initialize(), storageService.initialize() ]); // URI Identity const uriIdentityService = new UriIdentityService(fileService); services.set(IUriIdentityService, uriIdentityService); // Request services.set(IRequestService, new RequestChannelClient(mainProcessService.getChannel('request'))); // Checksum services.set(IChecksumService, new SyncDescriptor(ChecksumService, undefined, false /* proxied to other processes */)); // V8 Inspect profiler services.set(IV8InspectProfilingService, new SyncDescriptor(V8InspectProfilingService, undefined, false /* proxied to other processes */)); // Native Host const nativeHostService = ProxyChannel.toService<INativeHostService>(mainProcessService.getChannel('nativeHost'), { context: this.configuration.windowId }); services.set(INativeHostService, nativeHostService); // Download services.set(IDownloadService, new SyncDescriptor(DownloadService, undefined, true)); // Extension recommendations const activeWindowManager = this._register(new ActiveWindowManager(nativeHostService)); const activeWindowRouter = new StaticRouter(ctx => activeWindowManager.getActiveClientId().then(id => ctx === id)); services.set(IExtensionRecommendationNotificationService, new ExtensionRecommendationNotificationServiceChannelClient(this.server.getChannel('extensionRecommendationNotification', activeWindowRouter))); // Telemetry let telemetryService: ITelemetryService; const appenders: ITelemetryAppender[] = []; const internalTelemetry = isInternalTelemetry(productService, configurationService); if (supportsTelemetry(productService, environmentService)) { const logAppender = new TelemetryLogAppender(logService, loggerService, environmentService, productService); appenders.push(logAppender); if (productService.aiConfig?.ariaKey) { const collectorAppender = new OneDataSystemAppender(internalTelemetry, 'monacoworkbench', null, productService.aiConfig.ariaKey); this._register(toDisposable(() => collectorAppender.flush())); // Ensure the 1DS appender is disposed so that it flushes remaining data appenders.push(collectorAppender); } telemetryService = new TelemetryService({ appenders, commonProperties: resolveCommonProperties(release(), hostname(), process.arch, productService.commit, productService.version, this.configuration.machineId, internalTelemetry), sendErrorTelemetry: true, piiPaths: getPiiPathsFromEnvironment(environmentService), }, configurationService, productService); } else { telemetryService = NullTelemetryService; const nullAppender = NullAppender; appenders.push(nullAppender); } this.server.registerChannel('telemetryAppender', new TelemetryAppenderChannel(appenders)); services.set(ITelemetryService, telemetryService); // Custom Endpoint Telemetry const customEndpointTelemetryService = new CustomEndpointTelemetryService(configurationService, telemetryService, logService, loggerService, environmentService, productService); services.set(ICustomEndpointTelemetryService, customEndpointTelemetryService); // Extension Management services.set(IExtensionsProfileScannerService, new SyncDescriptor(ExtensionsProfileScannerService, undefined, true)); services.set(IExtensionsScannerService, new SyncDescriptor(ExtensionsScannerService, undefined, true)); services.set(IExtensionSignatureVerificationService, new SyncDescriptor(ExtensionSignatureVerificationService, undefined, true)); services.set(INativeServerExtensionManagementService, new SyncDescriptor(ExtensionManagementService, undefined, true)); // Extension Gallery services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService, undefined, true)); // Extension Tips services.set(IExtensionTipsService, new SyncDescriptor(ExtensionTipsService, undefined, false /* Eagerly scans and computes exe based recommendations */)); // Localizations services.set(ILanguagePackService, new SyncDescriptor(NativeLanguagePackService, undefined, false /* proxied to other processes */)); // Diagnostics services.set(IDiagnosticsService, new SyncDescriptor(DiagnosticsService, undefined, false /* proxied to other processes */)); // Settings Sync services.set(IUserDataSyncAccountService, new SyncDescriptor(UserDataSyncAccountService, undefined, true)); services.set(IUserDataSyncLogService, new SyncDescriptor(UserDataSyncLogService, undefined, true)); services.set(IUserDataSyncUtilService, new UserDataSyncUtilServiceClient(this.server.getChannel('userDataSyncUtil', client => client.ctx !== 'main'))); services.set(IGlobalExtensionEnablementService, new SyncDescriptor(GlobalExtensionEnablementService, undefined, false /* Eagerly resets installed extensions */)); services.set(IIgnoredExtensionsManagementService, new SyncDescriptor(IgnoredExtensionsManagementService, undefined, true)); services.set(IExtensionStorageService, new SyncDescriptor(ExtensionStorageService)); services.set(IUserDataSyncStoreManagementService, new SyncDescriptor(UserDataSyncStoreManagementService, undefined, true)); services.set(IUserDataSyncStoreService, new SyncDescriptor(UserDataSyncStoreService, undefined, true)); services.set(IUserDataSyncMachinesService, new SyncDescriptor(UserDataSyncMachinesService, undefined, true)); services.set(IUserDataSyncBackupStoreService, new SyncDescriptor(UserDataSyncBackupStoreService, undefined, false /* Eagerly cleans up old backups */)); services.set(IUserDataSyncEnablementService, new SyncDescriptor(UserDataSyncEnablementService, undefined, true)); services.set(IUserDataSyncService, new SyncDescriptor(UserDataSyncService, undefined, false /* Initializes the Sync State */)); services.set(IUserDataProfileStorageService, new SyncDescriptor(NativeUserDataProfileStorageService, undefined, true)); services.set(IUserDataSyncResourceProviderService, new SyncDescriptor(UserDataSyncResourceProviderService, undefined, true)); // Terminal const ptyHostService = new PtyHostService({ graceTime: LocalReconnectConstants.GraceTime, shortGraceTime: LocalReconnectConstants.ShortGraceTime, scrollback: configurationService.getValue<number>(TerminalSettingId.PersistentSessionScrollback) ?? 100 }, false, configurationService, environmentService, logService, loggerService ); ptyHostService.initialize(); services.set(ILocalPtyService, this._register(ptyHostService)); // Signing services.set(ISignService, new SyncDescriptor(SignService, undefined, false /* proxied to other processes */)); // Tunnel services.set(ISharedTunnelsService, new SyncDescriptor(SharedTunnelsService)); services.set(ISharedProcessTunnelService, new SyncDescriptor(SharedProcessTunnelService)); // Remote Tunnel services.set(IRemoteTunnelService, new SyncDescriptor(RemoteTunnelService)); return new InstantiationService(services); } private initChannels(accessor: ServicesAccessor): void { // Extensions Management const channel = new ExtensionManagementChannel(accessor.get(IExtensionManagementService), () => null); this.server.registerChannel('extensions', channel); // Language Packs const languagePacksChannel = ProxyChannel.fromService(accessor.get(ILanguagePackService)); this.server.registerChannel('languagePacks', languagePacksChannel); // Diagnostics const diagnosticsChannel = ProxyChannel.fromService(accessor.get(IDiagnosticsService)); this.server.registerChannel('diagnostics', diagnosticsChannel); // Extension Tips const extensionTipsChannel = new ExtensionTipsChannel(accessor.get(IExtensionTipsService)); this.server.registerChannel('extensionTipsService', extensionTipsChannel); // Checksum const checksumChannel = ProxyChannel.fromService(accessor.get(IChecksumService)); this.server.registerChannel('checksum', checksumChannel); // Profiling const profilingChannel = ProxyChannel.fromService(accessor.get(IV8InspectProfilingService)); this.server.registerChannel('v8InspectProfiling', profilingChannel); // Settings Sync const userDataSyncMachineChannel = new UserDataSyncMachinesServiceChannel(accessor.get(IUserDataSyncMachinesService)); this.server.registerChannel('userDataSyncMachines', userDataSyncMachineChannel); // Custom Endpoint Telemetry const customEndpointTelemetryChannel = ProxyChannel.fromService(accessor.get(ICustomEndpointTelemetryService)); this.server.registerChannel('customEndpointTelemetry', customEndpointTelemetryChannel); const userDataSyncAccountChannel = new UserDataSyncAccountServiceChannel(accessor.get(IUserDataSyncAccountService)); this.server.registerChannel('userDataSyncAccount', userDataSyncAccountChannel); const userDataSyncStoreManagementChannel = new UserDataSyncStoreManagementServiceChannel(accessor.get(IUserDataSyncStoreManagementService)); this.server.registerChannel('userDataSyncStoreManagement', userDataSyncStoreManagementChannel); const userDataSyncChannel = new UserDataSyncChannel(accessor.get(IUserDataSyncService), accessor.get(IUserDataProfilesService), accessor.get(ILogService)); this.server.registerChannel('userDataSync', userDataSyncChannel); const userDataAutoSync = this._register(accessor.get(IInstantiationService).createInstance(UserDataAutoSyncService)); const userDataAutoSyncChannel = new UserDataAutoSyncChannel(userDataAutoSync); this.server.registerChannel('userDataAutoSync', userDataAutoSyncChannel); // Terminal const localPtyService = accessor.get(ILocalPtyService); const localPtyChannel = ProxyChannel.fromService(localPtyService); this.server.registerChannel(TerminalIpcChannels.LocalPty, localPtyChannel); // Tunnel const sharedProcessTunnelChannel = ProxyChannel.fromService(accessor.get(ISharedProcessTunnelService)); this.server.registerChannel(ipcSharedProcessTunnelChannelName, sharedProcessTunnelChannel); // Worker const sharedProcessWorkerChannel = ProxyChannel.fromService(accessor.get(ISharedProcessWorkerService)); this.server.registerChannel(ipcUtilityProcessWorkerChannelName, sharedProcessWorkerChannel); // Remote Tunnel const remoteTunnelChannel = ProxyChannel.fromService(accessor.get(IRemoteTunnelService)); this.server.registerChannel('remoteTunnel', remoteTunnelChannel); } private registerErrorHandler(logService: ILogService): void { // Listen on global error events if (isUtilityProcess(process)) { process.on('uncaughtException', error => onUnexpectedError(error)); process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason)); } else { (globalThis as any).addEventListener('unhandledrejection', (event: any) => { // See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent onUnexpectedError(event.reason); // Prevent the printing of this event to the console event.preventDefault(); }); } // Install handler for unexpected errors setUnexpectedErrorHandler(error => { const message = toErrorMessage(error, true); if (!message) { return; } logService.error(`[uncaught exception in sharedProcess]: ${message}`); }); } } export async function main(configuration: ISharedProcessConfiguration): Promise<void> { // create shared process and signal back to main that we are // ready to accept message ports as client connections let ipcRenderer: typeof import('electron').ipcRenderer | undefined = undefined; if (!isUtilityProcess(process)) { ipcRenderer = (await import('electron')).ipcRenderer; } const sharedProcess = new SharedProcessMain(configuration, ipcRenderer); if (isUtilityProcess(process)) { process.parentPort.postMessage('vscode:shared-process->electron-main=ipc-ready'); } else { ipcRenderer!.send('vscode:shared-process->electron-main=ipc-ready'); } // await initialization and signal this back to electron-main await sharedProcess.init(); if (isUtilityProcess(process)) { process.parentPort.postMessage('vscode:shared-process->electron-main=init-done'); } else { ipcRenderer!.send('vscode:shared-process->electron-main=init-done'); } } if (isUtilityProcess(process)) { process.parentPort.once('message', (e: Electron.MessageEvent) => { main(e.data as ISharedProcessConfiguration); }); }
src/vs/code/node/sharedProcess/sharedProcessMain.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017572245269548148, 0.000171354811755009, 0.00016260657866951078, 0.00017217625281773508, 0.0000030997327939985553 ]
{ "id": 3, "code_window": [ "\t\tthis.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());\n", "\n", "\t\tthis.onDidChangeColor(this.model.color);\n", "\t}\n", "\n", "\tpublic get domNode(): HTMLElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n", "\t\t}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 56 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { EXTENSION_IDENTIFIER_PATTERN } from 'vs/platform/extensionManagement/common/extensionManagement'; export const ExtensionsConfigurationSchemaId = 'vscode://schemas/extensions'; export const ExtensionsConfigurationSchema: IJSONSchema = { id: ExtensionsConfigurationSchemaId, allowComments: true, allowTrailingCommas: true, type: 'object', title: localize('app.extensions.json.title', "Extensions"), additionalProperties: false, properties: { recommendations: { type: 'array', description: localize('app.extensions.json.recommendations', "List of extensions which should be recommended for users of this workspace. The identifier of an extension is always '${publisher}.${name}'. For example: 'vscode.csharp'."), items: { type: 'string', pattern: EXTENSION_IDENTIFIER_PATTERN, errorMessage: localize('app.extension.identifier.errorMessage', "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'.") }, }, unwantedRecommendations: { type: 'array', description: localize('app.extensions.json.unwantedRecommendations', "List of extensions recommended by VS Code that should not be recommended for users of this workspace. The identifier of an extension is always '${publisher}.${name}'. For example: 'vscode.csharp'."), items: { type: 'string', pattern: EXTENSION_IDENTIFIER_PATTERN, errorMessage: localize('app.extension.identifier.errorMessage', "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'.") }, }, } }; export const ExtensionsConfigurationInitialContent: string = [ '{', '\t// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.', '\t// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp', '', '\t// List of extensions which should be recommended for users of this workspace.', '\t"recommendations": [', '\t\t', '\t],', '\t// List of extensions recommended by VS Code that should not be recommended for users of this workspace.', '\t"unwantedRecommendations": [', '\t\t', '\t]', '}' ].join('\n');
src/vs/workbench/contrib/extensions/common/extensionsFileTemplate.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017535555525682867, 0.00017348374240100384, 0.00016904623771551996, 0.00017478715744800866, 0.0000023559291548735928 ]
{ "id": 3, "code_window": [ "\t\tthis.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());\n", "\n", "\t\tthis.onDidChangeColor(this.model.color);\n", "\t}\n", "\n", "\tpublic get domNode(): HTMLElement {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n", "\t\t}\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 56 }
test/** src/**/*.ts syntaxes/Readme.md tsconfig.json cgmanifest.json
extensions/javascript/.vscodeignore
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017377446056343615, 0.00017377446056343615, 0.00017377446056343615, 0.00017377446056343615, 0 ]
{ "id": 4, "code_window": [ "\t\tthis._register(this._hueStrip.onColorFlushed(this.flushColor, this));\n", "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._insertButton = new InsertButton(this._domNode);\n", "\t\t\tthis._register(this._insertButton);\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 106 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.9979932308197021, 0.028759123757481575, 0.00016366963973268867, 0.0006433326634578407, 0.14736191928386688 ]
{ "id": 4, "code_window": [ "\t\tthis._register(this._hueStrip.onColorFlushed(this.flushColor, this));\n", "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._insertButton = new InsertButton(this._domNode);\n", "\t\t\tthis._register(this._insertButton);\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 106 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { notEqual, strictEqual, throws } from 'assert'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { DecorationAddon } from 'vs/workbench/contrib/terminal/browser/xterm/decorationAddon'; import { TerminalCapabilityStore } from 'vs/platform/terminal/common/capabilities/terminalCapabilityStore'; import { ITerminalCommand } from 'vs/workbench/contrib/terminal/common/terminal'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { IDecoration, IDecorationOptions, Terminal } from 'xterm'; import { TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities'; import { CommandDetectionCapability } from 'vs/platform/terminal/common/capabilities/commandDetectionCapability'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { ContextMenuService } from 'vs/platform/contextview/browser/contextMenuService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { TestLifecycleService } from 'vs/workbench/test/browser/workbenchTestServices'; class TestTerminal extends Terminal { override registerDecoration(decorationOptions: IDecorationOptions): IDecoration | undefined { if (decorationOptions.marker.isDisposed) { return undefined; } const element = document.createElement('div'); return { marker: decorationOptions.marker, element, onDispose: () => { }, isDisposed: false, dispose: () => { }, onRender: (element: HTMLElement) => { return element; } } as unknown as IDecoration; } } suite('DecorationAddon', () => { let decorationAddon: DecorationAddon; let xterm: TestTerminal; setup(() => { const instantiationService = new TestInstantiationService(); const configurationService = new TestConfigurationService({ workbench: { hover: { delay: 5 }, }, terminal: { integrated: { shellIntegration: { decorationsEnabled: 'both' } } } }); instantiationService.stub(IThemeService, new TestThemeService()); xterm = new TestTerminal({ allowProposedApi: true, cols: 80, rows: 30 }); instantiationService.stub(IConfigurationService, configurationService); instantiationService.stub(IContextMenuService, instantiationService.createInstance(ContextMenuService)); const capabilities = new TerminalCapabilityStore(); capabilities.add(TerminalCapability.CommandDetection, instantiationService.createInstance(CommandDetectionCapability, xterm)); instantiationService.stub(ILifecycleService, new TestLifecycleService()); decorationAddon = instantiationService.createInstance(DecorationAddon, capabilities); xterm.loadAddon(decorationAddon); instantiationService.stub(ILogService, NullLogService); }); suite('registerDecoration', async () => { test('should throw when command has no marker', async () => { throws(() => decorationAddon.registerCommandDecoration({ command: 'cd src', timestamp: Date.now(), hasOutput: () => false } as ITerminalCommand)); }); test('should return undefined when marker has been disposed of', async () => { const marker = xterm.registerMarker(1); marker?.dispose(); strictEqual(decorationAddon.registerCommandDecoration({ command: 'cd src', marker, timestamp: Date.now(), hasOutput: () => false } as ITerminalCommand), undefined); }); test('should return decoration when marker has not been disposed of', async () => { const marker = xterm.registerMarker(2); notEqual(decorationAddon.registerCommandDecoration({ command: 'cd src', marker, timestamp: Date.now(), hasOutput: () => false } as ITerminalCommand), undefined); }); test('should return decoration with mark properties', async () => { const marker = xterm.registerMarker(2); notEqual(decorationAddon.registerCommandDecoration(undefined, undefined, { marker }), undefined); }); }); });
src/vs/workbench/contrib/terminal/test/browser/xterm/decorationAddon.test.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001790238602552563, 0.00017599033890292048, 0.00017369429406244308, 0.00017548268078826368, 0.000001746807811286999 ]
{ "id": 4, "code_window": [ "\t\tthis._register(this._hueStrip.onColorFlushed(this.flushColor, this));\n", "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._insertButton = new InsertButton(this._domNode);\n", "\t\t\tthis._register(this._insertButton);\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 106 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { CallHierarchyProviderRegistry, CallHierarchyDirection, CallHierarchyModel } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { CallHierarchyTreePeekWidget } from 'vs/workbench/contrib/callHierarchy/browser/callHierarchyPeek'; import { Event } from 'vs/base/common/event'; import { registerEditorContribution, EditorAction2, EditorContributionInstantiation } from 'vs/editor/browser/editorExtensions'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, RawContextKey, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { PeekContext } from 'vs/editor/contrib/peekView/browser/peekView'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { Range } from 'vs/editor/common/core/range'; import { IPosition } from 'vs/editor/common/core/position'; import { MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { Codicon } from 'vs/base/common/codicons'; import { registerIcon } from 'vs/platform/theme/common/iconRegistry'; import { isCancellationError } from 'vs/base/common/errors'; const _ctxHasCallHierarchyProvider = new RawContextKey<boolean>('editorHasCallHierarchyProvider', false, localize('editorHasCallHierarchyProvider', 'Whether a call hierarchy provider is available')); const _ctxCallHierarchyVisible = new RawContextKey<boolean>('callHierarchyVisible', false, localize('callHierarchyVisible', 'Whether call hierarchy peek is currently showing')); const _ctxCallHierarchyDirection = new RawContextKey<string>('callHierarchyDirection', undefined, { type: 'string', description: localize('callHierarchyDirection', 'Whether call hierarchy shows incoming or outgoing calls') }); function sanitizedDirection(candidate: string): CallHierarchyDirection { return candidate === CallHierarchyDirection.CallsFrom || candidate === CallHierarchyDirection.CallsTo ? candidate : CallHierarchyDirection.CallsTo; } class CallHierarchyController implements IEditorContribution { static readonly Id = 'callHierarchy'; static get(editor: ICodeEditor): CallHierarchyController | null { return editor.getContribution<CallHierarchyController>(CallHierarchyController.Id); } private static readonly _StorageDirection = 'callHierarchy/defaultDirection'; private readonly _ctxHasProvider: IContextKey<boolean>; private readonly _ctxIsVisible: IContextKey<boolean>; private readonly _ctxDirection: IContextKey<string>; private readonly _dispoables = new DisposableStore(); private readonly _sessionDisposables = new DisposableStore(); private _widget?: CallHierarchyTreePeekWidget; constructor( private readonly _editor: ICodeEditor, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @IStorageService private readonly _storageService: IStorageService, @ICodeEditorService private readonly _editorService: ICodeEditorService, @IInstantiationService private readonly _instantiationService: IInstantiationService, ) { this._ctxIsVisible = _ctxCallHierarchyVisible.bindTo(this._contextKeyService); this._ctxHasProvider = _ctxHasCallHierarchyProvider.bindTo(this._contextKeyService); this._ctxDirection = _ctxCallHierarchyDirection.bindTo(this._contextKeyService); this._dispoables.add(Event.any<any>(_editor.onDidChangeModel, _editor.onDidChangeModelLanguage, CallHierarchyProviderRegistry.onDidChange)(() => { this._ctxHasProvider.set(_editor.hasModel() && CallHierarchyProviderRegistry.has(_editor.getModel())); })); this._dispoables.add(this._sessionDisposables); } dispose(): void { this._ctxHasProvider.reset(); this._ctxIsVisible.reset(); this._dispoables.dispose(); } async startCallHierarchyFromEditor(): Promise<void> { this._sessionDisposables.clear(); if (!this._editor.hasModel()) { return; } const document = this._editor.getModel(); const position = this._editor.getPosition(); if (!CallHierarchyProviderRegistry.has(document)) { return; } const cts = new CancellationTokenSource(); const model = CallHierarchyModel.create(document, position, cts.token); const direction = sanitizedDirection(this._storageService.get(CallHierarchyController._StorageDirection, StorageScope.PROFILE, CallHierarchyDirection.CallsTo)); this._showCallHierarchyWidget(position, direction, model, cts); } async startCallHierarchyFromCallHierarchy(): Promise<void> { if (!this._widget) { return; } const model = this._widget.getModel(); const call = this._widget.getFocused(); if (!call || !model) { return; } const newEditor = await this._editorService.openCodeEditor({ resource: call.item.uri }, this._editor); if (!newEditor) { return; } const newModel = model.fork(call.item); this._sessionDisposables.clear(); CallHierarchyController.get(newEditor)?._showCallHierarchyWidget( Range.lift(newModel.root.selectionRange).getStartPosition(), this._widget.direction, Promise.resolve(newModel), new CancellationTokenSource() ); } private _showCallHierarchyWidget(position: IPosition, direction: CallHierarchyDirection, model: Promise<CallHierarchyModel | undefined>, cts: CancellationTokenSource) { this._ctxIsVisible.set(true); this._ctxDirection.set(direction); Event.any<any>(this._editor.onDidChangeModel, this._editor.onDidChangeModelLanguage)(this.endCallHierarchy, this, this._sessionDisposables); this._widget = this._instantiationService.createInstance(CallHierarchyTreePeekWidget, this._editor, position, direction); this._widget.showLoading(); this._sessionDisposables.add(this._widget.onDidClose(() => { this.endCallHierarchy(); this._storageService.store(CallHierarchyController._StorageDirection, this._widget!.direction, StorageScope.PROFILE, StorageTarget.USER); })); this._sessionDisposables.add({ dispose() { cts.dispose(true); } }); this._sessionDisposables.add(this._widget); model.then(model => { if (cts.token.isCancellationRequested) { return; // nothing } if (model) { this._sessionDisposables.add(model); this._widget!.showModel(model); } else { this._widget!.showMessage(localize('no.item', "No results")); } }).catch(err => { if (isCancellationError(err)) { this.endCallHierarchy(); return; } this._widget!.showMessage(localize('error', "Failed to show call hierarchy")); }); } showOutgoingCalls(): void { this._widget?.updateDirection(CallHierarchyDirection.CallsFrom); this._ctxDirection.set(CallHierarchyDirection.CallsFrom); } showIncomingCalls(): void { this._widget?.updateDirection(CallHierarchyDirection.CallsTo); this._ctxDirection.set(CallHierarchyDirection.CallsTo); } endCallHierarchy(): void { this._sessionDisposables.clear(); this._ctxIsVisible.set(false); this._editor.focus(); } } registerEditorContribution(CallHierarchyController.Id, CallHierarchyController, EditorContributionInstantiation.Eager); // eager because it needs to define a context key registerAction2(class extends EditorAction2 { constructor() { super({ id: 'editor.showCallHierarchy', title: { value: localize('title', "Peek Call Hierarchy"), original: 'Peek Call Hierarchy' }, menu: { id: MenuId.EditorContextPeek, group: 'navigation', order: 1000, when: ContextKeyExpr.and( _ctxHasCallHierarchyProvider, PeekContext.notInPeekEditor ), }, keybinding: { when: EditorContextKeys.editorTextFocus, weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.Shift + KeyMod.Alt + KeyCode.KeyH }, precondition: ContextKeyExpr.and( _ctxHasCallHierarchyProvider, PeekContext.notInPeekEditor ) }); } async runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { return CallHierarchyController.get(editor)?.startCallHierarchyFromEditor(); } }); registerAction2(class extends EditorAction2 { constructor() { super({ id: 'editor.showIncomingCalls', title: { value: localize('title.incoming', "Show Incoming Calls"), original: 'Show Incoming Calls' }, icon: registerIcon('callhierarchy-incoming', Codicon.callIncoming, localize('showIncomingCallsIcons', 'Icon for incoming calls in the call hierarchy view.')), precondition: ContextKeyExpr.and(_ctxCallHierarchyVisible, _ctxCallHierarchyDirection.isEqualTo(CallHierarchyDirection.CallsFrom)), keybinding: { weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.Shift + KeyMod.Alt + KeyCode.KeyH, }, menu: { id: CallHierarchyTreePeekWidget.TitleMenu, when: _ctxCallHierarchyDirection.isEqualTo(CallHierarchyDirection.CallsFrom), order: 1, } }); } runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor) { return CallHierarchyController.get(editor)?.showIncomingCalls(); } }); registerAction2(class extends EditorAction2 { constructor() { super({ id: 'editor.showOutgoingCalls', title: { value: localize('title.outgoing', "Show Outgoing Calls"), original: 'Show Outgoing Calls' }, icon: registerIcon('callhierarchy-outgoing', Codicon.callOutgoing, localize('showOutgoingCallsIcon', 'Icon for outgoing calls in the call hierarchy view.')), precondition: ContextKeyExpr.and(_ctxCallHierarchyVisible, _ctxCallHierarchyDirection.isEqualTo(CallHierarchyDirection.CallsTo)), keybinding: { weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.Shift + KeyMod.Alt + KeyCode.KeyH, }, menu: { id: CallHierarchyTreePeekWidget.TitleMenu, when: _ctxCallHierarchyDirection.isEqualTo(CallHierarchyDirection.CallsTo), order: 1 } }); } runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor) { return CallHierarchyController.get(editor)?.showOutgoingCalls(); } }); registerAction2(class extends EditorAction2 { constructor() { super({ id: 'editor.refocusCallHierarchy', title: { value: localize('title.refocus', "Refocus Call Hierarchy"), original: 'Refocus Call Hierarchy' }, precondition: _ctxCallHierarchyVisible, keybinding: { weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.Shift + KeyCode.Enter } }); } async runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { return CallHierarchyController.get(editor)?.startCallHierarchyFromCallHierarchy(); } }); registerAction2(class extends EditorAction2 { constructor() { super({ id: 'editor.closeCallHierarchy', title: localize('close', 'Close'), icon: Codicon.close, precondition: _ctxCallHierarchyVisible, keybinding: { weight: KeybindingWeight.WorkbenchContrib + 10, primary: KeyCode.Escape, when: ContextKeyExpr.not('config.editor.stablePeek') }, menu: { id: CallHierarchyTreePeekWidget.TitleMenu, order: 1000 } }); } runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void { return CallHierarchyController.get(editor)?.endCallHierarchy(); } });
src/vs/workbench/contrib/callHierarchy/browser/callHierarchy.contribution.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017675946583040059, 0.0001717246777843684, 0.0001630806364119053, 0.00017200643196702003, 0.0000028122619823989226 ]
{ "id": 4, "code_window": [ "\t\tthis._register(this._hueStrip.onColorFlushed(this.flushColor, this));\n", "\n", "\t\tif (this.showingStandaloneColorPicker) {\n", "\t\t\tthis._insertButton = new InsertButton(this._domNode);\n", "\t\t\tthis._register(this._insertButton);\n", "\t\t}\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis._domNode.classList.add('standalone-color-picker');\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "add", "edit_start_line_idx": 106 }
[ { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": " ", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "type", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html entity.other.attribute-name.html", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #E50000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #E50000", "hc_black": "entity.other.attribute-name: #9CDCFE", "dark_plus_experimental": "entity.other.attribute-name: #9CDCFE", "hc_light": "entity.other.attribute-name: #264F78", "light_plus_experimental": "entity.other.attribute-name: #E50000" } }, { "c": "=", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html punctuation.separator.key-value.html", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "\"", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.double.html punctuation.definition.string.begin.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.html: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.double.html: #0F4A85", "light_plus_experimental": "string.quoted.double.html: #0000FF" } }, { "c": "text/javascript", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.double.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.html: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.double.html: #0F4A85", "light_plus_experimental": "string.quoted.double.html: #0000FF" } }, { "c": "\"", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html meta.attribute.type.html string.quoted.double.html punctuation.definition.string.end.html", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.html: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.html: #0000FF", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string.quoted.double.html: #0F4A85", "light_plus_experimental": "string.quoted.double.html: #0000FF" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "\t", "t": "text.html.derivative meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "window", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js variable.other.object.js", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE", "dark_plus_experimental": "variable: #9CDCFE", "hc_light": "variable: #001080", "light_plus_experimental": "variable: #001080" } }, { "c": ".", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js punctuation.accessor.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "alert", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js entity.name.function.js", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "entity.name.function: #DCDCAA", "dark_plus_experimental": "entity.name.function: #DCDCAA", "hc_light": "entity.name.function: #5E2CBC", "light_plus_experimental": "entity.name.function: #795E26" } }, { "c": "(", "t": "text.html.derivative meta.embedded.block.html source.js meta.brace.round.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js punctuation.definition.string.begin.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": "hello", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js punctuation.definition.string.end.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": ")", "t": "text.html.derivative meta.embedded.block.html source.js meta.brace.round.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": ";", "t": "text.html.derivative meta.embedded.block.html source.js punctuation.terminator.statement.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html source.js-ignored-vscode", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "/", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "\t", "t": "text.html.derivative meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "window", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js variable.other.object.js", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE", "dark_plus_experimental": "variable: #9CDCFE", "hc_light": "variable: #001080", "light_plus_experimental": "variable: #001080" } }, { "c": ".", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js punctuation.accessor.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "alert", "t": "text.html.derivative meta.embedded.block.html source.js meta.function-call.js entity.name.function.js", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "entity.name.function: #DCDCAA", "dark_plus_experimental": "entity.name.function: #DCDCAA", "hc_light": "entity.name.function: #5E2CBC", "light_plus_experimental": "entity.name.function: #795E26" } }, { "c": "(", "t": "text.html.derivative meta.embedded.block.html source.js meta.brace.round.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js punctuation.definition.string.begin.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": "hello", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": "'", "t": "text.html.derivative meta.embedded.block.html source.js string.quoted.single.js punctuation.definition.string.end.js", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178", "dark_plus_experimental": "string: #CE9178", "hc_light": "string: #0F4A85", "light_plus_experimental": "string: #A31515" } }, { "c": ")", "t": "text.html.derivative meta.embedded.block.html source.js meta.brace.round.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": ";", "t": "text.html.derivative meta.embedded.block.html source.js punctuation.terminator.statement.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF", "dark_plus_experimental": "meta.embedded: #D4D4D4", "hc_light": "meta.embedded: #292929", "light_plus_experimental": "meta.embedded: #000000" } }, { "c": "<", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html source.js-ignored-vscode", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "/", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } }, { "c": "script", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6", "dark_plus_experimental": "entity.name.tag: #569CD6", "hc_light": "entity.name.tag: #0F4A85", "light_plus_experimental": "entity.name.tag: #800000" } }, { "c": ">", "t": "text.html.derivative meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080", "dark_plus_experimental": "punctuation.definition.tag: #808080", "hc_light": "punctuation.definition.tag: #0F4A85", "light_plus_experimental": "punctuation.definition.tag: #800000" } } ]
extensions/vscode-colorize-tests/test/colorize-results/12750_html.json
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017987957107834518, 0.00017522403504699469, 0.00017309296526946127, 0.00017501179536338896, 0.0000014045275520402356 ]
{ "id": 5, "code_window": [ "\t\tthis._register(PixelRatio.onDidChange(() => this.layout()));\n", "\n", "\t\tconst element = $('.colorpicker-widget');\n", "\t\tcontainer.appendChild(element);\n", "\n", "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService);\n", "\t\tthis.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker);\n", "\n", "\t\tthis._register(this.header);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService, standaloneColorPicker);\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 427 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.9983202815055847, 0.03812501206994057, 0.00016268412582576275, 0.0003805420419666916, 0.17590944468975067 ]
{ "id": 5, "code_window": [ "\t\tthis._register(PixelRatio.onDidChange(() => this.layout()));\n", "\n", "\t\tconst element = $('.colorpicker-widget');\n", "\t\tcontainer.appendChild(element);\n", "\n", "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService);\n", "\t\tthis.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker);\n", "\n", "\t\tthis._register(this.header);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService, standaloneColorPicker);\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 427 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ConfigurationChangedEvent, EditorAutoClosingEditStrategy, EditorAutoClosingStrategy, EditorAutoIndentStrategy, EditorAutoSurroundStrategy, EditorOption } from 'vs/editor/common/config/editorOptions'; import { LineTokens } from 'vs/editor/common/tokens/lineTokens'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { ICommand } from 'vs/editor/common/editorCommon'; import { IEditorConfiguration } from 'vs/editor/common/config/editorConfiguration'; import { PositionAffinity, TextModelResolvedOptions } from 'vs/editor/common/model'; import { AutoClosingPairs } from 'vs/editor/common/languages/languageConfiguration'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { createScopedLineTokens } from 'vs/editor/common/languages/supports'; import { IElectricAction } from 'vs/editor/common/languages/supports/electricCharacter'; import { CursorColumns } from 'vs/editor/common/core/cursorColumns'; import { normalizeIndentation } from 'vs/editor/common/core/indentation'; export interface IColumnSelectData { isReal: boolean; fromViewLineNumber: number; fromViewVisualColumn: number; toViewLineNumber: number; toViewVisualColumn: number; } /** * This is an operation type that will be recorded for undo/redo purposes. * The goal is to introduce an undo stop when the controller switches between different operation types. */ export const enum EditOperationType { Other = 0, DeletingLeft = 2, DeletingRight = 3, TypingOther = 4, TypingFirstSpace = 5, TypingConsecutiveSpace = 6, } export interface CharacterMap { [char: string]: string; } const autoCloseAlways = () => true; const autoCloseNever = () => false; const autoCloseBeforeWhitespace = (chr: string) => (chr === ' ' || chr === '\t'); export class CursorConfiguration { _cursorMoveConfigurationBrand: void = undefined; public readonly readOnly: boolean; public readonly tabSize: number; public readonly indentSize: number; public readonly insertSpaces: boolean; public readonly stickyTabStops: boolean; public readonly pageSize: number; public readonly lineHeight: number; public readonly typicalHalfwidthCharacterWidth: number; public readonly useTabStops: boolean; public readonly wordSeparators: string; public readonly emptySelectionClipboard: boolean; public readonly copyWithSyntaxHighlighting: boolean; public readonly multiCursorMergeOverlapping: boolean; public readonly multiCursorPaste: 'spread' | 'full'; public readonly multiCursorLimit: number; public readonly autoClosingBrackets: EditorAutoClosingStrategy; public readonly autoClosingQuotes: EditorAutoClosingStrategy; public readonly autoClosingDelete: EditorAutoClosingEditStrategy; public readonly autoClosingOvertype: EditorAutoClosingEditStrategy; public readonly autoSurround: EditorAutoSurroundStrategy; public readonly autoIndent: EditorAutoIndentStrategy; public readonly autoClosingPairs: AutoClosingPairs; public readonly surroundingPairs: CharacterMap; public readonly shouldAutoCloseBefore: { quote: (ch: string) => boolean; bracket: (ch: string) => boolean }; private readonly _languageId: string; private _electricChars: { [key: string]: boolean } | null; public static shouldRecreate(e: ConfigurationChangedEvent): boolean { return ( e.hasChanged(EditorOption.layoutInfo) || e.hasChanged(EditorOption.wordSeparators) || e.hasChanged(EditorOption.emptySelectionClipboard) || e.hasChanged(EditorOption.multiCursorMergeOverlapping) || e.hasChanged(EditorOption.multiCursorPaste) || e.hasChanged(EditorOption.multiCursorLimit) || e.hasChanged(EditorOption.autoClosingBrackets) || e.hasChanged(EditorOption.autoClosingQuotes) || e.hasChanged(EditorOption.autoClosingDelete) || e.hasChanged(EditorOption.autoClosingOvertype) || e.hasChanged(EditorOption.autoSurround) || e.hasChanged(EditorOption.useTabStops) || e.hasChanged(EditorOption.fontInfo) || e.hasChanged(EditorOption.readOnly) ); } constructor( languageId: string, modelOptions: TextModelResolvedOptions, configuration: IEditorConfiguration, public readonly languageConfigurationService: ILanguageConfigurationService ) { this._languageId = languageId; const options = configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); const fontInfo = options.get(EditorOption.fontInfo); this.readOnly = options.get(EditorOption.readOnly); this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.stickyTabStops = options.get(EditorOption.stickyTabStops); this.lineHeight = fontInfo.lineHeight; this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); this.useTabStops = options.get(EditorOption.useTabStops); this.wordSeparators = options.get(EditorOption.wordSeparators); this.emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard); this.copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting); this.multiCursorMergeOverlapping = options.get(EditorOption.multiCursorMergeOverlapping); this.multiCursorPaste = options.get(EditorOption.multiCursorPaste); this.multiCursorLimit = options.get(EditorOption.multiCursorLimit); this.autoClosingBrackets = options.get(EditorOption.autoClosingBrackets); this.autoClosingQuotes = options.get(EditorOption.autoClosingQuotes); this.autoClosingDelete = options.get(EditorOption.autoClosingDelete); this.autoClosingOvertype = options.get(EditorOption.autoClosingOvertype); this.autoSurround = options.get(EditorOption.autoSurround); this.autoIndent = options.get(EditorOption.autoIndent); this.surroundingPairs = {}; this._electricChars = null; this.shouldAutoCloseBefore = { quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes, true), bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets, false) }; this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs(); const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs(); if (surroundingPairs) { for (const pair of surroundingPairs) { this.surroundingPairs[pair.open] = pair.close; } } } public get electricChars() { if (!this._electricChars) { this._electricChars = {}; const electricChars = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter?.getElectricCharacters(); if (electricChars) { for (const char of electricChars) { this._electricChars[char] = true; } } } return this._electricChars; } /** * Should return opening bracket type to match indentation with */ public onElectricCharacter(character: string, context: LineTokens, column: number): IElectricAction | null { const scopedLineTokens = createScopedLineTokens(context, column - 1); const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter; if (!electricCharacterSupport) { return null; } return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset); } public normalizeIndentation(str: string): string { return normalizeIndentation(str, this.indentSize, this.insertSpaces); } private _getShouldAutoClose(languageId: string, autoCloseConfig: EditorAutoClosingStrategy, forQuotes: boolean): (ch: string) => boolean { switch (autoCloseConfig) { case 'beforeWhitespace': return autoCloseBeforeWhitespace; case 'languageDefined': return this._getLanguageDefinedShouldAutoClose(languageId, forQuotes); case 'always': return autoCloseAlways; case 'never': return autoCloseNever; } } private _getLanguageDefinedShouldAutoClose(languageId: string, forQuotes: boolean): (ch: string) => boolean { const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(forQuotes); return c => autoCloseBeforeSet.indexOf(c) !== -1; } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ public visibleColumnFromColumn(model: ICursorSimpleModel, position: Position): number { return CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize); } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ public columnFromVisibleColumn(model: ICursorSimpleModel, lineNumber: number, visibleColumn: number): number { const result = CursorColumns.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize); const minColumn = model.getLineMinColumn(lineNumber); if (result < minColumn) { return minColumn; } const maxColumn = model.getLineMaxColumn(lineNumber); if (result > maxColumn) { return maxColumn; } return result; } } /** * Represents a simple model (either the model or the view model). */ export interface ICursorSimpleModel { getLineCount(): number; getLineContent(lineNumber: number): string; getLineMinColumn(lineNumber: number): number; getLineMaxColumn(lineNumber: number): number; getLineFirstNonWhitespaceColumn(lineNumber: number): number; getLineLastNonWhitespaceColumn(lineNumber: number): number; normalizePosition(position: Position, affinity: PositionAffinity): Position; /** * Gets the column at which indentation stops at a given line. * @internal */ getLineIndentColumn(lineNumber: number): number; } export type PartialCursorState = CursorState | PartialModelCursorState | PartialViewCursorState; export class CursorState { _cursorStateBrand: void = undefined; public static fromModelState(modelState: SingleCursorState): PartialModelCursorState { return new PartialModelCursorState(modelState); } public static fromViewState(viewState: SingleCursorState): PartialViewCursorState { return new PartialViewCursorState(viewState); } public static fromModelSelection(modelSelection: ISelection): PartialModelCursorState { const selection = Selection.liftSelection(modelSelection); const modelState = new SingleCursorState( Range.fromPositions(selection.getSelectionStart()), SelectionStartKind.Simple, 0, selection.getPosition(), 0 ); return CursorState.fromModelState(modelState); } public static fromModelSelections(modelSelections: readonly ISelection[]): PartialModelCursorState[] { const states: PartialModelCursorState[] = []; for (let i = 0, len = modelSelections.length; i < len; i++) { states[i] = this.fromModelSelection(modelSelections[i]); } return states; } readonly modelState: SingleCursorState; readonly viewState: SingleCursorState; constructor(modelState: SingleCursorState, viewState: SingleCursorState) { this.modelState = modelState; this.viewState = viewState; } public equals(other: CursorState): boolean { return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState)); } } export class PartialModelCursorState { readonly modelState: SingleCursorState; readonly viewState: null; constructor(modelState: SingleCursorState) { this.modelState = modelState; this.viewState = null; } } export class PartialViewCursorState { readonly modelState: null; readonly viewState: SingleCursorState; constructor(viewState: SingleCursorState) { this.modelState = null; this.viewState = viewState; } } export const enum SelectionStartKind { Simple, Word, Line } /** * Represents the cursor state on either the model or on the view model. */ export class SingleCursorState { _singleCursorStateBrand: void = undefined; public readonly selection: Selection; constructor( public readonly selectionStart: Range, public readonly selectionStartKind: SelectionStartKind, public readonly selectionStartLeftoverVisibleColumns: number, public readonly position: Position, public readonly leftoverVisibleColumns: number, ) { this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); } public equals(other: SingleCursorState) { return ( this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.selectionStartKind === other.selectionStartKind && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart) ); } public hasSelection(): boolean { return (!this.selection.isEmpty() || !this.selectionStart.isEmpty()); } public move(inSelectionMode: boolean, lineNumber: number, column: number, leftoverVisibleColumns: number): SingleCursorState { if (inSelectionMode) { // move just position return new SingleCursorState( this.selectionStart, this.selectionStartKind, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } else { // move everything return new SingleCursorState( new Range(lineNumber, column, lineNumber, column), SelectionStartKind.Simple, leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } } private static _computeSelection(selectionStart: Range, position: Position): Selection { if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) { return Selection.fromPositions(selectionStart.getStartPosition(), position); } else { return Selection.fromPositions(selectionStart.getEndPosition(), position); } } } export class EditOperationResult { _editOperationResultBrand: void = undefined; readonly type: EditOperationType; readonly commands: Array<ICommand | null>; readonly shouldPushStackElementBefore: boolean; readonly shouldPushStackElementAfter: boolean; constructor( type: EditOperationType, commands: Array<ICommand | null>, opts: { shouldPushStackElementBefore: boolean; shouldPushStackElementAfter: boolean; } ) { this.type = type; this.commands = commands; this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; } } export function isQuote(ch: string): boolean { return (ch === '\'' || ch === '"' || ch === '`'); }
src/vs/editor/common/cursorCommon.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017763585492502898, 0.00017227575881406665, 0.00016322921146638691, 0.00017285399371758103, 0.0000034990521271538455 ]
{ "id": 5, "code_window": [ "\t\tthis._register(PixelRatio.onDidChange(() => this.layout()));\n", "\n", "\t\tconst element = $('.colorpicker-widget');\n", "\t\tcontainer.appendChild(element);\n", "\n", "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService);\n", "\t\tthis.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker);\n", "\n", "\t\tthis._register(this.header);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService, standaloneColorPicker);\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 427 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ use crate::{log, state::LauncherPaths}; use super::args::CliCore; pub struct CommandContext { pub log: log::Logger, pub paths: LauncherPaths, pub args: CliCore, pub http: reqwest::Client, }
cli/src/commands/context.rs
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001773183757904917, 0.0001755800622049719, 0.00017384176317136735, 0.0001755800622049719, 0.0000017383063095621765 ]
{ "id": 5, "code_window": [ "\t\tthis._register(PixelRatio.onDidChange(() => this.layout()));\n", "\n", "\t\tconst element = $('.colorpicker-widget');\n", "\t\tcontainer.appendChild(element);\n", "\n", "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService);\n", "\t\tthis.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker);\n", "\n", "\t\tthis._register(this.header);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.header = new ColorPickerHeader(element, this.model, themeService, standaloneColorPicker);\n" ], "file_path": "src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 427 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getDomNodePagePosition } from 'vs/base/browser/dom'; import { Action } from 'vs/base/common/actions'; import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorAction, EditorAction2, IActionOptions, registerEditorAction } from 'vs/editor/browser/editorExtensions'; import { Position } from 'vs/editor/common/core/position'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { MessageController } from 'vs/editor/contrib/message/browser/messageController'; import * as nls from 'vs/nls'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { PanelFocusContext } from 'vs/workbench/common/contextkeys'; import { IViewsService } from 'vs/workbench/common/views'; import { openBreakpointSource } from 'vs/workbench/contrib/debug/browser/breakpointsView'; import { BreakpointWidgetContext, BREAKPOINT_EDITOR_CONTRIBUTION_ID, CONTEXT_CALLSTACK_ITEM_TYPE, CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE, CONTEXT_DISASSEMBLE_REQUEST_SUPPORTED, CONTEXT_EXCEPTION_WIDGET_VISIBLE, CONTEXT_FOCUSED_STACK_FRAME_HAS_INSTRUCTION_POINTER_REFERENCE, CONTEXT_IN_DEBUG_MODE, CONTEXT_LANGUAGE_SUPPORTS_DISASSEMBLE_REQUEST, CONTEXT_STEP_INTO_TARGETS_SUPPORTED, EDITOR_CONTRIBUTION_ID, IBreakpointEditorContribution, IDebugConfiguration, IDebugEditorContribution, IDebugService, REPL_VIEW_ID, WATCH_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { getEvaluatableExpressionAtPosition } from 'vs/workbench/contrib/debug/common/debugUtils'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; class ToggleBreakpointAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.toggleBreakpoint', label: nls.localize('toggleBreakpointAction', "Debug: Toggle Breakpoint"), alias: 'Debug: Toggle Breakpoint', precondition: CONTEXT_DEBUGGERS_AVAILABLE, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyCode.F9, weight: KeybindingWeight.EditorContrib }, menuOpts: { when: CONTEXT_DEBUGGERS_AVAILABLE, title: nls.localize({ key: 'miToggleBreakpoint', comment: ['&& denotes a mnemonic'] }, "Toggle &&Breakpoint"), menuId: MenuId.MenubarDebugMenu, group: '4_new_breakpoint', order: 1 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { // TODO: add disassembly F9 if (editor.hasModel()) { const debugService = accessor.get(IDebugService); const modelUri = editor.getModel().uri; const canSet = debugService.canSetBreakpointsIn(editor.getModel()); // Does not account for multi line selections, Set to remove multiple cursor on the same line const lineNumbers = [...new Set(editor.getSelections().map(s => s.getPosition().lineNumber))]; await Promise.all(lineNumbers.map(async line => { const bps = debugService.getModel().getBreakpoints({ lineNumber: line, uri: modelUri }); if (bps.length) { await Promise.all(bps.map(bp => debugService.removeBreakpoints(bp.getId()))); } else if (canSet) { await debugService.addBreakpoints(modelUri, [{ lineNumber: line }]); } })); } } } class ConditionalBreakpointAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.conditionalBreakpoint', label: nls.localize('conditionalBreakpointEditorAction', "Debug: Add Conditional Breakpoint..."), alias: 'Debug: Add Conditional Breakpoint...', precondition: CONTEXT_DEBUGGERS_AVAILABLE, menuOpts: { menuId: MenuId.MenubarNewBreakpointMenu, title: nls.localize({ key: 'miConditionalBreakpoint', comment: ['&& denotes a mnemonic'] }, "&&Conditional Breakpoint..."), group: '1_breakpoints', order: 1, when: CONTEXT_DEBUGGERS_AVAILABLE } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const position = editor.getPosition(); if (position && editor.hasModel() && debugService.canSetBreakpointsIn(editor.getModel())) { editor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID)?.showBreakpointWidget(position.lineNumber, undefined, BreakpointWidgetContext.CONDITION); } } } class LogPointAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.addLogPoint', label: nls.localize('logPointEditorAction', "Debug: Add Logpoint..."), precondition: CONTEXT_DEBUGGERS_AVAILABLE, alias: 'Debug: Add Logpoint...', menuOpts: [ { menuId: MenuId.MenubarNewBreakpointMenu, title: nls.localize({ key: 'miLogPoint', comment: ['&& denotes a mnemonic'] }, "&&Logpoint..."), group: '1_breakpoints', order: 4, when: CONTEXT_DEBUGGERS_AVAILABLE, } ] }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const position = editor.getPosition(); if (position && editor.hasModel() && debugService.canSetBreakpointsIn(editor.getModel())) { editor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID)?.showBreakpointWidget(position.lineNumber, position.column, BreakpointWidgetContext.LOG_MESSAGE); } } } class EditBreakpointAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.editBreakpoint', label: nls.localize('EditBreakpointEditorAction', "Debug: Edit Breakpoint"), alias: 'Debug: Edit Existing Breakpoint', precondition: CONTEXT_DEBUGGERS_AVAILABLE, menuOpts: { menuId: MenuId.MenubarNewBreakpointMenu, title: nls.localize({ key: 'miEditBreakpoint', comment: ['&& denotes a mnemonic'] }, "&&Edit Breakpoint"), group: '1_breakpoints', order: 1, when: CONTEXT_DEBUGGERS_AVAILABLE } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const position = editor.getPosition(); const debugModel = debugService.getModel(); if (!(editor.hasModel() && position)) { return; } const lineBreakpoints = debugModel.getBreakpoints({ lineNumber: position.lineNumber }); if (lineBreakpoints.length === 0) { return; } const breakpointDistances = lineBreakpoints.map(b => { if (!b.column) { return position.column; } return Math.abs(b.column - position.column); }); const closestBreakpointIndex = breakpointDistances.indexOf(Math.min(...breakpointDistances)); const closestBreakpoint = lineBreakpoints[closestBreakpointIndex]; editor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID)?.showBreakpointWidget(closestBreakpoint.lineNumber, closestBreakpoint.column); } } class OpenDisassemblyViewAction extends EditorAction2 { public static readonly ID = 'editor.debug.action.openDisassemblyView'; constructor() { super({ id: OpenDisassemblyViewAction.ID, title: { value: nls.localize('openDisassemblyView', "Open Disassembly View"), original: 'Open Disassembly View', mnemonicTitle: nls.localize({ key: 'miDisassemblyView', comment: ['&& denotes a mnemonic'] }, "&&DisassemblyView") }, precondition: CONTEXT_FOCUSED_STACK_FRAME_HAS_INSTRUCTION_POINTER_REFERENCE, menu: [ { id: MenuId.EditorContext, group: 'debug', order: 5, when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, PanelFocusContext.toNegated(), CONTEXT_DEBUG_STATE.isEqualTo('stopped'), EditorContextKeys.editorTextFocus, CONTEXT_DISASSEMBLE_REQUEST_SUPPORTED, CONTEXT_LANGUAGE_SUPPORTS_DISASSEMBLE_REQUEST) }, { id: MenuId.DebugCallStackContext, group: 'z_commands', order: 50, when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), CONTEXT_CALLSTACK_ITEM_TYPE.isEqualTo('stackFrame'), CONTEXT_DISASSEMBLE_REQUEST_SUPPORTED) }, { id: MenuId.CommandPalette, when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), CONTEXT_DISASSEMBLE_REQUEST_SUPPORTED) } ] }); } runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, ...args: any[]): void { if (editor.hasModel()) { const editorService = accessor.get(IEditorService); editorService.openEditor(DisassemblyViewInput.instance, { pinned: true }); } } } class ToggleDisassemblyViewSourceCodeAction extends Action2 { public static readonly ID = 'debug.action.toggleDisassemblyViewSourceCode'; public static readonly configID: string = 'debug.disassemblyView.showSourceCode'; constructor() { super({ id: ToggleDisassemblyViewSourceCodeAction.ID, title: { value: nls.localize('toggleDisassemblyViewSourceCode', "Toggle Source Code in Disassembly View"), original: 'Toggle Source Code in Disassembly View', mnemonicTitle: nls.localize({ key: 'mitogglesource', comment: ['&& denotes a mnemonic'] }, "&&ToggleSource") }, f1: true, }); } run(accessor: ServicesAccessor, editor: ICodeEditor, ...args: any[]): void { const configService = accessor.get(IConfigurationService); if (configService) { const value = configService.getValue<IDebugConfiguration>('debug').disassemblyView.showSourceCode; configService.updateValue(ToggleDisassemblyViewSourceCodeAction.configID, !value); } } } export class RunToCursorAction extends EditorAction { public static readonly ID = 'editor.debug.action.runToCursor'; public static readonly LABEL = nls.localize('runToCursor', "Run to Cursor"); constructor() { super({ id: RunToCursorAction.ID, label: RunToCursorAction.LABEL, alias: 'Debug: Run to Cursor', precondition: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, PanelFocusContext.toNegated(), EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 2 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const position = editor.getPosition(); if (!(editor.hasModel() && position)) { return; } const uri = editor.getModel().uri; const debugService = accessor.get(IDebugService); const viewModel = debugService.getViewModel(); const uriIdentityService = accessor.get(IUriIdentityService); let column: number | undefined = undefined; const focusedStackFrame = viewModel.focusedStackFrame; if (focusedStackFrame && uriIdentityService.extUri.isEqual(focusedStackFrame.source.uri, uri) && focusedStackFrame.range.startLineNumber === position.lineNumber) { // If the cursor is on a line different than the one the debugger is currently paused on, then send the breakpoint on the line without a column // otherwise set it at the precise column #102199 column = position.column; } await debugService.runTo(uri, position.lineNumber, column); } } export class SelectionToReplAction extends EditorAction { public static readonly ID = 'editor.debug.action.selectionToRepl'; public static readonly LABEL = nls.localize('evaluateInDebugConsole', "Evaluate in Debug Console"); constructor() { super({ id: SelectionToReplAction.ID, label: SelectionToReplAction.LABEL, alias: 'Debug: Evaluate in Console', precondition: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 0 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const viewsService = accessor.get(IViewsService); const viewModel = debugService.getViewModel(); const session = viewModel.focusedSession; if (!editor.hasModel() || !session) { return; } const selection = editor.getSelection(); let text: string; if (selection.isEmpty()) { text = editor.getModel().getLineContent(selection.selectionStartLineNumber).trim(); } else { text = editor.getModel().getValueInRange(selection); } await session.addReplExpression(viewModel.focusedStackFrame!, text); await viewsService.openView(REPL_VIEW_ID, false); } } export class SelectionToWatchExpressionsAction extends EditorAction { public static readonly ID = 'editor.debug.action.selectionToWatch'; public static readonly LABEL = nls.localize('addToWatch', "Add to Watch"); constructor() { super({ id: SelectionToWatchExpressionsAction.ID, label: SelectionToWatchExpressionsAction.LABEL, alias: 'Debug: Add to Watch', precondition: ContextKeyExpr.and(EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 1 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const viewsService = accessor.get(IViewsService); const languageFeaturesService = accessor.get(ILanguageFeaturesService); if (!editor.hasModel()) { return; } let expression: string | undefined = undefined; const model = editor.getModel(); const selection = editor.getSelection(); if (!selection.isEmpty()) { expression = model.getValueInRange(selection); } else { const position = editor.getPosition(); const evaluatableExpression = await getEvaluatableExpressionAtPosition(languageFeaturesService, model, position); if (!evaluatableExpression) { return; } expression = evaluatableExpression.matchingExpression; } if (!expression) { return; } await viewsService.openView(WATCH_VIEW_ID); debugService.addWatchExpression(expression); } } class ShowDebugHoverAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.showDebugHover', label: nls.localize('showDebugHover', "Debug: Show Hover"), alias: 'Debug: Show Hover', precondition: CONTEXT_IN_DEBUG_MODE, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyCode.KeyI), weight: KeybindingWeight.EditorContrib } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const position = editor.getPosition(); if (!position || !editor.hasModel()) { return; } return editor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID)?.showHover(position, true); } } const NO_TARGETS_MESSAGE = nls.localize('editor.debug.action.stepIntoTargets.notAvailable', "Step targets are not available here"); class StepIntoTargetsAction extends EditorAction { public static readonly ID = 'editor.debug.action.stepIntoTargets'; public static readonly LABEL = nls.localize({ key: 'stepIntoTargets', comment: ['Step Into Targets lets the user step into an exact function he or she is interested in.'] }, "Step Into Target"); constructor() { super({ id: StepIntoTargetsAction.ID, label: StepIntoTargetsAction.LABEL, alias: 'Debug: Step Into Target', precondition: ContextKeyExpr.and(CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 1.5 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const contextMenuService = accessor.get(IContextMenuService); const uriIdentityService = accessor.get(IUriIdentityService); const session = debugService.getViewModel().focusedSession; const frame = debugService.getViewModel().focusedStackFrame; const selection = editor.getSelection(); const targetPosition = selection?.getPosition() || (frame && { lineNumber: frame.range.startLineNumber, column: frame.range.startColumn }); if (!session || !frame || !editor.hasModel() || !uriIdentityService.extUri.isEqual(editor.getModel().uri, frame.source.uri)) { if (targetPosition) { MessageController.get(editor)?.showMessage(NO_TARGETS_MESSAGE, targetPosition); } return; } const targets = await session.stepInTargets(frame.frameId); if (!targets?.length) { MessageController.get(editor)?.showMessage(NO_TARGETS_MESSAGE, targetPosition!); return; } // If there is a selection, try to find the best target with a position to step into. if (selection) { const positionalTargets: { start: Position; end?: Position; target: DebugProtocol.StepInTarget }[] = []; for (const target of targets) { if (target.line) { positionalTargets.push({ start: new Position(target.line, target.column || 1), end: target.endLine ? new Position(target.endLine, target.endColumn || 1) : undefined, target }); } } positionalTargets.sort((a, b) => b.start.lineNumber - a.start.lineNumber || b.start.column - a.start.column); const needle = selection.getPosition(); // Try to find a target with a start and end that is around the cursor // position. Or, if none, whatever is before the cursor. const best = positionalTargets.find(t => t.end && needle.isBefore(t.end) && t.start.isBeforeOrEqual(needle)) || positionalTargets.find(t => t.end === undefined && t.start.isBeforeOrEqual(needle)); if (best) { session.stepIn(frame.thread.threadId, best.target.id); return; } } // Otherwise, show a context menu and have the user pick a target editor.revealLineInCenterIfOutsideViewport(frame.range.startLineNumber); const cursorCoords = editor.getScrolledVisiblePosition(targetPosition!); const editorCoords = getDomNodePagePosition(editor.getDomNode()); const x = editorCoords.left + cursorCoords.left; const y = editorCoords.top + cursorCoords.top + cursorCoords.height; contextMenuService.showContextMenu({ getAnchor: () => ({ x, y }), getActions: () => { return targets.map(t => new Action(`stepIntoTarget:${t.id}`, t.label, undefined, true, () => session.stepIn(frame.thread.threadId, t.id))); } }); } } class GoToBreakpointAction extends EditorAction { constructor(private isNext: boolean, opts: IActionOptions) { super(opts); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<any> { const debugService = accessor.get(IDebugService); const editorService = accessor.get(IEditorService); const uriIdentityService = accessor.get(IUriIdentityService); if (editor.hasModel()) { const currentUri = editor.getModel().uri; const currentLine = editor.getPosition().lineNumber; //Breakpoints returned from `getBreakpoints` are already sorted. const allEnabledBreakpoints = debugService.getModel().getBreakpoints({ enabledOnly: true }); //Try to find breakpoint in current file let moveBreakpoint = this.isNext ? allEnabledBreakpoints.filter(bp => uriIdentityService.extUri.isEqual(bp.uri, currentUri) && bp.lineNumber > currentLine).shift() : allEnabledBreakpoints.filter(bp => uriIdentityService.extUri.isEqual(bp.uri, currentUri) && bp.lineNumber < currentLine).pop(); //Try to find breakpoints in following files if (!moveBreakpoint) { moveBreakpoint = this.isNext ? allEnabledBreakpoints.filter(bp => bp.uri.toString() > currentUri.toString()).shift() : allEnabledBreakpoints.filter(bp => bp.uri.toString() < currentUri.toString()).pop(); } //Move to first or last possible breakpoint if (!moveBreakpoint && allEnabledBreakpoints.length) { moveBreakpoint = this.isNext ? allEnabledBreakpoints[0] : allEnabledBreakpoints[allEnabledBreakpoints.length - 1]; } if (moveBreakpoint) { return openBreakpointSource(moveBreakpoint, false, true, false, debugService, editorService); } } } } class GoToNextBreakpointAction extends GoToBreakpointAction { constructor() { super(true, { id: 'editor.debug.action.goToNextBreakpoint', label: nls.localize('goToNextBreakpoint', "Debug: Go to Next Breakpoint"), alias: 'Debug: Go to Next Breakpoint', precondition: CONTEXT_DEBUGGERS_AVAILABLE }); } } class GoToPreviousBreakpointAction extends GoToBreakpointAction { constructor() { super(false, { id: 'editor.debug.action.goToPreviousBreakpoint', label: nls.localize('goToPreviousBreakpoint', "Debug: Go to Previous Breakpoint"), alias: 'Debug: Go to Previous Breakpoint', precondition: CONTEXT_DEBUGGERS_AVAILABLE }); } } class CloseExceptionWidgetAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.closeExceptionWidget', label: nls.localize('closeExceptionWidget', "Close Exception Widget"), alias: 'Close Exception Widget', precondition: CONTEXT_EXCEPTION_WIDGET_VISIBLE, kbOpts: { primary: KeyCode.Escape, weight: KeybindingWeight.EditorContrib } }); } async run(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const contribution = editor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID); contribution?.closeExceptionWidget(); } } registerAction2(OpenDisassemblyViewAction); registerAction2(ToggleDisassemblyViewSourceCodeAction); registerEditorAction(ToggleBreakpointAction); registerEditorAction(ConditionalBreakpointAction); registerEditorAction(LogPointAction); registerEditorAction(EditBreakpointAction); registerEditorAction(RunToCursorAction); registerEditorAction(StepIntoTargetsAction); registerEditorAction(SelectionToReplAction); registerEditorAction(SelectionToWatchExpressionsAction); registerEditorAction(ShowDebugHoverAction); registerEditorAction(GoToNextBreakpointAction); registerEditorAction(GoToPreviousBreakpointAction); registerEditorAction(CloseExceptionWidgetAction);
src/vs/workbench/contrib/debug/browser/debugEditorActions.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.0001778378791641444, 0.0001736461417749524, 0.0001648375327931717, 0.00017394636233802885, 0.000002541116600696114 ]
{ "id": 6, "code_window": [ "\t\t// colorPickerHeader.domNode.style.width = 600 + 'px';\n", "\t\t// colorPickerHeader.domNode.style.height = 20 + 'px';\n", "\n", "\t\tconst colorPickerBody = colorPicker?.body as ColorPickerBody;\n", "\t\tcolorPickerBody.domNode.style.background = 'red';\n", "\t\tconst saturationBox = colorPickerBody.saturationBox;\n", "\t\tconst hueStrip = colorPickerBody.hueStrip;\n", "\t\tconst opacityStrip = colorPickerBody.opacityStrip;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 218 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { PixelRatio } from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import { GlobalPointerMoveMonitor } from 'vs/base/browser/globalPointerMoveMonitor'; import { Widget } from 'vs/base/browser/ui/widget'; import { Color, HSVA, RGBA } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import 'vs/css!./colorPicker'; import { ColorPickerModel } from 'vs/editor/contrib/colorPicker/browser/colorPickerModel'; import { IEditorHoverColorPickerWidget } from 'vs/editor/contrib/hover/browser/hoverTypes'; import { localize } from 'vs/nls'; import { editorHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; const $ = dom.$; export class ColorPickerHeader extends Disposable { private readonly _domNode: HTMLElement; private readonly pickedColorNode: HTMLElement; private backgroundColor: Color; constructor(container: HTMLElement, private readonly model: ColorPickerModel, themeService: IThemeService) { super(); this._domNode = $('.colorpicker-header'); dom.append(container, this._domNode); this.pickedColorNode = dom.append(this._domNode, $('.picked-color')); const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)"); this.pickedColorNode.setAttribute('title', tooltip); const colorBox = dom.append(this._domNode, $('.original-color')); colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || ''; this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white; this._register(themeService.onDidColorThemeChange(theme => { this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white; })); this._register(dom.addDisposableListener(this.pickedColorNode, dom.EventType.CLICK, () => this.model.selectNextColorPresentation())); this._register(dom.addDisposableListener(colorBox, dom.EventType.CLICK, () => { this.model.color = this.model.originalColor; this.model.flushColor(); })); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this._register(model.onDidChangePresentation(this.onDidChangePresentation, this)); this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || ''; this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter()); this.onDidChangeColor(this.model.color); } public get domNode(): HTMLElement { return this._domNode; } private onDidChangeColor(color: Color): void { this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || ''; this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter()); this.onDidChangePresentation(); } private onDidChangePresentation(): void { this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : ''; this.pickedColorNode.prepend($('.codicon.codicon-color-mode')); } } export class ColorPickerBody extends Disposable { private readonly _domNode: HTMLElement; private readonly _saturationBox: SaturationBox; private readonly _hueStrip: Strip; private readonly _opacityStrip: Strip; private readonly _insertButton: InsertButton | null = null; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number, private showingStandaloneColorPicker: boolean = false) { super(); this._domNode = $('.colorpicker-body'); dom.append(container, this._domNode); this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio); this._register(this._saturationBox); this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this)); this._register(this._saturationBox.onColorFlushed(this.flushColor, this)); this._opacityStrip = new OpacityStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._opacityStrip); this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this)); this._register(this._opacityStrip.onColorFlushed(this.flushColor, this)); this._hueStrip = new HueStrip(this._domNode, this.model, showingStandaloneColorPicker); this._register(this._hueStrip); this._register(this._hueStrip.onDidChange(this.onDidHueChange, this)); this._register(this._hueStrip.onColorFlushed(this.flushColor, this)); if (this.showingStandaloneColorPicker) { this._insertButton = new InsertButton(this._domNode); this._register(this._insertButton); } } private flushColor(): void { this.model.flushColor(); } private onDidSaturationValueChange({ s, v }: { s: number; v: number }): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a)); } private onDidOpacityChange(a: number): void { const hsva = this.model.color.hsva; this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a)); } private onDidHueChange(value: number): void { const hsva = this.model.color.hsva; const h = (1 - value) * 360; this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a)); } get domNode() { return this._domNode; } get saturationBox() { return this._saturationBox; } get opacityStrip() { return this._opacityStrip; } get hueStrip() { return this._hueStrip; } get enterButton() { return this._insertButton; } layout(): void { console.log('inside of layout of the color picker body'); this._saturationBox.layout(); this._opacityStrip.layout(); this._hueStrip.layout(); } } class SaturationBox extends Disposable { private readonly _domNode: HTMLElement; private readonly selection: HTMLElement; private readonly _canvas: HTMLCanvasElement; private width!: number; private height!: number; private monitor: GlobalPointerMoveMonitor | null; private readonly _onDidChange = new Emitter<{ s: number; v: number }>(); readonly onDidChange: Event<{ s: number; v: number }> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, private readonly model: ColorPickerModel, private pixelRatio: number) { super(); this._domNode = $('.saturation-wrap'); dom.append(container, this._domNode); // Create canvas, draw selected color this._canvas = document.createElement('canvas'); this._canvas.className = 'saturation-box'; dom.append(this._domNode, this._canvas); // Add selection circle this.selection = $('.saturation-selection'); dom.append(this._domNode, this.selection); this.layout(); this._register(dom.addDisposableListener(this._domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this._register(this.model.onDidChangeColor(this.onDidChangeColor, this)); this.monitor = null; } public get domNode() { return this._domNode; } public get canvas() { return this._canvas; } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } this.monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this._domNode); if (e.target !== this.selection) { this.onDidChangePosition(e.offsetX, e.offsetY); } this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); if (this.monitor) { this.monitor.stopMonitoring(true); this.monitor = null; } }, true); } private onDidChangePosition(left: number, top: number): void { const s = Math.max(0, Math.min(1, left / this.width)); const v = Math.max(0, Math.min(1, 1 - (top / this.height))); this.paintSelection(s, v); this._onDidChange.fire({ s, v }); } layout(): void { console.log('inside of the layout of the saturation box'); this.width = this._domNode.offsetWidth; this.height = this._domNode.offsetHeight; console.log('this.width : ', this.width); console.log('this.heigth : ', this.height); // TODO: works if hard-coding the values, need to figure out why the above is zero this._canvas.width = this.width * this.pixelRatio; this._canvas.height = this.height * this.pixelRatio; this.paint(); const hsva = this.model.color.hsva; this.paintSelection(hsva.s, hsva.v); } private paint(): void { const hsva = this.model.color.hsva; const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1)); const ctx = this._canvas.getContext('2d')!; const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0); whiteGradient.addColorStop(0, 'rgba(255, 255, 255, 1)'); whiteGradient.addColorStop(0.5, 'rgba(255, 255, 255, 0.5)'); whiteGradient.addColorStop(1, 'rgba(255, 255, 255, 0)'); const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height); blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)'); blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)'); ctx.rect(0, 0, this._canvas.width, this._canvas.height); ctx.fillStyle = Color.Format.CSS.format(saturatedColor)!; ctx.fill(); ctx.fillStyle = whiteGradient; ctx.fill(); ctx.fillStyle = blackGradient; ctx.fill(); } private paintSelection(s: number, v: number): void { this.selection.style.left = `${s * this.width}px`; this.selection.style.top = `${this.height - v * this.height}px`; } private onDidChangeColor(): void { if (this.monitor && this.monitor.isMonitoring()) { return; } this.paint(); } } abstract class Strip extends Disposable { public domNode: HTMLElement; protected overlay: HTMLElement; protected slider: HTMLElement; private height!: number; private readonly _onDidChange = new Emitter<number>(); readonly onDidChange: Event<number> = this._onDidChange.event; private readonly _onColorFlushed = new Emitter<void>(); readonly onColorFlushed: Event<void> = this._onColorFlushed.event; constructor(container: HTMLElement, protected model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(); if (showingStandaloneColorPicker) { this.domNode = dom.append(container, $('.modified-strip')); this.overlay = dom.append(this.domNode, $('.modified-overlay')); } else { this.domNode = dom.append(container, $('.strip')); this.overlay = dom.append(this.domNode, $('.overlay')); } this.slider = dom.append(this.domNode, $('.slider')); this.slider.style.top = `0px`; this._register(dom.addDisposableListener(this.domNode, dom.EventType.POINTER_DOWN, e => this.onPointerDown(e))); this.layout(); } layout(): void { console.log('inside of the layout of the strip'); this.height = this.domNode.offsetHeight - this.slider.offsetHeight; console.log('this.height : ', this.height); const value = this.getValue(this.model.color); this.updateSliderPosition(value); } private onPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const monitor = this._register(new GlobalPointerMoveMonitor()); const origin = dom.getDomNodePagePosition(this.domNode); this.domNode.classList.add('grabbing'); if (e.target !== this.slider) { this.onDidChangeTop(e.offsetY); } monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null); const pointerUpListener = dom.addDisposableListener(document, dom.EventType.POINTER_UP, () => { this._onColorFlushed.fire(); pointerUpListener.dispose(); monitor.stopMonitoring(true); this.domNode.classList.remove('grabbing'); }, true); } private onDidChangeTop(top: number): void { const value = Math.max(0, Math.min(1, 1 - (top / this.height))); this.updateSliderPosition(value); this._onDidChange.fire(value); } private updateSliderPosition(value: number): void { this.slider.style.top = `${(1 - value) * this.height}px`; } protected abstract getValue(color: Color): number; } class OpacityStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('opacity-strip'); this._register(model.onDidChangeColor(this.onDidChangeColor, this)); this.onDidChangeColor(this.model.color); } private onDidChangeColor(color: Color): void { const { r, g, b } = color.rgba; const opaque = new Color(new RGBA(r, g, b, 1)); const transparent = new Color(new RGBA(r, g, b, 0)); this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`; } protected getValue(color: Color): number { return color.hsva.a; } } class HueStrip extends Strip { constructor(container: HTMLElement, model: ColorPickerModel, showingStandaloneColorPicker: boolean = false) { super(container, model, showingStandaloneColorPicker); this.domNode.classList.add('hue-strip'); } protected getValue(color: Color): number { return 1 - (color.hsva.h / 360); } } class InsertButton extends Disposable { private _button: HTMLElement; private readonly _onClicked = this._register(new Emitter<void>()); public readonly onClicked = this._onClicked.event; constructor(container: HTMLElement) { super(); this._button = dom.append(container, document.createElement('button')); this._button.classList.add('insert-button'); this._button.textContent = 'Insert'; this._button.onclick = e => { this._onClicked.fire(); }; } } export class ColorPickerWidget extends Widget implements IEditorHoverColorPickerWidget { private static readonly ID = 'editor.contrib.colorPickerWidget'; body: ColorPickerBody; header: ColorPickerHeader; constructor(container: Node, readonly model: ColorPickerModel, private pixelRatio: number, themeService: IThemeService, standaloneColorPicker: boolean = false) { super(); this._register(PixelRatio.onDidChange(() => this.layout())); const element = $('.colorpicker-widget'); container.appendChild(element); this.header = new ColorPickerHeader(element, this.model, themeService); this.body = new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker); this._register(this.header); this._register(this.body); } getId(): string { return ColorPickerWidget.ID; } layout(): void { console.log('inside of the color picker widget layout function'); this.body.layout(); } }
src/vs/editor/contrib/colorPicker/browser/colorPickerWidget.ts
1
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.9980660080909729, 0.07747775316238403, 0.00016209293971769512, 0.00017287986702285707, 0.24772605299949646 ]
{ "id": 6, "code_window": [ "\t\t// colorPickerHeader.domNode.style.width = 600 + 'px';\n", "\t\t// colorPickerHeader.domNode.style.height = 20 + 'px';\n", "\n", "\t\tconst colorPickerBody = colorPicker?.body as ColorPickerBody;\n", "\t\tcolorPickerBody.domNode.style.background = 'red';\n", "\t\tconst saturationBox = colorPickerBody.saturationBox;\n", "\t\tconst hueStrip = colorPickerBody.hueStrip;\n", "\t\tconst opacityStrip = colorPickerBody.opacityStrip;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 218 }
{ "version": "2.0.0", "tasks": [ { "type": "npm", "script": "watch-clientd", "label": "Core - Build", "isBackground": true, "presentation": { "reveal": "never", "group": "buildWatchers", "close": false }, "problemMatcher": { "owner": "typescript", "applyTo": "closedDocuments", "fileLocation": [ "absolute" ], "pattern": { "regexp": "Error: ([^(]+)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\): (.*)$", "file": 1, "location": 2, "message": 3 }, "background": { "beginsPattern": "Starting compilation...", "endsPattern": "Finished compilation with" } } }, { "type": "npm", "script": "watch-extensionsd", "label": "Ext - Build", "isBackground": true, "presentation": { "reveal": "never", "group": "buildWatchers", "close": false }, "problemMatcher": { "owner": "typescript", "applyTo": "closedDocuments", "fileLocation": [ "absolute" ], "pattern": { "regexp": "Error: ([^(]+)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\): (.*)$", "file": 1, "location": 2, "message": 3 }, "background": { "beginsPattern": "Starting compilation", "endsPattern": "Finished compilation" } } }, { "label": "VS Code - Build", "dependsOn": [ "Core - Build", "Ext - Build" ], "group": { "kind": "build", "isDefault": true }, "problemMatcher": [] }, { "type": "npm", "script": "kill-watch-clientd", "label": "Kill Core - Build", "group": "build", "presentation": { "reveal": "never", "group": "buildKillers", "close": true }, "problemMatcher": "$tsc" }, { "type": "npm", "script": "kill-watch-extensionsd", "label": "Kill Ext - Build", "group": "build", "presentation": { "reveal": "never", "group": "buildKillers", "close": true }, "problemMatcher": "$tsc" }, { "label": "Kill VS Code - Build", "dependsOn": [ "Kill Core - Build", "Kill Ext - Build" ], "group": "build", "problemMatcher": [] }, { "label": "Restart VS Code - Build", "dependsOn": [ "Kill VS Code - Build", "VS Code - Build" ], "group": "build", "dependsOrder": "sequence", "problemMatcher": [] }, { "type": "npm", "script": "watch-webd", "label": "Web Ext - Build", "group": "build", "isBackground": true, "presentation": { "reveal": "never" }, "problemMatcher": { "owner": "typescript", "applyTo": "closedDocuments", "fileLocation": [ "absolute" ], "pattern": { "regexp": "Error: ([^(]+)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\): (.*)$", "file": 1, "location": 2, "message": 3 }, "background": { "beginsPattern": "Starting compilation", "endsPattern": "Finished compilation" } } }, { "type": "npm", "script": "kill-watch-webd", "label": "Kill Web Ext - Build", "group": "build", "presentation": { "reveal": "never" }, "problemMatcher": "$tsc" }, { "label": "Run tests", "type": "shell", "command": "./scripts/test.sh", "windows": { "command": ".\\scripts\\test.bat" }, "group": "test", "presentation": { "echo": true, "reveal": "always" } }, { "label": "Run Dev", "type": "shell", "command": "./scripts/code.sh", "windows": { "command": ".\\scripts\\code.bat" }, "problemMatcher": [] }, { "type": "npm", "script": "electron", "label": "Download electron" }, { "type": "gulp", "task": "hygiene", "problemMatcher": [] }, { "type": "shell", "command": "./scripts/code-server.sh", "windows": { "command": ".\\scripts\\code-server.bat" }, "args": ["--no-launch", "--connection-token", "dev-token", "--port", "8080"], "label": "Run code server", "isBackground": true, "problemMatcher": { "pattern": { "regexp": "" }, "background": { "beginsPattern": ".*node .*", "endsPattern": "Web UI available at .*" } }, "presentation": { "reveal": "never" } }, { "type": "shell", "command": "./scripts/code-web.sh", "windows": { "command": ".\\scripts\\code-web.bat" }, "args": ["--port", "8080", "--browser", "none"], "label": "Run code web", "isBackground": true, "problemMatcher": { "pattern": { "regexp": "" }, "background": { "beginsPattern": ".*node .*", "endsPattern": "Listening on .*" } }, "presentation": { "reveal": "never" } }, { "type": "npm", "script": "eslint", "problemMatcher": { "source": "eslint", "base": "$eslint-stylish" } }, { "type": "shell", "command": "node build/lib/preLaunch.js", "label": "Ensure Prelaunch Dependencies", "presentation": { "reveal": "silent", "close": true } }, { "type": "npm", "script": "tsec-compile-check", "problemMatcher": [ { "base": "$tsc", "applyTo": "allDocuments", "owner": "tsec" } ], "group": "build", "label": "npm: tsec-compile-check", "detail": "node_modules/tsec/bin/tsec -p src/tsconfig.json --noEmit" }, { // Used for monaco editor playground launch config "label": "Launch Http Server", "type": "shell", "command": "node_modules/.bin/http-server --cors --port 5001 -a 127.0.0.1 -c-1 -s", "isBackground": true, "problemMatcher": { "pattern": { "regexp": "" }, "background": { "activeOnStart": true, "beginsPattern": "never match", "endsPattern": ".*" } }, "dependsOn": [ "Core - Build" ] } ] }
.vscode/tasks.json
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017645684420131147, 0.0001737911079544574, 0.0001708260242594406, 0.0001739692670525983, 0.0000014513162795992685 ]