diff options
| author | historia <[not public]> | 2026-06-29 04:03:38 -0400 |
|---|---|---|
| committer | historia <[not public]> | 2026-06-29 04:03:38 -0400 |
| commit | ba34490aaed5f7c242c2b0453130fefc07d0d5d0 (patch) | |
| tree | db5818757d5080221494cead1c7e61a576d1cb65 /internal | |
| parent | b1e252c996a6332d391f96624a7d6f149eb097c4 (diff) | |
| download | tui-ascii-mapper-main.tar.gz | |
Diffstat (limited to 'internal')
| -rw-r--r-- | internal/config/config.go | 135 | ||||
| -rw-r--r-- | internal/mapio/mapio.go | 212 | ||||
| -rw-r--r-- | internal/model/enums.go | 81 | ||||
| -rw-r--r-- | internal/model/map.go | 99 | ||||
| -rw-r--r-- | internal/model/model_test.go | 99 | ||||
| -rw-r--r-- | internal/model/terrain.go | 43 | ||||
| -rw-r--r-- | internal/model/undo.go | 42 | ||||
| -rw-r--r-- | internal/tools/tools.go | 327 | ||||
| -rw-r--r-- | internal/tools/tools_test.go | 36 | ||||
| -rw-r--r-- | internal/tui/app.go | 155 | ||||
| -rw-r--r-- | internal/tui/colorpicker.go | 180 | ||||
| -rw-r--r-- | internal/tui/dialogs.go | 526 | ||||
| -rw-r--r-- | internal/tui/handlers.go | 501 | ||||
| -rw-r--r-- | internal/tui/render.go | 465 | ||||
| -rw-r--r-- | internal/tui/update.go | 296 | ||||
| -rw-r--r-- | internal/tui/view.go | 142 |
16 files changed, 3339 insertions, 0 deletions
diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..cafa82f --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,135 @@ +package config + +import ( + "os" + "path/filepath" + + "tui-ascii-mapper/internal/model" + + "gopkg.in/yaml.v3" +) + +type ConfigKeybindings struct { + Quit string `yaml:"quit"` + Save string `yaml:"save"` + Undo string `yaml:"undo"` + Redo string `yaml:"redo"` + UnicodeToggle string `yaml:"unicode_toggle"` + ColorToggle string `yaml:"color_toggle"` + FillToggle string `yaml:"fill_toggle"` + Resize string `yaml:"resize"` + DrillDown string `yaml:"drill_down"` + DrillUp string `yaml:"drill_up"` + DeleteSubmap string `yaml:"delete_submap"` +} + +type Config struct { + Symbols []model.Terrain `yaml:"symbols"` + Keybindings ConfigKeybindings `yaml:"keybindings"` + SubmapBg string `yaml:"submap_bg"` + DefaultMapWidth int `yaml:"default_map_width"` + DefaultMapHeight int `yaml:"default_map_height"` +} + +func DefaultConfig() Config { + return Config{ + SubmapBg: "236", + DefaultMapWidth: 80, + DefaultMapHeight: 25, + Keybindings: ConfigKeybindings{ + Quit: "q", + Save: "s", + Undo: "u", + Redo: "r", + UnicodeToggle: "U", + ColorToggle: "C", + FillToggle: "F", + Resize: "R", + DrillDown: "enter", + DrillUp: "esc", + DeleteSubmap: "D", + }, + Symbols: []model.Terrain{ + {Name: "water", Symbol: "≋", ASCII: "~", Colors: []model.TerrainColor{{Color: "21", Weight: 30}, {Color: "27", Weight: 30}, {Color: "33", Weight: 20}, {Color: "39", Weight: 20}}}, + {Name: "mountains", Symbol: "▲", ASCII: "^", Colors: []model.TerrainColor{{Color: "243", Weight: 40}, {Color: "247", Weight: 30}, {Color: "250", Weight: 30}}}, + {Name: "crater", Symbol: "▼", ASCII: "v", Colors: []model.TerrainColor{{Color: "243", Weight: 40}, {Color: "247", Weight: 30}, {Color: "250", Weight: 30}}}, + {Name: "plains", Symbol: "≡", ASCII: "=", Colors: []model.TerrainColor{{Color: "106", Weight: 30}, {Color: "70", Weight: 25}, {Color: "64", Weight: 25}, {Color: "71", Weight: 20}}}, + {Name: "trees", Symbol: "♣", ASCII: "#", Colors: []model.TerrainColor{{Color: "28", Weight: 30}, {Color: "34", Weight: 25}, {Color: "22", Weight: 25}, {Color: "29", Weight: 20}}}, + {Name: "settlement", Symbol: "⌂", ASCII: "@", Colors: []model.TerrainColor{{Color: "130", Weight: 40}, {Color: "136", Weight: 30}, {Color: "94", Weight: 30}}}, + {Name: "outpost", Symbol: "◈", ASCII: "&", Colors: []model.TerrainColor{{Color: "172", Weight: 40}, {Color: "166", Weight: 30}, {Color: "130", Weight: 30}}}, + {Name: "road", Symbol: "·", ASCII: ".", Colors: []model.TerrainColor{{Color: "244", Weight: 40}, {Color: "242", Weight: 30}, {Color: "246", Weight: 30}}}, + {Name: "desert", Symbol: "░", ASCII: "_", Colors: []model.TerrainColor{{Color: "178", Weight: 30}, {Color: "180", Weight: 25}, {Color: "222", Weight: 25}, {Color: "179", Weight: 20}}}, + {Name: "snow", Symbol: "❄", ASCII: "*", Colors: []model.TerrainColor{{Color: "255", Weight: 40}, {Color: "254", Weight: 30}, {Color: "250", Weight: 30}}}, + {Name: "swamp", Symbol: "≈", ASCII: "%", Colors: []model.TerrainColor{{Color: "64", Weight: 30}, {Color: "65", Weight: 25}, {Color: "58", Weight: 25}, {Color: "107", Weight: 20}}}, + {Name: "cave", Symbol: "◌", ASCII: "n", Colors: []model.TerrainColor{{Color: "237", Weight: 40}, {Color: "235", Weight: 30}, {Color: "239", Weight: 30}}}, + {Name: "wall", Symbol: "█", ASCII: "|", Colors: []model.TerrainColor{{Color: "240", Weight: 40}, {Color: "238", Weight: 30}, {Color: "242", Weight: 30}}}, + {Name: "bridge", Symbol: "▬", ASCII: "-", Colors: []model.TerrainColor{{Color: "94", Weight: 40}, {Color: "130", Weight: 30}, {Color: "136", Weight: 30}}}, + {Name: "lava", Symbol: "▓", ASCII: "L", Colors: []model.TerrainColor{{Color: "196", Weight: 30}, {Color: "202", Weight: 25}, {Color: "208", Weight: 25}, {Color: "124", Weight: 20}}}, + {Name: "ice", Symbol: "▩", ASCII: "I", Colors: []model.TerrainColor{{Color: "51", Weight: 40}, {Color: "45", Weight: 30}, {Color: "50", Weight: 30}}}, + {Name: "ruins", Symbol: "▣", ASCII: "r", Colors: []model.TerrainColor{{Color: "244", Weight: 35}, {Color: "240", Weight: 35}, {Color: "243", Weight: 30}}}, + {Name: "farmland", Symbol: "▤", ASCII: "f", Colors: []model.TerrainColor{{Color: "142", Weight: 35}, {Color: "143", Weight: 35}, {Color: "106", Weight: 30}}}, + {Name: "tower", Symbol: "◬", ASCII: "T", Colors: []model.TerrainColor{{Color: "220", Weight: 40}, {Color: "214", Weight: 30}, {Color: "222", Weight: 30}}}, + {Name: "castle", Symbol: "♜", ASCII: "C", Colors: []model.TerrainColor{{Color: "248", Weight: 35}, {Color: "244", Weight: 35}, {Color: "136", Weight: 30}}}, + {Name: "coast", Symbol: "∼", ASCII: "s", Colors: []model.TerrainColor{{Color: "33", Weight: 35}, {Color: "39", Weight: 35}, {Color: "27", Weight: 30}}}, + {Name: "village", Symbol: "◉", ASCII: "o", Colors: []model.TerrainColor{{Color: "208", Weight: 35}, {Color: "172", Weight: 35}, {Color: "166", Weight: 30}}}, + {Name: "graveyard", Symbol: "☠", ASCII: "y", Colors: []model.TerrainColor{{Color: "238", Weight: 40}, {Color: "240", Weight: 30}, {Color: "242", Weight: 30}}}, + {Name: "tavern", Symbol: "♨", ASCII: "a", Colors: []model.TerrainColor{{Color: "130", Weight: 35}, {Color: "94", Weight: 35}, {Color: "131", Weight: 30}}}, + {Name: "dungeon", Symbol: "◎", ASCII: "d", Colors: []model.TerrainColor{{Color: "239", Weight: 40}, {Color: "237", Weight: 30}, {Color: "241", Weight: 30}}}, + {Name: "forest", Symbol: "♠", ASCII: "F", Colors: []model.TerrainColor{{Color: "28", Weight: 30}, {Color: "64", Weight: 25}, {Color: "22", Weight: 25}, {Color: "35", Weight: 20}}}, + {Name: "shrine", Symbol: "✞", ASCII: "h", Colors: []model.TerrainColor{{Color: "220", Weight: 35}, {Color: "214", Weight: 35}, {Color: "178", Weight: 30}}}, + {Name: "crypt", Symbol: "▦", ASCII: "x", Colors: []model.TerrainColor{{Color: "236", Weight: 40}, {Color: "238", Weight: 30}, {Color: "240", Weight: 30}}}, + {Name: "rift", Symbol: "⚡", ASCII: "i", Colors: []model.TerrainColor{{Color: "129", Weight: 35}, {Color: "93", Weight: 35}, {Color: "201", Weight: 30}}}, + {Name: "oasis", Symbol: "◯", ASCII: "b", Colors: []model.TerrainColor{{Color: "51", Weight: 35}, {Color: "33", Weight: 35}, {Color: "39", Weight: 30}}}, + {Name: "citadel", Symbol: "◘", ASCII: "V", Colors: []model.TerrainColor{{Color: "250", Weight: 35}, {Color: "248", Weight: 35}, {Color: "253", Weight: 30}}}, + {Name: "flowers", Symbol: "⚘", ASCII: "f", Colors: []model.TerrainColor{{Color: "169", Weight: 35}, {Color: "133", Weight: 35}, {Color: "170", Weight: 30}}}, + {Name: "wall/road", Symbol: "═", ASCII: "=", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "║", ASCII: "|", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╔", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╗", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╚", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╝", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╠", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╣", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╦", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╩", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + {Name: "wall/road", Symbol: "╬", ASCII: "+", Colors: []model.TerrainColor{{Color: "243", Weight: 100}}}, + }, + } +} + +func findConfigFile() string { + exe, err := os.Executable() + if err == nil { + dir := filepath.Dir(exe) + p := filepath.Join(dir, "config.yaml") + if _, err := os.Stat(p); err == nil { + return p + } + } + cfgDir := os.Getenv("XDG_CONFIG_HOME") + if cfgDir == "" { + home, _ := os.UserHomeDir() + cfgDir = filepath.Join(home, ".config") + } + p := filepath.Join(cfgDir, "tui-ascii-mapper", "config.yaml") + if _, err := os.Stat(p); err == nil { + return p + } + return "" +} + +func LoadConfig() Config { + path := findConfigFile() + if path == "" { + return DefaultConfig() + } + data, err := os.ReadFile(path) + if err != nil { + return DefaultConfig() + } + var cfg Config + if err := yaml.Unmarshal(data, &cfg); err != nil { + return DefaultConfig() + } + return cfg +} diff --git a/internal/mapio/mapio.go b/internal/mapio/mapio.go new file mode 100644 index 0000000..58a8848 --- /dev/null +++ b/internal/mapio/mapio.go @@ -0,0 +1,212 @@ +package mapio + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + + "tui-ascii-mapper/internal/model" + "tui-ascii-mapper/internal/tools" + + "gopkg.in/yaml.v3" +) + +type SaveData struct { + Name string `yaml:"name"` + Width int `yaml:"width"` + Height int `yaml:"height"` + Palette []model.Terrain `yaml:"palette"` + GridBody string `yaml:"grid_body,omitempty"` + GridColors []string `yaml:"grid_colors,omitempty"` + TextLabels []model.TextLabel `yaml:"text_labels,omitempty"` + Submaps []SubmapRef `yaml:"submaps,omitempty"` +} + +type SubmapRef struct { + X int `yaml:"x"` + Y int `yaml:"y"` + Data SaveData `yaml:"data"` +} + +func SerializeMap(m *model.Map, path string) error { + data := buildSaveData(m) + + yamlBytes, err := yaml.Marshal(data) + if err != nil { + return err + } + + var buf bytes.Buffer + buf.WriteString("---\n") + buf.Write(yamlBytes) + buf.WriteString("...\n") + + for _, row := range m.Grid { + for _, cell := range row { + if cell.Terrain < 0 || cell.Terrain >= len(m.Palette) { + buf.WriteByte(' ') + } else { + buf.WriteString(m.Palette[cell.Terrain].ASCII) + } + } + buf.WriteByte('\n') + } + + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + return os.WriteFile(path, buf.Bytes(), 0644) +} + +func buildSaveData(m *model.Map) SaveData { + sd := SaveData{ + Name: m.Name, + Width: m.Width, + Height: m.Height, + Palette: m.Palette, + } + var gb strings.Builder + for _, row := range m.Grid { + for _, cell := range row { + if cell.Terrain < 0 || cell.Terrain >= len(m.Palette) { + gb.WriteByte(' ') + } else { + gb.WriteString(m.Palette[cell.Terrain].ASCII) + } + } + gb.WriteByte('\n') + } + if m.Parent != nil { + sd.GridBody = gb.String() + } + + for y := range m.Grid { + for x := range m.Grid[y] { + c := m.Grid[y][x] + if c.Color != "" { + sd.GridColors = append(sd.GridColors, fmt.Sprintf("%d,%d,%s", x, y, c.Color)) + } + } + } + for _, tl := range m.TextLabels { + sd.TextLabels = append(sd.TextLabels, tl) + } + for pt, sub := range m.Submaps { + sd.Submaps = append(sd.Submaps, SubmapRef{ + X: pt.X, Y: pt.Y, + Data: buildSaveData(sub), + }) + } + return sd +} + +func DeserializeMap(path string) (*model.Map, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + content := string(data) + + if !strings.HasPrefix(content, "---\n") { + return nil, fmt.Errorf("invalid save file: missing YAML header") + } + + endIdx := strings.Index(content, "\n...\n") + if endIdx < 0 { + return nil, fmt.Errorf("invalid save file: missing ... terminator") + } + + yamlPart := content[4:endIdx] + gridPart := content[endIdx+5:] + + var sd SaveData + if err := yaml.Unmarshal([]byte(yamlPart), &sd); err != nil { + return nil, fmt.Errorf("invalid YAML header: %w", err) + } + + m := model.NewMap(sd.Name, sd.Width, sd.Height, sd.Palette) + m.Filename = path + + for _, entry := range sd.GridColors { + var x, y int + var c string + if n, _ := fmt.Sscanf(entry, "%d,%d,%s", &x, &y, &c); n == 3 { + if y >= 0 && y < m.Height && x >= 0 && x < m.Width { + m.Grid[y][x].Color = c + } + } + } + + lines := strings.Split(strings.TrimRight(gridPart, "\n"), "\n") + for y, line := range lines { + if y >= m.Height { + break + } + for x, ch := range line { + if x >= m.Width { + break + } + for i, t := range m.Palette { + if string(ch) == t.ASCII { + m.Grid[y][x].Terrain = i + break + } + } + } + } + + for _, tl := range sd.TextLabels { + tools.PlaceTextLabel(m, tl.Start, tl.Text, tl.Color) + } + + for _, sr := range sd.Submaps { + sub := restoreMap(&sr.Data, m) + m.Submaps[model.Point{X: sr.X, Y: sr.Y}] = sub + } + + return m, nil +} + +func restoreMap(sd *SaveData, parent *model.Map) *model.Map { + m := model.NewMap(sd.Name, sd.Width, sd.Height, sd.Palette) + m.Parent = parent + for _, entry := range sd.GridColors { + var x, y int + var c string + if n, _ := fmt.Sscanf(entry, "%d,%d,%s", &x, &y, &c); n == 3 { + if y >= 0 && y < m.Height && x >= 0 && x < m.Width { + m.Grid[y][x].Color = c + } + } + } + if sd.GridBody != "" { + lines := strings.Split(strings.TrimRight(sd.GridBody, "\n"), "\n") + for y, line := range lines { + if y >= m.Height { + break + } + for x, ch := range line { + if x >= m.Width { + break + } + for i, t := range m.Palette { + if string(ch) == t.ASCII { + m.Grid[y][x].Terrain = i + break + } + } + } + } + } + for _, tl := range sd.TextLabels { + tools.PlaceTextLabel(m, tl.Start, tl.Text, tl.Color) + } + for _, sr := range sd.Submaps { + sub := restoreMap(&sr.Data, m) + m.Submaps[model.Point{X: sr.X, Y: sr.Y}] = sub + } + return m +} diff --git a/internal/model/enums.go b/internal/model/enums.go new file mode 100644 index 0000000..a29cf84 --- /dev/null +++ b/internal/model/enums.go @@ -0,0 +1,81 @@ +package model + +type Tool int + +const ( + ToolBrush Tool = iota + ToolSelect + ToolErase + ToolFill + ToolLine + ToolRect + ToolCircle + ToolText +) + +func (t Tool) String() string { + switch t { + case ToolBrush: + return "Brush" + case ToolSelect: + return "Select" + case ToolErase: + return "Erase" + case ToolFill: + return "Fill" + case ToolLine: + return "Line" + case ToolRect: + return "Rectangle" + case ToolCircle: + return "Circle" + case ToolText: + return "Text" + } + return "" +} + +type Mode int + +const ( + ModeNormal Mode = iota + ModeDialog + ModeLinePreview + ModeRectPreview + ModeCirclePreview + ModeTextEdit +) + +type DialogType int + +const ( + DialogNone DialogType = iota + DialogSaveAs + DialogOpenMap + DialogResize + DialogQuitConfirm + DialogDeleteSubmapConfirm + DialogRenameSymbol + DialogRenameMap + DialogFileSave + DialogFileOpen +) + +func Clamp(v, lo, hi int) int { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} + +func ContainsInt(s []int, v int) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} diff --git a/internal/model/map.go b/internal/model/map.go new file mode 100644 index 0000000..de19660 --- /dev/null +++ b/internal/model/map.go @@ -0,0 +1,99 @@ +package model + +type Point struct{ X, Y int } + +type Cell struct { + Terrain int `yaml:"t"` + Color string `yaml:"c,omitempty"` + Text string `yaml:"x,omitempty"` +} + +type TextLabel struct { + Text string `yaml:"text"` + Start Point `yaml:"start"` + Color string `yaml:"color,omitempty"` +} + +type Map struct { + Name string `yaml:"name"` + Width int `yaml:"width"` + Height int `yaml:"height"` + Grid [][]Cell `yaml:"-"` + Palette []Terrain `yaml:"palette"` + TextLabels []TextLabel `yaml:"text_labels,omitempty"` + Submaps map[Point]*Map `yaml:"-"` + Parent *Map `yaml:"-"` + Filename string `yaml:"-"` +} + +func NewMap(name string, w, h int, palette []Terrain) *Map { + grid := make([][]Cell, h) + for y := range grid { + grid[y] = make([]Cell, w) + for x := range grid[y] { + grid[y][x].Terrain = -1 + } + } + return &Map{ + Name: name, + Width: w, + Height: h, + Grid: grid, + Palette: palette, + Submaps: make(map[Point]*Map), + } +} + +func (m *Map) Clone() *Map { + grid := make([][]Cell, m.Height) + for y := range grid { + grid[y] = make([]Cell, m.Width) + copy(grid[y], m.Grid[y]) + } + c := &Map{ + Name: m.Name, + Width: m.Width, + Height: m.Height, + Grid: grid, + Palette: m.Palette, + Submaps: make(map[Point]*Map), + Parent: m.Parent, + } + for _, tl := range m.TextLabels { + c.TextLabels = append(c.TextLabels, tl) + } + for pt, sub := range m.Submaps { + c.Submaps[pt] = sub + } + return c +} + +func (m *Map) InBounds(p Point) bool { + return p.X >= 0 && p.X < m.Width && p.Y >= 0 && p.Y < m.Height +} + +func (m *Map) SetCell(p Point, terrain int, color ...string) { + if !m.InBounds(p) { + return + } + text := m.Grid[p.Y][p.X].Text + clr := "" + if len(color) > 0 { + clr = color[0] + } + m.Grid[p.Y][p.X] = Cell{Terrain: terrain, Color: clr, Text: text} +} + +func (m *Map) SetText(p Point, text string) { + if !m.InBounds(p) { + return + } + m.Grid[p.Y][p.X].Text = text +} + +func (m *Map) CellAt(p Point) Cell { + if !m.InBounds(p) { + return Cell{Terrain: -1} + } + return m.Grid[p.Y][p.X] +} diff --git a/internal/model/model_test.go b/internal/model/model_test.go new file mode 100644 index 0000000..8e4ee63 --- /dev/null +++ b/internal/model/model_test.go @@ -0,0 +1,99 @@ +package model + +import "testing" + +func TestNewMap(t *testing.T) { + m := NewMap("test", 10, 5, nil) + if m.Width != 10 || m.Height != 5 { + t.Fatalf("NewMap size: got %dx%d", m.Width, m.Height) + } + if m.Grid[0][0].Terrain != -1 { + t.Fatal("NewMap: grid not initialized to -1") + } + if len(m.Grid) != 5 || len(m.Grid[0]) != 10 { + t.Fatal("NewMap: grid dimensions wrong") + } +} + +func TestClone(t *testing.T) { + m := NewMap("test", 10, 5, nil) + m2 := m.Clone() + m2.Grid[0][0].Terrain = 0 + if m.Grid[0][0].Terrain != -1 { + t.Fatal("Clone shares data") + } +} + +func TestInBounds(t *testing.T) { + m := NewMap("test", 10, 5, nil) + if !m.InBounds(Point{X: 0, Y: 0}) { + t.Fatal("InBounds(0,0) should be true") + } + if m.InBounds(Point{X: -1, Y: 0}) { + t.Fatal("InBounds(-1,0) should be false") + } + if m.InBounds(Point{X: 0, Y: 5}) { + t.Fatal("InBounds(0,5) should be false") + } + if m.InBounds(Point{X: 10, Y: 0}) { + t.Fatal("InBounds(10,0) should be false") + } +} + +func TestSetGetCell(t *testing.T) { + m := NewMap("test", 10, 5, nil) + m.SetCell(Point{X: 1, Y: 2}, 5, "red") + c := m.CellAt(Point{X: 1, Y: 2}) + if c.Terrain != 5 || c.Color != "red" { + t.Fatalf("SetCell/GetCell: got %d,%s", c.Terrain, c.Color) + } +} + +func TestUndoStack(t *testing.T) { + u := &UndoStack{} + m := NewMap("test", 3, 3, nil) + u.Push(m) + m.SetCell(Point{X: 1, Y: 1}, 2, "green") + u.Push(m) + m.SetCell(Point{X: 2, Y: 2}, 3, "blue") + + if entry := u.Undo(); entry != nil { + *entry.Target = *entry.State + } + if m.CellAt(Point{X: 2, Y: 2}).Terrain != -1 { + t.Fatal("Undo failed") + } +} + +func TestClamp(t *testing.T) { + if Clamp(5, 0, 10) != 5 { + t.Fatal("Clamp middle") + } + if Clamp(-1, 0, 10) != 0 { + t.Fatal("Clamp low") + } + if Clamp(11, 0, 10) != 10 { + t.Fatal("Clamp high") + } +} + +func TestPickColor(t *testing.T) { + tc := Terrain{Colors: []TerrainColor{{Color: "22", Weight: 100}}} + if tc.PickColor() != "22" { + t.Fatal("PickColor single failed") + } + tc2 := Terrain{} + if tc2.PickColor() != "0" { + t.Fatal("PickColor empty failed") + } +} + +func TestTerrainSymbol(t *testing.T) { + tr := Terrain{Symbol: "X", ASCII: "x"} + if tr.GetSymbol(true) != "X" { + t.Fatal("Unicode symbol") + } + if tr.GetSymbol(false) != "x" { + t.Fatal("ASCII symbol") + } +} diff --git a/internal/model/terrain.go b/internal/model/terrain.go new file mode 100644 index 0000000..7772620 --- /dev/null +++ b/internal/model/terrain.go @@ -0,0 +1,43 @@ +package model + +import "math/rand" + +type TerrainColor struct { + Color string `yaml:"color"` + Weight int `yaml:"weight"` +} + +type Terrain struct { + Name string `yaml:"name"` + Symbol string `yaml:"symbol"` + ASCII string `yaml:"ascii"` + Colors []TerrainColor `yaml:"colors"` +} + +func (t Terrain) GetSymbol(unicode bool) string { + if unicode { + return t.Symbol + } + return t.ASCII +} + +func (t Terrain) PickColor() string { + if len(t.Colors) == 0 { + return "0" + } + if len(t.Colors) == 1 { + return t.Colors[0].Color + } + total := 0 + for _, c := range t.Colors { + total += c.Weight + } + r := rand.Intn(total) + for _, c := range t.Colors { + r -= c.Weight + if r < 0 { + return c.Color + } + } + return t.Colors[0].Color +} diff --git a/internal/model/undo.go b/internal/model/undo.go new file mode 100644 index 0000000..5b0297b --- /dev/null +++ b/internal/model/undo.go @@ -0,0 +1,42 @@ +package model + +type UndoStack struct { + states []Entry + pos int +} + +type Entry struct { + Target *Map + State *Map +} + +func (u *UndoStack) Push(target *Map) { + keep := u.pos + 1 + if keep > len(u.states) { + keep = len(u.states) + } + u.states = append(u.states[:keep], Entry{Target: target, State: target.Clone()}) + u.pos = len(u.states) - 1 + if len(u.states) > 100 { + u.states = u.states[1:] + u.pos-- + } +} + +func (u *UndoStack) Undo() *Entry { + if u.pos <= 0 { + return nil + } + u.pos-- + return &u.states[u.pos] +} + +func (u *UndoStack) Redo() *Entry { + if u.pos >= len(u.states)-1 { + return nil + } + u.pos++ + return &u.states[u.pos] +} + +func (u *UndoStack) Pos() int { return u.pos } diff --git a/internal/tools/tools.go b/internal/tools/tools.go new file mode 100644 index 0000000..77b9f27 --- /dev/null +++ b/internal/tools/tools.go @@ -0,0 +1,327 @@ +package tools + +import "tui-ascii-mapper/internal/model" + +func Brush(m *model.Map, center model.Point, terrain int, size int, palette []model.Terrain) { + half := size / 2 + for dy := -half; dy <= half; dy++ { + for dx := -half; dx <= half; dx++ { + color := "" + if terrain >= 0 && terrain < len(palette) { + color = palette[terrain].PickColor() + } + m.SetCell(model.Point{X: center.X + dx, Y: center.Y + dy}, terrain, color) + } + } +} + +func ThickenPoints(pts []model.Point, size int) []model.Point { + if size <= 1 { + return pts + } + half := size / 2 + seen := make(map[model.Point]bool) + var result []model.Point + for _, p := range pts { + for dy := -half; dy <= half; dy++ { + for dx := -half; dx <= half; dx++ { + np := model.Point{X: p.X + dx, Y: p.Y + dy} + if !seen[np] { + seen[np] = true + result = append(result, np) + } + } + } + } + return result +} + +func FloodFill(m *model.Map, start model.Point, terrain int, palette []model.Terrain) { + if !m.InBounds(start) { + return + } + target := m.CellAt(start).Terrain + if target == terrain { + return + } + color := "" + if terrain >= 0 && terrain < len(palette) { + color = palette[terrain].PickColor() + } + type pt struct{ x, y int } + stack := []pt{{start.X, start.Y}} + visited := make([][]bool, m.Height) + for i := range visited { + visited[i] = make([]bool, m.Width) + } + for len(stack) > 0 { + p := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if !m.InBounds(model.Point{X: p.x, Y: p.y}) || visited[p.y][p.x] { + continue + } + if m.Grid[p.y][p.x].Terrain != target { + continue + } + visited[p.y][p.x] = true + m.SetCell(model.Point{X: p.x, Y: p.y}, terrain, color) + stack = append(stack, pt{p.x + 1, p.y}, pt{p.x - 1, p.y}, pt{p.x, p.y + 1}, pt{p.x, p.y - 1}) + } +} + +func BresenhamLine(a, b model.Point) []model.Point { + var pts []model.Point + x0, y0 := a.X, a.Y + x1, y1 := b.X, b.Y + dx := iabs(x1 - x0) + dy := -iabs(y1 - y0) + sx, sy := 1, 1 + if x0 > x1 { + sx = -1 + } + if y0 > y1 { + sy = -1 + } + err := dx + dy + for { + pts = append(pts, model.Point{X: x0, Y: y0}) + if x0 == x1 && y0 == y1 { + break + } + e2 := 2 * err + if e2 >= dy { + err += dy + x0 += sx + } + if e2 <= dx { + err += dx + y0 += sy + } + } + return pts +} + +func iabs(x int) int { + if x < 0 { + return -x + } + return x +} + +func DrawRect(a, b model.Point, filled bool) []model.Point { + x0, x1 := a.X, b.X + y0, y1 := a.Y, b.Y + if x0 > x1 { + x0, x1 = x1, x0 + } + if y0 > y1 { + y0, y1 = y1, y0 + } + var pts []model.Point + if filled { + for y := y0; y <= y1; y++ { + for x := x0; x <= x1; x++ { + pts = append(pts, model.Point{X: x, Y: y}) + } + } + return pts + } + for x := x0; x <= x1; x++ { + pts = append(pts, model.Point{X: x, Y: y0}, model.Point{X: x, Y: y1}) + } + for y := y0 + 1; y < y1; y++ { + pts = append(pts, model.Point{X: x0, Y: y}, model.Point{X: x1, Y: y}) + } + return pts +} + +func DrawCircle(center, edge model.Point, filled bool) []model.Point { + r2 := (edge.X-center.X)*(edge.X-center.X) + (edge.Y-center.Y)*(edge.Y-center.Y) + r := r2 + if r < 0 { + return nil + } + radius := IntSqrt(r) + var pts []model.Point + for dy := -radius; dy <= radius; dy++ { + for dx := -radius; dx <= radius; dx++ { + dist2 := dx*dx + dy*dy + if filled { + if dist2 <= r { + pts = append(pts, model.Point{X: center.X + dx, Y: center.Y + dy}) + } + } else { + if dist2 <= r && dist2 > (radius-1)*(radius-1) { + pts = append(pts, model.Point{X: center.X + dx, Y: center.Y + dy}) + } + } + } + } + return pts +} + +func DrawOval(f1, f2 model.Point, filled bool) []model.Point { + dx := f2.X - f1.X + dy := f2.Y - f1.Y + dist := IntSqrt(dx*dx + dy*dy) + if dist == 0 { + return nil + } + a := dist * 3 / 2 + if a < 1 { + a = 1 + } + a2 := a * a + c2 := dist * dist / 4 + b2 := a2 - c2 + if b2 < 0 { + b2 = 0 + } + + cx := (f1.X + f2.X) / 2 + cy := (f1.Y + f2.Y) / 2 + + minX := cx - a - 1 + maxX := cx + a + 1 + minY := cy - a - 1 + maxY := cy + a + 1 + + var pts []model.Point + for py := minY; py <= maxY; py++ { + for px := minX; px <= maxX; px++ { + d1 := distSq(px, py, f1.X, f1.Y) + d2 := distSq(px, py, f2.X, f2.Y) + sum := IntSqrt(d1) + IntSqrt(d2) + + if filled { + if sum <= 2*a { + pts = append(pts, model.Point{X: px, Y: py}) + } + } else { + if sum >= 2*a-1 && sum <= 2*a+1 { + pts = append(pts, model.Point{X: px, Y: py}) + } + } + } + } + return pts +} + +func distSq(x1, y1, x2, y2 int) int { + dx := x1 - x2 + dy := y1 - y2 + return dx*dx + dy*dy +} + +func IntSqrt(n int) int { + if n <= 0 { + return 0 + } + lo, hi := 0, n + for lo < hi { + mid := (lo + hi + 1) / 2 + if mid*mid <= n { + lo = mid + } else { + hi = mid - 1 + } + } + return lo +} + +func ApplyPoints(m *model.Map, pts []model.Point, terrain int, palette []model.Terrain) { + color := "" + if terrain >= 0 && terrain < len(palette) { + color = palette[terrain].PickColor() + } + for _, p := range pts { + m.SetCell(p, terrain, color) + } +} + +func PlaceTextLabel(m *model.Map, start model.Point, text string, color string) { + RemoveTextLabel(m, start) + tl := model.TextLabel{Text: text, Start: start, Color: color} + m.TextLabels = append(m.TextLabels, tl) + runes := []rune(text) + for i, r := range runes { + p := model.Point{X: start.X + i, Y: start.Y} + if m.InBounds(p) { + m.Grid[p.Y][p.X].Text = string(r) + } + } +} + +func RemoveTextLabel(m *model.Map, start model.Point) { + for i, tl := range m.TextLabels { + if tl.Start == start { + m.TextLabels = append(m.TextLabels[:i], m.TextLabels[i+1:]...) + break + } + } + for y := range m.Grid { + for x := range m.Grid[y] { + if m.Grid[y][x].Text == "" { + continue + } + found := false + for _, tl := range m.TextLabels { + runes := []rune(tl.Text) + for i := range runes { + if tl.Start.X+i == x && tl.Start.Y == y { + found = true + break + } + } + if found { + break + } + } + if !found { + m.Grid[y][x].Text = "" + } + } + } +} + +func FindTextLabelAt(m *model.Map, p model.Point) int { + for i, tl := range m.TextLabels { + runes := []rune(tl.Text) + for j := range runes { + if tl.Start.X+j == p.X && tl.Start.Y == p.Y { + return i + } + } + } + return -1 +} + +func MoveTextLabel(m *model.Map, oldStart, newStart model.Point) { + for i, tl := range m.TextLabels { + if tl.Start == oldStart { + for _, p := range LabelPositions(tl) { + if m.InBounds(p) { + m.Grid[p.Y][p.X].Text = "" + } + } + m.TextLabels[i].Start = newStart + runes := []rune(tl.Text) + for j, r := range runes { + p := model.Point{X: newStart.X + j, Y: newStart.Y} + if m.InBounds(p) { + m.Grid[p.Y][p.X].Text = string(r) + } + } + return + } + } +} + +func LabelPositions(tl model.TextLabel) []model.Point { + var pts []model.Point + runes := []rune(tl.Text) + for i := range runes { + pts = append(pts, model.Point{X: tl.Start.X + i, Y: tl.Start.Y}) + } + return pts +} diff --git a/internal/tools/tools_test.go b/internal/tools/tools_test.go new file mode 100644 index 0000000..22ac3d2 --- /dev/null +++ b/internal/tools/tools_test.go @@ -0,0 +1,36 @@ +package tools + +import ( + "fmt" + "testing" + + "tui-ascii-mapper/internal/model" +) + +func TestDemotools(t *testing.T) { + m := model.NewMap("test", 10, 10, nil) + Brush(m, model.Point{X: 5, Y: 5}, 0, 3, nil) + if m.Grid[5][5].Terrain != 0 { + t.Fatal("Brush failed") + } + pts := BresenhamLine(model.Point{X: 0, Y: 0}, model.Point{X: 3, Y: 0}) + if len(pts) != 4 || pts[0] != (model.Point{X: 0, Y: 0}) || pts[3] != (model.Point{X: 3, Y: 0}) { + t.Fatalf("Line failed: %v", pts) + } + if IntSqrt(25) != 5 || IntSqrt(26) != 5 || IntSqrt(0) != 0 { + t.Fatal("IntSqrt failed") + } + t2 := model.Terrain{Colors: []model.TerrainColor{{Color: "22", Weight: 100}}} + if t2.PickColor() != "22" { + t.Fatal("PickColor failed") + } + PlaceTextLabel(m, model.Point{X: 2, Y: 2}, "ABC", "") + if m.Grid[2][2].Text != "A" || m.Grid[2][3].Text != "B" { + t.Fatalf("TextLabel: %s,%s", m.Grid[2][2].Text, m.Grid[2][3].Text) + } + RemoveTextLabel(m, model.Point{X: 2, Y: 2}) + if m.Grid[2][2].Text != "" { + t.Fatal("TextLabel remove failed") + } + fmt.Println("tools: ok") +} diff --git a/internal/tui/app.go b/internal/tui/app.go new file mode 100644 index 0000000..066fa28 --- /dev/null +++ b/internal/tui/app.go @@ -0,0 +1,155 @@ +package tui + +import ( + "os" + + "tui-ascii-mapper/internal/config" + "tui-ascii-mapper/internal/mapio" + "tui-ascii-mapper/internal/model" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" +) + +type FilePickerState struct { + Files []os.DirEntry + CurDir string + Selected int + PopupX int + PopupY int + ListTop int +} + +type ColorPickerState struct { + Active bool + Cursor model.Point + Selected []string + ForText bool + GridX int + GridY int +} + +type AppModel struct { + map_ *model.Map + rootMap *model.Map + cursor model.Point + offset model.Point + prevCursor model.Point + + tool model.Tool + selected int + brushWidth int + unicode bool + colorMode bool + fillShapes bool + + mode model.Mode + dialog model.DialogType + + ti textinput.Model + + lineStart model.Point + linePreview []model.Point + rectStart model.Point + rectPreview []model.Point + circleCenter model.Point + circlePreview []model.Point + + textEditing bool + textInput textinput.Model + textColor string + movingLabel int + dragLabelOrigin model.Point + dragMouseOrigin model.Point + textCursorStart model.Point + + mouseDown bool + mouseBtn int + mouseStart model.Point + lastPaint model.Point + drawHeld bool + eraseHeld bool + + undo *model.UndoStack + + width int + height int + quitting bool + cfg config.Config + dialogMsg string + + colorPicker *ColorPickerState + dirty bool + undoPosAtSave int + hotkeySelect [10]int + palettePage int + filePicker *FilePickerState +} + +func (m *AppModel) curMap() *model.Map { return m.map_ } + +func (m *AppModel) curPalette() []model.Terrain { + if m.map_ != nil { + return m.map_.Palette + } + return nil +} + +func NewAppModel(cfg config.Config) *AppModel { + palette := make([]model.Terrain, len(cfg.Symbols)) + copy(palette, cfg.Symbols) + root := model.NewMap("untitled", cfg.DefaultMapWidth, cfg.DefaultMapHeight, palette) + + undo := &model.UndoStack{} + undo.Push(root) + undoAtSave := undo.Pos() + + ti := textinput.New() + ti.Placeholder = "" + ti.Prompt = "" + ti.CharLimit = 64 + + textTI := textinput.New() + textTI.Placeholder = "" + textTI.Prompt = "" + textTI.CharLimit = 256 + + return &AppModel{ + map_: root, + rootMap: root, + cursor: model.Point{X: 0, Y: 0}, + prevCursor: model.Point{X: -1, Y: -1}, + tool: model.ToolBrush, + brushWidth: 1, + selected: 0, + unicode: true, + colorMode: true, + mode: model.ModeNormal, + undo: undo, + cfg: cfg, + ti: ti, + textInput: textTI, + movingLabel: -1, + lastPaint: model.Point{X: -1, Y: -1}, + undoPosAtSave: undoAtSave, + } +} + +func (m *AppModel) Init() tea.Cmd { + return tea.Batch( + textinput.Blink, + tea.EnableMouseCellMotion, + ) +} + +func (m *AppModel) loadMapCmd(path string) tea.Cmd { + return func() tea.Msg { + md, err := mapio.DeserializeMap(path) + return mapLoadedMsg{data: md, err: err} + } +} + +type mapLoadedMsg struct { + data *model.Map + err error +} diff --git a/internal/tui/colorpicker.go b/internal/tui/colorpicker.go new file mode 100644 index 0000000..fba388e --- /dev/null +++ b/internal/tui/colorpicker.go @@ -0,0 +1,180 @@ +package tui + +import ( + "fmt" + "strings" + + "tui-ascii-mapper/internal/model" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +func (m *AppModel) openColorPicker(forText bool) { + m.colorPicker = &ColorPickerState{ + Active: true, + Cursor: model.Point{X: -1, Y: -1}, + Selected: nil, + ForText: forText, + } + if !forText && m.selected < len(m.curPalette()) { + for _, c := range m.curPalette()[m.selected].Colors { + m.colorPicker.Selected = append(m.colorPicker.Selected, c.Color) + } + } +} + +func (m *AppModel) handleColorPickerMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) { + x, y := msg.X, msg.Y + col := (x - m.colorPicker.GridX) / 2 + row := y - m.colorPicker.GridY + + if msg.Button == tea.MouseButtonLeft && msg.Action == tea.MouseActionPress { + if row >= 0 && row < 16 && col >= 0 && col < 16 { + idx := row*16 + col + cstr := fmt.Sprintf("%d", idx) + found := false + for i, c := range m.colorPicker.Selected { + if c == cstr { + m.colorPicker.Selected = append(m.colorPicker.Selected[:i], m.colorPicker.Selected[i+1:]...) + found = true + break + } + } + if !found { + m.colorPicker.Selected = append(m.colorPicker.Selected, cstr) + } + } + return m, nil + } + if msg.Action == tea.MouseActionRelease { + m.colorPicker.Cursor = model.Point{X: -1, Y: -1} + return m, nil + } + if row >= 0 && row < 16 && col >= 0 && col < 16 { + m.colorPicker.Cursor = model.Point{X: col, Y: row} + } + return m, nil +} + +func (m *AppModel) handleColorPickerKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + key := msg.String() + if m.colorPicker.Cursor.X < 0 { + m.colorPicker.Cursor = model.Point{X: 0, Y: 0} + } + switch key { + case "esc": + m.colorPicker = nil + return m, nil + case "enter": + if m.colorPicker.ForText { + idx := findTextLabelAtDirect(m.curMap(), m.cursor) + if idx >= 0 && len(m.colorPicker.Selected) > 0 { + m.dirty = true + m.undo.Push(m.curMap()) + m.curMap().TextLabels[idx].Color = m.colorPicker.Selected[0] + } + } else { + if m.selected < len(m.curPalette()) { + var colors []model.TerrainColor + for _, c := range m.colorPicker.Selected { + colors = append(colors, model.TerrainColor{Color: c, Weight: 100}) + } + if len(colors) > 0 { + m.curPalette()[m.selected].Colors = colors + } + } + } + m.colorPicker = nil + return m, nil + case "space": + idx := m.colorPicker.Cursor.Y*16 + m.colorPicker.Cursor.X + cstr := fmt.Sprintf("%d", idx) + found := false + for i, c := range m.colorPicker.Selected { + if c == cstr { + m.colorPicker.Selected = append(m.colorPicker.Selected[:i], m.colorPicker.Selected[i+1:]...) + found = true + break + } + } + if !found { + m.colorPicker.Selected = append(m.colorPicker.Selected, cstr) + } + case "up", "k": + m.colorPicker.Cursor.Y = (m.colorPicker.Cursor.Y - 1 + 16) % 16 + case "down", "j": + m.colorPicker.Cursor.Y = (m.colorPicker.Cursor.Y + 1) % 16 + case "left", "h": + m.colorPicker.Cursor.X = (m.colorPicker.Cursor.X - 1 + 16) % 16 + case "right", "l": + m.colorPicker.Cursor.X = (m.colorPicker.Cursor.X + 1) % 16 + case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9": + } + return m, nil +} + +func findTextLabelAtDirect(m *model.Map, p model.Point) int { + for i, tl := range m.TextLabels { + runes := []rune(tl.Text) + for j := range runes { + if tl.Start.X+j == p.X && tl.Start.Y == p.Y { + return i + } + } + } + return -1 +} + +func (m *AppModel) renderColorPickerFullscreen() string { + var inner strings.Builder + inner.WriteString(lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("33")).Render("Color Picker")) + inner.WriteString(" (space/click:toggle enter:apply esc:cancel)\n\n") + for row := 0; row < 16; row++ { + for col := 0; col < 16; col++ { + idx := row*16 + col + cstr := fmt.Sprintf("%d", idx) + sel := false + for _, c := range m.colorPicker.Selected { + if c == cstr { + sel = true + break + } + } + marker := " " + if sel { + marker = "\u25cf " + } + if row == m.colorPicker.Cursor.Y && col == m.colorPicker.Cursor.X { + marker = "\u25cb " + } + style := lipgloss.NewStyle().Background(lipgloss.Color(cstr)).Foreground(lipgloss.Color("255")) + inner.WriteString(style.Render(marker)) + } + inner.WriteByte('\n') + } + inner.WriteString("\nSelected: ") + for _, c := range m.colorPicker.Selected { + inner.WriteString(c + " ") + } + popup := lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + Background(lipgloss.Color("234")). + Padding(1, 2). + Render(inner.String()) + + popupW := lipgloss.Width(popup) + popupH := lipgloss.Height(popup) + gx := (m.width-popupW)/2 + 3 + gy := (m.height-popupH)/2 + 4 + if gx < 0 { + gx = 0 + } + if gy < 0 { + gy = 0 + } + m.colorPicker.GridX = gx + m.colorPicker.GridY = gy + + return m.centeredFullscreen(popup) +} diff --git a/internal/tui/dialogs.go b/internal/tui/dialogs.go new file mode 100644 index 0000000..014951d --- /dev/null +++ b/internal/tui/dialogs.go @@ -0,0 +1,526 @@ +package tui + +import ( + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "tui-ascii-mapper/internal/mapio" + "tui-ascii-mapper/internal/model" + + tea "github.com/charmbracelet/bubbletea" +) + +func (m *AppModel) handleDialogKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + key := msg.String() + + isFilePicker := m.dialog == model.DialogFileSave || m.dialog == model.DialogFileOpen || m.dialog == model.DialogSaveAs || m.dialog == model.DialogOpenMap + if isFilePicker && m.filePicker != nil { + switch key { + case "esc": + m.mode = model.ModeNormal + m.dialog = model.DialogNone + m.filePicker = nil + return m, nil + case "up": + if m.filePicker.Selected > 0 { + m.filePicker.Selected-- + } + return m, nil + case "down": + if m.filePicker.Selected < len(m.filePicker.Files)-1 { + m.filePicker.Selected++ + } + return m, nil + case "pgup": + m.filePicker.Selected -= 10 + if m.filePicker.Selected < 0 { + m.filePicker.Selected = 0 + } + return m, nil + case "pgdown": + m.filePicker.Selected += 10 + if m.filePicker.Selected >= len(m.filePicker.Files) { + m.filePicker.Selected = len(m.filePicker.Files) - 1 + } + return m, nil + case "left": + parent := filepath.Dir(m.filePicker.CurDir) + m.filePicker.CurDir = parent + m.filePicker.Selected = 0 + m.refreshFilePicker() + return m, nil + case "enter": + tiVal := strings.TrimSpace(m.ti.Value()) + if tiVal != "" { + m.filePicker = nil + return m.doFileAction(tiVal) + } + if m.filePicker.Selected >= 0 && m.filePicker.Selected < len(m.filePicker.Files) { + entry := m.filePicker.Files[m.filePicker.Selected] + if entry.IsDir() { + m.filePicker.CurDir = filepath.Join(m.filePicker.CurDir, entry.Name()) + m.filePicker.Selected = 0 + m.refreshFilePicker() + return m, nil + } + fullPath := filepath.Join(m.filePicker.CurDir, entry.Name()) + m.ti.SetValue(fullPath) + m.filePicker = nil + return m.doFileAction(fullPath) + } + return m, nil + } + var cmd tea.Cmd + m.ti, cmd = m.ti.Update(msg) + return m, cmd + } + + switch key { + case "esc": + if m.dialog == model.DialogQuitConfirm { + m.quitting = true + return m, tea.Quit + } + m.mode = model.ModeNormal + m.dialog = model.DialogNone + return m, nil + case "q": + if m.dialog == model.DialogQuitConfirm { + m.quitting = true + return m, tea.Quit + } + fallthrough + default: + var cmd tea.Cmd + m.ti, cmd = m.ti.Update(msg) + return m, cmd + case "enter": + switch m.dialog { + case model.DialogSaveAs: + name := m.ti.Value() + if name != "" { + m.rootMap.Filename = name + if err := mapio.SerializeMap(m.rootMap, name); err != nil { + m.dialogMsg = err.Error() + } else { + m.dialogMsg = fmt.Sprintf("Saved %s", name) + m.dirty = false + m.undoPosAtSave = m.undo.Pos() + } + } + case model.DialogResize: + var w, h int + val := m.ti.Value() + if n, _ := fmt.Sscanf(val, "%dx%d", &w, &h); n == 2 && w > 0 && h > 0 && w < 1000 && h < 1000 { + m.resizeMap(w, h) + } + case model.DialogQuitConfirm: + m.quitting = true + return m, tea.Quit + case model.DialogDeleteSubmapConfirm: + m.dirty = true + m.undo.Push(m.curMap()) + delete(m.curMap().Submaps, m.cursor) + case model.DialogRenameSymbol: + name := m.ti.Value() + if name != "" && m.selected < len(m.curPalette()) { + m.curPalette()[m.selected].Name = name + } + case model.DialogRenameMap: + name := m.ti.Value() + if name != "" { + m.curMap().Name = name + } + case model.DialogOpenMap: + name := m.ti.Value() + if name != "" { + return m, m.loadMapCmd(name) + } + } + m.mode = model.ModeNormal + m.dialog = model.DialogNone + return m, nil + } +} + +func (m *AppModel) doFileAction(path string) (tea.Model, tea.Cmd) { + switch m.dialog { + case model.DialogFileSave, model.DialogSaveAs: + m.rootMap.Filename = path + if err := mapio.SerializeMap(m.rootMap, path); err != nil { + m.dialogMsg = err.Error() + } else { + m.dialogMsg = fmt.Sprintf("Saved %s", path) + m.dirty = false + m.undoPosAtSave = m.undo.Pos() + } + case model.DialogFileOpen, model.DialogOpenMap: + m.mode = model.ModeNormal + m.dialog = model.DialogNone + return m, m.loadMapCmd(path) + } + m.mode = model.ModeNormal + m.dialog = model.DialogNone + return m, nil +} + +func (m *AppModel) handleFilePickerMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) { + _, y := msg.X, msg.Y + if msg.Button != tea.MouseButtonLeft || msg.Action != tea.MouseActionPress { + return m, nil + } + entryY := y - m.filePicker.PopupY + if entryY >= 0 && entryY < len(m.filePicker.Files) { + idx := entryY + m.filePicker.ListTop + if idx >= 0 && idx < len(m.filePicker.Files) { + m.filePicker.Selected = idx + entry := m.filePicker.Files[idx] + if entry.IsDir() { + m.filePicker.CurDir = filepath.Join(m.filePicker.CurDir, entry.Name()) + m.filePicker.Selected = 0 + m.refreshFilePicker() + } else { + fullPath := filepath.Join(m.filePicker.CurDir, entry.Name()) + m.ti.SetValue(fullPath) + m.filePicker = nil + return m.doFileAction(fullPath) + } + } + } + return m, nil +} + +func (m *AppModel) saveMap() { + if m.rootMap.Filename == "" { + m.mode = model.ModeDialog + m.dialog = model.DialogFileSave + m.openFilePicker() + m.ti.Focus() + return + } + if err := mapio.SerializeMap(m.rootMap, m.rootMap.Filename); err != nil { + m.dialogMsg = fmt.Sprintf("Save error: %v", err) + } else { + m.dialogMsg = fmt.Sprintf("Saved %s", m.rootMap.Filename) + m.dirty = false + m.undoPosAtSave = m.undo.Pos() + } +} + +func (m *AppModel) openFilePicker() { + cur := "." + m.filePicker = &FilePickerState{CurDir: cur, Selected: 0} + m.refreshFilePicker() + m.ti.SetValue("") +} + +func (m *AppModel) refreshFilePicker() { + entries, err := os.ReadDir(m.filePicker.CurDir) + if err != nil { + m.filePicker.Files = nil + return + } + sort.Slice(entries, func(i, j int) bool { + if entries[i].IsDir() != entries[j].IsDir() { + return entries[i].IsDir() + } + return entries[i].Name() < entries[j].Name() + }) + m.filePicker.Files = entries + if m.filePicker.Selected >= len(entries) { + m.filePicker.Selected = len(entries) - 1 + } + if m.filePicker.Selected < 0 { + m.filePicker.Selected = 0 + } +} + +func (m *AppModel) doFilePickerSelect() { + if m.filePicker == nil || len(m.filePicker.Files) == 0 { + return + } + entry := m.filePicker.Files[m.filePicker.Selected] + if entry.IsDir() { + m.filePicker.CurDir = filepath.Join(m.filePicker.CurDir, entry.Name()) + m.filePicker.Selected = 0 + m.refreshFilePicker() + return + } + m.ti.SetValue(filepath.Join(m.filePicker.CurDir, entry.Name())) +} + +func (m *AppModel) drillDown() { + m.cancelPreview() + sub, ok := m.curMap().Submaps[m.cursor] + if !ok { + sub = model.NewMap(fmt.Sprintf("%s/sub", m.curMap().Name), + m.cfg.DefaultMapWidth, m.cfg.DefaultMapHeight, + m.curMap().Palette) + sub.Parent = m.curMap() + sub.Filename = m.rootMap.Filename + m.curMap().Submaps[m.cursor] = sub + } + m.prevCursor = m.cursor + m.map_ = sub + m.cursor = model.Point{X: 0, Y: 0} + m.offset = model.Point{X: 0, Y: 0} +} + +func (m *AppModel) drillUp() { + if m.curMap().Parent == nil { + return + } + if m.isMapBlank(m.curMap()) { + delete(m.curMap().Parent.Submaps, m.prevCursor) + } + parent := m.curMap().Parent + m.map_ = parent + if m.prevCursor.X >= 0 { + m.cursor = m.prevCursor + } else { + m.cursor = model.Point{X: -1, Y: -1} + } + m.offset = model.Point{X: 0, Y: 0} + m.prevCursor = model.Point{X: -1, Y: -1} +} + +func (m *AppModel) isMapBlank(mm *model.Map) bool { + for y := range mm.Grid { + for x := range mm.Grid[y] { + if mm.Grid[y][x].Terrain >= 0 || mm.Grid[y][x].Text != "" { + return false + } + } + } + return len(mm.Submaps) == 0 +} + +func (m *AppModel) handleToolbarClick(x int) { + widths := []int{16, 10, 21, 5, 5, 5, 6, 6, 6} + pos := 0 + for i, w := range widths { + if x >= pos && x < pos+w { + switch i { + case 0: + m.mode = model.ModeDialog + m.dialog = model.DialogRenameMap + m.ti.SetValue(m.curMap().Name) + m.ti.Focus() + case 1: + m.mode = model.ModeDialog + m.dialog = model.DialogResize + m.ti.SetValue(fmt.Sprintf("%dx%d", m.curMap().Width, m.curMap().Height)) + m.ti.Focus() + case 2: + m.mode = model.ModeDialog + m.dialog = model.DialogFileSave + m.openFilePicker() + m.ti.SetValue(m.rootMap.Filename) + m.ti.Focus() + case 3: + m.unicode = !m.unicode + case 4: + m.colorMode = !m.colorMode + case 5: + m.fillShapes = !m.fillShapes + case 6: + m.saveMap() + case 7: + m.mode = model.ModeDialog + m.dialog = model.DialogFileOpen + m.openFilePicker() + m.ti.Focus() + case 8: + if m.dirty { + m.mode = model.ModeDialog + m.dialog = model.DialogQuitConfirm + } else { + m.quitting = true + } + } + return + } + pos += w + } +} + +func (m *AppModel) handleSidebarClick(x, y int) { + relY := y - 1 + + if relY >= 1 && relY <= 10 { + idx := m.palettePage*10 + (relY - 1) + if idx < len(m.curPalette()) { + m.selected = idx + } + return + } + + if relY == 11 { + if x < m.width-sidebarW+7 { + m.palettePagePrev() + } else { + m.palettePageNext() + } + return + } + + if relY == 12 { + if x < m.width-sidebarW+8 { + m.addSymbol() + } else { + m.removeSymbol() + } + return + } + if relY == 13 { + if x < m.width-sidebarW+8 { + m.moveSymbolUp() + } else { + m.moveSymbolDown() + } + return + } + if relY == 14 { + if x < m.width-sidebarW+10 { + m.mode = model.ModeDialog + m.dialog = model.DialogRenameSymbol + m.ti.SetValue(m.curPalette()[model.Clamp(m.selected, 0, len(m.curPalette())-1)].Name) + m.ti.Focus() + } else { + m.openColorPicker(false) + } + return + } + + toolRow := relY - 16 + if toolRow >= 0 && toolRow < 8 { + newTool := model.Tool(toolRow) + if m.tool != newTool && m.mode == model.ModeTextEdit { + m.mode = model.ModeNormal + m.movingLabel = -1 + m.textEditing = false + m.textInput.Blur() + } + m.tool = newTool + } + bwRow := relY - 25 + if bwRow >= 0 && bwRow < 3 { + m.brushWidth = []int{1, 3, 5}[bwRow] + } +} + +func (m *AppModel) addSymbol() { + p := m.curPalette() + if len(p) >= 100 { + return + } + m.dirty = true + m.undo.Push(m.curMap()) + m.curMap().Palette = append(p, model.Terrain{Name: "new", Symbol: "?", ASCII: "?", Colors: []model.TerrainColor{{Color: "255", Weight: 100}}}) +} + +func (m *AppModel) removeSymbol() { + if len(m.curPalette()) <= 1 { + return + } + m.dirty = true + m.undo.Push(m.curMap()) + idx := model.Clamp(m.selected, 0, len(m.curPalette())-1) + for y := range m.curMap().Grid { + for x := range m.curMap().Grid[y] { + c := &m.curMap().Grid[y][x] + if c.Terrain == idx { + c.Terrain = -1 + } else if c.Terrain > idx { + c.Terrain-- + } + } + } + m.curMap().Palette = append(m.curMap().Palette[:idx], m.curMap().Palette[idx+1:]...) + if m.selected >= len(m.curPalette()) { + m.selected = len(m.curPalette()) - 1 + } +} + +func (m *AppModel) moveSymbolUp() { + if m.selected <= 0 || m.selected >= len(m.curPalette()) { + return + } + m.dirty = true + m.undo.Push(m.curMap()) + i := m.selected + m.curPalette()[i], m.curPalette()[i-1] = m.curPalette()[i-1], m.curPalette()[i] + for y := range m.curMap().Grid { + for x := range m.curMap().Grid[y] { + c := &m.curMap().Grid[y][x] + if c.Terrain == i { + c.Terrain = i - 1 + } else if c.Terrain == i-1 { + c.Terrain = i + } + } + } + m.selected = i - 1 +} + +func (m *AppModel) moveSymbolDown() { + if m.selected < 0 || m.selected >= len(m.curPalette())-1 { + return + } + m.dirty = true + m.undo.Push(m.curMap()) + i := m.selected + m.curPalette()[i], m.curPalette()[i+1] = m.curPalette()[i+1], m.curPalette()[i] + for y := range m.curMap().Grid { + for x := range m.curMap().Grid[y] { + c := &m.curMap().Grid[y][x] + if c.Terrain == i { + c.Terrain = i + 1 + } else if c.Terrain == i+1 { + c.Terrain = i + } + } + } + m.selected = i + 1 +} + +func (m *AppModel) palettePagePrev() { + totalPages := (len(m.curPalette()) + 9) / 10 + if totalPages <= 1 { + return + } + m.palettePage = (m.palettePage - 1 + totalPages) % totalPages +} + +func (m *AppModel) palettePageNext() { + totalPages := (len(m.curPalette()) + 9) / 10 + if totalPages <= 1 { + return + } + m.palettePage = (m.palettePage + 1) % totalPages +} + +func (m *AppModel) resizeMap(w, h int) { + m.dirty = true + m.undo.Push(m.curMap()) + old := m.curMap() + newGrid := make([][]model.Cell, h) + for y := range newGrid { + newGrid[y] = make([]model.Cell, w) + for x := range newGrid[y] { + if y < old.Height && x < old.Width { + newGrid[y][x] = old.Grid[y][x] + } else { + newGrid[y][x].Terrain = -1 + } + } + } + old.Grid = newGrid + old.Width = w + old.Height = h + m.cursor.X = model.Clamp(m.cursor.X, 0, w-1) + m.cursor.Y = model.Clamp(m.cursor.Y, 0, h-1) +} diff --git a/internal/tui/handlers.go b/internal/tui/handlers.go new file mode 100644 index 0000000..6f78922 --- /dev/null +++ b/internal/tui/handlers.go @@ -0,0 +1,501 @@ +package tui + +import ( + "fmt" + + "tui-ascii-mapper/internal/model" + "tui-ascii-mapper/internal/tools" + + tea "github.com/charmbracelet/bubbletea" +) + +func (m *AppModel) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + m.dialogMsg = "" + if m.mode == model.ModeDialog { + return m.handleDialogKey(msg) + } + if m.colorPicker != nil && m.colorPicker.Active { + return m.handleColorPickerKey(msg) + } + if m.mode == model.ModeTextEdit { + return m.handleTextEditKey(msg) + } + + key := msg.String() + cfg := m.cfg.Keybindings + + switch key { + case cfg.Quit: + if m.curMap().Parent != nil { + m.drillUp() + } else if m.dirty { + m.mode = model.ModeDialog + m.dialog = model.DialogQuitConfirm + } else { + m.quitting = true + return m, tea.Quit + } + return m, nil + case cfg.Save: + m.saveMap() + return m, nil + case cfg.Undo: + if entry := m.undo.Undo(); entry != nil { + *entry.Target = *entry.State + m.dirty = m.undo.Pos() != m.undoPosAtSave + } + return m, nil + case cfg.Redo: + if entry := m.undo.Redo(); entry != nil { + *entry.Target = *entry.State + m.dirty = m.undo.Pos() != m.undoPosAtSave + } + return m, nil + case cfg.UnicodeToggle: + m.unicode = !m.unicode + return m, nil + case cfg.ColorToggle: + m.colorMode = !m.colorMode + return m, nil + case cfg.FillToggle, "f": + m.fillShapes = !m.fillShapes + return m, nil + case cfg.Resize: + m.mode = model.ModeDialog + m.dialog = model.DialogResize + m.ti.SetValue(fmt.Sprintf("%dx%d", m.curMap().Width, m.curMap().Height)) + m.ti.Focus() + return m, nil + case "!": + m.tool = model.ToolBrush + m.drawHeld, m.eraseHeld = false, false + case "@": + m.tool = model.ToolSelect + m.drawHeld, m.eraseHeld = false, false + case "#": + m.tool = model.ToolErase + m.drawHeld, m.eraseHeld = false, false + case "$": + m.tool = model.ToolFill + m.drawHeld, m.eraseHeld = false, false + case "%": + m.tool = model.ToolLine + m.drawHeld, m.eraseHeld = false, false + case "^": + m.tool = model.ToolRect + m.drawHeld, m.eraseHeld = false, false + case "&": + m.tool = model.ToolCircle + m.drawHeld, m.eraseHeld = false, false + case "*": + m.tool = model.ToolText + m.drawHeld, m.eraseHeld = false, false + case "(": + m.tool = model.ToolText + m.drawHeld, m.eraseHeld = false, false + + case "ctrl+1": + m.brushWidth = 1 + case "ctrl+2": + m.brushWidth = 3 + case "ctrl+3": + m.brushWidth = 5 + case "[": + if m.brushWidth > 1 { + m.brushWidth -= 2 + } + case "]": + if m.brushWidth < 5 { + m.brushWidth += 2 + } + case "enter": + if m.tool == model.ToolText { + return m.handleSpace() + } + if m.movingLabel >= 0 { + m.placeMovingLabel() + return m, nil + } + if m.mode == model.ModeLinePreview { + m.finalizeLinePreview() + } else if m.mode == model.ModeRectPreview { + m.finalizeRectPreview() + } else if m.mode == model.ModeCirclePreview { + m.finalizeCirclePreview() + } else if "enter" == cfg.DrillDown { + m.drillDown() + } + return m, nil + case cfg.DrillDown: + m.drillDown() + return m, nil + case cfg.DrillUp: + m.drillUp() + return m, nil + case cfg.DeleteSubmap: + if _, ok := m.curMap().Submaps[m.cursor]; ok { + m.mode = model.ModeDialog + m.dialog = model.DialogDeleteSubmapConfirm + } + return m, nil + case " ", "space": + return m.handleSpace() + case "backspace", "x": + return m.handleBackspace() + case "e": + if m.tool == model.ToolText { + return m.editTextAtCursor() + } + case "c": + if m.tool == model.ToolText { + idx := tools.FindTextLabelAt(m.curMap(), m.cursor) + if idx >= 0 { + m.openColorPicker(true) + return m, nil + } + } + case "esc": + if m.movingLabel >= 0 { + m.movingLabel = -1 + m.dragLabelOrigin = model.Point{X: 0, Y: 0} + m.dragMouseOrigin = model.Point{X: 0, Y: 0} + return m, nil + } + m.cancelPreview() + return m, nil + case "up", "down", "left", "right", "h", "j", "k", "l": + switch key { + case "up", "k": + m.moveCursor(0, -1) + case "down", "j": + m.moveCursor(0, 1) + case "left", "h": + m.moveCursor(-1, 0) + case "right", "l": + m.moveCursor(1, 0) + } + if m.movingLabel < 0 && m.drawHeld { + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(m.cursor) + } else if m.movingLabel < 0 && m.eraseHeld { + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(m.cursor, true) + } + return m, nil + default: + if len(msg.Runes) == 1 { + r := msg.Runes[0] + switch r { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + hk := (int(r-'0') + 9) % 10 + var indices []int + for i := range m.curPalette() { + if i%10 == hk { + indices = append(indices, i) + } + } + if len(indices) == 0 { + return m, nil + } + curOff := m.hotkeySelect[hk] + if m.selected%10 == hk && model.ContainsInt(indices, m.selected) { + curOff = (curOff + 1) % len(indices) + } else { + curOff = 0 + } + m.hotkeySelect[hk] = curOff + m.selected = indices[curOff] + m.palettePage = m.selected / 10 + case '=': + m.palettePageNext() + case '-': + m.palettePagePrev() + case '<', ',': + m.moveSymbolUp() + case '>', '.': + m.moveSymbolDown() + } + } + } + return m, nil +} + +func (m *AppModel) handleSpace() (tea.Model, tea.Cmd) { + m.drawHeld = false + m.eraseHeld = false + + if m.mode == model.ModeLinePreview { + m.finalizeLinePreview() + return m, nil + } + if m.mode == model.ModeRectPreview { + m.finalizeRectPreview() + return m, nil + } + if m.mode == model.ModeCirclePreview { + m.finalizeCirclePreview() + return m, nil + } + + if m.tool == model.ToolSelect { + return m, nil + } + + if m.tool == model.ToolLine && m.mode == model.ModeNormal { + m.lineStart = m.cursor + m.mode = model.ModeLinePreview + m.linePreview = nil + return m, nil + } + if m.tool == model.ToolRect && m.mode == model.ModeNormal { + m.rectStart = m.cursor + m.mode = model.ModeRectPreview + m.rectPreview = nil + return m, nil + } + if m.tool == model.ToolCircle && m.mode == model.ModeNormal { + m.circleCenter = m.cursor + m.mode = model.ModeCirclePreview + m.circlePreview = nil + return m, nil + } + if m.tool == model.ToolText { + if m.movingLabel >= 0 { + if m.movingLabel < len(m.curMap().TextLabels) { + old := m.curMap().TextLabels[m.movingLabel].Start + newPos := m.labelDragPos() + if old != newPos && m.curMap().InBounds(newPos) { + m.dirty = true + m.undo.Push(m.curMap()) + tools.MoveTextLabel(m.curMap(), old, newPos) + } + } + m.movingLabel = -1 + return m, nil + } + idx := tools.FindTextLabelAt(m.curMap(), m.cursor) + if idx >= 0 { + m.movingLabel = idx + tl := m.curMap().TextLabels[idx] + m.dragLabelOrigin = tl.Start + m.dragMouseOrigin = m.cursor + } else { + m.startTextEdit(m.cursor) + } + return m, nil + } + if m.tool == model.ToolErase { + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(m.cursor, true) + return m, nil + } + if m.tool == model.ToolFill { + m.dirty = true + m.undo.Push(m.curMap()) + m.fillAt(m.cursor) + return m, nil + } + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(m.cursor) + return m, nil +} + +func (m *AppModel) handleBackspace() (tea.Model, tea.Cmd) { + m.drawHeld = false + m.eraseHeld = false + if m.mode == model.ModeLinePreview || m.mode == model.ModeRectPreview || m.mode == model.ModeCirclePreview { + m.cancelPreview() + return m, nil + } + if m.tool == model.ToolText { + idx := tools.FindTextLabelAt(m.curMap(), m.cursor) + if idx >= 0 { + m.dirty = true + m.undo.Push(m.curMap()) + tools.RemoveTextLabel(m.curMap(), m.curMap().TextLabels[idx].Start) + } + return m, nil + } + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(m.cursor, true) + return m, nil +} + +func (m *AppModel) finalizeLinePreview() { + m.dirty = true + m.undo.Push(m.curMap()) + tools.ApplyPoints(m.curMap(), m.linePreview, m.selected, m.curPalette()) + m.linePreview = nil + m.mode = model.ModeNormal +} + +func (m *AppModel) finalizeRectPreview() { + m.dirty = true + m.undo.Push(m.curMap()) + tools.ApplyPoints(m.curMap(), m.rectPreview, m.selected, m.curPalette()) + m.rectPreview = nil + m.mode = model.ModeNormal +} + +func (m *AppModel) finalizeCirclePreview() { + m.dirty = true + m.undo.Push(m.curMap()) + tools.ApplyPoints(m.curMap(), m.circlePreview, m.selected, m.curPalette()) + m.circlePreview = nil + m.mode = model.ModeNormal +} + +func (m *AppModel) cancelPreview() { + m.linePreview = nil + m.rectPreview = nil + m.circlePreview = nil + m.mode = model.ModeNormal +} + +func (m *AppModel) moveCursor(dx, dy int) { + m.cursor.X = model.Clamp(m.cursor.X+dx, 0, m.curMap().Width-1) + m.cursor.Y = model.Clamp(m.cursor.Y+dy, 0, m.curMap().Height-1) + if m.mode == model.ModeLinePreview { + m.linePreview = tools.ThickenPoints(tools.BresenhamLine(m.lineStart, m.cursor), m.brushWidth) + } else if m.mode == model.ModeRectPreview { + m.rectPreview = tools.ThickenPoints(tools.DrawRect(m.rectStart, m.cursor, m.fillShapes), m.brushWidth) + } else if m.mode == model.ModeCirclePreview { + m.circlePreview = tools.ThickenPoints(tools.DrawCircle(m.circleCenter, m.cursor, m.fillShapes), m.brushWidth) + } +} + +func (m *AppModel) applyBrush(center model.Point, erase ...bool) { + if !m.curMap().InBounds(center) { + return + } + terrain := m.selected + if len(erase) > 0 && erase[0] { + terrain = -1 + } + palette := m.curPalette() + switch m.tool { + case model.ToolBrush: + tools.Brush(m.curMap(), center, terrain, m.brushWidth, palette) + case model.ToolErase: + tools.Brush(m.curMap(), center, terrain, m.brushWidth, palette) + default: + color := "" + if terrain >= 0 && terrain < len(palette) { + color = palette[terrain].PickColor() + } + m.curMap().SetCell(center, terrain, color) + } +} + +func (m *AppModel) fillAt(p model.Point) { + if m.selected >= 0 && m.selected < len(m.curPalette()) { + tools.FloodFill(m.curMap(), p, m.selected, m.curPalette()) + } +} + +func (m *AppModel) clampCursor() { + m.cursor.X = model.Clamp(m.cursor.X, 0, m.curMap().Width-1) + m.cursor.Y = model.Clamp(m.cursor.Y, 0, m.curMap().Height-1) +} + +func (m *AppModel) startTextEdit(p model.Point) { + m.mode = model.ModeTextEdit + m.textInput.SetValue("") + m.textInput.Focus() + m.cursor = p + m.textCursorStart = p + m.movingLabel = -1 +} + +func (m *AppModel) startTextEditText(idx int) { + if idx < 0 || idx >= len(m.curMap().TextLabels) { + return + } + m.mode = model.ModeTextEdit + m.textInput.SetValue(m.curMap().TextLabels[idx].Text) + m.textInput.Focus() + m.textCursorStart = m.curMap().TextLabels[idx].Start + m.movingLabel = idx + m.textEditing = true +} + +func (m *AppModel) editTextAtCursor() (tea.Model, tea.Cmd) { + idx := tools.FindTextLabelAt(m.curMap(), m.cursor) + if idx < 0 { + return m, nil + } + m.startTextEditText(idx) + return m, nil +} + +func (m *AppModel) placeMovingLabel() { + if m.movingLabel >= 0 && m.movingLabel < len(m.curMap().TextLabels) { + old := m.curMap().TextLabels[m.movingLabel].Start + newPos := m.labelDragPos() + if old != newPos && m.curMap().InBounds(newPos) { + m.dirty = true + m.undo.Push(m.curMap()) + tools.MoveTextLabel(m.curMap(), old, newPos) + } + } + m.movingLabel = -1 + m.dragLabelOrigin = model.Point{X: 0, Y: 0} + m.dragMouseOrigin = model.Point{X: 0, Y: 0} +} + +func (m *AppModel) labelDragPos() model.Point { + return model.Point{ + X: m.dragLabelOrigin.X + (m.cursor.X - m.dragMouseOrigin.X), + Y: m.dragLabelOrigin.Y + (m.cursor.Y - m.dragMouseOrigin.Y), + } +} + +func (m *AppModel) handleTextEditKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + key := msg.String() + + switch key { + case "esc": + m.mode = model.ModeNormal + m.movingLabel = -1 + m.textEditing = false + m.textInput.Blur() + return m, nil + case "backspace": + val := m.textInput.Value() + runes := []rune(val) + if len(runes) > 0 { + m.textInput.SetValue(string(runes[:len(runes)-1])) + } + return m, nil + case "enter": + m.commitTextEdit() + return m, nil + } + var cmd tea.Cmd + m.textInput, cmd = m.textInput.Update(msg) + return m, cmd +} + +func (m *AppModel) commitTextEdit() { + text := m.textInput.Value() + if text != "" { + m.dirty = true + m.undo.Push(m.curMap()) + start := m.cursor + if m.textEditing && m.movingLabel >= 0 && m.movingLabel < len(m.curMap().TextLabels) { + tools.RemoveTextLabel(m.curMap(), m.curMap().TextLabels[m.movingLabel].Start) + start = m.textCursorStart + m.textEditing = false + } + tools.PlaceTextLabel(m.curMap(), start, text, m.textColor) + } + m.mode = model.ModeNormal + m.movingLabel = -1 + m.textEditing = false + m.textInput.Blur() +} diff --git a/internal/tui/render.go b/internal/tui/render.go new file mode 100644 index 0000000..1b34a21 --- /dev/null +++ b/internal/tui/render.go @@ -0,0 +1,465 @@ +package tui + +import ( + "fmt" + "strings" + + "tui-ascii-mapper/internal/model" + + "github.com/charmbracelet/lipgloss" +) + +const sidebarW = 18 + +var ( + toolbarStyle = lipgloss.NewStyle().Background(lipgloss.Color("235")).Foreground(lipgloss.Color("252")) + sidebarStyle = lipgloss.NewStyle().Background(lipgloss.Color("235")).Foreground(lipgloss.Color("252")) + statusStyle = lipgloss.NewStyle().Background(lipgloss.Color("235")).Foreground(lipgloss.Color("252")) + accentBg = lipgloss.Color("33") + accentFg = lipgloss.Color("255") +) + +func (m *AppModel) renderToolbar() string { + items := []struct { + label string + width int + }{ + {"Name", 16}, + {"Size", 10}, + {"File", 21}, + {"Uni", 5}, + {"Col", 5}, + {"Fil", 5}, + {"Save", 6}, + {"Load", 6}, + {"Quit", 6}, + } + var styles []string + for i, it := range items { + var txt string + on := false + switch i { + case 0: + txt = " " + truncate(m.curMap().Name, it.width-2) + " " + case 1: + txt = fmt.Sprintf(" %dx%d ", m.curMap().Width, m.curMap().Height) + case 2: + txt = " " + truncate(shortFilename(m.rootMap.Filename), it.width-2) + " " + case 3: + txt = "[Uni]" + on = m.unicode + case 4: + txt = "[Col]" + on = m.colorMode + case 5: + txt = "[Fil]" + on = m.fillShapes + case 6: + txt = "[Save]" + if strings.Contains(m.dialogMsg, "Saved") { + on = true + } + case 7: + txt = "[Load]" + case 8: + txt = "[Quit]" + } + s := lipgloss.NewStyle().Width(it.width) + if on { + s = s.Background(lipgloss.Color("33")).Foreground(lipgloss.Color("0")) + } else { + s = s.Background(lipgloss.Color("235")).Foreground(lipgloss.Color("252")) + } + styles = append(styles, s.Render(txt)) + } + return toolbarStyle.Width(m.width).Render(lipgloss.JoinHorizontal(lipgloss.Top, styles...)) +} + +func truncate(s string, w int) string { + r := []rune(s) + if len(r) <= w { + return s + } + return string(r[:max(0, w-1)]) + "\u2026" +} + +func (m *AppModel) renderGrid(gw, gh int) string { + var sb strings.Builder + for row := 0; row < gh; row++ { + my := row + m.offset.Y + for col := 0; col < gw; col++ { + mx := col + m.offset.X + p := model.Point{X: mx, Y: my} + if !m.curMap().InBounds(p) { + sb.WriteString(m.cellStr("\u00b7", "240", "", false, false, false)) + continue + } + cell := m.curMap().CellAt(p) + isCursor := !m.mouseDown && p == m.cursor + isPreview := m.isPreviewCell(p) + hasSub := false + if _, ok := m.curMap().Submaps[p]; ok { + hasSub = true + } + + var sym string + var fg string + var bg string + + showText := cell.Text != "" + if showText && m.movingLabel >= 0 && m.movingLabel < len(m.curMap().TextLabels) { + tl := m.curMap().TextLabels[m.movingLabel] + runes := []rune(tl.Text) + for i := range runes { + if tl.Start.X+i == p.X && tl.Start.Y == p.Y { + showText = false + break + } + } + } + if showText { + sym = cell.Text + fg = "15" + } else if cell.Terrain >= 0 && cell.Terrain < len(m.curPalette()) { + sym = m.curPalette()[cell.Terrain].GetSymbol(m.unicode) + } else { + sym = " " + } + + if cell.Text == "" && m.colorMode { + if cell.Terrain >= 0 && cell.Color != "" { + fg = cell.Color + } else if cell.Terrain >= 0 { + fg = "255" + } + } + if hasSub { + bg = m.cfg.SubmapBg + } + if isPreview && sym == " " { + sym = "\u00b7" + fg = "250" + } + + if m.mode == model.ModeTextEdit && m.tool == model.ToolText { + text := m.textInput.Value() + cursorCh := "" + if m.textInput.Focused() { + cursorCh = "\u2502" + } + runes := []rune(text + cursorCh) + for i, r := range runes { + if p.X == m.textCursorStart.X+i && p.Y == m.textCursorStart.Y { + sym = string(r) + fg = "15" + break + } + } + } + if m.mode != model.ModeTextEdit && m.movingLabel >= 0 && m.movingLabel < len(m.curMap().TextLabels) { + tl := m.curMap().TextLabels[m.movingLabel] + pos := m.labelDragPos() + runes := []rune(tl.Text) + for i, r := range runes { + if p.X == pos.X+i && p.Y == pos.Y { + sym = string(r) + fg = "15" + break + } + } + } + + sb.WriteString(m.cellStr(sym, fg, bg, isCursor, isPreview, false)) + } + if row < gh-1 { + sb.WriteByte('\n') + } + } + return sb.String() +} + +func (m *AppModel) isPreviewCell(p model.Point) bool { + for _, pt := range m.linePreview { + if pt == p { + return true + } + } + for _, pt := range m.rectPreview { + if pt == p { + return true + } + } + for _, pt := range m.circlePreview { + if pt == p { + return true + } + } + return false +} + +func (m *AppModel) cellStr(sym, fg, bg string, cursor, preview, reverse bool) string { + if cursor { + return styledCell(sym, "0", "15", true) + } + if preview { + return styledCell(sym, fg, "240", false) + } + if bg != "" || fg != "" { + return styledCell(sym, fg, bg, false) + } + return sym +} + +func styledCell(sym, fg, bg string, reverse bool) string { + var parts []string + if reverse { + parts = append(parts, "\033[7m") + } else { + if bg != "" { + parts = append(parts, "\033[48;5;"+bg+"m") + } + if fg != "" { + parts = append(parts, "\033[38;5;"+fg+"m") + } + } + if len(parts) > 0 { + parts = append(parts, sym, "\033[0m") + return strings.Join(parts, "") + } + return sym +} + +func (m *AppModel) renderSidebar(gh int) string { + palette := m.curPalette() + totalPages := (len(palette) + 9) / 10 + startIdx := m.palettePage * 10 + endIdx := startIdx + 10 + if endIdx > len(palette) { + endIdx = len(palette) + } + + var sb strings.Builder + sb.WriteString(sidebarStyle.Width(sidebarW).Render(" ══ Symbols ══")) + sb.WriteByte('\n') + for i := startIdx; i < endIdx; i++ { + t := palette[i] + idx := i % 10 + sym := t.GetSymbol(m.unicode) + fg := "252" + if m.colorMode && len(t.Colors) > 0 { + fg = t.Colors[0].Color + } + coloredSym := lipgloss.NewStyle().Foreground(lipgloss.Color(fg)).Render(sym) + label := fmt.Sprintf("%d %s %-9s", (idx+1)%10, coloredSym, t.Name) + if i == m.selected { + label = lipgloss.NewStyle(). + Background(accentBg).Foreground(accentFg). + Width(sidebarW).Render(label) + } else { + label = lipgloss.NewStyle(). + Foreground(lipgloss.Color("252")). + Width(sidebarW).Render(label) + } + sb.WriteString(label) + sb.WriteByte('\n') + } + for i := endIdx - startIdx; i < 10; i++ { + sb.WriteByte('\n') + } + pageLabel := fmt.Sprintf(" << page %d/%d >> ", m.palettePage+1, totalPages) + sb.WriteString(sidebarStyle.Width(sidebarW).Render(pageLabel)) + sb.WriteByte('\n') + sb.WriteString(lipgloss.NewStyle().Width(sidebarW).Render(" [+ Add] [- Del]")) + sb.WriteByte('\n') + sb.WriteString(lipgloss.NewStyle().Width(sidebarW).Render(" [▲ Up] [▼ Down]")) + sb.WriteByte('\n') + sb.WriteString(lipgloss.NewStyle().Width(sidebarW).Render(" [Rename] [Color]")) + sb.WriteByte('\n') + sb.WriteString(sidebarStyle.Width(sidebarW).Render(" ══ Tools ══")) + sb.WriteByte('\n') + tools_ := []model.Tool{model.ToolBrush, model.ToolSelect, model.ToolErase, model.ToolFill, model.ToolLine, model.ToolRect, model.ToolCircle, model.ToolText} + tlabels := []string{"1 Brush", "2 Select", "3 Erase", "4 Fill", "5 Line", "6 Rect", "7 Circle", "8 Text"} + for i, tn := range tlabels { + label := tn + if tools_[i] == m.tool { + label = lipgloss.NewStyle().Background(accentBg).Foreground(accentFg).Width(sidebarW).Render(tn) + } + if label == tn { + label = lipgloss.NewStyle().Width(sidebarW).Render(label) + } + sb.WriteString(label) + sb.WriteByte('\n') + } + sb.WriteString(sidebarStyle.Width(sidebarW).Render("══ Brush Width ══")) + sb.WriteByte('\n') + for _, bw := range []int{1, 3, 5} { + label := fmt.Sprintf(" %dx%d", bw, bw) + if bw == m.brushWidth { + label = lipgloss.NewStyle().Background(accentBg).Foreground(accentFg).Width(sidebarW).Render(label) + } else { + label = lipgloss.NewStyle().Width(sidebarW).Render(label) + } + sb.WriteString(label) + sb.WriteByte('\n') + } + lines := strings.Split(sb.String(), "\n") + if len(lines) > gh { + lines = lines[:gh] + } + return strings.Join(lines, "\n") +} + +func (m *AppModel) renderStatus() string { + cell := m.curMap().CellAt(m.cursor) + terrainName := "" + if cell.Terrain >= 0 && cell.Terrain < len(m.curPalette()) { + terrainName = m.curPalette()[cell.Terrain].Name + } + subInfo := "" + if _, ok := m.curMap().Submaps[m.cursor]; ok { + subInfo = " [submap]" + } + modeLabel := m.tool.String() + if m.drawHeld { + modeLabel += " [DRAW]" + } else if m.eraseHeld { + modeLabel += " [ERASE]" + } + feedback := "" + if m.dialogMsg != "" { + feedback = " " + m.dialogMsg + } + return statusStyle.Width(m.width).Render( + fmt.Sprintf(" %d,%d %s %s %s%s%s", + m.cursor.X, m.cursor.Y, + modeLabel, terrainName, m.curMap().Name, subInfo, feedback)) +} + +func (m *AppModel) renderHelp() string { + cfg := m.cfg.Keybindings + help := fmt.Sprintf(" %s:Save %s:Quit %s:Undo %s:Redo Space:Draw Bksp:Erase Enter:Sub Esc:Up Arrows:Move 1-8:Tools f:FillShp []:Width", + cfg.Save, cfg.Quit, cfg.Undo, cfg.Redo) + if len(help) > m.width && m.width > 3 { + help = help[:m.width-3] + "..." + } + return statusStyle.Width(m.width).Render(help) +} + +func (m *AppModel) renderDialogBox() string { + switch m.dialog { + case model.DialogSaveAs: + return m.renderFilePickerPopup("Save As") + case model.DialogOpenMap: + return m.renderFilePickerPopup("Open Map") + case model.DialogFileSave: + return m.renderFilePickerPopup("Save As") + case model.DialogFileOpen: + return m.renderFilePickerPopup("Open Map") + case model.DialogResize: + return renderPopup("Resize Map", "Size (e.g. 80x25):", m.ti.View()) + case model.DialogQuitConfirm: + return renderPopup("Quit", "Quit without saving?", "[Enter] Quit [Esc] Cancel") + case model.DialogDeleteSubmapConfirm: + return renderPopup("Delete Submap", + fmt.Sprintf("Delete submap at %d,%d?", m.cursor.X, m.cursor.Y), + "[Enter] Confirm [Esc] Cancel") + case model.DialogRenameSymbol: + return renderPopup("Rename Symbol", "New name:", m.ti.View()) + case model.DialogRenameMap: + return renderPopup("Rename Map", "New name:", m.ti.View()) + } + return "" +} + +func (m *AppModel) renderDialogFullscreen() string { + popup := m.renderDialogBox() + return m.centeredFullscreen(popup) +} + +func (m *AppModel) renderFilePickerPopup(title string) string { + if m.filePicker == nil { + return renderPopup(title, "", "Loading...") + } + + var sb strings.Builder + sb.WriteString(lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("33")).Render(title)) + sb.WriteString("\n\n") + sb.WriteString("Path: ") + sb.WriteString(m.filePicker.CurDir) + sb.WriteString("\n") + sb.WriteString("File: ") + sb.WriteString(m.ti.View()) + sb.WriteString("\n\n") + + dirStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("39")) + fileStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("252")) + selStyle := lipgloss.NewStyle().Background(lipgloss.Color("33")).Foreground(lipgloss.Color("0")) + sizeStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("243")) + + maxShow := 15 + start := m.filePicker.Selected - maxShow/2 + if start < 0 { + start = 0 + } + end := start + maxShow + if end > len(m.filePicker.Files) { + end = len(m.filePicker.Files) + start = end - maxShow + if start < 0 { + start = 0 + } + } + + for i := start; i < end; i++ { + entry := m.filePicker.Files[i] + name := entry.Name() + var line string + + if entry.IsDir() { + line = dirStyle.Render(name + "/") + } else { + info, err := entry.Info() + if err == nil { + line = fmt.Sprintf("%s %s", sizeStyle.Render(formatSize(info.Size())), fileStyle.Render(name)) + } else { + line = fmt.Sprintf("%s %s", sizeStyle.Render(" ???"), fileStyle.Render(name)) + } + } + + if i == m.filePicker.Selected { + line = selStyle.Render(fmt.Sprintf(" >%s", line)) + } else { + line = fmt.Sprintf(" %s", line) + } + sb.WriteString(line) + sb.WriteByte('\n') + } + + if len(m.filePicker.Files) == 0 { + sb.WriteString(" (empty directory)\n") + } + + sb.WriteString("\n[Enter] Select [Esc] Cancel [Left] Up") + + w := 55 + popup := lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + Background(lipgloss.Color("234")). + Padding(1, 2). + Width(w). + Render(sb.String()) + + popupW := lipgloss.Width(popup) + popupH := lipgloss.Height(popup) + m.filePicker.PopupX = (m.width-popupW)/2 + 1 + 2 + m.filePicker.PopupY = (m.height-popupH)/2 + 7 + m.filePicker.ListTop = start + if m.filePicker.PopupX < 0 { + m.filePicker.PopupX = 0 + } + if m.filePicker.PopupY < 0 { + m.filePicker.PopupY = 0 + } + + return popup +} diff --git a/internal/tui/update.go b/internal/tui/update.go new file mode 100644 index 0000000..87e0917 --- /dev/null +++ b/internal/tui/update.go @@ -0,0 +1,296 @@ +package tui + +import ( + "fmt" + + "tui-ascii-mapper/internal/model" + "tui-ascii-mapper/internal/tools" + + tea "github.com/charmbracelet/bubbletea" +) + +func (m *AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + return m, nil + + case mapLoadedMsg: + if msg.err != nil { + m.dialogMsg = fmt.Sprintf("Load error: %v", msg.err) + m.mode = model.ModeNormal + m.dialog = model.DialogNone + return m, nil + } + m.map_ = msg.data + m.rootMap = msg.data + m.undo = &model.UndoStack{} + m.undo.Push(m.map_) + m.cursor = model.Point{X: 0, Y: 0} + m.offset = model.Point{X: 0, Y: 0} + m.dialogMsg = fmt.Sprintf("Loaded %s", msg.data.Filename) + m.mode = model.ModeNormal + m.dialog = model.DialogNone + m.dirty = false + m.undoPosAtSave = m.undo.Pos() + return m, nil + + case tea.MouseMsg: + return m.handleMouse(msg) + + case tea.KeyMsg: + return m.handleKey(msg) + } + + if m.mode == model.ModeDialog || m.mode == model.ModeTextEdit { + var cmd tea.Cmd + m.ti, cmd = m.ti.Update(msg) + if cmd != nil { + return m, cmd + } + m.textInput, cmd = m.textInput.Update(msg) + if cmd != nil { + return m, cmd + } + } + return m, nil +} + +func (m *AppModel) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) { + x, y := msg.X, msg.Y + + if m.colorPicker != nil && m.colorPicker.Active { + return m.handleColorPickerMouse(msg) + } + + isFilePicker := m.dialog == model.DialogFileSave || m.dialog == model.DialogFileOpen || m.dialog == model.DialogSaveAs || m.dialog == model.DialogOpenMap + if isFilePicker && m.filePicker != nil && m.filePicker.PopupY > 0 { + return m.handleFilePickerMouse(msg) + } + + isPress := msg.Button == tea.MouseButtonLeft && msg.Action == tea.MouseActionPress + isRelease := msg.Action == tea.MouseActionRelease + isRightPress := msg.Button == tea.MouseButtonRight && msg.Action == tea.MouseActionPress + + gridAreaW := m.width - sidebarW + gridH := m.height - 1 + if m.height > 6 { + gridH -= 2 + } + if gridH < 1 { + gridH = 1 + } + if gridAreaW < 1 { + gridAreaW = 1 + } + + if isPress && y == 0 { + m.handleToolbarClick(x) + if m.quitting { + return m, tea.Quit + } + return m, nil + } + + gridY := y - 1 + onSidebar := gridAreaW > 0 && x >= gridAreaW + + if isPress && onSidebar && gridY >= 0 { + m.handleSidebarClick(x, y) + return m, nil + } + + gx := x + m.offset.X + gy := gridY + m.offset.Y + inGrid := gridY >= 0 && gridY < gridH && x < gridAreaW + + if isPress { + m.mouseDown = true + m.lastPaint = model.Point{X: -1, Y: -1} + if inGrid { + p := model.Point{X: gx, Y: gy} + switch m.tool { + case model.ToolLine: + m.mouseStart = p + m.mode = model.ModeLinePreview + m.linePreview = nil + case model.ToolRect: + m.mouseStart = p + m.mode = model.ModeRectPreview + m.rectPreview = nil + case model.ToolCircle: + m.mouseStart = p + m.mode = model.ModeCirclePreview + m.circlePreview = nil + case model.ToolSelect: + m.cursor = p + m.clampCursor() + default: + return m.mouseDraw(p.X, p.Y) + } + } + return m, nil + } + + if isRelease { + if m.mouseDown { + m.mouseRelease(gx, gy) + } + m.mouseDown = false + m.lastPaint = model.Point{X: -1, Y: -1} + return m, nil + } + + if isRightPress { + if inGrid { + if m.tool == model.ToolText { + idx := tools.FindTextLabelAt(m.curMap(), model.Point{X: gx, Y: gy}) + if idx >= 0 { + m.dirty = true + m.undo.Push(m.curMap()) + tools.RemoveTextLabel(m.curMap(), m.curMap().TextLabels[idx].Start) + m.movingLabel = -1 + } + } else { + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(model.Point{X: gx, Y: gy}, true) + m.lastPaint = model.Point{X: gx, Y: gy} + } + } + return m, nil + } + + if m.mouseDown && inGrid && (gx != m.lastPaint.X || gy != m.lastPaint.Y) { + if m.movingLabel >= 0 && m.tool == model.ToolText { + m.cursor = model.Point{X: gx, Y: gy} + m.clampCursor() + } else if m.tool == model.ToolLine { + m.linePreview = tools.ThickenPoints(tools.BresenhamLine(m.mouseStart, model.Point{X: gx, Y: gy}), m.brushWidth) + m.lastPaint = model.Point{X: gx, Y: gy} + } else if m.tool == model.ToolRect { + m.rectPreview = tools.ThickenPoints(tools.DrawRect(m.mouseStart, model.Point{X: gx, Y: gy}, m.fillShapes), m.brushWidth) + m.lastPaint = model.Point{X: gx, Y: gy} + } else if m.tool == model.ToolCircle { + m.circlePreview = tools.ThickenPoints(tools.DrawCircle(m.mouseStart, model.Point{X: gx, Y: gy}, m.fillShapes), m.brushWidth) + m.lastPaint = model.Point{X: gx, Y: gy} + } else if m.tool != model.ToolText { + m.mouseDraw(gx, gy) + } + } + + switch msg.Button { + case tea.MouseButtonWheelUp: + if m.offset.Y > 0 { + m.offset.Y-- + } + case tea.MouseButtonWheelDown: + maxY := m.curMap().Height - gridH + if maxY < 0 { + maxY = 0 + } + if m.offset.Y < maxY { + m.offset.Y++ + } + } + + return m, nil +} + +func (m *AppModel) mouseDraw(gx, gy int) (tea.Model, tea.Cmd) { + p := model.Point{X: gx, Y: gy} + switch m.tool { + case model.ToolBrush: + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(p) + m.lastPaint = p + case model.ToolErase: + m.dirty = true + m.undo.Push(m.curMap()) + m.applyBrush(p, true) + m.lastPaint = p + case model.ToolFill: + m.dirty = true + m.undo.Push(m.curMap()) + m.fillAt(p) + m.lastPaint = p + case model.ToolText: + idx := tools.FindTextLabelAt(m.curMap(), p) + if idx >= 0 { + m.movingLabel = idx + tl := m.curMap().TextLabels[idx] + m.dragLabelOrigin = tl.Start + m.dragMouseOrigin = p + m.lastPaint = p + } + } + m.cursor = p + m.clampCursor() + return m, nil +} + +func (m *AppModel) mouseRelease(gx, gy int) { + p := model.Point{X: gx, Y: gy} + switch m.tool { + case model.ToolLine: + m.dirty = true + m.undo.Push(m.curMap()) + m.finishShape(m.mouseStart, p, model.ToolLine) + m.linePreview = nil + m.mode = model.ModeNormal + case model.ToolRect: + m.dirty = true + m.undo.Push(m.curMap()) + m.finishShape(m.mouseStart, p, model.ToolRect) + m.rectPreview = nil + m.mode = model.ModeNormal + case model.ToolCircle: + m.dirty = true + m.undo.Push(m.curMap()) + m.finishShape(m.mouseStart, p, model.ToolCircle) + m.circlePreview = nil + m.mode = model.ModeNormal + case model.ToolText: + if m.movingLabel >= 0 && m.movingLabel < len(m.curMap().TextLabels) { + old := m.curMap().TextLabels[m.movingLabel].Start + newPos := m.labelDragPos() + if old != newPos && m.curMap().InBounds(newPos) { + m.dirty = true + m.undo.Push(m.curMap()) + tools.MoveTextLabel(m.curMap(), old, newPos) + m.movingLabel = -1 + } else { + m.startTextEditText(m.movingLabel) + } + } else if m.cursor == p && m.curMap().InBounds(p) { + m.startTextEdit(p) + } + m.dragLabelOrigin = model.Point{X: 0, Y: 0} + m.dragMouseOrigin = model.Point{X: 0, Y: 0} + } +} + +func (m *AppModel) finishShape(a, b model.Point, tool model.Tool) { + palette := m.curPalette() + terrain := m.selected + if terrain < 0 || terrain >= len(palette) { + return + } + var pts []model.Point + switch tool { + case model.ToolLine: + pts = tools.BresenhamLine(a, b) + case model.ToolRect: + pts = tools.DrawRect(a, b, m.fillShapes) + case model.ToolCircle: + pts = tools.DrawCircle(a, b, m.fillShapes) + } + tools.ApplyPoints(m.curMap(), pts, terrain, palette) + if m.brushWidth > 1 { + for _, pt := range pts { + tools.Brush(m.curMap(), pt, terrain, m.brushWidth, palette) + } + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..fd8acdc --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,142 @@ +package tui + +import ( + "fmt" + "strings" + + "tui-ascii-mapper/internal/model" + + "github.com/charmbracelet/lipgloss" +) + +func (m *AppModel) View() string { + if m.quitting { + return "" + } + + if m.mode == model.ModeDialog { + return m.renderDialogFullscreen() + } + if m.colorPicker != nil && m.colorPicker.Active { + return m.renderColorPickerFullscreen() + } + return m.baseView() +} + +func (m *AppModel) baseView() string { + gridAreaW := m.width - sidebarW + gridH := m.height - 1 + showStatusHelp := m.height > 6 + if showStatusHelp { + gridH -= 2 + } + if gridAreaW < 1 { + gridAreaW = 1 + } + if gridH < 1 { + gridH = 1 + } + m.scrollToCursor(gridAreaW, gridH) + + var sb strings.Builder + sb.WriteString(m.renderToolbar()) + sb.WriteByte('\n') + + gridLines := strings.Split(m.renderGrid(gridAreaW, gridH), "\n") + sidebarLines := strings.Split(m.renderSidebar(gridH), "\n") + n := max(len(gridLines), len(sidebarLines)) + for i := 0; i < n; i++ { + if i < len(gridLines) { + sb.WriteString(padRight(gridLines[i], gridAreaW)) + } else { + sb.WriteString(strings.Repeat(" ", gridAreaW)) + } + if i < len(sidebarLines) { + sb.WriteString(sidebarLines[i]) + } + sb.WriteByte('\n') + } + if showStatusHelp { + sb.WriteString(m.renderStatus()) + sb.WriteByte('\n') + sb.WriteString(m.renderHelp()) + } + return sb.String() +} + +func (m *AppModel) showFeedback(msg string) { + m.dialogMsg = msg +} + +func (m *AppModel) scrollToCursor(gw, gh int) { + if m.cursor.X < m.offset.X { + m.offset.X = m.cursor.X + } + if m.cursor.X >= m.offset.X+gw { + m.offset.X = m.cursor.X - gw + 1 + } + if m.cursor.Y < m.offset.Y { + m.offset.Y = m.cursor.Y + } + if m.cursor.Y >= m.offset.Y+gh { + m.offset.Y = m.cursor.Y - gh + 1 + } + m.offset.X = model.Clamp(m.offset.X, 0, max(0, m.curMap().Width-gw)) + m.offset.Y = model.Clamp(m.offset.Y, 0, max(0, m.curMap().Height-gh)) +} + +func (m *AppModel) centeredFullscreen(content string) string { + return lipgloss.Place(m.width, m.height, + lipgloss.Center, lipgloss.Center, + content) +} + +func renderPopup(title, label, value string) string { + lines := []string{ + lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("33")).Render(title), + "", + label + " " + value, + } + w := 40 + for i, l := range lines { + lines[i] = lipgloss.NewStyle().Width(w).Render(l) + } + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + Background(lipgloss.Color("234")). + Padding(1, 2). + Width(w + 4). + Render(strings.Join(lines, "\n")) +} + +func padRight(s string, w int) string { + for lipgloss.Width(s) < w { + s += " " + } + return s +} + +func formatSize(size int64) string { + const unit = 1024 + if size < unit { + return fmt.Sprintf("%4dB", size) + } + div, exp := int64(unit), 0 + for n := size / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%3.0f%c", float64(size)/float64(div), "KMGTPE"[exp]) +} + +func shortFilename(path string) string { + if path == "" { + return "(unsaved)" + } + for i := len(path) - 1; i >= 0; i-- { + if path[i] == '/' || path[i] == '\\' { + return path[i+1:] + } + } + return path +} |
