x-1/state.go

118 lines
2.1 KiB
Go
Raw Normal View History

2024-01-03 15:29:40 +00:00
package main
import (
2024-01-24 05:42:18 +00:00
"bytes"
"errors"
2024-02-16 16:44:52 +00:00
"fmt"
2024-01-03 15:29:40 +00:00
"net/url"
2024-01-24 05:42:18 +00:00
"os"
"os/exec"
2024-01-03 15:29:40 +00:00
2024-02-16 16:44:52 +00:00
"github.com/charmbracelet/lipgloss"
2024-01-03 15:29:40 +00:00
"github.com/chzyer/readline"
)
type BrowserState struct {
*History
2024-01-17 15:55:42 +00:00
*Config
2024-01-03 15:29:40 +00:00
2024-01-03 19:17:37 +00:00
Modal []byte
Marks map[string]string
2024-01-08 18:10:24 +00:00
Identities Identities
2024-01-03 19:17:37 +00:00
NamedTours map[string]*Tour
DefaultTour Tour
CurrentTour *Tour
2024-01-03 15:29:40 +00:00
Readline *readline.Instance
2024-01-24 05:42:18 +00:00
Printer Printer
2024-01-03 15:29:40 +00:00
}
type History struct {
Url *url.URL
Depth int
DocType string
Body []byte
Formatted string
Links []Link
Back *History
Forward *History
// Non-negative if we browsed here via a page link, else -1.
//
// The non-negative value is the index in the "back" page's
// list of links that got us here.
NavIndex int
}
type Link struct {
Text string
Target *url.URL
Prompt bool
2024-01-03 15:29:40 +00:00
}
2024-01-08 18:10:24 +00:00
func NewBrowserState(conf *Config) *BrowserState {
2024-01-03 19:17:37 +00:00
state := &BrowserState{
2024-01-03 15:29:40 +00:00
History: &History{
Url: nil,
Depth: 0,
NavIndex: -1,
},
2024-01-17 15:55:42 +00:00
Config: conf,
2024-01-03 15:29:40 +00:00
}
2024-01-03 19:17:37 +00:00
state.CurrentTour = &state.DefaultTour
return state
2024-01-03 15:29:40 +00:00
}
2024-01-24 05:42:18 +00:00
type Printer interface {
PrintModal(*BrowserState, []byte) error
PrintPage(*BrowserState, string) error
2024-02-16 16:44:52 +00:00
PrintError(string) error
2024-01-24 05:42:18 +00:00
}
type PromptPrinter struct{}
2024-02-16 16:44:52 +00:00
func (PromptPrinter) PrintModal(state *BrowserState, contents []byte) error {
2024-01-24 05:42:18 +00:00
_, err := os.Stdout.Write(contents)
return err
}
2024-02-16 16:44:52 +00:00
func (PromptPrinter) PrintPage(state *BrowserState, body string) error {
2024-01-24 05:42:18 +00:00
if state.Quiet {
return nil
}
lessarg := []string{}
switch state.Pager {
case "auto":
lessarg = []string{"-F"}
fallthrough
case "always":
less, err := exec.LookPath("less")
if err != nil {
return err
}
cmd := exec.Command(less, lessarg...)
cmd.Stdin = bytes.NewBufferString(body)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
case "never":
_, err := os.Stdout.WriteString(body)
return err
default:
return errors.New("invalid 'pager' value in configuration")
}
}
2024-02-16 16:44:52 +00:00
var promptErrorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("196")).Bold(true)
func (PromptPrinter) PrintError(msg string) error {
_, err := fmt.Println(promptErrorStyle.Render(msg))
return err
}