ui.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package ui
  2. import (
  3. "fmt"
  4. "servitor/ansi"
  5. "servitor/config"
  6. "servitor/feed"
  7. "servitor/history"
  8. "servitor/mime"
  9. "servitor/pub"
  10. "servitor/splicer"
  11. "servitor/style"
  12. "os/exec"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "errors"
  17. )
  18. /*
  19. The public methods herein are threadsafe, the private methods
  20. are not and need to be protected by State.m
  21. */
  22. /* Modes */
  23. const (
  24. loading = iota
  25. normal
  26. command
  27. selection
  28. opening
  29. problem
  30. )
  31. const (
  32. enterKey byte = '\r'
  33. escapeKey byte = 27
  34. backspaceKey byte = 127
  35. )
  36. type Page struct {
  37. feed *feed.Feed
  38. frontier pub.Tangible
  39. loadingUp bool
  40. children pub.Container
  41. basepoint uint
  42. loadingDown bool
  43. }
  44. type State struct {
  45. m *sync.Mutex
  46. h history.History[*Page]
  47. width int
  48. height int
  49. output func(string)
  50. mode int
  51. buffer string
  52. }
  53. func (s *State) view() string {
  54. const cursor = "┃ "
  55. const parentConnector = " │\n"
  56. const childConnector = "\n"
  57. if s.mode == loading {
  58. return ansi.CenterVertically("", style.Color(" Loading…"), "", uint(s.height))
  59. }
  60. var top, center, bottom string
  61. for i := -config.Parsed.Style.Context; i <= config.Parsed.Style.Context; i++ {
  62. if !s.h.Current().feed.Contains(i) {
  63. continue
  64. }
  65. var serialized string
  66. if s.h.Current().feed.IsParent(i) {
  67. serialized = s.h.Current().feed.Get(i).Preview(s.width - 4)
  68. } else if s.h.Current().feed.IsChild(i) {
  69. serialized = "→ " + ansi.Indent(s.h.Current().feed.Get(i).Preview(s.width-8), " ", false)
  70. } else {
  71. serialized = s.h.Current().feed.Get(i).String(s.width - 4)
  72. }
  73. if i == 0 {
  74. center = ansi.Indent(serialized, cursor, true)
  75. if s.h.Current().feed.IsParent(i) {
  76. bottom = parentConnector
  77. } else {
  78. bottom = childConnector
  79. }
  80. continue
  81. }
  82. serialized = ansi.Indent(serialized, " ", true) + "\n"
  83. if s.h.Current().feed.IsParent(i) {
  84. serialized += parentConnector
  85. } else {
  86. serialized += childConnector
  87. }
  88. if i < 0 {
  89. top += serialized
  90. } else {
  91. bottom += serialized
  92. }
  93. }
  94. if s.h.Current().loadingUp && !s.h.Current().feed.Contains(-config.Parsed.Style.Context-1) {
  95. top = "\n " + style.Color("Loading…") + "\n\n" + top
  96. }
  97. if s.h.Current().loadingDown && !s.h.Current().feed.Contains(config.Parsed.Style.Context+1) {
  98. bottom += " " + style.Color("Loading…") + "\n"
  99. }
  100. /* Remove trailing newlines */
  101. top = strings.TrimSuffix(top, "\n")
  102. bottom = strings.TrimSuffix(bottom, "\n")
  103. output := ansi.CenterVertically(top, center, bottom, uint(s.height))
  104. var footer string
  105. switch s.mode {
  106. case normal:
  107. break
  108. case selection:
  109. footer = "Selecting " + s.buffer + " (press . to open internally, enter to open externally)"
  110. case command:
  111. footer = ":" + s.buffer
  112. case opening:
  113. footer = "Opening " + s.buffer + "\u2026"
  114. case problem:
  115. footer = s.buffer
  116. default:
  117. panic("encountered unrecognized mode")
  118. }
  119. if footer != "" {
  120. output = ansi.ReplaceLastLine(output, style.Highlight(ansi.SetLength(footer, s.width, "\u2026")))
  121. }
  122. return output
  123. }
  124. func (s *State) Update(input byte) {
  125. s.m.Lock()
  126. defer s.m.Unlock()
  127. if s.mode == loading {
  128. return
  129. }
  130. if input == escapeKey {
  131. s.buffer = ""
  132. s.mode = normal
  133. s.output(s.view())
  134. return
  135. }
  136. if input == backspaceKey {
  137. if len(s.buffer) == 0 {
  138. s.mode = normal
  139. s.output(s.view())
  140. return
  141. }
  142. bufferRunes := []rune(s.buffer)
  143. s.buffer = string(bufferRunes[:len(bufferRunes)-1])
  144. if s.buffer == "" && s.mode == selection {
  145. s.mode = normal
  146. }
  147. s.output(s.view())
  148. return
  149. }
  150. if s.mode == command {
  151. if input == enterKey {
  152. if args := strings.SplitN(s.buffer, " ", 2); len(args) == 2 {
  153. err := s.subcommand(args[0], args[1])
  154. if err != nil {
  155. s.buffer = "Failed to run command: " + err.Error()
  156. s.mode = problem
  157. s.output(s.view())
  158. s.buffer = ""
  159. s.mode = normal
  160. }
  161. } else {
  162. s.buffer = ""
  163. s.mode = normal
  164. s.output(s.view())
  165. }
  166. return
  167. }
  168. s.buffer += string(input)
  169. s.output(s.view())
  170. return
  171. }
  172. if input == ':' {
  173. s.buffer = ""
  174. s.mode = command
  175. s.output(s.view())
  176. return
  177. }
  178. if input >= '0' && input <= '9' {
  179. if s.mode != selection {
  180. s.buffer = ""
  181. }
  182. s.buffer += string(input)
  183. s.mode = selection
  184. s.output(s.view())
  185. return
  186. }
  187. if s.mode == selection {
  188. if input == '.' || input == enterKey {
  189. number, err := strconv.Atoi(s.buffer)
  190. if err != nil {
  191. panic("buffer had a non-number while in selection mode")
  192. }
  193. link, mediaType, present := s.h.Current().feed.Current().SelectLink(number)
  194. if !present {
  195. s.buffer = ""
  196. s.mode = normal
  197. s.output(s.view())
  198. return
  199. }
  200. if input == '.' {
  201. s.openInternally(link)
  202. return
  203. }
  204. if input == enterKey {
  205. s.openExternally(link, mediaType)
  206. return
  207. }
  208. }
  209. /* At this point we know input is a non-number, non-., non-enter */
  210. s.mode = normal
  211. s.buffer = ""
  212. }
  213. if s.mode == opening {
  214. s.mode = normal
  215. s.buffer = ""
  216. }
  217. /* At this point we know we are in normal mode */
  218. switch input {
  219. case 'k': // up
  220. s.h.Current().feed.MoveUp()
  221. s.loadSurroundings()
  222. case 'j': // down
  223. s.h.Current().feed.MoveDown()
  224. s.loadSurroundings()
  225. case 'g': // return to OP
  226. s.h.Current().feed.MoveToCenter()
  227. case 'h': // back in history
  228. s.h.Back()
  229. case 'l': // forward in history
  230. s.h.Forward()
  231. case ' ': // select
  232. s.switchTo(s.h.Current().feed.Current())
  233. case 'c': // get creator of post
  234. unwrapped := s.h.Current().feed.Current()
  235. if activity, ok := unwrapped.(*pub.Activity); ok {
  236. unwrapped = activity.Target()
  237. }
  238. if post, ok := unwrapped.(*pub.Post); ok {
  239. creators := post.Creators()
  240. s.switchTo(creators)
  241. }
  242. case 'r': // get recipient of post
  243. unwrapped := s.h.Current().feed.Current()
  244. if activity, ok := unwrapped.(*pub.Activity); ok {
  245. unwrapped = activity.Target()
  246. }
  247. if post, ok := unwrapped.(*pub.Post); ok {
  248. recipients := post.Recipients()
  249. s.switchTo(recipients)
  250. }
  251. case 'a': // get actor of activity
  252. if activity, ok := s.h.Current().feed.Current().(*pub.Activity); ok {
  253. actor := activity.Actor()
  254. s.switchTo(actor)
  255. }
  256. case 'o':
  257. unwrapped := s.h.Current().feed.Current()
  258. if activity, ok := unwrapped.(*pub.Activity); ok {
  259. unwrapped = activity.Target()
  260. }
  261. if post, ok := unwrapped.(*pub.Post); ok {
  262. if link, mediaType, present := post.Media(); present {
  263. s.openExternally(link, mediaType)
  264. }
  265. }
  266. case 'p':
  267. if actor, ok := s.h.Current().feed.Current().(*pub.Actor); ok {
  268. if link, mediaType, present := actor.ProfilePic(); present {
  269. s.openExternally(link, mediaType)
  270. }
  271. }
  272. case 'b':
  273. if actor, ok := s.h.Current().feed.Current().(*pub.Actor); ok {
  274. if link, mediaType, present := actor.Banner(); present {
  275. s.openExternally(link, mediaType)
  276. }
  277. }
  278. }
  279. s.output(s.view())
  280. }
  281. func (s *State) switchTo(item any) {
  282. switch narrowed := item.(type) {
  283. case []pub.Tangible:
  284. if len(narrowed) == 0 {
  285. return
  286. }
  287. if len(narrowed) == 1 {
  288. s.h.Add(&Page{
  289. feed: feed.Create(narrowed[0]),
  290. children: narrowed[0].Children(),
  291. frontier: narrowed[0],
  292. })
  293. } else {
  294. s.h.Add(&Page{
  295. feed: feed.CreateAndAppend(narrowed),
  296. })
  297. }
  298. case pub.Tangible:
  299. s.h.Add(&Page{
  300. feed: feed.Create(narrowed),
  301. children: narrowed.Children(),
  302. frontier: narrowed,
  303. })
  304. case pub.Container:
  305. if s.mode != loading {
  306. s.mode = loading
  307. s.buffer = ""
  308. s.output(s.view())
  309. }
  310. children, nextCollection, newBasepoint := narrowed.Harvest(uint(config.Parsed.Style.Context + 1), 0)
  311. s.h.Add(&Page{
  312. basepoint: newBasepoint,
  313. children: nextCollection,
  314. feed: feed.CreateAndAppend(children),
  315. })
  316. default:
  317. panic("can't switch to non-Tangible non-Container")
  318. }
  319. s.mode = normal
  320. s.buffer = ""
  321. s.loadSurroundings()
  322. }
  323. func (s *State) SetWidthHeight(width int, height int) {
  324. s.m.Lock()
  325. defer s.m.Unlock()
  326. if s.width == width && s.height == height {
  327. return
  328. }
  329. s.width = width
  330. s.height = height
  331. s.output(s.view())
  332. }
  333. func (s *State) loadSurroundings() {
  334. page := s.h.Current()
  335. context := config.Parsed.Style.Context
  336. if !page.loadingUp && !page.feed.Contains(-context) && page.frontier != nil {
  337. page.loadingUp = true
  338. go func() {
  339. parents, newFrontier := page.frontier.Parents(uint(context))
  340. s.m.Lock()
  341. page.feed.Prepend(parents)
  342. page.frontier = newFrontier
  343. page.loadingUp = false
  344. s.output(s.view())
  345. s.m.Unlock()
  346. }()
  347. }
  348. if !page.loadingDown && !page.feed.Contains(context) && page.children != nil {
  349. page.loadingDown = true
  350. go func() {
  351. // TODO: need to do a new renaming, maybe upperFrontier, lowerFrontier
  352. children, nextCollection, newBasepoint := page.children.Harvest(uint(context), page.basepoint)
  353. s.m.Lock()
  354. page.feed.Append(children)
  355. page.children = nextCollection
  356. page.basepoint = newBasepoint
  357. page.loadingDown = false
  358. s.output(s.view())
  359. s.m.Unlock()
  360. }()
  361. }
  362. }
  363. func (s *State) openUserInput(input string) {
  364. s.mode = loading
  365. s.buffer = ""
  366. s.output(s.view())
  367. go func() {
  368. result := pub.FetchUserInput(input)
  369. s.m.Lock()
  370. s.switchTo(result)
  371. s.output(s.view())
  372. s.m.Unlock()
  373. }()
  374. }
  375. func (s *State) openInternally(input string) {
  376. s.mode = loading
  377. s.buffer = ""
  378. s.output(s.view())
  379. go func() {
  380. result := pub.New(input, nil)
  381. s.m.Lock()
  382. s.switchTo(result)
  383. s.output(s.view())
  384. s.m.Unlock()
  385. }()
  386. }
  387. func (s *State) openFeed(input string) {
  388. inputs, present := config.Parsed.Feeds[input]
  389. if !present {
  390. s.mode = problem
  391. s.buffer = "Failed to open feed: " + input + " is not a known feed"
  392. s.output(s.view())
  393. s.mode = normal
  394. s.buffer = ""
  395. return
  396. }
  397. s.mode = loading
  398. s.buffer = ""
  399. s.output(s.view())
  400. go func() {
  401. result := splicer.NewSplicer(inputs)
  402. s.switchTo(result)
  403. s.output(s.view())
  404. }()
  405. }
  406. func NewState(width int, height int, output func(string)) *State {
  407. s := &State{
  408. h: history.History[*Page]{},
  409. width: width,
  410. height: height,
  411. output: output,
  412. m: &sync.Mutex{},
  413. mode: loading,
  414. }
  415. return s
  416. }
  417. func (s *State) Subcommand(name, argument string) error {
  418. s.m.Lock()
  419. if name == "feed" {
  420. if _, present := config.Parsed.Feeds[argument]; !present {
  421. return errors.New("failed to open feed: " + argument + " is not a known feed")
  422. }
  423. }
  424. err := s.subcommand(name, argument)
  425. if err != nil {
  426. /* Here I hold the lock indefinitely intentionally, to stop the ui thread and allow main.go to do cleanup */
  427. return err
  428. }
  429. s.m.Unlock()
  430. return nil
  431. }
  432. func (s *State) subcommand(name, argument string) error {
  433. switch name {
  434. case "open":
  435. s.openUserInput(argument)
  436. case "feed":
  437. s.openFeed(argument)
  438. default:
  439. return fmt.Errorf("unrecognized subcommand: %s", name)
  440. }
  441. return nil
  442. }
  443. func (s *State) openExternally(link string, mediaType *mime.MediaType) {
  444. s.mode = opening
  445. s.buffer = link
  446. s.output(s.view())
  447. command := make([]string, len(config.Parsed.Media.Hook))
  448. copy(command, config.Parsed.Media.Hook)
  449. foundPercentU := false
  450. for i, field := range command {
  451. if i == 0 {
  452. continue
  453. }
  454. switch field {
  455. case "%url":
  456. command[i] = link
  457. foundPercentU = true
  458. case "%mimetype":
  459. command[i] = mediaType.Essence
  460. case "%subtype":
  461. command[i] = mediaType.Subtype
  462. case "%supertype":
  463. command[i] = mediaType.Supertype
  464. }
  465. }
  466. cmd := exec.Command(command[0], command[1:]...)
  467. if !foundPercentU {
  468. cmd.Stdin = strings.NewReader(link)
  469. }
  470. go func() {
  471. outputBytes, err := cmd.CombinedOutput()
  472. output := string(outputBytes)
  473. s.m.Lock()
  474. defer s.m.Unlock()
  475. if s.mode != opening {
  476. return
  477. }
  478. if err != nil {
  479. s.mode = problem
  480. s.buffer = "Failed to open link: " + output
  481. s.output(s.view())
  482. s.mode = normal
  483. s.buffer = ""
  484. return
  485. }
  486. s.mode = normal
  487. s.buffer = ""
  488. s.output(s.view())
  489. }()
  490. }