Compare commits

...
Author SHA1 Message Date
l0ng-ai 7dee96dc64 fix(docker): show container logs, processes and image layers without the docker CLI
Connections reached through the Engine API (an SSH tunnel, a socket or a
TCP daemon) still ran `docker logs`, `docker top` and `docker image
history`, so on a machine without the docker CLI the Log and Processes
tabs and an image's layers failed. They now come from the Engine API
when the CLI is missing: the log streams and follows over its own
connection, undoing the chunked encoding and the per-stream frames (or a
TTY container's raw stream), and stops when the request is cancelled.
2026-11-20 11:45:38 +08:00
l0ng-ai 9293b13737 feat(vcs): show the Rollback Changes files as a checkable tree (#4684)
Rollback Changes listed the files flat. It now uses the checkable change tree of the Shelve and Create Patch dialogs: files grouped by directory under the repository, with tri-state boxes on repository and directory rows; the summary follows the selection.
2026-11-20 11:45:27 +08:00
l0ng-ai d1f79d05b3 fix(project-tree): add Manage Remotes and Clone to the Project view's Git menu (#4680)
The Project view's Git submenu stopped at Stash / Unstash; it now ends with Manage Remotes… and Clone…, like the editor's Git submenu and IDEA's Git context menu. Covered by a new e2e test in editorGitMenu.spec.ts.
2026-11-20 11:39:28 +08:00
l0ng-ai 176c43c908 fix(editor): make the paste history preview resizable (#4677)
Paste from History gives the preview more room by default and remembers the divider position (a resizable split). Delete moves beside the filter as a toolbar button; the snippets and preview use the active editor's font and zoom, and the preview drops line numbers to use its full width.
2026-11-20 11:33:27 +08:00
Nc 20b6b0aed5 fix(maven): sort sidebar profiles by ID (#4679)
The Maven sidebar listed profiles in model order. Profiles within each project group now sort by ID ignoring case, as IntelliJ's Maven tool window does; the -P argument keeps the model order.

Co-authored-by: qiany-sui <[email protected]>
2026-11-20 11:30:31 +08:00
l0ng-ai 101a0862e4 fix(database): reconnect a custom JDBC data source whose session was lost (#4675)
When a proxy or tunnel dropped an idle custom JDBC connection, every later statement failed and the source still showed Connected: the cached pool was only marked closed when the IDE closed it. After a failed statement the bridge now checks Connection.isValid (new valid op); an invalid or orphaned session closes the pool so the next statement or Connect reconnects. Keep-alive for JDBC uses the same check (and its option shows in the dialog); failures log at info.
2026-11-20 11:29:35 +08:00
Bin b48f0b6071 fix(vcs): enlarge deleted line marker hit area (#4669)
The deleted-lines marker is drawn above its gutter row, but clicks were resolved from the pointer's row, so clicking the triangle near the line boundary could miss the deletion. The marker gets a 12x12 transparent hit area (same triangle) with a pointer cursor, and clicks on it resolve to the deletion's row. Verified with vcs hunks and editor cm vitest, typecheck, and in the app (clicking the marker's upper half opens the Deleted lines popup).

Co-authored-by: ffgenius <[email protected]>
2026-11-20 11:23:37 +08:00
l0ng-ai a9b16c3e06 fix(debugger): keep call stack locations visible in narrow docks (#4671)
Call stack locations stay visible in narrow debug docks. Verified with e2e debugStackLayout, debugger vitest and typecheck.
2026-11-20 11:13:32 +08:00
28 changed files with 929 additions and 135 deletions

No files matched your search

+8
View File
@@ -749,6 +749,14 @@ impl Pool {
}
/// The keep-alive ping (Oracle needs a FROM clause).
/// Keep-alive: one cheap round trip on the session.
pub async fn ping(&self) -> IdeResult<()> {
match self {
Pool::Jdbc(p) => p.ping().await,
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
}
}
pub fn ping_sql(&self) -> &'static str {
match self {
Pool::Oracle(_) => "SELECT 1 FROM DUAL",
+38
View File
@@ -458,6 +458,44 @@ impl JdbcPool {
}
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let result = self.exchange_once(fields, sql, cancel).await;
if let Err(e) = &result
&& fields.first() != Some(&"open")
&& e.kind != ide_core::error::ErrorKind::Cancelled
&& !self.is_closed()
&& !self.session_valid().await
{
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
// pool so the next statement or Connect starts a new one instead of failing forever.
self.close().await;
}
result
}
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
pub(crate) async fn ping(&self) -> IdeResult<()> {
if self.session_valid().await {
return Ok(());
}
self.close().await;
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
}
/// Whether the JDBC session still works, asked after a failed statement.
async fn session_valid(&self) -> bool {
if self.bridge.lock().await.is_none() {
return false;
}
let cancel = CancellationToken::new();
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
Ok(Ok(result)) => {
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
}
Ok(Err(_)) | Err(_) => false,
}
}
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
let mut slot = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
+12 -7
View File
@@ -379,8 +379,8 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
loop {
tick.tick().await;
let Some(p) = pool.upgrade().filter(|p| !p.is_closed()) else { break };
if let Err(e) = p.rows(p.ping_sql(), 1).await {
tracing::debug!("keep-alive: {}", e.message);
if let Err(e) = p.ping().await {
tracing::info!("keep-alive: {}", e.message);
}
}
});
@@ -847,12 +847,12 @@ impl DbManager {
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().contains_key(id)
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().keys().cloned().collect()
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
@@ -862,8 +862,13 @@ impl DbManager {
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
if let Some(p) = self.pools.lock().get(id) {
return Ok(p.clone());
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
@@ -917,7 +922,7 @@ impl DbManager {
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.connected().into_iter().filter(|t| split_target(t).0 == id).collect();
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
+33
View File
@@ -213,3 +213,36 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
db.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires JDBC_FIXTURE_JAR (java/jdbc-bridge/build.py --test --out fixture.jar) and Java 17+"]
async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
db.save_jdbc_driver(DbJdbcDriver {
id: "fixture".into(),
name: "Fixture".into(),
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
url_template: String::new(),
})?;
let source = DataSource {
id: "test".into(),
name: "Fixture".into(),
driver: DbDriver::Jdbc,
global: true,
jdbc_driver: "fixture".into(),
url: "jdbc:fixture:".into(),
..Default::default()
};
db.save_sources(vec![source]).await?;
let cancel = CancellationToken::new();
db.execute("test", "first", 1, &cancel).await?;
// The fixture's session reports itself invalid after "drop", like a connection a proxy reset.
assert!(db.execute("test", "drop", 1, &cancel).await.unwrap_err().message.contains("connection reset"));
assert!(!db.is_connected("test"), "a lost session is no longer listed as connected");
assert_eq!(db.execute("test", "after reconnect", 1, &cancel).await?.affected, Some(1.0));
assert!(db.is_connected("test"));
db.disconnect("test").await;
Ok(())
}
+382 -9
View File
@@ -7,9 +7,10 @@
use crate::{
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
DockerEndpoint, DockerImage, DockerNetwork, DockerObject, DockerSnapshot, DockerVolume, split_csv,
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
DockerSnapshot, DockerVolume, split_csv,
};
use ide_core::{IdeError, IdeResult};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::{Read, Write};
@@ -193,9 +194,15 @@ fn request(addr: &Address, method: &str, path: &str, timeout: Duration) -> IdeRe
read_response(&mut conn)
}
/// Reads an HTTP/1.1 response: head until `\r\n\r\n`, then the body per its
/// framing (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
/// A response's status line and body framing.
struct Head {
status: u16,
chunked: bool,
length: Option<usize>,
}
/// Reads an HTTP/1.1 response head until `\r\n\r\n`.
fn read_head(stream: &mut impl Read) -> IdeResult<Head> {
let mut head: Vec<u8> = Vec::new();
let mut byte = [0u8; 1];
loop {
@@ -228,16 +235,27 @@ fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
length = value.parse().ok();
}
}
let body = if chunked {
Ok(Head { status, chunked, length })
}
/// Reads an HTTP/1.1 response: its head, then the body per its framing
/// (chunked, `Content-Length`, or until the connection closes).
fn read_response(stream: &mut impl Read) -> IdeResult<Response> {
let head = read_head(stream)?;
let body = read_body(stream, &head)?;
Ok(Response { status: head.status, body })
}
fn read_body(stream: &mut impl Read, head: &Head) -> IdeResult<Vec<u8>> {
Ok(if head.chunked {
read_chunked(stream)?
} else if let Some(n) = length {
} else if let Some(n) = head.length {
read_exact_n(stream, n)?
} else {
let mut body = Vec::new();
stream.read_to_end(&mut body)?;
body
};
Ok(Response { status, body })
})
}
/// Reads one `\n`-terminated line (returned without it).
@@ -482,6 +500,292 @@ pub(crate) fn inspect(
})())
}
/// The processes running in a container (`docker top`).
pub(crate) fn container_top(ep: &DockerEndpoint, id: &str, timeout: Duration) -> Option<IdeResult<DockerProcessList>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/containers/{}/top", path_segment(id)), timeout)?)?;
serde_json::from_str::<ApiTop>(&body)
.map(|t| DockerProcessList { titles: t.titles, processes: t.processes })
.map_err(|e| IdeError::internal(format!("the Docker daemon's process list is not JSON: {e}")))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiTop {
titles: Vec<String>,
processes: Vec<Vec<String>>,
}
/// An image's layers, newest first (`docker image history`).
pub(crate) fn image_history(
ep: &DockerEndpoint,
id: &str,
timeout: Duration,
) -> Option<IdeResult<Vec<DockerImageLayer>>> {
let addr = address(ep)?;
Some((|| {
let body = check(request(&addr, "GET", &format!("/images/{}/history", path_segment(id)), timeout)?)?;
let layers = serde_json::from_str::<Vec<ApiLayer>>(&body)
.map_err(|e| IdeError::internal(format!("the Docker daemon's image history is not JSON: {e}")))?;
Ok(map_layers(layers, unix_now()))
})())
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiLayer {
id: String,
created: i64,
created_by: String,
size: i64,
comment: String,
}
fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
layers
.into_iter()
.map(|l| DockerImageLayer {
id: l.id,
created_by: l.created_by,
size: human_size(l.size),
created_since: human_duration((now - l.created).max(0)),
created_at: unix_utc(l.created),
comment: l.comment,
})
.collect()
}
fn unix_now() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
}
/// How often a log stream that has nothing to read checks for cancellation.
const LOG_POLL: Duration = Duration::from_millis(200);
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerInspect {
config: ApiContainerConfig,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase", default)]
struct ApiContainerConfig {
tty: bool,
}
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
/// from `ep`'s daemon until they end or `cancel` fires.
#[allow(clippy::too_many_arguments)]
pub(crate) fn logs(
ep: &DockerEndpoint,
id: &str,
tail: u32,
follow: bool,
timestamps: bool,
timeout: Duration,
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> Option<IdeResult<()>> {
let addr = address(ep)?;
Some((|| {
// A TTY container's log is one raw stream; otherwise it is framed per stream.
let body = check(request(&addr, "GET", &format!("/containers/{}/json", path_segment(id)), timeout)?)?;
let tty = serde_json::from_str::<ApiContainerInspect>(&body).map(|c| c.config.tty).unwrap_or(false);
let path = format!(
"/containers/{}/logs?stdout=1&stderr=1&tail={tail}&follow={}&timestamps={}",
path_segment(id),
u8::from(follow),
u8::from(timestamps),
);
let mut conn = Conn::connect(&addr, timeout)?;
conn.write_all(
format!("GET {path} HTTP/1.1\r\nHost: docker\r\nUser-Agent: openidea\r\nConnection: close\r\n\r\n")
.as_bytes(),
)?;
let head = read_head(&mut conn)?;
if !(200..300).contains(&head.status) {
let body = read_body(&mut conn, &head)?;
check(Response { status: head.status, body })?;
}
conn.set_timeouts(LOG_POLL);
let mut decoder = LogDecoder::new(&head, tty);
let mut buf = [0u8; 8192];
while !decoder.done() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
match conn.read(&mut buf) {
Ok(0) => break,
Ok(n) => decoder.feed(&buf[..n], &mut |line| on_line(line))?,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e.into()),
}
}
decoder.finish(&mut |line| on_line(line));
Ok(())
})())
}
/// Turns a log response body, as it arrives, into lines: undoes the chunked
/// transfer encoding, then the per-stream frames (8-byte header: stream, 3 zero
/// bytes, big-endian length) unless the container has a TTY.
struct LogDecoder {
body: BodyFraming,
tty: bool,
header: Vec<u8>,
frame_left: usize,
frame_stderr: bool,
/// Partial lines of stdout and stderr.
partial: [Vec<u8>; 2],
}
enum BodyFraming {
Chunked { state: ChunkState, line: Vec<u8> },
Length(usize),
Close,
}
#[derive(Clone, Copy, PartialEq)]
enum ChunkState {
Size,
Data(usize),
DataEnd,
Trailer,
Done,
}
impl LogDecoder {
fn new(head: &Head, tty: bool) -> Self {
let body = if head.chunked {
BodyFraming::Chunked { state: ChunkState::Size, line: Vec::new() }
} else if let Some(n) = head.length {
BodyFraming::Length(n)
} else {
BodyFraming::Close
};
Self { body, tty, header: Vec::new(), frame_left: 0, frame_stderr: false, partial: [Vec::new(), Vec::new()] }
}
fn done(&self) -> bool {
matches!(self.body, BodyFraming::Chunked { state: ChunkState::Done, .. } | BodyFraming::Length(0))
}
fn feed(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) -> IdeResult<()> {
let mut payload = Vec::new();
match &mut self.body {
BodyFraming::Close => payload.extend_from_slice(bytes),
BodyFraming::Length(left) => {
let take = (*left).min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
*left -= take;
}
BodyFraming::Chunked { state, line } => {
while !bytes.is_empty() {
match *state {
ChunkState::Done => break,
ChunkState::Data(n) => {
let take = n.min(bytes.len());
payload.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
*state = if take == n { ChunkState::DataEnd } else { ChunkState::Data(n - take) };
}
_ => {
let b = bytes[0];
bytes = &bytes[1..];
if b != b'\n' {
if b != b'\r' {
line.push(b);
}
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
*state = match *state {
ChunkState::Size => {
let size = text.split(';').next().unwrap_or_default().trim();
match usize::from_str_radix(size, 16) {
Ok(0) => ChunkState::Trailer,
Ok(n) => ChunkState::Data(n),
Err(_) => {
return Err(IdeError::internal(
"the Docker daemon answered with a malformed chunked response",
));
}
}
}
ChunkState::DataEnd => ChunkState::Size,
_ if text.is_empty() => ChunkState::Done,
other => other,
};
}
}
}
}
}
self.frames(&payload, emit);
Ok(())
}
fn frames(&mut self, mut bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
if self.tty {
self.lines(false, bytes, emit);
return;
}
while !bytes.is_empty() {
if self.frame_left == 0 {
let take = (8 - self.header.len()).min(bytes.len());
self.header.extend_from_slice(&bytes[..take]);
bytes = &bytes[take..];
if self.header.len() == 8 {
self.frame_stderr = self.header[0] == 2;
self.frame_left =
u32::from_be_bytes([self.header[4], self.header[5], self.header[6], self.header[7]]) as usize;
self.header.clear();
}
continue;
}
let take = self.frame_left.min(bytes.len());
self.lines(self.frame_stderr, &bytes[..take], emit);
self.frame_left -= take;
bytes = &bytes[take..];
}
}
fn lines(&mut self, stderr: bool, bytes: &[u8], emit: &mut dyn FnMut(DockerLogLine)) {
let partial = &mut self.partial[usize::from(stderr)];
for &b in bytes {
if b == b'\n' {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
} else {
partial.push(b);
}
}
}
/// Emits the last lines that ended without a newline.
fn finish(&mut self, emit: &mut dyn FnMut(DockerLogLine)) {
for stderr in [false, true] {
let partial = &mut self.partial[usize::from(stderr)];
if !partial.is_empty() {
emit(DockerLogLine { stderr, text: line_text(partial) });
partial.clear();
}
}
}
}
fn line_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes.strip_suffix(b"\r").unwrap_or(bytes)).into_owned()
}
/// One URL path segment, percent-encoded so an id cannot change the path.
fn path_segment(id: &str) -> String {
let mut out = String::with_capacity(id.len());
@@ -817,6 +1121,75 @@ mod tests {
assert!(read_response(&mut &garbage[..]).is_err());
}
/// Feeds `body` one byte at a time, as a slow connection delivers it.
fn decode(head: Head, tty: bool, body: &[u8]) -> (Vec<(bool, String)>, bool) {
let mut lines = Vec::new();
let mut decoder = LogDecoder::new(&head, tty);
for b in body {
decoder.feed(std::slice::from_ref(b), &mut |l| lines.push((l.stderr, l.text))).unwrap();
}
let done = decoder.done();
decoder.finish(&mut |l| lines.push((l.stderr, l.text)));
(lines, done)
}
fn frame(stream: u8, text: &str) -> Vec<u8> {
let mut f = vec![stream, 0, 0, 0];
f.extend((text.len() as u32).to_be_bytes());
f.extend(text.as_bytes());
f
}
#[test]
fn engine_image_history_reads_like_the_cli() {
let layers: Vec<ApiLayer> = serde_json::from_str(
r#"[{"Id":"sha256:abc","Created":1000,"CreatedBy":"CMD [\"python3\"]","Size":20500,"Comment":"buildkit","Tags":["py:3"]},
{"Id":"<missing>","Created":940,"CreatedBy":"RUN x","Size":0,"Comment":""}]"#,
)
.unwrap();
let rows = map_layers(layers, 1000 + 2 * 7 * 86_400);
assert_eq!(
rows.iter().map(|l| (l.id.as_str(), l.size.as_str(), l.created_since.as_str())).collect::<Vec<_>>(),
[("sha256:abc", "20.5kB", "2 weeks ago"), ("<missing>", "0B", "2 weeks ago")]
);
assert_eq!(rows[0].created_by, "CMD [\"python3\"]");
let top: ApiTop = serde_json::from_str(r#"{"Titles":["PID","CMD"],"Processes":[["1","sh"]]}"#).unwrap();
assert_eq!(
(top.titles, top.processes),
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
);
}
#[test]
fn container_logs_split_into_stream_lines_across_chunks_and_frames() {
// Frames split mid-line, a CRLF line, and a stderr line between stdout parts.
let mut framed = frame(1, "tick 1\r\ntick");
framed.extend(frame(2, "oops\n"));
framed.extend(frame(1, " 2\nlast"));
let mut chunked = Vec::new();
for part in framed.chunks(7) {
chunked.extend(format!("{:x}\r\n", part.len()).as_bytes());
chunked.extend(part);
chunked.extend(b"\r\n");
}
chunked.extend(b"0\r\n\r\n");
let (lines, done) = decode(Head { status: 200, chunked: true, length: None }, false, &chunked);
assert!(done);
let expected = [(false, "tick 1"), (true, "oops"), (false, "tick 2"), (false, "last")];
assert_eq!(lines, expected.map(|(e, t)| (e, t.to_owned())));
// A TTY container's log is one raw stream; the body may end with the connection.
let (lines, done) = decode(Head { status: 200, chunked: false, length: None }, true, b"a\r\nb\n");
assert!(!done);
assert_eq!(lines, [(false, "a".to_owned()), (false, "b".to_owned())]);
// A Content-Length body ends after its length.
let body = frame(1, "one\n");
let (lines, done) = decode(Head { status: 200, chunked: false, length: Some(body.len()) }, false, &body);
assert!(done);
assert_eq!(lines, [(false, "one".to_owned())]);
}
#[test]
fn daemon_errors_carry_their_message() {
let resp = Response { status: 404, body: br#"{"message":"No such container: missing"}"#.to_vec() };
+15
View File
@@ -287,6 +287,11 @@ fn check_id(id: &str) -> IdeResult<&str> {
/// `docker image history --no-trunc --format '{{json .}}'` of one image.
pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImageLayer>> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(layers) = engine::image_history(ep, id, QUICK)
{
return layers;
}
let out = run(ep, &["image", "history", "--no-trunc", "--format", "{{json .}}", id], QUICK)?;
Ok(parse_image_history(&out))
}
@@ -294,6 +299,11 @@ pub fn image_history(ep: &DockerEndpoint, id: &str) -> IdeResult<Vec<DockerImage
/// `docker top <id>` of a running container.
pub fn container_top(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerProcessList> {
let id = check_id(id)?;
if docker_executable().is_none()
&& let Some(processes) = engine::container_top(ep, id, QUICK)
{
return processes;
}
let out = run(ep, &["top", id], QUICK)?;
Ok(parse_container_top(&out))
}
@@ -316,6 +326,11 @@ pub fn logs(
cancel: &CancellationToken,
on_line: &dyn Fn(DockerLogLine),
) -> IdeResult<()> {
if docker_executable().is_none()
&& let Some(streamed) = engine::logs(ep, id, tail, follow, timestamps, QUICK, cancel, on_line)
{
return streamed;
}
let tail = tail.to_string();
let mut args = vec!["logs", "--tail", &tail];
if follow {
+75
View File
@@ -0,0 +1,75 @@
import { expect, stubDesktop, test } from "./fixtures";
const functionName = "calculateRegionalSettlementFromExternalOrderBeforeReconciliation";
const sourcePath = "/dev/acme-api/build.gradle.kts";
test("keeps frame sources and the keyboard selection visible in a narrow debug dock", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 540 });
await stubDesktop(page);
await page.evaluate(
async ({ functionName, sourcePath }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const workerFrame = {
id: 51,
name: "processOrder",
path: sourcePath,
line: 5,
column: 0,
presentationHint: null,
};
window.__ipc.handlers.debug_scopes = () => [];
window.__ipc.handlers.debug_stack_trace = () => [workerFrame];
adoptSession(91, {
name: "Reconciliation",
adapter: "debugpy",
status: "paused",
stoppedThread: 1,
selectedThread: 1,
threads: [
{ id: 1, name: "MainThread" },
{ id: 2, name: "Order worker" },
],
selectedFrame: 1,
frames: Array.from({ length: 32 }, (_, index) => ({
id: index + 1,
name: index === 0 ? functionName : index === 1 ? "runBatch" : `reconcile(${index})`,
path: sourcePath,
line: index === 0 ? 41 : index,
column: 0,
presentationHint: null,
})),
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 420);
toolWindowService().show("debug", true);
},
{ functionName, sourcePath },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const thread = debug.getByRole("button", { name: "Thread", exact: true });
const frames = debug.getByRole("listbox", { name: "Frames", exact: true });
const first = frames.getByRole("option", { selected: true });
await expect(first.getByText(functionName, { exact: true })).toBeVisible();
expect(await frames.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(first.getByText(":42", { exact: true })).toBeInViewport({ ratio: 1 });
expect(await first.getByText(/build\.gradle\.kts/).evaluate((el) => el.clientWidth)).toBeGreaterThan(25);
const shortName = frames.getByText("runBatch", { exact: true });
expect(await shortName.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await frames.focus();
for (let i = 0; i < 25; i++) await page.keyboard.press("ArrowDown");
const selected = frames.getByRole("option", { selected: true });
await expect(selected.getByText("reconcile(25)", { exact: true })).toBeInViewport({ ratio: 0.95 });
expect(await frames.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await thread.click();
await page.getByRole("option", { name: "Order worker", exact: true }).click();
await expect(thread).toContainText("Order worker");
await expect(frames.getByRole("option", { selected: true })).toContainText("processOrder");
});
+12
View File
@@ -64,3 +64,15 @@ test("editor Git submenu keeps repository actions disabled without Git", async (
}
await expect(page.getByRole("menuitem", { name: "Clone…", exact: true })).toBeEnabled();
});
test("Project view Git submenu ends with Manage Remotes and Clone", async ({ workbench: page }) => {
await page.getByRole("treeitem", { name: /README\.md/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
const git = page.getByRole("menu").filter({ has: page.getByRole("menuitem", { name: "Clone…", exact: true }) });
const items = git.locator('[role="menuitem"], [role="menuitemcheckbox"]');
await expect(items.nth(-3)).toHaveText(/Unstash Changes…/);
await expect(items.nth(-2)).toHaveText(/Manage Remotes…/);
await expect(items.nth(-1)).toHaveText(/Clone…/);
await git.getByRole("menuitem", { name: "Manage Remotes…", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Git Remotes" })).toBeVisible();
});
+59
View File
@@ -0,0 +1,59 @@
import { expect, openFromTree, test } from "./fixtures";
test("Paste from History keeps the list and preview usable in a short dialog", async ({ workbench: page }) => {
const editor = await openFromTree(page, "App.tsx");
const content = editor.locator(".cm-content");
await content.focus();
const baseFont = Number.parseFloat(await content.evaluate((el) => getComputedStyle(el).fontSize));
await page.evaluate(async () => {
const source = await (await fetch("/src/editor/core/extras.ts")).text();
const imports = [...source.matchAll(/["'](\/src\/[^"']+)["']/g)].map((match) => match[1]!);
const activePath = (path: string) => imports.find((url) => url.split("?")[0] === path) ?? path;
const historyPath = activePath("/src/editor/core/clipboardHistory.ts");
const actionsPath = activePath("/src/platform/actions.ts");
const { recordClipboard } = await import(/* @vite-ignore */ historyPath);
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
recordClipboard("const older = 2;");
recordClipboard("const newest = 1;\n// paste marker");
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: async () => {} } });
for (let i = 0; i < 5; i++) await executeAction("editor.increaseFontSize");
});
const fontSize = `${baseFont + 5}px`;
await expect(content).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+Shift+v");
const dialog = page.getByRole("dialog", { name: "Choose Content to Paste" });
const divider = dialog.getByRole("separator", { name: "Resize paste preview" });
const list = dialog.getByRole("listbox", { name: "Clipboard history" });
const preview = dialog.getByLabel("Paste preview", { exact: true });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
await expect(list.getByText("const newest = 1;", { exact: true })).toHaveCSS("font-size", fontSize);
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(dialog.locator(".cm-gutters")).toHaveCount(0);
await page.setViewportSize({ width: 420, height: 440 });
const search = dialog.getByRole("textbox", { name: "Filter clipboard history" });
const remove = dialog.getByRole("button", { name: "Delete" });
await expect(search).toBeInViewport({ ratio: 1 });
await expect(remove).toBeInViewport({ ratio: 1 });
expect((await remove.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
const previous = Number(await divider.getAttribute("aria-valuenow"));
await divider.press("ArrowDown");
await expect.poll(async () => Number(await divider.getAttribute("aria-valuenow"))).toBeGreaterThan(previous);
const resized = await divider.getAttribute("aria-valuenow");
await expect(dialog.getByRole("button", { name: "Paste" })).toBeInViewport({ ratio: 1 });
await expect(preview).toContainText("// paste marker");
await search.fill("older");
await remove.click();
await expect(dialog.getByText("No matches", { exact: true })).toBeVisible();
await dialog.getByRole("button", { name: "Clear", exact: true }).click();
await expect(search).toHaveValue("");
await search.press("Enter");
await expect(dialog).toBeHidden();
await expect(content).toContainText("const newest = 1;");
await page.keyboard.press("Meta+Shift+v");
await expect(divider).toHaveAttribute("aria-valuenow", resized!);
await page.keyboard.press("Escape");
});
Binary file not shown.
@@ -243,6 +243,20 @@ public final class OpenIdeaJdbc {
} catch (SQLException | AbstractMethodError ignored) {}
row(reply, name);
}
case "valid" -> {
// After a failed statement: whether the session survived (a dropped TCP
// connection leaves every later statement failing until the IDE reconnects).
header(reply, "valid");
boolean valid;
try {
valid = connection != null && !connection.isClosed() && connection.isValid(5);
} catch (AbstractMethodError | SQLFeatureNotSupportedException e) {
valid = true; // A pre-JDBC 4 driver cannot tell: keep the session.
} catch (SQLException e) {
valid = false;
}
row(reply, Boolean.toString(valid));
}
case "page" -> execute(work, a, reply, true);
case "query" -> {
if (a.size() == 3 || a.get(3).isEmpty()) {
+10
View File
@@ -14,6 +14,7 @@ import java.util.logging.Logger;
public class SelfTest {
public static class Fixture implements Driver {
private boolean readonly;
private boolean dropped;
private int changes;
private Path started;
@@ -36,6 +37,8 @@ public class SelfTest {
case "getMetaData" -> meta;
case "close" -> null;
case "createStatement" -> statement();
case "isClosed" -> false;
case "isValid" -> !dropped;
default -> throw new SQLFeatureNotSupportedException();
});
}
@@ -53,6 +56,7 @@ public class SelfTest {
throw new SQLException("statement cancelled");
}
if (sql.equals("write") && readonly) throw new SQLException("read-only");
if (sql.equals("drop")) { dropped = true; throw new SQLException("connection reset"); }
changes++;
yield false;
}
@@ -122,6 +126,12 @@ public class SelfTest {
send(out, 5, "query", "after cancel", "0", "2");
var result = reply(in);
assert result[0] == 1 && result[result.length - 1] == 2;
send(out, 6, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("true");
send(out, 7, "query", "drop", "0", "2");
assert reply(in)[0] == 0;
send(out, 8, "valid");
assert new String(reply(in), StandardCharsets.UTF_8).contains("false");
} finally {
child.destroyForcibly().waitFor();
}
+12 -3
View File
@@ -276,14 +276,23 @@ export const openideaTheme = EditorView.theme({
},
".cm-openidea-laneDeleted": {
position: "absolute",
left: "0",
top: "-3px",
left: "-4px",
top: "-6px",
width: "12px",
height: "12px",
cursor: "pointer",
zIndex: "1",
},
".cm-openidea-laneDeleted::after": {
content: '""',
position: "absolute",
left: "4px",
top: "3px",
width: "0",
height: "0",
borderTop: "3px solid transparent",
borderBottom: "3px solid transparent",
borderLeft: "6px solid var(--lane-color)",
zIndex: "1",
},
".cm-foldGutter": { width: "16px" },
".cm-foldGutter .cm-gutterElement": {
@@ -11,15 +11,37 @@
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
flex: 1;
min-height: 0;
padding: var(--space-3);
}
.split {
flex: 1;
}
.history {
display: flex;
flex-direction: column;
gap: var(--space-1);
height: 100%;
min-height: 0;
padding-bottom: var(--space-2);
}
.toolbar {
display: flex;
flex: none;
align-items: center;
gap: var(--space-2);
}
.filter {
flex: 1;
}
.list {
flex: 2;
min-height: 84px;
flex: 1;
}
.label {
@@ -27,7 +49,9 @@
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
font-family: var(--paste-history-font-family, var(--font-mono));
font-size: var(--paste-history-font-size, var(--fs-code));
font-weight: var(--paste-history-font-weight, normal);
}
.detail {
@@ -36,8 +60,12 @@
font-size: var(--fs-small);
}
.previewPanel {
padding-top: var(--space-2);
}
.preview {
flex: 3;
height: 100%;
min-height: 0;
overflow: hidden;
border: 1px solid var(--border-strong);
+65 -40
View File
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { create } from "zustand";
import { EditorState } from "@codemirror/state";
import { EditorView, highlightSpecialChars, lineNumbers } from "@codemirror/view";
import { EditorView, highlightSpecialChars } from "@codemirror/view";
import { language, syntaxHighlighting } from "@codemirror/language";
import { tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
@@ -9,11 +9,14 @@ import { executeAction, registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { bindingsFor, normalizeBinding, strokeOf } from "@/platform/keymap";
import {
Button,
Dialog,
IconButton,
List,
SearchField,
SINGLE_FIRST,
SplitGroup,
SplitHandle,
SplitPanel,
T,
isRowSelected,
listNavigate,
@@ -22,9 +25,11 @@ import {
selectableText,
selectedRows,
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import { clipLabel, clipboardHistory, removeClipboardEntries } from "../clipboardHistory";
import { openideaHighlightStyle } from "../cm/highlight";
import { compartments } from "../cm/setup";
import { fontZoom } from "../cm/prefs";
import { openideaTheme } from "../cm/theme";
import styles from "./PasteHistoryDialog.module.css";
@@ -82,6 +87,11 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
const [entries, setEntries] = useState(clipboardHistory);
const [query, setQuery] = useState("");
const [selection, setSelection] = useState(SINGLE_FIRST);
const [editorFont] = useState(() => {
const { fontFamily, fontSize, fontWeight } = getComputedStyle(view.contentDOM);
return { fontFamily, fontSize, fontWeight };
});
const rowHeight = Math.max(useRowHeight(), Math.ceil(Number.parseFloat(editorFont.fontSize) || 0) + 8);
const search = useRef<HTMLInputElement>(null);
const rows = entries
.filter(({ text }) => text.toLocaleLowerCase().includes(query.toLocaleLowerCase()))
@@ -156,7 +166,7 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
title="Choose Content to Paste"
onClose={onClose}
className={styles.dialog}
width={680}
width={560}
resizable="both"
minWidth={360}
minHeight={320}
@@ -169,48 +179,63 @@ function PasteHistoryDialog({ view, paste, onClose }: Request & { onClose: () =>
},
{ label: "Cancel", role: "cancel" },
]}
footerStart={
<Button disabled={!selected.length} onClick={runRemove}>
<T>Delete</T>
</Button>
}
>
<div
className={styles.body}
style={
{
"--paste-history-font-family": editorFont.fontFamily,
"--paste-history-font-size": editorFont.fontSize,
"--paste-history-font-weight": editorFont.fontWeight,
} as CSSProperties
}
onKeyDown={onKeyDown}
onFocusCapture={(e) => setContext("pasteHistoryListFocus", !!e.target.closest('[role="listbox"]'))}
onBlurCapture={() => setContext("pasteHistoryListFocus", false)}
>
<SearchField
ref={search}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={28}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
<PastePreview source={view} text={preview} />
<SplitGroup orientation="vertical" storageKey="openidea.editor.pasteHistory" className={styles.split}>
<SplitPanel id="clipboard" defaultSize="30%" minSize="96px">
<div className={styles.history}>
<div className={styles.toolbar}>
<IconButton icon="minus" size="small" title="Delete" disabled={!selected.length} onClick={runRemove} />
<SearchField
ref={search}
className={styles.filter}
data-autofocus=""
aria-label="Filter clipboard history"
placeholder="Filter clipboard history"
value={query}
onChange={filter}
/>
</div>
<List
items={rows}
getKey={(row) => row.key}
activeIndex={selection.lead}
onSelect={(index, e) => setSelection(selectRow(rows, selection, index, rowSelectionMode(e)))}
isSelected={(row) => isRowSelected(selection, row.key)}
onActivate={(row, _index, e) => {
if (e.type === "keydown") runPaste();
else if (e.detail === 2) runPaste(row.key);
}}
rowHeight={rowHeight}
className={styles.list}
aria-label={tx("Clipboard history")}
empty={<T>{entries.length ? "No matches" : "Nothing to paste: the clipboard history is empty"}</T>}
renderItem={(row) => (
<>
<span className={styles.label}>{row.label}</span>
<span className={styles.detail}>{row.detail ?? tx("1 line")}</span>
</>
)}
/>
</div>
</SplitPanel>
<SplitHandle aria-label={tx("Resize paste preview")} />
<SplitPanel id="preview" defaultSize="70%" minSize="100px" className={styles.previewPanel}>
<PastePreview source={view} text={preview} />
</SplitPanel>
</SplitGroup>
</div>
</Dialog>
);
@@ -228,11 +253,11 @@ function PastePreview({ source, text }: { source: EditorView; text: string }) {
syntaxHighlighting(openideaHighlightStyle),
source.state.facet(language)?.extension ?? [],
compartments.font.get(source.state) ?? [],
fontZoom.init(() => source.state.field(fontZoom, false) ?? 0),
EditorState.tabSize.of(source.state.tabSize),
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-label": tx("Paste preview"), class: selectableText, tabindex: "0" }),
lineNumbers(),
highlightSpecialChars(),
],
}),
+17 -1
View File
@@ -130,7 +130,7 @@ describe("Maven tree", () => {
it("shows profiles, then the aggregator with lifecycle, plugins and its modules", () => {
const roots = mavenRoots(maven);
expect(labels(roots)).toEqual(["Profiles", "Multi Demo"]);
expect(labels(children(roots[0]!))).toEqual(["dev", "ci"]);
expect(labels(children(roots[0]!))).toEqual(["ci", "dev"]);
const top = children(roots[1]!);
expect(labels(top)).toEqual(["Lifecycle", "Plugins", "core", "Demo App"]);
expect(labels(children(top[0]!))).toEqual([
@@ -148,6 +148,22 @@ describe("Maven tree", () => {
expect(nodeIcon(roots[1]!)).toBe("maven-project");
});
it("sorts Maven profiles by ID ignoring case while preserving the order used for Maven arguments", () => {
const model = {
...maven,
profiles: [
{ id: "zulu", activeByDefault: false },
{ id: "Beta", activeByDefault: false },
{ id: "alpha_ci", activeByDefault: false },
{ id: "alpha", activeByDefault: true },
{ id: "alpha-edge", activeByDefault: false },
],
};
const group = mavenRoots(model)[0]!;
expect(labels(mavenChildren(group, model, [])!)).toEqual(["alpha", "alpha-edge", "alpha_ci", "Beta", "zulu"]);
expect(profilesArg(model.profiles, { zulu: true, alpha_ci: true, alpha: false })).toBe("zulu,alpha_ci,!alpha");
});
it("expands plugins to goals and dependencies to their transitive ones", () => {
const core = children(mavenRoots(maven)[1]!)[2]!;
const kids = children(core);
+5
View File
@@ -187,6 +187,11 @@ export function mavenChildren(
case "profiles":
return model.profiles
.filter((p) => p.projectRoot === node.projectRoot)
.sort((a, b) => {
const aId = a.id.toLowerCase();
const bId = b.id.toLowerCase();
return aId < bId ? -1 : aId > bId ? 1 : 0;
})
.map((profile) => ({ kind: "profile", key: `mvn:profile:${profileKey(profile)}`, profile }));
case "mavenProject": {
const p = node.project;
+8 -6
View File
@@ -1020,14 +1020,16 @@ export function SourceDialog({
}
onChange={(e) => setOptions({ timeZone: e.target.value })}
/>
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
</>
)}
{!sqlite && (
<SecondsOption
label="Run keep-alive query each"
value={options.keepAliveSecs}
fallback={60}
onChange={(keepAliveSecs) => setOptions({ keepAliveSecs })}
/>
)}
<SecondsOption
label="Auto-disconnect after"
value={options.autoDisconnectSecs}
+14
View File
@@ -1072,6 +1072,18 @@ function promptOf(id: string): string {
* `schema` is a console's active context: the backend puts the connection that runs
* each statement in it, so unqualified names resolve there.
*/
/** Shows `id` disconnected when the backend closed its connection (it reconnects on next use). */
async function syncDropped(id: string) {
const server = await call(commands.dbConnected()).catch(() => null);
if (!server || server.includes(id) || !useDatabase.getState().connected.has(id)) return;
useDatabase.setState((s) => {
const connected = new Set(s.connected);
connected.delete(id);
return { connected };
});
log("info", `${targetLabel(id)}: the connection was lost; the next statement reconnects`);
}
async function run(
id: string,
statements: SqlStatement[],
@@ -1087,6 +1099,8 @@ async function run(
);
if (!current()) return outcomes;
if (!wasConnected) log("info", "Connected");
// A failed statement can have found the session dead; the backend then dropped it.
if (outcomes.some((o) => o.error)) void syncDropped(id);
const prompt = schema || promptOf(id);
for (const o of outcomes) {
log("statement", o.statement.text, `${prompt}>`);
@@ -292,7 +292,7 @@ describe("debug tool window", () => {
expect(screen.getByRole("tab", { name: /main/ })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Threads & Variables" })).toBeTruthy();
expect(screen.getByRole("tab", { name: "Console" })).toBeTruthy();
expect(screen.getByText(", main.py:12")).toBeTruthy();
expect(screen.getByRole("option", { selected: true })).toHaveTextContent("main:12, main.py");
expect(screen.getByPlaceholderText("Evaluate expression (↩) or add a watch (⇧⌘↩)")).toBeTruthy();
expect(await screen.findByText("{int}")).toBeTruthy();
expect(screen.getByText("'hi'")).toBeTruthy();
@@ -102,11 +102,20 @@
display: flex;
flex-direction: column;
min-height: 0;
padding: 4px 0;
padding-bottom: var(--space-1);
}
.threadHeader {
display: flex;
align-items: center;
flex: none;
height: 30px;
padding: 0 var(--space-1);
border-bottom: 1px solid var(--border);
}
.threadSelect {
margin: 0 8px 4px;
max-width: 100%;
}
.frameList {
@@ -116,7 +125,7 @@
display: flex;
flex-direction: column;
outline: none;
padding: 0 4px;
padding: var(--space-1) var(--space-1) 0;
}
.frame {
@@ -150,24 +159,36 @@
flex: none;
}
.frameName {
.frameText,
.frameLabel {
display: flex;
align-items: baseline;
min-width: 0;
}
.frameText {
flex: 1;
}
.frameLine {
flex: none;
}
.frameName,
.frameFile {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.frameFile {
flex: 1;
min-width: 0;
/* ", File.java:12" hugs the name, cancelling the row gap. */
margin-left: -6px;
flex: 0 1000 auto;
min-width: min(12ch, 32%);
color: var(--fg-subtle);
overflow: hidden;
text-overflow: ellipsis;
font-size: var(--fs-small);
}
.hiddenFrames {
display: block;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-style: italic;
}
+33 -18
View File
@@ -1,6 +1,6 @@
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, useProject } from "@/platform/project";
@@ -22,6 +22,7 @@ import {
type TabItem,
T,
} from "@/ui";
import { revealVertically } from "@/ui/Tabs";
import { setMuted, useBreakpoints } from "../breakpoints/store";
import { frameLabel, groupFrames } from "../frames";
import { blurDebugView, focusDebugView } from "./focusedView";
@@ -347,10 +348,15 @@ function ThreadsAndVariables({ session }: { session: DebugSession }) {
function FramesPane({ session }: { session: DebugSession }) {
const root = useProject((s) => s.project?.root ?? null);
const [showAll, setShowAll] = useState(false);
const list = useRef<HTMLDivElement>(null);
const selectedRow = useRef<HTMLButtonElement>(null);
const items = useMemo(
() => groupFrames(session.frames, root, session.selectedFrame, showAll),
[session.frames, root, session.selectedFrame, showAll],
);
useLayoutEffect(() => {
if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current);
}, [items]);
const paused = session.status === "paused";
const onKeyDown = (e: KeyboardEvent) => {
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
@@ -365,19 +371,24 @@ function FramesPane({ session }: { session: DebugSession }) {
return (
<div className={styles.frames}>
{session.threads.length > 0 && (
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
className={styles.threadSelect}
/>
<div className={styles.threadHeader}>
<Select
value={session.selectedThread != null ? String(session.selectedThread) : null}
options={session.threads.map((t) => ({
value: String(t.id),
label: t.name,
verbatim: true,
detail: t.id === session.stoppedThread ? "suspended" : undefined,
}))}
onChange={(v) => void selectThread(session.id, +v)}
aria-label="Thread"
variant="ghost"
className={styles.threadSelect}
/>
</div>
)}
<div
ref={list}
className={styles.frameList}
role="listbox"
aria-label={tx("Frames")}
@@ -415,9 +426,11 @@ function FramesPane({ session }: { session: DebugSession }) {
) : (
<button
key={item.frame.id}
ref={item.frame.id === session.selectedFrame ? selectedRow : undefined}
type="button"
role="option"
aria-selected={item.frame.id === session.selectedFrame}
title={item.frame.path ? `${frameLabel(item.frame)}, ${basename(item.frame.path)}` : item.frame.name}
className={clsx(
styles.frame,
item.frame.id === session.selectedFrame && styles.frameSelected,
@@ -459,13 +472,15 @@ function FramesPane({ session }: { session: DebugSession }) {
}}
>
<Icon name="method" size={16} className={styles.frameIcon} />
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && (
<span className={styles.frameFile}>
, {basename(item.frame.path)}
{item.frame.line >= 0 ? `:${item.frame.line + 1}` : ""}
<span className={styles.frameText}>
<span className={styles.frameLabel}>
<span className={styles.frameName}>{item.frame.name}</span>
{item.frame.path && item.frame.line >= 0 && (
<span className={styles.frameLine}>:{item.frame.line + 1}</span>
)}
</span>
)}
{item.frame.path && <span className={styles.frameFile}>, {basename(item.frame.path)}</span>}
</span>
</button>
),
)}
+3
View File
@@ -417,6 +417,9 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
{ kind: "separator" },
act("vcs.stash", undefined, "Stash Changes…"),
act("vcs.unstash", undefined, "Unstash Changes…"),
{ kind: "separator" },
act("vcs.manageRemotes", undefined, "Manage Remotes…"),
act("vcs.clone", undefined, "Clone…"),
],
"branch",
),
+33 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import type { LineHunk } from "@/bindings";
import { applyRollback, hunkAtLine, hunkKeys, hunksOverlapping, nextHunk, prevHunk, rollbackEdit } from "../hunks";
@@ -132,6 +132,38 @@ describe("change lane clicks", () => {
setHunkPopupHooks(null);
parent.remove();
});
it("opens a deletion from the hit area above its line", async () => {
const { EditorView } = await import("@codemirror/view");
const { changeLane } = await import("@/editor/core/cm/lanes");
const { changeMarkers, setHunkPopupHooks } = await import("../gutter");
const opened: string[] = [];
setHunkPopupHooks({ open: (_v, hunk) => opened.push(hunk.kind), docChanged: () => {} });
const parent = document.createElement("div");
document.body.appendChild(parent);
const view = new EditorView({
parent,
state: EditorState.create({
doc: "a\nc\n",
extensions: [changeLane, changeMarkers({ path: "/p/f.txt" } as Parameters<typeof changeMarkers>[0])],
}),
});
view.dispatch({ effects: setHunksEffect.of([h("deleted", 1, 0, 1, 1, "b\n")]) });
const lane = view.dom.querySelector<HTMLElement>(".cm-openidea-lane")!;
vi.spyOn(lane, "getBoundingClientRect").mockReturnValue({ left: 100, right: 104, top: 0, bottom: 100 } as DOMRect);
const marker = view.dom.querySelector<HTMLElement>(".cm-openidea-laneDeleted")!;
vi.spyOn(marker, "getBoundingClientRect").mockReturnValue({ left: 96, top: 14, width: 12, height: 12 } as DOMRect);
const previous = view.lineBlockAt(view.state.doc.line(1).from);
const deleted = view.lineBlockAt(view.state.doc.line(2).from);
vi.spyOn(view, "lineBlockAtHeight").mockImplementation((height) => (height < 20 ? previous : deleted));
marker.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 96, clientY: 17 }),
);
expect(opened).toEqual(["deleted"]);
view.destroy();
setHunkPopupHooks(null);
parent.remove();
});
});
describe("change markers in folds", () => {
+4 -29
View File
@@ -2,7 +2,7 @@
import { useEffect, useId, useState } from "react";
import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
import { Checkbox, Dialog, IconButton, Input, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { runCommitChecks } from "./commitChecks";
@@ -12,10 +12,11 @@ import { workflowSettings } from "@/platform/workflowSettings";
import { notifyFileOperation } from "@/platform/fileOps";
import { confirmDialog, openDialog } from "./dialogs";
import { RepoPicker, useBranchInfo } from "./gitMenuDialogs";
import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
import { baseName, effectiveKind, stripSlash } from "./model";
import { logConsole, runOp, saveAll } from "./ops";
import { ensureCommitIdentity } from "./commitIdentity";
import { showCompareRevisions } from "./operations";
import { FileChecklist } from "./shelf";
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
@@ -216,7 +217,6 @@ export function showRollbackDialog(files: FileStatus[]) {
}
function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () => void }) {
const root = useVcs((s) => s.root) ?? "";
const [selected, setSelected] = useState(() => new Set(files.map((f) => f.path)));
const [deleteAdded, setDeleteAdded] = useState(false);
const hasAdded = files.some((f) => f.staged === "added");
@@ -256,32 +256,7 @@ function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () =
? tx`${selected.size} of ${files.length} file will be reverted to their last committed state. Uncommitted changes are lost.`
: tx`${selected.size} of ${files.length} files will be reverted to their last committed state. Uncommitted changes are lost.`}
</div>
<div className={styles.fileList} role="group" aria-label={tx("Files to roll back")}>
{files.map((f) => {
const kind = effectiveKind(f) ?? "modified";
return (
<div key={f.path} className={styles.fileRow}>
<Checkbox
aria-label={tx`Include ${baseName(f.path)}`}
checked={selected.has(f.path)}
onChange={(v) =>
setSelected((s) => {
const n = new Set(s);
if (v) n.add(f.path);
else n.delete(f.path);
return n;
})
}
/>
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
{baseName(f.path)}
</span>
<span className={styles.fileDir}>{dirName(relTo(root, stripSlash(f.path)))}</span>
</div>
);
})}
</div>
<FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to roll back" />
<div style={{ height: 12 }} />
</Dialog>
);
+10 -5
View File
@@ -235,14 +235,19 @@ const laneTheme = EditorView.baseTheme({
*/
export function laneMouseDown(view: EditorView, event: MouseEvent, path: string): boolean {
if (event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) return false;
const deletedMarker = event.target instanceof Element ? event.target.closest(".cm-openidea-laneDeleted") : null;
const lane = view.dom.querySelector(".cm-openidea-lane");
if (!lane) return false;
const rect = lane.getBoundingClientRect();
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
const block = view.lineBlockAtHeight(event.clientY - view.documentTop);
if (!deletedMarker) {
const rect = lane.getBoundingClientRect();
if (event.clientX < rect.left - 1 || event.clientX > rect.right + 3) return false;
if (event.clientY < rect.top || event.clientY > rect.bottom) return false;
}
const markerRect = deletedMarker?.getBoundingClientRect();
const y = markerRect ? markerRect.top + markerRect.height / 2 + 1 : event.clientY;
const block = view.lineBlockAtHeight(y - view.documentTop);
const hunk = hunkAtPos(view.state, block.from);
if (!hunk) return false;
if (!hunk || (deletedMarker && hunk.kind !== "deleted")) return false;
event.preventDefault();
event.stopPropagation();
showHunkPopup(view, hunk, path);
+1
View File
@@ -12,6 +12,7 @@
"Resize file type panes": "Resize file type panes",
"Problems actions": "Problems actions",
"TODO actions": "TODO actions",
"Resize paste preview": "Resize paste preview",
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
"Windows file and folder names cannot end with a period or space": "Windows file and folder names cannot end with a period or space",
"Use URL template": "Use URL template",
+1
View File
@@ -2963,6 +2963,7 @@
"Tests failed: {detail}": "测试失败:{detail}",
"TODO comment": "TODO 注释",
"TODO actions": "TODO 操作",
"Resize paste preview": "调整粘贴预览大小",
"TODO filters": "TODO 筛选器",
"TODO items": "TODO 项",
"TODO items unavailable": "TODO 项不可用",