From da45f627e09079eadbf7f14d3539380c7c5a8458 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Mon, 9 Sep 2019 19:35:16 -0700 Subject: [PATCH 01/25] Initial v2 commit, deep in restructuring... maybe not for the better? --- bookmarks.go | 68 ++++ client.go | 541 +++++++++++++++++++++++++++++ footbar.go | 54 +++ gopher/gopher.go | 2 +- gopher/open_browser_darwin.go | 2 +- gopher/open_browser_linux.go | 2 +- gopher/open_browser_other.go | 2 +- gopher/open_browser_windows.go | 2 +- headbar.go | 47 +++ main.go | 606 +++++++-------------------------- page.go | 30 ++ pages.go | 54 +++ url.go | 107 ++++++ 13 files changed, 1026 insertions(+), 491 deletions(-) create mode 100644 bookmarks.go create mode 100644 client.go create mode 100644 footbar.go create mode 100644 headbar.go create mode 100644 page.go create mode 100644 pages.go create mode 100644 url.go diff --git a/bookmarks.go b/bookmarks.go new file mode 100644 index 0000000..3b044fd --- /dev/null +++ b/bookmarks.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" +) + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Bookmarks struct { + IsOpen bool + IsFocused bool + Position int + Length int + Titles []string + Links []string +} + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +func (b *Bookmarks) Add([]string) error { + // TODO add a bookmark + return fmt.Errorf("") +} + +func (b *Bookmarks) Delete(int) error { + // TODO delete a bookmark + return fmt.Errorf("") +} + +func (b *Bookmarks) ToggleOpen() { + b.IsOpen = !b.IsOpen + if b.IsOpen { + b.IsFocused = true + } else { + b.IsFocused = false + } +} + +func (b *Bookmarks) ToggleFocused() { + if b.IsOpen { + b.IsFocused = !b.IsFocused + } +} + +func (b *Bookmarks) IniDump() string { + // TODO create dump of values for INI file + return "" +} + +func (b *Bookmarks) Render() ([]string, error) { + // TODO grab all of the bookmarks as a fixed + // width string including border and spacing + return []string{}, fmt.Errorf("") +} + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakeBookmarks() Bookmarks { + return Bookmarks{false, false, 0, 0, make([]string, 0), make([]string, 0)} +} + diff --git a/client.go b/client.go new file mode 100644 index 0000000..8c2bdc0 --- /dev/null +++ b/client.go @@ -0,0 +1,541 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net" + "os" + "os/exec" + "os/user" + "regexp" + "strconv" + "strings" + "time" + + "tildegit.org/sloum/bombadillo/cmdparse" + "tildegit.org/sloum/bombadillo/cui" + "tildegit.org/sloum/bombadillo/gopher" +) + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type client struct { + Height int + Width int + Options map[string]string + Message string + PageState Pages + BookMarks Bookmarks + TopBar Headbar + FootBar Footbar +} + + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +func (c *client) GetSize() { + for { + redraw := false + cmd := exec.Command("stty", "size") + cmd.Stdin = os.Stdin + out, err := cmd.Output() + if err != nil { + fmt.Println("Fatal error: Unable to retrieve terminal size") + os.Exit(5) + } + var h, w int + fmt.Sscan(string(out), &h, &w) + if h != c.Height || w != c.Width { + redraw = true + } + + c.Height = h + c.Width = w + + if redraw { + c.Draw() + } + + time.Sleep(1 * time.Second) + } +} + +func (c *client) Draw() { + // TODO build this out. + // It should call all of the renders + // and add them to the a string buffer + // It should then print the buffer +} + +func (c *client) TakeControlInput() { + input := cui.Getch() + + switch input { + case 'j', 'J': + // scroll down one line + c.Scroll(1) + case 'k', 'K': + // scroll up one line + c.Scroll(-1) + case 'q', 'Q': + // quite bombadillo + cui.Exit() + case 'g': + // scroll to top + c.Scroll(-len(c.PageState.History[c.PageState.Position].WrappedContent)) + case 'G': + // scroll to bottom + c.Scroll(len(c.PageState.History[c.PageState.Position].WrappedContent)) + case 'd': + // scroll down 75% + distance := c.Height - c.Height / 4 + c.Scroll(distance) + case 'u': + // scroll up 75% + distance := c.Height - c.Height / 4 + c.Scroll(-distance) + case 'b': + // go back + err := c.PageState.NavigateHistory(-1) + if err != nil { + c.SetMessage(err.Error(), false) + c.DrawMessage() + } else { + c.Draw() + } + case 'B': + // open the bookmarks browser + c.BookMarks.ToggleOpen() + c.Draw() + case 'f', 'F': + // go forward + err := c.PageState.NavigateHistory(1) + if err != nil { + c.SetMessage(err.Error(), false) + c.DrawMessage() + } else { + c.Draw() + } + case '\t': + // Toggle bookmark browser focus on/off + c.BookMarks.ToggleFocused() + c.Draw() + case ':', ' ': + // Process a command + c.ClearMessage() + c.ClearMessageLine() + entry, err := cui.GetLine() + c.ClearMessageLine() + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + break + } else if strings.TrimSpace(entry) == "" { + break + } + + parser := cmdparse.NewParser(strings.NewReader(entry)) + p, err := parser.Parse() + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + } else { + err := c.routeCommandInput(p) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + } + } + } +} + + +func (c *client) routeCommandInput(com *cmdparse.Command) error { + var err error + switch com.Type { + case cmdparse.SIMPLE: + c.simpleCommand(com.Action) + case cmdparse.GOURL: + c.goToURL(com.Target) + case cmdparse.GOLINK: + c.goToLink(com.Target) + case cmdparse.DO: + c.doCommand(com.Action, com.Value) + case cmdparse.DOLINK: + // err = doLinkCommand(com.Action, com.Target) + case cmdparse.DOAS: + c.doCommandAs(com.Action, com.Value) + case cmdparse.DOLINKAS: + // err = doLinkCommandAs(com.Action, com.Target, com.Value) + default: + return fmt.Errorf("Unknown command entry!") + } + + return err +} + +func (c *client) simpleCommand(action string) { + action = strings.ToUpper(action) + switch action { + case "Q", "QUIT": + cui.Exit() + case "H", "HOME": + if c.Options["homeurl"] != "unset" { + go c.Visit(c.Options["homeurl"]) + } else { + c.SetMessage(fmt.Sprintf("No home address has been set"), false) + c.DrawMessage() + } + case "B", "BOOKMARKS": + c.BookMarks.ToggleOpen() + case "SEARCH": + c.search() + case "HELP", "?": + go c.Visit(helplocation) + default: + c.SetMessage(fmt.Sprintf("Unknown action %q", action), true) + c.DrawMessage() + } +} + +func (c *client) doCommand(action string, values []string) { + if length := len(values); length != 1 { + c.SetMessage(fmt.Sprintf("Expected 1 argument, received %d", len(values)), true) + c.DrawMessage() + return + } + + switch action { + case "CHECK", "C": + c.displayConfigValue(values[0]) + default: + c.SetMessage(fmt.Sprintf("Unknown action %q", action), true) + c.DrawMessage() + } +} + +func (c *client) doCommandAs(action string, values []string) { + if len(values) < 2 { + c.SetMessage(fmt.Sprintf("Expected 1 argument, received %d", len(values)), true) + c.DrawMessage() + return + } + + if values[0] == "." { + values[0] = c.PageState.History[c.PageState.Position].Location.Full + } + + switch action { + case "ADD", "A": + err := c.BookMarks.Add(values) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + + err = saveConfig() + if err != nil { + c.SetMessage("Error saving bookmark to file", true) + c.DrawMessage() + } + if c.BookMarks.IsOpen { + c.Draw() + } + + case "WRITE", "W": + // TODO figure out how best to handle file + // writing... it will depend on request model + // using fetch would be best + // - - - - - - - - - - - - - - - - - - - - - + // var data []byte + // if values[0] == "." { + // d, err := c.getCurrentPageRawData() + // if err != nil { + // c.SetMessage(err.Error(), true) + // c.DrawMessage() + // return + // } + // data = []byte(d) + // } + // fp, err := c.saveFile(data, strings.Join(values[1:], " ")) + // if err != nil { + // c.SetMessage(err.Error(), true) + // c.DrawMessage() + // return + // } + // c.SetMessage(fmt.Sprintf("File saved to: %s", fp), false) + // c.DrawMessage() + + case "SET", "S": + if _, ok := c.Options[values[0]]; ok { + c.Options[values[0]] = strings.Join(values[1:], " ") + err := saveConfig() + if err != nil { + c.SetMessage("Value set, but error saving config to file", true) + c.DrawMessage() + } else { + c.SetMessage(fmt.Sprintf("%s is now set to %q", values[0], c.Options[values[0]]), true) + c.DrawMessage() + } + return + } + c.SetMessage(fmt.Sprintf("Unable to set %s, it does not exist", values[0]), true) + c.DrawMessage() + return + } + c.SetMessage(fmt.Sprintf("Unknown command structure"), true) +} + +func (c *client) getCurrentPageUrl() (string, error) { + if c.PageState.Length < 1 { + return "", fmt.Errorf("There are no pages in history") + } + return c.PageState.History[c.PageState.Position].Location.Full, nil +} + +func (c *client) getCurrentPageRawData() (string, error) { + if c.PageState.Length < 1 { + return "", fmt.Errorf("There are no pages in history") + } + return c.PageState.History[c.PageState.Position].RawContent, nil +} + +func (c *client) saveFile(data []byte, name string) (string, error) { + savePath := c.Options["savelocation"] + name + err := ioutil.WriteFile(savePath, data, 0644) + if err != nil { + return "", err + } + + return savePath, nil +} + +func (c *client) search() { + c.ClearMessage() + c.ClearMessageLine() + fmt.Print("?") + entry, err := cui.GetLine() + c.ClearMessageLine() + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } else if strings.TrimSpace(entry) == "" { + return + } + u, err := MakeUrl(c.Options["searchurl"]) + if err != nil { + c.SetMessage("'searchurl' is not set to a valid url", true) + c.DrawMessage() + return + } + switch u.Scheme { + case "gopher": + go c.Visit(fmt.Sprintf("%s\t%s",u.Full,entry)) + case "gemini": + // TODO url escape the entry variable + escapedEntry := entry + go c.Visit(fmt.Sprintf("%s?%s",u.Full,escapedEntry)) + case "http", "https": + c.SetMessage("Attempting to open in web browser", false) + c.DrawMessage() + err := gopher.OpenBrowser(u.Full) + if err != nil { + c.SetMessage(err.Error(), true) + } else { + c.SetMessage("Opened in web browser", false) + } + c.DrawMessage() + default: + c.SetMessage(fmt.Sprintf("%q is not a supported protocol", u.Scheme), true) + c.DrawMessage() + } +} + +func (c *client) Scroll(amount int) { + page := c.PageState.History[c.PageState.Position] + bottom := len(page.WrappedContent) - c.Height + if amount < 0 && page.ScrollPosition == 0 { + c.SetMessage("You are already at the top", false) + c.DrawMessage() + fmt.Print("\a") + return + } else if amount > 0 && page.ScrollPosition == bottom || bottom < 0 { + c.SetMessage("You are already at the bottom", false) + c.DrawMessage() + fmt.Print("\a") + return + } + + newScrollPosition := page.ScrollPosition + amount + if newScrollPosition < 0 { + newScrollPosition = 0 + } else if newScrollPosition > bottom { + newScrollPosition = bottom + } + + page.ScrollPosition = newScrollPosition + c.Draw() +} + +func (c *client) displayConfigValue(setting string) { + if val, ok := c.Options[setting]; ok { + c.SetMessage(fmt.Sprintf("%s is set to: %q", setting, val), false) + c.DrawMessage() + } else { + c.SetMessage(fmt.Sprintf("Invalid: %q does not exist", setting), true) + c.DrawMessage() + } +} + +func (c *client) SetMessage(msg string, isError bool) { + leadIn, leadOut := "", "" + if isError { + leadIn = "\033[31m" + leadOut = "\033[0m" + } + + c.Message = fmt.Sprintf("%s%s%s", leadIn, msg, leadOut) +} + +func (c *client) DrawMessage() { + c.ClearMessageLine() + cui.MoveCursorTo(c.Height-1, 0) + fmt.Print(c.Message) +} + +func (c *client) ClearMessage() { + c.Message = "" +} + +func (c *client) ClearMessageLine() { + cui.MoveCursorTo(c.Height-1, 0) + cui.Clear("line") +} + +func (c *client) goToURL(u string) { + if num, _ := regexp.MatchString(`^-?\d+.?\d*$`, u); num { + c.goToLink(u) + return + } + + go c.Visit(u) +} + +func (c *client) goToLink(l string) { + if num, _ := regexp.MatchString(`^-?\d+$`, l); num && c.PageState.Length > 0 { + linkcount := len(c.PageState.History[c.PageState.Position].Links) + item, err := strconv.Atoi(l) + if err != nil { + c.SetMessage(fmt.Sprintf("Invalid link id: %s", l), true) + c.DrawMessage() + return + } + if item <= linkcount && item > 0 { + linkurl := c.PageState.History[c.PageState.Position].Links[item-1] + c.Visit(linkurl) + } else { + c.SetMessage(fmt.Sprintf("Invalid link id: %s", l), true) + c.DrawMessage() + return + } + } + + c.SetMessage(fmt.Sprintf("Invalid link id: %s", l), true) + c.DrawMessage() +} + +func (c *client) Visit(url string) { + u, err := MakeUrl(url) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + + switch u.Scheme { + case "gopher": + // TODO send over to gopher request + case "gemini": + // TODO send over to gemini request + case "http", "https": + c.SetMessage("Attempting to open in web browser", false) + c.DrawMessage() + if strings.ToUpper(c.Options["openhttp"]) == "TRUE" { + err := gopher.OpenBrowser(u.Full) + if err != nil { + c.SetMessage(err.Error(), true) + } else { + c.SetMessage("Opened in web browser", false) + } + c.DrawMessage() + } else { + c.SetMessage("'openhttp' is not set to true, aborting opening web link", false) + c.DrawMessage() + } + default: + c.SetMessage(fmt.Sprintf("%q is not a supported protocol", u.Scheme), true) + c.DrawMessage() + } +} + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakeClient(name string) *client { + var userinfo, _ = user.Current() + var options = map[string]string{ + "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", + "savelocation": userinfo.HomeDir, + "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", + "openhttp": "false", + "httpbrowser": "lynx", + "configlocation": userinfo.HomeDir, + } + c := client{0, 0, options, "", MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} + c.GetSize() + return &c +} + +// Retrieve a byte slice of raw response dataa +// from a url string +func Fetch(url string) ([]byte, error) { + u, err := MakeUrl(url) + if err != nil { + return []byte(""), err + } + + timeOut := time.Duration(5) * time.Second + + if u.Host == "" || u.Port == "" { + return []byte(""), fmt.Errorf("Incomplete request url") + } + + addr := u.Host + ":" + u.Port + + conn, err := net.DialTimeout("tcp", addr, timeOut) + if err != nil { + return []byte(""), err + } + + send := u.Resource + "\n" + + _, err = conn.Write([]byte(send)) + if err != nil { + return []byte(""), err + } + + result, err := ioutil.ReadAll(conn) + if err != nil { + return []byte(""), err + } + + return result, err +} diff --git a/footbar.go b/footbar.go new file mode 100644 index 0000000..be1ea60 --- /dev/null +++ b/footbar.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" +) + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Footbar struct { + PercentRead string + PageType string + Content string +} + + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +func (f *Footbar) SetPercentRead(p int) { + f.PercentRead = fmt.Sprintf("%d%%", p) +} + +func (f *Footbar) SetPageType(t string) { + f.PageType = t +} + +func (f *Footbar) Draw() { + // TODO this will actually draw the bar + // without having to redraw everything else +} + +func (f *Footbar) Build(width string) string { + // TODO Build out header to specified width + f.Content = "" // This is a temp value to show intention + return "" +} + +func (f *Footbar) Render() string { + // TODO returns a full line + return "" +} + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakeFootbar() Footbar { + return Footbar{"", "N/A", ""} +} + diff --git a/gopher/gopher.go b/gopher/gopher.go index 82bedea..5f488fe 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -88,7 +88,7 @@ func Visit(addr, openhttp string) (View, error) { if u.Gophertype == "h" { if res, tf := isWebLink(u.Resource); tf && strings.ToUpper(openhttp) == "TRUE" { - err := openBrowser(res) + err := OpenBrowser(res) if err != nil { return View{}, err } diff --git a/gopher/open_browser_darwin.go b/gopher/open_browser_darwin.go index edafe36..33db791 100644 --- a/gopher/open_browser_darwin.go +++ b/gopher/open_browser_darwin.go @@ -4,6 +4,6 @@ package gopher import "os/exec" -func openBrowser(url string) error { +func OpenBrowser(url string) error { return exec.Command("open", url).Start() } diff --git a/gopher/open_browser_linux.go b/gopher/open_browser_linux.go index 2ce35c9..bea56c3 100644 --- a/gopher/open_browser_linux.go +++ b/gopher/open_browser_linux.go @@ -4,6 +4,6 @@ package gopher import "os/exec" -func openBrowser(url string) error { +func OpenBrowser(url string) error { return exec.Command("xdg-open", url).Start() } diff --git a/gopher/open_browser_other.go b/gopher/open_browser_other.go index 1659ea3..f452ed4 100644 --- a/gopher/open_browser_other.go +++ b/gopher/open_browser_other.go @@ -6,6 +6,6 @@ package gopher import "fmt" -func openBrowser(url string) error { +func OpenBrowser(url string) error { return fmt.Errorf("Unsupported os for browser detection") } diff --git a/gopher/open_browser_windows.go b/gopher/open_browser_windows.go index b57c9d6..2912217 100644 --- a/gopher/open_browser_windows.go +++ b/gopher/open_browser_windows.go @@ -4,6 +4,6 @@ package gopher import "os/exec" -func openBrowser(url string) error { +func OpenBrowser(url string) error { return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() } diff --git a/headbar.go b/headbar.go new file mode 100644 index 0000000..8aafc55 --- /dev/null +++ b/headbar.go @@ -0,0 +1,47 @@ +package main + + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Headbar struct { + title string + url string + content string +} + + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +func (h *Headbar) SetUrl(u string) { + h.url = u +} + +func (h *Headbar) Build(width string) string { + // TODO Build out header to specified width + h.content = "" // This is a temp value to show intention + return "" +} + +func (h *Headbar) Draw() { + // TODO this will actually draw the bar + // without having to redraw everything else +} + +func (h *Headbar) Render() string { + // TODO returns the content value + return "" +} + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakeHeadbar(title string) Headbar { + return Headbar{title, "", title} +} + diff --git a/main.go b/main.go index 015fe78..ff354bb 100644 --- a/main.go +++ b/main.go @@ -1,402 +1,143 @@ package main import ( - "fmt" "io/ioutil" "os" - "os/user" - "regexp" - "strconv" + // "strconv" "strings" - "tildegit.org/sloum/bombadillo/cmdparse" "tildegit.org/sloum/bombadillo/config" "tildegit.org/sloum/bombadillo/cui" - "tildegit.org/sloum/bombadillo/gopher" + // "tildegit.org/sloum/bombadillo/gopher" ) +var bombadillo *client var helplocation string = "gopher://colorfield.space:70/1/bombadillo-info" -var history gopher.History = gopher.MakeHistory() -var screen *cui.Screen -var userinfo, _ = user.Current() var settings config.Config -var options = map[string]string{ - "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", - "savelocation": userinfo.HomeDir, - "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", - "openhttp": "false", - "httpbrowser": "lynx", -} -func saveFile(address, name string) error { - quickMessage("Saving file...", false) - url, err := gopher.MakeUrl(address) - if err != nil { - quickMessage("Saving file...", true) - return err - } +// func saveFileFromData(v gopher.View) error { + // quickMessage("Saving file...", false) + // urlsplit := strings.Split(v.Address.Full, "/") + // filename := urlsplit[len(urlsplit)-1] + // saveMsg := fmt.Sprintf("Saved file as %q", options["savelocation"]+filename) + // err := ioutil.WriteFile(options["savelocation"]+filename, []byte(strings.Join(v.Content, "")), 0644) + // if err != nil { + // quickMessage("Saving file...", true) + // return err + // } - data, err := gopher.Retrieve(url) - if err != nil { - quickMessage("Saving file...", true) - return err - } + // quickMessage(saveMsg, false) + // return nil +// } - err = ioutil.WriteFile(options["savelocation"]+name, data, 0644) - if err != nil { - quickMessage("Saving file...", true) - return err - } - quickMessage(fmt.Sprintf("Saved file to %s%s", options["savelocation"], name), false) - return nil -} -func saveFileFromData(v gopher.View) error { - quickMessage("Saving file...", false) - urlsplit := strings.Split(v.Address.Full, "/") - filename := urlsplit[len(urlsplit)-1] - saveMsg := fmt.Sprintf("Saved file as %q", options["savelocation"]+filename) - err := ioutil.WriteFile(options["savelocation"]+filename, []byte(strings.Join(v.Content, "")), 0644) - if err != nil { - quickMessage("Saving file...", true) - return err - } +// func doLinkCommand(action, target string) error { + // num, err := strconv.Atoi(target) + // if err != nil { + // return fmt.Errorf("Expected number, got %q", target) + // } - quickMessage(saveMsg, false) - return nil -} + // switch action { + // case "DELETE", "D": + // err := settings.Bookmarks.Del(num) + // if err != nil { + // return err + // } -func search(u string) error { - cui.MoveCursorTo(screen.Height-1, 0) - cui.Clear("line") - fmt.Print("Enter form input: ") - cui.MoveCursorTo(screen.Height-1, 17) + // screen.Windows[1].Content = settings.Bookmarks.List() + // err = saveConfig() + // if err != nil { + // return err + // } - entry, err := cui.GetLine() - if err != nil { - return err - } + // screen.ReflashScreen(false) + // return nil + // case "BOOKMARKS", "B": + // if num > len(settings.Bookmarks.Links)-1 { + // return fmt.Errorf("There is no bookmark with ID %d", num) + // } + // err := goToURL(settings.Bookmarks.Links[num]) + // return err + // } - quickMessage("Searching...", false) - searchurl := fmt.Sprintf("%s\t%s", u, entry) - sv, err := gopher.Visit(searchurl, options["openhttp"]) - if err != nil { - quickMessage("Searching...", true) - return err - } - history.Add(sv) - quickMessage("Searching...", true) - updateMainContent() - screen.Windows[0].Scrollposition = 0 - screen.ReflashScreen(true) - return nil -} + // return fmt.Errorf("This method has not been built") +// } -func routeInput(com *cmdparse.Command) error { - var err error - switch com.Type { - case cmdparse.SIMPLE: - err = simpleCommand(com.Action) - case cmdparse.GOURL: - err = goToURL(com.Target) - case cmdparse.GOLINK: - err = goToLink(com.Target) - case cmdparse.DO: - err = doCommand(com.Action, com.Value) - case cmdparse.DOLINK: - err = doLinkCommand(com.Action, com.Target) - case cmdparse.DOAS: - err = doCommandAs(com.Action, com.Value) - case cmdparse.DOLINKAS: - err = doLinkCommandAs(com.Action, com.Target, com.Value) - default: - return fmt.Errorf("Unknown command entry!") - } - return err -} +// func doCommand(action string, values []string) error { + // if length := len(values); length != 1 { + // return fmt.Errorf("Expected 1 argument, received %d", length) + // } -func toggleBookmarks() { - bookmarks := screen.Windows[1] - main := screen.Windows[0] - if bookmarks.Show { - bookmarks.Show = false - screen.Activewindow = 0 - main.Active = true - bookmarks.Active = false - } else { - bookmarks.Show = true - screen.Activewindow = 1 - main.Active = false - bookmarks.Active = true - } + // switch action { + // case "CHECK", "C": + // err := checkConfigValue(values[0]) + // if err != nil { + // return err + // } + // return nil + // } + // return fmt.Errorf("Unknown command structure") +// } - screen.ReflashScreen(false) -} +// func doLinkCommandAs(action, target string, values []string) error { + // num, err := strconv.Atoi(target) + // if err != nil { + // return fmt.Errorf("Expected number, got %q", target) + // } -func simpleCommand(a string) error { - a = strings.ToUpper(a) - switch a { - case "Q", "QUIT": - cui.Exit() - case "H", "HOME": - return goHome() - case "B", "BOOKMARKS": - toggleBookmarks() - case "SEARCH": - return search(options["searchengine"]) - case "HELP", "?": - return goToURL(helplocation) + // links := history.Collection[history.Position].Links + // if num >= len(links) { + // return fmt.Errorf("Invalid link id: %s", target) + // } - default: - return fmt.Errorf("Unknown action %q", a) - } - return nil -} + // switch action { + // case "ADD", "A": + // newBookmark := append([]string{links[num-1]}, values...) + // err := settings.Bookmarks.Add(newBookmark) + // if err != nil { + // return err + // } -func goToURL(u string) error { - if num, _ := regexp.MatchString(`^-?\d+.?\d*$`, u); num { - return goToLink(u) - } - quickMessage("Loading...", false) - v, err := gopher.Visit(u, options["openhttp"]) - if err != nil { - quickMessage("Loading...", true) - return err - } - quickMessage("Loading...", true) + // screen.Windows[1].Content = settings.Bookmarks.List() - if v.Address.Gophertype == "7" { - err := search(v.Address.Full) - if err != nil { - return err - } - } else if v.Address.IsBinary { - return saveFileFromData(v) - } else { - history.Add(v) - } - updateMainContent() - screen.Windows[0].Scrollposition = 0 - screen.ReflashScreen(true) - return nil -} + // err = saveConfig() + // if err != nil { + // return err + // } -func goToLink(l string) error { - if num, _ := regexp.MatchString(`^-?\d+$`, l); num && history.Length > 0 { - linkcount := len(history.Collection[history.Position].Links) - item, _ := strconv.Atoi(l) - if item <= linkcount && item > 0 { - linkurl := history.Collection[history.Position].Links[item-1] - quickMessage("Loading...", false) - v, err := gopher.Visit(linkurl, options["openhttp"]) - if err != nil { - quickMessage("Loading...", true) - return err - } - quickMessage("Loading...", true) + // screen.ReflashScreen(false) + // return nil + // case "WRITE", "W": + // return saveFile(links[num-1], strings.Join(values, " ")) + // } - if v.Address.Gophertype == "7" { - err := search(linkurl) - if err != nil { - return err - } - } else if v.Address.IsBinary { - return saveFileFromData(v) - } else { - history.Add(v) - } - } else { - return fmt.Errorf("Invalid link id: %s", l) - } - } else { - return fmt.Errorf("Invalid link id: %s", l) - } - updateMainContent() - screen.Windows[0].Scrollposition = 0 - screen.ReflashScreen(true) - return nil -} + // return fmt.Errorf("This method has not been built") +// } -func goHome() error { - if options["homeurl"] != "unset" { - return goToURL(options["homeurl"]) - } - return fmt.Errorf("No home address has been set") -} - -func doLinkCommand(action, target string) error { - num, err := strconv.Atoi(target) - if err != nil { - return fmt.Errorf("Expected number, got %q", target) - } - - switch action { - case "DELETE", "D": - err := settings.Bookmarks.Del(num) - if err != nil { - return err - } - - screen.Windows[1].Content = settings.Bookmarks.List() - err = saveConfig() - if err != nil { - return err - } - - screen.ReflashScreen(false) - return nil - case "BOOKMARKS", "B": - if num > len(settings.Bookmarks.Links)-1 { - return fmt.Errorf("There is no bookmark with ID %d", num) - } - err := goToURL(settings.Bookmarks.Links[num]) - return err - } - - return fmt.Errorf("This method has not been built") -} - -func doCommandAs(action string, values []string) error { - if len(values) < 2 { - return fmt.Errorf("%q", values) - } - - if values[0] == "." { - values[0] = history.Collection[history.Position].Address.Full - } - - switch action { - case "ADD", "A": - err := settings.Bookmarks.Add(values) - if err != nil { - return err - } - - screen.Windows[1].Content = settings.Bookmarks.List() - err = saveConfig() - if err != nil { - return err - } - - screen.ReflashScreen(false) - return nil - case "WRITE", "W": - return saveFile(values[0], strings.Join(values[1:], " ")) - case "SET", "S": - if _, ok := options[values[0]]; ok { - options[values[0]] = strings.Join(values[1:], " ") - return saveConfig() - } - return fmt.Errorf("Unable to set %s, it does not exist", values[0]) - } - return fmt.Errorf("Unknown command structure") -} - -func doCommand(action string, values []string) error { - if length := len(values); length != 1 { - return fmt.Errorf("Expected 1 argument, received %d", length) - } - - switch action { - case "CHECK", "C": - err := checkConfigValue(values[0]) - if err != nil { - return err - } - return nil - } - return fmt.Errorf("Unknown command structure") -} - -func checkConfigValue(setting string) error { - if val, ok := options[setting]; ok { - quickMessage(fmt.Sprintf("%s is set to: %q", setting, val), false) - return nil - - } - return fmt.Errorf("Unable to check %q, it does not exist", setting) -} - -func doLinkCommandAs(action, target string, values []string) error { - num, err := strconv.Atoi(target) - if err != nil { - return fmt.Errorf("Expected number, got %q", target) - } - - links := history.Collection[history.Position].Links - if num >= len(links) { - return fmt.Errorf("Invalid link id: %s", target) - } - - switch action { - case "ADD", "A": - newBookmark := append([]string{links[num-1]}, values...) - err := settings.Bookmarks.Add(newBookmark) - if err != nil { - return err - } - - screen.Windows[1].Content = settings.Bookmarks.List() - - err = saveConfig() - if err != nil { - return err - } - - screen.ReflashScreen(false) - return nil - case "WRITE", "W": - return saveFile(links[num-1], strings.Join(values, " ")) - } - - return fmt.Errorf("This method has not been built") -} - -func updateMainContent() { - screen.Windows[0].Content = history.Collection[history.Position].Content - screen.Bars[0].SetMessage(history.Collection[history.Position].Address.Full) -} - -func clearInput(incError bool) { - cui.MoveCursorTo(screen.Height-1, 0) - cui.Clear("line") - if incError { - cui.MoveCursorTo(screen.Height, 0) - cui.Clear("line") - } -} - -func quickMessage(msg string, clearMsg bool) { - xPos := screen.Width - 2 - len(msg) - if xPos < 2 { - xPos = 2 - } - cui.MoveCursorTo(screen.Height, xPos) - if clearMsg { - cui.Clear("right") - } else { - fmt.Print("\033[48;5;21m\033[38;5;15m", msg, "\033[0m") - } -} +// func updateMainContent() { + // screen.Windows[0].Content = history.Collection[history.Position].Content + // screen.Bars[0].SetMessage(history.Collection[history.Position].Address.Full) +// } func saveConfig() error { - bkmrks := settings.Bookmarks.IniDump() + bkmrks := bombadillo.BookMarks.IniDump() + // TODO opts becomes a string builder rather than concat opts := "\n[SETTINGS]\n" - for k, v := range options { + for k, v := range bombadillo.Options { opts += k opts += "=" opts += v opts += "\n" } - return ioutil.WriteFile(userinfo.HomeDir+"/.bombadillo.ini", []byte(bkmrks+opts), 0644) + return ioutil.WriteFile(bombadillo.Options["configlocation"] + "/.bombadillo.ini", []byte(bkmrks+opts), 0644) } func loadConfig() error { - file, err := os.Open(userinfo.HomeDir + "/.bombadillo.ini") + file, err := os.Open(bombadillo.Options["configlocation"] + "/.bombadillo.ini") if err != nil { err = saveConfig() if err != nil { @@ -407,72 +148,29 @@ func loadConfig() error { confparser := config.NewParser(file) settings, _ = confparser.Parse() file.Close() - screen.Windows[1].Content = settings.Bookmarks.List() for _, v := range settings.Settings { lowerkey := strings.ToLower(v.Key) - if _, ok := options[lowerkey]; ok { - options[lowerkey] = v.Value + if lowerkey == "configlocation" { + // The config should always be stored in home + // folder. Users cannot really edit this value. + // It is still stored in the ini and as a part + // of the options map. + continue + } + + if _, ok := bombadillo.Options[lowerkey]; ok { + bombadillo.Options[lowerkey] = v.Value } } return nil } -func toggleActiveWindow() { - if screen.Windows[1].Show { - if screen.Windows[0].Active { - screen.Windows[0].Active = false - screen.Windows[1].Active = true - screen.Activewindow = 1 - } else { - screen.Windows[0].Active = true - screen.Windows[1].Active = false - screen.Activewindow = 0 - } - screen.Windows[1].DrawWindow() - } -} - -func displayError(err error) { - cui.MoveCursorTo(screen.Height, 0) - fmt.Print("\033[41m\033[37m", err, "\033[0m") -} - func initClient() error { - history.Position = -1 - - screen = cui.NewScreen() + bombadillo = MakeClient(" ((( Bombadillo ))) ") cui.SetCharMode() - - screen.AddWindow(2, 1, screen.Height-2, screen.Width, false, false, true) - screen.Windows[0].Active = true - screen.AddMsgBar(1, " ((( Bombadillo ))) ", " A fun gopher client!", true) - bookmarksWidth := 40 - if screen.Width < 40 { - bookmarksWidth = screen.Width - } - screen.AddWindow(2, screen.Width-bookmarksWidth, screen.Height-2, screen.Width, false, true, false) - return loadConfig() -} - -func handleResize() { - oldh, oldw := screen.Height, screen.Width - screen.GetSize() - if screen.Height != oldh || screen.Width != oldw { - screen.Windows[0].Box.Row2 = screen.Height - 2 - screen.Windows[0].Box.Col2 = screen.Width - bookmarksWidth := 40 - if screen.Width < 40 { - bookmarksWidth = screen.Width - } - screen.Windows[1].Box.Row2 = screen.Height - 2 - screen.Windows[1].Box.Col1 = screen.Width - bookmarksWidth - screen.Windows[1].Box.Col2 = screen.Width - - screen.DrawAllWindows() - screen.DrawMsgBars() - screen.ClearCommandArea() - } + err := loadConfig() + return err } func main() { @@ -480,91 +178,27 @@ func main() { defer cui.Exit() err := initClient() if err != nil { - // if we can't initialize the window, - // we can't do anything! + // if we can't initialize we should bail out panic(err) } - mainWindow := screen.Windows[0] + // Start polling for terminal size changes + go bombadillo.GetSize() if len(os.Args) > 1 { - err = goToURL(os.Args[1]) + // If a url was passed, move it down the line + // Goroutine so keypresses can be made during + // page load + go bombadillo.Visit(os.Args[1]) } else { - err = goHome() - } - - if err != nil { - displayError(err) - } else { - updateMainContent() + // Otherwise, load the homeurl + // Goroutine so keypresses can be made during + // page load + go bombadillo.Visit(bombadillo.Options["homeurl"]) } + // Loop indefinitely on user input for { - c := cui.Getch() - - handleResize() - - switch c { - case 'j', 'J': - screen.Windows[screen.Activewindow].ScrollDown() - screen.ReflashScreen(false) - case 'k', 'K': - screen.Windows[screen.Activewindow].ScrollUp() - screen.ReflashScreen(false) - case 'q', 'Q': - cui.Exit() - case 'g': - screen.Windows[screen.Activewindow].ScrollHome() - screen.ReflashScreen(false) - case 'G': - screen.Windows[screen.Activewindow].ScrollEnd() - screen.ReflashScreen(false) - case 'd': - screen.Windows[screen.Activewindow].PageDown() - screen.ReflashScreen(false) - case 'u': - screen.Windows[screen.Activewindow].PageUp() - screen.ReflashScreen(false) - case 'b': - success := history.GoBack() - if success { - mainWindow.Scrollposition = 0 - updateMainContent() - screen.ReflashScreen(true) - } - case 'B': - toggleBookmarks() - case 'f', 'F': - success := history.GoForward() - if success { - mainWindow.Scrollposition = 0 - updateMainContent() - screen.ReflashScreen(true) - } - case '\t': - toggleActiveWindow() - case ':', ' ': - cui.MoveCursorTo(screen.Height-1, 0) - entry, err := cui.GetLine() - if err != nil { - displayError(err) - } - - // Clear entry line and error line - clearInput(true) - if entry == "" { - continue - } - parser := cmdparse.NewParser(strings.NewReader(entry)) - p, err := parser.Parse() - if err != nil { - displayError(err) - } else { - err := routeInput(p) - if err != nil { - displayError(err) - } - } - } + bombadillo.TakeControlInput() } } diff --git a/page.go b/page.go new file mode 100644 index 0000000..2e4b85e --- /dev/null +++ b/page.go @@ -0,0 +1,30 @@ +package main + + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Page struct { + WrappedContent []string + RawContent string + Links []string + Location Url + ScrollPosition int +} + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakePage(url Url, content string) Page { + p := Page{make([]string, 0), content, make([]string, 0), url, 0} + return p +} + diff --git a/pages.go b/pages.go new file mode 100644 index 0000000..5c844e8 --- /dev/null +++ b/pages.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" +) + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Pages struct { + Position int + Length int + History [20]Page +} + + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +func (p *Pages) NavigateHistory(qty int) error { + newPosition := p.Position + qty + if newPosition < 0 { + return fmt.Errorf("You are already at the beginning of history") + } else if newPosition > p.Length - 1 { + return fmt.Errorf("Your way is blocked by void, there is nothing forward") + } + + p.Position = newPosition + return nil +} + +func (p *Pages) Add(pg Page) error { + // TODO add the given page onto the pages struct + // handling truncation of the history as needed. + return fmt.Errorf("") +} + +func (p *Pages) Render() ([]string, error) { + // TODO grab the current page as wrappedContent + // May need to handle spacing at end of lines. + return []string{}, fmt.Errorf("") +} + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func MakePages() Pages { + return Pages{-1, 0, [20]Page{}} +} + + diff --git a/url.go b/url.go new file mode 100644 index 0000000..b6dfebd --- /dev/null +++ b/url.go @@ -0,0 +1,107 @@ +package main + +import ( + "fmt" + "regexp" + "strings" +) + +//------------------------------------------------\\ +// + + + T Y P E S + + + \\ +//--------------------------------------------------\\ + +type Url struct { + Scheme string + Host string + Port string + Resource string + Full string + Mime string + DownloadOnly bool +} + +//------------------------------------------------\\ +// + + + R E C E I V E R S + + + \\ +//--------------------------------------------------\\ + +// There are currently no receivers for the Url struct + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + + +// MakeUrl is a Url constructor that takes in a string +// representation of a url and returns a Url struct and +// an error (or nil). +func MakeUrl(u string) (Url, error) { + var out Url + re := regexp.MustCompile(`^((?Pgopher|http|https|gemini):\/\/)?(?P[\w\-\.\d]+)(?::(?P\d+)?)?(?:/(?P[01345679gIhisp])?)?(?P.*)?$`) + match := re.FindStringSubmatch(u) + + if valid := re.MatchString(u); !valid { + return out, fmt.Errorf("Invalid url/unable to parse") + } + + for i, name := range re.SubexpNames() { + switch name { + case "scheme": + out.Scheme = match[i] + case "host": + out.Host = match[i] + case "port": + out.Port = match[i] + case "type": + out.Mime = match[i] + case "resource": + out.Resource = match[i] + } + } + + if out.Scheme == "" { + out.Scheme = "gopher" + } + + if out.Host == "" { + return out, fmt.Errorf("no host") + } + + if out.Scheme == "gopher" && out.Port == "" { + out.Port = "70" + } else if out.Scheme == "http" && out.Port == "" { + out.Port = "80" + } else if out.Scheme == "https" && out.Port == "" { + out.Port = "443" + } else if out.Scheme == "gemini" && out.Port == "" { + out.Port = "1965" + } + + if out.Scheme == "gopher" && out.Mime == "" { + out.Mime = "0" + } + + if out.Mime == "" && (out.Resource == "" || out.Resource == "/") && out.Scheme == "gopher" { + out.Mime = "1" + } + + if out.Mime == "7" && strings.Contains(out.Resource, "\t") { + out.Mime = "1" + } + + if out.Scheme == "gopher" { + switch out.Mime { + case "1", "0", "h", "7": + out.DownloadOnly = false + default: + out.DownloadOnly = true + } + } else { + out.Resource = fmt.Sprintf("%s%s", out.Mime, out.Resource) + out.Mime = "" + } + + out.Full = out.Scheme + "://" + out.Host + ":" + out.Port + "/" + out.Mime + out.Resource + + return out, nil +} From 84631a38da4fe79b673c1f0d1c4b14f290992685 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Tue, 10 Sep 2019 20:13:30 -0700 Subject: [PATCH 02/25] Adds telnet and http modules, updates visit method on client --- bookmarks.go | 62 +++++++++++++++++++++++++++------- client.go | 38 +++++++++++++-------- gopher/gopher.go | 22 ++++++------ gopher/open_browser_darwin.go | 9 ----- gopher/open_browser_linux.go | 9 ----- gopher/open_browser_other.go | 11 ------ gopher/open_browser_windows.go | 9 ----- http/open_browser_darwin.go | 13 +++++++ http/open_browser_linux.go | 13 +++++++ http/open_browser_other.go | 11 ++++++ http/open_browser_windows.go | 13 +++++++ page.go | 4 +-- telnet/telnet.go | 24 +++++++++++++ 13 files changed, 160 insertions(+), 78 deletions(-) delete mode 100644 gopher/open_browser_darwin.go delete mode 100644 gopher/open_browser_linux.go delete mode 100644 gopher/open_browser_other.go delete mode 100644 gopher/open_browser_windows.go create mode 100644 http/open_browser_darwin.go create mode 100644 http/open_browser_linux.go create mode 100644 http/open_browser_other.go create mode 100644 http/open_browser_windows.go create mode 100644 telnet/telnet.go diff --git a/bookmarks.go b/bookmarks.go index 3b044fd..a4c0c84 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "strings" ) //------------------------------------------------\\ @@ -21,14 +22,24 @@ type Bookmarks struct { // + + + R E C E I V E R S + + + \\ //--------------------------------------------------\\ -func (b *Bookmarks) Add([]string) error { - // TODO add a bookmark - return fmt.Errorf("") +func (b *Bookmarks) Add(v []string) (string, error) { + if len(v) < 2 { + return "", fmt.Errorf("Received %d arguments, expected 2+", len(v)) + } + b.Titles = append(b.Titles, strings.Join(v[1:], " ")) + b.Links = append(b.Links, v[0]) + b.Length = len(b.Titles) + return "Bookmark added successfully", nil } -func (b *Bookmarks) Delete(int) error { - // TODO delete a bookmark - return fmt.Errorf("") +func (b *Bookmarks) Delete(i int) (string, error) { + if i < len(b.Titles) && len(b.Titles) == len(b.Links) { + b.Titles = append(b.Titles[:i], b.Titles[i+1:]...) + b.Links = append(b.Links[:i], b.Links[i+1:]...) + b.Length = len(b.Titles) + return "Bookmark deleted successfully", nil + } + return "", fmt.Errorf("Bookmark %d does not exist", i) } func (b *Bookmarks) ToggleOpen() { @@ -46,17 +57,42 @@ func (b *Bookmarks) ToggleFocused() { } } -func (b *Bookmarks) IniDump() string { - // TODO create dump of values for INI file - return "" +func (b Bookmarks) IniDump() string { + if len(b.Titles) < 0 { + return "" + } + out := "[BOOKMARKS]\n" + for i := 0; i < len(b.Titles); i++ { + out += b.Titles[i] + out += "=" + out += b.Links[i] + out += "\n" + } + return out } -func (b *Bookmarks) Render() ([]string, error) { - // TODO grab all of the bookmarks as a fixed - // width string including border and spacing - return []string{}, fmt.Errorf("") +// Get a list, including link nums, of bookmarks +// as a string slice +func (b Bookmarks) List() []string { + var out []string + for i, t := range b.Titles { + out = append(out, fmt.Sprintf("[%d] %s", i, t)) + } + return out } +func (b Bookmarks) Render() ([]string, error) { + // TODO Use b.List() to get the necessary + // text and add on the correct border for + // rendering the focus. Use sprintf, left + // aligned: "| %-36.36s |" of the like. + return []string{}, nil +} + +// TODO handle scrolling of the bookmarks list +// either here widh a scroll up/down or in the client +// code for scroll + //------------------------------------------------\\ // + + + F U N C T I O N S + + + \\ diff --git a/client.go b/client.go index 8c2bdc0..bd4719e 100644 --- a/client.go +++ b/client.go @@ -14,7 +14,10 @@ import ( "tildegit.org/sloum/bombadillo/cmdparse" "tildegit.org/sloum/bombadillo/cui" - "tildegit.org/sloum/bombadillo/gopher" + // "tildegit.org/sloum/bombadillo/gemini" + // "tildegit.org/sloum/bombadillo/gopher" + "tildegit.org/sloum/bombadillo/http" + "tildegit.org/sloum/bombadillo/telnet" ) //------------------------------------------------\\ @@ -231,11 +234,14 @@ func (c *client) doCommandAs(action string, values []string) { switch action { case "ADD", "A": - err := c.BookMarks.Add(values) + msg, err := c.BookMarks.Add(values) if err != nil { c.SetMessage(err.Error(), true) c.DrawMessage() return + } else { + c.SetMessage(msg, false) + c.DrawMessage() } err = saveConfig() @@ -342,15 +348,7 @@ func (c *client) search() { escapedEntry := entry go c.Visit(fmt.Sprintf("%s?%s",u.Full,escapedEntry)) case "http", "https": - c.SetMessage("Attempting to open in web browser", false) - c.DrawMessage() - err := gopher.OpenBrowser(u.Full) - if err != nil { - c.SetMessage(err.Error(), true) - } else { - c.SetMessage("Opened in web browser", false) - } - c.DrawMessage() + c.Visit(u.Full) default: c.SetMessage(fmt.Sprintf("%q is not a supported protocol", u.Scheme), true) c.DrawMessage() @@ -463,19 +461,31 @@ func (c *client) Visit(url string) { // TODO send over to gopher request case "gemini": // TODO send over to gemini request + case "telnet": + c.SetMessage("Attempting to start telnet session", false) + c.DrawMessage() + msg, err := telnet.StartSession(u.Host, u.Port) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + } else { + c.SetMessage(msg, true) + c.DrawMessage() + } + c.Draw() case "http", "https": c.SetMessage("Attempting to open in web browser", false) c.DrawMessage() if strings.ToUpper(c.Options["openhttp"]) == "TRUE" { - err := gopher.OpenBrowser(u.Full) + msg, err := http.OpenInBrowser(u.Full) if err != nil { c.SetMessage(err.Error(), true) } else { - c.SetMessage("Opened in web browser", false) + c.SetMessage(msg, false) } c.DrawMessage() } else { - c.SetMessage("'openhttp' is not set to true, aborting opening web link", false) + c.SetMessage("'openhttp' is not set to true, cannot open web link", false) c.DrawMessage() } default: diff --git a/gopher/gopher.go b/gopher/gopher.go index 5f488fe..d2c97a4 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -5,7 +5,7 @@ package gopher import ( "errors" - "fmt" + // "fmt" "io/ioutil" "net" "strings" @@ -86,16 +86,16 @@ func Visit(addr, openhttp string) (View, error) { return View{}, err } - if u.Gophertype == "h" { - if res, tf := isWebLink(u.Resource); tf && strings.ToUpper(openhttp) == "TRUE" { - err := OpenBrowser(res) - if err != nil { - return View{}, err - } - - return View{}, fmt.Errorf("") - } - } + // if u.Gophertype == "h" { + // if res, tf := isWebLink(u.Resource); tf && strings.ToUpper(openhttp) == "TRUE" { + // err := OpenBrowser(res) + // if err != nil { + // return View{}, err + // } +// + // return View{}, fmt.Errorf("") + // } + // } text, err := Retrieve(u) if err != nil { diff --git a/gopher/open_browser_darwin.go b/gopher/open_browser_darwin.go deleted file mode 100644 index 33db791..0000000 --- a/gopher/open_browser_darwin.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build darwin - -package gopher - -import "os/exec" - -func OpenBrowser(url string) error { - return exec.Command("open", url).Start() -} diff --git a/gopher/open_browser_linux.go b/gopher/open_browser_linux.go deleted file mode 100644 index bea56c3..0000000 --- a/gopher/open_browser_linux.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build linux - -package gopher - -import "os/exec" - -func OpenBrowser(url string) error { - return exec.Command("xdg-open", url).Start() -} diff --git a/gopher/open_browser_other.go b/gopher/open_browser_other.go deleted file mode 100644 index f452ed4..0000000 --- a/gopher/open_browser_other.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !linux -// +build !darwin -// +build !windows - -package gopher - -import "fmt" - -func OpenBrowser(url string) error { - return fmt.Errorf("Unsupported os for browser detection") -} diff --git a/gopher/open_browser_windows.go b/gopher/open_browser_windows.go deleted file mode 100644 index 2912217..0000000 --- a/gopher/open_browser_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package gopher - -import "os/exec" - -func OpenBrowser(url string) error { - return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() -} diff --git a/http/open_browser_darwin.go b/http/open_browser_darwin.go new file mode 100644 index 0000000..dd7da7a --- /dev/null +++ b/http/open_browser_darwin.go @@ -0,0 +1,13 @@ +// +build darwin + +package http + +import "os/exec" + +func OpenInBrowser(url string) (string, error) { + err := exec.Command("open", url).Start() + if err != nil { + return "", err + } + return "Opened in system default web browser", nil +} diff --git a/http/open_browser_linux.go b/http/open_browser_linux.go new file mode 100644 index 0000000..dc99845 --- /dev/null +++ b/http/open_browser_linux.go @@ -0,0 +1,13 @@ +// +build linux + +package http + +import "os/exec" + +func OpenInBrowser(url string) (string, error) { + err := exec.Command("xdg-open", url).Start() + if err != nil { + return "", err + } + return "Opened in system default web browser", nil +} diff --git a/http/open_browser_other.go b/http/open_browser_other.go new file mode 100644 index 0000000..c6e5342 --- /dev/null +++ b/http/open_browser_other.go @@ -0,0 +1,11 @@ +// +build !linux +// +build !darwin +// +build !windows + +package http + +import "fmt" + +func OpenInBrowser(url string) (string, error) { + return "", fmt.Errorf("Unsupported os for browser detection") +} diff --git a/http/open_browser_windows.go b/http/open_browser_windows.go new file mode 100644 index 0000000..0ddf6c7 --- /dev/null +++ b/http/open_browser_windows.go @@ -0,0 +1,13 @@ +// +build windows + +package http + +import "os/exec" + +func OpenInBrowser(url string) (string, error) { + err := exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() + if err != nil { + return "", err + } + return "Opened in system default web browser", nil +} diff --git a/page.go b/page.go index 2e4b85e..9fa0a0e 100644 --- a/page.go +++ b/page.go @@ -6,7 +6,7 @@ package main //--------------------------------------------------\\ type Page struct { - WrappedContent []string + WrappedContent string RawContent string Links []string Location Url @@ -24,7 +24,7 @@ type Page struct { //--------------------------------------------------\\ func MakePage(url Url, content string) Page { - p := Page{make([]string, 0), content, make([]string, 0), url, 0} + p := Page{"", content, make([]string, 0), url, 0} return p } diff --git a/telnet/telnet.go b/telnet/telnet.go new file mode 100644 index 0000000..609f13d --- /dev/null +++ b/telnet/telnet.go @@ -0,0 +1,24 @@ +package telnet + +import ( + "fmt" + "os" + "os/exec" +) + +func StartSession(host string, port string) (string, error) { + // Case for telnet links + c := exec.Command("telnet", host, port) + c.Stdin = os.Stdin + c.Stdout = os.Stdout + c.Stderr = os.Stderr + // Clear the screen and position the cursor at the top left + fmt.Print("\033[2J\033[0;0H") + err := c.Run() + if err != nil { + return "", fmt.Errorf("Telnet error response: %s", err.Error()) + } + + return "Telnet session terminated", nil +} + From a6d1f45be871df3cfd3cc76b1418324f8fef7727 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Tue, 10 Sep 2019 20:23:44 -0700 Subject: [PATCH 03/25] Added clarifying comments --- client.go | 2 ++ cui/cui.go | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/client.go b/client.go index bd4719e..4773435 100644 --- a/client.go +++ b/client.go @@ -449,6 +449,8 @@ func (c *client) goToLink(l string) { } func (c *client) Visit(url string) { + // TODO both gemini and gopher should return a string + // The wrap lines function in cui needs to be rewritten u, err := MakeUrl(url) if err != nil { c.SetMessage(err.Error(), true) diff --git a/cui/cui.go b/cui/cui.go index a784ce7..b00e07e 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -85,6 +85,12 @@ func Clear(dir string) { // than the specified console width, splitting them over two lines. returns the // amended document content as a slice. func wrapLines(s []string, consolewidth int) []string { + // TODO redo this so that it returns a string and can hard and + // soft wrap. It will use parsing to go char by char. CUI should + // set tabs to 4 on screen init. Multispace chars should be detected + // tab spacing should be detected using % to see where the next tab stop + // is. Use a counter as building the sub buffer. len returns num of bytes + // be sure to get num of chars instead: len([]rune("a")). indent := " " //11 spaces out := []string{} for _, ln := range s { From b7d7d021ed6d69973ade395cec436b957aa44963 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Tue, 10 Sep 2019 22:30:29 -0700 Subject: [PATCH 04/25] Begun work on gopher module --- gopher/gopher.go | 121 ++++++++++++++++++++++++++++++----------------- 1 file changed, 77 insertions(+), 44 deletions(-) diff --git a/gopher/gopher.go b/gopher/gopher.go index d2c97a4..d32dc70 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -5,7 +5,7 @@ package gopher import ( "errors" - // "fmt" + "fmt" "io/ioutil" "net" "strings" @@ -21,17 +21,21 @@ import ( var types = map[string]string{ "0": "TXT", "1": "MAP", - "h": "HTM", "3": "ERR", "4": "BIN", "5": "DOS", - "s": "SND", - "g": "GIF", - "I": "IMG", - "9": "BIN", - "7": "FTS", "6": "UUE", + "7": "FTS", + "8": "TEL", + "9": "BIN", + "g": "GIF", + "G": "GEM", + "h": "HTM", + "I": "IMG", "p": "PNG", + "s": "SND", + "S": "SSH", + "T": "TEL", } //------------------------------------------------\\ @@ -43,25 +47,22 @@ var types = map[string]string{ // available to use directly, but in most implementations // using the "Visit" receiver of the History struct will // be better. -func Retrieve(u Url) ([]byte, error) { +func Retrieve(host, port, resource string) ([]byte, error) { nullRes := make([]byte, 0) timeOut := time.Duration(5) * time.Second - if u.Host == "" || u.Port == "" { + if host == "" || port == "" { return nullRes, errors.New("Incomplete request url") } - addr := u.Host + ":" + u.Port + addr := host + ":" + port conn, err := net.DialTimeout("tcp", addr, timeOut) if err != nil { return nullRes, err } - send := u.Resource + "\n" - if u.Scheme == "http" || u.Scheme == "https" { - send = u.Gophertype - } + send := resource + "\n" _, err = conn.Write([]byte(send)) if err != nil { @@ -73,43 +74,27 @@ func Retrieve(u Url) ([]byte, error) { return nullRes, err } - return result, err + return result, nil } -// Visit is a high level combination of a few different -// types that makes it easy to create a Url, make a request -// to that Url, and add the response and Url to a View. -// Returns a copy of the view and an error (or nil). -func Visit(addr, openhttp string) (View, error) { - u, err := MakeUrl(addr) +// Visit handles the making of the request, parsing of maps, and returning +// the correct information to the client +func Visit(gophertype, host, port, resource string) (string, []string, error) { + resp, err := Retrieve(host, port, resource) + text := string(resp) + links := []string{} + if err != nil { - return View{}, err + return "", []string{}, err + } else if IsDownloadOnly(gophertype) { + return text, []string{}, nil } - // if u.Gophertype == "h" { - // if res, tf := isWebLink(u.Resource); tf && strings.ToUpper(openhttp) == "TRUE" { - // err := OpenBrowser(res) - // if err != nil { - // return View{}, err - // } -// - // return View{}, fmt.Errorf("") - // } - // } - - text, err := Retrieve(u) - if err != nil { - return View{}, err + if gophertype == "1" { + text, links = parseMap(text) } - var pageContent []string - if u.IsBinary && u.Gophertype != "7" { - pageContent = []string{string(text)} - } else { - pageContent = strings.Split(string(text), "\n") - } - - return MakeView(u, pageContent), nil + return text, links, nil } func getType(t string) string { @@ -127,3 +112,51 @@ func isWebLink(resource string) (string, bool) { } return "", false } + +// TODO Make sure when parsing maps that links have the correct +// protocol rather than 'gopher', where applicable (telnet, gemini, etc). +func parseMap(text string) (string, []string) { + splitContent := strings.Split(text, "\n") + links := make([]string, 0, 10) + + for i, e := range splitContent { + e = strings.Trim(e, "\r\n") + if e == "." { + splitContent[i] = "" + continue + } + + line := strings.Split(e, "\t") + var title string + // TODO REFACTOR LINE == HERE + // - - - - - - - - - - - - - - + if len(line[0]) > 1 { + title = line[0][1:] + } else { + title = "" + } + if len(line) > 1 && len(line[0]) > 0 && string(line[0][0]) == "i" { + splitContent[i] = " " + string(title) + } else if len(line) >= 4 { + fulllink := fmt.Sprintf("%s://%s:%s/%s%s", "protocol" ,line[2], line[3], string(line[0][0]), line[1]) + links = append(links, fulllink) + linktext := fmt.Sprintf("(%s) %2d %s", getType(string(line[0][0])), len(links), title) + splitContent[i] = linktext + } + } + return "", links +} + +// Returns false for all text formats (including html +// even though it may link out. Things like telnet +// should never make it into the retrieve call for +// this module, having been handled in the client +// based on their protocol. +func IsDownloadOnly(gophertype string) bool { + switch gophertype { + case "0", "1", "3", "7", "h": + return false + default: + return true + } +} From bccca61ec223a6b1cac875e9a634b863575fa420 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Wed, 11 Sep 2019 22:53:36 -0700 Subject: [PATCH 05/25] Some level of screen draw now works --- bookmarks.go | 49 +++++++++++++++++--- client.go | 51 ++++++++++++++++++--- config/parser.go | 12 ++--- cui/cui.go | 4 +- footbar.go | 18 ++------ gopher/bookmark.go | 65 -------------------------- gopher/gopher.go | 42 +++++++++++++---- gopher/history.go | 112 --------------------------------------------- gopher/url.go | 94 ------------------------------------- gopher/view.go | 83 --------------------------------- headbar.go | 18 +++----- main.go | 8 ++-- page.go | 60 ++++++++++++++++++++++-- pages.go | 31 +++++++++---- url.go | 4 +- 15 files changed, 224 insertions(+), 427 deletions(-) delete mode 100644 gopher/bookmark.go delete mode 100644 gopher/history.go delete mode 100644 gopher/url.go delete mode 100644 gopher/view.go diff --git a/bookmarks.go b/bookmarks.go index a4c0c84..503e648 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -3,6 +3,8 @@ package main import ( "fmt" "strings" + + "tildegit.org/sloum/bombadillo/cui" ) //------------------------------------------------\\ @@ -81,16 +83,49 @@ func (b Bookmarks) List() []string { return out } -func (b Bookmarks) Render() ([]string, error) { - // TODO Use b.List() to get the necessary - // text and add on the correct border for - // rendering the focus. Use sprintf, left - // aligned: "| %-36.36s |" of the like. - return []string{}, nil +func (b Bookmarks) Render(termwidth, termheight int) []string { + width := 40 + termheight -= 3 + var wall, ceil, tr, tl, br, bl string + if termwidth < 40 { + width = termwidth + } + if b.IsFocused { + wall = cui.Shapes["awall"] + ceil = cui.Shapes["aceiling"] + tr = cui.Shapes["atr"] + br = cui.Shapes["abr"] + tl = cui.Shapes["atl"] + bl = cui.Shapes["abl"] + } else { + wall = cui.Shapes["wall"] + ceil = cui.Shapes["ceiling"] + tr = cui.Shapes["tr"] + br = cui.Shapes["br"] + tl = cui.Shapes["tl"] + bl = cui.Shapes["bl"] + } + + out := make([]string, 5) + top := fmt.Sprintf("%s%s%s", tl, strings.Repeat(ceil, width-2), tr) + out = append(out, top) + marks := b.List() + contentWidth := termwidth - 2 + for i := 0; i < termheight - 2; i++ { + if i + b.Position >= b.Length { + out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, "", wall )) + } else { + out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, marks[i + b.Position], wall )) + } + } + + bottom := fmt.Sprintf("%s%s%s", bl, strings.Repeat(ceil, width-2), br) + out = append(out, bottom) + return out } // TODO handle scrolling of the bookmarks list -// either here widh a scroll up/down or in the client +// either here with a scroll up/down or in the client // code for scroll diff --git a/client.go b/client.go index 4773435..f326fbc 100644 --- a/client.go +++ b/client.go @@ -15,7 +15,7 @@ import ( "tildegit.org/sloum/bombadillo/cmdparse" "tildegit.org/sloum/bombadillo/cui" // "tildegit.org/sloum/bombadillo/gemini" - // "tildegit.org/sloum/bombadillo/gopher" + "tildegit.org/sloum/bombadillo/gopher" "tildegit.org/sloum/bombadillo/http" "tildegit.org/sloum/bombadillo/telnet" ) @@ -68,10 +68,30 @@ func (c *client) GetSize() { } func (c *client) Draw() { - // TODO build this out. - // It should call all of the renders - // and add them to the a string buffer - // It should then print the buffer + var screen strings.Builder + screen.Grow(c.Height * c.Width) + screen.WriteString(c.TopBar.Render(c.Width, "This is a test")) + screen.WriteString("\n") + pageContent := c.PageState.Render(c.Height) + if c.BookMarks.IsOpen { + bm := c.BookMarks.Render(c.Width, c.Height) + bmWidth := len([]rune(bm[0])) + for i, ln := range pageContent { + screen.WriteString(ln[:len(ln) - bmWidth]) + screen.WriteString(bm[i]) + screen.WriteString("\n") + } + } else { + for _, ln := range pageContent { + screen.WriteString(ln) + screen.WriteString("\n") + } + } + screen.WriteString("\n") // for the input line + screen.WriteString(c.FootBar.Render(c.Width)) + cui.Clear("screen") + cui.MoveCursorTo(0,0) + fmt.Print(screen.String()) } func (c *client) TakeControlInput() { @@ -131,6 +151,7 @@ func (c *client) TakeControlInput() { // Process a command c.ClearMessage() c.ClearMessageLine() + cui.MoveCursorTo(c.Height-2, 0) entry, err := cui.GetLine() c.ClearMessageLine() if err != nil { @@ -460,9 +481,26 @@ func (c *client) Visit(url string) { switch u.Scheme { case "gopher": - // TODO send over to gopher request + u, err := MakeUrl(url) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + pg := MakePage(u, content, links) + pg.WrapContent(c.Width) + c.PageState.Add(pg) + c.Draw() case "gemini": // TODO send over to gemini request + c.SetMessage("Gemini is not currently supported", false) + c.DrawMessage() case "telnet": c.SetMessage("Attempting to start telnet session", false) c.DrawMessage() @@ -512,7 +550,6 @@ func MakeClient(name string) *client { "configlocation": userinfo.HomeDir, } c := client{0, 0, options, "", MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} - c.GetSize() return &c } diff --git a/config/parser.go b/config/parser.go index 4661ac6..038c889 100644 --- a/config/parser.go +++ b/config/parser.go @@ -4,7 +4,6 @@ import ( "fmt" "io" "strings" - "tildegit.org/sloum/bombadillo/gopher" ) //------------------------------------------------\\ @@ -21,7 +20,10 @@ type Parser struct { } type Config struct { - Bookmarks gopher.Bookmarks + // Bookmarks gopher.Bookmarks + Bookmarks struct { + Titles, Links []string + } Colors []KeyValue Settings []KeyValue } @@ -86,10 +88,8 @@ func (p *Parser) Parse() (Config, error) { } switch section { case "BOOKMARKS": - err := c.Bookmarks.Add([]string{keyval.Value, keyval.Key}) - if err != nil { - return c, err - } + c.Bookmarks.Titles = append(c.Bookmarks.Titles, keyval.Value) + c.Bookmarks.Links = append(c.Bookmarks.Links, keyval.Key) case "COLORS": c.Colors = append(c.Colors, keyval) case "SETTINGS": diff --git a/cui/cui.go b/cui/cui.go index b00e07e..5cb5d79 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -9,7 +9,7 @@ import ( "strings" ) -var shapes = map[string]string{ +var Shapes = map[string]string{ "wall": "╵", "ceiling": "╴", "tl": "┌", @@ -25,7 +25,7 @@ var shapes = map[string]string{ } func drawShape(shape string) { - if val, ok := shapes[shape]; ok { + if val, ok := Shapes[shape]; ok { fmt.Printf("%s", val) } else { fmt.Print("x") diff --git a/footbar.go b/footbar.go index be1ea60..dab20bf 100644 --- a/footbar.go +++ b/footbar.go @@ -9,9 +9,8 @@ import ( //--------------------------------------------------\\ type Footbar struct { - PercentRead string + PercentRead int PageType string - Content string } @@ -20,7 +19,7 @@ type Footbar struct { //--------------------------------------------------\\ func (f *Footbar) SetPercentRead(p int) { - f.PercentRead = fmt.Sprintf("%d%%", p) + f.PercentRead = p } func (f *Footbar) SetPageType(t string) { @@ -32,15 +31,8 @@ func (f *Footbar) Draw() { // without having to redraw everything else } -func (f *Footbar) Build(width string) string { - // TODO Build out header to specified width - f.Content = "" // This is a temp value to show intention - return "" -} - -func (f *Footbar) Render() string { - // TODO returns a full line - return "" +func (f *Footbar) Render(termWidth int) string { + return fmt.Sprintf("\033[7m%-*.*s\033[0m", termWidth, termWidth, "") } @@ -49,6 +41,6 @@ func (f *Footbar) Render() string { //--------------------------------------------------\\ func MakeFootbar() Footbar { - return Footbar{"", "N/A", ""} + return Footbar{100, "N/A"} } diff --git a/gopher/bookmark.go b/gopher/bookmark.go deleted file mode 100644 index 24ac80f..0000000 --- a/gopher/bookmark.go +++ /dev/null @@ -1,65 +0,0 @@ -package gopher - -import ( - "fmt" - "strings" -) - -//------------------------------------------------\\ -// + + + T Y P E S + + + \\ -//--------------------------------------------------\\ - -//Bookmarks is a holder for titles and links that -//can be retrieved by index -type Bookmarks struct { - Titles []string - Links []string -} - -//------------------------------------------------\\ -// + + + R E C E I V E R S + + + \\ -//--------------------------------------------------\\ - -// Add adds a new title and link combination to the bookmarks -// struct. It takes as input a string slice in which the first -// element represents the link and all following items represent -// the title of the bookmark (they will be joined with spaces). -func (b *Bookmarks) Add(v []string) error { - if len(v) < 2 { - return fmt.Errorf("Received %d arguments, expected 2 or more", len(v)) - } - b.Titles = append(b.Titles, strings.Join(v[1:], " ")) - b.Links = append(b.Links, v[0]) - return nil -} - -func (b *Bookmarks) Del(i int) error { - if i < len(b.Titles) && i < len(b.Links) { - b.Titles = append(b.Titles[:i], b.Titles[i+1:]...) - b.Links = append(b.Links[:i], b.Links[i+1:]...) - return nil - } - return fmt.Errorf("Bookmark %d does not exist", i) -} - -func (b Bookmarks) List() []string { - var out []string - for i, t := range b.Titles { - out = append(out, fmt.Sprintf("[%d] %s", i, t)) - } - return out -} - -func (b Bookmarks) IniDump() string { - if len(b.Titles) < 0 { - return "" - } - out := "[BOOKMARKS]\n" - for i := 0; i < len(b.Titles); i++ { - out += b.Titles[i] - out += "=" - out += b.Links[i] - out += "\n" - } - return out -} diff --git a/gopher/gopher.go b/gopher/gopher.go index d32dc70..b990682 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -81,15 +81,18 @@ func Retrieve(host, port, resource string) ([]byte, error) { // the correct information to the client func Visit(gophertype, host, port, resource string) (string, []string, error) { resp, err := Retrieve(host, port, resource) + if err != nil { + return "", []string{}, err + } + text := string(resp) links := []string{} - if err != nil { - return "", []string{}, err - } else if IsDownloadOnly(gophertype) { + if IsDownloadOnly(gophertype) { return text, []string{}, nil } + if gophertype == "1" { text, links = parseMap(text) } @@ -113,8 +116,6 @@ func isWebLink(resource string) (string, bool) { return "", false } -// TODO Make sure when parsing maps that links have the correct -// protocol rather than 'gopher', where applicable (telnet, gemini, etc). func parseMap(text string) (string, []string) { splitContent := strings.Split(text, "\n") links := make([]string, 0, 10) @@ -128,23 +129,23 @@ func parseMap(text string) (string, []string) { line := strings.Split(e, "\t") var title string - // TODO REFACTOR LINE == HERE - // - - - - - - - - - - - - - - + if len(line[0]) > 1 { title = line[0][1:] } else { title = "" } + if len(line) > 1 && len(line[0]) > 0 && string(line[0][0]) == "i" { splitContent[i] = " " + string(title) } else if len(line) >= 4 { - fulllink := fmt.Sprintf("%s://%s:%s/%s%s", "protocol" ,line[2], line[3], string(line[0][0]), line[1]) - links = append(links, fulllink) + link := buildLink(line[2], line[3], string(line[0][0]), line[1]) + links = append(links, link) linktext := fmt.Sprintf("(%s) %2d %s", getType(string(line[0][0])), len(links), title) splitContent[i] = linktext } } - return "", links + return strings.Join(splitContent, "\n"), links } // Returns false for all text formats (including html @@ -160,3 +161,24 @@ func IsDownloadOnly(gophertype string) bool { return true } } + +func buildLink(host, port, gtype, resource string) string { + switch gtype { + case "8", "T": + return fmt.Sprintf("telnet://%s:%s", host, port) + case "G": + return fmt.Sprintf("gemini://%s:%s%s", host, port, resource) + case "h": + u, tf := isWebLink(resource) + if tf { + if len(u) > 4 && string(u[:5]) == "http" { + return u + } else { + return fmt.Sprintf("http://%s", u) + } + } + return fmt.Sprintf("gopher://%s:%s/h%s", host, port, resource) + default: + return fmt.Sprintf("gopher://%s:%s/%s%s", host, port, gtype, resource) + } +} diff --git a/gopher/history.go b/gopher/history.go deleted file mode 100644 index 5fdc439..0000000 --- a/gopher/history.go +++ /dev/null @@ -1,112 +0,0 @@ -package gopher - -import ( - "errors" - "fmt" -) - -//------------------------------------------------\\ -// + + + T Y P E S + + + \\ -//--------------------------------------------------\\ - -// The history struct represents the history of the browsing -// session. It contains the current history position, the -// length of the active history space (this can be different -// from the available capacity in the Collection), and a -// collection array containing View structs representing -// each page in the current history. In general usage this -// struct should be initialized via the MakeHistory function. -type History struct { - Position int - Length int - Collection [20]View -} - -//------------------------------------------------\\ -// + + + R E C E I V E R S + + + \\ -//--------------------------------------------------\\ - -// The "Add" receiver takes a view and adds it to -// the history struct that called it. "Add" returns -// nothing. "Add" will shift history down if the max -// history length would be exceeded, and will reset -// history length if something is added in the middle. -func (h *History) Add(v View) { - v.ParseMap() - if h.Position == h.Length-1 && h.Length < len(h.Collection) { - h.Collection[h.Length] = v - h.Length++ - h.Position++ - } else if h.Position == h.Length-1 && h.Length == 20 { - for x := 1; x < len(h.Collection); x++ { - h.Collection[x-1] = h.Collection[x] - } - h.Collection[len(h.Collection)-1] = v - } else { - h.Position += 1 - h.Length = h.Position + 1 - h.Collection[h.Position] = v - } -} - -// The "Get" receiver is called by a history struct -// and returns a View from the current position, will -// return an error if history is empty and there is -// nothing to get. -func (h History) Get() (*View, error) { - if h.Position < 0 { - return nil, errors.New("History is empty, cannot get item from empty history.") - } - - return &h.Collection[h.Position], nil -} - -// The "GoBack" receiver is called by a history struct. -// When called it decrements the current position and -// displays the content for the View in that position. -// If history is at position 0, no action is taken. -func (h *History) GoBack() bool { - if h.Position > 0 { - h.Position-- - return true - } - - fmt.Print("\a") - return false -} - -// The "GoForward" receiver is called by a history struct. -// When called it increments the current position and -// displays the content for the View in that position. -// If history is at position len - 1, no action is taken. -func (h *History) GoForward() bool { - if h.Position+1 < h.Length { - h.Position++ - return true - } - - fmt.Print("\a") - return false -} - -// The "DisplayCurrentView" receiver is called by a history -// struct. It calls the Display receiver for th view struct -// at the current history position. "DisplayCurrentView" does -// not return anything, and does nothing if position is less -// that 0. -func (h *History) DisplayCurrentView() { - h.Collection[h.Position].Display() -} - -//------------------------------------------------\\ -// + + + F U N C T I O N S + + + \\ -//--------------------------------------------------\\ - -// Constructor function for History struct. -// This is used to initialize history position -// as -1, which is needed. Returns a copy of -// initialized History struct (does NOT return -// a pointer to the struct). -func MakeHistory() History { - return History{-1, 0, [20]View{}} -} diff --git a/gopher/url.go b/gopher/url.go deleted file mode 100644 index c94f020..0000000 --- a/gopher/url.go +++ /dev/null @@ -1,94 +0,0 @@ -package gopher - -import ( - "errors" - "regexp" - "strings" -) - -//------------------------------------------------\\ -// + + + T Y P E S + + + \\ -//--------------------------------------------------\\ - -// The url struct represents a URL for the rest of the system. -// It includes component parts as well as a full URL string. -type Url struct { - Scheme string - Host string - Port string - Gophertype string - Resource string - Full string - IsBinary bool -} - -//------------------------------------------------\\ -// + + + F U N C T I O N S + + + \\ -//--------------------------------------------------\\ - -// MakeUrl is a Url constructor that takes in a string -// representation of a url and returns a Url struct and -// an error (or nil). -func MakeUrl(u string) (Url, error) { - var out Url - re := regexp.MustCompile(`^((?Pgopher|http|https|ftp|telnet):\/\/)?(?P[\w\-\.\d]+)(?::(?P\d+)?)?(?:/(?P[01345679gIhisp])?)?(?P.*)?$`) - match := re.FindStringSubmatch(u) - - if valid := re.MatchString(u); !valid { - return out, errors.New("Invalid URL or command character") - } - - for i, name := range re.SubexpNames() { - switch name { - case "scheme": - out.Scheme = match[i] - case "host": - out.Host = match[i] - case "port": - out.Port = match[i] - case "type": - out.Gophertype = match[i] - case "resource": - out.Resource = match[i] - } - } - - if out.Scheme == "" { - out.Scheme = "gopher" - } - - if out.Host == "" { - return out, errors.New("no host") - } - - if out.Scheme == "gopher" && out.Port == "" { - out.Port = "70" - } else if out.Scheme == "http" && out.Port == "" { - out.Port = "80" - } else if out.Scheme == "https" && out.Port == "" { - out.Port = "443" - } - - if out.Gophertype == "" && (out.Resource == "" || out.Resource == "/") { - out.Gophertype = "1" - } - - if out.Scheme == "gopher" && out.Gophertype == "" { - out.Gophertype = "0" - } - - if out.Gophertype == "7" && strings.Contains(out.Resource, "\t") { - out.Gophertype = "1" - } - - switch out.Gophertype { - case "1", "0", "h", "7": - out.IsBinary = false - default: - out.IsBinary = true - } - - out.Full = out.Scheme + "://" + out.Host + ":" + out.Port + "/" + out.Gophertype + out.Resource - - return out, nil -} diff --git a/gopher/view.go b/gopher/view.go deleted file mode 100644 index 813f4ca..0000000 --- a/gopher/view.go +++ /dev/null @@ -1,83 +0,0 @@ -package gopher - -import ( - "fmt" - "strings" -) - -//------------------------------------------------\\ -// + + + T Y P E S + + + \\ -//--------------------------------------------------\\ - -// View is a struct representing a gopher page. It contains -// the page content as a string slice, a list of link URLs -// as string slices, and the Url struct representing the page. -type View struct { - Content []string - Links []string - Address Url -} - -//------------------------------------------------\\ -// + + + R E C E I V E R S + + + \\ -//--------------------------------------------------\\ - -// ParseMap is called by a view struct to parse a gophermap. -// It checks if the view is for a gophermap. If not,it does -// nothing. If so, it parses the gophermap into comment lines -// and link lines. For link lines it adds a link to the links -// slice and changes the content value to just the printable -// string plus a gophertype indicator and a link number that -// relates to the link position in the links slice. This -// receiver does not return anything. -func (v *View) ParseMap() { - if v.Address.Gophertype == "1" || v.Address.Gophertype == "7" { - for i, e := range v.Content { - e = strings.Trim(e, "\r\n") - if e == "." { - v.Content[i] = " " - continue - } - - line := strings.Split(e, "\t") - var title string - if len(line[0]) > 1 { - title = line[0][1:] - } else { - title = "" - } - if len(line) > 1 && len(line[0]) > 0 && string(line[0][0]) == "i" { - v.Content[i] = " " + string(title) - } else if len(line) >= 4 { - fulllink := fmt.Sprintf("%s:%s/%s%s", line[2], line[3], string(line[0][0]), line[1]) - v.Links = append(v.Links, fulllink) - linktext := fmt.Sprintf("(%s) %2d %s", getType(string(line[0][0])), len(v.Links), title) - v.Content[i] = linktext - } - } - } -} - -// Display is called on a view struct to print the contents of the view. -// This receiver does not return anything. -func (v View) Display() { - fmt.Println() - for _, el := range v.Content { - fmt.Println(el) - } -} - -//------------------------------------------------\\ -// + + + F U N C T I O N S + + + \\ -//--------------------------------------------------\\ - -// MakeView creates and returns a new View struct from -// a Url and a string splice of content. This is used to -// initialize a View with a Url struct, links, and content. -// It takes a Url struct and a content []string and returns -// a View (NOT a pointer to a View). -func MakeView(url Url, content []string) View { - v := View{content, make([]string, 0), url} - v.ParseMap() - return v -} diff --git a/headbar.go b/headbar.go index 8aafc55..d467a43 100644 --- a/headbar.go +++ b/headbar.go @@ -1,5 +1,8 @@ package main +import ( + "fmt" +) //------------------------------------------------\\ // + + + T Y P E S + + + \\ @@ -7,8 +10,6 @@ package main type Headbar struct { title string - url string - content string } @@ -16,13 +17,8 @@ type Headbar struct { // + + + R E C E I V E R S + + + \\ //--------------------------------------------------\\ -func (h *Headbar) SetUrl(u string) { - h.url = u -} - func (h *Headbar) Build(width string) string { // TODO Build out header to specified width - h.content = "" // This is a temp value to show intention return "" } @@ -31,9 +27,9 @@ func (h *Headbar) Draw() { // without having to redraw everything else } -func (h *Headbar) Render() string { - // TODO returns the content value - return "" +func (h *Headbar) Render(width int, message string) string { + maxMsgWidth := width - len([]rune(h.title)) + return fmt.Sprintf("\033[7m%s%-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, message) } @@ -42,6 +38,6 @@ func (h *Headbar) Render() string { //--------------------------------------------------\\ func MakeHeadbar(title string) Headbar { - return Headbar{title, "", title} + return Headbar{title} } diff --git a/main.go b/main.go index ff354bb..9f2e642 100644 --- a/main.go +++ b/main.go @@ -174,8 +174,8 @@ func initClient() error { } func main() { - cui.HandleAlternateScreen("smcup") - defer cui.Exit() + // cui.HandleAlternateScreen("smcup") + // defer cui.Exit() err := initClient() if err != nil { // if we can't initialize we should bail out @@ -189,12 +189,12 @@ func main() { // If a url was passed, move it down the line // Goroutine so keypresses can be made during // page load - go bombadillo.Visit(os.Args[1]) + bombadillo.Visit(os.Args[1]) } else { // Otherwise, load the homeurl // Goroutine so keypresses can be made during // page load - go bombadillo.Visit(bombadillo.Options["homeurl"]) + bombadillo.Visit(bombadillo.Options["homeurl"]) } // Loop indefinitely on user input diff --git a/page.go b/page.go index 9fa0a0e..e67124d 100644 --- a/page.go +++ b/page.go @@ -1,12 +1,16 @@ package main +import ( + "strings" + "bytes" +) //------------------------------------------------\\ // + + + T Y P E S + + + \\ //--------------------------------------------------\\ type Page struct { - WrappedContent string + WrappedContent []string RawContent string Links []string Location Url @@ -17,14 +21,64 @@ type Page struct { // + + + R E C E I V E R S + + + \\ //--------------------------------------------------\\ +func (p *Page) ScrollPositionRange(termHeight int) (int, int) { + termHeight -= 3 + if len(p.WrappedContent) - p.ScrollPosition < termHeight { + p.ScrollPosition = len(p.WrappedContent) - termHeight + } + if p.ScrollPosition < 0 { + p.ScrollPosition = 0 + } + var end int + if len(p.WrappedContent) < termHeight { + end = len(p.WrappedContent) + } else { + end = p.ScrollPosition + termHeight + } + return p.ScrollPosition, end +} + +func (p *Page) WrapContent(width int) { + // TODO this is a temporary wrapping function + // in order to test. Rebuild it. + src := strings.Split(p.RawContent, "\n") + out := []string{} + for _, ln := range src { + if len([]rune(ln)) <= width { + out = append(out, ln) + } else { + words := strings.SplitAfter(ln, " ") + var subout bytes.Buffer + for i, wd := range words { + sublen := subout.Len() + wdlen := len([]rune(wd)) + if sublen+wdlen <= width { + subout.WriteString(wd) + if i == len(words)-1 { + out = append(out, subout.String()) + } + } else { + out = append(out, subout.String()) + subout.Reset() + subout.WriteString(wd) + if i == len(words)-1 { + out = append(out, subout.String()) + subout.Reset() + } + } + } + } + } + p.WrappedContent = out +} //------------------------------------------------\\ // + + + F U N C T I O N S + + + \\ //--------------------------------------------------\\ -func MakePage(url Url, content string) Page { - p := Page{"", content, make([]string, 0), url, 0} +func MakePage(url Url, content string, links []string) Page { + p := Page{make([]string, 0), content, links, url, 0} return p } diff --git a/pages.go b/pages.go index 5c844e8..a4f12c3 100644 --- a/pages.go +++ b/pages.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "strings" ) //------------------------------------------------\\ @@ -31,16 +32,30 @@ func (p *Pages) NavigateHistory(qty int) error { return nil } -func (p *Pages) Add(pg Page) error { - // TODO add the given page onto the pages struct - // handling truncation of the history as needed. - return fmt.Errorf("") +func (p *Pages) Add(pg Page) { + if p.Position == p.Length - 1 && p.Length < len(p.History) { + p.History[p.Length] = pg + p.Length++ + p.Position++ + } else if p.Position == p.Length - 1 && p.Length == 20 { + for x := 1; x < len(p.History); x++ { + p.History[x-1] = p.History[x] + } + p.History[len(p.History)-1] = pg + } else { + p.Position += 1 + p.Length = p.Position + 1 + p.History[p.Position] = pg + } } -func (p *Pages) Render() ([]string, error) { - // TODO grab the current page as wrappedContent - // May need to handle spacing at end of lines. - return []string{}, fmt.Errorf("") +func (p *Pages) Render(termHeight int) []string { + if p.Length < 1 { + msg := "Welcome to Bombadillo,\nif this is your first time here\ntype:\n\n:help\n(and then press enter)" + return strings.Split(msg, "\n") + } + beg, end := p.History[p.Position].ScrollPositionRange(termHeight) + return p.History[p.Position].WrappedContent[beg:end] } //------------------------------------------------\\ diff --git a/url.go b/url.go index b6dfebd..58673fd 100644 --- a/url.go +++ b/url.go @@ -37,11 +37,11 @@ type Url struct { // an error (or nil). func MakeUrl(u string) (Url, error) { var out Url - re := regexp.MustCompile(`^((?Pgopher|http|https|gemini):\/\/)?(?P[\w\-\.\d]+)(?::(?P\d+)?)?(?:/(?P[01345679gIhisp])?)?(?P.*)?$`) + re := regexp.MustCompile(`^((?Pgopher|telnet|http|https|gemini):\/\/)?(?P[\w\-\.\d]+)(?::(?P\d+)?)?(?:/(?P[01345679gIhisp])?)?(?P.*)?$`) match := re.FindStringSubmatch(u) if valid := re.MatchString(u); !valid { - return out, fmt.Errorf("Invalid url/unable to parse") + return out, fmt.Errorf("Invalid url, unable to parse") } for i, name := range re.SubexpNames() { From 98e34576ca11e11865712f82ae99a1152899fdc8 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Thu, 12 Sep 2019 20:57:48 -0700 Subject: [PATCH 06/25] Worked out resizing and wrapping bugs. Now hard wraps, rather than soft. --- bookmarks.go | 4 +-- client.go | 72 +++++++++++++++++++++++++++++++++++++++++----------- headbar.go | 7 ++--- main.go | 8 ++++-- page.go | 45 +++++++++++++++----------------- pages.go | 30 +++++++++++++++++----- url.go | 2 +- 7 files changed, 114 insertions(+), 54 deletions(-) diff --git a/bookmarks.go b/bookmarks.go index 503e648..3e08eab 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -106,11 +106,11 @@ func (b Bookmarks) Render(termwidth, termheight int) []string { bl = cui.Shapes["bl"] } - out := make([]string, 5) + out := make([]string, 0, 5) top := fmt.Sprintf("%s%s%s", tl, strings.Repeat(ceil, width-2), tr) out = append(out, top) marks := b.List() - contentWidth := termwidth - 2 + contentWidth := width - 2 for i := 0; i < termheight - 2; i++ { if i + b.Position >= b.Length { out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, "", wall )) diff --git a/client.go b/client.go index f326fbc..c59195b 100644 --- a/client.go +++ b/client.go @@ -59,32 +59,45 @@ func (c *client) GetSize() { c.Height = h c.Width = w + if redraw { c.Draw() } - time.Sleep(1 * time.Second) + time.Sleep(500 * time.Millisecond) } } func (c *client) Draw() { var screen strings.Builder screen.Grow(c.Height * c.Width) - screen.WriteString(c.TopBar.Render(c.Width, "This is a test")) + screen.WriteString(c.TopBar.Render(c.Width)) screen.WriteString("\n") - pageContent := c.PageState.Render(c.Height) + pageContent := c.PageState.Render(c.Height, c.Width) if c.BookMarks.IsOpen { bm := c.BookMarks.Render(c.Width, c.Height) - bmWidth := len([]rune(bm[0])) - for i, ln := range pageContent { - screen.WriteString(ln[:len(ln) - bmWidth]) + bmWidth := 40 + for i := 0; i < c.Height - 3; i++ { + if c.Width > bmWidth { + contentWidth := c.Width - bmWidth - 1 + if i < len(pageContent) - 1 { + screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, pageContent[i])) + } else { + screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, " ")) + } + } screen.WriteString(bm[i]) screen.WriteString("\n") } } else { - for _, ln := range pageContent { - screen.WriteString(ln) - screen.WriteString("\n") + for i := 0; i < c.Height - 3; i++ { + if i < len(pageContent) - 1 { + screen.WriteString(pageContent[i]) + screen.WriteString("\n") + } else { + screen.WriteString(fmt.Sprintf("%*s", c.Width, " ")) + screen.WriteString("\n") + } } } screen.WriteString("\n") // for the input line @@ -92,6 +105,7 @@ func (c *client) Draw() { cui.Clear("screen") cui.MoveCursorTo(0,0) fmt.Print(screen.String()) + c.DrawMessage() } func (c *client) TakeControlInput() { @@ -100,34 +114,49 @@ func (c *client) TakeControlInput() { switch input { case 'j', 'J': // scroll down one line + c.ClearMessage() + c.ClearMessageLine() c.Scroll(1) case 'k', 'K': // scroll up one line + c.ClearMessage() + c.ClearMessageLine() c.Scroll(-1) case 'q', 'Q': // quite bombadillo cui.Exit() case 'g': // scroll to top + c.ClearMessage() + c.ClearMessageLine() c.Scroll(-len(c.PageState.History[c.PageState.Position].WrappedContent)) case 'G': // scroll to bottom + c.ClearMessage() + c.ClearMessageLine() c.Scroll(len(c.PageState.History[c.PageState.Position].WrappedContent)) case 'd': // scroll down 75% + c.ClearMessage() + c.ClearMessageLine() distance := c.Height - c.Height / 4 c.Scroll(distance) case 'u': // scroll up 75% + c.ClearMessage() + c.ClearMessageLine() distance := c.Height - c.Height / 4 c.Scroll(-distance) case 'b': // go back + c.ClearMessage() + c.ClearMessageLine() err := c.PageState.NavigateHistory(-1) if err != nil { c.SetMessage(err.Error(), false) c.DrawMessage() } else { + c.SetHeaderUrl() c.Draw() } case 'B': @@ -136,11 +165,14 @@ func (c *client) TakeControlInput() { c.Draw() case 'f', 'F': // go forward + c.ClearMessage() + c.ClearMessageLine() err := c.PageState.NavigateHistory(1) if err != nil { c.SetMessage(err.Error(), false) c.DrawMessage() } else { + c.SetHeaderUrl() c.Draw() } case '\t': @@ -151,7 +183,6 @@ func (c *client) TakeControlInput() { // Process a command c.ClearMessage() c.ClearMessageLine() - cui.MoveCursorTo(c.Height-2, 0) entry, err := cui.GetLine() c.ClearMessageLine() if err != nil { @@ -378,13 +409,13 @@ func (c *client) search() { func (c *client) Scroll(amount int) { page := c.PageState.History[c.PageState.Position] - bottom := len(page.WrappedContent) - c.Height + bottom := len(page.WrappedContent) - c.Height + 3 // 3 for the three bars: top, msg, bottom if amount < 0 && page.ScrollPosition == 0 { c.SetMessage("You are already at the top", false) c.DrawMessage() fmt.Print("\a") return - } else if amount > 0 && page.ScrollPosition == bottom || bottom < 0 { + } else if (amount > 0 && page.ScrollPosition == bottom) || bottom < 0 { c.SetMessage("You are already at the bottom", false) c.DrawMessage() fmt.Print("\a") @@ -398,7 +429,7 @@ func (c *client) Scroll(amount int) { newScrollPosition = bottom } - page.ScrollPosition = newScrollPosition + c.PageState.History[c.PageState.Position].ScrollPosition = newScrollPosition c.Draw() } @@ -464,9 +495,15 @@ func (c *client) goToLink(l string) { return } } +} - c.SetMessage(fmt.Sprintf("Invalid link id: %s", l), true) - c.DrawMessage() +func (c *client) SetHeaderUrl() { + if c.PageState.Length > 0 { + u := c.PageState.History[c.PageState.Position].Location.Full + c.TopBar.url = u + } else { + c.TopBar.url = "" + } } func (c *client) Visit(url string) { @@ -487,6 +524,8 @@ func (c *client) Visit(url string) { c.DrawMessage() return } + c.SetMessage("Loading...", false) + c.DrawMessage() content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) if err != nil { c.SetMessage(err.Error(), true) @@ -496,6 +535,9 @@ func (c *client) Visit(url string) { pg := MakePage(u, content, links) pg.WrapContent(c.Width) c.PageState.Add(pg) + c.ClearMessage() + c.ClearMessageLine() + c.SetHeaderUrl() c.Draw() case "gemini": // TODO send over to gemini request diff --git a/headbar.go b/headbar.go index d467a43..8782857 100644 --- a/headbar.go +++ b/headbar.go @@ -10,6 +10,7 @@ import ( type Headbar struct { title string + url string } @@ -27,9 +28,9 @@ func (h *Headbar) Draw() { // without having to redraw everything else } -func (h *Headbar) Render(width int, message string) string { +func (h *Headbar) Render(width int) string { maxMsgWidth := width - len([]rune(h.title)) - return fmt.Sprintf("\033[7m%s%-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, message) + return fmt.Sprintf("\033[7m%s%-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, h.url) } @@ -38,6 +39,6 @@ func (h *Headbar) Render(width int, message string) string { //--------------------------------------------------\\ func MakeHeadbar(title string) Headbar { - return Headbar{title} + return Headbar{title, ""} } diff --git a/main.go b/main.go index 9f2e642..780189f 100644 --- a/main.go +++ b/main.go @@ -163,6 +163,10 @@ func loadConfig() error { } } + for i, v := range settings.Bookmarks.Titles { + bombadillo.BookMarks.Add([]string{v, settings.Bookmarks.Links[i]}) + } + return nil } @@ -174,8 +178,8 @@ func initClient() error { } func main() { - // cui.HandleAlternateScreen("smcup") - // defer cui.Exit() + cui.HandleAlternateScreen("smcup") + defer cui.Exit() err := initClient() if err != nil { // if we can't initialize we should bail out diff --git a/page.go b/page.go index e67124d..3fe0a0e 100644 --- a/page.go +++ b/page.go @@ -2,7 +2,6 @@ package main import ( "strings" - "bytes" ) //------------------------------------------------\\ @@ -42,35 +41,31 @@ func (p *Page) ScrollPositionRange(termHeight int) (int, int) { func (p *Page) WrapContent(width int) { // TODO this is a temporary wrapping function // in order to test. Rebuild it. - src := strings.Split(p.RawContent, "\n") - out := []string{} - for _, ln := range src { - if len([]rune(ln)) <= width { - out = append(out, ln) + counter := 0 + var content strings.Builder + content.Grow(len(p.RawContent)) + for _, ch := range p.RawContent { + if ch == '\n' { + content.WriteRune(ch) + counter = 0 } else { - words := strings.SplitAfter(ln, " ") - var subout bytes.Buffer - for i, wd := range words { - sublen := subout.Len() - wdlen := len([]rune(wd)) - if sublen+wdlen <= width { - subout.WriteString(wd) - if i == len(words)-1 { - out = append(out, subout.String()) - } - } else { - out = append(out, subout.String()) - subout.Reset() - subout.WriteString(wd) - if i == len(words)-1 { - out = append(out, subout.String()) - subout.Reset() - } + if counter < width { + content.WriteRune(ch) + counter++ + } else { + content.WriteRune('\n') + counter = 0 + if p.Location.Mime == "1" { + spacer := " " + content.WriteString(spacer) + counter += len(spacer) } + content.WriteRune(ch) } } } - p.WrappedContent = out + + p.WrappedContent = strings.Split(content.String(), "\n") } //------------------------------------------------\\ diff --git a/pages.go b/pages.go index a4f12c3..9fde2d2 100644 --- a/pages.go +++ b/pages.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "strings" ) //------------------------------------------------\\ @@ -49,13 +48,32 @@ func (p *Pages) Add(pg Page) { } } -func (p *Pages) Render(termHeight int) []string { +func (p *Pages) Render(termHeight, termWidth int) []string { if p.Length < 1 { - msg := "Welcome to Bombadillo,\nif this is your first time here\ntype:\n\n:help\n(and then press enter)" - return strings.Split(msg, "\n") + return []string{""} } - beg, end := p.History[p.Position].ScrollPositionRange(termHeight) - return p.History[p.Position].WrappedContent[beg:end] + pos := p.History[p.Position].ScrollPosition + prev := len(p.History[p.Position].WrappedContent) + p.History[p.Position].WrapContent(termWidth) + now := len(p.History[p.Position].WrappedContent) + if prev > now { + diff := prev - now + pos = pos - diff + } else if prev < now { + diff := now - prev + pos = pos + diff + if pos > now - termHeight { + pos = now - termHeight + } + } + + if pos < 0 || now < termHeight - 3 { + pos = 0 + } + + p.History[p.Position].ScrollPosition = pos + + return p.History[p.Position].WrappedContent[pos:] } //------------------------------------------------\\ diff --git a/url.go b/url.go index 58673fd..7956d94 100644 --- a/url.go +++ b/url.go @@ -78,7 +78,7 @@ func MakeUrl(u string) (Url, error) { } if out.Scheme == "gopher" && out.Mime == "" { - out.Mime = "0" + out.Mime = "1" } if out.Mime == "" && (out.Resource == "" || out.Resource == "/") && out.Scheme == "gopher" { From f2f730f3c5d01c837b1dac771f55d88069fb39dc Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Fri, 13 Sep 2019 22:56:38 -0700 Subject: [PATCH 07/25] Vast improvements, still squashing bugs like crazy. --- bookmarks.go | 6 +-- client.go | 128 +++++++++++++++++++++++++++++++++++++++------------ defaults.go | 49 ++++++++++++++++++++ footbar.go | 27 +++++++---- headbar.go | 10 ++-- main.go | 99 ++------------------------------------- page.go | 18 +++++++- pages.go | 2 +- 8 files changed, 196 insertions(+), 143 deletions(-) create mode 100644 defaults.go diff --git a/bookmarks.go b/bookmarks.go index 3e08eab..a3eb82d 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -107,10 +107,10 @@ func (b Bookmarks) Render(termwidth, termheight int) []string { } out := make([]string, 0, 5) - top := fmt.Sprintf("%s%s%s", tl, strings.Repeat(ceil, width-2), tr) + contentWidth := width - 2 + top := fmt.Sprintf("%s%s%s", tl, strings.Repeat(ceil, contentWidth), tr) out = append(out, top) marks := b.List() - contentWidth := width - 2 for i := 0; i < termheight - 2; i++ { if i + b.Position >= b.Length { out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, "", wall )) @@ -119,7 +119,7 @@ func (b Bookmarks) Render(termwidth, termheight int) []string { } } - bottom := fmt.Sprintf("%s%s%s", bl, strings.Repeat(ceil, width-2), br) + bottom := fmt.Sprintf("%s%s%s", bl, strings.Repeat(ceil, contentWidth), br) out = append(out, bottom) return out } diff --git a/client.go b/client.go index c59195b..016cf3f 100644 --- a/client.go +++ b/client.go @@ -6,7 +6,7 @@ import ( "net" "os" "os/exec" - "os/user" + // "os/user" "regexp" "strconv" "strings" @@ -41,6 +41,8 @@ type client struct { //--------------------------------------------------\\ func (c *client) GetSize() { + c.SetMessage("Initializing...", false) + c.DrawMessage() for { redraw := false cmd := exec.Command("stty", "size") @@ -71,28 +73,33 @@ func (c *client) GetSize() { func (c *client) Draw() { var screen strings.Builder screen.Grow(c.Height * c.Width) - screen.WriteString(c.TopBar.Render(c.Width)) + screen.WriteString(c.TopBar.Render(c.Width, c.Options["theme"])) screen.WriteString("\n") pageContent := c.PageState.Render(c.Height, c.Width) + if c.Options["theme"] == "inverse" { + screen.WriteString("\033[7m") + } if c.BookMarks.IsOpen { bm := c.BookMarks.Render(c.Width, c.Height) - bmWidth := 40 + // TODO remove this hard coded value + bmWidth := len([]rune(bm[0])) for i := 0; i < c.Height - 3; i++ { if c.Width > bmWidth { - contentWidth := c.Width - bmWidth - 1 - if i < len(pageContent) - 1 { + contentWidth := c.Width - bmWidth + if i < len(pageContent) { screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, pageContent[i])) } else { screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, " ")) } } + screen.WriteString(bm[i]) screen.WriteString("\n") } } else { for i := 0; i < c.Height - 3; i++ { if i < len(pageContent) - 1 { - screen.WriteString(pageContent[i]) + screen.WriteString(fmt.Sprintf("%-*.*s", c.Width, c.Width, pageContent[i])) screen.WriteString("\n") } else { screen.WriteString(fmt.Sprintf("%*s", c.Width, " ")) @@ -100,8 +107,9 @@ func (c *client) Draw() { } } } + screen.WriteString("\033[0m") screen.WriteString("\n") // for the input line - screen.WriteString(c.FootBar.Render(c.Width)) + screen.WriteString(c.FootBar.Render(c.Width, c.PageState.Position, c.Options["theme"])) cui.Clear("screen") cui.MoveCursorTo(0,0) fmt.Print(screen.String()) @@ -183,6 +191,9 @@ func (c *client) TakeControlInput() { // Process a command c.ClearMessage() c.ClearMessageLine() + if c.Options["theme"] == "normal" { + fmt.Printf("\033[7m%*.*s\r", c.Width, c.Width, "") + } entry, err := cui.GetLine() c.ClearMessageLine() if err != nil { @@ -190,6 +201,7 @@ func (c *client) TakeControlInput() { c.DrawMessage() break } else if strings.TrimSpace(entry) == "" { + c.DrawMessage() break } @@ -221,7 +233,7 @@ func (c *client) routeCommandInput(com *cmdparse.Command) error { case cmdparse.DO: c.doCommand(com.Action, com.Value) case cmdparse.DOLINK: - // err = doLinkCommand(com.Action, com.Target) + c.doLinkCommand(com.Action, com.Target) case cmdparse.DOAS: c.doCommandAs(com.Action, com.Value) case cmdparse.DOLINKAS: @@ -337,7 +349,8 @@ func (c *client) doCommandAs(action string, values []string) { c.SetMessage("Value set, but error saving config to file", true) c.DrawMessage() } else { - c.SetMessage(fmt.Sprintf("%s is now set to %q", values[0], c.Options[values[0]]), true) + c.Draw() + c.SetMessage(fmt.Sprintf("%s is now set to %q", values[0], c.Options[values[0]]), false) c.DrawMessage() } return @@ -373,6 +386,47 @@ func (c *client) saveFile(data []byte, name string) (string, error) { return savePath, nil } +func (c *client) doLinkCommand(action, target string) { + num, err := strconv.Atoi(target) + if err != nil { + c.SetMessage(fmt.Sprintf("Expected number, got %q", target), true) + c.DrawMessage() + } + + switch action { + case "DELETE", "D": + msg, err := c.BookMarks.Delete(num) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } else { + c.SetMessage(msg, false) + c.DrawMessage() + } + + err = saveConfig() + if err != nil { + c.SetMessage("Error saving bookmark deletion to file", true) + c.DrawMessage() + } + if c.BookMarks.IsOpen { + c.Draw() + } + case "BOOKMARKS", "B": + if num > len(c.BookMarks.Links)-1 { + c.SetMessage(fmt.Sprintf("There is no bookmark with ID %d", num), true) + c.DrawMessage() + return + } + c.Visit(c.BookMarks.Links[num]) + default: + c.SetMessage(fmt.Sprintf("Action %q does not exist for target %q", action, target), true) + c.DrawMessage() + } + +} + func (c *client) search() { c.ClearMessage() c.ClearMessageLine() @@ -408,6 +462,7 @@ func (c *client) search() { } func (c *client) Scroll(amount int) { + var percentRead int page := c.PageState.History[c.PageState.Position] bottom := len(page.WrappedContent) - c.Height + 3 // 3 for the three bars: top, msg, bottom if amount < 0 && page.ScrollPosition == 0 { @@ -416,6 +471,7 @@ func (c *client) Scroll(amount int) { fmt.Print("\a") return } else if (amount > 0 && page.ScrollPosition == bottom) || bottom < 0 { + c.FootBar.SetPercentRead(100) c.SetMessage("You are already at the bottom", false) c.DrawMessage() fmt.Print("\a") @@ -430,6 +486,14 @@ func (c *client) Scroll(amount int) { } c.PageState.History[c.PageState.Position].ScrollPosition = newScrollPosition + + if len(page.WrappedContent) < c.Height - 3 { + percentRead = 100 + } else { + percentRead = int(float32(newScrollPosition + c.Height - 3) / float32(len(page.WrappedContent)) * 100.0) + } + c.FootBar.SetPercentRead(percentRead) + c.Draw() } @@ -446,21 +510,30 @@ func (c *client) displayConfigValue(setting string) { func (c *client) SetMessage(msg string, isError bool) { leadIn, leadOut := "", "" if isError { - leadIn = "\033[31m" + leadIn = "\033[91m" + leadOut = "\033[0m" + + if c.Options["theme"] == "normal" { + leadIn = "\033[101;7m" + } + } + + if c.Options["theme"] == "normal" { + leadIn = "\033[7m" leadOut = "\033[0m" } - c.Message = fmt.Sprintf("%s%s%s", leadIn, msg, leadOut) + c.Message = fmt.Sprintf("%s%-*.*s%s", leadIn, c.Width, c.Width, msg, leadOut) } func (c *client) DrawMessage() { c.ClearMessageLine() cui.MoveCursorTo(c.Height-1, 0) - fmt.Print(c.Message) + fmt.Printf("%s", c.Message) } func (c *client) ClearMessage() { - c.Message = "" + c.SetMessage("", false) } func (c *client) ClearMessageLine() { @@ -518,12 +591,6 @@ func (c *client) Visit(url string) { switch u.Scheme { case "gopher": - u, err := MakeUrl(url) - if err != nil { - c.SetMessage(err.Error(), true) - c.DrawMessage() - return - } c.SetMessage("Loading...", false) c.DrawMessage() content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) @@ -535,13 +602,14 @@ func (c *client) Visit(url string) { pg := MakePage(u, content, links) pg.WrapContent(c.Width) c.PageState.Add(pg) + c.Scroll(0) // to update percent read c.ClearMessage() c.ClearMessageLine() c.SetHeaderUrl() c.Draw() case "gemini": // TODO send over to gemini request - c.SetMessage("Gemini is not currently supported", false) + c.SetMessage("Bombadillo has not mastered Gemini yet, check back soon", false) c.DrawMessage() case "telnet": c.SetMessage("Attempting to start telnet session", false) @@ -582,16 +650,16 @@ func (c *client) Visit(url string) { //--------------------------------------------------\\ func MakeClient(name string) *client { - var userinfo, _ = user.Current() - var options = map[string]string{ - "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", - "savelocation": userinfo.HomeDir, - "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", - "openhttp": "false", - "httpbrowser": "lynx", - "configlocation": userinfo.HomeDir, - } - c := client{0, 0, options, "", MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} + // var userinfo, _ = user.Current() + // var options = map[string]string{ + // "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", + // "savelocation": userinfo.HomeDir, + // "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", + // "openhttp": "false", + // "httpbrowser": "lynx", + // "configlocation": userinfo.HomeDir, + // } + c := client{0, 0, defaultOptions, "", MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} return &c } diff --git a/defaults.go b/defaults.go new file mode 100644 index 0000000..87fa557 --- /dev/null +++ b/defaults.go @@ -0,0 +1,49 @@ +package main + +import ( + "os/user" +) + +var userinfo, _ = user.Current() +var defaultOptions = map[string]string{ + // + // General configuration options + // + "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", + "savelocation": userinfo.HomeDir, + "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", + "openhttp": "false", + "httpbrowser": "lynx", + "telnetcommand": "telnet", + "configlocation": userinfo.HomeDir, + "theme": "normal", // "normal", "inverted" +} + +// TODO decide whether or not to institute a color theme +// system. Preliminary testing implies it should be very +// doable. +var theme = map[string]string{ + "topbar_title_bg": "", + "topbar_link_fg": "", + "body_bg": "237", + "body_fg": "", + "bookmarks_bg": "", + "bookmarks_fg": "", + "command_bg": "", + "message_fg": "", + "error_fg": "", + "bottombar_bg": "", + "bottombar_fg": "", + // + // text style options + // + "topbar_title_style": "bold", + "topbar_link_style": "plain", + "body_style": "plain", + "bookmark_body_style": "plain", + "bookmark_border_style": "plain", + "message_style": "italic", + "error_style": "bold", + "command_style": "plain", + "bottom_bar_style": "plain", +} diff --git a/footbar.go b/footbar.go index dab20bf..c2d2e27 100644 --- a/footbar.go +++ b/footbar.go @@ -2,14 +2,16 @@ package main import ( "fmt" + "strconv" ) + //------------------------------------------------\\ // + + + T Y P E S + + + \\ //--------------------------------------------------\\ type Footbar struct { - PercentRead int + PercentRead string PageType string } @@ -19,20 +21,25 @@ type Footbar struct { //--------------------------------------------------\\ func (f *Footbar) SetPercentRead(p int) { - f.PercentRead = p + if p > 100 { + p = 100 + } else if p < 0 { + p = 0 + } + f.PercentRead = strconv.Itoa(p) + "%" } func (f *Footbar) SetPageType(t string) { f.PageType = t } -func (f *Footbar) Draw() { - // TODO this will actually draw the bar - // without having to redraw everything else -} - -func (f *Footbar) Render(termWidth int) string { - return fmt.Sprintf("\033[7m%-*.*s\033[0m", termWidth, termWidth, "") +func (f *Footbar) Render(termWidth, position int, theme string) string { + pre := fmt.Sprintf("HST: (%2.2d) - - - %4s Read ", position + 1, f.PercentRead) + out := "\033[0m%*.*s " + if theme == "inverse" { + out = "\033[7m%*.*s \033[0m" + } + return fmt.Sprintf(out, termWidth - 1, termWidth - 1, pre) } @@ -41,6 +48,6 @@ func (f *Footbar) Render(termWidth int) string { //--------------------------------------------------\\ func MakeFootbar() Footbar { - return Footbar{100, "N/A"} + return Footbar{"---", "N/A"} } diff --git a/headbar.go b/headbar.go index 8782857..e1f1434 100644 --- a/headbar.go +++ b/headbar.go @@ -28,9 +28,13 @@ func (h *Headbar) Draw() { // without having to redraw everything else } -func (h *Headbar) Render(width int) string { - maxMsgWidth := width - len([]rune(h.title)) - return fmt.Sprintf("\033[7m%s%-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, h.url) +func (h *Headbar) Render(width int, theme string) string { + maxMsgWidth := width - len([]rune(h.title)) - 2 + if theme == "inverse" { + return fmt.Sprintf("\033[7m%s▟\033[27m %-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, h.url) + } else { + return fmt.Sprintf("%s▟\033[7m %-*.*s\033[0m", h.title, maxMsgWidth, maxMsgWidth, h.url) + } } diff --git a/main.go b/main.go index 780189f..e754b9e 100644 --- a/main.go +++ b/main.go @@ -3,12 +3,10 @@ package main import ( "io/ioutil" "os" - // "strconv" "strings" "tildegit.org/sloum/bombadillo/config" "tildegit.org/sloum/bombadillo/cui" - // "tildegit.org/sloum/bombadillo/gopher" ) var bombadillo *client @@ -32,96 +30,6 @@ var settings config.Config // } - -// func doLinkCommand(action, target string) error { - // num, err := strconv.Atoi(target) - // if err != nil { - // return fmt.Errorf("Expected number, got %q", target) - // } - - // switch action { - // case "DELETE", "D": - // err := settings.Bookmarks.Del(num) - // if err != nil { - // return err - // } - - // screen.Windows[1].Content = settings.Bookmarks.List() - // err = saveConfig() - // if err != nil { - // return err - // } - - // screen.ReflashScreen(false) - // return nil - // case "BOOKMARKS", "B": - // if num > len(settings.Bookmarks.Links)-1 { - // return fmt.Errorf("There is no bookmark with ID %d", num) - // } - // err := goToURL(settings.Bookmarks.Links[num]) - // return err - // } - - // return fmt.Errorf("This method has not been built") -// } - - -// func doCommand(action string, values []string) error { - // if length := len(values); length != 1 { - // return fmt.Errorf("Expected 1 argument, received %d", length) - // } - - // switch action { - // case "CHECK", "C": - // err := checkConfigValue(values[0]) - // if err != nil { - // return err - // } - // return nil - // } - // return fmt.Errorf("Unknown command structure") -// } - -// func doLinkCommandAs(action, target string, values []string) error { - // num, err := strconv.Atoi(target) - // if err != nil { - // return fmt.Errorf("Expected number, got %q", target) - // } - - // links := history.Collection[history.Position].Links - // if num >= len(links) { - // return fmt.Errorf("Invalid link id: %s", target) - // } - - // switch action { - // case "ADD", "A": - // newBookmark := append([]string{links[num-1]}, values...) - // err := settings.Bookmarks.Add(newBookmark) - // if err != nil { - // return err - // } - - // screen.Windows[1].Content = settings.Bookmarks.List() - - // err = saveConfig() - // if err != nil { - // return err - // } - - // screen.ReflashScreen(false) - // return nil - // case "WRITE", "W": - // return saveFile(links[num-1], strings.Join(values, " ")) - // } - - // return fmt.Errorf("This method has not been built") -// } - -// func updateMainContent() { - // screen.Windows[0].Content = history.Collection[history.Position].Content - // screen.Bars[0].SetMessage(history.Collection[history.Position].Address.Full) -// } - func saveConfig() error { bkmrks := bombadillo.BookMarks.IniDump() // TODO opts becomes a string builder rather than concat @@ -186,6 +94,9 @@ func main() { panic(err) } + // TODO find out why the loading message + // has disappeared on initial load... + // Start polling for terminal size changes go bombadillo.GetSize() @@ -193,12 +104,12 @@ func main() { // If a url was passed, move it down the line // Goroutine so keypresses can be made during // page load - bombadillo.Visit(os.Args[1]) + go bombadillo.Visit(os.Args[1]) } else { // Otherwise, load the homeurl // Goroutine so keypresses can be made during // page load - bombadillo.Visit(bombadillo.Options["homeurl"]) + go bombadillo.Visit(bombadillo.Options["homeurl"]) } // Loop indefinitely on user input diff --git a/page.go b/page.go index 3fe0a0e..20514b6 100644 --- a/page.go +++ b/page.go @@ -38,9 +38,11 @@ func (p *Page) ScrollPositionRange(termHeight int) (int, int) { return p.ScrollPosition, end } +// Performs a hard wrap to the requested +// width and updates the WrappedContent +// of the Page struct width a string slice +// of the wrapped data func (p *Page) WrapContent(width int) { - // TODO this is a temporary wrapping function - // in order to test. Rebuild it. counter := 0 var content strings.Builder content.Grow(len(p.RawContent)) @@ -48,6 +50,18 @@ func (p *Page) WrapContent(width int) { if ch == '\n' { content.WriteRune(ch) counter = 0 + } else if ch == '\t' { + if counter + 4 < width { + content.WriteString(" ") + counter += 4 + } else { + content.WriteRune('\n') + counter = 0 + } + } else if ch == '\r' { + // This handles non-linux line endings... + // to some degree... + continue } else { if counter < width { content.WriteRune(ch) diff --git a/pages.go b/pages.go index 9fde2d2..08a403b 100644 --- a/pages.go +++ b/pages.go @@ -50,7 +50,7 @@ func (p *Pages) Add(pg Page) { func (p *Pages) Render(termHeight, termWidth int) []string { if p.Length < 1 { - return []string{""} + return make([]string, 0) } pos := p.History[p.Position].ScrollPosition prev := len(p.History[p.Position].WrappedContent) From cb3bcc9465907fe17ed6bbd57e4e22aa2ed40d3e Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sat, 14 Sep 2019 15:45:23 -0700 Subject: [PATCH 08/25] Relicenses bobmadillo --- LICENSE | 867 +++++++++++------------------------------------ client.go | 55 ++- gopher/gopher.go | 2 +- main.go | 10 +- url.go | 4 + 5 files changed, 233 insertions(+), 705 deletions(-) diff --git a/LICENSE b/LICENSE index f288702..63d7936 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,195 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +Non-Profit Open Software License 3.0 + +This Non-Profit Open Software License ("Non-Profit OSL") version 3.0 (the +"License") applies to any original work of authorship (the "Original Work") +whose owner (the "Licensor") has placed the following licensing notice adjacent +to the copyright notice for the Original Work: + +Licensed under the Non-Profit Open Software License version 3.0 + +1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, for the duration of the copyright, to +do the following: + + a) to reproduce the Original Work in copies, either alone or as part of a + collective work; + + b) to translate, adapt, alter, transform, modify, or arrange the Original + Work, thereby creating derivative works ("Derivative Works") based upon the + Original Work; + + c) to distribute or communicate copies of the Original Work and Derivative + Works to the public, with the proviso that copies of Original Work or Derivative + Works that You distribute or communicate shall be licensed under this Non-Profit + Open Software License or as provided in section 17(d); + + d) to perform the Original Work publicly; and + + e) to display the Original Work publicly. + +2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, +non-exclusive, sublicensable license, under patent claims owned or controlled +by the Licensor that are embodied in the Original Work as furnished by the +Licensor, for the duration of the patents, to make, use, sell, offer for sale, +have made, and import the Original Work and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the preferred +form of the Original Work for making modifications to it and all available +documentation describing how to modify the Original Work. Licensor agrees +to provide a machine-readable copy of the Source Code of the Original Work +along with each copy of the Original Work that Licensor distributes. Licensor +reserves the right to satisfy this obligation by placing a machine-readable +copy of the Source Code in an information repository reasonably calculated +to permit inexpensive and convenient access by You for as long as Licensor +continues to distribute the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the names +of any contributors to the Original Work, nor any of their trademarks or service +marks, may be used to endorse or promote products derived from this Original +Work without express prior permission of the Licensor. Except as expressly +stated herein, nothing in this License grants any license to Licensor's trademarks, +copyrights, patents, trade secrets or any other intellectual property. No +patent license is granted to make, use, sell, offer for sale, have made, or +import embodiments of any patent claims other than the licensed claims defined +in Section 2. No license is granted to the trademarks of Licensor even if +such marks are included in the Original Work. Nothing in this License shall +be interpreted to prohibit Licensor from licensing under terms different from +this License any Original Work that Licensor otherwise would have a right +to license. + +5) External Deployment. The term "External Deployment" means the use, distribution, +or communication of the Original Work or Derivative Works in any way such +that the Original Work or Derivative Works may be used by anyone other than +You, whether those works are distributed or communicated to those persons +or made available as an application intended for use over a network. As an +express condition for the grants of license hereunder, You must treat any +External Deployment by You of the Original Work or a Derivative Work as a +distribution under section 1(c). + +6) Attribution Rights. You must retain, in the Source Code of any Derivative +Works that You create, all copyright, patent, or trademark notices from the +Source Code of the Original Work, as well as any notices of licensing and +any descriptive text identified therein as an "Attribution Notice." You must +cause the Source Code for any Derivative Works that You create to carry a +prominent Attribution Notice reasonably calculated to inform recipients that +You have modified the Original Work. + +7) Warranty of Provenance and Disclaimer of Warranty. The Original Work is +provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either +express or implied, including, without limitation, the warranties of non-infringement, +merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO +THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY +constitutes an essential part of this License. No license to the Original +Work is granted by this License except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal theory, +whether in tort (including negligence), contract, or otherwise, shall the +Licensor be liable to anyone for any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License +or the use of the Original Work including, without limitation, damages for +loss of goodwill, work stoppage, computer failure or malfunction, or any and +all other commercial damages or losses. This limitation of liability shall +not apply to the extent applicable law prohibits such limitation. + +9) Acceptance and Termination. If, at any time, You expressly assented to +this License, that assent indicates your clear and irrevocable acceptance +of this License and all of its terms and conditions. If You distribute or +communicate copies of the Original Work or a Derivative Work, You must make +a reasonable effort under the circumstances to obtain the express assent of +recipients to the terms of this License. This License conditions your rights +to undertake the activities listed in Section 1, including your right to create +Derivative Works based upon the Original Work, and doing so without honoring +these terms and conditions is prohibited by copyright law and international +treaty. Nothing in this License is intended to affect copyright exceptions +and limitations (including "fair use" or "fair dealing"). This License shall +terminate immediately and You may no longer exercise any of the rights granted +to You by this License upon your failure to honor the conditions in Section +1(c). + +10) Termination for Patent Action. This License shall terminate automatically +and You may no longer exercise any of the rights granted to You by this License +as of the date You commence an action, including a cross-claim or counterclaim, +against Licensor or any licensee alleging that the Original Work infringes +a patent. This termination provision shall not apply for an action alleging +patent infringement by combinations of the Original Work with other software +or hardware. + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to +this License may be brought only in the courts of a jurisdiction wherein the +Licensor resides or in which Licensor conducts its primary business, and under +the laws of that jurisdiction excluding its conflict-of-law provisions. The +application of the United Nations Convention on Contracts for the International +Sale of Goods is expressly excluded. Any use of the Original Work outside +the scope of this License or after its termination shall be subject to the +requirements and penalties of copyright or patent law in the appropriate jurisdiction. +This section shall survive the termination of this License. + +12) Attorneys' Fees. In any action to enforce the terms of this License or +seeking damages relating thereto, the prevailing party shall be entitled to +recover its costs and expenses, including, without limitation, reasonable +attorneys' fees and costs incurred in connection with such action, including +any appeal of such action. This section shall survive the termination of this +License. + +13) Miscellaneous. If any provision of this License is held to be unenforceable, +such provision shall be reformed only to the extent necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, whether +in upper or lower case, means an individual or a legal entity exercising rights +under, and complying with all of the terms of, this License. For legal entities, +"You" includes any entity that controls, is controlled by, or is under common +control with you. For purposes of this definition, "control" means (i) the +power, direct or indirect, to cause the direction or management of such entity, +whether by contract or otherwise, or (ii) ownership of fifty percent (50%) +or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +15) Right to Use. You may use the Original Work in all ways not otherwise +restricted or conditioned by this License or by law, and Licensor promises +not to interfere with or be responsible for such uses by You. + +16) Modification of This License. This License is Copyright © 2005 Lawrence +Rosen. Permission is granted to copy, distribute, or communicate this License +without modification. Nothing in this License permits You to modify this License +as applied to the Original Work or to Derivative Works. However, You may modify +the text of this License and copy, distribute or communicate your modified +version (the "Modified License") and apply it to other original works of authorship +subject to the following conditions: (i) You may not indicate in any way that +your Modified License is the "Open Software License" or "OSL" and you may +not use those names in the name of your Modified License; (ii) You must replace +the notice specified in the first paragraph above with the notice "Licensed +under " or with a notice of your own that is +not confusingly similar to the notice in this License; and (iii) You may not +claim that your original works are open source software unless your Modified +License has been approved by Open Source Initiative (OSI) and You comply with +its license review and certification process. + +17) Non-Profit Amendment. The name of this amended version of the Open Software +License ("OSL 3.0") is "Non-Profit Open Software License 3.0". The original +OSL 3.0 license has been amended as follows: + + (a) Licensor represents and declares that it is a not-for-profit organization + that derives no revenue whatsoever from the distribution of the Original Work + or Derivative Works thereof, or from support or services relating thereto. + + (b) The first sentence of Section 7 ["Warranty of Provenance"] of OSL 3.0 + has been stricken. For Original Works licensed under this Non-Profit OSL 3.0, + LICENSOR OFFERS NO WARRANTIES WHATSOEVER. + + (c) In the first sentence of Section 8 ["Limitation of Liability"] of this + Non-Profit OSL 3.0, the list of damages for which LIABILITY IS LIMITED now + includes "direct" damages. + + (d) The proviso in Section 1(c) of this License now refers to this "Non-Profit + Open Software License" rather than the "Open Software License". You may distribute + or communicate the Original Work or Derivative Works thereof under this Non-Profit + OSL 3.0 license only if You make the representation and declaration in paragraph + (a) of this Section 17. Otherwise, You shall distribute or communicate the + Original Work or Derivative Works thereof only under the OSL 3.0 license and + You shall publish clear licensing notices so stating. Also by way of clarification, + this License does not authorize You to distribute or communicate works under + this Non-Profit OSL 3.0 if You received them under the original OSL 3.0 license. + + (e) Original Works licensed under this license shall reference "Non-Profit + OSL 3.0" in licensing notices to distinguish them from works licensed under + the original OSL 3.0 license. - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/client.go b/client.go index 016cf3f..91a6d10 100644 --- a/client.go +++ b/client.go @@ -40,11 +40,26 @@ type client struct { // + + + R E C E I V E R S + + + \\ //--------------------------------------------------\\ +func (c *client) GetSizeOnce() { + cmd := exec.Command("stty", "size") + cmd.Stdin = os.Stdin + out, err := cmd.Output() + if err != nil { + fmt.Println("Fatal error: Unable to retrieve terminal size") + os.Exit(5) + } + var h, w int + fmt.Sscan(string(out), &h, &w) + c.Height = h + c.Width = w +} + func (c *client) GetSize() { - c.SetMessage("Initializing...", false) - c.DrawMessage() + c.GetSizeOnce() + c.SetMessage("Loading...", false) + c.Draw() + for { - redraw := false cmd := exec.Command("stty", "size") cmd.Stdin = os.Stdin out, err := cmd.Output() @@ -55,14 +70,8 @@ func (c *client) GetSize() { var h, w int fmt.Sscan(string(out), &h, &w) if h != c.Height || w != c.Width { - redraw = true - } - - c.Height = h - c.Width = w - - - if redraw { + c.Height = h + c.Width = w c.Draw() } @@ -81,7 +90,6 @@ func (c *client) Draw() { } if c.BookMarks.IsOpen { bm := c.BookMarks.Render(c.Width, c.Height) - // TODO remove this hard coded value bmWidth := len([]rune(bm[0])) for i := 0; i < c.Height - 3; i++ { if c.Width > bmWidth { @@ -108,12 +116,12 @@ func (c *client) Draw() { } } screen.WriteString("\033[0m") + screen.WriteString(c.Message) screen.WriteString("\n") // for the input line screen.WriteString(c.FootBar.Render(c.Width, c.PageState.Position, c.Options["theme"])) cui.Clear("screen") cui.MoveCursorTo(0,0) fmt.Print(screen.String()) - c.DrawMessage() } func (c *client) TakeControlInput() { @@ -123,12 +131,10 @@ func (c *client) TakeControlInput() { case 'j', 'J': // scroll down one line c.ClearMessage() - c.ClearMessageLine() c.Scroll(1) case 'k', 'K': // scroll up one line c.ClearMessage() - c.ClearMessageLine() c.Scroll(-1) case 'q', 'Q': // quite bombadillo @@ -136,29 +142,24 @@ func (c *client) TakeControlInput() { case 'g': // scroll to top c.ClearMessage() - c.ClearMessageLine() c.Scroll(-len(c.PageState.History[c.PageState.Position].WrappedContent)) case 'G': // scroll to bottom c.ClearMessage() - c.ClearMessageLine() c.Scroll(len(c.PageState.History[c.PageState.Position].WrappedContent)) case 'd': // scroll down 75% c.ClearMessage() - c.ClearMessageLine() distance := c.Height - c.Height / 4 c.Scroll(distance) case 'u': // scroll up 75% c.ClearMessage() - c.ClearMessageLine() distance := c.Height - c.Height / 4 c.Scroll(-distance) case 'b': // go back c.ClearMessage() - c.ClearMessageLine() err := c.PageState.NavigateHistory(-1) if err != nil { c.SetMessage(err.Error(), false) @@ -174,7 +175,6 @@ func (c *client) TakeControlInput() { case 'f', 'F': // go forward c.ClearMessage() - c.ClearMessageLine() err := c.PageState.NavigateHistory(1) if err != nil { c.SetMessage(err.Error(), false) @@ -349,9 +349,8 @@ func (c *client) doCommandAs(action string, values []string) { c.SetMessage("Value set, but error saving config to file", true) c.DrawMessage() } else { - c.Draw() c.SetMessage(fmt.Sprintf("%s is now set to %q", values[0], c.Options[values[0]]), false) - c.DrawMessage() + c.Draw() } return } @@ -527,7 +526,7 @@ func (c *client) SetMessage(msg string, isError bool) { } func (c *client) DrawMessage() { - c.ClearMessageLine() + // c.ClearMessageLine() cui.MoveCursorTo(c.Height-1, 0) fmt.Printf("%s", c.Message) } @@ -580,8 +579,9 @@ func (c *client) SetHeaderUrl() { } func (c *client) Visit(url string) { - // TODO both gemini and gopher should return a string - // The wrap lines function in cui needs to be rewritten + c.SetMessage("Loading...", false) + c.DrawMessage() + u, err := MakeUrl(url) if err != nil { c.SetMessage(err.Error(), true) @@ -591,8 +591,6 @@ func (c *client) Visit(url string) { switch u.Scheme { case "gopher": - c.SetMessage("Loading...", false) - c.DrawMessage() content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) if err != nil { c.SetMessage(err.Error(), true) @@ -604,7 +602,6 @@ func (c *client) Visit(url string) { c.PageState.Add(pg) c.Scroll(0) // to update percent read c.ClearMessage() - c.ClearMessageLine() c.SetHeaderUrl() c.Draw() case "gemini": diff --git a/gopher/gopher.go b/gopher/gopher.go index b990682..dbf0d49 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -171,7 +171,7 @@ func buildLink(host, port, gtype, resource string) string { case "h": u, tf := isWebLink(resource) if tf { - if len(u) > 4 && string(u[:5]) == "http" { + if len(u) > 4 && string(u[:4]) == "http" { return u } else { return fmt.Sprintf("http://%s", u) diff --git a/main.go b/main.go index e754b9e..4f8348a 100644 --- a/main.go +++ b/main.go @@ -1,5 +1,11 @@ package main +// Bombadillo is distributed under the "Non-Profit Open Source Software License 3.0" +// The license is included with the source code in the file LICENSE. The basic +// takeway: use, remix, and share this software for any purpose that is not a commercial +// purpose as defined by the above mentioned license and is itself distributed udner +// the terms of said license with said license file included. + import ( "io/ioutil" "os" @@ -104,12 +110,12 @@ func main() { // If a url was passed, move it down the line // Goroutine so keypresses can be made during // page load - go bombadillo.Visit(os.Args[1]) + bombadillo.Visit(os.Args[1]) } else { // Otherwise, load the homeurl // Goroutine so keypresses can be made during // page load - go bombadillo.Visit(bombadillo.Options["homeurl"]) + bombadillo.Visit(bombadillo.Options["homeurl"]) } // Loop indefinitely on user input diff --git a/url.go b/url.go index 7956d94..faedbbb 100644 --- a/url.go +++ b/url.go @@ -101,6 +101,10 @@ func MakeUrl(u string) (Url, error) { out.Mime = "" } + if out.Scheme == "http" || out.Scheme == "https" { + out.Mime = "" + } + out.Full = out.Scheme + "://" + out.Host + ":" + out.Port + "/" + out.Mime + out.Resource return out, nil From e7a1b4e34828f6028fc2b5254b4b25cc1d4f0a47 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sun, 15 Sep 2019 21:24:45 -0700 Subject: [PATCH 09/25] Fixes order of opperations issue when drawing messages --- client.go | 108 +++++++++++++++++++++++++++++++++++++++++++---------- headbar.go | 10 ----- main.go | 19 +++++----- 3 files changed, 98 insertions(+), 39 deletions(-) diff --git a/client.go b/client.go index 91a6d10..e0abfa6 100644 --- a/client.go +++ b/client.go @@ -29,6 +29,7 @@ type client struct { Width int Options map[string]string Message string + MessageIsErr bool PageState Pages BookMarks Bookmarks TopBar Headbar @@ -116,7 +117,8 @@ func (c *client) Draw() { } } screen.WriteString("\033[0m") - screen.WriteString(c.Message) + // TODO using message here breaks on resize, must regenerate + screen.WriteString(c.RenderMessage()) screen.WriteString("\n") // for the input line screen.WriteString(c.FootBar.Render(c.Width, c.PageState.Position, c.Options["theme"])) cui.Clear("screen") @@ -237,7 +239,7 @@ func (c *client) routeCommandInput(com *cmdparse.Command) error { case cmdparse.DOAS: c.doCommandAs(com.Action, com.Value) case cmdparse.DOLINKAS: - // err = doLinkCommandAs(com.Action, com.Target, com.Value) + c.doLinkCommandAs(com.Action, com.Target, com.Value) default: return fmt.Errorf("Unknown command entry!") } @@ -361,6 +363,52 @@ func (c *client) doCommandAs(action string, values []string) { c.SetMessage(fmt.Sprintf("Unknown command structure"), true) } +func (c *client) doLinkCommandAs(action, target string, values []string) { + num, err := strconv.Atoi(target) + if err != nil { + c.SetMessage(fmt.Sprintf("Expected link number, got %q", target), true) + c.DrawMessage() + return + } + + switch action { + case "ADD", "A": + links := c.PageState.History[c.PageState.Position].Links + if num >= len(links) { + c.SetMessage(fmt.Sprintf("Invalid link id: %s", target), true) + c.DrawMessage() + return + } + bm := make([]string, 0, 5) + bm = append(bm, links[num-1]) + bm = append(bm, values...) + msg, err := c.BookMarks.Add(bm) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } else { + c.SetMessage(msg, false) + c.DrawMessage() + } + + err = saveConfig() + if err != nil { + c.SetMessage("Error saving bookmark to file", true) + c.DrawMessage() + } + if c.BookMarks.IsOpen { + c.Draw() + } + case "WRITE", "W": + // TODO get file writing working in some semblance of universal way + // return saveFile(links[num-1], strings.Join(values, " ")) + default: + c.SetMessage(fmt.Sprintf("Unknown command structure"), true) + } +} + + func (c *client) getCurrentPageUrl() (string, error) { if c.PageState.Length < 1 { return "", fmt.Errorf("There are no pages in history") @@ -429,6 +477,9 @@ func (c *client) doLinkCommand(action, target string) { func (c *client) search() { c.ClearMessage() c.ClearMessageLine() + // TODO handle keeping the full command bar here + // like was done for regular command entry + // maybe split into separate function fmt.Print("?") entry, err := cui.GetLine() c.ClearMessageLine() @@ -439,9 +490,9 @@ func (c *client) search() { } else if strings.TrimSpace(entry) == "" { return } - u, err := MakeUrl(c.Options["searchurl"]) + u, err := MakeUrl(c.Options["searchengine"]) if err != nil { - c.SetMessage("'searchurl' is not set to a valid url", true) + c.SetMessage("'searchengine' is not set to a valid url", true) c.DrawMessage() return } @@ -507,28 +558,47 @@ func (c *client) displayConfigValue(setting string) { } func (c *client) SetMessage(msg string, isError bool) { + c.MessageIsErr = isError + c.Message = msg +} + +func (c *client) DrawMessage() { leadIn, leadOut := "", "" - if isError { - leadIn = "\033[91m" - leadOut = "\033[0m" - - if c.Options["theme"] == "normal" { - leadIn = "\033[101;7m" - } - } - if c.Options["theme"] == "normal" { leadIn = "\033[7m" leadOut = "\033[0m" } - c.Message = fmt.Sprintf("%s%-*.*s%s", leadIn, c.Width, c.Width, msg, leadOut) + if c.MessageIsErr { + leadIn = "\033[31;1m" + leadOut = "\033[0m" + + if c.Options["theme"] == "normal" { + leadIn = "\033[41;1;7m" + } + } + + cui.MoveCursorTo(c.Height-1, 0) + fmt.Printf("%s%-*.*s%s", leadIn, c.Width, c.Width, c.Message, leadOut) } -func (c *client) DrawMessage() { - // c.ClearMessageLine() - cui.MoveCursorTo(c.Height-1, 0) - fmt.Printf("%s", c.Message) +func (c *client) RenderMessage() string { + leadIn, leadOut := "", "" + if c.Options["theme"] == "normal" { + leadIn = "\033[7m" + leadOut = "\033[0m" + } + + if c.MessageIsErr { + leadIn = "\033[31;1m" + leadOut = "\033[0m" + + if c.Options["theme"] == "normal" { + leadIn = "\033[41;1;7m" + } + } + + return fmt.Sprintf("%s%-*.*s%s", leadIn, c.Width, c.Width, c.Message, leadOut) } func (c *client) ClearMessage() { @@ -656,7 +726,7 @@ func MakeClient(name string) *client { // "httpbrowser": "lynx", // "configlocation": userinfo.HomeDir, // } - c := client{0, 0, defaultOptions, "", MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} + c := client{0, 0, defaultOptions, "", false, MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} return &c } diff --git a/headbar.go b/headbar.go index e1f1434..e6d43ef 100644 --- a/headbar.go +++ b/headbar.go @@ -18,16 +18,6 @@ type Headbar struct { // + + + R E C E I V E R S + + + \\ //--------------------------------------------------\\ -func (h *Headbar) Build(width string) string { - // TODO Build out header to specified width - return "" -} - -func (h *Headbar) Draw() { - // TODO this will actually draw the bar - // without having to redraw everything else -} - func (h *Headbar) Render(width int, theme string) string { maxMsgWidth := width - len([]rune(h.title)) - 2 if theme == "inverse" { diff --git a/main.go b/main.go index 4f8348a..f87b4d8 100644 --- a/main.go +++ b/main.go @@ -37,17 +37,19 @@ var settings config.Config func saveConfig() error { + var opts strings.Builder bkmrks := bombadillo.BookMarks.IniDump() - // TODO opts becomes a string builder rather than concat - opts := "\n[SETTINGS]\n" + + opts.WriteString(bkmrks) + opts.WriteString("\n[SETTINGS]\n") for k, v := range bombadillo.Options { - opts += k - opts += "=" - opts += v - opts += "\n" + opts.WriteString(k) + opts.WriteRune('=') + opts.WriteString(v) + opts.WriteRune('\n') } - return ioutil.WriteFile(bombadillo.Options["configlocation"] + "/.bombadillo.ini", []byte(bkmrks+opts), 0644) + return ioutil.WriteFile(bombadillo.Options["configlocation"] + "/.bombadillo.ini", []byte(opts.String()), 0644) } func loadConfig() error { @@ -100,9 +102,6 @@ func main() { panic(err) } - // TODO find out why the loading message - // has disappeared on initial load... - // Start polling for terminal size changes go bombadillo.GetSize() From 1af11f1b8f3b4a48016321ec952571c2c593b397 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sun, 15 Sep 2019 21:26:32 -0700 Subject: [PATCH 10/25] Removes duplicated code in messaging system --- client.go | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/client.go b/client.go index e0abfa6..3aba883 100644 --- a/client.go +++ b/client.go @@ -563,23 +563,8 @@ func (c *client) SetMessage(msg string, isError bool) { } func (c *client) DrawMessage() { - leadIn, leadOut := "", "" - if c.Options["theme"] == "normal" { - leadIn = "\033[7m" - leadOut = "\033[0m" - } - - if c.MessageIsErr { - leadIn = "\033[31;1m" - leadOut = "\033[0m" - - if c.Options["theme"] == "normal" { - leadIn = "\033[41;1;7m" - } - } - cui.MoveCursorTo(c.Height-1, 0) - fmt.Printf("%s%-*.*s%s", leadIn, c.Width, c.Width, c.Message, leadOut) + fmt.Print(c.RenderMessage()) } func (c *client) RenderMessage() string { From 7e53ce6aea61531cb7e30cfcd62d91d73a20314c Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Mon, 16 Sep 2019 09:53:13 -0700 Subject: [PATCH 11/25] Fixed broken simple command: b --- client.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/client.go b/client.go index 3aba883..2800c35 100644 --- a/client.go +++ b/client.go @@ -82,7 +82,8 @@ func (c *client) GetSize() { func (c *client) Draw() { var screen strings.Builder - screen.Grow(c.Height * c.Width) + screen.Grow(c.Height * c.Width + c.Width) + screen.WriteString("\033[0m") screen.WriteString(c.TopBar.Render(c.Width, c.Options["theme"])) screen.WriteString("\n") pageContent := c.PageState.Render(c.Height, c.Width) @@ -121,7 +122,7 @@ func (c *client) Draw() { screen.WriteString(c.RenderMessage()) screen.WriteString("\n") // for the input line screen.WriteString(c.FootBar.Render(c.Width, c.PageState.Position, c.Options["theme"])) - cui.Clear("screen") + // cui.Clear("screen") cui.MoveCursorTo(0,0) fmt.Print(screen.String()) } @@ -216,7 +217,7 @@ func (c *client) TakeControlInput() { err := c.routeCommandInput(p) if err != nil { c.SetMessage(err.Error(), true) - c.DrawMessage() + c.Draw() } } } @@ -261,6 +262,7 @@ func (c *client) simpleCommand(action string) { } case "B", "BOOKMARKS": c.BookMarks.ToggleOpen() + c.Draw() case "SEARCH": c.search() case "HELP", "?": From 21fe5714a396e78e1a161e1127bfd943aa92d616 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Mon, 16 Sep 2019 19:38:07 -0700 Subject: [PATCH 12/25] Bookmarks can be scrolled when focused --- bookmarks.go | 18 ++++++---- client.go | 95 ++++++++++++++++++++++++++++++++++++---------------- cui/cui.go | 28 +++++++++------- 3 files changed, 93 insertions(+), 48 deletions(-) diff --git a/bookmarks.go b/bookmarks.go index a3eb82d..9647725 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -86,20 +86,24 @@ func (b Bookmarks) List() []string { func (b Bookmarks) Render(termwidth, termheight int) []string { width := 40 termheight -= 3 - var wall, ceil, tr, tl, br, bl string + var walll, wallr, floor, ceil, tr, tl, br, bl string if termwidth < 40 { width = termwidth } if b.IsFocused { - wall = cui.Shapes["awall"] + walll = cui.Shapes["awalll"] + wallr = cui.Shapes["awallr"] ceil = cui.Shapes["aceiling"] + floor = cui.Shapes["afloor"] tr = cui.Shapes["atr"] br = cui.Shapes["abr"] tl = cui.Shapes["atl"] bl = cui.Shapes["abl"] } else { - wall = cui.Shapes["wall"] + walll = cui.Shapes["walll"] + wallr = cui.Shapes["wallr"] ceil = cui.Shapes["ceiling"] + floor = cui.Shapes["floor"] tr = cui.Shapes["tr"] br = cui.Shapes["br"] tl = cui.Shapes["tl"] @@ -112,14 +116,14 @@ func (b Bookmarks) Render(termwidth, termheight int) []string { out = append(out, top) marks := b.List() for i := 0; i < termheight - 2; i++ { - if i + b.Position >= b.Length { - out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, "", wall )) + if i + b.Position >= len(b.Titles) { + out = append(out, fmt.Sprintf("%s%-*.*s%s", walll, contentWidth, contentWidth, "", wallr)) } else { - out = append(out, fmt.Sprintf("%s%-*.*s%s", wall, contentWidth, contentWidth, marks[i + b.Position], wall )) + out = append(out, fmt.Sprintf("%s%-*.*s%s", walll, contentWidth, contentWidth, marks[i + b.Position], wallr)) } } - bottom := fmt.Sprintf("%s%s%s", bl, strings.Repeat(ceil, contentWidth), br) + bottom := fmt.Sprintf("%s%s%s", bl, strings.Repeat(floor, contentWidth), br) out = append(out, bottom) return out } diff --git a/client.go b/client.go index 2800c35..372a00d 100644 --- a/client.go +++ b/client.go @@ -102,8 +102,21 @@ func (c *client) Draw() { screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, " ")) } } + + if c.Options["theme"] == "inverse" && !c.BookMarks.IsFocused { + screen.WriteString("\033[2;7m") + } else if !c.BookMarks.IsFocused { + screen.WriteString("\033[2m") + } screen.WriteString(bm[i]) + + if c.Options["theme"] == "inverse" && !c.BookMarks.IsFocused { + screen.WriteString("\033[7;22m") + } else if !c.BookMarks.IsFocused { + screen.WriteString("\033[0m") + } + screen.WriteString("\n") } } else { @@ -514,39 +527,63 @@ func (c *client) search() { } func (c *client) Scroll(amount int) { - var percentRead int - page := c.PageState.History[c.PageState.Position] - bottom := len(page.WrappedContent) - c.Height + 3 // 3 for the three bars: top, msg, bottom - if amount < 0 && page.ScrollPosition == 0 { - c.SetMessage("You are already at the top", false) - c.DrawMessage() - fmt.Print("\a") - return - } else if (amount > 0 && page.ScrollPosition == bottom) || bottom < 0 { - c.FootBar.SetPercentRead(100) - c.SetMessage("You are already at the bottom", false) - c.DrawMessage() - fmt.Print("\a") - return - } + if c.BookMarks.IsFocused { + bottom := len(c.BookMarks.Titles) - c.Height + 5 // 3 for the three bars: top, msg, bottom + if amount < 0 && c.BookMarks.Position == 0 { + c.SetMessage("The bookmark ladder does not go up any further", false) + c.DrawMessage() + fmt.Print("\a") + return + } else if (amount > 0 && c.BookMarks.Position == bottom) || bottom < 0 { + c.SetMessage("Feel the ground beneath your bookmarks", false) + c.DrawMessage() + fmt.Print("\a") + return + } - newScrollPosition := page.ScrollPosition + amount - if newScrollPosition < 0 { - newScrollPosition = 0 - } else if newScrollPosition > bottom { - newScrollPosition = bottom - } + newScrollPosition := c.BookMarks.Position + amount + if newScrollPosition < 0 { + newScrollPosition = 0 + } else if newScrollPosition > bottom { + newScrollPosition = bottom + } - c.PageState.History[c.PageState.Position].ScrollPosition = newScrollPosition - - if len(page.WrappedContent) < c.Height - 3 { - percentRead = 100 + c.BookMarks.Position = newScrollPosition + c.Draw() } else { - percentRead = int(float32(newScrollPosition + c.Height - 3) / float32(len(page.WrappedContent)) * 100.0) - } - c.FootBar.SetPercentRead(percentRead) + var percentRead int + page := c.PageState.History[c.PageState.Position] + bottom := len(page.WrappedContent) - c.Height + 3 // 3 for the three bars: top, msg, bottom + if amount < 0 && page.ScrollPosition == 0 { + c.SetMessage("You are already at the top", false) + c.DrawMessage() + fmt.Print("\a") + return + } else if (amount > 0 && page.ScrollPosition == bottom) || bottom < 0 { + c.FootBar.SetPercentRead(100) + c.SetMessage("You are already at the bottom", false) + c.DrawMessage() + fmt.Print("\a") + return + } - c.Draw() + newScrollPosition := page.ScrollPosition + amount + if newScrollPosition < 0 { + newScrollPosition = 0 + } else if newScrollPosition > bottom { + newScrollPosition = bottom + } + + c.PageState.History[c.PageState.Position].ScrollPosition = newScrollPosition + + if len(page.WrappedContent) < c.Height - 3 { + percentRead = 100 + } else { + percentRead = int(float32(newScrollPosition + c.Height - 3) / float32(len(page.WrappedContent)) * 100.0) + } + c.FootBar.SetPercentRead(percentRead) + c.Draw() + } } func (c *client) displayConfigValue(setting string) { diff --git a/cui/cui.go b/cui/cui.go index 5cb5d79..e6cfb1c 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -10,18 +10,22 @@ import ( ) var Shapes = map[string]string{ - "wall": "╵", - "ceiling": "╴", - "tl": "┌", - "tr": "┐", - "bl": "└", - "br": "┘", - "awall": "║", - "aceiling": "═", - "atl": "╔", - "atr": "╗", - "abl": "╚", - "abr": "╝", + "walll": "╎", + "wallr": " ", + "ceiling": " ", + "floor": " ", + "tl": "╎", + "tr": " ", + "bl": "╎", + "br": " ", + "awalll": "▌", + "awallr": "▐", + "aceiling": "▀", + "afloor": "▄", + "atl": "▞", + "atr": "▜", + "abl": "▚", + "abr": "▟", } func drawShape(shape string) { From 8a3ddad58e9829bfe61d5c6990c1d1c0ec34c0d8 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Tue, 17 Sep 2019 21:57:21 -0700 Subject: [PATCH 13/25] Added ability to view a link's url with the check command --- .gitignore | 1 + client.go | 30 +++++++++++++---- gemini/gemini.go | 83 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 7 deletions(-) create mode 100644 gemini/gemini.go diff --git a/.gitignore b/.gitignore index 9fe1ace..cb9380e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ bombadillo +*.asciinema diff --git a/client.go b/client.go index 372a00d..766bd96 100644 --- a/client.go +++ b/client.go @@ -386,16 +386,19 @@ func (c *client) doLinkCommandAs(action, target string, values []string) { return } + num -= 1 + + links := c.PageState.History[c.PageState.Position].Links + if num >= len(links) || num < 0 { + c.SetMessage(fmt.Sprintf("Invalid link id: %s", target), true) + c.DrawMessage() + return + } + switch action { case "ADD", "A": - links := c.PageState.History[c.PageState.Position].Links - if num >= len(links) { - c.SetMessage(fmt.Sprintf("Invalid link id: %s", target), true) - c.DrawMessage() - return - } bm := make([]string, 0, 5) - bm = append(bm, links[num-1]) + bm = append(bm, links[num]) bm = append(bm, values...) msg, err := c.BookMarks.Add(bm) if err != nil { @@ -455,6 +458,7 @@ func (c *client) doLinkCommand(action, target string) { c.DrawMessage() } + switch action { case "DELETE", "D": msg, err := c.BookMarks.Delete(num) @@ -482,6 +486,18 @@ func (c *client) doLinkCommand(action, target string) { return } c.Visit(c.BookMarks.Links[num]) + case "CHECK", "C": + num -= 1 + + links := c.PageState.History[c.PageState.Position].Links + if num >= len(links) || num < 0 { + c.SetMessage(fmt.Sprintf("Invalid link id: %s", target), true) + c.DrawMessage() + return + } + link := links[num] + c.SetMessage(fmt.Sprintf("[%d] %s", num + 1, link), false) + c.DrawMessage() default: c.SetMessage(fmt.Sprintf("Action %q does not exist for target %q", action, target), true) c.DrawMessage() diff --git a/gemini/gemini.go b/gemini/gemini.go new file mode 100644 index 0000000..d0f3ce9 --- /dev/null +++ b/gemini/gemini.go @@ -0,0 +1,83 @@ +package gemini + +import ( + "crypto/tls" + "fmt" + "net" + "io/ioutil" + // "strings" + "time" + + // "tildegit.org/sloum/mailcap" +) + + +//------------------------------------------------\\ +// + + + F U N C T I O N S + + + \\ +//--------------------------------------------------\\ + +func Retrieve(host, port, resource string) ([]byte, error) { + nullRes := make([]byte, 0) + timeOut := time.Duration(5) * time.Second + + if host == "" || port == "" { + return nullRes, fmt.Errorf("Incomplete request url") + } + + addr := host + ":" + port + + conf := &tls.Config{ + InsecureSkipVerify: true, + } + + conn, err := net.DialTimeout("tcp", addr, timeOut) + if err != nil { + return nullRes, err + } + + secureConn := tls.Client(conn, conf) + + send := resource + "\n" + + _, err = secureConn.Write([]byte(send)) + if err != nil { + return nullRes, err + } + + result, err := ioutil.ReadAll(conn) + if err != nil { + return nullRes, err + } + + return result, nil +} + +func Visit(host, port, resource string) (string, []string, error) { + resp, err := Retrieve(host, port, resource) + if err != nil { + return "", []string{}, err + } + + // TODO break out the header + // header := "" + mime := "" + mimeMaj := mime + mimeMin := mime + // status := "" + content := string(resp) + + if mimeMaj == "text" && mimeMin == "gemini" { + // text := string(resp) + // links := []string{} + + // TODO parse geminimap from 'content' + } else if mimeMaj == "text" { + // TODO just return the text + } else { + // TODO use mailcap to try and open the file + } + + + return content, []string{}, nil +} + From 7e4a32c67a27052d8326ac70d9ad4057f6bbad27 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Wed, 18 Sep 2019 20:27:56 -0700 Subject: [PATCH 14/25] Adds buggy but present gemini support --- client.go | 34 +++++++++-- gemini/gemini.go | 147 +++++++++++++++++++++++++++++++++++------------ url.go | 2 +- 3 files changed, 141 insertions(+), 42 deletions(-) diff --git a/client.go b/client.go index 766bd96..4a49108 100644 --- a/client.go +++ b/client.go @@ -14,7 +14,7 @@ import ( "tildegit.org/sloum/bombadillo/cmdparse" "tildegit.org/sloum/bombadillo/cui" - // "tildegit.org/sloum/bombadillo/gemini" + "tildegit.org/sloum/bombadillo/gemini" "tildegit.org/sloum/bombadillo/gopher" "tildegit.org/sloum/bombadillo/http" "tildegit.org/sloum/bombadillo/telnet" @@ -715,9 +715,35 @@ func (c *client) Visit(url string) { c.SetHeaderUrl() c.Draw() case "gemini": - // TODO send over to gemini request - c.SetMessage("Bombadillo has not mastered Gemini yet, check back soon", false) - c.DrawMessage() + capsule, err := gemini.Visit(u.Host, u.Port, u.Resource) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + switch capsule.Status { + case 2: + pg := MakePage(u, capsule.Content, capsule.Links) + pg.WrapContent(c.Width) + c.PageState.Add(pg) + c.Scroll(0) + c.ClearMessage() + c.SetHeaderUrl() + c.Draw() + case 3: + c.SetMessage("[3] Redirect. Follow redirect? y or any other key for no", false) + c.DrawMessage() + ch := cui.Getch() + if ch == 'y' || ch == 'Y' { + c.Visit(capsule.Content) + } else { + c.SetMessage("Redirect aborted", false) + c.DrawMessage() + } + } + + // c.SetMessage("Bombadillo has not mastered Gemini yet, check back soon", false) + // c.DrawMessage() case "telnet": c.SetMessage("Attempting to start telnet session", false) c.DrawMessage() diff --git a/gemini/gemini.go b/gemini/gemini.go index d0f3ce9..e8edee0 100644 --- a/gemini/gemini.go +++ b/gemini/gemini.go @@ -3,81 +3,154 @@ package gemini import ( "crypto/tls" "fmt" - "net" "io/ioutil" - // "strings" - "time" + "strconv" + "strings" // "tildegit.org/sloum/mailcap" ) +type Capsule struct { + MimeMaj string + MimeMin string + Status int + Content string + Links []string +} //------------------------------------------------\\ // + + + F U N C T I O N S + + + \\ //--------------------------------------------------\\ -func Retrieve(host, port, resource string) ([]byte, error) { - nullRes := make([]byte, 0) - timeOut := time.Duration(5) * time.Second - +func Retrieve(host, port, resource string) (string, error) { if host == "" || port == "" { - return nullRes, fmt.Errorf("Incomplete request url") + return "", fmt.Errorf("Incomplete request url") } addr := host + ":" + port conf := &tls.Config{ + MinVersion: tls.VersionTLS12, InsecureSkipVerify: true, } - conn, err := net.DialTimeout("tcp", addr, timeOut) + conn, err := tls.Dial("tcp", addr, conf) if err != nil { - return nullRes, err + return "", err } - secureConn := tls.Client(conn, conf) + defer conn.Close() - send := resource + "\n" + send := "gemini://" + addr + "/" + resource + "\r\n" - _, err = secureConn.Write([]byte(send)) + _, err = conn.Write([]byte(send)) if err != nil { - return nullRes, err + return "", err } result, err := ioutil.ReadAll(conn) if err != nil { - return nullRes, err + return "", err } - return result, nil + return string(result), nil } -func Visit(host, port, resource string) (string, []string, error) { - resp, err := Retrieve(host, port, resource) +func Visit(host, port, resource string) (Capsule, error) { + capsule := MakeCapsule() + rawResp, err := Retrieve(host, port, resource) if err != nil { - return "", []string{}, err + return capsule, err } + + resp := strings.SplitN(rawResp, "\r\n", 2) + if len(resp) != 2 { + if err != nil { + return capsule, fmt.Errorf("Invalid response from server") + } + } + header := strings.SplitN(resp[0], " ", 2) + if len([]rune(header[0])) != 2 { + header = strings.SplitN(resp[0], "\t", 2) + if len([]rune(header[0])) != 2 { + return capsule, fmt.Errorf("Invalid response format from server") + } + } + + body := resp[1] - // TODO break out the header - // header := "" - mime := "" - mimeMaj := mime - mimeMin := mime - // status := "" - content := string(resp) - - if mimeMaj == "text" && mimeMin == "gemini" { - // text := string(resp) - // links := []string{} - - // TODO parse geminimap from 'content' - } else if mimeMaj == "text" { - // TODO just return the text - } else { - // TODO use mailcap to try and open the file + // Get status code single digit form + capsule.Status, err = strconv.Atoi(string(header[0][0])) + if err != nil { + return capsule, fmt.Errorf("Invalid status response from server") } + // Parse the meta as needed + var meta string - return content, []string{}, nil + switch capsule.Status { + case 1: + // handle search + return capsule, fmt.Errorf("Gemini input not yet supported") + case 2: + mimeAndCharset := strings.Split(header[1], ";") + meta = mimeAndCharset[0] + minMajMime := strings.Split(meta, "/") + if len(minMajMime) < 2 { + return capsule, fmt.Errorf("Improperly formatted mimetype received from server") + } + capsule.MimeMaj = minMajMime[0] + capsule.MimeMin = minMajMime[1] + if capsule.MimeMaj == "text" && capsule.MimeMin == "gemini" { + rootUrl := fmt.Sprintf("gemini://%s:%s", host, port) + capsule.Content, capsule.Links = parseGemini(body, rootUrl) + } else { + capsule.Content = body + } + return capsule, nil + case 3: + // The client will handle informing the user of a redirect + // and then request the new url + capsule.Content = header[1] + return capsule, nil + case 4: + return capsule, fmt.Errorf("[4] Temporary Failure. %s", header[1]) + case 5: + return capsule, fmt.Errorf("[5] Permanent Failure. %s", header[1]) + case 6: + return capsule, fmt.Errorf("[6] Client Certificate Required (Not supported by Bombadillo)") + default: + return capsule, fmt.Errorf("Invalid response status from server") + } +} + +func parseGemini(b, rootUrl string) (string, []string) { + splitContent := strings.Split(b, "\n") + links := make([]string, 0, 10) + + for i, ln := range splitContent { + splitContent[i] = strings.Trim(ln, "\r\n") + if len([]rune(ln)) > 3 && ln[:2] == "=>" { + trimmedSubLn := strings.Trim(ln[2:], "\r\n\t \a") + lineSplit := strings.SplitN(trimmedSubLn, " ", 2) + if len(lineSplit) != 2 { + lineSplit = append(lineSplit, lineSplit[0]) + } + lineSplit[0] = strings.Trim(lineSplit[0], "\t\n\r \a") + lineSplit[1] = strings.Trim(lineSplit[1], "\t\n\r \a") + if len(lineSplit[0]) > 0 && lineSplit[0][0] == '/' { + lineSplit[0] = fmt.Sprintf("%s%s", rootUrl, lineSplit[0]) + } + links = append(links, lineSplit[0]) + linknum := fmt.Sprintf("[%d]", len(links)) + splitContent[i] = fmt.Sprintf("%-5s %s", linknum, lineSplit[1]) + } + } + return strings.Join(splitContent, "\n"), links +} + + +func MakeCapsule() Capsule { + return Capsule{"", "", 0, "", make([]string, 0, 5)} } diff --git a/url.go b/url.go index faedbbb..5babdc8 100644 --- a/url.go +++ b/url.go @@ -97,8 +97,8 @@ func MakeUrl(u string) (Url, error) { out.DownloadOnly = true } } else { - out.Resource = fmt.Sprintf("%s%s", out.Mime, out.Resource) out.Mime = "" + out.Resource = fmt.Sprintf("%s%s", out.Mime, out.Resource) } if out.Scheme == "http" || out.Scheme == "https" { From 5114ac1a157717b042876d3e73c47cd758fe0cfb Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Wed, 18 Sep 2019 22:03:19 -0700 Subject: [PATCH 15/25] Updates gophermap rendering to support gemini urls as h URL:... style links --- gopher/gopher.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gopher/gopher.go b/gopher/gopher.go index dbf0d49..3b15440 100644 --- a/gopher/gopher.go +++ b/gopher/gopher.go @@ -171,7 +171,7 @@ func buildLink(host, port, gtype, resource string) string { case "h": u, tf := isWebLink(resource) if tf { - if len(u) > 4 && string(u[:4]) == "http" { + if strings.Index(u, "://") > 0 { return u } else { return fmt.Sprintf("http://%s", u) From 08795920159e960ab5ec1f67258cff5c071bb8bb Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Thu, 19 Sep 2019 15:32:26 -0700 Subject: [PATCH 16/25] Adds search with terms inline, also gemini file rendering --- client.go | 48 +++++++++++++++++++++++++++--------------------- gemini/gemini.go | 27 +++++++++++++++++---------- 2 files changed, 44 insertions(+), 31 deletions(-) diff --git a/client.go b/client.go index 4a49108..6d3aa28 100644 --- a/client.go +++ b/client.go @@ -277,7 +277,7 @@ func (c *client) simpleCommand(action string) { c.BookMarks.ToggleOpen() c.Draw() case "SEARCH": - c.search() + c.search("") case "HELP", "?": go c.Visit(helplocation) default: @@ -296,6 +296,8 @@ func (c *client) doCommand(action string, values []string) { switch action { case "CHECK", "C": c.displayConfigValue(values[0]) + case "SEARCH": + c.search(strings.Join(values, " ")) default: c.SetMessage(fmt.Sprintf("Unknown action %q", action), true) c.DrawMessage() @@ -505,21 +507,27 @@ func (c *client) doLinkCommand(action, target string) { } -func (c *client) search() { - c.ClearMessage() - c.ClearMessageLine() - // TODO handle keeping the full command bar here - // like was done for regular command entry - // maybe split into separate function - fmt.Print("?") - entry, err := cui.GetLine() - c.ClearMessageLine() - if err != nil { - c.SetMessage(err.Error(), true) - c.DrawMessage() - return - } else if strings.TrimSpace(entry) == "" { - return +func (c *client) search(q string) { + var entry string + var err error + if q == "" { + c.ClearMessage() + c.ClearMessageLine() + if c.Options["theme"] == "normal" { + fmt.Printf("\033[7m%*.*s\r", c.Width, c.Width, "") + } + fmt.Print("?") + entry, err = cui.GetLine() + c.ClearMessageLine() + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } else if strings.TrimSpace(entry) == "" { + return + } + } else { + entry = q } u, err := MakeUrl(c.Options["searchengine"]) if err != nil { @@ -614,7 +622,7 @@ func (c *client) displayConfigValue(setting string) { func (c *client) SetMessage(msg string, isError bool) { c.MessageIsErr = isError - c.Message = msg + c.Message = strings.ReplaceAll(msg, "\t", "%09") } func (c *client) DrawMessage() { @@ -682,7 +690,7 @@ func (c *client) goToLink(l string) { func (c *client) SetHeaderUrl() { if c.PageState.Length > 0 { u := c.PageState.History[c.PageState.Position].Location.Full - c.TopBar.url = u + c.TopBar.url = strings.ReplaceAll(u, "\t", "%09") } else { c.TopBar.url = "" } @@ -692,6 +700,7 @@ func (c *client) Visit(url string) { c.SetMessage("Loading...", false) c.DrawMessage() + url = strings.ReplaceAll(url, "%09", "\t") u, err := MakeUrl(url) if err != nil { c.SetMessage(err.Error(), true) @@ -741,9 +750,6 @@ func (c *client) Visit(url string) { c.DrawMessage() } } - - // c.SetMessage("Bombadillo has not mastered Gemini yet, check back soon", false) - // c.DrawMessage() case "telnet": c.SetMessage("Attempting to start telnet session", false) c.DrawMessage() diff --git a/gemini/gemini.go b/gemini/gemini.go index e8edee0..f2fd88c 100644 --- a/gemini/gemini.go +++ b/gemini/gemini.go @@ -131,19 +131,26 @@ func parseGemini(b, rootUrl string) (string, []string) { for i, ln := range splitContent { splitContent[i] = strings.Trim(ln, "\r\n") if len([]rune(ln)) > 3 && ln[:2] == "=>" { - trimmedSubLn := strings.Trim(ln[2:], "\r\n\t \a") - lineSplit := strings.SplitN(trimmedSubLn, " ", 2) - if len(lineSplit) != 2 { - lineSplit = append(lineSplit, lineSplit[0]) + var link, decorator string + subLn := strings.Trim(ln[2:], "\r\n\t \a") + splitPoint := strings.IndexAny(subLn, " \t") + + if splitPoint < 0 || len([]rune(subLn)) - 1 <= splitPoint { + link = subLn + decorator = subLn + } else { + link = strings.Trim(subLn[:splitPoint], "\t\n\r \a") + decorator = strings.Trim(subLn[splitPoint:], "\t\n\r \a") } - lineSplit[0] = strings.Trim(lineSplit[0], "\t\n\r \a") - lineSplit[1] = strings.Trim(lineSplit[1], "\t\n\r \a") - if len(lineSplit[0]) > 0 && lineSplit[0][0] == '/' { - lineSplit[0] = fmt.Sprintf("%s%s", rootUrl, lineSplit[0]) + + if len(link) > 0 && link[0] == '/' { + link = fmt.Sprintf("%s%s", rootUrl, link) + } else if len(link) > 0 && strings.Index(link, "://") < 0 { + link = fmt.Sprintf("%s/%s", rootUrl, link) } - links = append(links, lineSplit[0]) + links = append(links, link) linknum := fmt.Sprintf("[%d]", len(links)) - splitContent[i] = fmt.Sprintf("%-5s %s", linknum, lineSplit[1]) + splitContent[i] = fmt.Sprintf("%-5s %s", linknum, decorator) } } return strings.Join(splitContent, "\n"), links From fdaf6312aba7c58d267479a969d77cb1db710867 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Thu, 19 Sep 2019 20:29:17 -0700 Subject: [PATCH 17/25] Adds a terminal mode change to disallow line wrapping by the terminal, also fixes a resize scroll issue and disallows escape characters in text files --- client.go | 21 +++++++++++++-------- cui/cui.go | 1 + main.go | 1 + page.go | 7 +++---- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/client.go b/client.go index 6d3aa28..544cf56 100644 --- a/client.go +++ b/client.go @@ -73,7 +73,7 @@ func (c *client) GetSize() { if h != c.Height || w != c.Width { c.Height = h c.Width = w - c.Draw() + c.Scroll(0) } time.Sleep(500 * time.Millisecond) @@ -732,13 +732,18 @@ func (c *client) Visit(url string) { } switch capsule.Status { case 2: - pg := MakePage(u, capsule.Content, capsule.Links) - pg.WrapContent(c.Width) - c.PageState.Add(pg) - c.Scroll(0) - c.ClearMessage() - c.SetHeaderUrl() - c.Draw() + if capsule.MimeMaj == "text" { + pg := MakePage(u, capsule.Content, capsule.Links) + pg.WrapContent(c.Width) + c.PageState.Add(pg) + c.Scroll(0) + c.ClearMessage() + c.SetHeaderUrl() + c.Draw() + } else { + c.SetMessage("Still mulling how to handle binary files... come back soon", false) + c.DrawMessage() + } case 3: c.SetMessage("[3] Redirect. Follow redirect? y or any other key for no", false) c.DrawMessage() diff --git a/cui/cui.go b/cui/cui.go index e6cfb1c..deb69ea 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -65,6 +65,7 @@ func Exit() { fmt.Print("\n") fmt.Print("\033[?25h") + HandleAlternateScreen("smam") HandleAlternateScreen("rmcup") os.Exit(0) } diff --git a/main.go b/main.go index f87b4d8..b738899 100644 --- a/main.go +++ b/main.go @@ -94,6 +94,7 @@ func initClient() error { } func main() { + cui.HandleAlternateScreen("rmam") cui.HandleAlternateScreen("smcup") defer cui.Exit() err := initClient() diff --git a/page.go b/page.go index 20514b6..ee8b68c 100644 --- a/page.go +++ b/page.go @@ -46,7 +46,7 @@ func (p *Page) WrapContent(width int) { counter := 0 var content strings.Builder content.Grow(len(p.RawContent)) - for _, ch := range p.RawContent { + for _, ch := range []rune(p.RawContent) { if ch == '\n' { content.WriteRune(ch) counter = 0 @@ -58,9 +58,8 @@ func (p *Page) WrapContent(width int) { content.WriteRune('\n') counter = 0 } - } else if ch == '\r' { - // This handles non-linux line endings... - // to some degree... + } else if ch == '\r' || ch == '\v' || ch == '\b' || ch == '\f' || ch == 27 { + // Get rid of control characters we dont want continue } else { if counter < width { From 8c42748432874c7ac83c2f50fbbaf4caf82279ff Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Thu, 19 Sep 2019 21:29:52 -0700 Subject: [PATCH 18/25] Fixes issue where percent read was incorrect when moving through history --- client.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/client.go b/client.go index 544cf56..da0a40f 100644 --- a/client.go +++ b/client.go @@ -101,6 +101,7 @@ func (c *client) Draw() { } else { screen.WriteString(fmt.Sprintf("%-*.*s", contentWidth, contentWidth, " ")) } + screen.WriteString("\033[500C\033[39D") } if c.Options["theme"] == "inverse" && !c.BookMarks.IsFocused { @@ -125,7 +126,7 @@ func (c *client) Draw() { screen.WriteString(fmt.Sprintf("%-*.*s", c.Width, c.Width, pageContent[i])) screen.WriteString("\n") } else { - screen.WriteString(fmt.Sprintf("%*s", c.Width, " ")) + screen.WriteString(fmt.Sprintf("%*.*s", c.Width, c.Width, " ")) screen.WriteString("\n") } } @@ -182,6 +183,7 @@ func (c *client) TakeControlInput() { c.DrawMessage() } else { c.SetHeaderUrl() + c.SetPercentRead() c.Draw() } case 'B': @@ -197,6 +199,7 @@ func (c *client) TakeControlInput() { c.DrawMessage() } else { c.SetHeaderUrl() + c.SetPercentRead() c.Draw() } case '\t': @@ -610,6 +613,17 @@ func (c *client) Scroll(amount int) { } } +func (c *client) SetPercentRead() { + page := c.PageState.History[c.PageState.Position] + var percentRead int + if len(page.WrappedContent) < c.Height - 3 { + percentRead = 100 + } else { + percentRead = int(float32(page.ScrollPosition + c.Height - 3) / float32(len(page.WrappedContent)) * 100.0) + } + c.FootBar.SetPercentRead(percentRead) +} + func (c *client) displayConfigValue(setting string) { if val, ok := c.Options[setting]; ok { c.SetMessage(fmt.Sprintf("%s is set to: %q", setting, val), false) From 19f210f2431a1cbc58b0a11784354d73d0376a0f Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Fri, 20 Sep 2019 09:18:16 -0700 Subject: [PATCH 19/25] Renames a cui function to be more appropriate and adds command line flag for version number --- cui/cui.go | 6 +++--- main.go | 20 ++++++++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/cui/cui.go b/cui/cui.go index deb69ea..6fe79b5 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -65,8 +65,8 @@ func Exit() { fmt.Print("\n") fmt.Print("\033[?25h") - HandleAlternateScreen("smam") - HandleAlternateScreen("rmcup") + Tput("smam") // turn off line wrap + Tput("rmcup") // use alternate screen os.Exit(0) } @@ -178,7 +178,7 @@ func SetLineMode() { } } -func HandleAlternateScreen(opt string) { +func Tput(opt string) { cmd := exec.Command("tput", opt) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout diff --git a/main.go b/main.go index b738899..b5b8a01 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,8 @@ package main // the terms of said license with said license file included. import ( + "flag" + "fmt" "io/ioutil" "os" "strings" @@ -15,6 +17,8 @@ import ( "tildegit.org/sloum/bombadillo/cui" ) +const version = "2.0.0" + var bombadillo *client var helplocation string = "gopher://colorfield.space:70/1/bombadillo-info" var settings config.Config @@ -94,8 +98,16 @@ func initClient() error { } func main() { - cui.HandleAlternateScreen("rmam") - cui.HandleAlternateScreen("smcup") + getVersion := flag.Bool("v", false, "See version number") + flag.Parse() + if *getVersion { + fmt.Printf("Bombadillo v%s\n", version) + os.Exit(0) + } + args := flag.Args() + + cui.Tput("rmam") // turn off line wrapping + cui.Tput("smcup") // use alternate screen defer cui.Exit() err := initClient() if err != nil { @@ -106,11 +118,11 @@ func main() { // Start polling for terminal size changes go bombadillo.GetSize() - if len(os.Args) > 1 { + if len(args) > 0 { // If a url was passed, move it down the line // Goroutine so keypresses can be made during // page load - bombadillo.Visit(os.Args[1]) + bombadillo.Visit(args[0]) } else { // Otherwise, load the homeurl // Goroutine so keypresses can be made during From db1cf75d2efbd2b5b5e52cb9177b1dfca0290593 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Fri, 20 Sep 2019 16:15:53 -0700 Subject: [PATCH 20/25] Cleans up some display issues --- bookmarks.go | 1 + client.go | 183 +++++++++++++++++++++++++---------------------- defaults.go | 28 -------- gemini/gemini.go | 47 ++++++++++++ main.go | 2 +- 5 files changed, 146 insertions(+), 115 deletions(-) diff --git a/bookmarks.go b/bookmarks.go index 9647725..cb2b773 100644 --- a/bookmarks.go +++ b/bookmarks.go @@ -50,6 +50,7 @@ func (b *Bookmarks) ToggleOpen() { b.IsFocused = true } else { b.IsFocused = false + cui.Clear("screen") } } diff --git a/client.go b/client.go index da0a40f..07be1c7 100644 --- a/client.go +++ b/client.go @@ -3,7 +3,6 @@ package main import ( "fmt" "io/ioutil" - "net" "os" "os/exec" // "os/user" @@ -73,7 +72,8 @@ func (c *client) GetSize() { if h != c.Height || w != c.Width { c.Height = h c.Width = w - c.Scroll(0) + c.SetPercentRead() + c.Draw() } time.Sleep(500 * time.Millisecond) @@ -86,7 +86,7 @@ func (c *client) Draw() { screen.WriteString("\033[0m") screen.WriteString(c.TopBar.Render(c.Width, c.Options["theme"])) screen.WriteString("\n") - pageContent := c.PageState.Render(c.Height, c.Width) + pageContent := c.PageState.Render(c.Height, c.Width - 1) if c.Options["theme"] == "inverse" { screen.WriteString("\033[7m") } @@ -122,11 +122,11 @@ func (c *client) Draw() { } } else { for i := 0; i < c.Height - 3; i++ { - if i < len(pageContent) - 1 { - screen.WriteString(fmt.Sprintf("%-*.*s", c.Width, c.Width, pageContent[i])) + if i < len(pageContent) { + screen.WriteString(fmt.Sprintf("%-*.*s", c.Width - 1, c.Width - 1, pageContent[i])) screen.WriteString("\n") } else { - screen.WriteString(fmt.Sprintf("%*.*s", c.Width, c.Width, " ")) + screen.WriteString(fmt.Sprintf("%-*.*s", c.Width, c.Width, " ")) screen.WriteString("\n") } } @@ -301,6 +301,28 @@ func (c *client) doCommand(action string, values []string) { c.displayConfigValue(values[0]) case "SEARCH": c.search(strings.Join(values, " ")) + case "WRITE", "W": + if values[0] == "." { + values[0] = c.PageState.History[c.PageState.Position].Location.Full + } + u, err := MakeUrl(values[0]) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + fns := strings.Split(u.Resource, "/") + var fn string + if len(fns) > 0 { + fn = strings.Trim(fns[len(fns) - 1], "\t\r\n \a\f\v") + } else { + fn = "index" + } + if fn == "" { + fn = "index" + } + c.saveFile(u, fn) + default: c.SetMessage(fmt.Sprintf("Unknown action %q", action), true) c.DrawMessage() @@ -340,28 +362,15 @@ func (c *client) doCommandAs(action string, values []string) { } case "WRITE", "W": - // TODO figure out how best to handle file - // writing... it will depend on request model - // using fetch would be best - // - - - - - - - - - - - - - - - - - - - - - - // var data []byte - // if values[0] == "." { - // d, err := c.getCurrentPageRawData() - // if err != nil { - // c.SetMessage(err.Error(), true) - // c.DrawMessage() - // return - // } - // data = []byte(d) - // } - // fp, err := c.saveFile(data, strings.Join(values[1:], " ")) - // if err != nil { - // c.SetMessage(err.Error(), true) - // c.DrawMessage() - // return - // } - // c.SetMessage(fmt.Sprintf("File saved to: %s", fp), false) - // c.DrawMessage() + u, err := MakeUrl(values[0]) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + fileName := strings.Join(values[1:], "-") + fileName = strings.Trim(fileName, " \t\r\n\a\f\v") + c.saveFile(u, fileName) case "SET", "S": if _, ok := c.Options[values[0]]; ok { @@ -424,8 +433,10 @@ func (c *client) doLinkCommandAs(action, target string, values []string) { c.Draw() } case "WRITE", "W": - // TODO get file writing working in some semblance of universal way - // return saveFile(links[num-1], strings.Join(values, " ")) + out := make([]string, 0, len(values) + 1) + out = append(out, links[num]) + out = append(out, values...) + c.doCommandAs(action, out) default: c.SetMessage(fmt.Sprintf("Unknown command structure"), true) } @@ -446,14 +457,35 @@ func (c *client) getCurrentPageRawData() (string, error) { return c.PageState.History[c.PageState.Position].RawContent, nil } -func (c *client) saveFile(data []byte, name string) (string, error) { - savePath := c.Options["savelocation"] + name - err := ioutil.WriteFile(savePath, data, 0644) - if err != nil { - return "", err +func (c *client) saveFile(u Url, name string) { + var file []byte + var err error + switch u.Scheme { + case "gopher": + file, err = gopher.Retrieve(u.Host, u.Port, u.Resource) + case "gemini": + file, err = gemini.Fetch(u.Host, u.Port, u.Resource) + default: + c.SetMessage(fmt.Sprintf("Saving files over %s is not supported", u.Scheme), true) + c.DrawMessage() + return } - return savePath, nil + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + savePath := c.Options["savelocation"] + name + err = ioutil.WriteFile(savePath, file, 0644) + if err != nil { + c.SetMessage("Error writing file to disk", true) + c.DrawMessage() + return + } + + c.SetMessage(fmt.Sprintf("File saved to: %s", savePath), false) + c.DrawMessage() } func (c *client) doLinkCommand(action, target string) { @@ -503,6 +535,30 @@ func (c *client) doLinkCommand(action, target string) { link := links[num] c.SetMessage(fmt.Sprintf("[%d] %s", num + 1, link), false) c.DrawMessage() + case "WRITE", "W": + links := c.PageState.History[c.PageState.Position].Links + if len(links) < num || num < 1 { + c.SetMessage("Invalid link ID", true) + c.DrawMessage() + return + } + u, err := MakeUrl(links[num-1]) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + fns := strings.Split(u.Resource, "/") + var fn string + if len(fns) > 0 { + fn = strings.Trim(fns[len(fns) - 1], "\t\r\n \a\f\v") + } else { + fn = "index" + } + if fn == "" { + fn = "index" + } + c.saveFile(u, fn) default: c.SetMessage(fmt.Sprintf("Action %q does not exist for target %q", action, target), true) c.DrawMessage() @@ -576,7 +632,6 @@ func (c *client) Scroll(amount int) { } c.BookMarks.Position = newScrollPosition - c.Draw() } else { var percentRead int page := c.PageState.History[c.PageState.Position] @@ -609,8 +664,8 @@ func (c *client) Scroll(amount int) { percentRead = int(float32(newScrollPosition + c.Height - 3) / float32(len(page.WrappedContent)) * 100.0) } c.FootBar.SetPercentRead(percentRead) - c.Draw() } + c.Draw() } func (c *client) SetPercentRead() { @@ -731,9 +786,9 @@ func (c *client) Visit(url string) { return } pg := MakePage(u, content, links) - pg.WrapContent(c.Width) + pg.WrapContent(c.Width - 1) c.PageState.Add(pg) - c.Scroll(0) // to update percent read + c.SetPercentRead() c.ClearMessage() c.SetHeaderUrl() c.Draw() @@ -748,9 +803,9 @@ func (c *client) Visit(url string) { case 2: if capsule.MimeMaj == "text" { pg := MakePage(u, capsule.Content, capsule.Links) - pg.WrapContent(c.Width) + pg.WrapContent(c.Width - 1) c.PageState.Add(pg) - c.Scroll(0) + c.SetPercentRead() c.ClearMessage() c.SetHeaderUrl() c.Draw() @@ -808,51 +863,7 @@ func (c *client) Visit(url string) { //--------------------------------------------------\\ func MakeClient(name string) *client { - // var userinfo, _ = user.Current() - // var options = map[string]string{ - // "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", - // "savelocation": userinfo.HomeDir, - // "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", - // "openhttp": "false", - // "httpbrowser": "lynx", - // "configlocation": userinfo.HomeDir, - // } c := client{0, 0, defaultOptions, "", false, MakePages(), MakeBookmarks(), MakeHeadbar(name), MakeFootbar()} return &c } -// Retrieve a byte slice of raw response dataa -// from a url string -func Fetch(url string) ([]byte, error) { - u, err := MakeUrl(url) - if err != nil { - return []byte(""), err - } - - timeOut := time.Duration(5) * time.Second - - if u.Host == "" || u.Port == "" { - return []byte(""), fmt.Errorf("Incomplete request url") - } - - addr := u.Host + ":" + u.Port - - conn, err := net.DialTimeout("tcp", addr, timeOut) - if err != nil { - return []byte(""), err - } - - send := u.Resource + "\n" - - _, err = conn.Write([]byte(send)) - if err != nil { - return []byte(""), err - } - - result, err := ioutil.ReadAll(conn) - if err != nil { - return []byte(""), err - } - - return result, err -} diff --git a/defaults.go b/defaults.go index 87fa557..2d8ac8c 100644 --- a/defaults.go +++ b/defaults.go @@ -19,31 +19,3 @@ var defaultOptions = map[string]string{ "theme": "normal", // "normal", "inverted" } -// TODO decide whether or not to institute a color theme -// system. Preliminary testing implies it should be very -// doable. -var theme = map[string]string{ - "topbar_title_bg": "", - "topbar_link_fg": "", - "body_bg": "237", - "body_fg": "", - "bookmarks_bg": "", - "bookmarks_fg": "", - "command_bg": "", - "message_fg": "", - "error_fg": "", - "bottombar_bg": "", - "bottombar_fg": "", - // - // text style options - // - "topbar_title_style": "bold", - "topbar_link_style": "plain", - "body_style": "plain", - "bookmark_body_style": "plain", - "bookmark_border_style": "plain", - "message_style": "italic", - "error_style": "bold", - "command_style": "plain", - "bottom_bar_style": "plain", -} diff --git a/gemini/gemini.go b/gemini/gemini.go index f2fd88c..91755f4 100644 --- a/gemini/gemini.go +++ b/gemini/gemini.go @@ -56,6 +56,53 @@ func Retrieve(host, port, resource string) (string, error) { return string(result), nil } +func Fetch(host, port, resource string) ([]byte, error) { + rawResp, err := Retrieve(host, port, resource) + if err != nil { + return make([]byte, 0), err + } + + resp := strings.SplitN(rawResp, "\r\n", 2) + if len(resp) != 2 { + if err != nil { + return make([]byte, 0), fmt.Errorf("Invalid response from server") + } + } + header := strings.SplitN(resp[0], " ", 2) + if len([]rune(header[0])) != 2 { + header = strings.SplitN(resp[0], "\t", 2) + if len([]rune(header[0])) != 2 { + return make([]byte,0), fmt.Errorf("Invalid response format from server") + } + } + + // Get status code single digit form + status, err := strconv.Atoi(string(header[0][0])) + if err != nil { + return make([]byte, 0), fmt.Errorf("Invalid status response from server") + } + + if status != 2 { + switch status { + case 1: + return make([]byte, 0), fmt.Errorf("[1] Queries cannot be saved.") + case 3: + return make([]byte, 0), fmt.Errorf("[3] Redirects cannot be saved.") + case 4: + return make([]byte, 0), fmt.Errorf("[4] Temporary Failure.") + case 5: + return make([]byte, 0), fmt.Errorf("[5] Permanent Failure.") + case 6: + return make([]byte, 0), fmt.Errorf("[6] Client Certificate Required (Not supported by Bombadillo)") + default: + return make([]byte, 0), fmt.Errorf("Invalid response status from server") + } + } + + return []byte(resp[1]), nil + +} + func Visit(host, port, resource string) (Capsule, error) { capsule := MakeCapsule() rawResp, err := Retrieve(host, port, resource) diff --git a/main.go b/main.go index b5b8a01..0e5c803 100644 --- a/main.go +++ b/main.go @@ -106,7 +106,7 @@ func main() { } args := flag.Args() - cui.Tput("rmam") // turn off line wrapping + cui.Tput("rmam") // turn off line wrapping cui.Tput("smcup") // use alternate screen defer cui.Exit() err := initClient() From 1050b858dd1b741a12df4a3aac146b979c58e2c4 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Fri, 20 Sep 2019 18:24:12 -0700 Subject: [PATCH 21/25] Finished working through file saving for gopher and gemini, and added mailcap functionality to gemini --- client.go | 107 +++++++++++++++++++++++++++++++++++++++++++++------- defaults.go | 1 + main.go | 23 +++-------- 3 files changed, 100 insertions(+), 31 deletions(-) diff --git a/client.go b/client.go index 07be1c7..4ff6a05 100644 --- a/client.go +++ b/client.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "os" "os/exec" - // "os/user" "regexp" "strconv" "strings" @@ -17,6 +16,7 @@ import ( "tildegit.org/sloum/bombadillo/gopher" "tildegit.org/sloum/bombadillo/http" "tildegit.org/sloum/bombadillo/telnet" + // "tildegit.org/sloum/mailcap" ) //------------------------------------------------\\ @@ -460,6 +460,8 @@ func (c *client) getCurrentPageRawData() (string, error) { func (c *client) saveFile(u Url, name string) { var file []byte var err error + c.SetMessage(fmt.Sprintf("Saving %s ...", name), false) + c.DrawMessage() switch u.Scheme { case "gopher": file, err = gopher.Retrieve(u.Host, u.Port, u.Resource) @@ -488,6 +490,22 @@ func (c *client) saveFile(u Url, name string) { c.DrawMessage() } +func (c *client) saveFileFromData(d, name string) { + data := []byte(d) + c.SetMessage(fmt.Sprintf("Saving %s ...", name), false) + c.DrawMessage() + savePath := c.Options["savelocation"] + name + err := ioutil.WriteFile(savePath, data, 0644) + if err != nil { + c.SetMessage("Error writing file to disk", true) + c.DrawMessage() + return + } + + c.SetMessage(fmt.Sprintf("File saved to: %s", savePath), false) + c.DrawMessage() +} + func (c *client) doLinkCommand(action, target string) { num, err := strconv.Atoi(target) if err != nil { @@ -779,19 +797,29 @@ func (c *client) Visit(url string) { switch u.Scheme { case "gopher": - content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) - if err != nil { - c.SetMessage(err.Error(), true) - c.DrawMessage() - return + if u.DownloadOnly { + nameSplit := strings.Split(u.Resource, "/") + filename := nameSplit[len(nameSplit) - 1] + filename = strings.Trim(filename, " \t\r\n\v\f\a") + if filename == "" { + filename = "gopherfile" + } + c.saveFile(u, filename) + } else { + content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + pg := MakePage(u, content, links) + pg.WrapContent(c.Width - 1) + c.PageState.Add(pg) + c.SetPercentRead() + c.ClearMessage() + c.SetHeaderUrl() + c.Draw() } - pg := MakePage(u, content, links) - pg.WrapContent(c.Width - 1) - c.PageState.Add(pg) - c.SetPercentRead() - c.ClearMessage() - c.SetHeaderUrl() - c.Draw() case "gemini": capsule, err := gemini.Visit(u.Host, u.Port, u.Resource) if err != nil { @@ -810,8 +838,59 @@ func (c *client) Visit(url string) { c.SetHeaderUrl() c.Draw() } else { - c.SetMessage("Still mulling how to handle binary files... come back soon", false) + c.SetMessage("The file is non-text: (o)pen or (w)rite to disk", false) c.DrawMessage() + var ch rune + for { + ch = cui.Getch() + if ch == 'o' || ch == 'w' { + break + } + } + switch ch { + case 'o': + mime := fmt.Sprintf("%s/%s", capsule.MimeMaj, capsule.MimeMin) + var term bool + if c.Options["terminalonly"] == "true" { + term = true + } else { + term = false + } + mcEntry, err := mc.FindMatch(mime, "view", term) + if err != nil { + c.SetMessage(err.Error(), true) + c.DrawMessage() + return + } + file, err := ioutil.TempFile("/tmp/", "bombadillo-*.tmp") + if err != nil { + c.SetMessage("Unable to create temporary file for opening, aborting file open", true) + c.DrawMessage() + return + } + // defer os.Remove(file.Name()) + file.Write([]byte(capsule.Content)) + com, e := mcEntry.Command(file.Name()) + if e != nil { + c.SetMessage(e.Error(), true) + c.DrawMessage() + return + } + com.Stdin = os.Stdin + com.Stdout = os.Stdout + com.Stderr = os.Stderr + if c.Options["terminalonly"] == "true" { + cui.Clear("screen") + } + com.Run() + c.SetMessage("File opened by an appropriate program", true) + c.DrawMessage() + c.Draw() + case 'w': + nameSplit := strings.Split(u.Resource, "/") + filename := nameSplit[len(nameSplit) - 1] + c.saveFileFromData(capsule.Content, filename) + } } case 3: c.SetMessage("[3] Redirect. Follow redirect? y or any other key for no", false) diff --git a/defaults.go b/defaults.go index 2d8ac8c..8d744de 100644 --- a/defaults.go +++ b/defaults.go @@ -17,5 +17,6 @@ var defaultOptions = map[string]string{ "telnetcommand": "telnet", "configlocation": userinfo.HomeDir, "theme": "normal", // "normal", "inverted" + "terminalonly": "true", } diff --git a/main.go b/main.go index 0e5c803..1e7c6bc 100644 --- a/main.go +++ b/main.go @@ -15,6 +15,7 @@ import ( "tildegit.org/sloum/bombadillo/config" "tildegit.org/sloum/bombadillo/cui" + "tildegit.org/sloum/mailcap" ) const version = "2.0.0" @@ -22,23 +23,7 @@ const version = "2.0.0" var bombadillo *client var helplocation string = "gopher://colorfield.space:70/1/bombadillo-info" var settings config.Config - - -// func saveFileFromData(v gopher.View) error { - // quickMessage("Saving file...", false) - // urlsplit := strings.Split(v.Address.Full, "/") - // filename := urlsplit[len(urlsplit)-1] - // saveMsg := fmt.Sprintf("Saved file as %q", options["savelocation"]+filename) - // err := ioutil.WriteFile(options["savelocation"]+filename, []byte(strings.Join(v.Content, "")), 0644) - // if err != nil { - // quickMessage("Saving file...", true) - // return err - // } - - // quickMessage(saveMsg, false) - // return nil -// } - +var mc *mailcap.Mailcap func saveConfig() error { var opts strings.Builder @@ -106,6 +91,10 @@ func main() { } args := flag.Args() + // Build the mailcap db + // So that we can open files from gemini + mc = mailcap.NewMailcap() + cui.Tput("rmam") // turn off line wrapping cui.Tput("smcup") // use alternate screen defer cui.Exit() From 2f14011a486eb34eece358f9d55439f063aab261 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sat, 21 Sep 2019 14:12:18 -0700 Subject: [PATCH 22/25] Adds temporary ability to not add invalid value for theme. Also adds a temporary first draft of a manpage for bombadillo. --- bombadillo.1 | 201 +++++++++++++++++++++++++++++++++++++++++++++++++++ client.go | 8 +- defaults.go | 3 + main.go | 7 ++ 4 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 bombadillo.1 diff --git a/bombadillo.1 b/bombadillo.1 new file mode 100644 index 0000000..1d28a72 --- /dev/null +++ b/bombadillo.1 @@ -0,0 +1,201 @@ +." Text automatically generated by txt2man +.TH "bombadillo" 1 "21 SEP 2019" "" "General Opperation Manual" +.SH NAME +\fBbombadillo \fP- a non-web client +.SH SYNOPSIS +.nf +.fam C +\fBbombadillo\fP [\fB-v\fP] [\fB-h\fP] [\fIurl\fP] +.fam T +.fi +.SH DESCRIPTION +\fBbombadillo\fP is a terminal based client for a number of internet protocols, including gopher and gemini. \fBbombadillo\fP will also connect links to a user's default web browser or telnet client. Commands input is loosely based on Vi and Less and is comprised of two modes: key and line input mode. +.SH OPTIONS +.TP +.B +\fB-v\fP +Display the version number of \fBbombadillo\fP. +.TP +.B +\fB-h\fP +Usage help. Displays all command line options with a short description. +.SH COMMANDS +.SS KEY COMMANDS +These commands work as a single keypress anytime \fBbombadillo\fP is not taking in a line based command. This is the default command mode of \fBbombadillo\fP. +.TP +.B +b +Navigate back one place in your document history. +.TP +.B +B +Toggle the bookmarks panel open/closed. +.TP +.B +d +Scroll down an amount corresponding to 75% of your terminal window height in the current document. +.TP +.B +f +Navigate forward one place in your document history. +.TP +.B +g +Scroll to the top of the current document. +.TP +.B +G +Scroll to the bottom of the current document. +.TP +.B +j +Scroll down a single line in the current document. +.TP +.B +k +Scroll up a single line. +.TP +.B +q +Quit \fBbombadillo\fP. +.TP +.B +u +Scroll up an amount corresponding to 75% of your terminal window height in the current document. +.TP +.B + +Toggle the scroll focus between the bookmarks panel and the document panel. Only has an effect if the bookmarks panel is open. +.TP +.B + +Enter line command mode. Once a line command is input, the mode will automatically revert to key command mode. +.TP +.B +: +Alias for . Enter line command mode. +.SS LINE COMMANDS +These commands are typed in by the user to perform an action of some sort. As listed in KEY COMMANDS, this mode is initiated by pressing : or . The command names themselves are not case sensitive, though the arguments supplied to them may be. +.SS NAVIGATION +.TP +.B +[url] +Navigates to the requested url. +.TP +.B +[link id] +Follows a link on the current document with the given number. +.TP +.B +bookmarks [bookmark id] +Navigates to the url represented by the bookmark matching bookmark id. \fIb\fP can be entered, rather than the full \fIbookmarks\fP. +.TP +.B +home +Navigates to the document set by the \fIhomeurl\fP setting. \fIh\fP can be entered, rather than the full \fIhome\fP. +.TP +.B +search [keywords\.\.\.] +Submits a search to the search engine set by the \fIsearchengine\fP setting, with the query being the provided keyword(s). +.TP +.B +search +Queries the user for search terms and submits a search to the search engine set by the \fIsearchengine\fP setting. +.TP +.B +write [url] +Writes data from a given url to a file. The file is named by the last component of the url path. If the last component is blank or \fI/\fP a default name will be used. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +write [url] [filename\.\.\.] +Writes data from a given url to a file. The file is named by the filename argument should should not include a leading \fI/\fP. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +write [link id]] +Writes data from a given link id in the current document to a file. The file is named by the last component of the url path. If the last component is blank or \fI/\fP a default name will be used. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +write [link id] [filename\.\.\.] +Writes data from a given link id in the current document to a file. The file is named by the filename argument should should not include a leading \fI/\fP. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +write . +Writes the current document to a file. The file is named by the last component of the url path. If the last component is blank or \fI/\fP a default name will be used. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +write . [filename\.\.\.] +Writes the current document to a file. The file is named by the filename argument should should not include a leading \fI/\fP. The file saves to the folder set by the \fIsavelocation\fP setting. \fIw\fP can be entered rather than the full \fIwrite\fP. +.TP +.B +help +Navigates to the gopher based help page for \fBbombadillo\fP. \fI?\fP can be used instead of the full \fIhelp\fP. +.SS BOOKMARKS +.TP +.B +bookmarks +Toggles the bookmarks panel open/closed. Alias for KEY COMMAND \fIB\fP. \fIb\fP can be used instead of the full \fIbookmarks\fP. +.TP +.B +add [url] [name\.\.\.] +Adds the url as a bookmarks labeled by name. \fIa\fP can be used instead of the full \fIadd\fP. +.TP +.B +add [link id] [name\.\.\.] +Adds the url represented by the link id within the current document as a bookmark labeled by name. \fIa\fP can be used instead of the full \fIadd\fP. +.TP +.B +add [.] [name\.\.\.] +Adds the current document's url as a bookmark labeled by name. \fIa\fP can be used instead of the full \fIadd\fP. +.TP +.B +delete [bookmark id]] +Deletes the bookmark matching the bookmark id. \fId\fP can be used instead of the full \fIdelete\fP. +.SS MISC +.TP +.B +check [link id] +Displays the url corresponding to a given link id for the current document. \fIc\fP can be used instead of the full \fIcheck\fP. +.TP +.B +check [setting name] +Displays the current value for a given configuration setting. \fIc\fP can be used instead of the full \fIcheck\fP. +.TP +.B +set [setting name] +Sets the value for a given configuration setting. \fIs\fP can be used instead of the full \fIset\fP. +.TP +.B +quit +Quits \fBbombadillo\fP. Alias for KEY COMMAND \fIq\fP. \fIq\fP can be used instead of the full \fIquit\fP. +.SH FILES +\fBbombadillo\fP keeps a hidden configuration file in a user's home directory. The file is a simplified ini file titled '.bombadillo.ini'. It is generated when a user first loads \fBbombadillo\fP and is updated with bookmarks and settings as a user adds them. The file can be directly edited, but it is best to use the SET command to update settings whenever possible. To return to the state of a fresh install, simply remove the file and a new one will be generated with the \fBbombadillo\fP defaults. +.SH SETTINGS +The following is a list of the settings that \fBbombadillo\fP recognizes, as well as a description of their valid values. +.TP +.B +homeurl +The url that \fBbombadillo\fP navigates to when the program loads or when the \fIhome\fP or \fIh\fP LINE COMMAND is issued. This should be a valid url. If a scheme/protocol is not included, gopher will be assumed. +.TP +.B +savelocation +The path to the folder that \fBbombadillo\fP should write files to. This should be a valid filepath for the system and should end in a \fI/\fP. Defaults to a user's home directory. +.TP +.B +searchengine +The url to use for the LINE COMMANDs \fI?\fP and \fIsearch\fP. Should be a valid search path that terms may be appended to. Defaults to \fIgopher://gopher.floodgap.com:70/7/v2/vs\fP. +.TP +.B +openhttp +Tells the client whether or not to try to follow web (http/https) links. If set to \fItrue\fP, \fBbombadillo\fP will try to open a user's default web browser to the link in question. Any value other than \fItrue\fP is considered false. Defaults to \fIfalse\fP. +.TP +.B +telnetcommand +Tells the client what command to use to start a telnet session. Should be a valid command, including any flags. The address being navigated to will be added to the end of the command. Defaults to \fItelnet\fP. +.TP +.B +theme +Can toggle between visual modes. Valid values are \fInormal\fP and \fIinverse\fP. When set to ivnerse, the terminal color mode is inversed. Defaults to \fInormal\fP. +.TP +.B +terminalonly +Sets whether or not to try to open non-text files served via gemini in gui programs or not. If set to \fItrue\fP, bombdaillo will only attempt to use terminal programs to open files. If set to anything else, \fBbombadillo\fP may choose graphical and terminal programs. Defaults to \fItrue\fP. diff --git a/client.go b/client.go index 4ff6a05..77c14ad 100644 --- a/client.go +++ b/client.go @@ -374,7 +374,13 @@ func (c *client) doCommandAs(action string, values []string) { case "SET", "S": if _, ok := c.Options[values[0]]; ok { - c.Options[values[0]] = strings.Join(values[1:], " ") + val := strings.Join(values[1:], " ") + if values[0] == "theme" && val != "normal" && val != "inverse" { + c.SetMessage("Theme can only be set to 'normal' or 'inverse'", true) + c.DrawMessage() + return + } + c.Options[values[0]] = val err := saveConfig() if err != nil { c.SetMessage("Value set, but error saving config to file", true) diff --git a/defaults.go b/defaults.go index 8d744de..690a403 100644 --- a/defaults.go +++ b/defaults.go @@ -9,6 +9,9 @@ var defaultOptions = map[string]string{ // // General configuration options // + // Edit these values before compile to have different default values + // ... though they can always be edited from within bombadillo as well + // it just may take more time/work. "homeurl": "gopher://colorfield.space:70/1/bombadillo-info", "savelocation": userinfo.HomeDir, "searchengine": "gopher://gopher.floodgap.com:70/7/v2/vs", diff --git a/main.go b/main.go index 1e7c6bc..e66a9e9 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,10 @@ func saveConfig() error { opts.WriteString(bkmrks) opts.WriteString("\n[SETTINGS]\n") for k, v := range bombadillo.Options { + if k == "theme" && v != "normal" && v != "inverse" { + v = "normal" + bombadillo.Options["theme"] = "normal" + } opts.WriteString(k) opts.WriteRune('=') opts.WriteString(v) @@ -64,6 +68,9 @@ func loadConfig() error { } if _, ok := bombadillo.Options[lowerkey]; ok { + if lowerkey == "theme" && v.Value != "normal" && v.Value != "inverse" { + v.Value = "normal" + } bombadillo.Options[lowerkey] = v.Value } } From ff209c4ae3dd85e1809a69423f8ce0965b92c2d9 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sat, 21 Sep 2019 22:02:20 -0700 Subject: [PATCH 23/25] Adds status 1 support to gemini, fixes bug in url where gophertypes were getting thrown out of nongopher addresses, and fixes up relative linking in gemini maps --- client.go | 23 +++++++++++++++-------- gemini/gemini.go | 13 +++++++------ url.go | 2 +- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/client.go b/client.go index 77c14ad..642d9f4 100644 --- a/client.go +++ b/client.go @@ -280,7 +280,7 @@ func (c *client) simpleCommand(action string) { c.BookMarks.ToggleOpen() c.Draw() case "SEARCH": - c.search("") + c.search("", "", "?") case "HELP", "?": go c.Visit(helplocation) default: @@ -300,7 +300,7 @@ func (c *client) doCommand(action string, values []string) { case "CHECK", "C": c.displayConfigValue(values[0]) case "SEARCH": - c.search(strings.Join(values, " ")) + c.search(strings.Join(values, " "), "", "") case "WRITE", "W": if values[0] == "." { values[0] = c.PageState.History[c.PageState.Position].Location.Full @@ -590,16 +590,16 @@ func (c *client) doLinkCommand(action, target string) { } -func (c *client) search(q string) { +func (c *client) search(query, url, question string) { var entry string var err error - if q == "" { + if query == "" { c.ClearMessage() c.ClearMessageLine() if c.Options["theme"] == "normal" { fmt.Printf("\033[7m%*.*s\r", c.Width, c.Width, "") } - fmt.Print("?") + fmt.Print(question) entry, err = cui.GetLine() c.ClearMessageLine() if err != nil { @@ -610,11 +610,14 @@ func (c *client) search(q string) { return } } else { - entry = q + entry = query } - u, err := MakeUrl(c.Options["searchengine"]) + if url == "" { + url = c.Options["searchengine"] + } + u, err := MakeUrl(url) if err != nil { - c.SetMessage("'searchengine' is not set to a valid url", true) + c.SetMessage("The search url is not a valid url", true) c.DrawMessage() return } @@ -811,6 +814,8 @@ func (c *client) Visit(url string) { filename = "gopherfile" } c.saveFile(u, filename) + } else if u.Mime == "7" { + c.search("", u.Full, "?") } else { content, links, err := gopher.Visit(u.Mime, u.Host, u.Port, u.Resource) if err != nil { @@ -834,6 +839,8 @@ func (c *client) Visit(url string) { return } switch capsule.Status { + case 1: + c.search("", u.Full, capsule.Content) case 2: if capsule.MimeMaj == "text" { pg := MakePage(u, capsule.Content, capsule.Links) diff --git a/gemini/gemini.go b/gemini/gemini.go index 91755f4..7b6de31 100644 --- a/gemini/gemini.go +++ b/gemini/gemini.go @@ -137,8 +137,8 @@ func Visit(host, port, resource string) (Capsule, error) { switch capsule.Status { case 1: - // handle search - return capsule, fmt.Errorf("Gemini input not yet supported") + capsule.Content = header[1] + return capsule, nil case 2: mimeAndCharset := strings.Split(header[1], ";") meta = mimeAndCharset[0] @@ -149,7 +149,10 @@ func Visit(host, port, resource string) (Capsule, error) { capsule.MimeMaj = minMajMime[0] capsule.MimeMin = minMajMime[1] if capsule.MimeMaj == "text" && capsule.MimeMin == "gemini" { - rootUrl := fmt.Sprintf("gemini://%s:%s", host, port) + if len(resource) > 0 && resource[0] != '/' { + resource = fmt.Sprintf("/%s", resource) + } + rootUrl := fmt.Sprintf("gemini://%s:%s%s", host, port, resource) capsule.Content, capsule.Links = parseGemini(body, rootUrl) } else { capsule.Content = body @@ -190,10 +193,8 @@ func parseGemini(b, rootUrl string) (string, []string) { decorator = strings.Trim(subLn[splitPoint:], "\t\n\r \a") } - if len(link) > 0 && link[0] == '/' { + if strings.Index(link, "://") < 0 { link = fmt.Sprintf("%s%s", rootUrl, link) - } else if len(link) > 0 && strings.Index(link, "://") < 0 { - link = fmt.Sprintf("%s/%s", rootUrl, link) } links = append(links, link) linknum := fmt.Sprintf("[%d]", len(links)) diff --git a/url.go b/url.go index 5babdc8..faedbbb 100644 --- a/url.go +++ b/url.go @@ -97,8 +97,8 @@ func MakeUrl(u string) (Url, error) { out.DownloadOnly = true } } else { - out.Mime = "" out.Resource = fmt.Sprintf("%s%s", out.Mime, out.Resource) + out.Mime = "" } if out.Scheme == "http" || out.Scheme == "https" { From b66dd3baa9dbbb489d7e4b8926b7dd0dbfdaf6a0 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Sun, 22 Sep 2019 15:08:15 -0700 Subject: [PATCH 24/25] Fixes relative linking for gemini --- gemini/gemini.go | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/gemini/gemini.go b/gemini/gemini.go index 7b6de31..4d8b044 100644 --- a/gemini/gemini.go +++ b/gemini/gemini.go @@ -151,9 +151,12 @@ func Visit(host, port, resource string) (Capsule, error) { if capsule.MimeMaj == "text" && capsule.MimeMin == "gemini" { if len(resource) > 0 && resource[0] != '/' { resource = fmt.Sprintf("/%s", resource) + } else if resource == "" { + resource = "/" } - rootUrl := fmt.Sprintf("gemini://%s:%s%s", host, port, resource) - capsule.Content, capsule.Links = parseGemini(body, rootUrl) + currentUrl := fmt.Sprintf("gemini://%s:%s%s", host, port, resource) + rootUrl := fmt.Sprintf("gemini://%s:%s", host, port) + capsule.Content, capsule.Links = parseGemini(body, rootUrl, currentUrl) } else { capsule.Content = body } @@ -174,7 +177,7 @@ func Visit(host, port, resource string) (Capsule, error) { } } -func parseGemini(b, rootUrl string) (string, []string) { +func parseGemini(b, rootUrl, currentUrl string) (string, []string) { splitContent := strings.Split(b, "\n") links := make([]string, 0, 10) @@ -193,9 +196,10 @@ func parseGemini(b, rootUrl string) (string, []string) { decorator = strings.Trim(subLn[splitPoint:], "\t\n\r \a") } - if strings.Index(link, "://") < 0 { - link = fmt.Sprintf("%s%s", rootUrl, link) + if strings.Index(link, "://") < 0 { + link = handleRelativeUrl(link, rootUrl, currentUrl) } + links = append(links, link) linknum := fmt.Sprintf("[%d]", len(links)) splitContent[i] = fmt.Sprintf("%-5s %s", linknum, decorator) @@ -204,6 +208,24 @@ func parseGemini(b, rootUrl string) (string, []string) { return strings.Join(splitContent, "\n"), links } +func handleRelativeUrl(u, root, current string) string { + if len(u) < 1 { + return u + } + + if u[0] == '/' { + return fmt.Sprintf("%s%s", root, u) + } + + ind := strings.LastIndex(current, "/") + if ind < 10 { + return fmt.Sprintf("%s/%s", root, u) + } + + current = current[:ind + 1] + return fmt.Sprintf("%s%s", current, u) +} + func MakeCapsule() Capsule { return Capsule{"", "", 0, "", make([]string, 0, 5)} From 74473ff3091abd421bfab60776fa011a4ccad256 Mon Sep 17 00:00:00 2001 From: sloumdrone Date: Mon, 23 Sep 2019 08:49:33 -0700 Subject: [PATCH 25/25] Returns license to gpl3 --- LICENSE | 756 +++++++++++++++++++++++++++++++++++++++++++------------- main.go | 21 +- 2 files changed, 607 insertions(+), 170 deletions(-) diff --git a/LICENSE b/LICENSE index 63d7936..810fce6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,195 +1,621 @@ -Non-Profit Open Software License 3.0 + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -This Non-Profit Open Software License ("Non-Profit OSL") version 3.0 (the -"License") applies to any original work of authorship (the "Original Work") -whose owner (the "Licensor") has placed the following licensing notice adjacent -to the copyright notice for the Original Work: + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Licensed under the Non-Profit Open Software License version 3.0 + Preamble -1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, -non-exclusive, sublicensable license, for the duration of the copyright, to -do the following: + The GNU General Public License is a free, copyleft license for +software and other kinds of works. - a) to reproduce the Original Work in copies, either alone or as part of a - collective work; + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. - b) to translate, adapt, alter, transform, modify, or arrange the Original - Work, thereby creating derivative works ("Derivative Works") based upon the - Original Work; + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - c) to distribute or communicate copies of the Original Work and Derivative - Works to the public, with the proviso that copies of Original Work or Derivative - Works that You distribute or communicate shall be licensed under this Non-Profit - Open Software License or as provided in section 17(d); + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. - d) to perform the Original Work publicly; and + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. - e) to display the Original Work publicly. + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. -2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, -non-exclusive, sublicensable license, under patent claims owned or controlled -by the Licensor that are embodied in the Original Work as furnished by the -Licensor, for the duration of the patents, to make, use, sell, offer for sale, -have made, and import the Original Work and Derivative Works. + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. -3) Grant of Source Code License. The term "Source Code" means the preferred -form of the Original Work for making modifications to it and all available -documentation describing how to modify the Original Work. Licensor agrees -to provide a machine-readable copy of the Source Code of the Original Work -along with each copy of the Original Work that Licensor distributes. Licensor -reserves the right to satisfy this obligation by placing a machine-readable -copy of the Source Code in an information repository reasonably calculated -to permit inexpensive and convenient access by You for as long as Licensor -continues to distribute the Original Work. + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. -4) Exclusions From License Grant. Neither the names of Licensor, nor the names -of any contributors to the Original Work, nor any of their trademarks or service -marks, may be used to endorse or promote products derived from this Original -Work without express prior permission of the Licensor. Except as expressly -stated herein, nothing in this License grants any license to Licensor's trademarks, -copyrights, patents, trade secrets or any other intellectual property. No -patent license is granted to make, use, sell, offer for sale, have made, or -import embodiments of any patent claims other than the licensed claims defined -in Section 2. No license is granted to the trademarks of Licensor even if -such marks are included in the Original Work. Nothing in this License shall -be interpreted to prohibit Licensor from licensing under terms different from -this License any Original Work that Licensor otherwise would have a right -to license. + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. -5) External Deployment. The term "External Deployment" means the use, distribution, -or communication of the Original Work or Derivative Works in any way such -that the Original Work or Derivative Works may be used by anyone other than -You, whether those works are distributed or communicated to those persons -or made available as an application intended for use over a network. As an -express condition for the grants of license hereunder, You must treat any -External Deployment by You of the Original Work or a Derivative Work as a -distribution under section 1(c). + The precise terms and conditions for copying, distribution and +modification follow. -6) Attribution Rights. You must retain, in the Source Code of any Derivative -Works that You create, all copyright, patent, or trademark notices from the -Source Code of the Original Work, as well as any notices of licensing and -any descriptive text identified therein as an "Attribution Notice." You must -cause the Source Code for any Derivative Works that You create to carry a -prominent Attribution Notice reasonably calculated to inform recipients that -You have modified the Original Work. + TERMS AND CONDITIONS -7) Warranty of Provenance and Disclaimer of Warranty. The Original Work is -provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either -express or implied, including, without limitation, the warranties of non-infringement, -merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO -THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY -constitutes an essential part of this License. No license to the Original -Work is granted by this License except under this disclaimer. + 0. Definitions. -8) Limitation of Liability. Under no circumstances and under no legal theory, -whether in tort (including negligence), contract, or otherwise, shall the -Licensor be liable to anyone for any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License -or the use of the Original Work including, without limitation, damages for -loss of goodwill, work stoppage, computer failure or malfunction, or any and -all other commercial damages or losses. This limitation of liability shall -not apply to the extent applicable law prohibits such limitation. + "This License" refers to version 3 of the GNU General Public License. -9) Acceptance and Termination. If, at any time, You expressly assented to -this License, that assent indicates your clear and irrevocable acceptance -of this License and all of its terms and conditions. If You distribute or -communicate copies of the Original Work or a Derivative Work, You must make -a reasonable effort under the circumstances to obtain the express assent of -recipients to the terms of this License. This License conditions your rights -to undertake the activities listed in Section 1, including your right to create -Derivative Works based upon the Original Work, and doing so without honoring -these terms and conditions is prohibited by copyright law and international -treaty. Nothing in this License is intended to affect copyright exceptions -and limitations (including "fair use" or "fair dealing"). This License shall -terminate immediately and You may no longer exercise any of the rights granted -to You by this License upon your failure to honor the conditions in Section -1(c). + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. -10) Termination for Patent Action. This License shall terminate automatically -and You may no longer exercise any of the rights granted to You by this License -as of the date You commence an action, including a cross-claim or counterclaim, -against Licensor or any licensee alleging that the Original Work infringes -a patent. This termination provision shall not apply for an action alleging -patent infringement by combinations of the Original Work with other software -or hardware. + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. -11) Jurisdiction, Venue and Governing Law. Any action or suit relating to -this License may be brought only in the courts of a jurisdiction wherein the -Licensor resides or in which Licensor conducts its primary business, and under -the laws of that jurisdiction excluding its conflict-of-law provisions. The -application of the United Nations Convention on Contracts for the International -Sale of Goods is expressly excluded. Any use of the Original Work outside -the scope of this License or after its termination shall be subject to the -requirements and penalties of copyright or patent law in the appropriate jurisdiction. -This section shall survive the termination of this License. + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. -12) Attorneys' Fees. In any action to enforce the terms of this License or -seeking damages relating thereto, the prevailing party shall be entitled to -recover its costs and expenses, including, without limitation, reasonable -attorneys' fees and costs incurred in connection with such action, including -any appeal of such action. This section shall survive the termination of this -License. + A "covered work" means either the unmodified Program or a work based +on the Program. -13) Miscellaneous. If any provision of this License is held to be unenforceable, -such provision shall be reformed only to the extent necessary to make it enforceable. + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. -14) Definition of "You" in This License. "You" throughout this License, whether -in upper or lower case, means an individual or a legal entity exercising rights -under, and complying with all of the terms of, this License. For legal entities, -"You" includes any entity that controls, is controlled by, or is under common -control with you. For purposes of this definition, "control" means (i) the -power, direct or indirect, to cause the direction or management of such entity, -whether by contract or otherwise, or (ii) ownership of fifty percent (50%) -or more of the outstanding shares, or (iii) beneficial ownership of such entity. + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. -15) Right to Use. You may use the Original Work in all ways not otherwise -restricted or conditioned by this License or by law, and Licensor promises -not to interfere with or be responsible for such uses by You. + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. -16) Modification of This License. This License is Copyright © 2005 Lawrence -Rosen. Permission is granted to copy, distribute, or communicate this License -without modification. Nothing in this License permits You to modify this License -as applied to the Original Work or to Derivative Works. However, You may modify -the text of this License and copy, distribute or communicate your modified -version (the "Modified License") and apply it to other original works of authorship -subject to the following conditions: (i) You may not indicate in any way that -your Modified License is the "Open Software License" or "OSL" and you may -not use those names in the name of your Modified License; (ii) You must replace -the notice specified in the first paragraph above with the notice "Licensed -under " or with a notice of your own that is -not confusingly similar to the notice in this License; and (iii) You may not -claim that your original works are open source software unless your Modified -License has been approved by Open Source Initiative (OSI) and You comply with -its license review and certification process. + 1. Source Code. -17) Non-Profit Amendment. The name of this amended version of the Open Software -License ("OSL 3.0") is "Non-Profit Open Software License 3.0". The original -OSL 3.0 license has been amended as follows: + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. - (a) Licensor represents and declares that it is a not-for-profit organization - that derives no revenue whatsoever from the distribution of the Original Work - or Derivative Works thereof, or from support or services relating thereto. + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. - (b) The first sentence of Section 7 ["Warranty of Provenance"] of OSL 3.0 - has been stricken. For Original Works licensed under this Non-Profit OSL 3.0, - LICENSOR OFFERS NO WARRANTIES WHATSOEVER. + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. - (c) In the first sentence of Section 8 ["Limitation of Liability"] of this - Non-Profit OSL 3.0, the list of damages for which LIABILITY IS LIMITED now - includes "direct" damages. + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. - (d) The proviso in Section 1(c) of this License now refers to this "Non-Profit - Open Software License" rather than the "Open Software License". You may distribute - or communicate the Original Work or Derivative Works thereof under this Non-Profit - OSL 3.0 license only if You make the representation and declaration in paragraph - (a) of this Section 17. Otherwise, You shall distribute or communicate the - Original Work or Derivative Works thereof only under the OSL 3.0 license and - You shall publish clear licensing notices so stating. Also by way of clarification, - this License does not authorize You to distribute or communicate works under - this Non-Profit OSL 3.0 if You received them under the original OSL 3.0 license. + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. - (e) Original Works licensed under this license shall reference "Non-Profit - OSL 3.0" in licensing notices to distinguish them from works licensed under - the original OSL 3.0 license. + The Corresponding Source for a work in source code form is that +same work. + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/main.go b/main.go index e66a9e9..ffe6eab 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,21 @@ package main +// Bombadillo is a gopher and gemini client for the terminal of unix or unix-like systems. +// +// Copyright (C) 2019 Brian Evans +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . -// Bombadillo is distributed under the "Non-Profit Open Source Software License 3.0" -// The license is included with the source code in the file LICENSE. The basic -// takeway: use, remix, and share this software for any purpose that is not a commercial -// purpose as defined by the above mentioned license and is itself distributed udner -// the terms of said license with said license file included. import ( "flag"