# Cursor / vscode-R 开 r.plot.useHttpgd 时的交互预览防护，只影响 print(ggplot)。
# 首张 ggplot 常在刚打开的 unigd 上把 viewport 路径置 NULL，
# grid::depth() 报 UseMethod("depth") on NULL。
# 给 NULL 登记 depth（返回 0，不 pop 视口），并在监视器注入 device 后预开 httpgd。
# knitr 走 ragg_png，不经过这里。
#
# 用法（项目 .Rprofile，放在 renv/activate.R 之后）：
#   if (interactive() && file.exists("scripts/book-plot/R/httpgd-warmup.R")) {
#     source("scripts/book-plot/R/httpgd-warmup.R")
#   }
# 只在新会话生效；改完须 q() 再开终端。
if (interactive()) {
  local({
    registerS3method(
      "depth",
      "NULL",
      function(x, ...) 0L,
      envir = asNamespace("grid")
    )
    warmup <- function(...) {
      if (isTRUE(getOption("bookplot.httpgd_warmed"))) {
        return(FALSE)
      }
      devfun <- getOption("device")
      src <- if (is.function(devfun)) {
        paste(deparse(body(devfun)), collapse = "\n")
      } else {
        ""
      }
      tries <- getOption("bookplot.httpgd_tries", 0L)
      options(bookplot.httpgd_tries = tries + 1L)
      # 监视器尚未注入 httpgd 设备：最多再等 20 个顶层命令
      if (!grepl("httpgd::", src, fixed = TRUE)) {
        return(tries < 20L)
      }
      cur <- names(grDevices::dev.cur())
      already <- grepl("unigd|httpgd", cur)
      if (!already && requireNamespace("httpgd", quietly = TRUE)) {
        try({
          httpgd::hgd(silent = TRUE)
          vsc <- get0(".vsc", ifnotfound = NULL, inherits = TRUE)
          if (is.environment(vsc) && is.function(vsc$request)) {
            vsc$request("httpgd", url = httpgd::hgd_url())
          }
        }, silent = TRUE)
      }
      options(bookplot.httpgd_warmed = TRUE)
      FALSE
    }
    invisible(addTaskCallback(warmup, name = "bookplot-httpgd-warmup"))
  })
}
