Skip to content

Commit

Permalink
Code improvements and fixing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
esimov committed Jul 8, 2024
1 parent 5bd6697 commit f9f78ac
Show file tree
Hide file tree
Showing 10 changed files with 216 additions and 198 deletions.
8 changes: 2 additions & 6 deletions color/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,9 @@ func StringFormatBoth(fg, bg int, str string, args []string) string {
return fmt.Sprintf("\x1b[48;5;%dm\x1b[38;5;%d;%sm%s\x1b[0m", bg, fg, strings.Join(args, ";"), str)
}

// StringRandom returns a random colored string.
func StringRandom(str string) string {
return String(Random(180, 231), str)
}

// Random color number.
func Random(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
src := rand.NewSource(time.Now().UnixNano())
rand := rand.New(src)
return rand.Intn(max-min) + min
}
10 changes: 6 additions & 4 deletions io/diagrams.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package io

import (
"io/ioutil"
"log"
"fmt"
"os"
"path/filepath"
)

Expand All @@ -12,13 +12,15 @@ func ListDiagrams(dir string) ([]string, error) {

cwd, err := filepath.Abs(filepath.Dir(""))
if err != nil {
log.Fatal(err)
return nil, fmt.Errorf("could not return the current working directory: %w", err)
}

path := cwd + dir
files, err := ioutil.ReadDir(path)
files, err := os.ReadDir(path)
if err != nil {
return nil, err
}

for _, file := range files {
diagrams = append(diagrams, file.Name())
}
Expand Down
47 changes: 19 additions & 28 deletions io/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,58 @@ package io

import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)

// ReadFile read the input file.
func ReadFile(input string) []byte {
b, err := ioutil.ReadFile(input)
func ReadFile(input string) ([]byte, error) {
b, err := os.ReadFile(input)
if err != nil {
return nil
return nil, fmt.Errorf("error reading the file: %w", err)
}
return b
return b, nil
}

// SaveFile saves the diagram into the output directory.
func SaveFile(fileName string, output string, data string) (*os.File, error) {
var file *os.File

cwd, err := filepath.Abs(filepath.Dir(""))
if err != nil {
log.Fatal(err)
}
cwd, _ := filepath.Abs(filepath.Dir(""))

filePath := cwd + output
// Check if output directory does not exits. In this case create it.
// Check if the output directory does not exits. In this case create it.
if _, err := os.Stat(filePath); os.IsNotExist(err) {
os.Mkdir(filePath, os.ModePerm)
}

// Create the output file.
file, err = os.Create(filepath.Join(filePath, fileName))
if isError(err) {
return nil, err
file, err := os.Create(filepath.Join(filePath, fileName))
if err != nil {
return nil, fmt.Errorf("error creating the file: %w", err)
}
defer file.Close()

file, err = os.OpenFile(filepath.Join(filePath, fileName), os.O_RDWR, 0644)
if isError(err) {
return nil, err
if err != nil {
return nil, fmt.Errorf("error opening the file: %w", err)
}

defer file.Close()

_, err = file.WriteString(data)
if isError(err) {
if err != nil {
return nil, err
}

return file, nil
}

// DeleteDiagram deletes a diagram.
func DeleteDiagram(fileName string) error {
err := os.Remove(fileName)
if isError(err) {
return err
}
return nil
}

// isError ia a generic function to check for errors.
func isError(err error) bool {
if err != nil {
fmt.Errorf("Could not save file: %v", err.Error())
return fmt.Errorf("failed deleting the diagram: %w", err)
}
return (err != nil)

return nil
}
11 changes: 7 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Package Diagram is a Go package to generate hand drawn diagrams from ASCII arts.
// Diagram is a Go library to generate hand drawn diagrams from ASCII arts.
//
// It's a full featured CLI application which converts the ASCII text into hand drawn diagrams.
package main
Expand Down Expand Up @@ -51,9 +51,12 @@ func main() {

// In case the option parameters are used, the hand-drawn diagrams are generated without to enter into the CLI app.
if (*source != "") && (*destination != "") {
input := string(io.ReadFile(*source))
input, err := io.ReadFile("sample.txt")
if err != nil {
log.Fatalf("error reading the sample file: %v", err)
}

err := canvas.DrawDiagram(input, *destination, *fontPath)
err = canvas.DrawDiagram(string(input), *destination, *fontPath)
if err != nil {
log.Fatal("Error on converting the ascii art to hand drawn diagrams!")
} else if *preview {
Expand All @@ -67,7 +70,7 @@ func main() {
log.Fatalf("Failed to read image '%s': %v\n", *destination, err)
}

gui := gui.NewGUI(source, "ASCII diagram preview")
gui := gui.NewGUI(source, "Diagram preview")

if err := gui.Draw(); err != nil {
log.Fatalf("diagram GUI draw error: %v", err)
Expand Down
4 changes: 2 additions & 2 deletions ui/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ func (ui *UI) log(message string, isError bool) error {
} else {
message = decorate(message, "green")
}
return ui.writeContent(LOG_PANEL, message)
return ui.writeContent(logPanel, message)
}

// clearLog clears the log message.
func (ui *UI) clearLog() error {
return ui.writeContent(LOG_PANEL, "")
return ui.writeContent(logPanel, "")
}
2 changes: 1 addition & 1 deletion ui/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (e *editor) Edit(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier)
maxY := strings.Count(v.ViewBuffer(), "\n") - 1
v.SetCursor(maxX, maxY)
case gocui.KeyCtrlX:
if v.Name() == DIAGRAM_PANEL {
if v.Name() == editorPanel {
cache = []byte(v.ViewBuffer())
e.ui.ClearView(v.Name())
v.SetCursor(0, 0)
Expand Down
60 changes: 38 additions & 22 deletions ui/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package ui
import (
"bytes"
"fmt"
"log"
"path/filepath"
"runtime"
"text/tabwriter"
"time"

"github.com/esimov/diagram/io"
"github.com/jroimartin/gocui"
Expand Down Expand Up @@ -35,8 +35,8 @@ var keyHandlers = &handlers{
*getDeleteHandler(),
{nil, gocui.KeyCtrlX, "Ctrl+x", "Clear editor content", nil},
{nil, gocui.KeyCtrlZ, "Ctrl+z", "Restore editor content", nil},
{nil, gocui.KeyCtrlS, "Ctrl+s", "Save diagram", onSaveDiagram},
{nil, gocui.KeyCtrlD, "Ctrl+d", "Draw diagram", onDrawDiagram},
{nil, gocui.KeyCtrlS, "Ctrl+s", "Save diagram", onDiagramSave},
{nil, gocui.KeyCtrlG, "Ctrl+p", "Generate diagram", onDiagramGenerate},
{nil, gocui.KeyCtrlQ, "Ctrl+q", "Quit", onQuit},
}

Expand Down Expand Up @@ -69,17 +69,17 @@ func onQuit(ui *UI, wrap bool) Fn {
}
}

// onSaveDiagram is an event listener which get triggered when a save action is performed.
func onSaveDiagram(ui *UI, wrap bool) Fn {
// onDiagramSave is an event listener which get triggered when a save action is performed.
func onDiagramSave(ui *UI, wrap bool) Fn {
return func(*gocui.Gui, *gocui.View) error {
return ui.saveDiagram(DIAGRAM_PANEL)
return ui.saveDiagram(editorPanel)
}
}

// onDrawDiagram is an event listener which get triggered when a draw action is performed.
func onDrawDiagram(ui *UI, wrap bool) Fn {
// onDiagramGenerate is an event listener which get triggered when a draw action is performed.
func onDiagramGenerate(ui *UI, wrap bool) Fn {
return func(*gocui.Gui, *gocui.View) error {
return ui.drawDiagram(DIAGRAM_PANEL)
return ui.generateDiagram(editorPanel)
}
}

Expand All @@ -105,7 +105,7 @@ func (handlers handlers) ApplyKeyBindings(ui *UI, g *gocui.Gui) error {
if cy < ui.getViewTotalRows(v)-1 {
v.SetCursor(cx, cy+1)
}
ui.modifyView(DIAGRAM_PANEL)
ui.modifyView(editorPanel)
return nil
}
onUp := func(g *gocui.Gui, v *gocui.View) error {
Expand All @@ -114,52 +114,68 @@ func (handlers handlers) ApplyKeyBindings(ui *UI, g *gocui.Gui) error {
if cy > 0 {
v.SetCursor(cx, cy-1)
}
ui.modifyView(DIAGRAM_PANEL)
ui.modifyView(editorPanel)
return nil
}
onDelete := func(g *gocui.Gui, v *gocui.View) error {
if ui.logTimer != nil {
ui.logTimer.Stop()
}

cx, cy := v.Cursor()
cv, err := ui.gui.View(SAVED_DIAGRAMS_PANEL)
cv, err := ui.gui.View(savedDiagramsPanel)
if err != nil {
return err
}
cwd, err := filepath.Abs(filepath.Dir(""))
if err != nil {
log.Fatal(err)
return err
}
currentFile = ui.getViewRow(cv, cy)[0]
fn := cwd + "/" + DIAGRAMS_DIR + "/" + currentFile
fn := fmt.Sprintf("%s/%s/%s", cwd, mainDir, currentFile)

io.DeleteDiagram(fn)
ui.updateDiagramList(SAVED_DIAGRAMS_PANEL)
err = io.DeleteDiagram(fn)
if err != nil {
return err
}
ui.log(fmt.Sprintf("The file %s has been deleted successfully from the %s directory", currentFile, cwd), false)
ui.updateDiagramList(savedDiagramsPanel)

if cy > 0 {
v.SetCursor(cx, cy-1)
}
ui.modifyView(DIAGRAM_PANEL)
ui.modifyView(editorPanel)

// Hide log message after 4 seconds
ui.logTimer = time.AfterFunc(4*time.Second, func() {
ui.gui.Update(func(*gocui.Gui) error {
return ui.clearLog()
})
})

return nil
}

if err := g.SetKeybinding(SAVED_DIAGRAMS_PANEL, gocui.KeyArrowDown, gocui.ModNone, onDown); err != nil {
if err := g.SetKeybinding(savedDiagramsPanel, gocui.KeyArrowDown, gocui.ModNone, onDown); err != nil {
return err
}

if err := g.SetKeybinding(SAVED_DIAGRAMS_PANEL, gocui.KeyArrowUp, gocui.ModNone, onUp); err != nil {
if err := g.SetKeybinding(savedDiagramsPanel, gocui.KeyArrowUp, gocui.ModNone, onUp); err != nil {
return err
}

if runtime.GOOS == "darwin" {
if err := g.SetKeybinding(SAVED_DIAGRAMS_PANEL, gocui.KeyBackspace2, gocui.ModNone, onDelete); err != nil {
if err := g.SetKeybinding(savedDiagramsPanel, gocui.KeyBackspace2, gocui.ModNone, onDelete); err != nil {
return err
}
} else {
if err := g.SetKeybinding(SAVED_DIAGRAMS_PANEL, gocui.KeyDelete, gocui.ModNone, onDelete); err != nil {
if err := g.SetKeybinding(savedDiagramsPanel, gocui.KeyDelete, gocui.ModNone, onDelete); err != nil {
return err
}
}

return g.SetKeybinding("", gocui.KeyCtrlH, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error {
return ui.toggleHelp(g, handlers.HelpContent())
return ui.toggleHelp(handlers.HelpContent())
})
}

Expand Down
Loading

0 comments on commit f9f78ac

Please sign in to comment.