//! 共有エディタ状態(T029)。
//! 参照: data-model.md(EditorContext), contracts/zed-ide-bridge.md
//!
//! LSP 側(Zed からの didOpen/documentHighlight/codeAction)が書き込み、
//! MCP 側(Claude への push / pull)が読み出す。診断は初版スコープ外(FR-022)。
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
/// LSP の位置(0-origin の line/character)。
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Position {
pub line: u32,
pub character: u32,
}
/// 選択範囲。start==end のとき isEmpty=true(カーソルのみ)。
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Selection {
pub start: Position,
pub end: Position,
#[serde(rename = "isEmpty")]
pub is_empty: bool,
}
/// 現在のエディタコンテキスト。診断は持たない(スコープ外)。
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct EditorContext {
/// アクティブファイルの絶対パス(未保存/untitled は None)。
#[serde(rename = "filePath", skip_serializing_if = "Option::is_none")]
pub file_path: Option<String>,
/// file:// URL(filePath があるときのみ)。
#[serde(rename = "fileUrl", skip_serializing_if = "Option::is_none")]
pub file_url: Option<String>,
/// 現在の選択(カーソルのみのときは isEmpty=true)。
#[serde(skip_serializing_if = "Option::is_none")]
pub selection: Option<Selection>,
/// 選択されているテキスト本体(カーソルのみのときは "")。
/// Claude Code IDE プロトコルは `text` フィールドを期待する(claudecode.nvim 準拠)。
#[serde(default)]
pub text: String,
}
impl EditorContext {
/// untitled/未保存でも安全に扱う(FR-023)。filePath が無くてもパニックしない。
pub fn is_addressable(&self) -> bool {
self.file_path.is_some()
}
}
/// プロセス全体で共有する状態。
pub struct SharedState {
inner: Mutex<EditorContext>,
/// selection_changed を接続中の全 Claude クライアントへ配るための通知チャネル。
tx: broadcast::Sender<EditorContext>,
}
impl SharedState {
pub fn new() -> Arc<Self> {
let (tx, _rx) = broadcast::channel(64);
Arc::new(SharedState {
inner: Mutex::new(EditorContext::default()),
tx,
})
}
/// push 購読用の受信ハンドルを得る。
pub fn subscribe(&self) -> broadcast::Receiver<EditorContext> {
self.tx.subscribe()
}
/// 現在のコンテキストを取得(pull 経路: getCurrentSelection 用, FR-026)。
pub async fn snapshot(&self) -> EditorContext {
self.inner.lock().await.clone()
}
/// コンテキストを更新し、変化があれば push 配信する。
/// 同値なら配信しない(無駄な通知を避ける)。
pub async fn update(&self, next: EditorContext) {
let mut guard = self.inner.lock().await;
if *guard != next {
*guard = next.clone();
drop(guard);
// 受信者がいない場合の Err は無視(接続前は正常)。
let _ = self.tx.send(next);
}
}
}