Skip to content

Commit

Permalink
Fix editor
Browse files Browse the repository at this point in the history
  • Loading branch information
bahner committed Mar 16, 2024
1 parent 0221fd0 commit 95c667f
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 57 deletions.
2 changes: 1 addition & 1 deletion config/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

const (
defaultLocation string = "did:ma:k2k4r8lprgw7fl8inpau5d05mnhw2cq5srex1rihptz0bbg8fzu7b5mm#pong"
defaultLocation string = "did:ma:k2k4r8p5sxlnznc9ral4fueapazs36hqoj3go1g0o7662gnk9skhfrik#pong"
fakeActorIdentity string = "NO_DEFAULT_ACTOR_IDENITY"
)

Expand Down
6 changes: 5 additions & 1 deletion config/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,11 @@ func generatePongConfigFile(identity string, node string) {
},
"mode": map[string]interface{}{
"pong": map[string]interface{}{
"reply": DEFAULT_PONG_REPLY,
"reply": PongReply(),
"fortune": map[string]interface{}{
"enable": PongFortuneMode(),
"args": PongFortuneArgs(),
},
},
},
}
Expand Down
7 changes: 6 additions & 1 deletion config/mode.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
const (
DEFAULT_PONG_REPLY = "Pong!"
DEFAULT_PONG_FORTUNE_MODE = false
DEFAULT_PONG_FORTUNE_ARGS = "-s"

defaultPongMode = false
defaultRelayMode = false
Expand Down Expand Up @@ -74,5 +75,9 @@ func Mode() string {
}

func PongFortuneMode() bool {
return viper.GetBool("mode.pong.fortune") && PongMode()
return viper.GetBool("mode.pong.fortune.enable") && PongMode()
}

func PongFortuneArgs() string {
return viper.GetString("mode.pong.fortune.args")
}
27 changes: 17 additions & 10 deletions mode/pong/reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,29 @@ import (
"github.com/spf13/viper"
)

var (
replyBytes = []byte(viper.GetString("mode.pong.reply"))
angryBytes = []byte(fmt.Sprintf("I'm doing the %s here! 😤", replyBytes))
fortuneArgs = []string{"-s"}
)
var fortuneArgs = []string{"-o"}

func reply(m *msg.Message) []byte {
if string(m.Content) == string(replyBytes) {
return angryBytes

if string(m.Content) == string(replyBytes()) {
return angryBytes()
}

if config.PongFortuneMode() {
return getFortuneCookie(fortuneArgs)
}

return replyBytes
return replyBytes()
}

func replyBytes() []byte {
replyMsg := viper.GetString("mode.pong.reply")
return []byte(replyMsg)
}

func angryBytes() []byte {
replyMsg := viper.GetString("mode.pong.reply")
return []byte(fmt.Sprintf("I'm doing the %s here! 😤", replyMsg))
}

// Returns a fortune cookie if the pong-fortune mode is enabled, otherwise the default reply.
Expand All @@ -35,7 +42,7 @@ func getFortuneCookie(args []string) []byte {
_, err := exec.LookPath("fortune")
if err != nil {
log.Errorf("fortune command not found: %s", err)
return replyBytes
return replyBytes()
}

// Prepare the command with any arguments passed
Expand All @@ -47,7 +54,7 @@ func getFortuneCookie(args []string) []byte {
err = cmd.Run()
if err != nil {
log.Errorf("error running fortune command: %s", err)
return replyBytes
return replyBytes()
}

return out.Bytes()
Expand Down
13 changes: 8 additions & 5 deletions mode/pong/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,21 @@ import (

func init() {
pflag.String("pong-reply", config.DEFAULT_PONG_REPLY, "The message to send back to the sender")

viper.BindPFlag("mode.pong.reply", pflag.Lookup("pong-reply"))
viper.SetDefault("mode.pong.reply", config.DEFAULT_PONG_REPLY)

viper.BindPFlag("mode.pong.fortune.enable", pflag.Lookup("pong-fortune"))
viper.SetDefault("mode.pong.fortune.enable", config.DEFAULT_PONG_FORTUNE_MODE)

viper.SetDefault("mode.pong.fortune.args", config.DEFAULT_PONG_FORTUNE_ARGS)
}

// Run the pong actor. Cancel it from outside to stop it.
func Run(a *actor.Actor, p *p2p.P2P) {

ctx := context.Background()

viper.BindPFlag("mode.pong.reply", pflag.Lookup("pong-reply"))
viper.SetDefault("mode.pong.reply", config.DEFAULT_PONG_REPLY)
viper.BindPFlag("mode.pong.fortune", pflag.Lookup("pong-fortune"))
viper.SetDefault("mode.pong.fortune", config.DEFAULT_PONG_FORTUNE_MODE)

fmt.Printf("Starting pong mode as %s\n", a.Entity.DID.Id)
go p.StartDiscoveryLoop(ctx)
fmt.Println("Discovery loop started.")
Expand Down
2 changes: 0 additions & 2 deletions ui/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ func (ui *ChatUI) handleCommands(input string) {
switch args[0] {
case "/broadcast":
ui.handleBroadcastCommand(args)
case "/edit":
ui.handleEditCommand()
case "/enter":
ui.handleEnterCommand(args)
case "/entity":
Expand Down
57 changes: 33 additions & 24 deletions ui/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ package ui

import (
"bytes"
"errors"
"os"
"os/exec"

"github.com/bahner/go-ma-actor/config"
log "github.com/sirupsen/logrus"
)

const editorUsage = "'"
const editorHelp = "Opens the default editor to edit a message"

var ErrEmptyEdit = errors.New("empty edit")

func (ui *ChatUI) invokeEditor() ([]byte, error) {
tmpfile, err := os.CreateTemp("", "edit")
if err != nil {
Expand All @@ -18,58 +24,61 @@ func (ui *ChatUI) invokeEditor() ([]byte, error) {

var editorErr error
var contents []byte

// Use Suspend to stop the TUI and run the external editor
ui.app.Suspend(func() {
// Launch external editor
cmd := exec.Command(config.GetEditor(), tmpfile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
editorErr = cmd.Run() // This will wait until the editor is closed
if editorErr != nil {
return
}

if editorErr == nil {
// Read the file only if there was no error with the editor
contents, editorErr = os.ReadFile(tmpfile.Name())
// Check if the file was modified by comparing modification times
fi, err := os.Stat(tmpfile.Name())
if err != nil {
editorErr = err
return
}

if fi.Size() == 0 {
editorErr = ErrEmptyEdit
return
}

contents, editorErr = os.ReadFile(tmpfile.Name())
})

// Check if there was an error with the editor or reading the file
if editorErr != nil {
return nil, editorErr
}

if contents == nil {
// It's unusual for contents to be nil without an error, but handle gracefully
return nil, ErrEmptyEdit
}

// Remove newlies, We want this to be a single line
// Trim right to remove trailing newlines
contents = bytes.TrimRight(contents, "\n")
// Replace all newlines with spaces (or another character if preferred)
contents = bytes.ReplaceAll(contents, []byte("\n"), []byte(separator))

// // Replace all newlines with spaces (or another character if preferred)
// contents = bytes.ReplaceAll(contents, []byte("\n"), []byte(separator))

// Append a single newline at the end if desired
contents = append(contents, '\n')

return contents, nil
}

func (ui *ChatUI) handleEditCommand() {
func (ui *ChatUI) handleEditorCommand() {

m, err := ui.invokeEditor()
if err != nil {
ui.displaySystemMessage("Error invoking editor: " + err.Error())
return
}

if len(m) == 0 {
ui.displaySystemMessage("No changes made")
ui.displaySystemMessage("editor: " + err.Error())
return
}

log.Debugf("Editor returned: %s", m)

ui.app.QueueUpdateDraw(func() {
ui.inputField = ui.setupInputField()
ui.updateRoot()
ui.inputField.SetText(string(m))
ui.app.SetFocus(ui.inputField)
})
ui.chInput <- string(m)

log.Debug("Editor command handled")

Expand Down
25 changes: 12 additions & 13 deletions ui/entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ func (ui *ChatUI) handleEntityListCommand(args []string) {
} else {
ui.displaySystemMessage("No entities found")
}
} else {
ui.handleHelpCommand(entityListUsage, entityListHelp)
return
}
ui.handleHelpCommand(entityListUsage, entityListHelp)

}

Expand All @@ -104,10 +104,8 @@ func (ui *ChatUI) handleEntityNickCommand(args []string) {
ui.msgBox.SetTitle(nick)
}
ui.displaySystemMessage(e.DID.Id + aliasSeparator + e.Nick)
} else {
ui.handleHelpCommand(entityNickUsage, entityNickHelp)
return
}

ui.handleHelpCommand(entityNickUsage, entityNickHelp)
}

Expand All @@ -123,9 +121,9 @@ func (ui *ChatUI) handleEntityShowCommand(args []string) {
}
entityInfo := fmt.Sprintf(e.DID.Id + aliasSeparator + e.Nick)
ui.displaySystemMessage(entityInfo)
} else {
ui.handleHelpCommand(entityShowUsage, entityShowHelp)
return
}
ui.handleHelpCommand(entityShowUsage, entityShowHelp)

}

Expand All @@ -137,9 +135,9 @@ func (ui *ChatUI) handleEntityRemoveCommand(args []string) {
id = entity.Lookup(id)
entity.RemoveNick(id)
ui.displaySystemMessage("Nick removed for " + id + " if it existed")
} else {
ui.handleHelpCommand(entityRemoveUsage, entityRemoveHelp)
return
}
ui.handleHelpCommand(entityRemoveUsage, entityRemoveHelp)

}

Expand All @@ -160,9 +158,9 @@ func (ui *ChatUI) handleEntityConnectCommand(args []string) {
return
}
ui.displaySystemMessage("Connected to " + id + aliasSeparator + pai.ID.String())
} else {
ui.handleHelpCommand(entityConnectUsage, entityConnectHelp)
return
}
ui.handleHelpCommand(entityConnectUsage, entityConnectHelp)
}

func (ui *ChatUI) handleEntityResolveCommand(args []string) {
Expand Down Expand Up @@ -194,8 +192,9 @@ func (ui *ChatUI) handleEntityResolveCommand(args []string) {
ui.displaySystemMessage("Resolved DID Document for " + e.DID.Id + " (CID: " + c.String() + ")")
e.Doc = d

} else {
ui.handleHelpCommand(entityResolveUsage, entityResolveHelp)
return

}
ui.handleHelpCommand(entityResolveUsage, entityResolveHelp)

}
10 changes: 10 additions & 0 deletions ui/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ func (ui *ChatUI) handleEvents() {

input = strings.TrimSpace(input)

if input == "" {
ui.handleEditorCommand()
continue
}

if strings.HasPrefix(input, "/") {
log.Debug("handleEvents got command: ", input)
ui.handleCommands(input)
Expand All @@ -49,6 +54,11 @@ func (ui *ChatUI) handleEvents() {
ui.handleMsgCommand(input)
continue
}
if strings.HasPrefix(input, "'") {
log.Debug("handleEvents got command: ", input)
ui.handleEditorCommand()
continue
}
ui.handleChatMessage(input)

case m := <-ui.chMessages:
Expand Down
6 changes: 6 additions & 0 deletions ui/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ func (ui *ChatUI) handleHelpCommands(args []string) {
ui.displayHelpText(helpText)
ui.displaySystemMessage("")
ui.displaySystemMessage("Available commands:")
ui.displaySystemMessage("/help @")
ui.displaySystemMessage("/help '")
ui.displaySystemMessage("/help broadcast")
ui.displaySystemMessage("/help enter")
ui.displaySystemMessage("/help entity")
Expand All @@ -54,6 +56,10 @@ func (ui *ChatUI) handleHelpCommands(args []string) {
ui.displaySystemMessage("/help")
} else {
switch args[1] {
case "@":
ui.handleHelpCommand(msgUsage, msgHelp)
case "'":
ui.handleHelpCommand(editorUsage, editorHelp)
case "broadcast":
ui.handleHelpCommand(broadcastUsage, broadcastHelp)
case "enter":
Expand Down

0 comments on commit 95c667f

Please sign in to comment.