fix(python): respect inherited MPLBACKEND and tidy plot files (#6653)

Follow-up to #6529. A run that inherits the IDE's environment now keeps an MPLBACKEND set in the login shell or the project's .envrc instead of replacing it with the Plots backend; debug launches get the backend too, unless their own environment names one. Figures dropped from the Plots tool window are deleted from the project's plots folder (plots_delete, limited to finished figures in that folder, compared canonicalized), and the watcher reports a figure once it is renamed into place.

Refs #6514

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-28 14:57:42 +08:00
1 джерело d5ba63e333
коміт d698b50361
17 files changed
+324 -50

No files matched your search

+4 -2
Переглянути файл
@@ -62,8 +62,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
python.as_deref(),
config.cwd.as_deref(),
);
let plots = super::plots::prepare(host, &project);
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
let plots = super::plots::prepare(host, &project).await;
// The debuggee inherits the IDE's environment as a run started in its folder does.
let dir = config.cwd.as_deref().map(|c| c.to_path_buf()).unwrap_or_else(|| project.root.clone());
super::python::prepare_debug(&mut config, &paths, plots.as_ref().map(|p| (p, dir.as_path())))?;
}
let label = window;
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
+2 -1
Переглянути файл
@@ -28,7 +28,7 @@ pub mod lsp;
pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
mod plots;
pub mod plots;
pub mod project;
pub mod pytest_fixtures;
mod python;
@@ -107,6 +107,7 @@ ide_command::domains!(
mcp_reports: crate::mcp::reports,
nav: crate::ops::nav,
notebook: crate::ops::notebook,
plots: crate::ops::plots,
plugins_commands: crate::plugins::commands,
plugins_commit: crate::plugins::commit,
plugins_index_ops: crate::plugins::index_ops,
+93 -13
Переглянути файл
@@ -2,25 +2,37 @@
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
use crate::Host;
use crate::project::Project;
use ide_core::IdeEvent;
use ide_command::command;
use ide_core::{IdeEvent, IdeResult, SharedSink};
use ide_run::plots::Plots;
use notify::{RecursiveMode, Watcher};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::io;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
/// `None` when Settings › Python turns the tool window off.
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
/// The backend and plots folder for a Python run of `project`, installed and watched on first use
/// (off the async runtime: the first use empties the folder); `None` when Settings › Python turns
/// the tool window off.
pub(crate) async fn prepare(host: &Host, project: &Arc<Project>) -> Option<Plots> {
if !project.settings.effective().languages.python.show_plots_in_tool_window {
return None;
}
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
Ok(()) => Some(plots),
Err(e) => {
let (project, target) = (project.clone(), plots.clone());
let ready = super::blocking_value(move || {
ide_run::plots::install(&target.backend).and_then(|()| watch(&project, &target.dir))
})
.await;
match ready {
Ok(Ok(())) => Some(plots),
Ok(Err(e)) => {
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
None
}
Err(e) => {
tracing::warn!("cannot set up the Plots tool window: {}", e.message);
None
}
}
}
@@ -32,8 +44,13 @@ fn watch(project: &Project, dir: &Path) -> io::Result<()> {
// Figures of an earlier session are not shown again.
let _ = std::fs::remove_dir_all(dir);
std::fs::create_dir_all(dir)?;
let sink = project.sink.clone();
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
*slot = Some(watch_dir(dir, project.sink.clone())?);
Ok(())
}
/// Sends `PlotAdded` for each finished figure in `dir`. A file can be reported more than once
/// (created, renamed, modified); the window lists each path once.
fn watch_dir(dir: &Path, sink: SharedSink) -> io::Result<RecommendedWatcher> {
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
for path in res.map(|e| e.paths).unwrap_or_default() {
if is_plot(&path) && path.is_file() {
@@ -43,8 +60,7 @@ fn watch(project: &Project, dir: &Path) -> io::Result<()> {
})
.map_err(io::Error::other)?;
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
*slot = Some(watcher);
Ok(())
Ok(watcher)
}
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
@@ -53,9 +69,32 @@ fn is_plot(path: &Path) -> bool {
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
}
/// Deletes figures the Plots tool window dropped; only figures in this project's plots folder.
#[command(trust = always)]
pub async fn plots_delete(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
let dir = host.project(window)?.cache_dir.join("plots");
super::blocking_value(move || delete(&dir, &paths)).await
}
/// Paths are compared canonicalized: the watcher reports real paths, and the cache folder may be
/// reached through a symlink.
fn delete(dir: &Path, paths: &[PathBuf]) {
let Ok(dir) = dunce::canonicalize(dir) else { return };
let in_dir = |p: &Path| p.parent().and_then(|d| dunce::canonicalize(d).ok()).is_some_and(|d| d == dir);
for path in paths.iter().filter(|p| is_plot(p) && in_dir(p)) {
let _ = std::fs::remove_file(path);
}
}
ide_command::domain!(
plots:
plots_delete,
);
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
#[test]
fn only_finished_pngs_are_plots() {
@@ -63,4 +102,45 @@ mod tests {
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
}
#[cfg(unix)]
#[test]
fn deletes_only_finished_figures_in_the_plots_folder_through_a_symlink() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("real");
std::fs::create_dir_all(real.join("plots")).unwrap();
std::fs::create_dir_all(real.join("other")).unwrap();
std::os::unix::fs::symlink(&real, tmp.path().join("link")).unwrap();
let files = [real.join("plots/1-2-0.png"), real.join("plots/.1-2-1.png"), real.join("other/1-2-2.png")];
for f in &files {
std::fs::write(f, b"png").unwrap();
}
let reported: Vec<_> = files.iter().map(|f| dunce::canonicalize(f).unwrap()).collect();
delete(&tmp.path().join("link/plots"), &reported);
assert_eq!(files.map(|f| f.exists()), [false, true, true]);
}
#[test]
fn reports_a_figure_once_it_is_renamed_into_place() {
let tmp = tempfile::tempdir().unwrap();
let dir = dunce::canonicalize(tmp.path()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
let _ = tx.send(e);
});
let _watch = watch_dir(&dir, sink).unwrap();
std::fs::write(dir.join(".1-2-0.png"), b"png").unwrap();
std::fs::rename(dir.join(".1-2-0.png"), dir.join("1-2-0.png")).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
let mut seen = Vec::new();
while Instant::now() < deadline {
if let Ok(IdeEvent::PlotAdded { path }) = rx.recv_timeout(Duration::from_millis(200)) {
seen.push(path);
} else if !seen.is_empty() {
break;
}
}
assert!(!seen.is_empty(), "no PlotAdded event");
assert!(seen.iter().all(|p| p.ends_with("1-2-0.png") && !p.ends_with(".1-2-0.png")), "{seen:?}");
}
}
+53 -7
Переглянути файл
@@ -52,12 +52,12 @@ pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
extra.get("python")?.as_str().map(str::to_owned)
}
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
/// launch's environment.
/// Adds the project's import paths, and the Plots tool window's backend (`plots`, with the folder
/// the debuggee starts in), to a debugpy launch's environment.
pub(super) fn prepare_debug(
config: &mut LaunchConfig,
paths: &[PathBuf],
plots: Option<&ide_run::plots::Plots>,
plots: Option<(&ide_run::plots::Plots, &Path)>,
) -> IdeResult<()> {
// Adapter-specific env takes precedence over the common launch fields in DAP.
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
@@ -77,8 +77,8 @@ pub(super) fn prepare_debug(
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
let inherit = !vars.contains_key("PYTHONPATH");
ide_run::python_path::extend(&mut vars, paths, inherit)?;
if let Some(plots) = plots {
ide_run::plots::add(&mut vars, plots, true)?;
if let Some((plots, dir)) = plots {
ide_run::plots::add(&mut vars, plots, Some(dir))?;
}
for (key, value) in vars {
object.insert(key, serde_json::json!(value));
@@ -86,8 +86,8 @@ pub(super) fn prepare_debug(
config.extra_json = extra.map(|e| e.to_string());
} else {
ide_run::python_path::extend(&mut config.env, paths, true)?;
if let Some(plots) = plots {
ide_run::plots::add(&mut config.env, plots, true)?;
if let Some((plots, dir)) = plots {
ide_run::plots::add(&mut config.env, plots, Some(dir))?;
}
}
Ok(())
@@ -147,4 +147,50 @@ mod tests {
assert_eq!(std::env::split_paths(&vars["PYTHONPATH"]).collect::<Vec<_>>(), [root, vendor]);
}
}
#[test]
fn debug_adds_the_plots_backend_to_the_launch_env_unless_it_sets_one() {
let root = std::env::temp_dir().join("project");
if ide_core::process::host_var_os_in(&root, "MPLBACKEND").is_some() {
eprintln!("skipped: this machine sets MPLBACKEND");
return;
}
let plots = ide_run::plots::Plots { backend: root.join("backend"), dir: root.join("plots") };
let launch = |extra: serde_json::Value, env: BTreeMap<String, String>| LaunchConfig {
name: "Python".into(),
adapter: "debugpy".into(),
request: "launch".into(),
program: Some("main.py".into()),
args: vec![],
cwd: None,
env,
extra_json: Some(extra.to_string()),
};
let env_of = |config: &LaunchConfig| -> serde_json::Value {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["env"].clone()
};
// The launch's own variables stay as they are, other values included.
let mut config = launch(serde_json::json!({"env": {"DEBUG": "1", "LEVEL": 3}}), BTreeMap::new());
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root))).unwrap();
let env = env_of(&config);
assert_eq!((env["DEBUG"].as_str(), env["LEVEL"].as_i64()), (Some("1"), Some(3)));
assert_eq!(env["MPLBACKEND"], "module://openidea_matplotlib_backend");
assert_eq!(env["OPENIDEA_PLOTS_DIR"], plots.dir.to_string_lossy().as_ref());
let path: Vec<_> = std::env::split_paths(env["PYTHONPATH"].as_str().unwrap()).collect();
// A PYTHONPATH this machine sets follows.
assert_eq!(path[..2], [plots.backend.clone(), root.clone()]);
// A backend the launch names, in either environment field, is kept.
let mut config = launch(serde_json::json!({"env": {"MPLBACKEND": "Agg"}}), BTreeMap::new());
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root))).unwrap();
let env = env_of(&config);
assert_eq!(env["MPLBACKEND"], "Agg");
assert!(env.get("OPENIDEA_PLOTS_DIR").is_none());
let own = BTreeMap::from([("MPLBACKEND".into(), "TkAgg".into())]);
let mut config = launch(serde_json::json!({}), own);
prepare_debug(&mut config, std::slice::from_ref(&root), Some((&plots, &root))).unwrap();
assert_eq!(config.env["MPLBACKEND"], "TkAgg");
assert!(!config.env.contains_key("OPENIDEA_PLOTS_DIR"));
}
}
+1 -1
Переглянути файл
@@ -553,7 +553,7 @@ async fn start_inner(
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths,
ruby_reporter: ruby_reporter_dir(host, &config),
plots: if is_python { super::plots::prepare(host, &project) } else { None },
plots: if is_python { super::plots::prepare(host, &project).await } else { None },
};
project.require_trust()?;
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
+69 -10
Переглянути файл
@@ -1,5 +1,8 @@
//! The Plots tool window's matplotlib backend (see `plots/`): Python runs get `MPLBACKEND` pointing at
//! it, and `plt.show()` saves each figure as a PNG in the project's plots folder, which the IDE watches.
//!
//! The backend is found through `PYTHONPATH`, as PyCharm's is: a child process that drops `PYTHONPATH`
//! (`python -I`, a replaced environment) but keeps `MPLBACKEND` cannot import it.
use ide_core::IdeResult;
use std::collections::BTreeMap;
use std::io;
@@ -28,13 +31,16 @@ pub fn install(dir: &Path) -> io::Result<()> {
std::fs::write(path, text)
}
/// Points matplotlib at the backend, unless the run's environment (or, when it inherits it, the
/// IDE's own) already sets `MPLBACKEND`.
pub fn add(env: &mut BTreeMap<String, String>, plots: &Plots, inherit: bool) -> IdeResult<()> {
if env.contains_key("MPLBACKEND") || (inherit && crate::system_env().contains_key("MPLBACKEND")) {
/// Points matplotlib at the backend, unless the run's environment already sets `MPLBACKEND`.
/// `inherit_in`: the folder the run starts in when it inherits the IDE's environment; what it
/// inherits there (the login shell's and the project's `.envrc` variables too) counts.
pub fn add(env: &mut BTreeMap<String, String>, plots: &Plots, inherit_in: Option<&Path>) -> IdeResult<()> {
if env.contains_key("MPLBACKEND")
|| inherit_in.is_some_and(|dir| ide_core::process::host_var_os_in(dir, "MPLBACKEND").is_some())
{
return Ok(());
}
crate::python_path::extend(env, std::slice::from_ref(&plots.backend), inherit)?;
crate::python_path::extend(env, std::slice::from_ref(&plots.backend), inherit_in.is_some())?;
env.insert("MPLBACKEND".into(), format!("module://{MODULE}"));
env.insert("OPENIDEA_PLOTS_DIR".into(), plots.dir.to_string_lossy().into_owned());
Ok(())
@@ -43,24 +49,77 @@ pub fn add(env: &mut BTreeMap<String, String>, plots: &Plots, inherit: bool) ->
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn plots(root: &Path) -> Plots {
Plots { backend: root.join("backend"), dir: root.join("plots") }
}
#[test]
fn installs_the_backend_and_leaves_a_users_backend_alone() {
let tmp = tempfile::tempdir().unwrap();
let plots = Plots { backend: tmp.path().join("backend"), dir: tmp.path().join("plots") };
let plots = plots(tmp.path());
install(&plots.backend).unwrap();
install(&plots.backend).unwrap();
assert_eq!(std::fs::read_to_string(plots.backend.join(FILE.0)).unwrap(), FILE.1);
let mut env = BTreeMap::from([("PYTHONPATH".into(), "/src".into())]);
add(&mut env, &plots, false).unwrap();
add(&mut env, &plots, None).unwrap();
assert_eq!(env["MPLBACKEND"], "module://openidea_matplotlib_backend");
assert_eq!(env["OPENIDEA_PLOTS_DIR"], plots.dir.to_string_lossy());
let path: Vec<_> = std::env::split_paths(&env["PYTHONPATH"]).collect();
assert_eq!(path, [plots.backend.clone(), PathBuf::from("/src")]);
let mut own = BTreeMap::from([("MPLBACKEND".into(), "Agg".into())]);
add(&mut own, &plots, false).unwrap();
assert_eq!(own, BTreeMap::from([("MPLBACKEND".into(), "Agg".into())]));
let own = BTreeMap::from([("MPLBACKEND".into(), "Agg".into())]);
let mut env = own.clone();
add(&mut env, &plots, Some(tmp.path())).unwrap();
assert_eq!(env, own);
}
/// A backend the run inherits (here the project's `.envrc`) wins over the Plots backend.
#[test]
fn leaves_an_inherited_backend_alone() {
if std::env::var_os("MPLBACKEND").is_some() {
eprintln!("skipped: this process sets MPLBACKEND");
return;
}
let tmp = tempfile::tempdir().unwrap();
let plots = plots(tmp.path());
let project = tmp.path().join("project");
ide_core::project_env::set(&project, vec![("MPLBACKEND".into(), Some("Agg".into()))]);
let mut env = BTreeMap::new();
add(&mut env, &plots, Some(&project.join("src"))).unwrap();
ide_core::project_env::remove(&project);
assert!(env.is_empty(), "{env:?}");
}
/// Runs the real backend when this machine's `python3` has matplotlib (skipped otherwise).
#[test]
fn the_backend_saves_each_shown_figure_once() {
let python = if cfg!(windows) { "python" } else { "python3" };
if !Command::new(python).args(["-c", "import matplotlib"]).output().is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no matplotlib for {python}");
return;
}
let tmp = tempfile::tempdir().unwrap();
let plots = plots(tmp.path());
install(&plots.backend).unwrap();
let mut env = BTreeMap::new();
add(&mut env, &plots, None).unwrap();
let script = "import matplotlib.pyplot as plt\n\
plt.plot([1, 2]); plt.figure(); plt.plot([2, 1])\n\
plt.show()\n\
f = plt.figure(); plt.plot([3, 1]); f.show()\n\
plt.show()\n\
print(plt.get_backend())\n";
let out = Command::new(python).args(["-c", script]).envs(&env).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "module://openidea_matplotlib_backend");
let mut names: Vec<String> =
std::fs::read_dir(&plots.dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into()).collect();
names.sort();
// Two figures, then the third once: `f.show()` saved it and `plt.show()` doesn't again.
assert_eq!(names.len(), 3, "{names:?}");
assert!(names.iter().all(|n| n.ends_with(".png") && !n.starts_with('.')), "{names:?}");
}
}
+15 -2
Переглянути файл
@@ -1,29 +1,42 @@
"""matplotlib backend of OpenIDEA's Plots tool window (MPLBACKEND=module://openidea_matplotlib_backend).
plt.show() saves every open figure as a PNG in OPENIDEA_PLOTS_DIR, where the IDE picks it up, and
closes the figures; Figure.show() saves that figure.
closes the figures; Figure.show() saves that figure. A figure shown again unchanged is not saved twice.
"""
import hashlib
import io
import itertools
import os
import time
import weakref
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import FigureManagerBase, _Backend
from matplotlib.backends.backend_agg import FigureCanvasAgg
_counter = itertools.count()
# The digest of each live figure's last saved image.
_saved = weakref.WeakKeyDictionary()
def _save(figure):
directory = os.environ.get("OPENIDEA_PLOTS_DIR")
if not directory:
return
buffer = io.BytesIO()
figure.savefig(buffer, format="png")
data = buffer.getvalue()
digest = hashlib.sha1(data).digest()
if _saved.get(figure) == digest:
return
_saved[figure] = digest
os.makedirs(directory, exist_ok=True)
name = "%d-%d-%d.png" % (time.time_ns(), os.getpid(), next(_counter))
# Written under a hidden name first: the IDE reads only finished files.
partial = os.path.join(directory, "." + name)
figure.savefig(partial, format="png")
with open(partial, "wb") as file:
file.write(data)
os.replace(partial, os.path.join(directory, name))
+1 -1
Переглянути файл
@@ -431,7 +431,7 @@ impl ProcessManager {
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test") {
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
if let Some(plots) = &options.plots {
crate::plots::add(&mut env.vars, plots, !env.clear)?;
crate::plots::add(&mut env.vars, plots, (!env.clear).then_some(cwd.as_path()))?;
}
}
if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) {
+8
Переглянути файл
@@ -140,6 +140,14 @@ Run with Coverage uses coverage.py in the project interpreter, and Profile uses
Jupyter notebooks (`.ipynb`) run on a Python interpreter; see [Notebooks](/en/guide/notebook).
### Plots
matplotlib figures from runs, debug sessions and the Python Console go to the **Plots** tool window (right) instead of matplotlib's own window: `plt.show()` adds every open figure, and `Figure.show()` adds that figure. The window keeps the newest 100 plots; you can save one as PNG, copy it to the clipboard or delete it.
- A run that sets `MPLBACKEND` itself keeps its backend, including one inherited from the login shell or the project's `.envrc`. A `backend:` line in `matplotlibrc` is overridden.
- The IDE's backend is found through `PYTHONPATH`. A child process that drops `PYTHONPATH` but keeps `MPLBACKEND` (`python -I`, or `subprocess` with a replaced `env`) cannot import it; unset `MPLBACKEND` for that process.
- Turn it off with **Show plots in tool window** on **Settings › Languages & Frameworks › Python Interpreter**.
## Debugging
Python debugging uses debugpy. If it is missing when you start a debug session, OpenIDEA offers to install it. The IDE keeps a private copy of debugpy in its tools folder and loads it into whichever interpreter runs your program, so you do not need debugpy in the project environment.
+8
Переглянути файл
@@ -140,6 +140,14 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
Jupyter Notebook(`.ipynb`)在 Python 解释器上运行,见 [Notebook](/zh/guide/notebook)。
### 绘图
运行、调试会话和 Python 控制台中的 matplotlib 图形会显示在右侧的 **绘图** 工具窗口,而不是 matplotlib 自己的窗口:`plt.show()` 添加所有打开的图形,`Figure.show()` 添加该图形。窗口保留最新的 100 张图,可以另存为 PNG、复制到剪贴板或删除。
- 运行自行设置了 `MPLBACKEND` 时保留它的后端,包括从登录 shell 或项目 `.envrc` 继承的值。`matplotlibrc` 中的 `backend:` 会被覆盖。
- IDE 的后端通过 `PYTHONPATH` 找到。子进程去掉 `PYTHONPATH` 却保留 `MPLBACKEND` 时(`python -I`,或 `subprocess` 传入替换过的 `env`)无法导入它;请为该进程取消设置 `MPLBACKEND`。
- 在 **设置 › 语言和框架 › Python 解释器** 中关闭 **在工具窗口中显示绘图**。
## 调试
Python 调试使用 debugpy。开始调试时如果缺少 debugpy,OpenIDEA 会提示安装。IDE 在自己的工具文件夹里保存一份 debugpy,并把它加载到运行程序的解释器中,所以项目环境里不需要安装 debugpy。
+1
Переглянути файл
@@ -472,6 +472,7 @@ notebook_undo always project_host bin
notebook_variables trusted project_host bindings async
open_project always project_host bindings async
path_completions always project_host bindings async
plots_delete always project_host bindings async
plugin_activation_event trusted desktop bindings async
plugin_answer_clipboard trusted project_host bindings sync
plugin_answer_command trusted project_host bindings sync
+2
Переглянути файл
@@ -1277,6 +1277,8 @@ export const commands = {
openProject: (path: string) => typedError<ProjectInfo_Serialize, IdeError>(__TAURI_INVOKE("open_project", { path })),
/** Files and folders that continue `prefix`, a path being typed in `from`. */
pathCompletions: (from: IpcPath, prefix: string) => typedError<PathCompletion[], IdeError>(__TAURI_INVOKE("path_completions", { from, prefix })),
/** Deletes figures the Plots tool window dropped; only figures in this project's plots folder. */
plotsDelete: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("plots_delete", { paths })),
/** An activation event from the UI: `kind` is `language`, `file` (project-relative path) or `view`. */
pluginActivationEvent: (kind: string, value: string) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_activation_event", { kind, value })),
/**
+42 -5
Переглянути файл
@@ -1,22 +1,59 @@
import { beforeEach, describe, expect, it } from "vitest";
import { addPlot, clearPlots, removePlot, usePlots } from "./store";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { writeDesktopBase64 } from "@/platform/desktopFiles";
import { commands } from "@/platform/ipc";
import { provideNotificationService } from "@/workbench/contributions";
import { MAX_PLOTS, addPlot, clearPlots, removePlot, savePlot, usePlots } from "./store";
vi.mock("@/platform/dialog", () => ({ save: async () => "/out/plot.png" }));
vi.mock("@/platform/desktopFiles", () => ({ writeDesktopBase64: vi.fn(async () => {}) }));
const deleted = vi.spyOn(commands, "plotsDelete").mockResolvedValue({ status: "ok", data: null });
describe("plots", () => {
beforeEach(clearPlots);
beforeEach(() => {
clearPlots();
deleted.mockClear();
});
it("lists each figure once and selects the newest", () => {
expect([addPlot("/p/a.png"), addPlot("/p/b.png"), addPlot("/p/a.png")]).toEqual([true, true, false]);
expect(usePlots.getState()).toEqual({ plots: ["/p/a.png", "/p/b.png"], selected: "/p/b.png" });
expect(deleted).not.toHaveBeenCalled();
});
it("selects a neighbour of the deleted figure", () => {
it("deletes a figure's file and selects a neighbour", () => {
["/p/a.png", "/p/b.png", "/p/c.png"].forEach(addPlot);
usePlots.setState({ selected: "/p/b.png" });
removePlot("/p/b.png");
expect(usePlots.getState().selected).toBe("/p/c.png");
expect(deleted).toHaveBeenLastCalledWith(["/p/b.png"]);
removePlot("/p/c.png");
expect(usePlots.getState().selected).toBe("/p/a.png");
removePlot("/p/a.png");
clearPlots();
expect(usePlots.getState()).toEqual({ plots: [], selected: null });
expect(deleted).toHaveBeenLastCalledWith(["/p/a.png"]);
});
it("keeps the newest figures and deletes the files of older ones", () => {
for (let i = 0; i <= MAX_PLOTS; i++) addPlot(`/p/${i}.png`);
const { plots } = usePlots.getState();
expect([plots.length, plots[0], plots.at(-1)]).toEqual([MAX_PLOTS, "/p/1.png", `/p/${MAX_PLOTS}.png`]);
expect(deleted).toHaveBeenCalledWith(["/p/0.png"]);
});
it("saves the figure's PNG bytes and reports a failure", async () => {
const notes: string[] = [];
provideNotificationService({ notify: (n) => void notes.push(`${n.level}: ${n.title}`) });
const read = vi
.spyOn(commands, "fsReadImage")
.mockResolvedValue({ status: "ok", data: "data:image/png;base64,UE5H" });
await savePlot("/p/a.png");
expect(read).toHaveBeenCalledWith("/p/a.png");
expect(writeDesktopBase64).toHaveBeenCalledWith("/out/plot.png", "UE5H");
expect(notes).toEqual([]);
read.mockResolvedValueOnce({ status: "error", error: { kind: "internal", message: "gone", data: null } });
await savePlot("/p/a.png");
expect(notes).toEqual(["error: Cannot save the plot"]);
});
});
+22 -5
Переглянути файл
@@ -6,6 +6,9 @@ import { writeDesktopBase64 } from "@/platform/desktopFiles";
import { tx } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
/** The window keeps this many figures; a run that shows more drops (and deletes) the oldest. */
export const MAX_PLOTS = 100;
interface PlotsState {
plots: string[];
selected: string | null;
@@ -13,15 +16,23 @@ interface PlotsState {
export const usePlots = create<PlotsState>(() => ({ plots: [], selected: null }));
/** The files of figures the window no longer lists; failures only leave a file in the cache. */
function deleteFiles(paths: string[]) {
if (paths.length) void call(commands.plotsDelete(paths)).catch(() => {});
}
/** Shows a new figure; false when it is already listed (the watcher reports a file more than once). */
export function addPlot(path: string): boolean {
const { plots } = usePlots.getState();
if (plots.includes(path)) return false;
usePlots.setState({ plots: [...plots, path], selected: path });
const all = [...plots, path];
const dropped = all.slice(0, Math.max(0, all.length - MAX_PLOTS));
usePlots.setState({ plots: all.slice(dropped.length), selected: path });
deleteFiles(dropped);
return true;
}
/** Removes a figure from the list and selects its neighbour. */
/** Deletes a figure and selects its neighbour. */
export function removePlot(path: string) {
const { plots, selected } = usePlots.getState();
const at = plots.indexOf(path);
@@ -30,9 +41,14 @@ export function removePlot(path: string) {
plots: rest,
selected: selected === path ? (rest[Math.min(at, rest.length - 1)] ?? null) : selected,
});
deleteFiles([path]);
}
export const clearPlots = () => usePlots.setState({ plots: [], selected: null });
export function clearPlots() {
const { plots } = usePlots.getState();
usePlots.setState({ plots: [], selected: null });
deleteFiles(plots);
}
const failed = (title: string) => (e: unknown) =>
notifications().notify({ level: "error", title, body: e instanceof Error ? e.message : String(e) });
@@ -45,8 +61,9 @@ export async function savePlot(path: string) {
filters: [{ name: "PNG", extensions: ["png"] }],
});
if (!to) return;
const url = await call(commands.fsReadImage(path));
await writeDesktopBase64(to, url.slice(url.indexOf(",") + 1)).catch(failed(tx("Cannot save the plot")));
await call(commands.fsReadImage(path))
.then((url) => writeDesktopBase64(to, url.slice(url.indexOf(",") + 1)))
.catch(failed(tx("Cannot save the plot")));
}
export function copyPlot(path: string) {
+1 -1
Переглянути файл
@@ -452,7 +452,7 @@ export function PythonInterpreterPage() {
<SettingToggle
k="languages.python.showPlotsInToolWindow"
label="Show plots in tool window"
hint="Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window."
hint="Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window."
/>
</Section>
+1 -1
Переглянути файл
@@ -4390,7 +4390,7 @@
"Delete Plot": "Delete Plot",
"Delete All Plots": "Delete All Plots",
"Show plots in tool window": "Show plots in tool window",
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.": "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.",
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.": "Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.",
"cProfile": "cProfile",
"py-spy": "py-spy",
"Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.",
+1 -1
Переглянути файл
@@ -10926,7 +10926,7 @@
"Delete Plot": "删除绘图",
"Delete All Plots": "删除全部绘图",
"Show plots in tool window": "在工具窗口中显示绘图",
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND. Off: figures open in matplotlib's own window.": "运行、调试会话和 Python 控制台的 matplotlib 图形会发送到“绘图”工具窗口,除非运行自行设置了 MPLBACKEND。关闭后,图形在 matplotlib 自己的窗口中打开。",
"Runs, debug sessions and the Python Console send matplotlib figures to the Plots tool window, unless the run sets MPLBACKEND; a backend in matplotlibrc is overridden. Off: figures open in matplotlib's own window.": "运行、调试会话和 Python 控制台的 matplotlib 图形会发送到“绘图”工具窗口,除非运行自行设置了 MPLBACKEND;matplotlibrc 中设置的后端会被覆盖。关闭后,图形在 matplotlib 自己的窗口中打开。",
"cProfile": "cProfile",
"py-spy": "py-spy",
"Automatic uses py-spy where it is installed and can sample without root (not on macOS), else cProfile from the standard library.": "自动:已安装 py-spy 且无需 root 即可采样时(macOS 除外)使用 py-spy,否则使用标准库的 cProfile。",