diff --git a/README.md b/README.md index dbd3995..f6d268e 100644 --- a/README.md +++ b/README.md @@ -25,18 +25,24 @@ rum --config ./rum.yaml 探索順: `--config ` / 環境変数 `RUM_CONFIG` → `./rum.yaml` → `~/.config/rum/config.yaml` → `~/.chira/rum.yaml` ```yaml -source: db # db(SQLite)| dir(md/txt) -db: ~/.chira/ura.db # source: db で開く SQLite -dir: ~/.chira/md # source: dir で開くディレクトリ / :md :sync の既定 +boxes: + - name: メモ + source: db + db: ~/.chira/ura.db + - name: 下書き + source: dir + dir: ~/.chira/md ``` -`~` は展開される。`rum.example.yaml` を参照。 +単一の `source`, `db`, `dir` も後方互換で動作します。 +`~` は展開されます。`rum.example.yaml` を参照。 -## 読み込み元の切替 +## 3ペイン + チラ裏メタファ -- `:db ` — SQLite に切替(chira-ura のメモ。`notes` テーブルを読み書き) -- `:dir ` — md/txt ディレクトリに切替 -- `:md [dir]` / `:sync [dir]` — 外部 `chira md` / `chira md import` +- **BOX**: 箱(ノートブック)の一覧。箱 = 読み込み元(SQLite / ディレクトリ)。 +- **紙(シート)**: 選択中 BOX の紙一覧。1 枚 = 1 ノート。 +- **エディタ**: 紙の本文。1 枚は **たて 24 行固定**(25 行目は入力不可)。溢れたら新しい紙に続きを書く。 +- **裏写り**: おもて面の文字が裏からうっすら透ける演出(空行に直前の紙の行が淡く重なる)。既定 ON、`:set ura` / `:set noura` でトグル可能。 ## 操作早見表 @@ -47,6 +53,14 @@ dir: ~/.chira/md # source: dir で開くディレクトリ / :md :sync - `Command`: `:` でコマンド入力 - `Search`: `/` で検索入力 +### ペイン・リスト操作 +- `Tab` / `Shift-Tab`: ペイン移動(BOX ↔ 紙 ↔ エディタ) +- `↑` / `↓`(十字)または `j` / `k`: リスト選択 / エディタの行移動 +- `n`: フォーカス中ペインで新規作成 + - BOX ペイン → 箱を新規(`:box `) + - 紙ペイン → 紙を新規 +- `Ctrl-n` / `Ctrl-p`(または `]s` / `[s`): 次の紙 / 前の紙 + ### 移動(Normal / Visual) - `h`, `j`, `k`, `l`: 左 / 下 / 上 / 右 - `w`: 次の単語先頭 @@ -55,8 +69,8 @@ dir: ~/.chira/md # source: dir で開くディレクトリ / :md :sync - `$`: 行末 - `gg`: 先頭行 - `G`: 最終行 -- `Ctrl-p`: 前のファイル -- `Ctrl-n`: 次のファイル +- `Ctrl-p`: 前の紙 +- `Ctrl-n`: 次の紙 ### 編集(Normal) - `i`: カーソル位置で Insert モード @@ -93,9 +107,10 @@ dir: ~/.chira/md # source: dir で開くディレクトリ / :md :sync - `:wq` / `:x`: 保存して終了 - `:e `: 指定ファイルを開く - `:e! [path]`: 現在のファイルまたは指定ファイルを再読み込み(変更破棄) -- `:new`: 新規メモ作成 -- `:next`: 次のファイルを開く -- `:prev`: 前のファイルを開く +- `:new`: 新規紙作成 +- `:next` / `:prev`: 次/前の紙を開く +- `:set ura` / `:set noura`: 裏写り演出の有効化 / 無効化 +- `:box `: 新規 BOX の追加・設定保存 - `:md [dir]`: 外部コマンド `chira md [dir]` を実行 - `:sync [dir]`: 外部コマンド `chira md import [dir]` を実行 diff --git a/src/app.rs b/src/app.rs index 7dbece3..db8764d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,4 +1,5 @@ use crate::buffer::{ClipboardContent, Position, TextBuffer}; +use crate::config::{BoxConfig, Config}; use crate::doc::{derive_title, generate_note_id, Document, FrontMatter}; use anyhow::Result; use chrono::Utc; @@ -71,6 +72,14 @@ pub struct SearchState { pub current_index: Option, } +/// PR #11: 3 ペイン UI のフォーカス対象(BOX / 紙 / エディタ) +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pane { + Box, + Sheet, + Editor, +} + pub struct App { pub source: Source, /// md ディレクトリ(Source::Dir の実体 / `:md` `:sync` の既定) @@ -100,6 +109,13 @@ pub struct App { pub should_quit: bool, pub viewport_top: usize, + // PR #11: 3 ペイン UI(BOX / 紙 / エディタ)と裏写りの状態 + pub config: Config, + pub boxes: Vec, + pub box_index: usize, + pub focused_pane: Pane, + pub ura_enabled: bool, + pub prev_doc_lines: Option>, /// Cached SQLite connection for DB mode pub db_conn: Option, /// Path of the currently cached SQLite connection @@ -108,6 +124,13 @@ pub struct App { impl App { pub fn new(source: Source, md_dir: PathBuf) -> Result { + // 既定設定(BOX 無し)で構築。設定ファイルを読む入口は new_with_config。 + Self::new_with_config(Config::default(), source, md_dir) + } + + /// PR #11: YAML 設定(BOX 一覧)を込めて App を構築する。 + pub fn new_with_config(config: Config, source: Source, md_dir: PathBuf) -> Result { + let boxes = config.effective_boxes(); let root_dir = match &source { Source::Dir(p) => p.clone(), Source::Db(_) => md_dir, @@ -119,6 +142,10 @@ impl App { } let mut app = Self { + config, + boxes, + box_index: 0, + focused_pane: Pane::Editor, source, root_dir, files: Vec::new(), @@ -138,10 +165,25 @@ impl App { pending_operator: None, should_quit: false, viewport_top: 0, + ura_enabled: true, + prev_doc_lines: None, db_conn: None, db_conn_path: None, }; + // BOX のインデックスを現在の source と一致させる + if let Some(pos) = app + .boxes + .iter() + .position(|b| match (&app.source, b.source.as_str()) { + (Source::Db(p), "db") => &b.resolved_path() == p, + (Source::Dir(p), "dir") => &b.resolved_path() == p, + _ => false, + }) + { + app.box_index = pos; + } + app.refresh(); let initial_result = app.open_initial(); app.apply_command_result(initial_result); @@ -149,6 +191,37 @@ impl App { Ok(app) } + /// 直前の紙(前の面)の行を取得(裏写り用) + pub fn update_prev_doc_lines(&mut self) { + self.prev_doc_lines = None; + match &self.source { + Source::Db(db_path) => { + if self.note_index > 0 && self.note_index - 1 < self.notes.len() { + let prev_id = &self.notes[self.note_index - 1].id; + if let Ok(conn) = Connection::open(db_path) { + if let Ok(content) = conn.query_row( + "SELECT content FROM notes WHERE id = ?1", + rusqlite::params![prev_id], + |r| r.get::<_, String>(0), + ) { + self.prev_doc_lines = + Some(content.lines().map(|s| s.to_string()).collect()); + } + } + } + } + Source::Dir(_) => { + if self.file_index > 0 && self.file_index - 1 < self.files.len() { + let prev_file = &self.files[self.file_index - 1]; + if let Ok(doc) = Document::load_from_file(prev_file) { + self.prev_doc_lines = + Some(doc.body.lines().map(|s| s.to_string()).collect()); + } + } + } + } + } + /// Retrieve or open a cached database connection for the given path, configuring busy timeout and WAL mode. pub fn get_db_connection(&mut self, path: &Path) -> rusqlite::Result<&mut Connection> { let same_path = self.db_conn_path.as_deref() == Some(path); @@ -333,6 +406,7 @@ impl App { }; self.note_index = idx; self.viewport_top = 0; + self.update_prev_doc_lines(); Ok(format!("\"{}\" opened", entry.title)) } @@ -394,6 +468,7 @@ impl App { self.buffer = TextBuffer::from_string(&doc.body); self.doc = doc; self.file_index = idx; + self.update_prev_doc_lines(); Ok(format!( "\"{}\" opened", target.file_name().unwrap().to_string_lossy() @@ -445,9 +520,47 @@ impl App { doc.ensure_front_matter(); self.doc = doc; self.buffer = TextBuffer::new(); + self.update_prev_doc_lines(); "New note created".to_string() } + /// PR #11: BOX をインデックス指定で切り替える + pub fn select_box(&mut self, idx: usize) { + if idx >= self.boxes.len() { + return; + } + self.box_index = idx; + let b = self.boxes[idx].clone(); + let path = b.resolved_path(); + match b.source.to_ascii_lowercase().as_str() { + "dir" => { + if !path.exists() { + let _ = fs::create_dir_all(&path); + } + self.root_dir = path.clone(); + self.source = Source::Dir(path); + self.refresh_file_list(); + self.file_index = 0; + if !self.files.is_empty() { + let _ = self.open_file_at_index(0); + } else { + self.new_note(); + } + } + _ => { + self.source = Source::Db(path); + self.refresh_notes(); + self.note_index = 0; + if !self.notes.is_empty() { + let _ = self.open_note_at_index(0); + } else { + self.new_note(); + } + } + } + self.status_message = Some(format!("Switched to BOX: {}", b.name)); + } + pub fn save_current_file(&mut self, target_path: Option<&str>) -> Result { self.doc.body = self.buffer.to_string(); @@ -566,10 +679,38 @@ impl App { } } + /// PR #11: 次のペインへ(Tab) + pub fn next_pane(&mut self) { + self.focused_pane = match self.focused_pane { + Pane::Box => Pane::Sheet, + Pane::Sheet => Pane::Editor, + Pane::Editor => Pane::Box, + }; + } + + /// PR #11: 前のペインへ(Shift-Tab) + pub fn prev_pane(&mut self) { + self.focused_pane = match self.focused_pane { + Pane::Box => Pane::Editor, + Pane::Sheet => Pane::Box, + Pane::Editor => Pane::Sheet, + }; + } + fn handle_normal_key(&mut self, key: KeyEvent) { // Clear status message on key press if not setting a new one self.status_message = None; + // PR #11: Pane switching with Tab / Shift-Tab (BackTab) + if key.code == KeyCode::Tab { + self.next_pane(); + return; + } + if key.code == KeyCode::BackTab { + self.prev_pane(); + return; + } + // Check Ctrl shortcuts if key.modifiers.contains(KeyModifiers::CONTROL) { match key.code { @@ -636,9 +777,25 @@ impl App { self.search_input.clear(); self.search_cursor = 0; } - KeyCode::Char('n') => { - self.goto_next_search_match(); - } + KeyCode::Char('n') => match self.focused_pane { + // PR #11: BOX ペインで n: 箱を新規作成 + Pane::Box => { + self.mode = Mode::Command; + self.command_input = "box ".to_string(); + self.command_cursor = self.command_input.len(); + self.status_message = + Some("Create new box: :box ".to_string()); + } + // PR #11: 紙ペインで n: 紙を新規作成 + Pane::Sheet => { + self.new_note(); + self.focused_pane = Pane::Editor; + self.mode = Mode::Insert; + } + Pane::Editor => { + self.goto_next_search_match(); + } + }, KeyCode::Char('N') => { self.goto_prev_search_match(); } @@ -714,11 +871,49 @@ impl App { KeyCode::Char('l') | KeyCode::Right => { self.buffer.move_right(false); } - KeyCode::Char('j') | KeyCode::Down => { - self.buffer.move_down(); - } - KeyCode::Char('k') | KeyCode::Up => { - self.buffer.move_up(); + KeyCode::Char('j') | KeyCode::Down => match self.focused_pane { + // PR #11: BOX ペインでは次の BOX を選ぶ + Pane::Box => { + if !self.boxes.is_empty() { + let next = (self.box_index + 1) % self.boxes.len(); + self.select_box(next); + } + } + // PR #11: 紙ペインでは次の紙へ + Pane::Sheet => { + let result = self.next_file(); + self.apply_command_result(result); + } + Pane::Editor => { + self.buffer.move_down(); + } + }, + KeyCode::Char('k') | KeyCode::Up => match self.focused_pane { + // PR #11: BOX ペインでは前の BOX を選ぶ + Pane::Box => { + if !self.boxes.is_empty() { + let prev = if self.box_index == 0 { + self.boxes.len().saturating_sub(1) + } else { + self.box_index - 1 + }; + self.select_box(prev); + } + } + // PR #11: 紙ペインでは前の紙へ + Pane::Sheet => { + let result = self.prev_file(); + self.apply_command_result(result); + } + Pane::Editor => { + self.buffer.move_up(); + } + }, + KeyCode::Enter => { + // PR #11: BOX / 紙ペインで Enter でエディタへ戻る + if self.focused_pane == Pane::Box || self.focused_pane == Pane::Sheet { + self.focused_pane = Pane::Editor; + } } KeyCode::Char('w') => { self.buffer.move_word_forward(); @@ -1175,6 +1370,56 @@ impl App { } } + /// PR #11: 裏写りの ON/OFF(:set ura | :set noura) + fn cmd_set(&mut self, arg: Option<&str>) -> Result { + match arg { + Some("ura") => { + self.ura_enabled = true; + Ok("ura (裏写り) enabled".to_string()) + } + Some("noura") => { + self.ura_enabled = false; + Ok("ura (裏写り) disabled".to_string()) + } + _ => Err("usage: :set ura | :set noura".to_string()), + } + } + + /// PR #11: BOX を設定に追加して選ぶ(:box ) + fn cmd_box(&mut self, parts: &[&str]) -> Result { + if parts.len() >= 4 { + let name = parts[1].to_string(); + let kind = parts[2].to_lowercase(); + let path_str = parts[3].to_string(); + let is_dir = kind == "dir"; + let new_box = BoxConfig { + name: name.clone(), + source: if is_dir { + "dir".to_string() + } else { + "db".to_string() + }, + db: if is_dir { None } else { Some(path_str.clone()) }, + dir: if is_dir { Some(path_str.clone()) } else { None }, + }; + match self.config.add_box(new_box) { + Ok(cfg_path) => { + self.boxes = self.config.boxes.clone(); + let new_idx = self.boxes.len() - 1; + self.select_box(new_idx); + Ok(format!( + "Added BOX \"{}\" to {}", + name, + cfg_path.display() + )) + } + Err(e) => Err(format!("failed to save config: {e}")), + } + } else { + Err("usage: :box ".to_string()) + } + } + pub fn execute_command(&mut self, command_line: &str) { self.mode = Mode::Normal; @@ -1203,6 +1448,9 @@ impl App { "dir" => self.cmd_dir(arg), "md" => self.cmd_md(arg), "sync" => self.cmd_sync(arg), + // PR #11: 裏写りの ON/OFF と BOX 追加 + "set" => self.cmd_set(arg), + "box" => self.cmd_box(&parts), _ => Err(format!("Unknown command: {}", cmd)), }; self.apply_command_result(result); @@ -1786,6 +2034,45 @@ mod tests { assert!(msg.starts_with("Error:")); } + // --- PR #11: 3 ペイン UI --- + + #[test] + fn test_pane_switching() { + let dir = std::env::temp_dir().join("rum_pane_test"); + let _ = fs::create_dir_all(&dir); + let mut app = + App::new_with_config(Config::default(), Source::Dir(dir.clone()), dir.clone()).unwrap(); + + assert_eq!(app.focused_pane, Pane::Editor); + app.next_pane(); + assert_eq!(app.focused_pane, Pane::Box); + app.next_pane(); + assert_eq!(app.focused_pane, Pane::Sheet); + app.next_pane(); + assert_eq!(app.focused_pane, Pane::Editor); + + app.prev_pane(); + assert_eq!(app.focused_pane, Pane::Sheet); + app.prev_pane(); + assert_eq!(app.focused_pane, Pane::Box); + let _ = fs::remove_dir_all(dir); + } + + #[test] + fn test_set_ura_toggle() { + let dir = std::env::temp_dir().join("rum_ura_test"); + let _ = fs::create_dir_all(&dir); + let mut app = + App::new_with_config(Config::default(), Source::Dir(dir.clone()), dir.clone()).unwrap(); + + assert!(app.ura_enabled); + app.execute_command("set noura"); + assert!(!app.ura_enabled); + app.execute_command("set ura"); + assert!(app.ura_enabled); + let _ = fs::remove_dir_all(dir); + } + #[test] fn test_db_save_note_transaction_atomicity() { let temp_dir = std::env::temp_dir().join(format!( @@ -1918,3 +2205,4 @@ mod tests { } } + diff --git a/src/buffer.rs b/src/buffer.rs index 179a895..fbbfd71 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -1,5 +1,8 @@ use unicode_width::UnicodeWidthChar; +/// 1枚の紙はたて24行固定 +pub const MAX_SHEET_LINES: usize = 24; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Position { pub row: usize, @@ -49,9 +52,12 @@ impl TextBuffer { pub fn from_string(text: &str) -> Self { let mut lines: Vec = text.lines().map(|s| s.to_string()).collect(); - if lines.is_empty() || text.ends_with('\n') { + if lines.is_empty() || (text.ends_with('\n') && lines.len() < MAX_SHEET_LINES) { lines.push(String::new()); } + if lines.len() > MAX_SHEET_LINES { + lines.truncate(MAX_SHEET_LINES); + } Self { lines, cursor: Position { row: 0, col: 0 }, @@ -338,6 +344,10 @@ impl TextBuffer { } pub fn insert_newline(&mut self) { + // 1 枚 = たて 24 行。25 行目は入力できない(改行を無視)。 + if self.lines.len() >= MAX_SHEET_LINES { + return; + } self.commit_edit(); let line = &self.lines[self.cursor.row]; let chars: Vec = line.chars().collect(); @@ -412,12 +422,16 @@ impl TextBuffer { self.commit_edit(); match clip { ClipboardContent::Lines(lines) => { - // Paste below current line - for (i, line) in lines.iter().enumerate() { + // Paste below current line, respecting MAX_SHEET_LINES + let available = MAX_SHEET_LINES.saturating_sub(self.lines.len()); + let to_insert = lines.len().min(available); + for (i, line) in lines.iter().take(to_insert).enumerate() { self.lines.insert(self.cursor.row + 1 + i, line.clone()); } - self.cursor.row += 1; - self.cursor.col = 0; + if to_insert > 0 { + self.cursor.row += 1; + self.cursor.col = 0; + } } ClipboardContent::Chars(text) => { let line = &mut self.lines[self.cursor.row]; @@ -438,6 +452,9 @@ impl TextBuffer { } pub fn open_line_below(&mut self) { + if self.lines.len() >= MAX_SHEET_LINES { + return; + } self.commit_edit(); self.lines.insert(self.cursor.row + 1, String::new()); self.cursor.row += 1; @@ -445,6 +462,9 @@ impl TextBuffer { } pub fn open_line_above(&mut self) { + if self.lines.len() >= MAX_SHEET_LINES { + return; + } self.commit_edit(); self.lines.insert(self.cursor.row, String::new()); self.cursor.col = 0; @@ -526,6 +546,31 @@ mod tests { assert_eq!(buf.lines, vec!["line 2", "line 1", "line 3"]); } + #[test] + fn test_24_lines_limit() { + let mut lines = Vec::new(); + for i in 0..24 { + lines.push(format!("line {}", i)); + } + let full_text = lines.join("\n"); + let mut buf = TextBuffer::from_string(&full_text); + assert_eq!(buf.line_count(), 24); + + // 25行目の newline は無視される + buf.insert_newline(); + assert_eq!(buf.line_count(), 24); + + // open_line_below / open_line_above も無視される + buf.open_line_below(); + assert_eq!(buf.line_count(), 24); + buf.open_line_above(); + assert_eq!(buf.line_count(), 24); + + // paste も 24 行を超えない + buf.paste(&ClipboardContent::Lines(vec!["extra".to_string()])); + assert_eq!(buf.line_count(), 24); + } + #[test] fn test_unedited_session_records_no_undo_step() { let mut buf = TextBuffer::from_string("abc"); diff --git a/src/config.rs b/src/config.rs index 99dedcc..91c8572 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,32 @@ -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; +/// BOX(箱 / ノートブック)の設定 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BoxConfig { + pub name: String, + pub source: String, // "db" または "dir" + #[serde(default, skip_serializing_if = "Option::is_none")] + pub db: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dir: Option, +} + +impl BoxConfig { + pub fn resolved_path(&self) -> PathBuf { + match self.source.to_ascii_lowercase().as_str() { + "dir" => { + let p = self.dir.as_deref().unwrap_or("~/.chira/md"); + expand(p) + } + _ => { + let p = self.db.as_deref().unwrap_or("~/.chira/ura.db"); + expand(p) + } + } + } +} + /// rum の設定。パスはハードコードせず YAML から読む。 /// /// 探索順(最初に見つかったものを使う): @@ -10,7 +36,7 @@ use std::path::{Path, PathBuf}; /// 4. `~/.chira/rum.yaml` /// /// 値が無いフィールドは Default(下記)で埋まる。 -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Config { /// 既定の読み込み元: "db"(SQLite)または "dir"(md/txt ディレクトリ) @@ -19,6 +45,12 @@ pub struct Config { pub db: String, /// source: dir のときに開くディレクトリ(`:md` / `:sync` の既定でもある) pub dir: String, + /// BOX 一覧(未設定の場合は source/db/dir から自動生成) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub boxes: Vec, + /// 読み込んだ設定ファイルのパス(追記・保存用) + #[serde(skip)] + pub loaded_path: Option, } impl Default for Config { @@ -27,6 +59,8 @@ impl Default for Config { source: "db".to_string(), db: "~/.chira/ura.db".to_string(), dir: "~/.chira/md".to_string(), + boxes: Vec::new(), + loaded_path: None, } } } @@ -40,7 +74,8 @@ impl Config { }; if let Some(path) = path { if let Ok(text) = std::fs::read_to_string(&path) { - if let Ok(cfg) = serde_yaml::from_str::(&text) { + if let Ok(mut cfg) = serde_yaml::from_str::(&text) { + cfg.loaded_path = Some(path); return cfg; } } @@ -55,6 +90,54 @@ impl Config { pub fn dir_path(&self) -> PathBuf { expand(&self.dir) } + + /// 有効な BOX 一覧を返す。 + /// `boxes` が空なら後方互換として既存の source / db / dir から 1 つ生成する。 + pub fn effective_boxes(&self) -> Vec { + if !self.boxes.is_empty() { + return self.boxes.clone(); + } + let is_dir = self.source.eq_ignore_ascii_case("dir"); + vec![BoxConfig { + name: if is_dir { + "下書き".to_string() + } else { + "メモ".to_string() + }, + source: if is_dir { + "dir".to_string() + } else { + "db".to_string() + }, + db: if is_dir { None } else { Some(self.db.clone()) }, + dir: if is_dir { Some(self.dir.clone()) } else { None }, + }] + } + + /// 新しい BOX を設定に追加し、設定ファイルに保存する。 + pub fn add_box(&mut self, box_cfg: BoxConfig) -> anyhow::Result { + if self.boxes.is_empty() { + self.boxes = self.effective_boxes(); + } + self.boxes.push(box_cfg); + + let target_path = self.loaded_path.clone().unwrap_or_else(|| { + dirs::config_dir() + .map(|d| d.join("rum").join("config.yaml")) + .unwrap_or_else(|| PathBuf::from("rum.yaml")) + }); + + if let Some(parent) = target_path.parent() { + if !parent.as_os_str().is_empty() { + let _ = std::fs::create_dir_all(parent); + } + } + + let yaml = serde_yaml::to_string(self)?; + std::fs::write(&target_path, yaml)?; + self.loaded_path = Some(target_path.clone()); + Ok(target_path) + } } fn find_default_config() -> Option { @@ -195,6 +278,50 @@ mod tests { assert_eq!(cfg.dir, "/tmp/notes"); // 未指定は Default assert!(cfg.db.ends_with("ura.db")); + let boxes = cfg.effective_boxes(); + assert_eq!(boxes.len(), 1); + assert_eq!(boxes[0].name, "下書き"); + assert_eq!(boxes[0].source, "dir"); + } + + #[test] + fn yaml_parses_boxes() { + let yaml = r#" +boxes: + - name: メモ + source: db + db: ~/.chira/ura.db + - name: 下書き + source: dir + dir: ~/.chira/md +"#; + let cfg: Config = serde_yaml::from_str(yaml).unwrap(); + assert_eq!(cfg.boxes.len(), 2); + assert_eq!(cfg.boxes[0].name, "メモ"); + assert_eq!(cfg.boxes[0].source, "db"); + assert_eq!(cfg.boxes[1].name, "下書き"); + assert_eq!(cfg.boxes[1].source, "dir"); + } + + #[test] + fn add_box_persists_to_file() { + let tmp = std::env::temp_dir().join("rum_test_config.yaml"); + let mut cfg = Config { + loaded_path: Some(tmp.clone()), + ..Config::default() + }; + cfg.add_box(BoxConfig { + name: "新規箱".to_string(), + source: "dir".to_string(), + db: None, + dir: Some("/tmp/new_box".to_string()), + }) + .unwrap(); + + let loaded = Config::load(Some(tmp.to_str().unwrap())); + assert_eq!(loaded.boxes.len(), 2); + assert_eq!(loaded.boxes[1].name, "新規箱"); + let _ = std::fs::remove_file(tmp); } #[test] diff --git a/src/main.rs b/src/main.rs index b9af1d7..b1e7a25 100644 --- a/src/main.rs +++ b/src/main.rs @@ -151,7 +151,7 @@ fn main() -> Result<()> { }; let md_dir: PathBuf = cfg.dir_path(); - let mut app = App::new(source, md_dir)?; + let mut app = App::new_with_config(cfg, source, md_dir)?; enable_raw_mode()?; let mut stdout = io::stdout(); diff --git a/src/ui.rs b/src/ui.rs index e47244e..34fa13f 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,4 +1,5 @@ -use crate::app::{App, Mode, Source}; +use crate::app::{App, Mode, Pane, Source}; +use crate::buffer::MAX_SHEET_LINES; use ratatui::{ layout::{Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, @@ -11,7 +12,7 @@ pub fn render(frame: &mut Frame, app: &mut App) { let size = frame.area(); // Vertical layout: - // 0: Main editor area (Sidebar + Editor) + // 0: Main 3-pane area (BOX + 紙 + エディタ) // 1: Status line (1 row) // 2: Command/Search/Echo line (1 row) let chunks = Layout::default() @@ -27,23 +28,85 @@ pub fn render(frame: &mut Frame, app: &mut App) { let status_area = chunks[1]; let command_area = chunks[2]; - // Split main_area horizontally: Sidebar (22%) and Editor (78%) + // Split main_area horizontally into 3 panes: + // BOX (18%), 紙/シート (24%), エディタ (58%) let h_chunks = Layout::default() .direction(Direction::Horizontal) - .constraints([Constraint::Percentage(22), Constraint::Percentage(78)]) + .constraints([ + Constraint::Percentage(18), + Constraint::Percentage(24), + Constraint::Percentage(58), + ]) .split(main_area); - let sidebar_area = h_chunks[0]; - let editor_area = h_chunks[1]; + let box_area = h_chunks[0]; + let sheet_area = h_chunks[1]; + let editor_area = h_chunks[2]; - render_sidebar(frame, app, sidebar_area); + render_box_pane(frame, app, box_area); + render_sheet_pane(frame, app, sheet_area); render_editor(frame, app, editor_area); render_status(frame, app, status_area); render_command(frame, app, command_area); } -fn render_sidebar(frame: &mut Frame, app: &App, area: Rect) { - let (names, selected, title): (Vec, usize, String) = match &app.source { +fn render_box_pane(frame: &mut Frame, app: &App, area: Rect) { + let is_focused = app.focused_pane == Pane::Box; + let border_color = if is_focused { + Color::Yellow + } else { + Color::DarkGray + }; + + let items: Vec = app + .boxes + .iter() + .enumerate() + .map(|(i, b)| { + let is_selected = i == app.box_index; + let style = if is_selected { + Style::default() + .fg(if is_focused { + Color::Yellow + } else { + Color::Cyan + }) + .add_modifier(Modifier::BOLD) + } else { + Style::default().fg(Color::White) + }; + + let prefix = if is_selected { "▶ " } else { " " }; + let tag = format!("[{}] ", b.source); + ListItem::new(format!("{}{}{}", prefix, tag, b.name)).style(style) + }) + .collect(); + + let title = if is_focused { + format!(" [BOX ({})] ", app.boxes.len()) + } else { + format!(" BOX ({}) ", app.boxes.len()) + }; + + let list = List::new(items).block( + Block::default() + .borders(Borders::ALL) + .title(title) + .border_style(Style::default().fg(border_color)), + ); + + frame.render_widget(list, area); +} + +fn render_sheet_pane(frame: &mut Frame, app: &App, area: Rect) { + let is_focused = app.focused_pane == Pane::Sheet; + let border_color = if is_focused { + Color::Yellow + } else { + Color::DarkGray + }; + + let (names, selected, count_str): (Vec, usize, String) = match &app.source { Source::Dir(_) => ( app.files .iter() @@ -54,7 +117,7 @@ fn render_sidebar(frame: &mut Frame, app: &App, area: Rect) { }) .collect(), app.file_index, - format!(" Files ({}) ", app.files.len()), + format!("{}", app.files.len()), ), Source::Db(_) => ( app.notes @@ -68,7 +131,7 @@ fn render_sidebar(frame: &mut Frame, app: &App, area: Rect) { }) .collect(), app.note_index, - format!(" Notes ({}) ", app.notes.len()), + format!("{}", app.notes.len()), ), }; @@ -79,7 +142,11 @@ fn render_sidebar(frame: &mut Frame, app: &App, area: Rect) { let is_selected = i == selected; let style = if is_selected { Style::default() - .fg(Color::Yellow) + .fg(if is_focused { + Color::Yellow + } else { + Color::Cyan + }) .add_modifier(Modifier::BOLD) } else { Style::default().fg(Color::White) @@ -89,20 +156,55 @@ fn render_sidebar(frame: &mut Frame, app: &App, area: Rect) { ListItem::new(format!("{}{}", prefix, name)).style(style) }) .collect(); + + let title = if is_focused { + format!(" [紙 ({})] ", count_str) + } else { + format!(" 紙 ({}) ", count_str) + }; + let list = List::new(items).block( Block::default() .borders(Borders::ALL) .title(title) - .border_style(Style::default().fg(Color::Cyan)), + .border_style(Style::default().fg(border_color)), ); frame.render_widget(list, area); } fn render_editor(frame: &mut Frame, app: &mut App, area: Rect) { + let is_focused = app.focused_pane == Pane::Editor; + let border_color = if is_focused { + Color::Yellow + } else { + Color::Blue + }; + + let title = if is_focused { + format!( + " [エディタ (24行の紙{})] ", + if app.ura_enabled { + " / 裏写り:ON" + } else { + "" + } + ) + } else { + format!( + " エディタ (24行の紙{}) ", + if app.ura_enabled { + " / 裏写り:ON" + } else { + "" + } + ) + }; + let block = Block::default() .borders(Borders::ALL) - .border_style(Style::default().fg(Color::Blue)); + .title(title) + .border_style(Style::default().fg(border_color)); let inner_area = block.inner(area); frame.render_widget(block, area); @@ -111,7 +213,7 @@ fn render_editor(frame: &mut Frame, app: &mut App, area: Rect) { } let line_count = app.buffer.line_count(); - let line_num_width = format!("{}", line_count.max(1)).len() + 1; + let line_num_width = 3; // 行番号 1..24 // Adjust viewport vertical scroll let cursor_row = app.buffer.cursor.row; @@ -140,57 +242,98 @@ fn render_editor(frame: &mut Frame, app: &mut App, area: Rect) { for row_idx in 0..visible_rows { let actual_row = app.viewport_top + row_idx; - if actual_row < line_count { - let line_text = &app.buffer.lines[actual_row]; - let num_str = format!("{:>width$} ", actual_row + 1, width = line_num_width - 1); + if actual_row < MAX_SHEET_LINES { + let num_str = format!("{:>2} ", actual_row + 1); let mut spans = vec![Span::styled(num_str, Style::default().fg(Color::DarkGray))]; - // Colorize visual selection or search matches - if let Some((v_start, v_end)) = visual_range { - if actual_row >= v_start.row && actual_row <= v_end.row { - let chars: Vec = line_text.chars().collect(); - let sel_start = if actual_row == v_start.row { - v_start.col - } else { - 0 - }; - let sel_end = if actual_row == v_end.row { - v_end.col - } else { - chars.len().saturating_sub(1) - }; - - let before: String = chars[..sel_start.min(chars.len())].iter().collect(); - let selected: String = if sel_start <= sel_end && sel_start < chars.len() { - chars[sel_start..=sel_end.min(chars.len() - 1)] - .iter() - .collect() - } else { - String::new() - }; - let after: String = if sel_end + 1 < chars.len() { - chars[sel_end + 1..].iter().collect() - } else { - String::new() - }; + if actual_row < line_count { + let line_text = &app.buffer.lines[actual_row]; + + // Check for bleed-through (裏写り): + // 「現在の紙の空行にだけ、直前の紙(前の面)の行を淡く重ねる。入力の邪魔をしない(非空行には出さない)」 + let is_empty_line = line_text.trim().is_empty(); + let bleed_through = if app.ura_enabled && is_empty_line { + app.prev_doc_lines + .as_ref() + .and_then(|lines| lines.get(actual_row)) + .filter(|s| !s.trim().is_empty()) + } else { + None + }; - spans.push(Span::raw(before)); + if let Some(bleed_text) = bleed_through { + // うっすら透ける淡い演出(DarkGray / Faint) spans.push(Span::styled( - selected, - Style::default().bg(Color::DarkGray).fg(Color::White), + bleed_text.clone(), + Style::default() + .fg(Color::Rgb(80, 80, 80)) + .add_modifier(Modifier::DIM), )); - spans.push(Span::raw(after)); + } else if let Some((v_start, v_end)) = visual_range { + // Visual selection + if actual_row >= v_start.row && actual_row <= v_end.row { + let chars: Vec = line_text.chars().collect(); + let sel_start = if actual_row == v_start.row { + v_start.col + } else { + 0 + }; + let sel_end = if actual_row == v_end.row { + v_end.col + } else { + chars.len().saturating_sub(1) + }; + + let before: String = chars[..sel_start.min(chars.len())].iter().collect(); + let selected: String = if sel_start <= sel_end && sel_start < chars.len() { + chars[sel_start..=sel_end.min(chars.len() - 1)] + .iter() + .collect() + } else { + String::new() + }; + let after: String = if sel_end + 1 < chars.len() { + chars[sel_end + 1..].iter().collect() + } else { + String::new() + }; + + spans.push(Span::raw(before)); + spans.push(Span::styled( + selected, + Style::default().bg(Color::DarkGray).fg(Color::White), + )); + spans.push(Span::raw(after)); + } else { + spans.push(Span::raw(line_text.clone())); + } } else { spans.push(Span::raw(line_text.clone())); } } else { - spans.push(Span::raw(line_text.clone())); + // Within 24 lines of sheet, but empty after current buffer lines + let bleed_through = if app.ura_enabled { + app.prev_doc_lines + .as_ref() + .and_then(|lines| lines.get(actual_row)) + .filter(|s| !s.trim().is_empty()) + } else { + None + }; + if let Some(bleed_text) = bleed_through { + spans.push(Span::styled( + bleed_text.clone(), + Style::default() + .fg(Color::Rgb(80, 80, 80)) + .add_modifier(Modifier::DIM), + )); + } } lines_to_render.push(Line::from(spans)); } else { - // Tilde for lines past EOF + // Lines past 24: sheet boundary, show ~ lines_to_render.push(Line::from(vec![Span::styled( "~", Style::default().fg(Color::DarkGray), @@ -202,7 +345,9 @@ fn render_editor(frame: &mut Frame, app: &mut App, area: Rect) { frame.render_widget(paragraph, inner_area); // Set cursor position in editor - if app.mode == Mode::Normal || app.mode == Mode::Insert || app.mode == Mode::Visual { + if is_focused + && (app.mode == Mode::Normal || app.mode == Mode::Insert || app.mode == Mode::Visual) + { let cursor_screen_y = inner_area.y + (cursor_row - app.viewport_top) as u16; let visual_col = app.buffer.visual_col(4); let cursor_screen_x = inner_area.x + line_num_width as u16 + visual_col as u16; @@ -257,7 +402,17 @@ fn render_status(frame: &mut Frame, app: &App, area: Rect) { String::new() }; - let left = format!(" {} {}{}{}", mode_str, file_name, mod_flag, fm_info); + let box_info = app + .boxes + .get(app.box_index) + .map(|b| format!(" [{}]", b.name)) + .unwrap_or_default(); + let ura_info = if app.ura_enabled { " [ura]" } else { "" }; + + let left = format!( + " {} {}{}{}{}{}", + mode_str, file_name, mod_flag, box_info, ura_info, fm_info + ); let spaces = area .width