дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 20:46:22 +02:00
Порівняти коміти
47
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
bd37494ee8 | ||
|
|
f597ae8c81 | ||
|
|
eb036f2b67 | ||
|
|
ad95695588 | ||
|
|
9e6c29a7b7 | ||
|
|
89fa6cb02c | ||
|
|
6f284741b3 | ||
|
|
4b253d368e | ||
|
|
f274189c92 | ||
|
|
5f17748295 | ||
|
|
2d94628d1d | ||
|
|
26aabf5229 | ||
|
|
87ce01d251 | ||
|
|
3dd918c5b2 | ||
|
|
9a74fe4418 | ||
|
|
a70a0ae6f1 | ||
|
|
9be4803462 | ||
|
|
8122127dde | ||
|
|
cdcce048fe | ||
|
|
1cea43694e | ||
|
|
260ac4efbf | ||
|
|
9805fb42b8 | ||
|
|
4a18d4d205 | ||
|
|
9ecef0ef0f | ||
|
|
aec80ced53 | ||
|
|
e5a4a6940a | ||
|
|
196af0ac37 | ||
|
|
1e4388490c | ||
|
|
ad8958901b | ||
|
|
25b49b1473 | ||
|
|
1a689ff5da | ||
|
|
2544db3025 | ||
|
|
6355534ed5 | ||
|
|
7bc26b9387 | ||
|
|
d7b9401a07 | ||
|
|
465e4f80bc | ||
|
|
1743aec533 | ||
|
|
52e2215dcf | ||
|
|
57bccc916c | ||
|
|
46a712524d | ||
|
|
0f5607d76c | ||
|
|
8c23c589ca | ||
|
|
ae7a8e74c8 | ||
|
|
a7b67347c2 | ||
|
|
707b6fe169 | ||
|
|
b9a0c66ca6 | ||
|
|
26f83240a7 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"detector": {
|
||||
"ignoreRules": [],
|
||||
"ignoreFiles": [],
|
||||
"ignoreValues": [
|
||||
{
|
||||
"rule": "gradient-text",
|
||||
"value": "*",
|
||||
"files": ["src/features/agents/Session.module.css"],
|
||||
"createdAt": "2026-11-24T14:58:12.514Z",
|
||||
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"generatedAt": "2026-11-24T15:06:05+00:00",
|
||||
"title": "Design System: OpenIDEA",
|
||||
"extensions": {
|
||||
"colorMeta": {
|
||||
"workbench-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Workbench Blue",
|
||||
"canonical": "#3871e1",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.073 262)",
|
||||
"oklch(25% 0.121 262)",
|
||||
"oklch(35% 0.17 262)",
|
||||
"oklch(48% 0.17 262)",
|
||||
"oklch(60% 0.17 262)",
|
||||
"oklch(72% 0.136 262)",
|
||||
"oklch(84% 0.078 262)",
|
||||
"oklch(95% 0.024 262)"
|
||||
]
|
||||
},
|
||||
"link-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Link Blue",
|
||||
"canonical": "#2f5eb9",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 262)",
|
||||
"oklch(25% 0.107 262)",
|
||||
"oklch(35% 0.15 262)",
|
||||
"oklch(48% 0.15 262)",
|
||||
"oklch(60% 0.15 262)",
|
||||
"oklch(72% 0.12 262)",
|
||||
"oklch(84% 0.069 262)",
|
||||
"oklch(95% 0.021 262)"
|
||||
]
|
||||
},
|
||||
"selection-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash",
|
||||
"canonical": "#d0dffe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
},
|
||||
"tab-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Tab Wash",
|
||||
"canonical": "#e3ebfe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.026 262)",
|
||||
"oklch(25% 0.043 262)",
|
||||
"oklch(35% 0.06 262)",
|
||||
"oklch(48% 0.06 262)",
|
||||
"oklch(60% 0.06 262)",
|
||||
"oklch(72% 0.048 262)",
|
||||
"oklch(84% 0.027 262)",
|
||||
"oklch(95% 0.009 262)"
|
||||
]
|
||||
},
|
||||
"danger": {
|
||||
"role": "status",
|
||||
"displayName": "Danger",
|
||||
"canonical": "#c54e58",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 18)",
|
||||
"oklch(25% 0.107 18)",
|
||||
"oklch(35% 0.15 18)",
|
||||
"oklch(48% 0.15 18)",
|
||||
"oklch(60% 0.15 18)",
|
||||
"oklch(72% 0.12 18)",
|
||||
"oklch(84% 0.069 18)",
|
||||
"oklch(95% 0.021 18)"
|
||||
]
|
||||
},
|
||||
"warning": {
|
||||
"role": "status",
|
||||
"displayName": "Warning",
|
||||
"canonical": "#a56906",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.056 70)",
|
||||
"oklch(25% 0.093 70)",
|
||||
"oklch(35% 0.13 70)",
|
||||
"oklch(48% 0.13 70)",
|
||||
"oklch(60% 0.13 70)",
|
||||
"oklch(72% 0.104 70)",
|
||||
"oklch(84% 0.059 70)",
|
||||
"oklch(95% 0.019 70)"
|
||||
]
|
||||
},
|
||||
"success": {
|
||||
"role": "status",
|
||||
"displayName": "Success",
|
||||
"canonical": "#338555",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.047 152)",
|
||||
"oklch(25% 0.079 152)",
|
||||
"oklch(35% 0.11 152)",
|
||||
"oklch(48% 0.11 152)",
|
||||
"oklch(60% 0.11 152)",
|
||||
"oklch(72% 0.088 152)",
|
||||
"oklch(84% 0.05 152)",
|
||||
"oklch(95% 0.016 152)"
|
||||
]
|
||||
},
|
||||
"frame-grey": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-white": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island White",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"raised-paper": {
|
||||
"role": "neutral",
|
||||
"displayName": "Raised Paper",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-secondary": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Secondary",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-faint": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Faint",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"hairline": {
|
||||
"role": "neutral",
|
||||
"displayName": "Hairline",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"frame-grey-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-strong-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Strong (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"selection-wash-dark": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash (Dark)",
|
||||
"canonical": "#2a4371",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
}
|
||||
},
|
||||
"typographyMeta": {
|
||||
"title": {
|
||||
"displayName": "Title",
|
||||
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
|
||||
},
|
||||
"body": {
|
||||
"displayName": "Body",
|
||||
"purpose": "Default UI text, menus, rows, buttons."
|
||||
},
|
||||
"label": {
|
||||
"displayName": "Label",
|
||||
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
|
||||
},
|
||||
"label-tiny": {
|
||||
"displayName": "Label Tiny",
|
||||
"purpose": "Stripe labels, counters, badges."
|
||||
},
|
||||
"input-large": {
|
||||
"displayName": "Input Large",
|
||||
"purpose": "Search Everywhere and other large query fields."
|
||||
},
|
||||
"code": {
|
||||
"displayName": "Code",
|
||||
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
|
||||
}
|
||||
},
|
||||
"shadows": [
|
||||
{
|
||||
"name": "shadow-popup",
|
||||
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-dialog",
|
||||
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
|
||||
"purpose": "Window-style shadow for dialogs (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-tooltip",
|
||||
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Hover tooltips (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-balloon",
|
||||
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
|
||||
"purpose": "Notification balloons (Light)."
|
||||
}
|
||||
],
|
||||
"motion": [
|
||||
{
|
||||
"name": "ease",
|
||||
"value": "cubic-bezier(0.2, 0, 0, 1)",
|
||||
"purpose": "Default easing for every state transition."
|
||||
},
|
||||
{
|
||||
"name": "dur-fast",
|
||||
"value": "80ms",
|
||||
"purpose": "Hover, press and focus changes on controls."
|
||||
},
|
||||
{
|
||||
"name": "dur",
|
||||
"value": "140ms",
|
||||
"purpose": "Standard transitions such as popup fades."
|
||||
},
|
||||
{
|
||||
"name": "dur-slow",
|
||||
"value": "220ms",
|
||||
"purpose": "Upper bound for any state transition."
|
||||
}
|
||||
],
|
||||
"density": [
|
||||
{
|
||||
"name": "default",
|
||||
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
|
||||
},
|
||||
{
|
||||
"name": "compact",
|
||||
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
|
||||
}
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"name": "Primary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-primary",
|
||||
"description": "The one default action in a dialog or form.",
|
||||
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
|
||||
},
|
||||
{
|
||||
"name": "Secondary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-secondary",
|
||||
"description": "Every other dialog action: Cancel, Apply, Browse.",
|
||||
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
|
||||
},
|
||||
{
|
||||
"name": "Ghost Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-ghost",
|
||||
"description": "Low-emphasis text actions in headers and inline rows.",
|
||||
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
|
||||
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
|
||||
},
|
||||
{
|
||||
"name": "Toolbar Icon Button",
|
||||
"kind": "button",
|
||||
"refersTo": "icon-button",
|
||||
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
|
||||
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
|
||||
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Text Field",
|
||||
"kind": "input",
|
||||
"refersTo": "input",
|
||||
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
|
||||
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
|
||||
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
|
||||
},
|
||||
{
|
||||
"name": "Chip",
|
||||
"kind": "chip",
|
||||
"refersTo": "chip",
|
||||
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
|
||||
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
|
||||
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Tree Rows",
|
||||
"kind": "custom",
|
||||
"refersTo": "list-row-selected",
|
||||
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
|
||||
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
|
||||
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
|
||||
},
|
||||
{
|
||||
"name": "Island on Frame",
|
||||
"kind": "card",
|
||||
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
|
||||
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
|
||||
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
|
||||
},
|
||||
{
|
||||
"name": "Tooltip",
|
||||
"kind": "custom",
|
||||
"refersTo": "tooltip",
|
||||
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
|
||||
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
|
||||
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
|
||||
}
|
||||
],
|
||||
"narrative": {
|
||||
"northStar": "The Quiet Workbench",
|
||||
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
|
||||
"keyCharacteristics": [
|
||||
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
|
||||
"Grey frame, rounded content islands, tonal layering only.",
|
||||
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
|
||||
"High density on a 4px grid. Compact mode is a first-class variant.",
|
||||
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
|
||||
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
|
||||
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"name": "The IDEA Reference Rule",
|
||||
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
|
||||
"section": "overview"
|
||||
},
|
||||
{
|
||||
"name": "The One Accent Rule",
|
||||
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Token Only Rule",
|
||||
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Flat Scale Rule",
|
||||
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The User Owns Size Rule",
|
||||
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The Flat at Rest Rule",
|
||||
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
|
||||
"section": "elevation"
|
||||
}
|
||||
],
|
||||
"dos": [
|
||||
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
|
||||
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
|
||||
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
|
||||
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
|
||||
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
|
||||
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
|
||||
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
|
||||
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
|
||||
],
|
||||
"donts": [
|
||||
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
|
||||
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
|
||||
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
|
||||
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
|
||||
"**Don't** put shadows on docked panels, islands, rows or controls.",
|
||||
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
|
||||
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
|
||||
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
|
||||
]
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -158,7 +158,17 @@
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx"
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
|
||||
Створено
@@ -4189,6 +4189,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
---
|
||||
name: OpenIDEA
|
||||
description: The IDE you know, rebuilt in Rust.
|
||||
colors:
|
||||
workbench-blue: "#3871e1"
|
||||
link-blue: "#2f5eb9"
|
||||
frame-grey: "#e9eaee"
|
||||
island-white: "#ffffff"
|
||||
raised-paper: "#f7f8f9"
|
||||
ink: "#000000"
|
||||
ink-secondary: "#5f6269"
|
||||
ink-muted: "#6c707e"
|
||||
ink-faint: "#9fa2a8"
|
||||
hairline: "#e9eaee"
|
||||
control-edge: "#d1d3d9"
|
||||
selection-wash: "#d0dffe"
|
||||
tab-wash: "#e3ebfe"
|
||||
danger: "#c54e58"
|
||||
warning: "#a56906"
|
||||
success: "#338555"
|
||||
frame-grey-dark: "#26282c"
|
||||
island-dark: "#191a1c"
|
||||
ink-dark: "#d1d3d9"
|
||||
ink-strong-dark: "#dfe1e5"
|
||||
ink-muted-dark: "#8c8f95"
|
||||
control-edge-dark: "#40434a"
|
||||
selection-wash-dark: "#2a4371"
|
||||
typography:
|
||||
title:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 600
|
||||
lineHeight: 1.4
|
||||
body:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "12px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label-tiny:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "11px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
input-large:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "15px"
|
||||
fontWeight: 400
|
||||
code:
|
||||
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: "22px"
|
||||
fontFeature: "\"liga\" 0"
|
||||
rounded:
|
||||
small: "4px"
|
||||
control: "4px"
|
||||
row: "4px"
|
||||
selection: "5px"
|
||||
tab: "6px"
|
||||
toolbar-button: "6px"
|
||||
tooltip: "6px"
|
||||
popup: "8px"
|
||||
island: "10px"
|
||||
popup-large: "10px"
|
||||
dialog: "10px"
|
||||
spacing:
|
||||
space-0-5: "2px"
|
||||
space-1: "4px"
|
||||
space-1-5: "6px"
|
||||
space-2: "8px"
|
||||
space-3: "12px"
|
||||
space-4: "16px"
|
||||
components:
|
||||
button-primary:
|
||||
backgroundColor: "{colors.workbench-blue}"
|
||||
textColor: "{colors.island-white}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-secondary:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-ghost:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
icon-button:
|
||||
textColor: "{colors.ink-muted}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
icon-button-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
input:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
chip:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.label}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
padding: "0 6px"
|
||||
height: "22px"
|
||||
tooltip:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.tooltip}"
|
||||
padding: "6px 10px"
|
||||
list-row-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.row}"
|
||||
height: "24px"
|
||||
---
|
||||
|
||||
# Design System: OpenIDEA
|
||||
|
||||
## Overview
|
||||
|
||||
**Creative North Star: "The Quiet Workbench"**
|
||||
|
||||
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
|
||||
|
||||
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
|
||||
|
||||
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
|
||||
|
||||
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
|
||||
|
||||
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
|
||||
|
||||
**Key Characteristics:**
|
||||
|
||||
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
|
||||
- Grey frame, rounded content islands, tonal layering only.
|
||||
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
|
||||
- High density on a 4px grid. Compact mode is a first-class variant.
|
||||
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
|
||||
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
|
||||
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
|
||||
|
||||
## Colors
|
||||
|
||||
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
|
||||
|
||||
### Project colour
|
||||
|
||||
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
|
||||
|
||||
### Primary
|
||||
|
||||
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
|
||||
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
|
||||
|
||||
### Neutral
|
||||
|
||||
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
|
||||
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
|
||||
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
|
||||
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
|
||||
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
|
||||
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
|
||||
|
||||
### Functional vocabularies
|
||||
|
||||
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
|
||||
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
|
||||
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
|
||||
|
||||
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
|
||||
|
||||
## Typography
|
||||
|
||||
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
|
||||
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
|
||||
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
|
||||
|
||||
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
|
||||
|
||||
### Hierarchy
|
||||
|
||||
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
|
||||
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
|
||||
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
|
||||
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
|
||||
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
|
||||
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
|
||||
|
||||
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
|
||||
|
||||
## Layout
|
||||
|
||||
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
|
||||
|
||||
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
|
||||
|
||||
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
|
||||
|
||||
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
|
||||
|
||||
### Shadow Vocabulary
|
||||
|
||||
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
|
||||
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
|
||||
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
|
||||
|
||||
## Shapes
|
||||
|
||||
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
|
||||
|
||||
## Components
|
||||
|
||||
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
|
||||
|
||||
### Buttons
|
||||
|
||||
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
|
||||
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
|
||||
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
|
||||
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
|
||||
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
|
||||
|
||||
### Icon Buttons (toolbar actions)
|
||||
|
||||
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
|
||||
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
|
||||
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
|
||||
- Tone variants (`danger`, `accent`) recolour only the icon.
|
||||
|
||||
### Chips
|
||||
|
||||
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
|
||||
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
|
||||
|
||||
### Inputs / Fields
|
||||
|
||||
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
|
||||
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
|
||||
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- Search fields have a muted leading icon. Monospace fields use the code font.
|
||||
|
||||
### Lists and Trees
|
||||
|
||||
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
|
||||
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
|
||||
|
||||
### Popups, Menus and Dialogs
|
||||
|
||||
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
|
||||
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
|
||||
|
||||
### Tabs
|
||||
|
||||
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
|
||||
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
|
||||
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
|
||||
|
||||
### Tool Window Stripes (signature)
|
||||
|
||||
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
### Do:
|
||||
|
||||
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
|
||||
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
|
||||
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
|
||||
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
|
||||
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
|
||||
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
|
||||
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
|
||||
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
|
||||
|
||||
### Don't:
|
||||
|
||||
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
|
||||
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
|
||||
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
|
||||
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
|
||||
- **Don't** put shadows on docked panels, islands, rows or controls.
|
||||
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
|
||||
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
|
||||
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## Platform
|
||||
|
||||
web
|
||||
|
||||
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
|
||||
|
||||
## Users
|
||||
|
||||
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
|
||||
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
|
||||
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
|
||||
|
||||
## Product Purpose
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
|
||||
|
||||
## Positioning
|
||||
|
||||
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
|
||||
|
||||
## Operating Context
|
||||
|
||||
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
|
||||
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
|
||||
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
|
||||
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
Hard constraints future work must preserve:
|
||||
|
||||
1. The default keymap and interaction habits stay the same as IDEA's.
|
||||
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
|
||||
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
|
||||
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
|
||||
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
|
||||
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
|
||||
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
|
||||
|
||||
Other facts:
|
||||
|
||||
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
|
||||
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
|
||||
|
||||
## Brand Commitments
|
||||
|
||||
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
|
||||
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
|
||||
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
|
||||
|
||||
## Evidence on Hand
|
||||
|
||||
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
|
||||
- Demo video linked from `README.md`.
|
||||
- No testimonials, customer logos or user counts exist. Do not fabricate them.
|
||||
|
||||
## Product Principles
|
||||
|
||||
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
|
||||
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
|
||||
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
|
||||
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
|
||||
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
|
||||
|
||||
## Accessibility & Inclusion
|
||||
|
||||
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
|
||||
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
|
||||
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
|
||||
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if config::is_context_option(&o.id) {
|
||||
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
|
||||
if o.category.is_none() {
|
||||
o.category = Some("model_config".into());
|
||||
}
|
||||
} else if o.category.as_deref() != Some("thought_level") {
|
||||
} else if o.category.is_none() {
|
||||
o.category = Some("thought_level".into());
|
||||
}
|
||||
o
|
||||
|
||||
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
|
||||
assert_eq!(calls[1].1["mcpServers"], json!([]));
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
|
||||
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
|
||||
assert_eq!(fast.category.as_deref(), Some("model_config"));
|
||||
assert_eq!(fast.current.as_deref(), Some("false"));
|
||||
// The effort option belongs to the session's model; m2 may offer other levels.
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ use tokio::time::Instant;
|
||||
|
||||
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
|
||||
const COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
|
||||
const CATALOG_SCHEMA: u8 = 2;
|
||||
|
||||
type Store = Arc<Mutex<HashMap<String, Known>>>;
|
||||
type Key = (PathBuf, PathBuf, String);
|
||||
@@ -80,6 +82,8 @@ impl CatalogData {
|
||||
pub(crate) struct SavedCatalog {
|
||||
/// An opaque cryptographic digest, never raw launch arguments or credentials.
|
||||
fingerprint: String,
|
||||
#[serde(default)]
|
||||
schema: u8,
|
||||
#[serde(flatten)]
|
||||
catalog: CatalogData,
|
||||
}
|
||||
@@ -111,7 +115,7 @@ impl LaunchContext {
|
||||
hash.update(&(value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
field(&mut hash, b"openidea-model-catalog-v1");
|
||||
field(&mut hash, b"openidea-model-catalog-v2");
|
||||
field(
|
||||
&mut hash,
|
||||
match self.spec.driver {
|
||||
@@ -200,7 +204,14 @@ impl AgentCatalogs {
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.map(|saved| {
|
||||
let mut catalog = saved.catalog.clone();
|
||||
if saved.schema < CATALOG_SCHEMA {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -228,7 +239,8 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -281,7 +293,7 @@ impl AgentCatalogs {
|
||||
AgentModelCatalog {
|
||||
provider: provider.to_owned(),
|
||||
config: shared.config_for_new_task(catalog.config, provider),
|
||||
thought_levels: catalog.thought_levels,
|
||||
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
|
||||
refreshing: entry.flight.is_some(),
|
||||
refreshed_at_ms: catalog.refreshed_at_ms,
|
||||
retry_at_ms: model_failure
|
||||
@@ -318,7 +330,9 @@ impl AgentCatalogs {
|
||||
let generation = state.generation;
|
||||
let saved =
|
||||
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
|
||||
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
|
||||
let matching = saved
|
||||
.as_ref()
|
||||
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
|
||||
let age = saved
|
||||
.as_ref()
|
||||
.filter(|_| matching)
|
||||
@@ -489,7 +503,11 @@ impl AgentCatalogs {
|
||||
}
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
SavedCatalog {
|
||||
fingerprint: entry.context.fingerprint(),
|
||||
schema: CATALOG_SCHEMA,
|
||||
catalog: catalog.clone(),
|
||||
},
|
||||
);
|
||||
entry.catalog = Some(catalog);
|
||||
shared.persist_known(&cache);
|
||||
|
||||
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
}
|
||||
|
||||
/// Moves options that approve everything without asking to a value that asks: the agent's
|
||||
/// default or ask mode, else its first one that asks.
|
||||
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
|
||||
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
@@ -73,9 +73,15 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
continue;
|
||||
}
|
||||
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
|
||||
let value = ["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
let value = option
|
||||
.default_value
|
||||
.as_deref()
|
||||
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
|
||||
.or_else(|| {
|
||||
["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
})
|
||||
.or_else(|| option.values.iter().find(asks));
|
||||
if let Some(value) = value {
|
||||
option.current = Some(value.value.clone());
|
||||
@@ -83,11 +89,26 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
|
||||
Some((option, value))
|
||||
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
|
||||
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
|
||||
option.current = Some(value.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
|
||||
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
|
||||
if provider != "cursor" {
|
||||
return;
|
||||
}
|
||||
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
|
||||
&& fast.values.iter().any(|v| v.value == "false")
|
||||
{
|
||||
fast.current = Some("false".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bypass_mode(mode: &str) -> bool {
|
||||
@@ -126,14 +147,20 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_context_option(id: &str) -> bool {
|
||||
matches!(id, "context_tier" | "contextTier")
|
||||
matches!(id, "context" | "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
}
|
||||
|
||||
@@ -164,7 +191,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
.then(|| "thought_level".into())
|
||||
})
|
||||
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
|
||||
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
|
||||
}),
|
||||
current,
|
||||
default_value,
|
||||
@@ -337,6 +364,11 @@ fn legacy(
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_label(s: String, fallback: &str) -> String {
|
||||
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
|
||||
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
let value = v.get("value")?.as_str()?.to_owned();
|
||||
let meta = v.get("_meta");
|
||||
@@ -352,7 +384,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(AgentConfigValue {
|
||||
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
|
||||
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
|
||||
description: str_of(v, "description"),
|
||||
cost_category,
|
||||
usage_multiplier,
|
||||
@@ -434,19 +466,16 @@ mod tests {
|
||||
]}
|
||||
}));
|
||||
assert!(bypass_approvals(&full_access));
|
||||
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
|
||||
|
||||
let asking = options_of(&json!({
|
||||
let mut asking = options_of(&json!({
|
||||
"modes": {"currentModeId": "ask", "availableModes": [
|
||||
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
|
||||
]}
|
||||
}));
|
||||
assert!(!bypass_approvals(&asking));
|
||||
assert_eq!(
|
||||
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
|
||||
Some("full-access"),
|
||||
"the offered bypass mode stays available"
|
||||
);
|
||||
apply_bypass_approvals(&mut asking);
|
||||
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
|
||||
assert!(bypass_approvals(&asking));
|
||||
|
||||
let permissions = |current: &str| {
|
||||
options_of(&json!({"configOptions": [{
|
||||
@@ -503,7 +532,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
"configOptions": [
|
||||
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
|
||||
@@ -512,19 +541,39 @@ mod tests {
|
||||
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "medium",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "256k",
|
||||
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
|
||||
{"id": "contextTier", "type": "select", "currentValue": "default",
|
||||
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
|
||||
{"id": "fast", "type": "select", "currentValue": "false",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
|
||||
{"id": "fast", "type": "select", "currentValue": "true",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
|
||||
]
|
||||
}));
|
||||
assert_eq!(c.len(), 4);
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
|
||||
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
|
||||
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
|
||||
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
|
||||
assert_eq!(c[2].category.as_deref(), Some("model_config"));
|
||||
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
|
||||
assert_eq!(c[3].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].values[1].name, "Fast");
|
||||
assert!(
|
||||
is_per_model_option(&c[1])
|
||||
&& is_per_model_option(&c[2])
|
||||
&& is_per_model_option(&c[3])
|
||||
&& is_per_model_option(&c[4])
|
||||
);
|
||||
assert!(!is_per_model_option(&c[0]));
|
||||
|
||||
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
|
||||
let mut cursor_opts = c.clone();
|
||||
apply_model_defaults("cursor", &mut cursor_opts);
|
||||
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
|
||||
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
|
||||
let mut other_opts = c.clone();
|
||||
apply_model_defaults("claude", &mut other_opts);
|
||||
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
|
||||
|
||||
// Editing effort on the same model preserves its initial `default_value` for Reset.
|
||||
merge_update(
|
||||
@@ -546,11 +595,34 @@ mod tests {
|
||||
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
|
||||
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "low",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "1m",
|
||||
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
|
||||
]),
|
||||
);
|
||||
let effort = c.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
|
||||
let context = c.iter().find(|o| o.id == "context").unwrap();
|
||||
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
|
||||
let mut c = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "full-access"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
|
||||
"options": [{"value": "off"}, {"value": "on"}]},
|
||||
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "bypass"}]}
|
||||
]}));
|
||||
apply_bypass_approvals(&mut c);
|
||||
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
|
||||
// Original agent default_values stay intact.
|
||||
assert_eq!(
|
||||
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
|
||||
[Some("ask"), Some("off"), Some("ask")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
|
||||
|
||||
use crate::model::AgentImage;
|
||||
use base64::Engine;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
/// Image files larger than this are not inlined into the conversation.
|
||||
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
|
||||
|
||||
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
|
||||
/// image blob, or a `resource_link` to an image file.
|
||||
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
match str_of(content, "type")? {
|
||||
"image" => {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
|
||||
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut image = from_uri(uri)?;
|
||||
image.name = str_of(content, "name").map(str::to_owned);
|
||||
Some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The image at a `data:` URL or a `file://` URI.
|
||||
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
if let Some(rest) = uri.strip_prefix("data:") {
|
||||
let (mime, data) = rest.split_once(";base64,")?;
|
||||
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
}
|
||||
|
||||
/// The image file at `path`, when it has an image extension and isn't too large.
|
||||
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
let mime = mime_of(path)?;
|
||||
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
(!bytes.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
/// `image` as an ACP image content block.
|
||||
pub(crate) fn content(image: &AgentImage) -> Value {
|
||||
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
|
||||
}
|
||||
|
||||
fn mime_of(path: &Path) -> Option<&'static str> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"bmp" => "image/bmp",
|
||||
"svg" => "image/svg+xml",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
pub(crate) fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let path = String::from_utf8_lossy(&out).into_owned();
|
||||
// `file:///C:/x` on Windows.
|
||||
match path.as_bytes() {
|
||||
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_blocks_inline_data_urls_blobs_and_image_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("shot 1.png");
|
||||
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
|
||||
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
|
||||
let uri = crate::file_uri(&file);
|
||||
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
|
||||
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
|
||||
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
|
||||
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
|
||||
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
|
||||
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
|
||||
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
|
||||
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
|
||||
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
|
||||
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
|
||||
let text = crate::file_uri(&dir.path().join("notes.txt"));
|
||||
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
|
||||
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
|
||||
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
|
||||
assert!(from_file(&dir.path().join("missing.png")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ mod conversation;
|
||||
mod elicitation;
|
||||
mod external;
|
||||
pub mod hermes;
|
||||
mod images;
|
||||
pub mod mcp;
|
||||
mod model;
|
||||
mod native;
|
||||
@@ -330,19 +331,23 @@ impl Shared {
|
||||
let hook = self.new_task_approvals.read().clone();
|
||||
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
|
||||
config::ask_for_approvals(&mut config);
|
||||
return config;
|
||||
}
|
||||
if let Some((o, v)) = config::bypass_mode(&config).map(|(o, v)| (o.id.clone(), v.value.clone()))
|
||||
&& let Some(o) = config.iter_mut().find(|c| c.id == o)
|
||||
{
|
||||
o.current = Some(v);
|
||||
}
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == config::CURSOR_APPROVAL) {
|
||||
o.current = Some("bypass".into());
|
||||
} else {
|
||||
config::apply_bypass_approvals(&mut config);
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub(crate) fn thought_levels_for_new_task(
|
||||
&self,
|
||||
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
provider: &str,
|
||||
) -> BTreeMap<String, Vec<AgentConfigOption>> {
|
||||
for options in levels.values_mut() {
|
||||
config::apply_model_defaults(provider, options);
|
||||
}
|
||||
levels
|
||||
}
|
||||
|
||||
/// The commands the agent offered last time in this project.
|
||||
fn known_commands(&self, provider: &str) -> Vec<AgentCommand> {
|
||||
let cache = self.known.lock();
|
||||
@@ -374,8 +379,19 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
// Restore each option's agent default so a session's manual overrides never pollute the catalog.
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
let levels: Vec<_> = config
|
||||
.iter()
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if let Some(def) = o.default_value.clone().filter(|d| o.values.iter().any(|v| v.value == *d)) {
|
||||
o.current = Some(def);
|
||||
}
|
||||
o
|
||||
})
|
||||
.collect();
|
||||
if !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
@@ -735,7 +751,7 @@ impl AgentManager {
|
||||
let mut info = provider::describe(p);
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = catalog.thought_levels;
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
info.commands = self.shared.known_commands(&p.id);
|
||||
info
|
||||
})
|
||||
@@ -1058,7 +1074,7 @@ impl AgentManager {
|
||||
};
|
||||
// Until the session reports its own, show what the agent offered last time with the choices applied.
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &spec.id);
|
||||
let mut levels = catalog.thought_levels;
|
||||
let mut levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &spec.id);
|
||||
let mut config = self.shared.config_for_new_task(catalog.config, &spec.id);
|
||||
for choice in &req.config {
|
||||
if let Some(o) = config.iter_mut().find(|o| o.id == choice.id) {
|
||||
@@ -3821,12 +3837,8 @@ impl Task {
|
||||
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
|
||||
fn adopt_user_chunk(self: &Arc<Self>, update: &Value) {
|
||||
let content = update.get("content");
|
||||
let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
|
||||
mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
name: None,
|
||||
});
|
||||
let text = timeline::content_text(content).unwrap_or_default();
|
||||
let image = content.and_then(images::from_content);
|
||||
let text = if image.is_some() { String::new() } else { timeline::content_text(content).unwrap_or_default() };
|
||||
if text.is_empty() && image.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -473,6 +473,39 @@ fn history_replays_turns() {
|
||||
assert_eq!(updates[4]["status"], "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_generated_and_attached_images_carry_their_pixels() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("shot.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let png_path = png.to_str().unwrap();
|
||||
let encoded = "iVBORw0K";
|
||||
let view = json!({"id": "v", "type": "imageView", "path": png_path});
|
||||
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
|
||||
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
|
||||
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
|
||||
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
|
||||
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
|
||||
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
|
||||
let saved =
|
||||
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
|
||||
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
|
||||
|
||||
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
|
||||
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
|
||||
{"type": "image", "url": "https://example.com/a.png"},
|
||||
{"type": "localImage", "path": png_path},
|
||||
{"type": "localImage", "path": "/gone.png"}
|
||||
]}]}]});
|
||||
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
|
||||
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
|
||||
assert_eq!(contents[1]["type"], "resource_link");
|
||||
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
|
||||
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_preserves_async_questions_with_stable_answer_ids() {
|
||||
let updates = history(
|
||||
|
||||
@@ -348,36 +348,18 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
|
||||
}
|
||||
"resource" => {
|
||||
let r = b.get("resource")?;
|
||||
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let text = r.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
|
||||
}
|
||||
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
|
||||
"resource_link" => {
|
||||
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// A `session/update` notification's `update` for content.
|
||||
pub(super) fn chunk(kind: &str, text: &str) -> Value {
|
||||
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
|
||||
@@ -467,6 +449,9 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
"imageView" => {
|
||||
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
call.insert("locations".into(), json!([{ "path": path }]));
|
||||
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
(format!("View {}", display_path(path, cwd)), "read")
|
||||
}
|
||||
"collabAgentToolCall" => {
|
||||
@@ -482,7 +467,12 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
}
|
||||
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
|
||||
"sleep" => ("Wait".to_owned(), "other"),
|
||||
"imageGeneration" => ("Generate an image".to_owned(), "other"),
|
||||
"imageGeneration" => {
|
||||
if done && let Some(image) = generated_image(item) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
("Generate an image".to_owned(), "other")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
|
||||
@@ -493,6 +483,19 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
Some(Value::Object(call))
|
||||
}
|
||||
|
||||
fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
json!({ "type": "content", "content": crate::images::content(image) })
|
||||
}
|
||||
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
}
|
||||
|
||||
/// The output of a running command, as a `tool_call_update`.
|
||||
pub(super) fn command_output(id: &str, output: &str) -> Value {
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
|
||||
@@ -856,9 +859,23 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
"user_message_chunk",
|
||||
c.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
)),
|
||||
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
|
||||
Some("localImage" | "mention" | "skill") => {
|
||||
Some("image") => {
|
||||
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
|
||||
let content = crate::images::from_uri(url).map_or_else(
|
||||
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|
||||
|image| crate::images::content(&image),
|
||||
);
|
||||
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
|
||||
}
|
||||
Some("localImage") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(match crate::images::from_file(std::path::Path::new(path)) {
|
||||
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": crate::images::content(&image) }),
|
||||
None => chunk("user_message_chunk", path),
|
||||
});
|
||||
}
|
||||
Some("mention" | "skill") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(chunk("user_message_chunk", path));
|
||||
}
|
||||
|
||||
@@ -3942,14 +3942,10 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
|
||||
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
|
||||
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(
|
||||
cursor
|
||||
.thought_levels
|
||||
.values()
|
||||
.next()
|
||||
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
|
||||
);
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
let levels = cursor.thought_levels.values().next().expect("discovered model options");
|
||||
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -8,6 +8,9 @@ use std::collections::HashMap;
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
|
||||
/// Image files a read tool names that are shown when it reports none itself.
|
||||
const MAX_READ_IMAGES: usize = 4;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
@@ -171,51 +174,17 @@ impl Timeline {
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
|
||||
&& let (Some(data), Some(mime)) =
|
||||
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
|
||||
&& !data.is_empty()
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(content) = update.get("content").and_then(Value::as_array) {
|
||||
merge_content(content, output, images, diffs);
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
// Agents that only name the image a read tool opened (Cursor): show the file itself.
|
||||
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
|
||||
images.extend(
|
||||
locs.iter()
|
||||
.filter(|p| p.0.is_absolute())
|
||||
.take(MAX_READ_IMAGES)
|
||||
.filter_map(|p| crate::images::from_file(&p.0)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,6 +351,54 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
images: &mut Vec<AgentImage>,
|
||||
diffs: &mut Vec<AgentToolDiff>,
|
||||
) {
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.and_then(crate::images::from_content) {
|
||||
new_images.push(image);
|
||||
} else if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
@@ -432,6 +449,7 @@ fn tail(mut text: String) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::AgentImage;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -478,6 +496,47 @@ mod tests {
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_come_from_linked_files_and_resource_blobs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("out.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
|
||||
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
|
||||
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
|
||||
]}));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
|
||||
assert_eq!(types, ["image/png", "image/gif"]);
|
||||
assert_eq!(output.as_deref(), Some("Read the image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completed_read_shows_the_image_file_it_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("icon.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let text = dir.path().join("a.rs");
|
||||
std::fs::write(&text, b"fn main() {}").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
for (id, path) in [("img", &png), ("src", &text)] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
|
||||
"locations": [{"path": path}]}));
|
||||
}
|
||||
let images = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { images, .. } => images.len(),
|
||||
_ => panic!(),
|
||||
};
|
||||
assert_eq!(images(&t, 0), 0, "not before the read completes");
|
||||
for id in ["img", "src"] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
|
||||
}
|
||||
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -10,3 +10,6 @@ ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -12,11 +12,12 @@ mod process;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
|
||||
const DEVICES: Duration = Duration::from_secs(20);
|
||||
@@ -28,6 +29,8 @@ const TAIL_LINES: u32 = 200;
|
||||
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
|
||||
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
|
||||
|
||||
fn exe(name: &str) -> String {
|
||||
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
|
||||
@@ -91,6 +94,51 @@ fn executable() -> IdeResult<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The SDK's `emulator` executable, which starts AVDs.
|
||||
pub fn emulator_executable() -> Option<PathBuf> {
|
||||
let name = exe("emulator");
|
||||
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Starts AVD `avd` in its own process group, so it
|
||||
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
|
||||
/// the emulator exits within its first seconds, with what it printed.
|
||||
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
|
||||
let emulator = emulator_executable().ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
|
||||
)
|
||||
})?;
|
||||
start_emulator(&emulator, avd)
|
||||
}
|
||||
|
||||
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
|
||||
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
|
||||
let log = std::fs::File::create(&log_path)?;
|
||||
let mut cmd = Command::new(emulator);
|
||||
cmd.arg("-avd").arg(avd);
|
||||
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
|
||||
let mut child = prepare(own_group(&mut cmd)).spawn()?;
|
||||
let deadline = Instant::now() + EMULATOR_STARTUP;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
|
||||
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
|
||||
return Err(IdeError::unavailable(if tail.is_empty() {
|
||||
format!("the emulator exited ({status})")
|
||||
} else {
|
||||
tail
|
||||
}));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
// Reaps it whenever it ends.
|
||||
std::thread::spawn(move || child.wait());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Connected devices, online ones first; starting the adb daemon when needed.
|
||||
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
|
||||
let adb = executable()?;
|
||||
@@ -206,6 +254,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
|
||||
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
|
||||
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
|
||||
|
||||
let args = dir.path().join("args");
|
||||
let running =
|
||||
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
|
||||
start_emulator(&running, "Pixel_9").unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
|
||||
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
|
||||
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_is_absolute_when_found() {
|
||||
if let Some(adb) = adb_executable() {
|
||||
|
||||
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
"help:evaluate".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -965,6 +965,7 @@ pub struct LaunchBuild {
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
/// The build's console, messages and progress stream to `on_event` as it runs.
|
||||
pub fn build_for_launch(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
@@ -972,8 +973,9 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
@@ -986,9 +988,10 @@ pub fn build_for_launches(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let result = run(root, &plan, cancel, on_event)?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
.messages
|
||||
@@ -1822,8 +1825,16 @@ mod tests {
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let dirs = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
true,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dirs.class_dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
@@ -1834,16 +1845,25 @@ mod tests {
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error =
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
let error = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
false,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
assert!(error.contains("Kotlin compilation failed"), "{error}");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
@@ -361,7 +361,9 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
|
||||
|
||||
@@ -16,6 +16,7 @@ mod process;
|
||||
#[cfg(test)]
|
||||
mod process_numbers;
|
||||
pub mod sbt;
|
||||
pub mod surefire;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
|
||||
@@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
Some(PathBuf::from(repo.replace("${user.home}", &home)))
|
||||
}
|
||||
|
||||
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
|
||||
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
|
||||
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
|
||||
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
|
||||
return Some(PathBuf::from(repo));
|
||||
}
|
||||
let mut args = options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return local_repository_of(Path::new(path)).or_else(default_local_repo);
|
||||
}
|
||||
}
|
||||
default_local_repo()
|
||||
}
|
||||
|
||||
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
|
||||
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
|
||||
/// in the local repository, which a repository filled from a private mirror often lacks even when
|
||||
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
|
||||
/// downloaded, else a pinned one.
|
||||
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
|
||||
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
|
||||
let (artifact, pinned) = match prefix {
|
||||
"help" => ("maven-help-plugin", "3.5.1"),
|
||||
"dependency" => ("maven-dependency-plugin", "3.8.1"),
|
||||
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
|
||||
};
|
||||
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
|
||||
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
|
||||
}
|
||||
|
||||
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
|
||||
/// from major version `min_major` up.
|
||||
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
|
||||
let dir = repo.join("org/apache/maven/plugins").join(artifact);
|
||||
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
|
||||
std::fs::read_dir(&dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter_map(|v| parse(&v).map(|n| (n, v)))
|
||||
.filter(|(n, v)| {
|
||||
n.first().is_some_and(|&major| major >= min_major)
|
||||
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
|
||||
})
|
||||
.max()
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
|
||||
Self::new_with_jdk(local_repo, profiles, None)
|
||||
@@ -2557,6 +2610,24 @@ mod tests {
|
||||
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ide_goals_resolve_from_the_repository_the_run_uses() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let settings = tmp.path().join("settings.xml");
|
||||
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
|
||||
let s = settings.to_string_lossy().into_owned();
|
||||
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
|
||||
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
|
||||
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
|
||||
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
|
||||
// No repository known: a pinned version, still by coordinates.
|
||||
assert_eq!(
|
||||
plugin_goal("dependency:build-classpath", None),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
|
||||
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
|
||||
//!
|
||||
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
|
||||
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
|
||||
|
||||
use crate::maven::{MavenModel, interpolate};
|
||||
use crate::xml::{self, Element};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::Path;
|
||||
|
||||
const SUREFIRE: &str = "maven-surefire-plugin";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SurefireConfig {
|
||||
/// `<argLine>`, split into JVM options.
|
||||
pub arg_line: Vec<String>,
|
||||
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
|
||||
pub system_properties: BTreeMap<String, String>,
|
||||
/// `<environmentVariables>`.
|
||||
pub environment: BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// `<additionalClasspathElements>`.
|
||||
pub additional_classpath: Vec<String>,
|
||||
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
|
||||
pub classpath_excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
|
||||
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
|
||||
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
|
||||
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
|
||||
let pom = root.join(&project.pom);
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
// A cache written before the POM last changed would apply an old configuration.
|
||||
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
|
||||
return None;
|
||||
}
|
||||
let root = xml::parse(&xml::read_text(&path)?)?;
|
||||
let projects: Vec<Element> = if root.name == "projects" {
|
||||
root.children.into_iter().filter(|p| p.name == "project").collect()
|
||||
} else {
|
||||
vec![root]
|
||||
};
|
||||
projects.into_iter().find(|p| {
|
||||
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
|
||||
group.as_deref() == Some(project.group_id.as_str())
|
||||
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
|
||||
})
|
||||
});
|
||||
let (element, own) = match effective {
|
||||
Some(e) => (e, false),
|
||||
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
|
||||
None => (xml::parse(&xml::read_text(&pom)?)?, true),
|
||||
};
|
||||
let mut props: HashMap<String, String> = element
|
||||
.child("properties")
|
||||
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
|
||||
.unwrap_or_default();
|
||||
let dir = module.to_string_lossy().into_owned();
|
||||
for (key, value) in [
|
||||
("basedir", dir.clone()),
|
||||
("project.basedir", dir.clone()),
|
||||
("project.build.directory", format!("{dir}/target")),
|
||||
("project.groupId", project.group_id.clone()),
|
||||
("project.artifactId", project.artifact_id.clone()),
|
||||
("project.version", project.version.clone()),
|
||||
] {
|
||||
props.entry(key.into()).or_insert(value);
|
||||
}
|
||||
Some(read(&element, &props, own))
|
||||
}
|
||||
|
||||
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
|
||||
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
|
||||
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
|
||||
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
if own && plugins.is_empty() {
|
||||
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
}
|
||||
let mut configurations: Vec<&Element> = Vec::new();
|
||||
for plugin in plugins {
|
||||
configurations.extend(plugin.child("configuration"));
|
||||
let default_test = plugin
|
||||
.list("executions", "execution")
|
||||
.into_iter()
|
||||
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
|
||||
configurations.extend(default_test.and_then(|e| e.child("configuration")));
|
||||
}
|
||||
let value = |text: &str| resolve(text.trim(), props);
|
||||
let mut config = SurefireConfig::default();
|
||||
for c in configurations {
|
||||
if let Some(arg_line) = c.child("argLine") {
|
||||
config.arg_line = split_arg_line(&value(&arg_line.text));
|
||||
}
|
||||
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
|
||||
config.system_properties.insert(p.name.clone(), value(&p.text));
|
||||
}
|
||||
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
|
||||
for p in c.list("systemProperties", "property") {
|
||||
if let Some(name) = p.text_of("name") {
|
||||
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
|
||||
config.environment.insert(e.name.clone(), value(&e.text));
|
||||
}
|
||||
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
|
||||
config.working_directory = Some(dir);
|
||||
}
|
||||
let texts = |list: &str, item: &str| -> Vec<String> {
|
||||
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
|
||||
};
|
||||
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
|
||||
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
|
||||
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
|
||||
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
|
||||
let mut out = interpolate(text, props);
|
||||
for open in ["@{", "${"] {
|
||||
while let Some(start) = out.find(open) {
|
||||
let Some(len) = out[start..].find('}') else { break };
|
||||
let key = &out[start + 2..start + len];
|
||||
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
|
||||
out.replace_range(start..=start + len, &replacement);
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
|
||||
fn split_arg_line(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current: Option<String> = None;
|
||||
let mut quote: Option<char> = None;
|
||||
for c in line.chars() {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => current.get_or_insert_default().push(c),
|
||||
None if c == '"' || c == '\'' => {
|
||||
quote = Some(c);
|
||||
current.get_or_insert_default();
|
||||
}
|
||||
None if c.is_whitespace() => out.extend(current.take()),
|
||||
None => current.get_or_insert_default().push(c),
|
||||
}
|
||||
}
|
||||
out.extend(current);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const POM: &str = r#"<project>
|
||||
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
|
||||
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
|
||||
<build><plugins><plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
|
||||
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
|
||||
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
|
||||
<environmentVariables><TZ>UTC</TZ></environmentVariables>
|
||||
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
|
||||
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
|
||||
</configuration>
|
||||
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
|
||||
</plugin></plugins></build>
|
||||
</project>"#;
|
||||
|
||||
fn model(dir: &Path) -> MavenModel {
|
||||
crate::maven::load(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join("pom.xml"), POM).unwrap();
|
||||
let cache = root.join("cache");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
let d = root.to_string_lossy();
|
||||
assert_eq!(
|
||||
config.arg_line,
|
||||
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
|
||||
);
|
||||
assert_eq!(config.system_properties["openidea.fail"], "true");
|
||||
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
|
||||
assert_eq!(config.system_properties["old"], "style");
|
||||
assert_eq!(config.environment["TZ"], "UTC");
|
||||
assert_eq!(config.working_directory, Some(format!("{d}/work")));
|
||||
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
|
||||
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
|
||||
|
||||
// A sync's effective POM wins: it has what the module inherits.
|
||||
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
|
||||
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
assert_eq!(config.arg_line[0], "-Xmx1g");
|
||||
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_arg_line_like_surefire() {
|
||||
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
|
||||
}
|
||||
}
|
||||
@@ -86,20 +86,29 @@ const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
|
||||
/// plugin version is, which may be cached instead.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from.
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
"help:effective-pom".into(),
|
||||
maven::plugin_goal("help:effective-pom", repo),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
|
||||
tree,
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
@@ -367,25 +376,8 @@ pub fn sync_maven(
|
||||
verbose: true,
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read
|
||||
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
|
||||
// then the user's default repository (which `plugin()` resolves itself).
|
||||
let local_repo: Option<PathBuf> =
|
||||
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|
||||
|| {
|
||||
let mut args = options.maven_options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return maven::local_repository_of(Path::new(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
},
|
||||
);
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
let repo = maven::local_repository_for(&options.maven_options);
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
@@ -407,7 +399,6 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
let repo = local_repo.clone().or_else(maven::default_local_repo);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
@@ -425,7 +416,7 @@ pub fn sync_maven(
|
||||
}
|
||||
})?;
|
||||
let effective_projects = std::fs::read_to_string(&effective)
|
||||
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
|
||||
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
|
||||
.unwrap_or_default();
|
||||
let trees = maven::parse_dependency_tree(&out.text);
|
||||
for (key, plugins, deps) in effective_projects {
|
||||
@@ -953,11 +944,27 @@ mod tests {
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, None);
|
||||
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[2], "dependency:tree");
|
||||
assert!(offline.contains(&"-Dverbose".to_owned()));
|
||||
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
|
||||
// #5757: offline, plugins in the local repository are named by their coordinates, since
|
||||
// the prefix needs group metadata a repository filled from a private mirror may lack.
|
||||
for (artifact, version) in
|
||||
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
|
||||
{
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
@@ -1029,7 +1036,7 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
|
||||
let maven = loaded.maven.unwrap();
|
||||
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
|
||||
@@ -1054,6 +1061,6 @@ mod tests {
|
||||
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
|
||||
// `-T1` pins the daemon serial so the dependency trees stay parseable.
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
}
|
||||
}
|
||||
@@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
"help:evaluate".into(),
|
||||
evaluate.clone(),
|
||||
"-Dexpression=project.id".into(),
|
||||
format!("-Doutput={}", output.display()),
|
||||
]);
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
|
||||
return Ok(WebBuild {
|
||||
command: top.command.clone(),
|
||||
args,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
use std::io::{Cursor, Error, ErrorKind, Result};
|
||||
|
||||
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
|
||||
/// retain transparency; the PNG flavor is also written for browsers and image editors.
|
||||
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
|
||||
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
|
||||
let mut decoder = png::Decoder::new(Cursor::new(png));
|
||||
decoder.set_transformations(png::Transformations::normalize_to_color8());
|
||||
let mut reader = decoder.read_info().map_err(invalid)?;
|
||||
let rgba_size = (reader.info().width as usize)
|
||||
.checked_mul(reader.info().height as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let size = reader
|
||||
.output_buffer_size()
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let mut pixels = vec![0; size];
|
||||
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
|
||||
let mut dib = vec![0; 124];
|
||||
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
|
||||
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
|
||||
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
|
||||
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
|
||||
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
|
||||
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
|
||||
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
|
||||
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
|
||||
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
|
||||
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
|
||||
let rgba = match info.color_type {
|
||||
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
|
||||
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
|
||||
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
|
||||
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
|
||||
png::ColorType::Indexed => unreachable!("palette expansion requested"),
|
||||
};
|
||||
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
|
||||
}
|
||||
Ok(dib)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut png, 1, 2);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
|
||||
}
|
||||
png
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
|
||||
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
let dib = png_to_dib(&png).unwrap();
|
||||
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
|
||||
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
|
||||
let round_trip = crate::dib_to_png(&dib).unwrap();
|
||||
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
|
||||
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut pixels).unwrap();
|
||||
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
|
||||
for (color, pixels, expected) in [
|
||||
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
|
||||
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
|
||||
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
|
||||
] {
|
||||
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
|
||||
}
|
||||
assert!(png_to_dib(b"not a PNG").is_err());
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,29 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
mod image;
|
||||
|
||||
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
|
||||
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
|
||||
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| !width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.is_some_and(|size| size <= 64 * 1024 * 1024)
|
||||
{
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
|
||||
}
|
||||
imp::set_png(png, owner)
|
||||
}
|
||||
|
||||
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
|
||||
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
@@ -240,6 +263,7 @@ mod imp {
|
||||
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
|
||||
/// bitmap on the clipboard reads as one.
|
||||
const CF_DIB: u32 = 8;
|
||||
const CF_DIBV5: u32 = 17;
|
||||
|
||||
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
|
||||
/// keeps transparency, so it is read first.
|
||||
@@ -422,6 +446,48 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
|
||||
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
|
||||
// before replacing the clipboard; free only allocations the OS did not take.
|
||||
unsafe {
|
||||
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
|
||||
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
|
||||
let error = std::io::Error::last_os_error();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let mut result = Ok(());
|
||||
if EmptyClipboard() == 0 {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
} else {
|
||||
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
|
||||
if SetClipboardData(*format, *memory).is_null() {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
break;
|
||||
}
|
||||
*memory = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
@@ -489,7 +555,7 @@ mod imp {
|
||||
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
|
||||
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
@@ -587,6 +653,23 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let data = NSData::with_bytes(png);
|
||||
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
board.clearContents();
|
||||
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other("Cannot write clipboard image"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
@@ -617,6 +700,21 @@ mod imp {
|
||||
mod imp {
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_image(&image);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = png;
|
||||
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
@@ -658,6 +756,15 @@ mod imp {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
|
||||
assert!(set_png(b"not a PNG", 0).is_err());
|
||||
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -201,6 +201,7 @@ pub struct FoldingSettings {
|
||||
pub file_header: bool,
|
||||
pub imports: bool,
|
||||
pub doc_comments: bool,
|
||||
pub go_short_blocks: bool,
|
||||
}
|
||||
|
||||
impl Default for FoldingSettings {
|
||||
@@ -211,6 +212,7 @@ impl Default for FoldingSettings {
|
||||
file_header: true,
|
||||
imports: true,
|
||||
doc_comments: false,
|
||||
go_short_blocks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -362,6 +364,8 @@ pub struct InlayHintsSettings {
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
|
||||
pub closing_labels: bool,
|
||||
pub disabled_languages: Vec<String>,
|
||||
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
|
||||
pub code_vision: bool,
|
||||
@@ -394,6 +398,7 @@ impl Default for InlayHintsSettings {
|
||||
types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision: true,
|
||||
code_vision_usages: true,
|
||||
|
||||
@@ -264,6 +264,20 @@ pub struct FlutterDevice {
|
||||
pub emulator: bool,
|
||||
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
|
||||
pub unavailable: Option<String>,
|
||||
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulator_id: Option<String>,
|
||||
}
|
||||
|
||||
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FlutterEmulator {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// `android` or `ios`.
|
||||
pub platform_type: Option<String>,
|
||||
}
|
||||
|
||||
/// See [`FlutterDeviceList`].
|
||||
@@ -289,6 +303,10 @@ pub enum FlutterDaemonStatus {
|
||||
pub struct FlutterDeviceList {
|
||||
pub status: FlutterDaemonStatus,
|
||||
pub devices: Vec<FlutterDevice>,
|
||||
/// The emulators that no listed device runs on.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulators: Vec<FlutterEmulator>,
|
||||
}
|
||||
|
||||
/// See [`IdeEvent::Direnv`].
|
||||
|
||||
@@ -145,7 +145,7 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: true,
|
||||
fold_turns: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
@@ -1657,6 +1657,20 @@ pub struct MavenSettings {
|
||||
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
|
||||
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
|
||||
pub update_snapshots: bool,
|
||||
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
|
||||
pub run_tests_using: MavenRunTestsUsing,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
|
||||
/// and run actions are delegated to Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MavenRunTestsUsing {
|
||||
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
|
||||
#[default]
|
||||
Ide,
|
||||
/// Surefire (`mvn test -Dtest=…`).
|
||||
Maven,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
@@ -2099,8 +2113,10 @@ mod tests {
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
assert!(!old.agents.fold_turns);
|
||||
assert!(!Settings::default().agents.show_cost);
|
||||
assert!(!Settings::default().agents.fit_window_width);
|
||||
assert!(!Settings::default().agents.fold_turns);
|
||||
let mut settings = Settings::default();
|
||||
settings.agents.show_usage_limits = false;
|
||||
settings.agents.fit_window_width = true;
|
||||
@@ -2318,6 +2334,7 @@ mod maven_linkage_tests {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.runner_jre.is_empty());
|
||||
assert!(!old.delegate_build);
|
||||
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
|
||||
assert!(MavenSettings::default().runner_jre.is_empty());
|
||||
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
|
||||
pub(crate) use scan::watch_for_attached_jvm;
|
||||
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
|
||||
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
|
||||
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
|
||||
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
|
||||
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
|
||||
|
||||
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(crate) trait AttachProbe: Send + Sync {
|
||||
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
|
||||
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
|
||||
fn is_application_jvm(&self, pid: u32) -> bool;
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
|
||||
}
|
||||
|
||||
pub(super) struct JdkProbe {
|
||||
@@ -91,6 +92,10 @@ impl AttachProbe for JdkProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
ide_jvm_attach::is_application_jvm(pid)
|
||||
}
|
||||
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
fn alive(pid: u32) -> bool {
|
||||
|
||||
@@ -47,6 +47,8 @@ struct FakeProbe {
|
||||
application_jvms: Vec<u32>,
|
||||
/// Pids `ensure_listener` was asked for.
|
||||
ensured: parking_lot::Mutex<Vec<u32>>,
|
||||
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
|
||||
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
type StopHook = Box<dyn Fn() + Send + Sync>;
|
||||
@@ -109,6 +111,8 @@ impl FakeProbe {
|
||||
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
|
||||
application_jvms: Vec::new(),
|
||||
ensured: parking_lot::Mutex::new(Vec::new()),
|
||||
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
|
||||
json_dirs: parking_lot::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +197,12 @@ impl AttachProbe for FakeProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
self.application_jvms.contains(&pid)
|
||||
}
|
||||
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
self.enter("thread_dump_json");
|
||||
self.json_dirs.lock().push(dir.to_owned());
|
||||
self.leave();
|
||||
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
|
||||
}
|
||||
}
|
||||
|
||||
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
|
||||
@@ -1205,10 +1215,95 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
|
||||
JvmThreadsUnavailable::Jvm { reason }
|
||||
}
|
||||
|
||||
/// The text dump alone: without a directory no JSON dump is asked for.
|
||||
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
|
||||
dump_threads(fake, pid, suspended, None, &|| suspended)
|
||||
}
|
||||
|
||||
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
|
||||
match r {
|
||||
JvmThreadsResult::Ready { dump } => dump,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
|
||||
|
||||
fn json_dir() -> &'static Path {
|
||||
Path::new("/data/cache/heap-snapshots/x")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_below_21_ask_for_no_json() {
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_on_21_add_the_json_after_the_text() {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!(dump.text, THREADS);
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_json_dump_keeps_the_text_dump() {
|
||||
let cases = [
|
||||
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
|
||||
(AttachError::Timeout, VirtualThreadsNote::Failed),
|
||||
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
|
||||
];
|
||||
for (error, note) in cases {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Err(error)].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
|
||||
}
|
||||
|
||||
// No directory to write the file into.
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_text(&fake, 12, false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_text_dump_asks_for_no_json() {
|
||||
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
|
||||
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_while_suspended_on_21_skip_the_json() {
|
||||
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// The program hits a breakpoint while the text dump is taken.
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let stop = stopped.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_while_running_start_the_listener() {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let r = dump_threads(&fake, 12, false);
|
||||
let r = dump_text(&fake, 12, false);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
|
||||
assert!(!dump.taken_while_suspended);
|
||||
@@ -1218,10 +1313,7 @@ fn threads_while_running_start_the_listener() {
|
||||
#[test]
|
||||
fn threads_while_suspended_without_listener_do_not_attach() {
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
|
||||
);
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
}
|
||||
|
||||
@@ -1230,12 +1322,12 @@ fn threads_while_suspended_on_11_are_refused() {
|
||||
let mut fake = dumping_threads(12, Vec::new());
|
||||
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
|
||||
);
|
||||
fake.version = None;
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
|
||||
);
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
@@ -1245,7 +1337,7 @@ fn threads_while_suspended_on_11_are_refused() {
|
||||
fn threads_while_suspended_on_17_use_the_running_listener() {
|
||||
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let r = dump_threads(&fake, 12, true);
|
||||
let r = dump_text(&fake, 12, true);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!(dump.java_version, "17.0.13");
|
||||
@@ -1257,7 +1349,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
|
||||
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
fake.application_jvms = vec![12];
|
||||
let r = dump_tree(&fake, &[10, 11, 12], false);
|
||||
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 12);
|
||||
assert_eq!(*fake.ensured.lock(), [12]);
|
||||
@@ -1266,7 +1358,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
|
||||
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
|
||||
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
|
||||
);
|
||||
assert_eq!(*fake.ensured.lock(), [10]);
|
||||
@@ -1290,7 +1382,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(std::process::id() as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
|
||||
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, jvm);
|
||||
assert_eq!(*fake.ensured.lock(), [jvm]);
|
||||
@@ -1340,7 +1432,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(99, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
@@ -1348,7 +1440,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
|
||||
assert_eq!(*fake.ensured.lock(), [555]);
|
||||
@@ -1369,26 +1461,71 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
|
||||
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
|
||||
let fake = Arc::new(dumping_threads(99, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!(dump.pid, 4242);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
|
||||
let bare = stopped_attach(4242);
|
||||
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running at first, the program hits a breakpoint while the text dump is taken.
|
||||
let bare = bare_session("attach");
|
||||
bare.session.jvm_pid.store(4242, Ordering::Release);
|
||||
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
|
||||
let session = bare.session.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
|
||||
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running, the same session gets the JSON dump too.
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let bare = bare_session("attach");
|
||||
@@ -1397,7 +1534,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let histogram = bare.session.jvm_memory.lock().await;
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
|
||||
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
|
||||
// The program hits a breakpoint while the dump waits behind the session's histogram.
|
||||
bare.session.suspended.stopped(None, true);
|
||||
@@ -1411,28 +1548,28 @@ fn threads_of_an_exited_program() {
|
||||
let mut fake = dumping_threads(99, Vec::new());
|
||||
fake.alive = false;
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_dump_errors_map_to_reasons() {
|
||||
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
|
||||
|
||||
let mut fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
|
||||
fake.alive = false;
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
|
||||
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
|
||||
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
|
||||
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
|
||||
panic!("not a failure")
|
||||
};
|
||||
assert!(message.contains("no"), "{message}");
|
||||
@@ -1456,14 +1593,20 @@ fn thread_results_serialize_with_camel_case_tags() {
|
||||
java_version: String::new(),
|
||||
taken_while_suspended: true,
|
||||
elapsed_ms: 3,
|
||||
virtual_json: None,
|
||||
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
|
||||
serde_json::json!({
|
||||
"status": "ready",
|
||||
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
|
||||
"dump": {
|
||||
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
|
||||
"virtualJson": null, "virtualNote": "whileSuspended"
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1479,7 +1622,7 @@ async fn threads_take_the_memory_lock() {
|
||||
let running = Suspension::default();
|
||||
let (classes, threads) = tokio::join!(
|
||||
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
|
||||
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
|
||||
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
|
||||
);
|
||||
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
|
||||
let threads = threads.unwrap();
|
||||
@@ -1493,12 +1636,14 @@ async fn threads_take_the_memory_lock() {
|
||||
async fn queued_thread_dump_reads_suspension_under_the_lock() {
|
||||
let pid = std::process::id();
|
||||
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
|
||||
let suspended = Suspension::default();
|
||||
let suspended = Arc::new(Suspension::default());
|
||||
let fake = Arc::new(dumping_threads(0, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let running = state.lock().await;
|
||||
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
|
||||
let stopped = suspended.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
|
||||
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
|
||||
// The program hits a breakpoint while the dump waits behind a class-table request.
|
||||
suspended.stopped(None, true);
|
||||
@@ -1515,12 +1660,27 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
|
||||
fake.jdwp = Some((5005, 4242));
|
||||
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
|
||||
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
|
||||
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
|
||||
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 4242);
|
||||
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
|
||||
let pid = std::process::id();
|
||||
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
|
||||
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
|
||||
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capability_matches_memory() {
|
||||
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
|
||||
|
||||
@@ -8,11 +8,15 @@ use super::{
|
||||
};
|
||||
use crate::session::Session;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_jvm_attach::AttachError;
|
||||
use ide_jvm_attach::{AttachError, JavaVersion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The first release whose virtual threads are final and that writes the JSON dump.
|
||||
const VIRTUAL_THREADS_MAJOR: u32 = 21;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JvmThreadDump {
|
||||
@@ -23,6 +27,20 @@ pub struct JvmThreadDump {
|
||||
pub taken_while_suspended: bool,
|
||||
/// Wall time of the `Thread.print` request.
|
||||
pub elapsed_ms: u32,
|
||||
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
|
||||
pub virtual_json: Option<String>,
|
||||
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
|
||||
pub virtual_note: Option<VirtualThreadsNote>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VirtualThreadsNote {
|
||||
/// A debugger holds the VM, which would hang the JSON request until it resumes.
|
||||
WhileSuspended,
|
||||
/// Over the attach reply limit (64 MiB).
|
||||
TooLarge,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -48,13 +66,17 @@ pub enum JvmThreadsResult {
|
||||
Unavailable { reason: JvmThreadsUnavailable },
|
||||
}
|
||||
|
||||
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
|
||||
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
|
||||
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
|
||||
/// dump timeouts, so callers run it in `spawn_blocking`.
|
||||
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
|
||||
dump_threads(&JdkProbe { suspended: false }, pid, false)
|
||||
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
|
||||
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
|
||||
}
|
||||
|
||||
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn session_thread_dump(
|
||||
session: Arc<Session>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
until_located(&session).await;
|
||||
let launched = histogram_pid(&session);
|
||||
// Detached, so a caller that gives up cannot release the lock while the JVM is still
|
||||
@@ -62,7 +84,9 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
tokio::spawn(async move {
|
||||
let target = session_target(&session, launched);
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
@@ -70,43 +94,53 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
|
||||
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
|
||||
/// is: a JVM the debugger holds suspended is never asked to open a listener.
|
||||
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn debugged_run_thread_dump(
|
||||
session: Arc<Session>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
// Detached for the same reason as `session_thread_dump`.
|
||||
tokio::spawn(async move {
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
known_pid_dump(&session, probe, pid).await
|
||||
known_pid_dump(&session, probe, pid, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
}
|
||||
|
||||
/// The session's suspension decides the JSON dump too: it is read again before that request.
|
||||
pub(super) async fn known_pid_dump(
|
||||
session: &Session,
|
||||
session: &Arc<Session>,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
let target =
|
||||
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
|
||||
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
|
||||
}
|
||||
|
||||
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
|
||||
/// session; `suspended` and then `probe` are read once it is held.
|
||||
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
|
||||
/// before the JSON dump.
|
||||
pub(super) async fn thread_dump(
|
||||
state: &tokio::sync::Mutex<JvmMemoryState>,
|
||||
suspended: impl FnOnce() -> bool,
|
||||
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
target: JvmTarget<'_>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
let _turn = state.lock().await;
|
||||
let suspended = suspended();
|
||||
let suspended = suspended_now();
|
||||
let lookup = match lookup(target) {
|
||||
Ok(lookup) => lookup,
|
||||
Err(reason) => return Ok(jvm(reason)),
|
||||
};
|
||||
let probe = probe(suspended);
|
||||
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
|
||||
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
|
||||
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
|
||||
Err(reason) => (None, jvm(reason)),
|
||||
})
|
||||
.await
|
||||
@@ -118,19 +152,32 @@ pub(super) async fn thread_dump(
|
||||
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
|
||||
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
|
||||
/// Gradle client), else the reported pid.
|
||||
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
|
||||
pub(super) fn dump_tree(
|
||||
probe: &dyn AttachProbe,
|
||||
tree: &[i32],
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> JvmThreadsResult {
|
||||
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
|
||||
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
|
||||
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
|
||||
match jvm_pid {
|
||||
Some(pid) => dump_threads(probe, pid, suspended),
|
||||
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
|
||||
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
|
||||
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
|
||||
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
|
||||
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
|
||||
pub(crate) fn dump_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> JvmThreadsResult {
|
||||
if suspended {
|
||||
if !probe.has_listener(pid) {
|
||||
return jvm(gone(probe, pid));
|
||||
@@ -149,6 +196,8 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
Err(e) => return failure(probe, pid, e),
|
||||
};
|
||||
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let (virtual_json, virtual_note) =
|
||||
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
|
||||
JvmThreadsResult::Ready {
|
||||
dump: JvmThreadDump {
|
||||
text,
|
||||
@@ -156,10 +205,40 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
java_version: version.map(|v| v.text).unwrap_or_default(),
|
||||
taken_while_suspended: suspended,
|
||||
elapsed_ms,
|
||||
virtual_json,
|
||||
virtual_note,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The program may have stopped during the text dump, so the suspension is read again.
|
||||
fn virtual_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
version: Option<&JavaVersion>,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> (Option<String>, Option<VirtualThreadsNote>) {
|
||||
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
|
||||
return (None, None);
|
||||
}
|
||||
if suspended || suspended_now() {
|
||||
return (None, Some(VirtualThreadsNote::WhileSuspended));
|
||||
}
|
||||
let Some(dir) = json_dir else {
|
||||
return (None, Some(VirtualThreadsNote::Failed));
|
||||
};
|
||||
match probe.thread_dump_json(pid, dir) {
|
||||
Ok(json) => (Some(json), None),
|
||||
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
|
||||
Err(e) => {
|
||||
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
|
||||
(None, Some(VirtualThreadsNote::Failed))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
|
||||
let reason = match error {
|
||||
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
|
||||
|
||||
@@ -1977,20 +1977,27 @@ impl DebugManager {
|
||||
jvm_memory::session_heap_dump(session, dir, cancel).await
|
||||
}
|
||||
|
||||
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
|
||||
/// debugger holds suspended is asked only when it is 17 or later and its listener already
|
||||
/// runs: otherwise the request would hang until the program resumes.
|
||||
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
|
||||
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
|
||||
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
|
||||
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
|
||||
/// until the program resumes.
|
||||
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
|
||||
let session = self.session(s)?;
|
||||
jvm_memory::session_thread_dump(session).await
|
||||
jvm_memory::session_thread_dump(session, json_dir).await
|
||||
}
|
||||
|
||||
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
|
||||
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
|
||||
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
|
||||
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
|
||||
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
|
||||
/// dump either. `None` when no session debugs `pid`.
|
||||
pub async fn debugged_jvm_thread_dump(
|
||||
&self,
|
||||
run: RunId,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> Option<IdeResult<JvmThreadsResult>> {
|
||||
let session = self.jvm_session_of(run, pid)?;
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
|
||||
}
|
||||
|
||||
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
|
||||
|
||||
@@ -3096,7 +3096,7 @@ async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
|
||||
let pid = jvm.id();
|
||||
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
|
||||
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
|
||||
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
|
||||
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid, None).await.unwrap().unwrap();
|
||||
let alive = jvm.try_wait().unwrap().is_none();
|
||||
let _ = jvm.kill();
|
||||
let _ = jvm.wait();
|
||||
@@ -3120,7 +3120,7 @@ async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
|
||||
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
|
||||
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
|
||||
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243, None).await.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
AND has_schema_privilege(nspname, 'USAGE') ORDER BY 1"
|
||||
}
|
||||
DbDriver::Mysql if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::SqlServer if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::SqlServer if system => "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1",
|
||||
DbDriver::Snowflake if system => "SELECT schema_name FROM information_schema.schemata ORDER BY 1",
|
||||
DbDriver::Snowflake => {
|
||||
"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'INFORMATION_SCHEMA' ORDER BY 1"
|
||||
@@ -89,8 +89,8 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') ORDER BY 1"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT schema_name FROM information_schema.schemata \
|
||||
WHERE schema_name NOT IN ('sys', 'information_schema', 'guest') ORDER BY 1"
|
||||
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \
|
||||
WHERE SCHEMA_NAME NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest') ORDER BY 1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,8 +133,8 @@ pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -177,14 +177,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT column_name, data_type, is_nullable, column_default, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = {s} \
|
||||
AND tc.table_name = {t} AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = {s} \
|
||||
AND tc.TABLE_NAME = {t} AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_SCHEMA = {s} AND c.TABLE_NAME = {t} \
|
||||
ORDER BY c.ORDINAL_POSITION"
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT column_name, {SNOWFLAKE_TYPE}, is_nullable, column_default, 0 \
|
||||
@@ -300,18 +300,18 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, c.is_nullable, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM information_schema.table_constraints tc \
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position"
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME \
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
@@ -372,11 +372,12 @@ pub fn foreign_keys(driver: DbDriver) -> &'static str {
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position LIMIT 20000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, \
|
||||
referenced_table_schema, referenced_table_name, referenced_column_name \
|
||||
FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL \
|
||||
AND table_schema NOT IN ('sys', 'information_schema') \
|
||||
ORDER BY table_schema, table_name, constraint_name, ordinal_position"
|
||||
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
|
||||
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
|
||||
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
|
||||
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
|
||||
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
|
||||
WHERE fk.is_ms_shipped = 0 ORDER BY 1, 2, 3, fkc.constraint_column_id"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, \
|
||||
@@ -410,7 +411,13 @@ pub fn table_foreign_keys(driver: DbDriver, schema: &str, table: &str) -> String
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT table_schema, table_name, constraint_name, column_name, referenced_table_schema, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE referenced_table_name IS NOT NULL AND table_schema = {s} AND table_name = {t} ORDER BY constraint_name, ordinal_position"
|
||||
"SELECT OBJECT_SCHEMA_NAME(fk.parent_object_id), OBJECT_NAME(fk.parent_object_id), fk.name, pc.name, \
|
||||
OBJECT_SCHEMA_NAME(fk.referenced_object_id), OBJECT_NAME(fk.referenced_object_id), rc.name \
|
||||
FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id \
|
||||
JOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id \
|
||||
JOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id \
|
||||
WHERE fk.parent_object_id = OBJECT_ID(N{}) ORDER BY 3, fkc.constraint_column_id",
|
||||
quote_literal(driver, &qualified(driver, schema, table))
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT con.owner, con.table_name, con.constraint_name, col.column_name, rcon.owner, rcon.table_name, rcol.column_name FROM all_constraints con JOIN all_cons_columns col ON col.owner = con.owner AND col.table_name = con.table_name AND col.constraint_name = con.constraint_name JOIN all_constraints rcon ON rcon.owner = con.r_owner AND rcon.constraint_name = con.r_constraint_name JOIN all_cons_columns rcol ON rcol.owner = rcon.owner AND rcol.table_name = rcon.table_name AND rcol.constraint_name = rcon.constraint_name WHERE con.constraint_type = 'R' AND con.owner = {s} AND con.table_name = {t} ORDER BY con.constraint_name, col.position"
|
||||
@@ -712,8 +719,8 @@ pub fn routines(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
)),
|
||||
DbDriver::SqlServer => Some(format!(
|
||||
"SELECT r.routine_name, lower(r.routine_type), '', r.data_type \
|
||||
FROM information_schema.routines r WHERE r.routine_schema = {s} ORDER BY 1"
|
||||
"SELECT r.ROUTINE_NAME, lower(r.ROUTINE_TYPE), '', r.DATA_TYPE \
|
||||
FROM INFORMATION_SCHEMA.ROUTINES r WHERE r.ROUTINE_SCHEMA = {s} ORDER BY 1"
|
||||
)),
|
||||
DbDriver::Snowflake => Some(format!(
|
||||
"SELECT function_name, 'function', argument_signature, data_type FROM information_schema.functions \
|
||||
@@ -1019,19 +1026,65 @@ mod tests {
|
||||
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
|
||||
assert_eq!(
|
||||
schemas(DbDriver::SqlServer, true),
|
||||
"SELECT schema_name FROM information_schema.schemata ORDER BY 1"
|
||||
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA ORDER BY 1"
|
||||
);
|
||||
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'information_schema', 'guest')"));
|
||||
assert!(schemas(DbDriver::SqlServer, false).contains("NOT IN ('sys', 'INFORMATION_SCHEMA', 'guest')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("information_schema.tables"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("information_schema.columns"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("referenced_table_name IS NOT NULL"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("table_schema = 'dbo'"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("information_schema.columns"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
/// `INFORMATION_SCHEMA` views and their columns in upper case, `sys` views in lower case.
|
||||
#[test]
|
||||
fn sqlserver_catalog_names_keep_their_declared_case() {
|
||||
let d = DbDriver::SqlServer;
|
||||
let queries = [
|
||||
schemas(d, true).to_owned(),
|
||||
schemas(d, false).to_owned(),
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
];
|
||||
const COLUMNS: [&str; 15] = [
|
||||
"information_schema",
|
||||
"schema_name",
|
||||
"table_name",
|
||||
"table_schema",
|
||||
"table_type",
|
||||
"column_name",
|
||||
"data_type",
|
||||
"is_nullable",
|
||||
"column_default",
|
||||
"constraint_name",
|
||||
"constraint_type",
|
||||
"ordinal_position",
|
||||
"routine_name",
|
||||
"routine_type",
|
||||
"routine_schema",
|
||||
];
|
||||
for q in queries {
|
||||
let words: Vec<&str> = q.split(|c: char| !c.is_alphanumeric() && c != '_').collect();
|
||||
for (i, word) in words.iter().enumerate() {
|
||||
let catalog = COLUMNS.contains(&word.to_lowercase().as_str())
|
||||
|| i > 0 && words[i - 1] == "INFORMATION_SCHEMA" && !word.is_empty();
|
||||
if catalog {
|
||||
assert_eq!(*word, word.to_uppercase(), "{word} in {q}");
|
||||
}
|
||||
}
|
||||
assert!(!q.contains("referenced_table_name"), "SQL Server has no referenced_* columns: {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -136,3 +136,62 @@ async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
assert!(!db.databases("s").await.unwrap().names.contains(&name));
|
||||
drop(held);
|
||||
}
|
||||
|
||||
/// #5772: a case-sensitive collation resolves catalog names only in their declared case.
|
||||
#[tokio::test]
|
||||
async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
use ide_db::sql;
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let parts = server.splitn(4, ':');
|
||||
let source = |database: &str| DataSource {
|
||||
driver: DbDriver::SqlServer,
|
||||
host: parts.clone().next().unwrap().into(),
|
||||
port: Some(parts.clone().nth(1).unwrap().parse().unwrap()),
|
||||
user: parts.clone().nth(2).unwrap().into(),
|
||||
database: database.into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let password = parts.clone().nth(3);
|
||||
let name = format!("oi_cs_catalog_{}", std::process::id());
|
||||
let master = Pool::connect(&source("master"), password, None).await.unwrap();
|
||||
master.rows(&format!("CREATE DATABASE {name} COLLATE Latin1_General_CS_AS"), 1).await.unwrap();
|
||||
let pool = Pool::connect(&source(&name), password, None).await.unwrap();
|
||||
pool.rows("CREATE TABLE dbo.Parent (Id int PRIMARY KEY)", 1).await.unwrap();
|
||||
pool.rows("CREATE TABLE dbo.Child (Id int PRIMARY KEY, ParentId int CONSTRAINT FK_Child_Parent REFERENCES dbo.Parent (Id))", 1)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.rows("CREATE VIEW dbo.Kids AS SELECT Id FROM dbo.Child", 1).await.unwrap();
|
||||
pool.rows("CREATE PROCEDURE dbo.Touch AS SELECT 1", 1).await.unwrap();
|
||||
let d = DbDriver::SqlServer;
|
||||
let cells = |rows: Vec<Vec<Option<String>>>| -> Vec<Vec<String>> {
|
||||
rows.into_iter().map(|r| r.into_iter().map(Option::unwrap_or_default).collect()).collect()
|
||||
};
|
||||
let schemas = cells(pool.rows(sql::schemas(d, false), 100).await.unwrap());
|
||||
assert!(schemas.contains(&vec!["dbo".to_owned()]));
|
||||
assert!(!schemas.iter().any(|s| s[0] == "INFORMATION_SCHEMA" || s[0] == "sys"));
|
||||
assert!(
|
||||
cells(pool.rows(sql::schemas(d, true), 100).await.unwrap()).contains(&vec!["INFORMATION_SCHEMA".to_owned()])
|
||||
);
|
||||
assert_eq!(
|
||||
cells(pool.rows(&sql::tables(d, "dbo"), 100).await.unwrap()),
|
||||
[["Child", "table"], ["Kids", "view"], ["Parent", "table"]]
|
||||
);
|
||||
assert_eq!(
|
||||
cells(pool.rows(&sql::columns(d, "dbo", "Child"), 100).await.unwrap())
|
||||
.iter()
|
||||
.map(|c| (c[0].as_str(), c[4].as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
[("Id", "1"), ("ParentId", "0")]
|
||||
);
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
.rows(&format!("ALTER DATABASE {name} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE {name}"), 1)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! The daemon speaks JSON-RPC over stdio, one bracketed message per line. After
|
||||
//! `daemon.connected` it is asked for `device.enable`, which makes it report `device.added` /
|
||||
//! `device.removed`, and once for `device.getDevices`, whose answer ends the "discovering" state.
|
||||
//! `emulator.getEmulators` lists what can be started, then and whenever the chooser opens.
|
||||
//!
|
||||
//! The daemon keeps running after its stdin closes, so closing the pipe does not end it: on Unix
|
||||
//! a watcher in its process group ends the group once the IDE is gone, even after a crash. A
|
||||
@@ -13,21 +14,25 @@ mod devtools;
|
||||
pub use devtools::DevToolsServer;
|
||||
|
||||
use ide_android::AndroidDevice;
|
||||
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList};
|
||||
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
|
||||
use ide_core::process::{kill_tree, own_group, prepare, terminate_tree};
|
||||
use ide_core::tool_path::{find_command, search_path_in};
|
||||
use ide_core::{IdeEvent, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
const ENABLE: u64 = 1;
|
||||
const GET_DEVICES: u64 = 2;
|
||||
const GET_EMULATORS: u64 = 3;
|
||||
/// `emulator.launch` waits for `xcrun simctl` or similar; past this the daemon is stuck.
|
||||
const LAUNCH_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// How long the daemon gets to exit on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(200);
|
||||
/// Lines of unrecognised output kept to explain a failure.
|
||||
@@ -39,6 +44,9 @@ enum Message {
|
||||
Added(FlutterDevice),
|
||||
Removed(String),
|
||||
Devices(Vec<FlutterDevice>),
|
||||
Emulators(Vec<FlutterEmulator>),
|
||||
/// The answer to a request of ours other than the ones above.
|
||||
Response(u64, Result<(), String>),
|
||||
Other,
|
||||
}
|
||||
|
||||
@@ -51,9 +59,15 @@ fn device(value: &Value) -> Option<FlutterDevice> {
|
||||
category: text("category"),
|
||||
emulator: value.get("emulator").and_then(Value::as_bool).unwrap_or(false),
|
||||
unavailable: None,
|
||||
emulator_id: text("emulatorId"),
|
||||
})
|
||||
}
|
||||
|
||||
fn emulator(value: &Value) -> Option<FlutterEmulator> {
|
||||
let text = |key| value.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
Some(FlutterEmulator { id: text("id")?, name: text("name")?, platform_type: text("platformType") })
|
||||
}
|
||||
|
||||
/// The messages of one stdout line; `None` for anything outside the protocol (the tool's own
|
||||
/// chatter, such as waiting for the startup lock).
|
||||
fn parse_line(line: &str) -> Option<Vec<Message>> {
|
||||
@@ -74,11 +88,23 @@ fn parse_message(message: &Value) -> Message {
|
||||
params.get("id").and_then(Value::as_str).map_or(Message::Other, |id| Message::Removed(id.to_owned()))
|
||||
}
|
||||
Some(_) => Message::Other,
|
||||
None if message.get("id").and_then(Value::as_u64) == Some(GET_DEVICES) => {
|
||||
let result = message.get("result").and_then(Value::as_array);
|
||||
Message::Devices(result.into_iter().flatten().filter_map(device).collect())
|
||||
None => {
|
||||
let result = message.get("result").and_then(Value::as_array).into_iter().flatten();
|
||||
match message.get("id").and_then(Value::as_u64) {
|
||||
Some(ENABLE) | None => Message::Other,
|
||||
Some(GET_DEVICES) => Message::Devices(result.filter_map(device).collect()),
|
||||
// A failure (no Android SDK, no Xcode) lists none.
|
||||
Some(GET_EMULATORS) => Message::Emulators(result.filter_map(emulator).collect()),
|
||||
Some(id) => Message::Response(
|
||||
id,
|
||||
match message.get("error") {
|
||||
None | Some(Value::Null) => Ok(()),
|
||||
Some(Value::String(error)) => Err(error.clone()),
|
||||
Some(error) => Err(error.to_string()),
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
None => Message::Other,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +112,12 @@ fn request(id: u64, method: &str) -> String {
|
||||
format!("{}\n", json!([{ "id": id, "method": method }]))
|
||||
}
|
||||
|
||||
/// The emulators no device runs on.
|
||||
fn idle_emulators(emulators: &[FlutterEmulator], devices: &BTreeMap<String, FlutterDevice>) -> Vec<FlutterEmulator> {
|
||||
let running = |e: &FlutterEmulator| devices.values().any(|d| d.emulator_id.as_ref() == Some(&e.id));
|
||||
emulators.iter().filter(|e| !running(e)).cloned().collect()
|
||||
}
|
||||
|
||||
/// The daemon's devices, plus the Android devices adb sees that Flutter leaves out until they
|
||||
/// are usable. A daemon Android device's id is its adb serial.
|
||||
fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Vec<FlutterDevice> {
|
||||
@@ -97,6 +129,7 @@ fn merged(daemon: &BTreeMap<String, FlutterDevice>, adb: &[AndroidDevice]) -> Ve
|
||||
category: Some("mobile".into()),
|
||||
emulator: d.serial.starts_with("emulator-"),
|
||||
unavailable: Some(d.state.clone()),
|
||||
emulator_id: None,
|
||||
}));
|
||||
let rank = |d: &FlutterDevice| match d.category.as_deref() {
|
||||
Some("mobile") => 0,
|
||||
@@ -121,15 +154,30 @@ struct State {
|
||||
status: FlutterDaemonStatus,
|
||||
devices: BTreeMap<String, FlutterDevice>,
|
||||
adb: Vec<AndroidDevice>,
|
||||
emulators: Vec<FlutterEmulator>,
|
||||
/// Requests awaiting their answer; dropped with the daemon, which fails them.
|
||||
pending: HashMap<u64, mpsc::Sender<Result<(), String>>>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn list(&self) -> FlutterDeviceList {
|
||||
FlutterDeviceList { status: self.status.clone(), devices: merged(&self.devices, &self.adb) }
|
||||
FlutterDeviceList {
|
||||
status: self.status.clone(),
|
||||
devices: merged(&self.devices, &self.adb),
|
||||
emulators: idle_emulators(&self.emulators, &self.devices),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `requests` to the daemon; false without one.
|
||||
fn send(&mut self, requests: &str) -> bool {
|
||||
let Some(stdin) = self.running.as_mut().and_then(|r| r.stdin.as_mut()) else { return false };
|
||||
stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush()).is_ok()
|
||||
}
|
||||
|
||||
fn shut_down(&mut self) {
|
||||
self.generation += 1;
|
||||
self.pending.clear();
|
||||
if let Some(Running { mut child, stdin }) = self.running.take() {
|
||||
drop(stdin);
|
||||
// Off the caller's thread: closing a window must not wait for the grace period.
|
||||
@@ -181,12 +229,48 @@ impl FlutterDaemon {
|
||||
state.list()
|
||||
}
|
||||
|
||||
/// Reads adb again: a device awaiting authorization changes no daemon event.
|
||||
/// Reads adb again (a device awaiting authorization changes no daemon event) and asks the
|
||||
/// daemon for its emulators again (one may have been created since).
|
||||
pub fn refresh(&self) {
|
||||
let generation = self.0.state.lock().generation;
|
||||
let mut state = self.0.state.lock();
|
||||
if state.status == FlutterDaemonStatus::Ready {
|
||||
state.send(&request(GET_EMULATORS, "emulator.getEmulators"));
|
||||
}
|
||||
let generation = state.generation;
|
||||
drop(state);
|
||||
refresh_adb(&self.0, generation);
|
||||
}
|
||||
|
||||
/// Starts an emulator the list offers; it shows up as a device once booted. Blocks until the
|
||||
/// launch is under way. An AVD is started by `ide-android` rather than the daemon, which
|
||||
/// would make it a child of its process group and end it with the daemon.
|
||||
pub fn launch_emulator(&self, id: &str) -> Result<(), String> {
|
||||
let mut state = self.0.state.lock();
|
||||
let android = state.emulators.iter().any(|e| e.id == id && e.platform_type.as_deref() == Some("android"));
|
||||
if android {
|
||||
drop(state);
|
||||
return ide_android::launch_emulator(id).map_err(|e| e.message);
|
||||
}
|
||||
state.next_id = state.next_id.max(GET_EMULATORS) + 1;
|
||||
let request_id = state.next_id;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
state.pending.insert(request_id, tx);
|
||||
let params = json!({ "emulatorId": id });
|
||||
let line = format!("{}\n", json!([{ "id": request_id, "method": "emulator.launch", "params": params }]));
|
||||
if !state.send(&line) {
|
||||
state.pending.remove(&request_id);
|
||||
return Err("the Flutter daemon is not running".into());
|
||||
}
|
||||
drop(state);
|
||||
let answer = rx.recv_timeout(LAUNCH_TIMEOUT);
|
||||
self.0.state.lock().pending.remove(&request_id);
|
||||
match answer {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Err("the Flutter daemon did not answer".into()),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Err("the Flutter daemon exited".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the daemon (project closed, or no longer trusted).
|
||||
pub fn stop(&self) {
|
||||
let mut state = self.0.state.lock();
|
||||
@@ -194,6 +278,7 @@ impl FlutterDaemon {
|
||||
state.status = FlutterDaemonStatus::Stopped;
|
||||
state.devices.clear();
|
||||
state.adb.clear();
|
||||
state.emulators.clear();
|
||||
}
|
||||
|
||||
/// Ends the daemon before returning, for a process about to exit.
|
||||
@@ -211,6 +296,7 @@ fn start(shared: &Arc<Shared>, state: &mut State) {
|
||||
state.status = FlutterDaemonStatus::Starting;
|
||||
state.devices.clear();
|
||||
state.adb.clear();
|
||||
state.emulators.clear();
|
||||
let (shared, generation) = (shared.clone(), state.generation);
|
||||
std::thread::spawn(move || run(&shared, generation));
|
||||
}
|
||||
@@ -265,6 +351,7 @@ fn finish(shared: &Shared, generation: u64, status: FlutterDaemonStatus) {
|
||||
return;
|
||||
}
|
||||
let running = state.running.take();
|
||||
state.pending.clear();
|
||||
state.status = status;
|
||||
let list = state.list();
|
||||
drop(state);
|
||||
@@ -358,12 +445,25 @@ fn handle(shared: &Arc<Shared>, generation: u64, message: Message) -> bool {
|
||||
match message {
|
||||
Message::Other => return true,
|
||||
Message::Connected => {
|
||||
if let Some(stdin) = state.running.as_mut().and_then(|r| r.stdin.as_mut()) {
|
||||
let requests = request(ENABLE, "device.enable") + &request(GET_DEVICES, "device.getDevices");
|
||||
let _ = stdin.write_all(requests.as_bytes()).and_then(|()| stdin.flush());
|
||||
state.send(
|
||||
&(request(ENABLE, "device.enable")
|
||||
+ &request(GET_DEVICES, "device.getDevices")
|
||||
+ &request(GET_EMULATORS, "emulator.getEmulators")),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
Message::Response(id, result) => {
|
||||
if let Some(tx) = state.pending.remove(&id) {
|
||||
let _ = tx.send(result);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Message::Emulators(emulators) => {
|
||||
if state.emulators == emulators {
|
||||
return true;
|
||||
}
|
||||
state.emulators = emulators;
|
||||
}
|
||||
Message::Added(device) => {
|
||||
state.devices.insert(device.id.clone(), device);
|
||||
}
|
||||
@@ -395,6 +495,7 @@ mod tests {
|
||||
category: Some(category.into()),
|
||||
emulator,
|
||||
unavailable: None,
|
||||
emulator_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,6 +534,33 @@ mod tests {
|
||||
let Some([Message::Devices(devices)]) = answer.as_deref() else { panic!("{answer:?}") };
|
||||
assert_eq!((devices[0].id.as_str(), devices[0].category.as_deref()), ("chrome", None));
|
||||
assert_eq!(parse_line(r#"[{"id":1,"result":null}]"#), Some(vec![Message::Other]));
|
||||
let emulators = parse_line(
|
||||
r#"[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]"#,
|
||||
);
|
||||
let Some([Message::Emulators(emulators)]) = emulators.as_deref() else { panic!("{emulators:?}") };
|
||||
assert_eq!(
|
||||
(emulators[0].id.as_str(), emulators[0].platform_type.as_deref()),
|
||||
("apple_ios_simulator", Some("ios"))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_line(r#"[{"id":3,"error":"Unable to find Android SDK","trace":""}]"#),
|
||||
Some(vec![Message::Emulators(vec![])])
|
||||
);
|
||||
assert_eq!(parse_line(r#"[{"id":7,"result":null}]"#), Some(vec![Message::Response(7, Ok(()))]));
|
||||
assert_eq!(
|
||||
parse_line(r#"[{"id":7,"error":"emulator 'x' not found","trace":"..."}]"#),
|
||||
Some(vec![Message::Response(7, Err("emulator 'x' not found".into()))])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offers_only_the_emulators_no_device_runs_on() {
|
||||
let emulator = |id: &str| FlutterEmulator { id: id.into(), name: id.into(), platform_type: None };
|
||||
let mut pixel = dev("emulator-5554", "Pixel", "mobile", true);
|
||||
pixel.emulator_id = Some("Pixel_9".into());
|
||||
let devices: BTreeMap<_, _> = [(pixel.id.clone(), pixel)].into_iter().collect();
|
||||
let idle = idle_emulators(&[emulator("Pixel_9"), emulator("apple_ios_simulator")], &devices);
|
||||
assert_eq!(idle, [emulator("apple_ios_simulator")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -498,8 +626,9 @@ mod tests {
|
||||
echo $$ > pid
|
||||
echo 'Waiting for another flutter command to release the startup lock...'
|
||||
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
|
||||
read enable; read get; echo "$enable$get" > requests
|
||||
read enable; read get; read emulators; echo "$enable$get$emulators" > requests
|
||||
echo '[{"id":1,"result":null}]'
|
||||
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","category":"mobile","platformType":"ios"}]}]'
|
||||
echo '[{"id":2,"result":[{"id":"macos","name":"macOS","category":"desktop","emulator":false}]}]'
|
||||
echo '[{"event":"device.added","params":{"id":"chrome","name":"Chrome","category":"web","emulator":false}}]'
|
||||
echo '[{"event":"device.removed","params":{"id":"macos","name":"macOS"}}]'
|
||||
@@ -518,6 +647,8 @@ cat > /dev/null
|
||||
});
|
||||
let requests = std::fs::read_to_string(dir.path().join("requests")).unwrap();
|
||||
assert!(requests.contains("device.enable") && requests.contains("device.getDevices"), "{requests}");
|
||||
assert!(requests.contains("emulator.getEmulators"), "{requests}");
|
||||
assert_eq!(daemon.devices().emulators[0].name, "iOS Simulator");
|
||||
assert!(lists.0.lock().iter().any(|l| l.devices.iter().any(|d| d.id == "macos")));
|
||||
|
||||
let pid = std::fs::read_to_string(dir.path().join("pid")).unwrap();
|
||||
@@ -529,6 +660,36 @@ cat > /dev/null
|
||||
assert_eq!(daemon.0.state.lock().status, FlutterDaemonStatus::Stopped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_an_emulator_through_the_daemon_and_reports_its_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = r#"
|
||||
echo '[{"event":"daemon.connected","params":{"version":"0.6.1","pid":1}}]'
|
||||
read enable; read get; read emulators
|
||||
echo '[{"id":2,"result":[]}]'
|
||||
echo '[{"id":3,"result":[{"id":"apple_ios_simulator","name":"iOS Simulator","platformType":"ios"}]}]'
|
||||
read launch; echo "$launch" > launch
|
||||
echo '[{"id":4,"result":null}]'
|
||||
read launch
|
||||
echo '[{"id":5,"error":"Unable to run Simulator: xcrun not found","trace":""}]'
|
||||
cat > /dev/null
|
||||
"#;
|
||||
let (daemon, _lists) = daemon(dir.path(), script);
|
||||
daemon.devices();
|
||||
wait_for("the emulators", || !daemon.devices().emulators.is_empty());
|
||||
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Ok(()));
|
||||
let launch = std::fs::read_to_string(dir.path().join("launch")).unwrap();
|
||||
let launch: Value = serde_json::from_str(&launch).unwrap();
|
||||
assert_eq!(launch[0]["method"], "emulator.launch");
|
||||
assert_eq!(launch[0]["params"], json!({ "emulatorId": "apple_ios_simulator" }));
|
||||
assert_eq!(
|
||||
daemon.launch_emulator("apple_ios_simulator"),
|
||||
Err("Unable to run Simulator: xcrun not found".into())
|
||||
);
|
||||
daemon.stop();
|
||||
assert_eq!(daemon.launch_emulator("apple_ios_simulator"), Err("the Flutter daemon is not running".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_daemon_does_not_outlive_the_ide() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -33,8 +33,10 @@ fn get_workspace_roots() -> Tool {
|
||||
"get_workspace_roots",
|
||||
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
|
||||
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
|
||||
Call this when asked about the workspace, project or working directories, and before planning a change that may span
|
||||
projects. Other tools reach an attached project by its root as `projectPath`.",
|
||||
Call this before the first project-related operation in a session, and when asked about the workspace, project or
|
||||
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
|
||||
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
|
||||
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
|
||||
|call| async move {
|
||||
let root = call.root().to_path_buf();
|
||||
let mut roots = vec![root.clone()];
|
||||
|
||||
@@ -515,6 +515,7 @@ async fn resolve_jvm_application(
|
||||
test == Some(true),
|
||||
policy,
|
||||
&cancel,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
use ide_lsp::jdtls::JavaBuildStatus;
|
||||
|
||||
@@ -114,6 +114,12 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
|
||||
config.extra_json = Some(extra.to_string());
|
||||
}
|
||||
if finds_java_sources(&config)
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
let roots = host.blocking(move || Ok(java_source_roots(&project))).await?;
|
||||
config = add_java_source_paths(config, &roots);
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
let mut ruby_tools = Vec::new();
|
||||
if config.adapter == "rdbg" && config.request == "launch" {
|
||||
@@ -308,6 +314,46 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch
|
||||
config
|
||||
}
|
||||
|
||||
/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed).
|
||||
fn java_source_roots(project: &crate::project::Project) -> Vec<PathBuf> {
|
||||
use ide_workspace::roots::RootKind;
|
||||
project
|
||||
.roots()
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map(|r| project.root.join(&r.path))
|
||||
.filter(|p| p.is_dir())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file:
|
||||
/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and
|
||||
/// java-analyzer after the module it debugs (whose sibling modules it does not load).
|
||||
fn finds_java_sources(config: &LaunchConfig) -> bool {
|
||||
matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER)
|
||||
}
|
||||
|
||||
/// Without a file for the stopped frame the editor cannot follow the execution point, so Java
|
||||
/// sessions get every source root of the project. The user's own list wins.
|
||||
fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig {
|
||||
if !finds_java_sources(&config) || roots.is_empty() {
|
||||
return config;
|
||||
}
|
||||
let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) {
|
||||
None => serde_json::Map::new(),
|
||||
Some(Ok(serde_json::Value::Object(extra))) => extra,
|
||||
Some(_) => return config,
|
||||
};
|
||||
if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) {
|
||||
return config;
|
||||
}
|
||||
let paths: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect();
|
||||
extra.insert("sourcePaths".into(), paths.into());
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
config
|
||||
}
|
||||
|
||||
/// A JVM launched by java-debug writes what java-debug decodes its output as
|
||||
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
|
||||
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
|
||||
@@ -671,11 +717,21 @@ pub async fn debug_jvm_memory_classes(
|
||||
host.debugger.jvm_memory_classes(session).await
|
||||
}
|
||||
|
||||
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
|
||||
/// A `Thread.print -l` of the debuggee JVM (with the JSON dump on JDK 21+), or why it cannot be
|
||||
/// taken.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
|
||||
host.require_trust(window)?;
|
||||
host.debugger.jvm_thread_dump(session).await
|
||||
let heap_root = host.heap.root().to_path_buf();
|
||||
let dir = host.blocking(move || Ok(super::thread_dump::json_dir(&heap_root))).await?;
|
||||
let result = host.debugger.jvm_thread_dump(session, dir.clone()).await;
|
||||
let _ = host
|
||||
.blocking(move || {
|
||||
super::thread_dump::discard_json_dir(dir);
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
/// Up to `limit` live instances of the class in the stopped JVM.
|
||||
@@ -737,6 +793,34 @@ mod tests {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_sessions_look_up_sources_in_project_roots() {
|
||||
let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")];
|
||||
let source_paths = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"]
|
||||
.clone()
|
||||
};
|
||||
for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] {
|
||||
for request in ["launch", "attach"] {
|
||||
let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots);
|
||||
assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"]));
|
||||
}
|
||||
}
|
||||
let mut bare = launch("java-debug", "attach", serde_json::json!({}));
|
||||
bare.extra_json = None;
|
||||
assert_eq!(
|
||||
source_paths(&add_java_source_paths(bare, &roots)),
|
||||
serde_json::json!(["/p/src/main/java", "/p/src/test/java"])
|
||||
);
|
||||
|
||||
let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]}));
|
||||
assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"]));
|
||||
let other = launch("debugpy", "launch", serde_json::json!({}));
|
||||
assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json);
|
||||
let none = launch("java-debug", "launch", serde_json::json!({}));
|
||||
assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_debug_launches_on_windows_write_utf8() {
|
||||
let extra =
|
||||
|
||||
@@ -25,6 +25,16 @@ pub fn flutter_daemon_restart(host: &Host, window: &str) -> IdeResult<FlutterDev
|
||||
Ok(host.project(window)?.flutter.restart())
|
||||
}
|
||||
|
||||
/// Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || project.flutter.launch_emulator(&id))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
/// The address of the project's DevTools server, started on first use. A server that failed or
|
||||
/// exited is only started again by the next request.
|
||||
#[command(trust = trusted)]
|
||||
@@ -36,4 +46,5 @@ pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String
|
||||
.map_err(IdeError::unavailable)
|
||||
}
|
||||
|
||||
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_devtools_url);
|
||||
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
|
||||
flutter_devtools_url);
|
||||
@@ -4,9 +4,11 @@ pub(crate) mod cache;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::Channel;
|
||||
use super::build::{load, with_profiles, workspace};
|
||||
use cache::LaunchEvents;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_build::compile::{self, BuildEvent};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
@@ -18,6 +20,8 @@ use std::path::{Path, PathBuf};
|
||||
/// Builds according to `policy`, then resolves the runtime (or test)
|
||||
/// classpath and the JDK of the module at `module` (absolute, or relative to the project root).
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
|
||||
/// whose build another launch's build joins receives that build's events.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_resolve_launch(
|
||||
host: &Host,
|
||||
@@ -26,12 +30,16 @@ pub async fn java_resolve_launch(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
request: RequestId,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
// Resources a Gradle build filters or renames are processed by Gradle, replacing the language
|
||||
// server's plain copies.
|
||||
host.require_trust(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel).await;
|
||||
let events: LaunchEvents = std::sync::Arc::new(move |event| {
|
||||
let _ = on_event.send(event);
|
||||
});
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -43,8 +51,15 @@ pub(crate) async fn resolve_launch(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let progress = |message: &str| {
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: message.to_owned(), fraction: None });
|
||||
}
|
||||
};
|
||||
progress("Resolving the module");
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
@@ -54,11 +69,11 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
@@ -90,6 +105,9 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
let mut external_build =
|
||||
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
if build && !delegated {
|
||||
progress("Compiling with the Java language server");
|
||||
}
|
||||
let mut info = project.lsp.java_launch(&module, test, build && !delegated, full, delegated, cancel).await?;
|
||||
if info.errors.iter().any(|e| processor_recreated_a_file(&e.message)) {
|
||||
if build && !delegated && is_maven {
|
||||
@@ -118,6 +136,11 @@ pub(crate) async fn resolve_launch(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
@@ -130,7 +153,7 @@ pub(crate) async fn resolve_launch(
|
||||
root,
|
||||
&model,
|
||||
&module,
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members, events: events.clone() },
|
||||
local_repo.clone(),
|
||||
&cancel,
|
||||
)?;
|
||||
@@ -140,7 +163,7 @@ pub(crate) async fn resolve_launch(
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel, &on_event)?;
|
||||
if let Some(failure) = built.failure {
|
||||
if policy != BuildPolicy::MakeAndContinueOnErrors {
|
||||
return Err(IdeError::internal(failure));
|
||||
@@ -154,6 +177,7 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
if delegated {
|
||||
on_event(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
// m2e runs inside jdtls on the server JDK and can resolve a different
|
||||
// Maven profile/classifier than the module build. Ask the same Maven
|
||||
// process that built the module for its runtime/test dependencies.
|
||||
@@ -203,6 +227,7 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
@@ -211,18 +236,24 @@ async fn resolve_launch_without_jdtls(
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
@@ -254,6 +285,9 @@ async fn resolve_launch_without_jdtls(
|
||||
}
|
||||
}
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
}
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
@@ -474,6 +508,7 @@ async fn build_members(
|
||||
members.push(cache::Member {
|
||||
module: launch.module.clone(),
|
||||
rebuild_on_jdt_errors: rebuild_on_jdt_errors(launch.policy, prefer_maven, errors),
|
||||
events: launch.events.clone(),
|
||||
});
|
||||
}
|
||||
Ok(members)
|
||||
@@ -646,6 +681,129 @@ pub async fn java_build_workspace(
|
||||
result
|
||||
}
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
class_paths: Vec<String>,
|
||||
) -> IdeResult<JunitLaunch> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
let surefire = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|maven| ide_build::surefire::surefire_config(&scope.root, &scope.cache, maven, &module))
|
||||
.unwrap_or_default();
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(junit_launch(&module, class_paths, surefire, [Some(runner), launcher].into_iter().flatten()))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The test JVM of OpenIDEA's JUnit runner.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JunitLaunch {
|
||||
pub class_paths: Vec<String>,
|
||||
/// Surefire's `argLine`, then its system properties as `-Dkey=value`.
|
||||
pub vm_args: Vec<String>,
|
||||
pub env: std::collections::BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// The Surefire settings that were applied (`argLine`, `systemPropertyVariables`…), for the console.
|
||||
pub surefire: Vec<String>,
|
||||
}
|
||||
|
||||
fn junit_launch(
|
||||
module: &Path,
|
||||
class_paths: Vec<String>,
|
||||
surefire: ide_build::surefire::SurefireConfig,
|
||||
runner: impl Iterator<Item = PathBuf>,
|
||||
) -> JunitLaunch {
|
||||
let mut applied = Vec::new();
|
||||
let mut note = |used: bool, name: &str| {
|
||||
if used {
|
||||
applied.push(name.to_owned());
|
||||
}
|
||||
};
|
||||
note(!surefire.arg_line.is_empty(), "argLine");
|
||||
note(!surefire.system_properties.is_empty(), "systemPropertyVariables");
|
||||
note(!surefire.environment.is_empty(), "environmentVariables");
|
||||
note(surefire.working_directory.is_some(), "workingDirectory");
|
||||
note(!surefire.additional_classpath.is_empty(), "additionalClasspathElements");
|
||||
note(!surefire.classpath_excludes.is_empty(), "classpathDependencyExcludes");
|
||||
// `group:artifact` in a Maven repository (`g/r/p/artifact/…`) or the Gradle cache (`g.r.p/artifact/…`).
|
||||
let excluded = |path: &str| {
|
||||
let path = path.replace('\\', "/");
|
||||
surefire.classpath_excludes.iter().any(|e| {
|
||||
e.split_once(':').is_some_and(|(group, artifact)| {
|
||||
path.contains(&format!("/{}/{artifact}/", group.replace('.', "/")))
|
||||
|| path.contains(&format!("/{group}/{artifact}/"))
|
||||
})
|
||||
})
|
||||
};
|
||||
let mut class_paths: Vec<String> = class_paths.into_iter().filter(|p| !excluded(p)).collect();
|
||||
class_paths.extend(surefire.additional_classpath);
|
||||
class_paths.extend(runner.map(|p| p.to_string_lossy().into_owned()));
|
||||
let mut vm_args = surefire.arg_line;
|
||||
vm_args.extend(surefire.system_properties.into_iter().map(|(k, v)| format!("-D{k}={v}")));
|
||||
JunitLaunch {
|
||||
class_paths,
|
||||
vm_args,
|
||||
env: surefire.environment,
|
||||
working_directory: surefire.working_directory.map(|d| module.join(d).to_string_lossy().into_owned()),
|
||||
surefire: applied,
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
let name = format!("junit-platform-launcher-{version}.jar");
|
||||
let dest = data_dir.join("junit").join(&name);
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
// ponytail: unverified like the Lombok download (Central publishes SHA-1 only); HTTPS from Central.
|
||||
let fetched = ide_tools::Http::new(&ide_core::tool_path::search_path())
|
||||
.map(ide_tools::Http::https_only)
|
||||
.and_then(|http| http.download(&url, &partial, None, &CancellationToken::new(), &|_| {}))
|
||||
.and_then(|()| Ok(std::fs::rename(&partial, &dest)?));
|
||||
fetched.map(|()| dest).map_err(|e| {
|
||||
IdeError::unavailable(format!(
|
||||
"Cannot download {name} from Maven Central ({}). Add org.junit.platform:junit-platform-launcher to the \
|
||||
test dependencies, or set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
e.message
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// An annotation processor's error for writing a file this build already wrote (JDT's
|
||||
/// `IdeFilerImpl`: "Source file already created", javac's Filer: "Attempt to recreate a file").
|
||||
fn processor_recreated_a_file(message: &str) -> bool {
|
||||
@@ -663,6 +821,35 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
arg_line: vec!["-Xmx1g".into()],
|
||||
system_properties: [("openidea.fail".to_owned(), "true".to_owned())].into(),
|
||||
environment: [("TZ".to_owned(), "UTC".to_owned())].into(),
|
||||
working_directory: Some("work".into()),
|
||||
additional_classpath: vec!["/extra".into()],
|
||||
classpath_excludes: vec!["org.slf4j:slf4j-simple".into(), "com.acme:gone".into()],
|
||||
};
|
||||
let classpath = vec![
|
||||
"/m/target/test-classes".into(),
|
||||
"/m2/org/slf4j/slf4j-simple/2.0/slf4j-simple-2.0.jar".into(),
|
||||
"/gradle/files-2.1/com.acme/gone/1/abc/gone-1.jar".into(),
|
||||
"/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar".into(),
|
||||
];
|
||||
let launch = junit_launch(Path::new("/m"), classpath, surefire, [PathBuf::from("/runner.jar")].into_iter());
|
||||
assert_eq!(
|
||||
launch.class_paths,
|
||||
["/m/target/test-classes", "/m2/org/slf4j/slf4j-api/2.0/slf4j-api-2.0.jar", "/extra", "/runner.jar"]
|
||||
);
|
||||
assert_eq!(launch.vm_args, ["-Xmx1g", "-Dopenidea.fail=true"]);
|
||||
assert_eq!(launch.env["TZ"], "UTC");
|
||||
assert_eq!(launch.working_directory.as_deref(), Path::new("/m").join("work").to_str());
|
||||
assert_eq!(launch.surefire.len(), 6);
|
||||
let plain = junit_launch(Path::new("/m"), vec![], Default::default(), std::iter::empty());
|
||||
assert!(plain.surefire.is_empty() && plain.vm_args.is_empty() && plain.working_directory.is_none());
|
||||
}
|
||||
|
||||
fn fake_jdk(dir: &Path, version: Option<&str>) -> PathBuf {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
@@ -946,4 +1133,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_resolve_launch);
|
||||
ide_command::domain!(java: java_build_workspace, java_debug_adapter, java_debug_server, java_junit_runner, java_resolve_launch);
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Immutable Maven outputs retained in the project cache, including across close/reopen.
|
||||
use ide_build::compile::{self, LaunchFingerprint};
|
||||
use ide_build::compile::{self, BuildEvent, LaunchFingerprint};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_run::BuildPolicy;
|
||||
use parking_lot::Mutex;
|
||||
@@ -131,6 +131,10 @@ pub(super) fn has_record(root: &Path, cache: &Path, module: &Path) -> bool {
|
||||
[false, true].into_iter().any(|test| record_path(root, cache, module, test).is_some_and(|record| record.is_file()))
|
||||
}
|
||||
|
||||
/// Where the build of a launch streams its console, messages and progress: the run
|
||||
/// console, the status bar and the Build tool window of the launch's request.
|
||||
pub(in crate::ops) type LaunchEvents = Arc<dyn Fn(BuildEvent) + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct BuildOptions {
|
||||
pub test: bool,
|
||||
@@ -142,13 +146,15 @@ pub(super) struct BuildOptions {
|
||||
/// together, #3971): their modules join this Maven run, and their launches then reuse
|
||||
/// the snapshots recorded here instead of running Maven again.
|
||||
pub members: Vec<Member>,
|
||||
/// The launch's own events; members that join the build get them too.
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// A launch module joining another launch's build; see [`BuildOptions::members`].
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Member {
|
||||
pub module: PathBuf,
|
||||
pub rebuild_on_jdt_errors: bool,
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// Launches share a build only within the same workspace project's cache.
|
||||
@@ -180,11 +186,12 @@ impl Sessions {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Waiting(Arc<Mutex<Vec<Arc<WaitingLaunch>>>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct WaitingLaunch {
|
||||
pub module: PathBuf,
|
||||
pub test: bool,
|
||||
pub policy: BuildPolicy,
|
||||
/// The launch's build events, for a build it joins.
|
||||
pub events: Option<LaunchEvents>,
|
||||
}
|
||||
|
||||
/// Leaves [`Waiting`] when dropped.
|
||||
@@ -194,8 +201,14 @@ pub(super) struct WaitingGuard {
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
pub(super) fn add(&self, module: PathBuf, test: bool, policy: BuildPolicy) -> WaitingGuard {
|
||||
let launch = Arc::new(WaitingLaunch { module, test, policy });
|
||||
pub(super) fn add(
|
||||
&self,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> WaitingGuard {
|
||||
let launch = Arc::new(WaitingLaunch { module, test, policy, events });
|
||||
self.0.lock().push(launch.clone());
|
||||
WaitingGuard { all: self.0.clone(), launch }
|
||||
}
|
||||
@@ -266,7 +279,7 @@ impl Session {
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Outputs> {
|
||||
self.initialize();
|
||||
let BuildOptions { test, policy, rebuild_on_jdt_errors, members } = options;
|
||||
let BuildOptions { test, policy, rebuild_on_jdt_errors, members, events } = options;
|
||||
let mut lead = match self.prepare(root, model, module, test, policy, &local_repo, cancel)? {
|
||||
Ok(outputs) => return Ok(outputs),
|
||||
Err(pending) => pending,
|
||||
@@ -284,11 +297,13 @@ impl Session {
|
||||
let policy = if rebuild_on_jdt_errors { BuildPolicy::Rebuild } else { policy };
|
||||
let mut joined = Vec::new();
|
||||
let mut rebuild = policy == BuildPolicy::Rebuild;
|
||||
let mut sinks: Vec<LaunchEvents> = events.into_iter().collect();
|
||||
for member in members {
|
||||
if let Err(pending) =
|
||||
self.prepare(root, model, &member.module, test, BuildPolicy::Make, &local_repo, cancel)?
|
||||
{
|
||||
rebuild |= member.rebuild_on_jdt_errors;
|
||||
sinks.extend(member.events);
|
||||
joined.push(pending);
|
||||
}
|
||||
}
|
||||
@@ -298,7 +313,13 @@ impl Session {
|
||||
tracing::info!(?modules, "Building the launch modules in one Maven run");
|
||||
}
|
||||
let kind = if rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel)?.into_iter();
|
||||
// Every launch waiting for this build follows it.
|
||||
let on_event = |event: BuildEvent| {
|
||||
for sink in &sinks {
|
||||
sink(event.clone());
|
||||
}
|
||||
};
|
||||
let mut built = compile::build_for_launches(root, model, &modules, test, kind, cancel, &on_event)?.into_iter();
|
||||
let lead_built = built.next().unwrap();
|
||||
for (pending, built) in joined.into_iter().zip(built) {
|
||||
match built.failure {
|
||||
@@ -648,10 +669,31 @@ mod tests {
|
||||
let mut session = Session::new(root.join("cache"));
|
||||
let (a, b) = (root.join("a"), root.join("b"));
|
||||
let with = |rebuild_on_jdt_errors: bool| BuildOptions {
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors }],
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors, events: None }],
|
||||
..Default::default()
|
||||
};
|
||||
let lead = session.build(root, &model, &a, with(false), None, &cancel).unwrap();
|
||||
// The lead's and the member's launches both follow the shared build.
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = |name: &'static str| -> LaunchEvents {
|
||||
let seen = seen.clone();
|
||||
Arc::new(move |event| {
|
||||
if let BuildEvent::Step { command, .. } = event {
|
||||
seen.lock().push(format!("{name}: {command}"));
|
||||
}
|
||||
})
|
||||
};
|
||||
let options = BuildOptions {
|
||||
members: vec![Member { module: b.clone(), rebuild_on_jdt_errors: false, events: Some(sink("b")) }],
|
||||
events: Some(sink("a")),
|
||||
..Default::default()
|
||||
};
|
||||
let lead = session.build(root, &model, &a, options, None, &cancel).unwrap();
|
||||
let seen = seen.lock().clone();
|
||||
assert_eq!(seen.len(), 2, "{seen:?}");
|
||||
assert!(
|
||||
seen[0].starts_with("a: ") && seen[1].starts_with("b: ") && seen[0].contains("-pl a,b -am"),
|
||||
"{seen:?}"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(lead.snapshot.join("0/Main.class")).unwrap(), "a");
|
||||
assert_eq!(fs::read_to_string(lead.snapshot.join("1/Main.class")).unwrap(), "lib");
|
||||
// b's own launch runs from the snapshot the shared build recorded for it.
|
||||
@@ -690,17 +732,17 @@ mod tests {
|
||||
let root = dir.path();
|
||||
let model = reactor_fixture(root);
|
||||
let waiting = Waiting::default();
|
||||
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic);
|
||||
let lead = waiting.add(root.join("a"), false, BuildPolicy::Automatic, None);
|
||||
let _guards = [
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Make),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("a"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("lib"), true, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild),
|
||||
waiting.add(root.join("other"), false, BuildPolicy::Automatic),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Make, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("b"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("a"), false, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("lib"), true, BuildPolicy::Automatic, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::Rebuild, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::MakeAndContinueOnErrors, None),
|
||||
waiting.add(root.join("lib"), false, BuildPolicy::NoBuild, None),
|
||||
waiting.add(root.join("other"), false, BuildPolicy::Automatic, None),
|
||||
];
|
||||
let join = |prefer_maven| {
|
||||
super::super::joining_launches(
|
||||
|
||||
@@ -3,6 +3,7 @@ use ide_command::command;
|
||||
use ide_core::{IdeResult, RunId};
|
||||
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
|
||||
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
|
||||
@@ -22,13 +23,43 @@ pub async fn run_jvm_thread_dump(
|
||||
Ok(pid) => pid,
|
||||
Err(refused) => return Ok(refused),
|
||||
};
|
||||
let heap_root = host.heap.root().to_path_buf();
|
||||
let dir = host.blocking(move || Ok(json_dir(&heap_root))).await?;
|
||||
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
|
||||
// may hold it suspended, which only its session knows.
|
||||
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
|
||||
return dump;
|
||||
let result = match host.debugger.debugged_jvm_thread_dump(id, pid, dir.clone()).await {
|
||||
Some(dump) => dump,
|
||||
None => {
|
||||
let json = dir.clone();
|
||||
// The attach handshake blocks for seconds.
|
||||
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid, json.as_deref()))).await
|
||||
}
|
||||
};
|
||||
let _ = host
|
||||
.blocking(move || {
|
||||
discard_json_dir(dir);
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
result
|
||||
}
|
||||
|
||||
/// A fresh owner-only directory for the JVM's JSON dump under the heap snapshot root, whose
|
||||
/// stale-directory sweep also removes a file a JVM writes after its request timed out. `None`
|
||||
/// when it cannot be created: the dump then goes without virtual threads.
|
||||
pub(crate) fn json_dir(heap_root: &Path) -> Option<PathBuf> {
|
||||
ide_heap::create_snapshot_dir(heap_root)
|
||||
.inspect_err(|e| tracing::warn!("no directory for the JSON thread dump under {}: {e}", heap_root.display()))
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(crate) fn discard_json_dir(dir: Option<PathBuf>) {
|
||||
if let Some(dir) = dir
|
||||
&& let Err(e) = std::fs::remove_dir_all(&dir)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("could not delete thread dump directory {}: {e}", dir.display());
|
||||
}
|
||||
// The attach handshake blocks for seconds.
|
||||
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
|
||||
}
|
||||
|
||||
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
|
||||
@@ -100,6 +131,30 @@ mod tests {
|
||||
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn json_dir_is_private_and_removed_afterwards() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let heap_root = root.path().join("heap-snapshots");
|
||||
let dir = json_dir(&heap_root).expect("a directory");
|
||||
assert_eq!(dir.parent(), Some(heap_root.as_path()));
|
||||
assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
// A file the JVM wrote after its request timed out goes with the directory.
|
||||
std::fs::write(dir.join("threads-1-2.json"), "{}").unwrap();
|
||||
discard_json_dir(Some(dir.clone()));
|
||||
assert!(!dir.exists());
|
||||
discard_json_dir(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dir_is_none_when_it_cannot_be_created() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let blocked = root.path().join("file");
|
||||
std::fs::write(&blocked, "").unwrap();
|
||||
assert_eq!(json_dir(&blocked), None);
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn unsupported_without_reading_the_process_table() {
|
||||
|
||||
@@ -85,9 +85,26 @@ done
|
||||
for (index, root) in roots.into_iter().enumerate() {
|
||||
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
|
||||
let test = index != 0;
|
||||
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
|
||||
.await
|
||||
.unwrap();
|
||||
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info =
|
||||
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
|
||||
.await
|
||||
.unwrap();
|
||||
// The build streams its command and progress while it runs.
|
||||
use ide_build::compile::BuildEvent;
|
||||
let events = events.lock().unwrap();
|
||||
assert!(
|
||||
events.iter().any(|e| matches!(e, BuildEvent::Step { command, .. } if command.contains("-pl app -am"))),
|
||||
"{events:?}"
|
||||
);
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.any(|e| matches!(e, BuildEvent::Progress { message, .. } if message == "Resolving the classpath")),
|
||||
"{events:?}"
|
||||
);
|
||||
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
|
||||
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
@@ -95,7 +112,7 @@ done
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains("dependency:build-classpath"), "{calls}");
|
||||
assert!(calls.contains(":build-classpath"), "{calls}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -305,6 +305,18 @@ impl PathFilter {
|
||||
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
|
||||
}
|
||||
|
||||
/// The folders directly in `dir` that the index would walk.
|
||||
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
|
||||
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
|
||||
builder
|
||||
.max_depth(Some(1))
|
||||
.build()
|
||||
.flatten()
|
||||
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
|
||||
.map(|e| e.into_path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
|
||||
let matches = parking_lot::Mutex::new(Vec::new());
|
||||
for root in self.roots() {
|
||||
|
||||
@@ -1246,3 +1246,66 @@ fn queries_during_streaming_scan_do_not_deadlock() {
|
||||
|
||||
done_rx.recv_timeout(Duration::from_secs(60)).expect("concurrent index queries deadlocked with streaming scan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconciling_a_few_changed_files_does_not_show_indexing() {
|
||||
let fx = sample();
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().push(e))
|
||||
};
|
||||
let idx = fx.open_with(sink);
|
||||
let announced = |events: &Mutex<Vec<IdeEvent>>| {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::IndexState { indexing: true, .. } | IdeEvent::Task { done: false, .. }))
|
||||
.count()
|
||||
};
|
||||
let settle = || {
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
// The touched folders are reconciled once the snapshot delay has passed.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
};
|
||||
|
||||
// A program appending to its log in the project, as a debugged Spring app does.
|
||||
events.lock().clear();
|
||||
let log = fx.write("logs/app.log", "start\n");
|
||||
for i in 0..3 {
|
||||
std::fs::write(&log, format!("line {i}\n").repeat(i + 1)).unwrap();
|
||||
idx.update(std::slice::from_ref(&log), &[]);
|
||||
settle();
|
||||
}
|
||||
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
|
||||
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
|
||||
}
|
||||
|
||||
/// #5749: a file at the project root changing must not re-walk the whole project when the
|
||||
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
|
||||
#[test]
|
||||
fn reconciling_a_root_change_lists_only_that_folder() {
|
||||
let fx = sample();
|
||||
let idx = fx.open();
|
||||
|
||||
// Written behind the index's back, deep in a folder it already knows.
|
||||
fx.write("src/order/Unreported.java", "class Unreported {}\n");
|
||||
// A new folder, a vanished one and an unreported file next to the changed root file.
|
||||
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
|
||||
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
|
||||
fx.write("Unlisted.txt", "x\n");
|
||||
let log = fx.write("app.log", "line\n");
|
||||
idx.update(std::slice::from_ref(&log), &[]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
// The touched folders are reconciled once the snapshot delay has passed.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
|
||||
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
|
||||
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
|
||||
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
|
||||
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
|
||||
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
|
||||
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
|
||||
}
|
||||
@@ -36,6 +36,15 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
|
||||
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
|
||||
#[cfg(test)]
|
||||
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
|
||||
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
|
||||
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
|
||||
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
|
||||
#[cfg(not(test))]
|
||||
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
|
||||
#[cfg(test)]
|
||||
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
|
||||
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
|
||||
const QUIET_SCAN_FILES: usize = 200;
|
||||
pub(crate) const MAX_RECENT: usize = 50;
|
||||
|
||||
pub(crate) enum Job {
|
||||
@@ -75,6 +84,8 @@ pub(crate) struct Shared {
|
||||
idle: Condvar,
|
||||
/// Coalesced post-update snapshot refresh.
|
||||
snapshot_due: Mutex<Option<Instant>>,
|
||||
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
|
||||
snapshot_saved: Mutex<Option<Instant>>,
|
||||
/// Directories whose watcher events still need reconciliation before a
|
||||
/// refreshed snapshot can be trusted.
|
||||
pending_dirs: Mutex<HashSet<PathBuf>>,
|
||||
@@ -103,6 +114,7 @@ impl Shared {
|
||||
wake: Condvar::new(),
|
||||
idle: Condvar::new(),
|
||||
snapshot_due: Mutex::default(),
|
||||
snapshot_saved: Mutex::default(),
|
||||
pending_dirs: Mutex::default(),
|
||||
}
|
||||
}
|
||||
@@ -444,7 +456,8 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// A cancelled scan (project closed) still ends its progress task and the indexing state.
|
||||
fn end_scan(&self, task: TaskId) {
|
||||
fn end_scan(&self, task: Option<TaskId>) {
|
||||
let Some(task) = task else { return };
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
@@ -471,13 +484,13 @@ impl Shared {
|
||||
}
|
||||
|
||||
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
|
||||
self.scan(None, found, guard);
|
||||
self.scan(None, &[], found, guard);
|
||||
// Parsing every file churns through far more memory than the index keeps.
|
||||
ide_core::memory::release_free_pages();
|
||||
}
|
||||
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
/// Shows "Indexing" (the status flag and a background task) for a scan.
|
||||
fn start_scan(&self) -> TaskId {
|
||||
self.indexing.store(true, Ordering::SeqCst);
|
||||
self.emit_state();
|
||||
let task = TaskId::next();
|
||||
@@ -489,6 +502,25 @@ impl Shared {
|
||||
done: false,
|
||||
cancellable: false,
|
||||
});
|
||||
task
|
||||
}
|
||||
|
||||
/// A full scan shows "Indexing" from the start. A subtree scan (folders the watcher reported,
|
||||
/// reconciled after each burst of changes) shows it only once it has
|
||||
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
|
||||
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
|
||||
///
|
||||
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
|
||||
/// them for a full scan) or directly in one of `shallow`.
|
||||
fn scan(
|
||||
&self,
|
||||
dirs: Option<&[PathBuf]>,
|
||||
shallow: &[PathBuf],
|
||||
prewalked: Option<Vec<Found>>,
|
||||
guard: SystemTime,
|
||||
) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
let mut task = dirs.is_none().then(|| self.start_scan());
|
||||
|
||||
let filter = self.filter();
|
||||
let walk_started = Instant::now();
|
||||
@@ -507,7 +539,10 @@ impl Shared {
|
||||
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
|
||||
let stale: Vec<PathBuf> = d
|
||||
.paths()
|
||||
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
|
||||
.filter(|p| {
|
||||
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|
||||
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
|
||||
})
|
||||
.filter(|p| !seen.contains(p.as_path()))
|
||||
.cloned()
|
||||
.collect();
|
||||
@@ -524,6 +559,9 @@ impl Shared {
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
if task.is_none() && total >= QUIET_SCAN_FILES {
|
||||
task = Some(self.start_scan());
|
||||
}
|
||||
let update_started = Instant::now();
|
||||
let mut laps = ChunkLaps::default();
|
||||
{
|
||||
@@ -564,7 +602,9 @@ impl Shared {
|
||||
}
|
||||
done += batch.len();
|
||||
laps.add(self.publish(batch.drain(..)));
|
||||
if last_progress.elapsed() >= PROGRESS_EVERY {
|
||||
if let Some(task) = task
|
||||
&& last_progress.elapsed() >= PROGRESS_EVERY
|
||||
{
|
||||
last_progress = Instant::now();
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
@@ -606,15 +646,19 @@ impl Shared {
|
||||
}
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
*self.snapshot_due.lock() = None;
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
title: "Indexing".into(),
|
||||
message: None,
|
||||
fraction: Some(1.0),
|
||||
done: true,
|
||||
cancellable: false,
|
||||
});
|
||||
*self.snapshot_saved.lock() = Some(Instant::now());
|
||||
if let Some(task) = task {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: task,
|
||||
title: "Indexing".into(),
|
||||
message: None,
|
||||
fraction: Some(1.0),
|
||||
done: true,
|
||||
cancellable: false,
|
||||
});
|
||||
}
|
||||
// The counts may have changed either way.
|
||||
self.emit_state();
|
||||
if self.is_cancelled() {
|
||||
return None;
|
||||
@@ -757,17 +801,67 @@ impl Shared {
|
||||
}
|
||||
let mut due = self.snapshot_due.lock();
|
||||
if due.is_none() {
|
||||
*due = Some(Instant::now() + SNAPSHOT_DELAY);
|
||||
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
|
||||
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
|
||||
/// A folder the index already has files below is listed one level deep: its own files, plus
|
||||
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
|
||||
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
|
||||
/// project after every change to a file at its root.
|
||||
fn reconcile(&self, dirs: &[PathBuf]) {
|
||||
let filter = self.filter();
|
||||
// The subfolders each reported folder has indexed files in; absent when it has none.
|
||||
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
|
||||
{
|
||||
let d = self.data.read();
|
||||
for path in d.paths() {
|
||||
for dir in dirs {
|
||||
let Ok(rest) = path.strip_prefix(dir) else { continue };
|
||||
let subdirs = known.entry(dir.as_path()).or_default();
|
||||
let mut parts = rest.components();
|
||||
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
|
||||
subdirs.insert(dir.join(first));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
let mut trees = Vec::new();
|
||||
let mut shallow = Vec::new();
|
||||
for dir in dirs {
|
||||
let Some(indexed) = known.get(dir.as_path()) else {
|
||||
found.extend(filter.walk(dir, &self.cancelled));
|
||||
trees.push(dir.clone());
|
||||
continue;
|
||||
};
|
||||
found.extend(filter.list_dir(dir));
|
||||
shallow.push(dir.clone());
|
||||
for sub in filter.child_dirs(dir) {
|
||||
if !indexed.contains(&sub) {
|
||||
found.extend(filter.walk(&sub, &self.cancelled));
|
||||
trees.push(sub);
|
||||
}
|
||||
}
|
||||
// Gone from disk; a subfolder only hidden from the listing (an extra content root
|
||||
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
|
||||
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
|
||||
}
|
||||
// Reported folders may nest; parse each file once.
|
||||
let mut unique = HashSet::new();
|
||||
found.retain(|f| unique.insert(f.path.clone()));
|
||||
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
|
||||
}
|
||||
|
||||
fn save_snapshot_now(&self) {
|
||||
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
|
||||
if !dirs.is_empty() {
|
||||
// Reconcile the directories touched since the last scan before
|
||||
// recording their mtimes; otherwise a missed watcher event could be
|
||||
// blessed into the manifest.
|
||||
self.scan(Some(&dirs), None, SystemTime::now());
|
||||
self.reconcile(&dirs);
|
||||
return;
|
||||
}
|
||||
if let Some(store) = &self.store {
|
||||
@@ -779,6 +873,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
*self.snapshot_due.lock() = None;
|
||||
*self.snapshot_saved.lock() = Some(Instant::now());
|
||||
}
|
||||
|
||||
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
|
||||
@@ -884,7 +979,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if !rescan {
|
||||
self.scan(Some(&roots), None, SystemTime::now());
|
||||
self.scan(Some(&roots), &[], None, SystemTime::now());
|
||||
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
|
||||
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
|
||||
}
|
||||
@@ -1174,7 +1269,7 @@ mod metric_tests {
|
||||
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
|
||||
}
|
||||
std::fs::write(root.join("keep.txt"), "x").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 41);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
@@ -1198,7 +1293,7 @@ mod metric_tests {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "x").unwrap();
|
||||
}
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 7);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
@@ -1233,11 +1328,11 @@ mod metric_tests {
|
||||
for i in 0..count {
|
||||
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
|
||||
}
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count as usize, count);
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
|
||||
assert_eq!(hot.outcomes.total(), 0);
|
||||
}
|
||||
@@ -1249,7 +1344,7 @@ mod metric_tests {
|
||||
let shared = shared(&root);
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
let (found, hash) = {
|
||||
let data = shared.data.read();
|
||||
let e = data.get(&path).unwrap();
|
||||
@@ -1269,10 +1364,10 @@ mod metric_tests {
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}\n").unwrap();
|
||||
let shared = shared(&root);
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
|
||||
assert_eq!(hot.outcomes, ExtractionCounts::default());
|
||||
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
|
||||
@@ -1283,7 +1378,7 @@ mod metric_tests {
|
||||
rec.mtime = rec.mtime.wrapping_add(1);
|
||||
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
|
||||
shared.data.write().insert(entry, symbols);
|
||||
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
|
||||
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().symbol_count, 1);
|
||||
@@ -1339,13 +1434,13 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let found = index.walk_roots(None);
|
||||
index.load_persisted(&found);
|
||||
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
|
||||
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
|
||||
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
|
||||
assert_eq!(counts.outcomes, ExtractionCounts::default());
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
@@ -1362,7 +1457,7 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
@@ -1411,7 +1506,7 @@ mod metric_tests {
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index.scan(None, None, SystemTime::now()).unwrap();
|
||||
index.scan(None, &[], None, SystemTime::now()).unwrap();
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
@@ -1462,7 +1557,7 @@ mod metric_tests {
|
||||
});
|
||||
index
|
||||
});
|
||||
assert!(index.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
|
||||
assert!(index.is_cancelled());
|
||||
assert!(!index.indexing.load(Ordering::Relaxed));
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
@@ -1473,7 +1568,7 @@ mod metric_tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let shared = shared(dir.path());
|
||||
shared.cancel();
|
||||
assert!(shared.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
|
||||
assert!(!shared.indexing.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,16 @@ const DUMP_BASE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// Only `-all` and a quoted path: any argument the DCmd rejects while the VM is suspended
|
||||
/// hangs the attach listener (17/21/25) until resume, and so does an unquoted path with a space.
|
||||
pub fn heap_dump_command(path: &Path) -> Result<String, AttachError> {
|
||||
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("heap dump path {path:?} is not UTF-8")))?;
|
||||
Ok(format!("GC.heap_dump -all {}", quoted_path(path, "heap dump")?))
|
||||
}
|
||||
|
||||
/// `path` in double quotes, as a DCmd argument; `what` names the file in errors.
|
||||
pub(crate) fn quoted_path(path: &Path, what: &str) -> Result<String, AttachError> {
|
||||
let text = path.to_str().ok_or_else(|| AttachError::Protocol(format!("{what} path {path:?} is not UTF-8")))?;
|
||||
if text.contains(['"', '\0', '\n', '\r']) {
|
||||
return Err(AttachError::Protocol(format!("heap dump path {text:?} cannot be quoted for the JVM")));
|
||||
return Err(AttachError::Protocol(format!("{what} path {text:?} cannot be quoted for the JVM")));
|
||||
}
|
||||
Ok(format!("GC.heap_dump -all \"{text}\""))
|
||||
Ok(format!("\"{text}\""))
|
||||
}
|
||||
|
||||
/// The JVM answers result code 0 for IO failures too, so success is told apart by its text.
|
||||
|
||||
@@ -20,5 +20,6 @@ pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
|
||||
pub use properties::{jdwp_port, parse_properties};
|
||||
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
|
||||
pub use threads::{
|
||||
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
|
||||
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm,
|
||||
thread_dump_json, thread_print,
|
||||
};
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::heap_dump::quoted_path;
|
||||
use crate::listener::is_hotspot;
|
||||
use crate::socket::{AttachError, jcmd};
|
||||
use crate::socket::{AttachError, MAX_OUTPUT, jcmd};
|
||||
|
||||
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
|
||||
/// bounds a JVM stuck at a safepoint.
|
||||
@@ -30,6 +33,55 @@ pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError>
|
||||
jcmd(pid, "Thread.print -l", timeout)
|
||||
}
|
||||
|
||||
/// `Thread.dump_to_file -format=json`, the only dump that lists virtual threads (JDK 21+). The
|
||||
/// JVM writes it into `dir`, an absolute directory; the file is read up to [`MAX_OUTPUT`] and
|
||||
/// deleted whatever the outcome. Never send it to a VM a debugger holds suspended: 21 and 25 hang
|
||||
/// the request, and every later attach request behind it, until the VM resumes.
|
||||
pub fn thread_dump_json(pid: u32, dir: &Path, timeout: Duration) -> Result<String, AttachError> {
|
||||
dump_json_with(pid, dir, MAX_OUTPUT, |command| jcmd(pid, command, timeout))
|
||||
}
|
||||
|
||||
fn dump_json_with(
|
||||
pid: u32,
|
||||
dir: &Path,
|
||||
max: usize,
|
||||
send: impl FnOnce(&str) -> Result<String, AttachError>,
|
||||
) -> Result<String, AttachError> {
|
||||
// The JVM resolves a relative path against its own working directory.
|
||||
if !dir.is_absolute() {
|
||||
return Err(AttachError::Protocol(format!("thread dump directory {dir:?} is not absolute")));
|
||||
}
|
||||
// JDK 21 has no `-overwrite` and writes nothing when the file exists.
|
||||
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
|
||||
let path = dir.join(format!("threads-{pid}-{nanos}.json"));
|
||||
let command = format!("Thread.dump_to_file -format=json {}", quoted_path(&path, "thread dump")?);
|
||||
let _delete = DeleteOnDrop(&path);
|
||||
let reply = send(&command)?;
|
||||
read_capped(&path, max).map_err(|e| match e {
|
||||
AttachError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
AttachError::Protocol(format!("the JVM wrote no thread dump: {}", reply.trim()))
|
||||
}
|
||||
e => e,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_capped(path: &Path, max: usize) -> Result<String, AttachError> {
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)?.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
return Err(AttachError::TooLarge);
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| AttachError::Protocol("the thread dump is not UTF-8".into()))
|
||||
}
|
||||
|
||||
struct DeleteOnDrop<'a>(&'a Path);
|
||||
|
||||
impl Drop for DeleteOnDrop<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ProcEntry {
|
||||
pub pid: u32,
|
||||
@@ -119,6 +171,7 @@ fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32)
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
|
||||
ProcEntry { pid, ppid, command: command.to_string() }
|
||||
@@ -239,6 +292,77 @@ mod tests {
|
||||
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
|
||||
}
|
||||
|
||||
/// The path the fake JVM is asked to write, from `Thread.dump_to_file … "<path>"`.
|
||||
fn requested_path(command: &str) -> PathBuf {
|
||||
PathBuf::from(command.split('"').nth(1).expect("quoted path"))
|
||||
}
|
||||
|
||||
fn is_empty(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).unwrap().next().is_none()
|
||||
}
|
||||
|
||||
/// `<tmp>/a b`: the space is what an unquoted path would break on.
|
||||
fn dir_with_space() -> (tempfile::TempDir, PathBuf) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let dir = root.path().join("a b");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
(root, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_reads_the_file_and_deletes_it() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let mut sent = String::new();
|
||||
let json = dump_json_with(42, &dir, 1024, |command| {
|
||||
sent = command.to_owned();
|
||||
std::fs::write(requested_path(command), "{\"threadDump\":{}}").unwrap();
|
||||
Ok(format!("Created {}\n", requested_path(command).display()))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(json, "{\"threadDump\":{}}");
|
||||
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
|
||||
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_file_is_deleted_when_it_is_too_large() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let result = dump_json_with(42, &dir, 1024, |command| {
|
||||
std::fs::write(requested_path(command), vec![b' '; 1025]).unwrap();
|
||||
Ok(String::new())
|
||||
});
|
||||
assert!(matches!(result, Err(AttachError::TooLarge)), "{result:?}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_file_is_deleted_when_the_request_fails() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
let result = dump_json_with(42, &dir, 1024, |command| {
|
||||
// The JVM wrote the file but the reply came too late.
|
||||
std::fs::write(requested_path(command), "{}").unwrap();
|
||||
Err(AttachError::Timeout)
|
||||
});
|
||||
assert!(matches!(result, Err(AttachError::Timeout)), "{result:?}");
|
||||
assert!(is_empty(&dir));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_without_a_file_reports_the_reply() {
|
||||
let (_root, dir) = dir_with_space();
|
||||
// JDK 21 answers result code 0 when it writes nothing.
|
||||
let result = dump_json_with(42, &dir, 1024, |_| Ok("/x.json exists, use -overwrite to overwrite\n".into()));
|
||||
let Err(AttachError::Protocol(message)) = result else { panic!("{result:?}") };
|
||||
assert!(message.contains("exists"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_dump_refuses_a_relative_directory() {
|
||||
let result = dump_json_with(42, Path::new("dumps"), 1024, |_| panic!("sent a relative path"));
|
||||
assert!(matches!(result, Err(AttachError::Protocol(_))), "{result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
|
||||
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_jvm_attach::{
|
||||
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
|
||||
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
|
||||
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
|
||||
select_run_jvm, temp_dir, thread_print, vm_flags,
|
||||
select_run_jvm, temp_dir, thread_dump_json, thread_print, vm_flags,
|
||||
};
|
||||
|
||||
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
|
||||
@@ -33,6 +33,25 @@ public class Deadlock {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Two virtual threads in a monitor deadlock, which `Thread.print` does not list.
|
||||
const VIRTUAL_DEADLOCK_JAVA: &str = r#"
|
||||
public class VirtualDeadlock {
|
||||
static final Object A = new Object(), B = new Object();
|
||||
|
||||
static void sleep(long ms) {
|
||||
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Thread.ofVirtual().name("v-sync-1").start(() -> { synchronized (A) { sleep(200); synchronized (B) { } } });
|
||||
Thread.ofVirtual().name("v-sync-2").start(() -> { synchronized (B) { sleep(200); synchronized (A) { } } });
|
||||
System.out.println("READY");
|
||||
System.out.flush();
|
||||
sleep(60_000);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
const MAIN_JAVA: &str = r#"
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -386,3 +405,33 @@ fn thread_print_reports_a_deadlock() {
|
||||
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
|
||||
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a real JDK >= 21: set OPENIDEA_TEST_JAVA to its bin/java"]
|
||||
fn thread_dump_json_lists_virtual_threads() {
|
||||
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
|
||||
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
|
||||
return;
|
||||
};
|
||||
let major = reported_major(&java);
|
||||
if major < 21 {
|
||||
eprintln!("JDK {major} has no virtual threads; skipping");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut guard =
|
||||
launch_class(&java, dir.path(), "VirtualDeadlock", VIRTUAL_DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
|
||||
let pid = guard.0.id();
|
||||
wait_for_ready(&output_lines(&mut guard.0));
|
||||
wait_for_listener(pid);
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
|
||||
let dumps = dir.path().join("a b");
|
||||
std::fs::create_dir(&dumps).unwrap();
|
||||
let started = Instant::now();
|
||||
let json = thread_dump_json(pid, &dumps, THREAD_DUMP_TIMEOUT).unwrap();
|
||||
eprintln!("JDK {major} JSON thread dump: {} bytes in {:?}", json.len(), started.elapsed());
|
||||
assert!(json.contains("\"threadContainers\""), "{json}");
|
||||
assert!(json.contains("\"v-sync-1\"") && json.contains("\"v-sync-2\""), "{json}");
|
||||
assert!(std::fs::read_dir(&dumps).unwrap().next().is_none(), "dump file left in {dumps:?}");
|
||||
}
|
||||
@@ -358,6 +358,7 @@ pub enum FoldKind {
|
||||
Region,
|
||||
Comment,
|
||||
Imports,
|
||||
Compact,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -144,7 +144,11 @@ pub(super) fn folding(
|
||||
if !node.is_named() {
|
||||
return true;
|
||||
}
|
||||
if let Some(close_row) = kinds.bracket_close_row(&node) {
|
||||
if spec.name == "go"
|
||||
&& let Some(end) = go_compact_end(&node, text)
|
||||
{
|
||||
push(&mut out, start, end, FoldKind::Compact);
|
||||
} else if let Some(close_row) = kinds.bracket_close_row(&node) {
|
||||
push(&mut out, start, close_row, FoldKind::Region);
|
||||
} else if kinds.has(&node, FOLD_NODE) {
|
||||
push(&mut out, start, last_content_row(&node, text), FoldKind::Region);
|
||||
@@ -157,6 +161,71 @@ pub(super) fn folding(
|
||||
out
|
||||
}
|
||||
|
||||
// Only join a single statement on the next line. Comments, blank lines and
|
||||
// nested multi-line statements must keep their own lines.
|
||||
fn go_compact_end(node: &Node, text: &str) -> Option<usize> {
|
||||
let start = node.start_position().row;
|
||||
let braced = match node.kind() {
|
||||
"block" => {
|
||||
let parent = node.parent()?;
|
||||
if parent.kind() != "if_statement"
|
||||
|| parent.child_by_field_name("consequence") != Some(*node)
|
||||
|| !go_error_guard(parent.child_by_field_name("condition")?, text)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
true
|
||||
}
|
||||
"expression_case" | "type_case" | "communication_case" | "default_case" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let body = node.named_child(node.named_child_count().checked_sub(1)?)?;
|
||||
if body.kind() != "statement_list" || body.named_child_count() != 1 {
|
||||
return None;
|
||||
}
|
||||
let header_end = body.prev_sibling()?;
|
||||
if header_end.kind() != if braced { "{" } else { ":" } || header_end.end_position().row != start {
|
||||
return None;
|
||||
}
|
||||
let statement = body.named_child(0)?;
|
||||
let position = statement.start_position();
|
||||
if statement.has_error()
|
||||
|| statement.is_extra()
|
||||
|| position.row != start + 1
|
||||
|| statement.end_position().row != position.row
|
||||
|| !own_line(text, statement.start_byte(), position.column)
|
||||
|| !text.get(header_end.end_byte()..statement.start_byte())?.trim().is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let tail = text.get(statement.end_byte()..)?.split('\n').next()?.trim();
|
||||
if !matches!(tail, "" | ";") {
|
||||
return None;
|
||||
}
|
||||
let end = start + if braced { 2 } else { 1 };
|
||||
(!braced || node.end_position().row == end).then_some(end)
|
||||
}
|
||||
|
||||
// Folding runs without Go type information. Recognize conventional error
|
||||
// guards and leave other nil checks alone.
|
||||
fn go_error_guard(condition: Node, text: &str) -> bool {
|
||||
if condition.kind() != "binary_expression"
|
||||
|| !condition.child_by_field_name("operator").is_some_and(|op| op.kind() == "!=")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (Some(left), Some(right)) = (condition.child_by_field_name("left"), condition.child_by_field_name("right"))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let name = match (left.kind(), right.kind()) {
|
||||
("identifier", "nil") => left,
|
||||
("nil", "identifier") => right,
|
||||
_ => return false,
|
||||
};
|
||||
name.utf8_text(text.as_bytes()).is_ok_and(|name| name == "err" || name.ends_with("Err"))
|
||||
}
|
||||
|
||||
fn push(out: &mut Vec<FoldRange>, start: usize, end: usize, kind: FoldKind) {
|
||||
if end > start {
|
||||
out.push(FoldRange { start_line: start as u32, end_line: end as u32, kind });
|
||||
|
||||
@@ -1206,6 +1206,56 @@ fn folding_go_imports_and_ruby_ends() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_compact_folds_keep_only_single_line_statements_inline() {
|
||||
let src = r#"package main
|
||||
|
||||
func f() {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return err // keep the comment on its own line
|
||||
}
|
||||
switch mode {
|
||||
case "compact":
|
||||
run()
|
||||
case "multi":
|
||||
run()
|
||||
stop()
|
||||
default:
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"keep both lines")
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let found = folds("go", src);
|
||||
let compact: Vec<_> = found.iter().copied().filter(|r| r.2 == FoldKind::Compact).collect();
|
||||
assert_eq!(compact, [(3, 5, FoldKind::Compact), (10, 11, FoldKind::Compact), (15, 16, FoldKind::Compact)]);
|
||||
assert!(found.contains(&(6, 8, FoldKind::Region)));
|
||||
assert!(found.contains(&(18, 21, FoldKind::Region)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_compact_if_folds_are_limited_to_conventional_error_guards() {
|
||||
for (guard, kind) in [
|
||||
("err != nil", FoldKind::Compact),
|
||||
("nil != err", FoldKind::Compact),
|
||||
("parseErr := parse(); parseErr != nil", FoldKind::Compact),
|
||||
("cfg != nil", FoldKind::Region),
|
||||
("err == nil", FoldKind::Region),
|
||||
("invalid", FoldKind::Region),
|
||||
] {
|
||||
let source = format!(
|
||||
"package main\nfunc f() error {{\n if {guard} {{\n return err\n }}\n return nil\n}}\n"
|
||||
);
|
||||
assert!(folds("go", &source).contains(&(2, 4, kind)), "unexpected fold for {guard}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_swift_control_flow_and_haskell_binds() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The Dart analysis server's closing labels (`dart/textDocument/publishClosingLabels`): the
|
||||
//! widget or call a closing `)` / `]` ends, shown after it at the end of the line (`// Column`).
|
||||
|
||||
use crate::convert::Conv;
|
||||
use crate::text::{DocText, Encoding, col_to_byte, units};
|
||||
use crate::types::{InlayHint, InlayKind};
|
||||
use ide_core::Pos;
|
||||
use lsp_types as lsp;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
#[cfg(test)]
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Params {
|
||||
pub uri: String,
|
||||
pub labels: Vec<Label>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
pub(crate) struct Label {
|
||||
range: lsp::Range,
|
||||
label: String,
|
||||
}
|
||||
|
||||
/// One end-of-line hint per line, as the Flutter plugin shows them: `// Padding // Center` when
|
||||
/// several constructs close on one line. A label whose range no longer ends in `)` or `]` (the
|
||||
/// text changed since the analysis) is left out.
|
||||
pub(crate) fn hints(conv: &Conv, path: &Path, text: &DocText, labels: Vec<Label>) -> Vec<InlayHint> {
|
||||
let mut lines: BTreeMap<u32, Vec<String>> = BTreeMap::new();
|
||||
for l in labels {
|
||||
let end = conv.pos(path, l.range.end);
|
||||
let line = text.line(end.line as usize);
|
||||
let before = &line[..col_to_byte(line, end.col as usize, Encoding::Utf16)];
|
||||
if before.ends_with([')', ']']) {
|
||||
lines.entry(end.line).or_default().push(l.label);
|
||||
}
|
||||
}
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|(line, labels)| InlayHint {
|
||||
position: Pos::new(line, units(text.line(line as usize), Encoding::Utf16) as u32),
|
||||
label: format!("// {}", labels.join(" // ")),
|
||||
kind: InlayKind::ClosingLabel,
|
||||
padding_left: true,
|
||||
padding_right: false,
|
||||
tooltip: None,
|
||||
parts: Vec::new(),
|
||||
text_edits: Vec::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn labels(v: serde_json::Value) -> Vec<Label> {
|
||||
serde_json::from_value(v).unwrap()
|
||||
}
|
||||
|
||||
fn label(line: u32, from: u32, to: u32, label: &str) -> serde_json::Value {
|
||||
json!({ "label": label, "range": { "start": { "line": line, "character": from }, "end": { "line": line, "character": to } } })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_go_to_the_end_of_the_line_and_share_it() {
|
||||
let text = DocText::new("return Center(\n child: Padding(\n child: Text('a'))), // x\n");
|
||||
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
|
||||
let hints = hints(
|
||||
&conv,
|
||||
Path::new("/a.dart"),
|
||||
&text,
|
||||
labels(json!([label(2, 4, 21, "Padding"), label(2, 4, 22, "Center"), label(2, 11, 20, "Text")])),
|
||||
);
|
||||
assert_eq!(hints.len(), 1);
|
||||
assert_eq!(hints[0].label, "// Padding // Center // Text");
|
||||
assert_eq!(hints[0].position, Pos::new(2, 28));
|
||||
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_that_no_longer_ends_at_a_bracket_is_dropped() {
|
||||
let text = DocText::new("Column(children: [])\nRow(\n");
|
||||
let conv = Conv::new(Encoding::Utf16, |_: &Path| None::<Arc<DocText>>);
|
||||
let hints = hints(
|
||||
&conv,
|
||||
Path::new("/a.dart"),
|
||||
&text,
|
||||
labels(json!([label(0, 0, 19, "<Widget>[]"), label(1, 0, 3, "Row")])),
|
||||
);
|
||||
assert_eq!(hints.iter().map(|h| h.label.as_str()).collect::<Vec<_>>(), ["// <Widget>[]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_servers_and_wide_characters_give_utf16_columns() {
|
||||
let text = Arc::new(DocText::new("Text('🙂')\n"));
|
||||
let doc = text.clone();
|
||||
let conv = Conv::new(Encoding::Utf8, move |_: &Path| Some(doc.clone()));
|
||||
let hints = hints(&conv, Path::new("/a.dart"), &text, labels(json!([label(0, 0, 12, "Text")])));
|
||||
assert_eq!(hints[0].position, Pos::new(0, 10));
|
||||
}
|
||||
}
|
||||
@@ -414,6 +414,23 @@ impl ClientHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_closing_labels(&self, mgr: &LspManager, params: Value) {
|
||||
let params: crate::closing_labels::Params = match serde_json::from_value(params) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
tracing::debug!("{}: bad publishClosingLabels: {e}", self.server.name);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(path) = uri_to_path(¶ms.uri) else { return };
|
||||
if !self.server.is_live(self.generation) {
|
||||
return;
|
||||
}
|
||||
if mgr.set_closing_labels(&path, &self.server, self.generation, self.encoding(), params.labels) {
|
||||
mgr.sink().emit(IdeEvent::LspRefresh { server: self.server.id, kind: LspRefreshKind::InlayHints });
|
||||
}
|
||||
}
|
||||
|
||||
/// Once per unresolved plugin, whether m2e marked a `pom.xml` or only logged it.
|
||||
fn build_plan_failure(&self, mgr: &LspManager, (plugin, body): (String, String)) {
|
||||
if mgr.first_message(&self.server.name, &format!("build plan: {plugin}")) {
|
||||
@@ -622,6 +639,7 @@ impl Handler for ClientHandler {
|
||||
}
|
||||
"textDocument/publishDiagnostics" => self.publish_diagnostics(&mgr, params),
|
||||
"dart/textDocument/publishFlutterOutline" => self.publish_flutter_outline(&mgr, params),
|
||||
"dart/textDocument/publishClosingLabels" => self.publish_closing_labels(&mgr, params),
|
||||
"window/showMessage" => self.show_message(&mgr, ¶ms),
|
||||
"window/logMessage" => {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
|
||||
|
||||
@@ -10,6 +10,7 @@ mod angular;
|
||||
mod arduino;
|
||||
mod caps;
|
||||
mod clang_tidy;
|
||||
mod closing_labels;
|
||||
mod compose;
|
||||
mod convert;
|
||||
mod external_project;
|
||||
@@ -150,6 +151,14 @@ struct DocState {
|
||||
/// When the servers last got new text (open or change): diagnostics published before are stale.
|
||||
changed: std::time::Instant,
|
||||
flutter_outline: Option<FlutterOutline>,
|
||||
/// The Dart server's closing labels for the current text; dropped on the next change.
|
||||
closing_labels: Option<ClosingLabels>,
|
||||
}
|
||||
|
||||
struct ClosingLabels {
|
||||
server: ide_core::ServerId,
|
||||
generation: u64,
|
||||
hints: Vec<InlayHint>,
|
||||
}
|
||||
|
||||
/// The widget tree last published for a document, valid while that server instance runs.
|
||||
@@ -1303,6 +1312,7 @@ impl LspManager {
|
||||
notebook: None,
|
||||
changed: std::time::Instant::now(),
|
||||
flutter_outline: None,
|
||||
closing_labels: None,
|
||||
};
|
||||
let compose_added = {
|
||||
let mut docs = self.docs.lock();
|
||||
@@ -1351,6 +1361,7 @@ impl LspManager {
|
||||
let Some(d) = docs.get_mut(&doc) else { return };
|
||||
d.version = version as i32;
|
||||
d.changed = std::time::Instant::now();
|
||||
d.closing_labels = None;
|
||||
|
||||
// Servers that have this document open on their current instance.
|
||||
let targets: Vec<(Arc<Server>, Running, SyncKind, Encoding)> = d
|
||||
@@ -2453,6 +2464,37 @@ impl LspManager {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Records published closing labels; whether what the open documents of `path` show changed.
|
||||
fn set_closing_labels(
|
||||
&self,
|
||||
path: &Path,
|
||||
server: &Server,
|
||||
generation: u64,
|
||||
enc: Encoding,
|
||||
labels: Vec<closing_labels::Label>,
|
||||
) -> bool {
|
||||
let mut changed = false;
|
||||
for d in self.docs.lock().values_mut().filter(|d| d.path == path && d.notebook.is_none()) {
|
||||
// Not `self.conv`: it would lock `docs` again for a UTF-8 server's text.
|
||||
let text = d.text.clone();
|
||||
let conv = Conv::new(enc, move |_: &Path| Some(text.clone()));
|
||||
let hints = closing_labels::hints(&conv, path, &d.text, labels.clone());
|
||||
changed |= !hints.is_empty() || d.closing_labels.as_ref().is_some_and(|c| !c.hints.is_empty());
|
||||
d.closing_labels = Some(ClosingLabels { server: server.id, generation, hints });
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn closing_label_hints(&self, doc: DocId, range: Range) -> Vec<InlayHint> {
|
||||
let docs = self.docs.lock();
|
||||
let Some(d) = docs.get(&doc) else { return Vec::new() };
|
||||
let Some(c) = d.closing_labels.as_ref() else { return Vec::new() };
|
||||
if !d.servers.iter().any(|a| a.server.id == c.server && a.server.is_live(c.generation)) {
|
||||
return Vec::new();
|
||||
}
|
||||
c.hints.iter().filter(|h| range.start <= h.position && h.position <= range.end).cloned().collect()
|
||||
}
|
||||
|
||||
pub async fn workspace_symbols(&self, query: &str, cancel: CancellationToken) -> IdeResult<Vec<WorkspaceSymbol>> {
|
||||
let servers: Vec<Arc<Server>> = self.servers.lock().clone();
|
||||
let targets = self.ready_targets(&servers, |c| c.has("workspaceSymbolProvider")).await;
|
||||
@@ -3315,6 +3357,7 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
let mut v = out.finish(Vec::new())?;
|
||||
v.extend(self.closing_label_hints(doc, range));
|
||||
v.sort_by_key(|h| h.position);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
@@ -237,6 +237,7 @@ impl LspManager {
|
||||
notebook: Some(path.to_owned()),
|
||||
changed: std::time::Instant::now(),
|
||||
flutter_outline: None,
|
||||
closing_labels: None,
|
||||
},
|
||||
);
|
||||
state.cells.push((cell.id.clone(), doc));
|
||||
|
||||
@@ -247,6 +247,8 @@ pub enum InlayKind {
|
||||
Type,
|
||||
Parameter,
|
||||
Other,
|
||||
/// What a closing bracket ends, at the end of its line (the Dart server's closing labels).
|
||||
ClosingLabel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -1549,6 +1549,40 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
|
||||
assert!(h.mgr.flutter_outline(reopened).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
let (doc, path) = h.open("a.mk", "Center(\n child: Text('x'))\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("mock");
|
||||
s.respond("textDocument/inlayHint", json!([]));
|
||||
let refreshes = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|e| matches!(e, IdeEvent::LspRefresh { kind: LspRefreshKind::InlayHints, .. }))
|
||||
.count()
|
||||
};
|
||||
let at = |l0: u32, c0: u32, c1: u32| json!({"start":{"line":l0,"character":c0},"end":{"line":1,"character":c1}});
|
||||
let labels = json!({ "uri": uri_of(&path), "labels": [
|
||||
{ "range": at(1, 9, 18), "label": "Text" },
|
||||
{ "range": at(0, 0, 19), "label": "Center" },
|
||||
]});
|
||||
s.peer().notify("dart/textDocument/publishClosingLabels", labels).unwrap();
|
||||
eventually(|| refreshes() == 1).await;
|
||||
let whole = Range::new(Pos::new(0, 0), Pos::new(2, 0));
|
||||
let hints = h.mgr.inlay_hints(doc, whole).await.unwrap();
|
||||
assert_eq!(hints.len(), 1);
|
||||
assert_eq!(hints[0].label, "// Text // Center");
|
||||
assert_eq!(hints[0].position, Pos::new(1, 19));
|
||||
assert_eq!(hints[0].kind, InlayKind::ClosingLabel);
|
||||
assert!(h.mgr.inlay_hints(doc, Range::new(Pos::new(0, 0), Pos::new(0, 7))).await.unwrap().is_empty());
|
||||
|
||||
// Edited text: the labels wait for the next analysis.
|
||||
h.mgr.did_change(doc, 2, &[change(rng(0, 0, 0, 0), " ")], &|| unreachable!());
|
||||
assert!(h.mgr.inlay_hints(doc, whole).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn diagnostics_become_events_and_feed_code_actions() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
|
||||
@@ -168,8 +168,13 @@ impl Session<'_> {
|
||||
"instructions": format!(
|
||||
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
|
||||
for a project open in a window, its editors. The project's workspace can include other \
|
||||
projects attached to it: call `get_workspace_roots` to list them before answering about \
|
||||
workspace directories or planning a change across projects."
|
||||
projects attached to it, which a session's working directory doesn't show. Before the \
|
||||
first project-related operation in a session, call `get_workspace_roots`: its \
|
||||
`projectRoot` is the project this connection serves and the default base for paths, and \
|
||||
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
|
||||
not a list of projects to change; it doesn't change your working directory or \
|
||||
permissions. Pass another root as `projectPath` to reach that project. Call it again \
|
||||
when the user switches projects or attaches one."
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -282,6 +282,8 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||||
|
||||
@@ -350,7 +350,7 @@ impl Cx<'_> {
|
||||
SPRING_BOOT => self.java_app(name, c, true, &mut ignored)?,
|
||||
GO_APPLICATION => self.go_config(name, c, false, &mut ignored)?,
|
||||
GO_TEST => self.go_config(name, c, true, &mut ignored)?,
|
||||
FLUTTER => self.flutter(name, c, &mut ignored)?,
|
||||
FLUTTER => self.flutter(name, c)?,
|
||||
COMPOUND => {
|
||||
members = c.children_named("toRun").filter_map(|t| t.attr("name")).map(str::to_owned).collect();
|
||||
config(name, "compound", String::new(), Vec::new(), None)
|
||||
@@ -440,8 +440,10 @@ impl Cx<'_> {
|
||||
}
|
||||
|
||||
/// The Flutter plugin's configuration (its `SdkFields`): `flutter run` in the entry's package,
|
||||
/// `additionalArgs` then `--flavor=<buildFlavor>` after the entry, as the plugin passes them.
|
||||
fn flutter(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
/// `--flavor=<buildFlavor>` then `additionalArgs` after the entry, in the order the Flutter
|
||||
/// form writes them. `attachArgs` (for Flutter Attach) is a form field: with it the form's
|
||||
/// params are stored.
|
||||
fn flutter(&self, name: &str, c: &El) -> Res<RunConfig> {
|
||||
let Some(entry) = self.path(c.option("filePath"))? else {
|
||||
return Err(SkipReason::NothingToRun);
|
||||
};
|
||||
@@ -449,9 +451,19 @@ impl Cx<'_> {
|
||||
let Some((package, _)) = dart_package(self.root, &entry) else {
|
||||
return Err(SkipReason::MissingFile { file: "pubspec.yaml".into() });
|
||||
};
|
||||
let mut extra = self.words(c.option("additionalArgs"))?;
|
||||
extra.extend(self.text(c.option("buildFlavor"))?.map(|f| format!("--flavor={f}")));
|
||||
let flavor = self.text(c.option("buildFlavor"))?;
|
||||
let mut extra: Vec<String> = flavor.iter().map(|f| format!("--flavor={f}")).collect();
|
||||
extra.extend(self.words(c.option("additionalArgs"))?);
|
||||
let mut rc = flutter_run(name, self.root, &package, &entry, extra);
|
||||
if let Some(attach) = self.text(c.option("attachArgs"))? {
|
||||
let params = [
|
||||
("entry", rc.args.get(2).cloned()),
|
||||
("flavor", flavor),
|
||||
("arguments", self.text(c.option("additionalArgs"))?),
|
||||
("attachArgs", Some(attach)),
|
||||
];
|
||||
rc.extras.params = params.into_iter().filter_map(|(k, v)| Some((k.to_owned(), v?))).collect();
|
||||
}
|
||||
// `<option name="envs"><map><entry key=… value=…/></map></option>`.
|
||||
let envs = c.children_named("option").filter(|o| o.attr("name") == Some("envs"));
|
||||
for e in envs.flat_map(|o| o.children.iter()).flat_map(|m| m.children_named("entry")) {
|
||||
@@ -459,9 +471,6 @@ impl Cx<'_> {
|
||||
rc.env.insert(key.to_owned(), e.attr("value").unwrap_or_default().to_owned());
|
||||
}
|
||||
}
|
||||
if self.text(c.option("attachArgs"))?.is_some() {
|
||||
ignored.push("attachArgs".into());
|
||||
}
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
|
||||
@@ -114,7 +114,8 @@ enum Line {
|
||||
///
|
||||
/// A read with NUL bytes, which text in the others never has, is UTF-16LE (ASCII characters
|
||||
/// and line ends in it have them); UTF-16 goes on until one of its lines has ended and a read
|
||||
/// without NUL bytes comes.
|
||||
/// without NUL bytes comes, or at once when a read without NUL bytes is text in UTF-8 again:
|
||||
/// a program that writes a buffer whose tail is NULs leaves a UTF-16 line that never ends.
|
||||
pub struct MixedDecoder {
|
||||
utf8: Utf8Decoder,
|
||||
native: Option<NativeDecoder>,
|
||||
@@ -133,22 +134,25 @@ impl MixedDecoder {
|
||||
return;
|
||||
}
|
||||
let nul = bytes.contains(&0);
|
||||
match self.utf16.as_ref().map(|u| u.open || nul) {
|
||||
Some(true) => {
|
||||
if let Some(u) = &mut self.utf16 {
|
||||
u.decode(bytes, out);
|
||||
}
|
||||
return;
|
||||
if let Some(u) = &self.utf16 {
|
||||
// UTF-16 text has a NUL byte in every ASCII character and in every line end: a read
|
||||
// without one that reads as UTF-8 is the console's own text again. It ends UTF-16
|
||||
// even mid-line, which a buffer written with a NUL tail never leaves.
|
||||
let text = !nul && !u.odd && reads_as_utf8(bytes);
|
||||
if text || !(u.open || nul) {
|
||||
self.utf16 = None;
|
||||
}
|
||||
Some(false) => self.utf16 = None,
|
||||
None if nul => {
|
||||
self.end_line(out);
|
||||
let mut u = Utf16::new();
|
||||
u.decode(utf16_aligned(bytes), out);
|
||||
self.utf16 = Some(u);
|
||||
return;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(u) = &mut self.utf16 {
|
||||
u.decode(bytes, out);
|
||||
return;
|
||||
}
|
||||
if nul {
|
||||
self.end_line(out);
|
||||
let mut u = Utf16::new();
|
||||
u.decode(utf16_aligned(bytes), out);
|
||||
self.utf16 = Some(u);
|
||||
return;
|
||||
}
|
||||
for piece in bytes.split_inclusive(|b| *b == b'\n') {
|
||||
let ends = piece.last() == Some(&b'\n');
|
||||
@@ -272,6 +276,12 @@ fn utf16_aligned(bytes: &[u8]) -> &[u8] {
|
||||
if even > odd { &bytes[1..] } else { bytes }
|
||||
}
|
||||
|
||||
/// Whether `bytes` is text in UTF-8: two code units or more, and valid. A shorter read could be
|
||||
/// one UTF-16 character that happens to be valid UTF-8 on its own.
|
||||
fn reads_as_utf8(bytes: &[u8]) -> bool {
|
||||
bytes.len() >= 4 && std::str::from_utf8(bytes).is_ok()
|
||||
}
|
||||
|
||||
fn decode_with(d: &mut encoding_rs::Decoder, bytes: &[u8], out: &mut String, last: bool) {
|
||||
let mut src = bytes;
|
||||
loop {
|
||||
@@ -441,6 +451,37 @@ mod encoding_tests {
|
||||
assert_eq!(out, "한국어 OK\r\n中文 OK\r\n");
|
||||
}
|
||||
|
||||
/// A program that writes a fixed-size buffer filled only in part, the rest NUL: the UTF-16
|
||||
/// line it looks like never ends, and what it writes after must not stay UTF-16LE.
|
||||
#[test]
|
||||
fn utf16_ends_at_the_text_after_a_line_that_never_ends() {
|
||||
let mut d = mixed(936);
|
||||
let mut out = String::new();
|
||||
d.decode_into("[10:45:00] before 正常输出\n".as_bytes(), &mut out);
|
||||
let mut buffer = b"abc".to_vec();
|
||||
buffer.resize(1024, 0);
|
||||
d.decode_into(&buffer, &mut out);
|
||||
d.decode_into("after-0: hello 正常输出\n".as_bytes(), &mut out);
|
||||
d.decode_into("after-1: hello 正常输出\n".as_bytes(), &mut out);
|
||||
out.push_str(&d.finish());
|
||||
assert!(out.starts_with("[10:45:00] before 正常输出\n"), "{out:?}");
|
||||
assert!(out.ends_with("after-0: hello 正常输出\nafter-1: hello 正常输出\n"), "{out:?}");
|
||||
}
|
||||
|
||||
/// `水` is `34 6C` in UTF-16LE, which reads as `4l` in UTF-8: a read that short is not
|
||||
/// taken for text again.
|
||||
#[test]
|
||||
fn a_short_read_that_is_a_utf16_character_stays_utf16() {
|
||||
let mut d = mixed(936);
|
||||
let mut out = String::new();
|
||||
d.decode_into(&utf16("OK "), &mut out);
|
||||
d.decode_into(&[0x34, 0x6C], &mut out);
|
||||
d.decode_into(&utf16("\r\n"), &mut out);
|
||||
d.decode_into("done ✓\n".as_bytes(), &mut out);
|
||||
out.push_str(&d.finish());
|
||||
assert_eq!(out, "OK 水\r\ndone ✓\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_code_page_other_lines_are_lossy_utf8_and_utf16_still_reads() {
|
||||
let mut d = MixedDecoder::new(None);
|
||||
|
||||
@@ -1238,11 +1238,22 @@ fn flutter_flavors_entry_points_arguments_and_envs() {
|
||||
assert_eq!(c.kind, "flutter");
|
||||
assert_eq!(
|
||||
c.args,
|
||||
s(&["run", "-t", "lib/main_dev.dart", "--dart-define=API=https://dev.example", "--verbose", "--flavor=dev"])
|
||||
s(&["run", "-t", "lib/main_dev.dart", "--flavor=dev", "--dart-define=API=https://dev.example", "--verbose"])
|
||||
);
|
||||
assert_eq!(cwd(c), Some(PathBuf::from("app")));
|
||||
assert_eq!(c.env, BTreeMap::from([("FLUTTER_LOG".into(), "1".into())]));
|
||||
assert_eq!(ignored(&r, "Dev"), ["attachArgs"]);
|
||||
// The Flutter form's fields, Additional attach args among them.
|
||||
let params = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
assert_eq!(
|
||||
c.extras.params,
|
||||
params(&[
|
||||
("entry", "lib/main_dev.dart"),
|
||||
("flavor", "dev"),
|
||||
("arguments", r#"--dart-define=API="https://dev.example" --verbose"#),
|
||||
("attachArgs", "--debug-port 9000"),
|
||||
])
|
||||
);
|
||||
assert!(ignored(&r, "Dev").is_empty());
|
||||
assert_eq!(reason(&r, "Gone"), &SkipReason::MissingFile { file: "pubspec.yaml".into() });
|
||||
assert_eq!(reason(&r, "No entry"), &SkipReason::NothingToRun);
|
||||
}
|
||||
@@ -127,6 +127,7 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
|
||||
description: def.description.clone(),
|
||||
git: def.git,
|
||||
fields: def.fields.iter().map(field).collect(),
|
||||
directory: def.directory.clone(),
|
||||
dynamic: def.service.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,16 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
|
||||
out
|
||||
}
|
||||
|
||||
/// The project folder's name: the generator's `directory` template (the solution name of a
|
||||
/// .NET project with a solution), or the project name.
|
||||
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
|
||||
def.directory
|
||||
.as_deref()
|
||||
.map(|t| render(t, values).trim().to_owned())
|
||||
.filter(|folder| !folder.is_empty())
|
||||
.unwrap_or_else(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The fields a project service adds to the form (its metadata); empty for other generators.
|
||||
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
|
||||
let def = def(id).ok_or_else(|| unknown(id))?;
|
||||
@@ -398,15 +408,19 @@ pub(crate) fn create_with(
|
||||
if let Some(e) = name_error(name) {
|
||||
return Err(IdeError::invalid(e));
|
||||
}
|
||||
let values = with_defaults(def, name, &req.values);
|
||||
let folder = project_folder(def, name, &values);
|
||||
if let Some(e) = name_error(&folder) {
|
||||
return Err(IdeError::invalid(e));
|
||||
}
|
||||
let location = req.location.to_path_buf();
|
||||
if !location.is_dir() {
|
||||
std::fs::create_dir_all(&location)?;
|
||||
}
|
||||
let target = location.join(name);
|
||||
let target = location.join(&folder);
|
||||
if target_taken(&target) {
|
||||
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
|
||||
}
|
||||
let values = with_defaults(def, name, &req.values);
|
||||
|
||||
let search = search_path();
|
||||
let mut missing = def
|
||||
@@ -420,10 +434,10 @@ pub(crate) fn create_with(
|
||||
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
|
||||
}
|
||||
|
||||
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
|
||||
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
|
||||
let _ = std::fs::remove_dir_all(&staging.0);
|
||||
std::fs::create_dir_all(&staging.0)?;
|
||||
let project = staging.0.join(name);
|
||||
let project = staging.0.join(&folder);
|
||||
|
||||
download_service(def, &values, &staging.0, &project, cancel, emit)?;
|
||||
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
|
||||
|
||||
@@ -169,6 +169,17 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
|
||||
let (pin, lines) = render(&[("solution", "false")]);
|
||||
assert_eq!(pin, None);
|
||||
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
|
||||
|
||||
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
|
||||
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
|
||||
let folder = |pairs: &[(&str, &str)]| {
|
||||
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
|
||||
};
|
||||
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
|
||||
assert_eq!(folder(&[]), "Shop");
|
||||
assert_eq!(folder(&[("solution", "false")]), "Shop");
|
||||
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -198,6 +209,11 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
|
||||
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
|
||||
assert_eq!(pin["sdk"]["version"], "10.0.400");
|
||||
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
|
||||
// A solution named apart from the project names the folder.
|
||||
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
|
||||
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(project, tmp.path().join("Store"));
|
||||
assert!(project.join("global.json").is_file());
|
||||
}
|
||||
|
||||
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
|
||||
|
||||
@@ -30,6 +30,11 @@ pub(crate) struct Def {
|
||||
pub requires: Vec<RequireDef>,
|
||||
#[serde(default)]
|
||||
pub fields: Vec<FieldDef>,
|
||||
/// The project folder's name, when it isn't the project name: a template over the fields
|
||||
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
|
||||
/// use it.
|
||||
#[serde(default)]
|
||||
pub directory: Option<String>,
|
||||
#[serde(default)]
|
||||
pub service: Option<ServiceDef>,
|
||||
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
|
||||
@@ -280,6 +285,9 @@ pub struct GeneratorInfo {
|
||||
/// Offer "Create Git repository".
|
||||
pub git: bool,
|
||||
pub fields: Vec<Field>,
|
||||
/// The project folder's name when it isn't the project name: a template over the fields
|
||||
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
|
||||
pub directory: Option<String>,
|
||||
/// More fields come from `scaffold_options` (a project service's metadata).
|
||||
pub dynamic: bool,
|
||||
}
|
||||
|
||||
@@ -1644,6 +1644,90 @@ pub fn jdbc_bridge_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Extracts the JUnit Platform test runner (`java/junit-runner`) into the application's data directory.
|
||||
pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"junit-runner",
|
||||
"1.0.0",
|
||||
include_bytes!("../../../java/junit-runner/openidea-junit-runner.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The JUnit Platform launcher a test classpath needs to start the runner.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum JunitLauncher {
|
||||
/// The classpath has `junit-platform-launcher` already.
|
||||
OnClasspath,
|
||||
/// `junit-platform-launcher` of the engine's version, next to the engine jar in its repository.
|
||||
Found(PathBuf),
|
||||
/// Not found locally: the engine's version, to download.
|
||||
Missing(String),
|
||||
/// No `junit-platform-engine` on the classpath (JUnit 4 alone, TestNG).
|
||||
NoPlatform,
|
||||
}
|
||||
|
||||
/// Like IDEA, the launcher must match the engine's version: a project usually depends on
|
||||
/// `junit-jupiter` only, which brings the engine but no launcher. The Maven local repository
|
||||
/// (`…/junit-platform-engine/<v>/…jar`) and the Gradle cache (`…/junit-platform-engine/<v>/<sha1>/…jar`)
|
||||
/// keep the launcher in a sibling folder.
|
||||
pub fn junit_launcher(class_paths: &[String]) -> JunitLauncher {
|
||||
let name = |p: &str| Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or_default().to_owned();
|
||||
if class_paths.iter().any(|p| name(p).starts_with("junit-platform-launcher-")) {
|
||||
return JunitLauncher::OnClasspath;
|
||||
}
|
||||
let Some((engine, version)) = class_paths.iter().find_map(|p| {
|
||||
let version = name(p).strip_prefix("junit-platform-engine-")?.strip_suffix(".jar")?.to_owned();
|
||||
Some((PathBuf::from(p), version))
|
||||
}) else {
|
||||
return JunitLauncher::NoPlatform;
|
||||
};
|
||||
let jar = format!("junit-platform-launcher-{version}.jar");
|
||||
let artifact = engine.ancestors().find(|a| a.file_name().is_some_and(|n| n == "junit-platform-engine"));
|
||||
let launcher_dir = artifact.and_then(Path::parent).map(|d| d.join("junit-platform-launcher").join(&version));
|
||||
let found = launcher_dir.and_then(|dir| {
|
||||
let direct = dir.join(&jar);
|
||||
if direct.is_file() {
|
||||
return Some(direct);
|
||||
}
|
||||
std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path().join(&jar)).find(|p| p.is_file())
|
||||
});
|
||||
match found {
|
||||
Some(path) => JunitLauncher::Found(path),
|
||||
None => JunitLauncher::Missing(version),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod junit_launcher_tests {
|
||||
use super::{JunitLauncher, junit_launcher};
|
||||
|
||||
#[test]
|
||||
fn finds_the_launcher_of_the_engine_version_in_maven_and_gradle_repositories() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = |p: &std::path::Path| p.to_string_lossy().into_owned();
|
||||
let maven = dir.path().join("m2/org/junit/platform");
|
||||
let maven_engine = maven.join("junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar");
|
||||
let maven_launcher = maven.join("junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar");
|
||||
let gradle = dir.path().join("gradle/files-2.1/org.junit.platform");
|
||||
let gradle_engine = gradle.join("junit-platform-engine/1.10.2/aaa/junit-platform-engine-1.10.2.jar");
|
||||
let gradle_launcher = gradle.join("junit-platform-launcher/1.10.2/bbb/junit-platform-launcher-1.10.2.jar");
|
||||
for jar in [&maven_engine, &maven_launcher, &gradle_engine, &gradle_launcher] {
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(jar, "").unwrap();
|
||||
}
|
||||
assert_eq!(junit_launcher(&["classes".into(), s(&maven_engine)]), JunitLauncher::Found(maven_launcher));
|
||||
assert_eq!(junit_launcher(&[s(&gradle_engine)]), JunitLauncher::Found(gradle_launcher));
|
||||
let other = dir.path().join("lib/junit-platform-engine-1.9.0.jar");
|
||||
assert_eq!(junit_launcher(&[s(&other)]), JunitLauncher::Missing("1.9.0".into()));
|
||||
assert_eq!(
|
||||
junit_launcher(&[s(&other), "/x/junit-platform-launcher-1.9.0.jar".into()]),
|
||||
JunitLauncher::OnClasspath
|
||||
);
|
||||
assert_eq!(junit_launcher(&["/x/junit-4.13.2.jar".into()]), JunitLauncher::NoPlatform);
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the app-owned JDT LS bundle that inspects java-debug's JVMs.
|
||||
pub fn jvm_inspect_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
|
||||
@@ -46,7 +46,10 @@ fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<Line
|
||||
utf16_len(&s.as_bytes()[..bounds.0])
|
||||
};
|
||||
(prev_start, prev_offset) = (bounds.0, text_offset);
|
||||
let (m, used) = in_window(line_no, s, rest, bounds, text_offset);
|
||||
// Only the ranges starting in the window: `in_window` reserves room for all it is given,
|
||||
// and the rest of a long line can hold every match on it.
|
||||
let starting = rest.partition_point(|&(a, _)| a <= bounds.1);
|
||||
let (m, used) = in_window(line_no, s, &rest[..starting], bounds, text_offset);
|
||||
out.push(m);
|
||||
rest = &rest[used.max(1)..];
|
||||
if rest.is_empty() {
|
||||
@@ -265,6 +268,17 @@ mod tests {
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_window_holds_room_for_its_own_matches_only() {
|
||||
// 7,000 windows of one match each on a 4 MB line.
|
||||
let s = format!("{}function", "x".repeat(592)).repeat(7_000);
|
||||
let ranges: Vec<_> = s.match_indices("function").map(|(a, m)| (a, a + m.len())).collect();
|
||||
let mut out = Vec::new();
|
||||
line_matches(0, s.as_bytes(), &ranges, &mut out);
|
||||
let reserved: usize = out.iter().map(|m| m.ranges.capacity()).sum();
|
||||
assert!(reserved <= 4 * out.len(), "{reserved} ranges reserved for {} windows", out.len());
|
||||
}
|
||||
|
||||
/// `main`'s windowing, which counts each window's offset from the line start.
|
||||
fn reference(line_no: u32, line: &[u8], ranges: &[(usize, usize)]) -> Vec<LineMatch> {
|
||||
fn from_str(line_no: u32, s: &str, ranges: &[(usize, usize)], out: &mut Vec<LineMatch>) {
|
||||
|
||||
@@ -3,11 +3,11 @@ title: "UI guidelines"
|
||||
description: "Rules for frontend UI code: design tokens, CSS Modules, icons, the UI primitives, accessibility and WebKit compatibility."
|
||||
---
|
||||
|
||||
The visual style is dark, low-contrast greys and one cool accent. Consistency comes from a small set of rules that apply to every component.
|
||||
The visual style is the JetBrains new UI in its Islands form: rounded content islands on a grey frame, low-contrast greys and one cool accent. Islands Light is the default theme, and Islands Dark, High Contrast and the Solarized themes set the same tokens. Consistency comes from a small set of rules that apply to every component.
|
||||
|
||||
## Design tokens
|
||||
|
||||
[`src/styles/tokens.css`](https://github.com/l0ng-ai/openidea/blob/main/src/styles/tokens.css) is the source of truth for colours and metrics (spacing, sizes, radii, font weights). `:root` holds the dark theme; `[data-theme="light"]` and `[data-theme="dark-hc"]` (high contrast) override it. Themes from plugins and colour-scheme settings set the same variables at runtime.
|
||||
[`src/styles/tokens.css`](https://github.com/l0ng-ai/openidea/blob/main/src/styles/tokens.css) is the source of truth for colours and metrics (spacing, sizes, radii, font weights). `:root` holds the dark theme; `[data-theme="light"]` (the default) and `[data-theme="dark-hc"]` (high contrast) override it. Themes from plugins and colour-scheme settings set the same variables at runtime.
|
||||
|
||||
- **Use only tokens in components.** No hex, `rgb()` or named colour literals in a component's CSS or inline styles: `color: var(--fg-muted)`, not `color: #8c8c8c`.
|
||||
- **Need a new colour or metric?** Add a token to `tokens.css` for every theme variant, with a name that says what it is for, not what it looks like.
|
||||
|
||||
@@ -62,17 +62,18 @@ When you edit a POM in the editor, the tool window shows **Build files changed s
|
||||
|
||||
**Settings › Build, Execution, Deployment › Maven**:
|
||||
|
||||
| Setting | What it does |
|
||||
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls |
|
||||
| **JRE** | JDK for Maven sync, builds, goals and tests |
|
||||
| **Maven home path** | A Maven installation to use instead of the project's `mvnw` |
|
||||
| **User settings file** | Passed as `-s` |
|
||||
| **Toolchains file** | Passed as `-t` |
|
||||
| **Local repository** | Passed as `-Dmaven.repo.local` |
|
||||
| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one |
|
||||
| **Thread count** | Passed as `-T` (for example `4` or `2C`) |
|
||||
| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 |
|
||||
| Setting | What it does |
|
||||
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Delegate IDE build/run actions to Maven** | Run and Debug build Maven modules with Maven (`javac`) instead of jdtls |
|
||||
| **Run tests using** | **OpenIDEA** (default): a JUnit 5 test run from the gutter starts on jdtls' test classpath, without Maven, with the module's Surefire configuration. **Maven**: Surefire |
|
||||
| **JRE** | JDK for Maven sync, builds, goals and tests |
|
||||
| **Maven home path** | A Maven installation to use instead of the project's `mvnw` |
|
||||
| **User settings file** | Passed as `-s` |
|
||||
| **Toolchains file** | Passed as `-t` |
|
||||
| **Local repository** | Passed as `-Dmaven.repo.local` |
|
||||
| **Active profiles** | Comma-separated profiles (`-P`); `!id` excludes one |
|
||||
| **Thread count** | Passed as `-T` (for example `4` or `2C`) |
|
||||
| **Use Maven Daemon (mvnd)** | Runs builds, sync and run configurations through `mvnd`; falls back to `mvn` if it is missing or the JDK is older than 17 |
|
||||
|
||||
## Gradle
|
||||
|
||||
|
||||
@@ -107,9 +107,12 @@ Double-click a table to edit its data, a data source to open its console, and a
|
||||
| Duplicate (data source) | `⌘D` | `Ctrl+D` |
|
||||
| Generate DDL to Clipboard | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
|
||||
| Generate DDL to Query Console | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
|
||||
| Diagrams › Show Diagram | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
|
||||
|
||||
These keys work while the Database tree has focus. The context menu also has **Truncate…**, **Run SQL Script…** (runs every statement of a `.sql` file), **Import Data from File…**, **Go to Referenced Table** (on foreign keys), SQL templates (select, insert, update, delete) and **Remove Data Source…**.
|
||||
|
||||
**Diagrams › Show Diagram** opens a read-only ER diagram of the selected tables, or of every table of a selected schema (up to 50), in an editor tab: columns with `PK` / `FK` markers and the foreign keys between the shown tables. Select several tables with `⌘`/`Ctrl`-click or `Shift`-click. Zoom with `⌘`/`Ctrl`+wheel; the diagram's buttons show it full screen or save it as an image.
|
||||
|
||||
**Modify Table…** and **New › Table** open a dialog to add, drop or change columns (name, data type, not null, primary key, default) with a live SQL preview. SQLite can only rename or drop existing columns. ClickHouse tables can't be modified this way.
|
||||
|
||||
## Query console
|
||||
|
||||
@@ -57,7 +57,7 @@ Click a line number to add or remove a line breakpoint, or use **Toggle Line Bre
|
||||
|
||||
- `⌥`-click (`Alt`-click) adds a temporary breakpoint, which is removed after it is hit once.
|
||||
- `⇧`-click (`Shift`-click) adds a logging breakpoint that does not suspend the program, and opens its properties.
|
||||
- Middle-click enables or disables an existing breakpoint.
|
||||
- Middle-click enables or disables an existing breakpoint. From the keyboard, **Toggle Breakpoint Enabled** (Find Action) enables or disables every breakpoint on the caret line, or on each line a selection or caret covers.
|
||||
- Right-click a breakpoint to edit its properties.
|
||||
|
||||
Blank and comment-only lines take no breakpoint. By default line breakpoints can only go into files of languages that have a debugger; turn on **Allow placing breakpoints in any file** in **Settings › Build, Execution, Deployment › Debugger** to lift that.
|
||||
@@ -164,7 +164,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
|
||||
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
|
||||
- **JavaScript in the browser**: a **JavaScript Debug** configuration opens a URL in Chrome or Edge and debugs the page's scripts in their sources through source maps. See [JavaScript and TypeScript](/en/languages/javascript#debugging).
|
||||
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
|
||||
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
|
||||
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
|
||||
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
|
||||
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ Showing an empty Terminal window opens a tab in the start directory (the project
|
||||
|
||||
- **+** (**New Tab**) opens a tab with the default shell.
|
||||
- The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**.
|
||||
- Right-click a tab for **Rename Session…**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
|
||||
- Drag tabs to reorder them, or drop a tab on the edge of another group to split.
|
||||
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
|
||||
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A terminal moved to the editor can return via **Move to Terminal** or by dragging its editor tab onto a Terminal tab strip, pane edge, or the **Terminal** stripe button.
|
||||
|
||||
A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends.
|
||||
|
||||
@@ -56,6 +56,7 @@ The pane's context menu has **Copy**, **Paste**, **Select All**, **Clear Buffer*
|
||||
|
||||
- `http`, `https` and `file` URLs open in your browser. OSC 8 hyperlinks from programs work too.
|
||||
- File locations such as `src/main.rs:42:7` or `Main.java(42,7)` open in the editor at that line. Paths resolve against the shell's current directory, then by file name across the project.
|
||||
- Hold `⌘` (`Ctrl` on Windows/Linux) and hover over an existing file or folder name (`README.md`, `src/features`, `/tmp`) to turn it into a link: clicking opens files in an editor tab of the current window, opens project folders in the **Project** tool window, and reveals folders outside the project in Finder / Explorer / Files.
|
||||
- Pasting copied files pastes their paths, quoted for the shell in use (bash/zsh/fish, PowerShell or cmd). Pasting an image from the clipboard saves it to a file and pastes that file's path.
|
||||
- Dropping files from your file manager onto the terminal types their quoted paths at the prompt. They are not run.
|
||||
|
||||
|
||||
@@ -202,7 +202,7 @@ The **Log** tab of the Git tool window shows the commit graph.
|
||||
- The details pane shows the changed files, the commit message, who committed it, which branches contain it and its signature.
|
||||
- In the **Signature** column, hover over a badge to see the verification result, signer, and key fingerprint when available. After changing your verification keys or trust settings, click **Refresh** in the log toolbar to check again.
|
||||
|
||||
Right-click a commit for **Copy Revision Number** (`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`), **Create Patch…**, **Cherry-Pick**, **Checkout Revision**, **Show Repository at Revision**, **Compare with Local**, **Reset Current Branch to Here…**, **Revert Commit**, **Undo Commit…**, **New Branch…**, **New Tag…**, **View in Browser** and more. With two commits selected, **Compare Versions** diffs them. With the commit list focused, `F2` edits the commit message, `⌥⌘N` / `Ctrl+Alt+N` creates a branch, `←` / `→` go to the child or parent commit, and `F3` / `F11` toggles a commit bookmark (`⌥F3` / `Ctrl+F11` with a mnemonic).
|
||||
Right-click a commit for **Copy Revision Number** (`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`), **Create Patch…**, **Cherry-Pick**, **Checkout Revision**, **Show Repository at Revision**, **Compare with Local**, **Reset Current Branch to Here…**, **Revert Commit**, **Undo Commit…**, **New Branch…**, **New Tag…**, **View in Browser** and more. With two commits selected, **Compare Versions** diffs them. With the commit list focused, `F2` edits the commit message, `⌥⌘N` / `Ctrl+Alt+N` creates a branch, `←` / `→` go to the child or parent commit, and `F3` / `F11` toggles a commit bookmark (`⌥F3` / `Ctrl+F11` with a mnemonic). **Copy Commit Subject**, run from **Find Action** or a shortcut you assign in **Settings › Keymap**, copies the subject lines of the selected commits, one per line.
|
||||
|
||||
In the changed-files pane, use **Apply Selected Changes** to bring only the selected files' changes into the working tree.
|
||||
Use **Extract Selected Changes** on part of a commit to move those files' changes into a new commit immediately after it. The operation preserves the tip's tree, local edits, and staged changes. The success notification offers **Undo** while HEAD still points to the rewritten tip.
|
||||
|
||||
@@ -100,16 +100,18 @@ In a Maven project with Kotlin sources, OpenIDEA builds the Kotlin code in the b
|
||||
|
||||
## Run and test
|
||||
|
||||
| What | How it runs |
|
||||
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. |
|
||||
| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions |
|
||||
| Executable jar | **JAR Application** configuration |
|
||||
| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) |
|
||||
| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations |
|
||||
| What | How it runs |
|
||||
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `main` method | **Application** configuration on the module's runtime or test classpath. Java 25 instance `main` methods are recognized. |
|
||||
| `@SpringBootApplication` class | **Spring Boot** configuration, with active profiles and update actions |
|
||||
| Executable jar | **JAR Application** configuration |
|
||||
| WAR | **Tomcat Server** configuration on a local Tomcat installation (the IDE never writes into it) |
|
||||
| JUnit 4, JUnit 5 and TestNG tests | Maven (Surefire `-Dtest=…`) or Gradle (`--tests …`) test configurations; JUnit 5 in a Maven module runs on jdtls' test classpath |
|
||||
|
||||
Gutter icons on main methods, test classes and test methods create these configurations, and Maven and Gradle run configurations are detected from the build files. For Gradle, **Build and run using** decides whether an Application runs as a Gradle `JavaExec` task (the default) or is launched by OpenIDEA on the classpath reported by jdtls.
|
||||
|
||||
A JUnit 5 test class or method run from the gutter of a Maven module starts on jdtls' test classpath with OpenIDEA's JUnit Platform runner, without Maven, like IDEA (**Settings › Build, Execution, Deployment › Maven › Run tests using**). The runner adds `junit-platform-launcher` of the engine's version when the project has none (from the local repository, else downloaded once from Maven Central). As in IDEA, the test JVM gets the module's Surefire configuration: `argLine` (with `@{…}` late replacement), `systemPropertyVariables`, `environmentVariables`, `workingDirectory`, `additionalClasspathElements` and `classpathDependencyExcludes`, read from the effective POM of the last Maven sync (before a sync, from the module's own `pom.xml`). Resource filtering and Surefire's other settings (forking, includes, groups) don't apply; choose **Maven** to run through Surefire.
|
||||
|
||||
Test results are read from the JUnit XML reports Maven and Gradle write, so passed tests are listed as well. The test tree supports rerunning failed tests. VM options of a Gradle run configuration are applied to the JVMs Gradle forks (`run`, `bootRun`, `test`). When a classpath is too long for the command line (common on Windows), it is moved into an argument file or a manifest-only jar.
|
||||
|
||||
See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
|
||||
|
||||
@@ -3,11 +3,11 @@ title: "UI 规范"
|
||||
description: "前端 UI 代码的规则:设计 token、CSS Modules、图标、UI 基础组件、无障碍以及 WebKit 兼容性。"
|
||||
---
|
||||
|
||||
视觉风格是深色、低对比度的灰阶,加一种冷色强调色。一致性靠一小组适用于所有组件的规则来保证。
|
||||
视觉风格是 JetBrains 新 UI 的 Islands 形态:灰色底框上的圆角内容岛、低对比度的灰阶,加一种冷色强调色。默认主题是 Islands Light,Islands Dark、High Contrast 和 Solarized 主题使用同一套 token。一致性靠一小组适用于所有组件的规则来保证。
|
||||
|
||||
## 设计 token
|
||||
|
||||
[`src/styles/tokens.css`](https://github.com/l0ng-ai/openidea/blob/main/src/styles/tokens.css) 是颜色和尺寸(间距、大小、圆角、字重)的唯一来源。`:root` 是深色主题,`[data-theme="light"]` 和 `[data-theme="dark-hc"]`(高对比度)在其上覆盖。插件主题和配色设置在运行时改写的也是这些变量。
|
||||
[`src/styles/tokens.css`](https://github.com/l0ng-ai/openidea/blob/main/src/styles/tokens.css) 是颜色和尺寸(间距、大小、圆角、字重)的唯一来源。`:root` 是深色主题,`[data-theme="light"]`(默认主题)和 `[data-theme="dark-hc"]`(高对比度)在其上覆盖。插件主题和配色设置在运行时改写的也是这些变量。
|
||||
|
||||
- **组件里只用 token。** 组件的 CSS 或内联样式中不出现十六进制、`rgb()` 或颜色名字面量:写 `color: var(--fg-muted)`,不写 `color: #8c8c8c`。
|
||||
- **需要新的颜色或尺寸?** 在 `tokens.css` 里为每个主题变体都加上 token,名字说明用途,而不是描述外观。
|
||||
|
||||
@@ -62,17 +62,18 @@ Maven 和 Gradle 使用设置里配置的 wrapper 或本地安装(见下文)
|
||||
|
||||
**设置 › 构建、执行、部署 › Maven**:
|
||||
|
||||
| 设置 | 作用 |
|
||||
| ------------------------------------ | ------------------------------------------------------------------------------- |
|
||||
| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls |
|
||||
| **JRE** | Maven 同步、构建、目标和测试使用的 JDK |
|
||||
| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` |
|
||||
| **用户设置文件** | 作为 `-s` 传入 |
|
||||
| **Toolchains 文件** | 作为 `-t` 传入 |
|
||||
| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 |
|
||||
| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 |
|
||||
| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) |
|
||||
| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` |
|
||||
| 设置 | 作用 |
|
||||
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **将 IDE 构建/运行操作委托给 Maven** | 运行和调试时用 Maven(`javac`)构建 Maven 模块,而不是 jdtls |
|
||||
| **运行测试使用** | **OpenIDEA**(默认):从装订区域运行的 JUnit 5 测试直接在 jdtls 的测试类路径上启动,不经过 Maven,并应用模块的 Surefire 配置;**Maven**:通过 Surefire 运行 |
|
||||
| **JRE** | Maven 同步、构建、目标和测试使用的 JDK |
|
||||
| **Maven 主路径** | 使用指定的 Maven 安装,而不是项目里的 `mvnw` |
|
||||
| **用户设置文件** | 作为 `-s` 传入 |
|
||||
| **Toolchains 文件** | 作为 `-t` 传入 |
|
||||
| **本地仓库** | 作为 `-Dmaven.repo.local` 传入 |
|
||||
| **活动 profiles** | 逗号分隔的 profile(`-P`),`!id` 表示排除 |
|
||||
| **线程数** | 作为 `-T` 传入(如 `4` 或 `2C`) |
|
||||
| **使用 Maven Daemon (mvnd)** | 构建、同步和运行配置都通过 `mvnd` 执行;找不到 mvnd 或 JDK 低于 17 时退回 `mvn` |
|
||||
|
||||
## Gradle
|
||||
|
||||
|
||||
@@ -107,9 +107,12 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
|
||||
| 复制(数据源) | `⌘D` | `Ctrl+D` |
|
||||
| 生成 DDL 到剪贴板 | `⌘⌥⇧G` | `Ctrl+Alt+Shift+G` |
|
||||
| 生成 DDL 到查询控制台 | `⌘⌥⇧B` | `Ctrl+Alt+Shift+B` |
|
||||
| 图表 › 显示图表 | `⌘⌥⇧U` | `Ctrl+Alt+Shift+U` |
|
||||
|
||||
这些快捷键在数据库树获得焦点时生效。右键菜单中还有 **截断…**、**运行 SQL 脚本…**(执行某个 `.sql` 文件中的所有语句)、**从文件导入数据…**、**转到引用的表**(外键上)、SQL 模板(select、insert、update、delete)以及 **移除数据源…**。
|
||||
|
||||
**图表 › 显示图表** 会在编辑器标签页中打开所选表(或所选模式中的全部表,最多 50 个)的只读 ER 图:列带有 `PK` / `FK` 标记,并显示所示表之间的外键关系。用 `⌘`/`Ctrl` 单击或 `Shift` 单击可选择多个表。用 `⌘`/`Ctrl`+滚轮缩放;图上的按钮可全屏显示或保存为图片。
|
||||
|
||||
**修改表…** 和 **新建 › 表** 会打开一个对话框,可以添加、删除或修改列(名称、数据类型、非空、主键、默认值),并实时预览 SQL。SQLite 只能重命名或删除已有列。ClickHouse 表不能用这种方式修改。
|
||||
|
||||
## 查询控制台
|
||||
|
||||
@@ -59,7 +59,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
|
||||
|
||||
- `⌥` 点击(`Alt` 点击)添加临时断点,命中一次后自动移除。
|
||||
- `⇧` 点击(`Shift` 点击)添加不挂起程序的日志断点,并打开它的属性。
|
||||
- 中键点击已有断点,启用或禁用它。
|
||||
- 中键点击已有断点,启用或禁用它。用键盘时,**切换断点启用状态**(通过查找操作)启用或禁用光标所在行上的所有断点,或选区和各光标覆盖的每一行上的断点。
|
||||
- 右键点击断点,编辑它的属性。
|
||||
|
||||
空行和只有注释的行不能加断点。默认情况下,行断点只能放在有调试器的语言文件里;如需放开限制,在 **设置 › 构建、执行、部署 › 调试器** 中打开 **允许在任意文件中设置断点**。
|
||||
@@ -166,7 +166,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
|
||||
- **Java HotSwap**:**运行 › 调试操作 › 重新加载已更改的类** 编译改动,并把变化的类重新加载到正在运行的 Java 调试会话中。已经在执行的帧要等返回后才会用上新代码。保存后 JDT LS 自动完成构建时,IDE 也会提示是否重新加载。
|
||||
- **浏览器中的 JavaScript**:**JavaScript 调试** 配置在 Chrome 或 Edge 中打开一个 URL,通过 source map 在源码中调试页面脚本。见 [JavaScript 与 TypeScript](/zh/languages/javascript)。
|
||||
- **Maven 和 Gradle**:调试 Maven 或 Gradle 配置时,IDE 会让 JVM 带上 JDWP agent 启动,再用 java-debug 附加上去。
|
||||
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
|
||||
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
|
||||
- **PHP**:如果 PHP 解释器没有加载 Xdebug,断点会被跳过;会话启动时 IDE 会提示。
|
||||
- **Python**:**设置 › 构建、执行、部署 › Python 调试器** 中有 **调试时自动附加到子进程** 和 **兼容 Gevent**。
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
|
||||
|
||||
- **+**(**新建标签页**)用默认 Shell 打开一个标签页。
|
||||
- **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。
|
||||
- 右键标签页可以 **重命名会话…**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
|
||||
- 拖动标签页可以调整顺序,拖到另一组的边缘则会拆分。
|
||||
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
|
||||
- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。移到编辑器的终端可通过 **移至终端**,或将编辑器标签拖回终端标签栏、面板边缘或 **终端** 边栏按钮来归位。
|
||||
|
||||
标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。
|
||||
|
||||
@@ -56,6 +56,7 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
|
||||
|
||||
- `http`、`https` 和 `file` 链接在浏览器中打开,程序输出的 OSC 8 超链接同样可用。
|
||||
- `src/main.rs:42:7`、`Main.java(42,7)` 这类文件位置会在编辑器中打开并定位到该行。路径先按 Shell 的当前目录解析,找不到时再在整个项目中按文件名查找。
|
||||
- 按住 `⌘`(Windows/Linux 上为 `Ctrl`)将鼠标悬停在已存在的文件名或文件夹名(如 `README.md`、`src/features`、`/tmp`)上会变为超链接:点击文件会在当前窗口的编辑器标签页中打开,项目内的文件夹会在左侧 **项目** 视图中展开并选中,项目外的文件夹则会在访达 / 资源管理器 / 文件管理器中显示。
|
||||
- 粘贴复制的文件时,会粘贴按当前 Shell(bash/zsh/fish、PowerShell 或 cmd)规则加好引号的路径。粘贴剪贴板中的图片时,会先保存为文件,再粘贴该文件的路径。
|
||||
- 从文件管理器把文件拖到终端,会在提示符处输入加了引号的路径,但不会执行。
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
- 详情面板显示变更文件、提交消息、提交者、包含该提交的分支以及签名。
|
||||
- 将鼠标悬停在 **签名** 列的图标上,可查看验签结果,以及可用的签名者和密钥指纹。更改验签密钥或信任设置后,点击日志工具栏的 **刷新** 重新验签。
|
||||
|
||||
右键提交可以选择 **复制修订号**(`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`)、**创建补丁…**、**拣选**、**签出修订**、**显示此修订版本的仓库**、**与本地比较**、**将当前分支重置到此处…**、**还原提交**、**撤消提交…**、**新建分支…**、**新建标签…**、**在浏览器中查看** 等。选中两个提交时,**比较版本** 会比较它们。提交列表获得焦点时,`F2` 编辑提交消息,`⌥⌘N` / `Ctrl+Alt+N` 新建分支,`←` / `→` 跳到子提交或父提交,`F3` / `F11` 切换提交书签(`⌥F3` / `Ctrl+F11` 带助记符)。
|
||||
右键提交可以选择 **复制修订号**(`⌥⇧⌘C` / `Ctrl+Alt+Shift+C`)、**创建补丁…**、**拣选**、**签出修订**、**显示此修订版本的仓库**、**与本地比较**、**将当前分支重置到此处…**、**还原提交**、**撤消提交…**、**新建分支…**、**新建标签…**、**在浏览器中查看** 等。选中两个提交时,**比较版本** 会比较它们。提交列表获得焦点时,`F2` 编辑提交消息,`⌥⌘N` / `Ctrl+Alt+N` 新建分支,`←` / `→` 跳到子提交或父提交,`F3` / `F11` 切换提交书签(`⌥F3` / `Ctrl+F11` 带助记符)。从 **查找操作** 或在 **设置 › 按键映射** 中分配的快捷键执行 **复制提交主题**,会复制所选提交的主题行,每行一个。
|
||||
|
||||
### 改写历史
|
||||
|
||||
|
||||
@@ -100,16 +100,18 @@ IDE 会把代理设置传给 jdtls,所以在代理环境下也能解析依赖
|
||||
|
||||
## 运行与测试
|
||||
|
||||
| 对象 | 运行方式 |
|
||||
| ----------------------------- | -------------------------------------------------------------------------------- |
|
||||
| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 |
|
||||
| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 |
|
||||
| 可执行 jar | **JAR 应用程序** 配置 |
|
||||
| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) |
|
||||
| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置 |
|
||||
| 对象 | 运行方式 |
|
||||
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------- |
|
||||
| `main` 方法 | **应用程序** 配置,使用模块的运行时或测试类路径;支持 Java 25 的实例 `main` 方法 |
|
||||
| `@SpringBootApplication` 类 | **Spring Boot** 配置,可设置活动 profile 和更新操作 |
|
||||
| 可执行 jar | **JAR 应用程序** 配置 |
|
||||
| WAR | **Tomcat 服务器** 配置,运行在本地 Tomcat 安装上(IDE 不会往安装目录里写东西) |
|
||||
| JUnit 4、JUnit 5、TestNG 测试 | Maven(Surefire `-Dtest=…`)或 Gradle(`--tests …`)测试配置;Maven 模块中的 JUnit 5 直接在 jdtls 的测试类路径上运行 |
|
||||
|
||||
main 方法、测试类和测试方法旁的边栏图标会创建这些配置;Maven 和 Gradle 的运行配置会从构建文件中自动检测。对 Gradle 项目,**构建和运行使用** 决定“应用程序”是作为 Gradle 的 `JavaExec` 任务运行(默认),还是由 OpenIDEA 用 jdtls 给出的类路径直接启动。
|
||||
|
||||
在 Maven 模块的装订区域运行 JUnit 5 测试类或方法时,OpenIDEA 用自带的 JUnit Platform 运行器在 jdtls 的测试类路径上直接启动,不经过 Maven,与 IDEA 一致(**设置 › 构建、执行、部署 › Maven › 运行测试使用**)。项目没有 `junit-platform-launcher` 时,运行器会补上与 engine 同版本的 launcher(先找本地仓库,找不到再从 Maven Central 下载一次)。与 IDEA 一样,测试 JVM 会应用模块的 Surefire 配置:`argLine`(支持 `@{…}` 晚替换)、`systemPropertyVariables`、`environmentVariables`、`workingDirectory`、`additionalClasspathElements` 和 `classpathDependencyExcludes`,取自最近一次 Maven 同步的有效 POM(同步前取模块自己的 `pom.xml`)。资源过滤和 Surefire 的其他设置(fork、includes、groups)不会生效;需要时请选 **Maven**,通过 Surefire 运行。
|
||||
|
||||
测试结果从 Maven 和 Gradle 生成的 JUnit XML 报告中读取,通过的测试也会列出;测试树支持只重跑失败的测试。Gradle 运行配置的 VM 选项会作用到 Gradle fork 出来的 JVM(`run`、`bootRun`、`test`)。类路径超出命令行长度限制时(Windows 上常见),会改用参数文件或只含 manifest 的 jar。
|
||||
|
||||
另见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
|
||||
|
||||
@@ -92,23 +92,23 @@ async function seedChanges(page: Page) {
|
||||
await page.evaluate(async (id) => {
|
||||
// Seed the store in the browser realm; a static import would run in Node.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
(await import(storePath)).useAgents.setState({
|
||||
changes: new Map([
|
||||
[
|
||||
id,
|
||||
[
|
||||
{
|
||||
path: "/dev/acme-api/file.ts",
|
||||
relPath: "file.ts",
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
},
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const changes = [
|
||||
{
|
||||
path: "/dev/acme-api/file.ts",
|
||||
relPath: "file.ts",
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
repo: null,
|
||||
},
|
||||
];
|
||||
const { commands } = await import(ipcPath);
|
||||
// The Changes tab reads them again when it opens.
|
||||
commands.agentChanges = async () => ({ status: "ok", data: changes });
|
||||
commands.agentBaseText = async () => ({ status: "ok", data: "" });
|
||||
(await import(storePath)).useAgents.setState({ changes: new Map([[id, changes]]) });
|
||||
}, firstTask.id);
|
||||
}
|
||||
|
||||
@@ -383,42 +383,35 @@ test("Find Action focuses the current task input after closing its popup", async
|
||||
await expect.poll(() => selection(box)).toEqual(expected);
|
||||
});
|
||||
|
||||
test("docked Changes view returns to the task input without losing its selection", async ({ workbench: page }) => {
|
||||
test("a task's changes open in a tab of their own", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
const box = messageBox(page);
|
||||
await expect(box).toBeVisible();
|
||||
const chip = page.getByRole("button", { name: /1 changed file/ });
|
||||
await chip.click();
|
||||
const changes = page.getByRole("region", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(changes.getByRole("tree", { name: "Changed files" }).getByText("file.ts")).toBeVisible();
|
||||
await expect(changes.locator('[data-combined-block="/dev/acme-api/file.ts"]')).toBeVisible();
|
||||
// The conversation stays in its tab, as it was.
|
||||
await expect(box).toBeHidden();
|
||||
await page.getByRole("tab", { name: firstTask.title, exact: true }).click();
|
||||
await expect(box).toBeVisible();
|
||||
|
||||
// Again: the same tab, not another one.
|
||||
await chip.click();
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: `Changes: ${firstTask.title}` })).toHaveCount(1);
|
||||
});
|
||||
|
||||
test("a docked task's changes open in the editor, the conversation staying in place", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "toolWindow");
|
||||
const box = messageBox(page);
|
||||
const expected = await selectDraft(box, true);
|
||||
await selectDraft(box, true);
|
||||
await seedChanges(page);
|
||||
await page.getByRole("button", { name: /1 changed file/ }).click();
|
||||
const changes = page.getByRole("complementary", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
await expect(box).toHaveCount(0);
|
||||
await changes.getByRole("button", { name: "Back to conversation", exact: true }).focus();
|
||||
await page.keyboard.press("Meta+L");
|
||||
await expect(changes).toBeHidden();
|
||||
await expect(box).toBeFocused();
|
||||
await expect(page.getByRole("region", { name: "Changes", exact: true })).toBeVisible();
|
||||
await expect(box).toBeVisible();
|
||||
await expect(box).toHaveText(draft);
|
||||
await expect.poll(() => selection(box)).toEqual(expected);
|
||||
});
|
||||
|
||||
test("dragging the Changes pane's edge resizes it for the next session too", async ({ workbench: page }) => {
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
const changes = page.getByRole("complementary", { name: "Changes", exact: true });
|
||||
await expect(changes).toBeVisible();
|
||||
const handle = changes.getByRole("separator", { name: "Resize changes", exact: true });
|
||||
const before = (await changes.boundingBox())!.width;
|
||||
const box = (await handle.boundingBox())!;
|
||||
await page.mouse.move(box.x, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x - 120, box.y + box.height / 2, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await changes.boundingBox())!.width).toBeGreaterThan(before + 100);
|
||||
const widened = (await changes.boundingBox())!.width;
|
||||
|
||||
// The next session starts with the dragged width.
|
||||
await page.reload();
|
||||
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
@@ -60,34 +61,47 @@ const entries: AgentEntry[] = [
|
||||
diffs: [],
|
||||
},
|
||||
{ type: "agent", text: "The preview is ready: front, side and back." },
|
||||
{
|
||||
type: "user",
|
||||
text: "Looks good.",
|
||||
attachments: [],
|
||||
sentMs: 3000,
|
||||
doneMs: 4000,
|
||||
steered: false,
|
||||
},
|
||||
{ type: "agent", text: "Glad it helped." },
|
||||
];
|
||||
|
||||
async function showImages(page: Page, foldTurns = true) {
|
||||
await page.evaluate(
|
||||
async ({ task, entries, foldTurns }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { useProject } = await import(projectPath);
|
||||
const { commands } = await import(ipcPath);
|
||||
commands.agentEntries = async () => ({ status: "ok", data: entries });
|
||||
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries, foldTurns },
|
||||
);
|
||||
}
|
||||
|
||||
for (const foldTurns of [true, false]) {
|
||||
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
|
||||
await page.evaluate(
|
||||
async ({ task, entries, foldTurns }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { useProject } = await import(projectPath);
|
||||
const { commands } = await import(ipcPath);
|
||||
commands.agentEntries = async () => ({ status: "ok", data: entries });
|
||||
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries, foldTurns },
|
||||
);
|
||||
await showImages(page, foldTurns);
|
||||
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
|
||||
const preview = page.getByRole("img", { name: "Image", exact: true });
|
||||
await expect(preview).toBeVisible();
|
||||
@@ -98,6 +112,8 @@ for (const foldTurns of [true, false]) {
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
|
||||
const fold = page.locator("details").first();
|
||||
await expect(fold).not.toHaveAttribute("open");
|
||||
if (foldTurns) await expect(fold.locator("summary").first()).toContainText("1s");
|
||||
else await expect(fold.locator("summary").first()).not.toContainText("1s");
|
||||
await preview.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
|
||||
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
|
||||
@@ -109,3 +125,41 @@ for (const foldTurns of [true, false]) {
|
||||
await expect(preview).toBeVisible();
|
||||
});
|
||||
}
|
||||
|
||||
test("copies full-size PNG pixels from the thumbnail menu and the image preview", async ({
|
||||
workbench: page,
|
||||
context,
|
||||
}) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await showImages(page);
|
||||
const thumbnail = page.getByRole("img", { name: "Image", exact: true });
|
||||
await expect(thumbnail).toBeVisible();
|
||||
const clipboard = () =>
|
||||
page.evaluate(async () => {
|
||||
const items = await navigator.clipboard.read();
|
||||
const item = items.find((item) => item.types.includes("image/png"));
|
||||
// The write may still be in flight; let the poll try again.
|
||||
if (!item) return null;
|
||||
const png = await item.getType("image/png");
|
||||
const image = await createImageBitmap(png);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = image.width;
|
||||
canvas.height = image.height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.drawImage(image, 0, 0);
|
||||
const pixel = [...context.getImageData(150, 92, 1, 1).data];
|
||||
image.close();
|
||||
return { width: canvas.width, height: canvas.height, type: png.type, pixel };
|
||||
});
|
||||
await thumbnail.click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Copy Image", exact: true }).click();
|
||||
const expected = { width: 900, height: 220, type: "image/png", pixel: [15, 118, 110, 255] };
|
||||
await expect.poll(clipboard).toEqual(expected);
|
||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
await thumbnail.click();
|
||||
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
|
||||
await dialog.getByRole("button", { name: "Copy Image", exact: true }).click();
|
||||
await expect(dialog.getByRole("button", { name: "Copied", exact: true })).toBeVisible();
|
||||
expect(await clipboard()).toEqual(expected);
|
||||
await expect(dialog).toBeVisible();
|
||||
});
|
||||
@@ -17,7 +17,7 @@ const MACOS = device("macos", "macOS", "desktop");
|
||||
const CHROME = device("chrome", "Chrome", "web");
|
||||
const UNAUTHORIZED = device("R5C", "R5C", "mobile", "unauthorized");
|
||||
|
||||
async function stubFlutter(page: Page, status: unknown = { kind: "ready" }) {
|
||||
async function stubFlutter(page: Page, status: unknown = { kind: "ready" }, emulators: unknown[] = []) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ list }) => {
|
||||
@@ -38,13 +38,14 @@ async function stubFlutter(page: Page, status: unknown = { kind: "ready" }) {
|
||||
h.run_apply_settings = (args) => args.configs;
|
||||
h.flutter_devices = () => list;
|
||||
h.flutter_devices_refresh = () => null;
|
||||
h.flutter_emulator_launch = () => null;
|
||||
h.run_start = () => ({ id: 3, configId: config.id, name: config.name, pid: 42, running: true, pty: false });
|
||||
const runModule = "/src/features/run/store.ts";
|
||||
const { loadConfigs, selectConfig } = await import(/* @vite-ignore */ runModule);
|
||||
await loadConfigs();
|
||||
selectConfig(config.id);
|
||||
},
|
||||
{ list: { status, devices: [MACOS, CHROME, UNAUTHORIZED] } },
|
||||
{ list: { status, devices: [MACOS, CHROME, UNAUTHORIZED], emulators } },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -79,3 +80,38 @@ test("says when the Flutter SDK is missing", async ({ workbench: page }) => {
|
||||
await stubFlutter(page, { kind: "notInstalled" });
|
||||
await expect(chooser(page)).toContainText("Flutter SDK not found");
|
||||
});
|
||||
|
||||
test("starts an emulator and selects its device once it connects", async ({ workbench: page }) => {
|
||||
const pixel = { id: "Pixel_9", name: "Pixel 9", platformType: "android" };
|
||||
const simulator = { id: "apple_ios_simulator", name: "iOS Simulator", platformType: "ios" };
|
||||
await stubFlutter(page, { kind: "ready" }, [pixel, simulator]);
|
||||
await chooser(page).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Open iOS Simulator" })).toBeVisible();
|
||||
await page.getByRole("menuitem", { name: "Open Android Emulator: Pixel 9" }).click();
|
||||
await expect.poll(async () => ipcCalls(page, "flutter_emulator_launch")).toEqual([{ id: "Pixel_9" }]);
|
||||
await expect(chooser(page)).toContainText("Starting Pixel 9…");
|
||||
|
||||
const booted = { ...device("emulator-5554", "sdk gphone64 arm64", "mobile"), emulator: true, emulatorId: "Pixel_9" };
|
||||
await page.evaluate((list) => window.__ipc.emit({ type: "flutterDevices", list }), {
|
||||
status: { kind: "ready" },
|
||||
devices: [MACOS, booted],
|
||||
emulators: [simulator],
|
||||
});
|
||||
await expect(chooser(page)).toContainText("sdk gphone64 arm64");
|
||||
});
|
||||
|
||||
test("says why an emulator could not start", async ({ workbench: page }) => {
|
||||
await stubFlutter(page, { kind: "ready" }, [
|
||||
{ id: "apple_ios_simulator", name: "iOS Simulator", platformType: "ios" },
|
||||
]);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.flutter_emulator_launch = () => {
|
||||
throw { kind: "unavailable", message: "Unable to find Xcode" };
|
||||
};
|
||||
});
|
||||
await chooser(page).click();
|
||||
await page.getByRole("menuitem", { name: "Open iOS Simulator" }).click();
|
||||
await expect(page.getByText("Could not start iOS Simulator")).toBeVisible();
|
||||
await expect(page.getByText("Unable to find Xcode")).toBeVisible();
|
||||
await expect(chooser(page)).toContainText("macOS");
|
||||
});
|
||||
@@ -334,7 +334,7 @@ test("long Git Log filter values shorten inside their buttons", async ({ workben
|
||||
const branch = toolbar.getByRole("button", { name: `Branch: ${branchName}`, exact: true });
|
||||
const value = branch.getByText(branchName, { exact: true });
|
||||
const clear = toolbar.getByRole("button", { name: "Clear Branch filter", exact: true });
|
||||
for (const width of [1120, 620]) {
|
||||
for (const width of [1120, 680]) {
|
||||
await page.setViewportSize({ width, height: 720 });
|
||||
await expect(branch).toBeVisible();
|
||||
await expect(value).toHaveCSS("text-overflow", "ellipsis");
|
||||
@@ -356,7 +356,7 @@ test("long Git Log filter values shorten inside their buttons", async ({ workben
|
||||
await expect(page.getByRole("menuitem", { name: `Branch: ${branchName}`, exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await page.setViewportSize({ width: 620, height: 720 });
|
||||
await page.setViewportSize({ width: 680, height: 720 });
|
||||
await clear.click();
|
||||
await expect(toolbar.getByRole("button", { name: "Branch", exact: true })).toBeVisible();
|
||||
await expect(clear).toBeHidden();
|
||||
|
||||
@@ -9,6 +9,7 @@ const java: GeneratorInfo = {
|
||||
order: 1,
|
||||
description: "A plain Java application built with Maven or Gradle.",
|
||||
git: true,
|
||||
directory: null,
|
||||
dynamic: false,
|
||||
fields: [
|
||||
{
|
||||
|
||||
@@ -40,6 +40,18 @@ test("Project Libraries groups attachments below one toolbar and saves the selec
|
||||
await expect(tree.getByRole("treeitem", { name: "Sources", exact: true })).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(tree.getByRole("treeitem", { name: "lib/report.jar", exact: true })).toBeVisible();
|
||||
await expect(tree.getByText("lib/report.jar", { exact: true })).toHaveCSS("font-size", "13px");
|
||||
// The roots fill the row and the notes go below them, however short the notes are (#5771).
|
||||
const layout = await toolbar.evaluate((el) => {
|
||||
const panel = el.parentElement!;
|
||||
const notes = panel.nextElementSibling as HTMLElement;
|
||||
for (const line of notes.children) line.textContent = "Short note.";
|
||||
const p = panel.getBoundingClientRect();
|
||||
const n = notes.getBoundingClientRect();
|
||||
const row = panel.parentElement!.getBoundingClientRect();
|
||||
return { panelWidth: p.width, rowWidth: row.width, notesBelow: n.top >= p.bottom };
|
||||
});
|
||||
expect(layout.notesBelow).toBe(true);
|
||||
expect(layout.panelWidth).toBeCloseTo(layout.rowWidth, 0);
|
||||
const remove = toolbar.getByRole("button", { name: "Remove Library Root", exact: true });
|
||||
await expect(remove).toBeDisabled();
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("terminal output menu groups session, clipboard and split actions and opens Find", async ({ workbench: page }) => {
|
||||
await page.evaluate(async () => {
|
||||
@@ -360,3 +360,363 @@ test("terminal composition follows a drawn caret inside the session", async ({ w
|
||||
})
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test("dragging terminal tabs into editor strips and split edges preserves live sessions and scrollback", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
let id = 0;
|
||||
const killed: number[] = [];
|
||||
(window as unknown as { __killedPtys: number[] }).__killedPtys = killed;
|
||||
handlers.term_default_shell = () => "/bin/zsh";
|
||||
handlers.term_available_shells = () => ["/bin/zsh"];
|
||||
handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id });
|
||||
handlers.term_resize = () => null;
|
||||
handlers.term_write = () => null;
|
||||
handlers.term_is_busy = () => false;
|
||||
handlers.term_kill = (args: unknown) => {
|
||||
killed.push((args as { id: number }).id);
|
||||
return null;
|
||||
};
|
||||
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const editor = (await import(contributions)).editorService();
|
||||
await editor.openFile("/dev/acme-api/App.tsx", { focus: false });
|
||||
await editor.openFile("/dev/acme-api/README.md", { focus: false });
|
||||
const store = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(store);
|
||||
layout.setToolWindowSize("bottom", 240);
|
||||
layout.showToolWindow("terminal", true);
|
||||
});
|
||||
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
|
||||
// Open a second terminal tab and write distinct output into both sessions.
|
||||
await terminal.getByRole("button", { name: "New Tab", exact: true }).click();
|
||||
const termStrip = terminal.getByRole("tablist", { name: "Terminal sessions" });
|
||||
await expect(termStrip.getByRole("tab")).toHaveCount(2);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const store = "/src/features/terminal/store.ts";
|
||||
const rt = await import(store);
|
||||
const [first, second] = rt.useTerminals.getState().tabs;
|
||||
const s1 = rt.getSession(first!.session)!;
|
||||
const s2 = rt.getSession(second!.session)!;
|
||||
await new Promise<void>((done) => s1.term.write("ALPHA-SESSION-OUTPUT\r\n", done));
|
||||
await new Promise<void>((done) => s2.term.write("BETA-TEST-RUNNER\r\n", done));
|
||||
});
|
||||
|
||||
// 1) Drag "Local" into the editor tab strip between App.tsx and README.md.
|
||||
const localTab = termStrip.getByRole("tab", { name: "Local", exact: true });
|
||||
const readmeTab = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "README.md" });
|
||||
const from1 = (await localTab.boundingBox())!;
|
||||
const to1 = (await readmeTab.boundingBox())!;
|
||||
await page.mouse.move(from1.x + from1.width / 2, from1.y + from1.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to1.x + 6, to1.y + to1.height / 2, { steps: 8 });
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-strip-hover.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await page.mouse.up();
|
||||
|
||||
const editorLists = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await expect(editorLists.first().getByRole("tab")).toHaveText(["App.tsx", "Local", "README.md"]);
|
||||
await expect(termStrip.getByRole("tab")).toHaveCount(1);
|
||||
|
||||
const editorArea = page.locator("[data-pane-id]");
|
||||
await expect(editorArea.locator(".xterm-rows")).toContainText("ALPHA-SESSION-OUTPUT");
|
||||
await expect(editorArea.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
|
||||
// 2) Drag the remaining "Local (2)" onto the right edge of the editor pane to split it, hiding the empty tool window.
|
||||
const local2Tab = termStrip.getByRole("tab", { name: "Local (2)", exact: true });
|
||||
const paneBox = (await editorArea.first().locator('[role="tabpanel"]').boundingBox())!;
|
||||
const from2 = (await local2Tab.boundingBox())!;
|
||||
await page.mouse.move(from2.x + from2.width / 2, from2.y + from2.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(paneBox.x + paneBox.width - 20, paneBox.y + paneBox.height / 2, { steps: 8 });
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-split-hover.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(terminal).toBeHidden();
|
||||
await expect(editorArea).toHaveCount(2);
|
||||
await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER");
|
||||
await expect(editorArea.nth(1).locator(".xterm-helper-textarea")).toBeFocused();
|
||||
|
||||
// 3) Resize the editor split divider and confirm both panes and the live PTY survive.
|
||||
const widthBefore = (await editorArea.nth(1).boundingBox())!.width;
|
||||
const divider = page.locator("[data-editor-area]").getByRole("separator");
|
||||
const divBox = (await divider.boundingBox())!;
|
||||
await page.mouse.move(divBox.x + divBox.width / 2, divBox.y + divBox.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(divBox.x - 100, divBox.y + divBox.height / 2, { steps: 6 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await editorArea.nth(1).boundingBox())!.width).toBeGreaterThan(widthBefore + 50);
|
||||
await expect(editorArea.nth(1).locator(".xterm-rows")).toContainText("BETA-TEST-RUNNER");
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/after-final.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]);
|
||||
});
|
||||
|
||||
test("editor terminal tabs move and drag back to the Terminal stripe, tab strip, and split edges", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
let id = 0;
|
||||
const killed: number[] = [];
|
||||
(window as unknown as { __killedPtys: number[] }).__killedPtys = killed;
|
||||
handlers.term_default_shell = () => "/bin/zsh";
|
||||
handlers.term_available_shells = () => ["/bin/zsh"];
|
||||
handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id });
|
||||
handlers.term_resize = () => null;
|
||||
handlers.term_write = () => null;
|
||||
handlers.term_is_busy = () => true;
|
||||
handlers.term_kill = (args: unknown) => {
|
||||
killed.push((args as { id: number }).id);
|
||||
return null;
|
||||
};
|
||||
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const editor = (await import(contributions)).editorService();
|
||||
await editor.openFile("/dev/acme-api/App.tsx", { focus: false });
|
||||
await editor.openFile("/dev/acme-api/README.md", { focus: false });
|
||||
const store = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(store);
|
||||
layout.setToolWindowSize("bottom", 240);
|
||||
layout.showToolWindow("terminal", true);
|
||||
});
|
||||
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
await terminal.getByRole("button", { name: "New Tab", exact: true }).click();
|
||||
const termStrip = terminal.getByRole("tablist", { name: "Terminal sessions" });
|
||||
await expect(termStrip.getByRole("tab")).toHaveCount(2);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const store = "/src/features/terminal/store.ts";
|
||||
const rt = await import(store);
|
||||
const [first, second] = rt.useTerminals.getState().tabs;
|
||||
await new Promise<void>((done) => rt.getSession(first!.session)!.term.write("ALPHA-SESSION-OUTPUT\r\n", done));
|
||||
await new Promise<void>((done) => rt.getSession(second!.session)!.term.write("BETA-TEST-RUNNER\r\n", done));
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(actions);
|
||||
await executeAction("terminal.moveToEditor", first!.id);
|
||||
await executeAction("terminal.moveToEditor", second!.id);
|
||||
});
|
||||
|
||||
await expect(terminal).toBeHidden();
|
||||
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md", "Local", "Local (2)"]);
|
||||
|
||||
// 1) Drag "Local" from the editor onto the Terminal stripe button while Terminal is hidden.
|
||||
const editorLocal = editorTabs.getByRole("tab", { name: "Local", exact: true });
|
||||
const stripeBtn = page.locator('[data-stripe-button="terminal"]');
|
||||
const from1 = (await editorLocal.boundingBox())!;
|
||||
const to1 = (await stripeBtn.boundingBox())!;
|
||||
await page.mouse.move(from1.x + from1.width / 2, from1.y + from1.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to1.x + to1.width / 2, to1.y + to1.height / 2, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
|
||||
await expect(terminal).toBeVisible();
|
||||
await expect(termStrip.getByRole("tab", { name: "Local", exact: true })).toBeVisible();
|
||||
await expect(terminal.locator(".xterm-rows")).toContainText("ALPHA-SESSION-OUTPUT");
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
|
||||
// 2) Drag "Local (2)" from the editor onto the right edge of the Terminal pane to create a split.
|
||||
const editorLocal2 = editorTabs.getByRole("tab", { name: "Local (2)", exact: true });
|
||||
const termPanelBox = (await terminal.getByRole("tabpanel").boundingBox())!;
|
||||
const from2 = (await editorLocal2.boundingBox())!;
|
||||
await page.mouse.move(from2.x + from2.width / 2, from2.y + from2.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(termPanelBox.x + termPanelBox.width - 20, termPanelBox.y + termPanelBox.height / 2, {
|
||||
steps: 8,
|
||||
});
|
||||
await page.mouse.up();
|
||||
|
||||
const termStrips = terminal.getByRole("tablist", { name: "Terminal sessions" });
|
||||
await expect(termStrips).toHaveCount(2);
|
||||
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md"]);
|
||||
await expect(terminal.locator(".xterm-rows").nth(1)).toContainText("BETA-TEST-RUNNER");
|
||||
|
||||
// 3) Context menu round-trip: Move to Editor -> editor tab context menu Move to Terminal.
|
||||
await termStrips.nth(1).getByRole("tab", { name: "Local (2)", exact: true }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Move to Editor" }).click();
|
||||
const reopenedEditorTab = editorTabs.getByRole("tab", { name: "Local (2)", exact: true });
|
||||
await expect(reopenedEditorTab).toBeVisible();
|
||||
await reopenedEditorTab.click({ button: "right" });
|
||||
const moveBackItem = page.getByRole("menuitem", { name: "Move to Terminal" });
|
||||
await expect(moveBackItem).toBeVisible();
|
||||
await moveBackItem.click();
|
||||
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx", "README.md"]);
|
||||
await expect(termStrip.getByRole("tab")).toHaveText(["Local", "Local (2)"]);
|
||||
expect(await page.evaluate(() => (window as unknown as { __killedPtys: number[] }).__killedPtys)).toEqual([]);
|
||||
});
|
||||
|
||||
test("⌘+hover turns existing terminal files and folders into hyperlinks and routes clicks by target kind and project scope", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
let id = 0;
|
||||
const revealed: string[][] = [];
|
||||
(window as unknown as { __revealedInFinder: string[][] }).__revealedInFinder = revealed;
|
||||
const entries: Record<string, "file" | "dir"> = {
|
||||
"/dev/acme-api/App.tsx": "file",
|
||||
"/dev/acme-api/src": "dir",
|
||||
"/tmp/outside.log": "file",
|
||||
"/tmp/outside-dir": "dir",
|
||||
};
|
||||
handlers.term_default_shell = () => "/bin/zsh";
|
||||
handlers.term_available_shells = () => ["/bin/zsh"];
|
||||
handlers.term_spawn = () => ({ id: ++id, title: "zsh", pid: id });
|
||||
handlers.term_resize = () => null;
|
||||
handlers.term_write = () => null;
|
||||
handlers.term_is_busy = () => false;
|
||||
handlers.term_kill = () => null;
|
||||
handlers.fs_entry_kind = (args) => {
|
||||
const p = String(args.path ?? "");
|
||||
if (p in entries) return entries[p];
|
||||
throw { kind: "notFound", message: `No such entry: ${p}` };
|
||||
};
|
||||
handlers.fs_read_dir = (args) => {
|
||||
if (args.path === "/dev/acme-api/src") {
|
||||
return [{ name: "main.ts", path: "/dev/acme-api/src/main.ts", kind: "file", ignored: false }];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
handlers.find_files = () => [];
|
||||
handlers["plugin:opener|reveal_item_in_dir"] = (args) => {
|
||||
revealed.push(args.paths as string[]);
|
||||
return null;
|
||||
};
|
||||
|
||||
const store = "/src/workbench/toolwindows/store.ts";
|
||||
const layout = await import(store);
|
||||
layout.hideToolWindow("project");
|
||||
layout.setToolWindowSize("bottom", 240);
|
||||
layout.showToolWindow("terminal", true);
|
||||
});
|
||||
|
||||
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
|
||||
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
|
||||
|
||||
// Row 0 has all 6 cases: in-project file, non-existent file, in-project dir, non-existent dir,
|
||||
// out-of-project file, out-of-project dir, and non-existent out-of-project dir.
|
||||
const line = "App.tsx missing.ts src no_dir/ /tmp/outside.log /tmp/outside-dir /tmp/nope";
|
||||
await page.evaluate(async (text) => {
|
||||
const store = "/src/features/terminal/store.ts";
|
||||
const rt = await import(store);
|
||||
const s = rt.getSession(rt.useTerminals.getState().tabs[0]!.session)!;
|
||||
s.term.reset();
|
||||
await new Promise<void>((done) => s.term.write(`${text}\r\n`, done));
|
||||
}, line);
|
||||
|
||||
const screen = terminal.locator(".xterm-screen");
|
||||
const pointFor = async (token: string) => {
|
||||
const startCol = line.indexOf(token);
|
||||
const box = (await screen.boundingBox())!;
|
||||
const dims = await page.evaluate(async () => {
|
||||
const store = "/src/features/terminal/store.ts";
|
||||
const rt = await import(store);
|
||||
const { term } = rt.getSession(rt.useTerminals.getState().tabs[0]!.session)!;
|
||||
return { cols: term.cols, rows: term.rows };
|
||||
});
|
||||
return {
|
||||
x: box.x + ((startCol + Math.min(2, token.length / 2)) / dims.cols) * box.width,
|
||||
y: box.y + (0.5 / dims.rows) * box.height,
|
||||
};
|
||||
};
|
||||
|
||||
const pathLink = terminal.locator(".openidea-terminal-path-link");
|
||||
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
|
||||
// 1) Hover & click `App.tsx` WITHOUT ⌘: no link decoration and no editor tab opens.
|
||||
const appPt = await pointFor("App.tsx");
|
||||
await page.mouse.move(appPt.x, appPt.y);
|
||||
await expect(pathLink).toHaveCount(0);
|
||||
await page.mouse.click(appPt.x, appPt.y);
|
||||
await expect(editorTabs).toHaveCount(0);
|
||||
|
||||
// 2) Press ⌘ while already hovering `App.tsx`: becomes a hyperlink; ⌘+click opens `App.tsx` in editor!
|
||||
await page.keyboard.down("Meta");
|
||||
await expect(pathLink).toHaveCount(1);
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-hover-file.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await page.mouse.click(appPt.x, appPt.y);
|
||||
await page.keyboard.up("Meta");
|
||||
await expect(editorTabs.getByRole("tab", { name: "App.tsx", selected: true })).toBeVisible();
|
||||
|
||||
// 3) Non-existent targets (`missing.ts`, `no_dir/`, `/tmp/nope`) do NOT turn into links on ⌘+hover or ⌘+click.
|
||||
for (const absent of ["missing.ts", "no_dir/", "/tmp/nope"]) {
|
||||
const pt = await pointFor(absent);
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(pt.x, pt.y);
|
||||
await expect(pathLink).toHaveCount(0);
|
||||
await page.mouse.click(pt.x, pt.y);
|
||||
await page.keyboard.up("Meta");
|
||||
}
|
||||
await expect(editorTabs.getByRole("tab")).toHaveText(["App.tsx"]);
|
||||
|
||||
// 4) Out-of-project existing file (`/tmp/outside.log`) opens in an editor tab of the current window.
|
||||
const outFilePt = await pointFor("/tmp/outside.log");
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(outFilePt.x, outFilePt.y);
|
||||
await expect(pathLink).toHaveCount(1);
|
||||
await page.mouse.click(outFilePt.x, outFilePt.y);
|
||||
await page.keyboard.up("Meta");
|
||||
await expect(editorTabs.getByRole("tab", { name: "outside.log", selected: true })).toBeVisible();
|
||||
|
||||
// 5) In-project folder (`src`) opens the Project tool window on the left, expands `src`, and selects it.
|
||||
const projectRegion = page.getByRole("region", { name: "Project", exact: true });
|
||||
await expect(projectRegion).toBeHidden();
|
||||
const srcPt = await pointFor("src");
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(srcPt.x, srcPt.y);
|
||||
await expect(pathLink).toHaveCount(1);
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-hover-folder.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await page.mouse.click(srcPt.x, srcPt.y);
|
||||
await page.keyboard.up("Meta");
|
||||
await expect(projectRegion).toBeVisible();
|
||||
const srcItem = projectRegion.getByRole("treeitem", { name: "src", exact: true });
|
||||
await expect(srcItem).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(srcItem).toHaveAttribute("aria-selected", "true");
|
||||
await expect(projectRegion.getByRole("treeitem", { name: "main.ts", exact: true })).toBeVisible();
|
||||
if (process.env.OPENIDEA_TERMINAL_SHOTS)
|
||||
await page.screenshot({
|
||||
path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/pr3-opened-folder.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
|
||||
// 6) Out-of-project folder (`/tmp/outside-dir`) reveals in Finder instead of changing Project selection.
|
||||
const outDirPt = await pointFor("/tmp/outside-dir");
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(outDirPt.x, outDirPt.y);
|
||||
await expect(pathLink).toHaveCount(1);
|
||||
await page.mouse.click(outDirPt.x, outDirPt.y);
|
||||
await page.keyboard.up("Meta");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => (window as unknown as { __revealedInFinder: string[][] }).__revealedInFinder))
|
||||
.toEqual([["/tmp/outside-dir"]]);
|
||||
});
|
||||
@@ -3,6 +3,9 @@ name = ".NET"
|
||||
group = ".NET"
|
||||
icon = "project-dotnet"
|
||||
description = "A .NET project from dotnet new."
|
||||
# With a solution, the top folder is named after it (MySolution/MyProject/MyProject.csproj).
|
||||
# `solution-name` is sent only while "Create solution" is checked; otherwise it renders the name.
|
||||
directory = "{{solution-name}}"
|
||||
|
||||
# `dotnet --version` fails without an SDK (a runtime-only install). Blazor Web App and the
|
||||
# other templates' current options need SDK 8.
|
||||
@@ -50,6 +53,7 @@ type = "checkbox"
|
||||
default = "true"
|
||||
hint = "As in Visual Studio: the solution file at the top, the project in its own folder."
|
||||
|
||||
|
||||
[[fields]]
|
||||
id = "solution-name"
|
||||
label = "Solution name:"
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# JUnit Platform runner
|
||||
|
||||
`ai.openidea.junit.Runner` runs the JUnit Platform tests named by its arguments
|
||||
(`com.acme.OrderTest`, `com.acme.OrderTest#method`; a method selects every overload, so
|
||||
parameterized tests run too) and prints each test as the TeamCity service messages of
|
||||
`src/features/run/gradleTests.gradle`, which the Run window's JVM parser already reads. It exits
|
||||
with 1 when a test failed or none ran.
|
||||
|
||||
OpenIDEA starts it for the gutter's JUnit 5 tests of Maven modules (Settings › Maven › Run tests
|
||||
using: OpenIDEA) as `java -ea -cp <test classpath>:<runner>:<launcher> ai.openidea.junit.Runner …`.
|
||||
`ide_sdk::java::junit_launcher` picks `junit-platform-launcher` of the engine's version, and
|
||||
`ide_build::surefire` reads the module's Surefire configuration for the JVM (IDEA's `MavenJUnitPatcher`).
|
||||
|
||||
The jar is committed and embedded by `ide-sdk` (`junit_runner_jar`). Rebuild it after changing
|
||||
the source, and check it against JUnit with:
|
||||
|
||||
```sh
|
||||
python3 build.py --test
|
||||
python3 build.py
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
b4727459201b0011beb0742bd807421a1fc8426b116193031ed87825bc2d4f04 org/junit/platform/junit-platform-launcher/1.11.3/junit-platform-launcher-1.11.3.jar
|
||||
0043f72f611664735da8dc9a308bf12ecd2236b05339351c4741edb4d8fab0da org/junit/platform/junit-platform-engine/1.11.3/junit-platform-engine-1.11.3.jar
|
||||
be262964b0b6b48de977c61d4f931df8cf61e80e750cc3f3a0a39cdd21c1008c org/junit/platform/junit-platform-commons/1.11.3/junit-platform-commons-1.11.3.jar
|
||||
b509448ac506d607319f182537f0b35d71007582ec741832a1f111e5b5b70b38 org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar
|
||||
48e2df636cab6563ced64dcdff8abb2355627cb236ef0bf37598682ddf742f1b org/opentest4j/opentest4j/1.3.0/opentest4j-1.3.0.jar
|
||||
5d8147a60f49453973e250ed68701b7ff055964fe2462fc2cb1ec1d6d44889ba org/junit/jupiter/junit-jupiter-api/5.11.3/junit-jupiter-api-5.11.3.jar
|
||||
e62420c99f7c0d59a2159a2ef63e61877e9c80bd722c03ca8bf3bdcea050a589 org/junit/jupiter/junit-jupiter-engine/5.11.3/junit-jupiter-engine-5.11.3.jar
|
||||
0f798ebec744c4e6605fd4f2072f41a8e989e2d469e21db5aa67cf799c0b51ec org/junit/jupiter/junit-jupiter-params/5.11.3/junit-jupiter-params-5.11.3.jar
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Build the committed JUnit Platform runner (Java 8 bytecode), or test it: python3 build.py [--test].
|
||||
|
||||
Compiles against the JUnit jars of build-dependencies.sha256, taken from the local Maven
|
||||
repository (MAVEN_REPO, default ~/.m2/repository; `mvn dependency:get` fetches a missing one).
|
||||
--test runs tests/SampleTest.java through the runner and checks its service messages."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
root = Path(__file__).resolve().parent
|
||||
repo = Path(os.environ.get("MAVEN_REPO", Path.home() / ".m2" / "repository"))
|
||||
java_home = os.environ.get("JAVA_HOME")
|
||||
test = "--test" in sys.argv[1:]
|
||||
|
||||
|
||||
def tool(name):
|
||||
return str(Path(java_home) / "bin" / name) if java_home else name
|
||||
|
||||
|
||||
jars = []
|
||||
for line in (root / "build-dependencies.sha256").read_text().splitlines():
|
||||
digest, path = line.split()
|
||||
jar = repo / path
|
||||
if hashlib.sha256(jar.read_bytes()).hexdigest() != digest:
|
||||
sys.exit(f"{jar}: SHA-256 mismatch")
|
||||
jars.append(str(jar))
|
||||
# The launcher API only: the runner must not depend on an engine.
|
||||
api = [j for j in jars if "/junit-platform-" in j or "apiguardian" in j]
|
||||
|
||||
with tempfile.TemporaryDirectory() as scratch:
|
||||
classes = Path(scratch) / "classes"
|
||||
sources = sorted((root / "src").rglob("*.java"))
|
||||
subprocess.run([tool("javac"), "--release", "8", "-encoding", "UTF-8", "-g", "-Xlint:-options",
|
||||
"-cp", os.pathsep.join(api), "-d", str(classes), *map(str, sources)], check=True)
|
||||
if test:
|
||||
sample = Path(scratch) / "sample"
|
||||
cp = os.pathsep.join(jars)
|
||||
subprocess.run([tool("javac"), "-encoding", "UTF-8", "-cp", cp, "-d", str(sample),
|
||||
str(root / "tests" / "SampleTest.java")], check=True)
|
||||
run = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]),
|
||||
"ai.openidea.junit.Runner", "sample.SampleTest"], capture_output=True)
|
||||
out = run.stdout.decode("utf-8")
|
||||
print(out)
|
||||
expected = [
|
||||
"##teamcity[testStarted name='passes' className='sample.SampleTest']",
|
||||
"##teamcity[testStdOut name='passes' className='sample.SampleTest' out='hello |[ünï|]|n']",
|
||||
"##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'",
|
||||
"##teamcity[testIgnored name='disabled' className='sample.SampleTest'",
|
||||
"##teamcity[testIgnored name='aborted' className='sample.SampleTest']",
|
||||
"##teamcity[testFailed name='parameterized' className='sample.SampleTest'",
|
||||
"##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=",
|
||||
"7 tests completed, 2 failed, 2 skipped",
|
||||
]
|
||||
missing = [e for e in expected if e not in out]
|
||||
assert not missing, missing
|
||||
assert run.returncode == 1, run.returncode
|
||||
method = subprocess.run([tool("java"), "-cp", os.pathsep.join([str(classes), str(sample), cp]),
|
||||
"ai.openidea.junit.Runner", "sample.SampleTest#parameterized"], capture_output=True)
|
||||
assert method.stdout.decode().count("testStarted") == 2, method.stdout
|
||||
print("ok")
|
||||
sys.exit(0)
|
||||
with zipfile.ZipFile(root / "openidea-junit-runner.jar", "w") as jar:
|
||||
for path in sorted(classes.rglob("*.class")):
|
||||
entry = zipfile.ZipInfo(path.relative_to(classes).as_posix(), (2026, 1, 1, 0, 0, 0))
|
||||
jar.writestr(entry, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED)
|
||||
Loaded 100 of 369 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача