diff --git a/src/features/debugger/__tests__/tableView.test.tsx b/src/features/debugger/__tests__/tableView.test.tsx new file mode 100644 index 0000000000..151110f828 --- /dev/null +++ b/src/features/debugger/__tests__/tableView.test.tsx @@ -0,0 +1,245 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ debugEvaluateIn: vi.fn() })); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { ...real, commands: { ...real.commands, ...ipc } }; +}); + +import type { DebugSessionId, Variable } from "@/platform/ipc"; +import { adoptSession, useDebug } from "../state"; +import { clampWindow, isTableType, parseTableResult, tableExpression } from "../tableView"; +import { TableViewDialog } from "../ui/TableViewDialog"; +import { VariablesView } from "../ui/VariablesView"; +import { useOverlays } from "../ui/popoverStore"; +import { hideContextMenu, useContextMenuStore } from "@/ui/Menu"; + +/** How debugpy shows the helper's JSON reply: Python's repr of a str. */ +const pyRepr = (o: unknown) => `'${JSON.stringify(o).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`; +const reply = (o: unknown) => + Promise.resolve({ + status: "ok" as const, + data: { name: "", value: pyRepr(o), typeName: "str", variablesReference: 0, evaluateName: null }, + }); + +const PAGE = { + kind: "frame" as const, + shape: [250, 2], + rows: 250, + columns: 2, + dtypes: ["object", "float64"], + headers: ["name", "score"], + index: ["0", "1"], + cells: [ + ['it\'s "x"', "1.5"], + ["日本", "nan"], + ], +}; + +function session(adapter = "debugpy") { + useDebug.setState({ sessions: {}, active: null }); + adoptSession(7, { adapter }); + useDebug.setState((s) => ({ + sessions: { 7: { ...s.sessions[7]!, status: "paused", selectedFrame: 10 } }, + active: 7, + })); +} + +/** A `stopped` event as `state.ts` records it: the frame is unknown until the stack trace arrives. */ +function stop(frame: number | null) { + act(() => + useDebug.setState((s) => ({ + sessions: { + 7: { ...s.sessions[7]!, stops: s.sessions[7]!.stops + (frame == null ? 1 : 0), selectedFrame: frame }, + }, + })), + ); +} + +beforeEach(() => session()); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); + useDebug.setState({ sessions: {}, active: null }); + useOverlays.setState({ tableView: null }); +}); + +describe("table view model", () => { + it("knows the types debugpy reports for DataFrame, Series and ndarray", () => { + expect(["DataFrame", "Series", "ndarray"].every(isTableType)).toBe(true); + expect(isTableType("list")).toBe(false); + expect(isTableType(null)).toBe(false); + }); + + it("reads the helper's reply through Python's string quoting", () => { + expect(parseTableResult(pyRepr(PAGE))).toEqual({ page: PAGE }); + expect(parseTableResult(pyRepr({ error: "ndim", ndim: 3 }))).toEqual({ error: "ndim", ndim: 3 }); + expect(parseTableResult("NameError: name 'df' is not defined")).toEqual({ + error: "NameError: name 'df' is not defined", + }); + }); + + it("moves a window the object no longer reaches back to its last page", () => { + const w = { row: 100, column: 30 }; + expect(clampWindow(w, { rows: 250, columns: 45 })).toBe(w); + expect(clampWindow({ row: 200, column: 30 }, { rows: 50, columns: 45 })).toEqual({ row: 0, column: 30 }); + expect(clampWindow({ row: 200, column: 30 }, { rows: 150, columns: 12 })).toEqual({ row: 100, column: 0 }); + expect(clampWindow({ row: 100, column: 0 }, { rows: 0, columns: 0 })).toEqual({ row: 0, column: 0 }); + }); + + it("passes the expression outside the helper's lambda, with the page window", () => { + const e = tableExpression("frames['a']", { row: 100, column: 30 }); + expect(e).toMatch( + /^\(lambda g, o: \(exec\(".*", g\), g\['f'\]\(o, 100, 100, 30, 30\)\)\[1\]\)\(\{\}, \(frames\['a'\]\)\)$/s, + ); + }); +}); + +describe("View as Table", () => { + it("shows a page with headers, dtypes and index, and fetches the next rows on demand", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE)); + render( {}} />); + const table = await screen.findByRole("table"); + expect( + within(table) + .getAllByRole("columnheader") + .map((h) => h.textContent), + ).toEqual(["", "nameobject", "scorefloat64"]); + expect(within(table).getAllByRole("row")[1]!.textContent).toBe('0it\'s "x"1.5'); + expect(screen.getByText("Shape (250, 2)")).toBeInTheDocument(); + expect(screen.getByText("Rows 1–100 of 250")).toBeInTheDocument(); + expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, tableExpression("df", { row: 0, column: 0 }), "clipboard"); + + fireEvent.click(screen.getByRole("button", { name: "Next Rows" })); + await waitFor(() => + expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith( + 7, + 10, + tableExpression("df", { row: 100, column: 0 }), + "clipboard", + ), + ); + expect(await screen.findByText("Rows 101–200 of 250")).toBeInTheDocument(); + }); + + it("asks for a 2-D slice of an array with more dimensions", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply({ error: "ndim", ndim: 3 })); + render( {}} />); + expect(await screen.findByRole("alert")).toHaveTextContent("A 3-dimensional array can't be shown as a table"); + }); + + it("shows the exception of an expression that fails in the frame", async () => { + // With the `clipboard` context debugpy answers with the exception's repr as the value. + ipc.debugEvaluateIn.mockImplementation(() => + Promise.resolve({ + status: "ok" as const, + data: { + name: "", + value: `NameError("name 'df' is not defined")`, + typeName: "NameError", + variablesReference: 3, + evaluateName: null, + }, + }), + ); + render( {}} />); + expect(await screen.findByRole("alert")).toHaveTextContent(`NameError("name 'df' is not defined")`); + }); + + it("goes back to the last page when a step leaves the object shorter than the page shown", async () => { + let rows = 250; + ipc.debugEvaluateIn.mockImplementation(() => reply({ ...PAGE, rows, shape: [rows, 2] })); + render( {}} />); + fireEvent.click(await screen.findByRole("button", { name: "Next Rows" })); + fireEvent.click(await screen.findByRole("button", { name: "Next Rows" })); + expect(await screen.findByText("Rows 201–250 of 250")).toBeInTheDocument(); + + rows = 50; + stop(null); + stop(10); + await waitFor(() => + expect(ipc.debugEvaluateIn).toHaveBeenLastCalledWith( + 7, + 10, + tableExpression("df", { row: 0, column: 0 }), + "clipboard", + ), + ); + expect(await screen.findByText("Shape (50, 2)")).toBeInTheDocument(); + expect(screen.getAllByRole("row")).toHaveLength(3); + }); + + it("waits for the stopped frame, and doesn't show the previous stop's page meanwhile", async () => { + ipc.debugEvaluateIn.mockImplementation(() => reply(PAGE)); + render( {}} />); + await screen.findByRole("table"); + ipc.debugEvaluateIn.mockClear(); + let answer: (v: unknown) => void = () => {}; + ipc.debugEvaluateIn.mockImplementation(() => new Promise((r) => (answer = r))); + + stop(null); + expect(ipc.debugEvaluateIn).not.toHaveBeenCalled(); + expect(screen.queryByRole("table")).toBeNull(); + stop(12); + expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith( + 7, + 12, + tableExpression("df", { row: 0, column: 0 }), + "clipboard", + ); + expect(screen.queryByRole("table")).toBeNull(); + await act(async () => answer(await reply(PAGE))); + expect(screen.getByRole("table")).toBeInTheDocument(); + }); + + it("puts a DataFrame's dtypes on its columns even when the page has one column", async () => { + ipc.debugEvaluateIn.mockImplementation(() => + reply({ ...PAGE, shape: [250, 31], columns: 31, dtypes: ["float64"], headers: ["z"], cells: [["1.0"], ["2.0"]] }), + ); + render( {}} />); + const table = await screen.findByRole("table"); + expect(within(table).getAllByRole("columnheader")[1]).toHaveTextContent("zfloat64"); + expect(screen.getByText("Shape (250, 31)")).toBeInTheDocument(); + }); + + const frame: Variable = { + name: "df", + value: " a\n0 1", + typeName: "DataFrame", + variablesReference: 5, + evaluateName: "df", + }; + const menuFor = (v: Variable) => { + render( + , + ); + fireEvent.contextMenu(screen.getByRole("treeitem")); + const labels = (useContextMenuStore.getState().menu?.items ?? []).map((i) => ("label" in i ? i.label : "|")); + hideContextMenu(); + cleanup(); + return labels; + }; + + it("is offered for a DataFrame in a Python session, and opens outside the Variables view", () => { + render( + , + ); + fireEvent.contextMenu(screen.getByRole("treeitem")); + const item = useContextMenuStore.getState().menu?.items.find((i) => "label" in i && i.label === "View as Table"); + act(() => hideContextMenu()); + expect(item && "run" in item).toBe(true); + if (item && "run" in item) item.run?.(); + // The Variables view unmounts while the program runs; the viewer stays open across steps. + expect(useOverlays.getState().tableView).toEqual({ expression: "df", session: 7 }); + }); + + it("is not offered for other values or other debuggers", () => { + expect(menuFor({ ...frame, typeName: "list" })).not.toContain("View as Table"); + session("lldb"); + expect(menuFor(frame)).not.toContain("View as Table"); + }); +}); diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index 94e7633d35..0246e98e58 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -68,7 +68,8 @@ const useAnyOverlay = () => s.attach || s.smartStep || s.streamChooser || - s.streamAbort != null + s.streamAbort != null || + s.tableView ), ); diff --git a/src/features/debugger/tableView.ts b/src/features/debugger/tableView.ts new file mode 100644 index 0000000000..c5cbdca813 --- /dev/null +++ b/src/features/debugger/tableView.ts @@ -0,0 +1,112 @@ +/** + * View as Table (PyCharm's View as Array / DataFrame): one window of a pandas DataFrame / + * Series or numpy array at a time, read with `evaluate` in the paused frame. The debuggee + * slices the object itself, so only the rows and columns on screen cross the wire. + */ +import { stringText } from "./valueText"; + +/** Type names debugpy reports for values the viewer can show. */ +const TABLE_TYPES = new Set(["DataFrame", "Series", "ndarray"]); + +export function isTableType(typeName: string | null | undefined): boolean { + return !!typeName && TABLE_TYPES.has(typeName); +} + +/** Numbers are right-aligned, as in the database grid. */ +export function isNumericDtype(dtype: string | undefined): boolean { + return !!dtype && /^(u?int|float|complex|Int|UInt|Float)\d*$/.test(dtype); +} + +export const ROW_PAGE = 100; +export const COLUMN_PAGE = 30; + +export interface TableWindow { + row: number; + column: number; +} + +export interface TablePage { + kind: "frame" | "series" | "array"; + /** The object's own shape, e.g. `[1000, 5]`. */ + shape: number[]; + rows: number; + columns: number; + /** One dtype per shown column for a DataFrame, else the object's single dtype. */ + dtypes: string[]; + headers: string[]; + index: string[]; + cells: string[][]; +} + +/** `error`: "type" (not a table), "ndim" (more than two dimensions; `ndim` says how many) or the error text. */ +export type TableResult = { page: TablePage } | { error: string; ndim?: number }; + +// Runs in the debuggee. Cells are cut at 200 characters so one huge cell can't flood the reply. +const HELPER = ` +def f(o, r0, nr, c0, nc): + import json + s = lambda v: str(v)[:200] + try: + if hasattr(o, 'iloc') and hasattr(o, 'columns'): + k, d = 'frame', o.iloc[r0:r0 + nr, c0:c0 + nc] + R, C = o.shape + dt, h = [str(x) for x in d.dtypes], [s(c) for c in d.columns] + idx, cells = [s(i) for i in d.index], [[s(v) for v in r] for r in d.itertuples(index=False, name=None)] + elif hasattr(o, 'iloc'): + k, d = 'series', o.iloc[r0:r0 + nr] + R, C = len(o), 1 + dt, h = [str(o.dtype)], ['' if o.name is None else s(o.name)] + idx, cells = [s(i) for i in d.index], [[s(v)] for v in d] + elif hasattr(o, 'ndim') and hasattr(o, 'dtype'): + if o.ndim > 2: + return json.dumps({'error': 'ndim', 'ndim': o.ndim}) + k, a = 'array', (o.reshape(1, 1) if o.ndim == 0 else o) + R, C = a.shape[0], (a.shape[1] if a.ndim == 2 else 1) + d = a[r0:r0 + nr, c0:c0 + nc] if a.ndim == 2 else a[r0:r0 + nr].reshape(-1, 1) + dt, h = [str(o.dtype)], [str(c0 + j) for j in range(d.shape[1])] if a.ndim == 2 else ['0'] + idx, cells = [str(r0 + i) for i in range(d.shape[0])], [[s(v) for v in r] for r in d] + else: + return json.dumps({'error': 'type'}) + return json.dumps({'kind': k, 'shape': list(o.shape), 'rows': R, 'columns': C, 'dtypes': dt, + 'headers': h, 'index': idx, 'cells': cells}) + except Exception as e: + return json.dumps({'error': '%s: %s' % (type(e).__name__, e)}) +`; + +/** + * The window moved back onto the object when a step or another frame left it with fewer rows + * or columns than the window starts at (the last page then); `w` itself when it still fits. + */ +export function clampWindow(w: TableWindow, page: Pick): TableWindow { + const fit = (at: number, total: number, size: number) => + at < total ? at : Math.max(0, Math.floor((total - 1) / size) * size); + const row = fit(w.row, page.rows, ROW_PAGE); + const column = fit(w.column, page.columns, COLUMN_PAGE); + return row === w.row && column === w.column ? w : { row, column }; +} + +/** + * One expression (evaluate takes no statements): defines the helper in a fresh namespace + * and calls it. `expression` is passed as an argument, outside the lambda, because a + * lambda body can't see the frame's locals that `eval` was given. + */ +export function tableExpression(expression: string, w: TableWindow): string { + return ( + `(lambda g, o: (exec(${JSON.stringify(HELPER)}, g), ` + + `g['f'](o, ${w.row}, ${ROW_PAGE}, ${w.column}, ${COLUMN_PAGE}))[1])({}, (${expression}))` + ); +} + +/** The helper's reply (a Python string literal holding JSON), or the adapter's own error text. */ +export function parseTableResult(value: string): TableResult { + let data: unknown; + try { + data = JSON.parse(stringText(value)); + } catch { + return { error: value }; + } + const d = data as Record; + if (typeof d.error === "string") + return d.error === "ndim" ? { error: "ndim", ndim: Number(d.ndim) } : { error: d.error }; + return { page: d as unknown as TablePage }; +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index d7fb2f0df1..e7a3c6d386 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -78,6 +78,7 @@ import { EventBreakpointsSection } from "../js/EventBreakpointsSection"; import { StreamChainChooser } from "../streams/StreamChainChooser"; import { StreamAbortDialog } from "../streams/StreamAbortDialog"; import { closeBreakpointPopover, useOverlays } from "./popoverStore"; +import { TableViewDialog } from "./TableViewDialog"; import { VariablesView, type VarRoot } from "./VariablesView"; import { useExpressionCompletion } from "./ExpressionCompletion"; import { pushHistory, readHistory } from "./expressionHistory"; @@ -96,10 +97,29 @@ export function DebuggerOverlays() { + ); } +function TableView() { + const view = useOverlays((s) => s.tableView); + // A finished session (Stop, or Restart, which starts another id) has nothing left to show. + const live = useDebug((s) => view != null && isLive(s.sessions[view.session])); + useEffect(() => { + if (view && !live) useOverlays.setState({ tableView: null }); + }, [view, live]); + if (!view || !live) return null; + return ( + useOverlays.setState({ tableView: null })} + /> + ); +} + function errorText(e: unknown) { return e instanceof Error ? e.message : String(e); } diff --git a/src/features/debugger/ui/TableViewDialog.module.css b/src/features/debugger/ui/TableViewDialog.module.css new file mode 100644 index 0000000000..62d4f8c475 --- /dev/null +++ b/src/features/debugger/ui/TableViewDialog.module.css @@ -0,0 +1,115 @@ +.dialog { + height: clamp(320px, 60vh, 760px); +} + +/* The table scrolls under a fixed bar, not the whole dialog body. */ +.content { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; +} + +.bar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-2); + padding-bottom: var(--space-2); +} + +.expression { + flex: 1 1 200px; + min-width: 0; + height: var(--h-list-row); + padding: 0 6px; + font-family: var(--font-mono); + font-size: var(--fs-ui); + color: var(--fg); + background: var(--bg-input); + border: 1px solid var(--border); + border-radius: var(--radius-small); +} + +.expression:focus { + outline: none; + border-color: var(--focus-ring); +} + +.summary, +.pager { + color: var(--fg-secondary); + white-space: nowrap; +} + +.pager { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} + +.scroll { + flex: 1; + min-height: 0; + overflow: auto; + box-shadow: inset 0 0 0 1px var(--border); + border-radius: var(--radius-small); +} + +.table { + border-collapse: separate; + border-spacing: 0; + font-family: var(--font-mono); + font-size: var(--fs-ui); + color: var(--fg); +} + +.table th, +.table td { + height: var(--h-list-row); + padding: 0 8px; + white-space: pre; + border-right: 1px solid var(--border); + border-bottom: 1px solid var(--border); +} + +.table thead th { + position: sticky; + top: 0; + z-index: 1; + text-align: left; + font-weight: normal; + color: var(--fg-secondary); + background: var(--bg-island); +} + +.table .index { + position: sticky; + left: 0; + text-align: right; + font-weight: normal; + color: var(--fg-secondary); + background: var(--bg-island); +} + +.table thead .index { + z-index: 2; +} + +.table tbody tr:hover td { + background: var(--bg-hover); +} + +.numeric { + text-align: right; +} + +.dtype { + margin-left: var(--space-1); + color: var(--fg-subtle); +} + +.message { + padding: var(--space-3) 0; + color: var(--fg-secondary); +} diff --git a/src/features/debugger/ui/TableViewDialog.tsx b/src/features/debugger/ui/TableViewDialog.tsx new file mode 100644 index 0000000000..27273b82da --- /dev/null +++ b/src/features/debugger/ui/TableViewDialog.tsx @@ -0,0 +1,205 @@ +/** View as Table: a DataFrame / Series / ndarray of the paused frame, one page of rows and columns at a time. */ +import { useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import type { DebugSessionId } from "@/platform/ipc"; +import { Dialog, IconButton } from "@/ui"; +import { formatMessage, tx } from "@/platform/i18n"; +import { evaluate, useDebug } from "../state"; +import { + COLUMN_PAGE, + ROW_PAGE, + clampWindow, + isNumericDtype, + parseTableResult, + tableExpression, + type TableResult, +} from "../tableView"; +import styles from "./TableViewDialog.module.css"; + +export function TableViewDialog({ + expression: initial, + session, + onClose, +}: { + expression: string; + session: DebugSessionId; + onClose: () => void; +}) { + const [draft, setDraft] = useState(initial); + const [expression, setExpression] = useState(initial); + const [win, setWin] = useState({ row: 0, column: 0 }); + const [result, setResult] = useState(null); + // A step, a new stop or another frame shows the values the object has there. + const stops = useDebug((st) => st.sessions[session]?.stops); + const frame = useDebug((st) => st.sessions[session]?.selectedFrame); + const paused = useDebug((st) => st.sessions[session]?.status === "paused"); + + // What the shown page was read for; another expression, stop or frame makes it stale. + const readFor = useRef(""); + + useEffect(() => { + const key = `${expression}\n${stops}\n${frame}`; + if (readFor.current !== key) { + readFor.current = key; + setResult(null); + } + const s = useDebug.getState().sessions[session]; + // Right after a stop the frame is unknown until the stack trace arrives; without a frame, + // debugpy would run the expression in a namespace of its own. + if (!s || s.status !== "paused" || s.selectedFrame == null) return; + let live = true; + evaluate(tableExpression(expression, win), "clipboard", s).then( + (v) => { + if (!live) return; + const r = parseTableResult(v.value); + const fits = "page" in r ? clampWindow(win, r.page) : win; + if (fits !== win) setWin(fits); + else setResult(r); + }, + (e: unknown) => live && setResult({ error: e instanceof Error ? e.message : String(e) }), + ); + return () => { + live = false; + }; + }, [expression, win, session, stops, frame, paused]); + + const page = result && "page" in result ? result.page : null; + const error = !paused + ? tx("Values are available while the program is paused") + : result && "error" in result + ? result.error === "type" + ? tx("Not a pandas DataFrame or Series, or a numpy array") + : result.error === "ndim" + ? formatMessage(tx("A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]"), { + n: String(result.ndim), + }) + : result.error + : null; + + const pager = ( + at: number, + size: number, + total: number, + move: (to: number) => void, + label: { range: string; previous: string; next: string }, + ) => + total > size && ( + + move(at - size)} + /> + + {formatMessage(label.range, { + from: String(at + 1), + to: String(Math.min(at + size, total)), + total: String(total), + })} + + = total} + onClick={() => move(at + size)} + /> + + ); + + return ( + {initial}} + width="clamp(520px, 70vw, 1100px)" + minWidth={420} + minHeight={260} + resizable="both" + aria-label={formatMessage(tx("Table view of {label}"), { label: initial })} + className={styles.dialog} + > +
+
+ setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key !== "Enter" || !draft.trim()) return; + e.preventDefault(); + setExpression(draft.trim()); + setWin({ row: 0, column: 0 }); + }} + /> + {page && ( + + {formatMessage(tx("Shape ({shape})"), { shape: page.shape.join(", ") })} + {page.kind !== "frame" ? ` · ${page.dtypes[0]}` : ""} + + )} + {page && + pager(win.row, ROW_PAGE, page.rows, (row) => setWin({ ...win, row }), { + range: tx("Rows {from}–{to} of {total}"), + previous: tx("Previous Rows"), + next: tx("Next Rows"), + })} + {page && + pager(win.column, COLUMN_PAGE, page.columns, (column) => setWin({ ...win, column }), { + range: tx("Columns {from}–{to} of {total}"), + previous: tx("Previous Columns"), + next: tx("Next Columns"), + })} +
+ {error ? ( +
+ {error} +
+ ) : page ? ( +
+ + + + + ))} + + + + {page.cells.map((row, r) => ( + + + {row.map((cell, c) => ( + + ))} + + ))} + +
+ {page.headers.map((h, i) => ( + + {h} + {page.kind === "frame" && {page.dtypes[i]}} +
+ {page.index[r]} + + {cell} +
+
+ ) : ( +
{tx("Loading…")}
+ )} +
+
+ ); +} diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx index 301e3f6e3d..c18a0d3d2a 100644 --- a/src/features/debugger/ui/VariablesView.tsx +++ b/src/features/debugger/ui/VariablesView.tsx @@ -19,11 +19,14 @@ import { removeAllWatches, removeWatch, revealFrame, + rootOf, sessionSupports, setVariableValue, useDebug, } from "../state"; import { blurDebugView, focusDebugView } from "./focusedView"; +import { openTableView } from "./popoverStore"; +import { isTableType } from "../tableView"; import { classifyValue, oneLine, shownValue, sortVariables } from "../values"; import { stringText, valueText } from "../valueText"; import { workflowSettings } from "@/platform/workflowSettings"; @@ -400,6 +403,9 @@ export function VariablesView({ { kind: "separator" }, ); if (editable(node)) items.push({ label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) }); + const tableExpression = node.evaluateName; + if (tableExpression && session != null && isTableType(node.typeName) && pausedIn(session)?.adapter === "debugpy") + items.push({ label: "View as Table", run: () => openTableView(tableExpression, session) }); items.push( { label: "Copy Value", icon: "copy", run: () => void copyValue(node) }, { label: "Copy Name", run: () => void writeClipboardText(node.name) }, @@ -480,6 +486,12 @@ export function VariablesView({ ); } +/** The session with this id while it is paused, with the adapter its root session started. */ +function pausedIn(session: DebugSessionId | null) { + const s = session != null ? useDebug.getState().sessions[session] : undefined; + return s?.status === "paused" ? rootOf(s) : null; +} + /** * View: the whole value in a popup that a click outside closes. Adapters cut long strings * short in variables; the value is evaluated again as for copying (`clipboard`), which diff --git a/src/features/debugger/ui/popoverStore.ts b/src/features/debugger/ui/popoverStore.ts index 845266696c..87a4b70860 100644 --- a/src/features/debugger/ui/popoverStore.ts +++ b/src/features/debugger/ui/popoverStore.ts @@ -40,6 +40,8 @@ interface OverlayState { streamChooser: { session: DebugSessionId; frame: number; chains: StreamChainInfo[] } | null; /** The session whose stream trace "Abort Operation…" asks about. */ streamAbort: DebugSessionId | null; + /** View as Table; it stays open across steps, so it lives here rather than in the Variables view. */ + tableView: { expression: string; session: DebugSessionId } | null; } export const useOverlays = create(() => ({ @@ -51,6 +53,7 @@ export const useOverlays = create(() => ({ smartStep: null, streamChooser: null, streamAbort: null, + tableView: null, })); export function openBreakpointPopover(path: string, id: string, at: { x: number; y: number }, focusLog = false) { @@ -61,6 +64,10 @@ export function closeBreakpointPopover() { useOverlays.setState({ popover: null }); } +export function openTableView(expression: string, session: DebugSessionId) { + useOverlays.setState({ tableView: { expression, session } }); +} + export function openEvaluateDialog(expression = "") { useOverlays.setState({ evaluate: { expression } }); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index aa007f28b4..c250b6a01a 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3040,5 +3040,17 @@ "Mail:": "Mail:", "A folder with this name already exists and is not empty": "A folder with this name already exists and is not empty", "Show Only Affected Changes": "Show Only Affected Changes", - "Layout": "Layout" + "Layout": "Layout", + "Values are available while the program is paused": "Values are available while the program is paused", + "Not a pandas DataFrame or Series, or a numpy array": "Not a pandas DataFrame or Series, or a numpy array", + "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]": "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]", + "Table view of {label}": "Table view of {label}", + "Shape ({shape})": "Shape ({shape})", + "Rows {from}–{to} of {total}": "Rows {from}–{to} of {total}", + "Columns {from}–{to} of {total}": "Columns {from}–{to} of {total}", + "View as Table": "View as Table", + "Previous Rows": "Previous Rows", + "Next Rows": "Next Rows", + "Previous Columns": "Previous Columns", + "Next Columns": "Next Columns" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 75f5af9fea..1cfc96f78f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9358,5 +9358,17 @@ "Homepage:": "主页:", "Mail:": "邮件:", "Show Only Affected Changes": "仅显示受影响的变更", - "Layout": "布局" + "Layout": "布局", + "Values are available while the program is paused": "程序暂停时才能查看值", + "Not a pandas DataFrame or Series, or a numpy array": "不是 pandas DataFrame、Series 或 numpy 数组", + "A {n}-dimensional array can't be shown as a table: view a 2-D slice, e.g. a[0]": "{n} 维数组无法显示为表格:请查看二维切片,例如 a[0]", + "Table view of {label}": "{label} 的表格视图", + "Shape ({shape})": "形状 ({shape})", + "Rows {from}–{to} of {total}": "第 {from}–{to} 行,共 {total} 行", + "Columns {from}–{to} of {total}": "第 {from}–{to} 列,共 {total} 列", + "View as Table": "以表格查看", + "Previous Rows": "上一组行", + "Next Rows": "下一组行", + "Previous Columns": "上一组列", + "Next Columns": "下一组列" }