ui.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. )
  17. /*
  18. The public methods herein are threadsafe, the private methods
  19. are not and need to be protected by State.m
  20. */
  21. /* Modes */
  22. const (
  23. loading = iota
  24. normal
  25. command
  26. selection
  27. opening
  28. problem
  29. )
  30. const (
  31. enterKey byte = '\r'
  32. escapeKey byte = 27
  33. backspaceKey byte = 127
  34. )
  35. type Page struct {
  36. feed *feed.Feed
  37. frontier pub.Tangible
  38. loadingUp bool
  39. children pub.Container
  40. basepoint uint
  41. loadingDown bool
  42. }
  43. type State struct {
  44. m *sync.Mutex
  45. h history.History[*Page]
  46. width int
  47. height int
  48. output func(string)
  49. config *config.Config
  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 := -s.config.Context; i <= s.config.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(-s.config.Context-1) {
  95. top = "\n " + style.Color("Loading…") + "\n\n" + top
  96. }
  97. if s.h.Current().loadingDown && !s.h.Current().feed.Contains(s.config.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. }
  165. return
  166. }
  167. s.buffer += string(input)
  168. s.output(s.view())
  169. return
  170. }
  171. if input == ':' {
  172. s.buffer = ""
  173. s.mode = command
  174. s.output(s.view())
  175. return
  176. }
  177. if input >= '0' && input <= '9' {
  178. if s.mode != selection {
  179. s.buffer = ""
  180. }
  181. s.buffer += string(input)
  182. s.mode = selection
  183. s.output(s.view())
  184. return
  185. }
  186. if s.mode == selection {
  187. if input == '.' || input == enterKey {
  188. number, err := strconv.Atoi(s.buffer)
  189. if err != nil {
  190. panic("buffer had a non-number while in selection mode")
  191. }
  192. link, mediaType, present := s.h.Current().feed.Current().SelectLink(number)
  193. if !present {
  194. s.buffer = ""
  195. s.mode = normal
  196. s.output(s.view())
  197. return
  198. }
  199. if input == '.' {
  200. s.openInternally(link)
  201. return
  202. }
  203. if input == enterKey {
  204. s.openExternally(link, mediaType)
  205. return
  206. }
  207. }
  208. /* At this point we know input is a non-number, non-., non-enter */
  209. s.mode = normal
  210. s.buffer = ""
  211. }
  212. if s.mode == opening {
  213. s.mode = normal
  214. s.buffer = ""
  215. }
  216. /* At this point we know we are in normal mode */
  217. switch input {
  218. case 'k': // up
  219. s.h.Current().feed.MoveUp()
  220. s.loadSurroundings()
  221. case 'j': // down
  222. s.h.Current().feed.MoveDown()
  223. s.loadSurroundings()
  224. case 'g': // return to OP
  225. s.h.Current().feed.MoveToCenter()
  226. case 'h': // back in history
  227. s.h.Back()
  228. case 'l': // forward in history
  229. s.h.Forward()
  230. case ' ': // select
  231. s.switchTo(s.h.Current().feed.Current())
  232. case 'c': // get creator of post
  233. unwrapped := s.h.Current().feed.Current()
  234. if activity, ok := unwrapped.(*pub.Activity); ok {
  235. unwrapped = activity.Target()
  236. }
  237. if post, ok := unwrapped.(*pub.Post); ok {
  238. creators := post.Creators()
  239. s.switchTo(creators)
  240. }
  241. case 'r': // get recipient of post
  242. unwrapped := s.h.Current().feed.Current()
  243. if activity, ok := unwrapped.(*pub.Activity); ok {
  244. unwrapped = activity.Target()
  245. }
  246. if post, ok := unwrapped.(*pub.Post); ok {
  247. recipients := post.Recipients()
  248. s.switchTo(recipients)
  249. }
  250. case 'a': // get actor of activity
  251. if activity, ok := s.h.Current().feed.Current().(*pub.Activity); ok {
  252. actor := activity.Actor()
  253. s.switchTo(actor)
  254. }
  255. case 'o':
  256. unwrapped := s.h.Current().feed.Current()
  257. if activity, ok := unwrapped.(*pub.Activity); ok {
  258. unwrapped = activity.Target()
  259. }
  260. if post, ok := unwrapped.(*pub.Post); ok {
  261. if link, mediaType, present := post.Media(); present {
  262. s.openExternally(link, mediaType)
  263. }
  264. }
  265. case 'p':
  266. if actor, ok := s.h.Current().feed.Current().(*pub.Actor); ok {
  267. if link, mediaType, present := actor.ProfilePic(); present {
  268. s.openExternally(link, mediaType)
  269. }
  270. }
  271. case 'b':
  272. if actor, ok := s.h.Current().feed.Current().(*pub.Actor); ok {
  273. if link, mediaType, present := actor.Banner(); present {
  274. s.openExternally(link, mediaType)
  275. }
  276. }
  277. }
  278. s.output(s.view())
  279. }
  280. func (s *State) switchTo(item any) {
  281. switch narrowed := item.(type) {
  282. case []pub.Tangible:
  283. if len(narrowed) == 0 {
  284. return
  285. }
  286. if len(narrowed) == 1 {
  287. s.h.Add(&Page{
  288. feed: feed.Create(narrowed[0]),
  289. children: narrowed[0].Children(),
  290. frontier: narrowed[0],
  291. })
  292. } else {
  293. s.h.Add(&Page{
  294. feed: feed.CreateAndAppend(narrowed),
  295. })
  296. }
  297. case pub.Tangible:
  298. s.h.Add(&Page{
  299. feed: feed.Create(narrowed),
  300. children: narrowed.Children(),
  301. frontier: narrowed,
  302. })
  303. case pub.Container:
  304. if s.mode != loading {
  305. s.mode = loading
  306. s.buffer = ""
  307. s.output(s.view())
  308. }
  309. children, nextCollection, newBasepoint := narrowed.Harvest(uint(s.config.Context), 0)
  310. s.h.Add(&Page{
  311. basepoint: newBasepoint,
  312. children: nextCollection,
  313. feed: feed.CreateAndAppend(children),
  314. })
  315. default:
  316. panic("can't switch to non-Tangible non-Container")
  317. }
  318. s.mode = normal
  319. s.buffer = ""
  320. s.loadSurroundings()
  321. }
  322. func (s *State) SetWidthHeight(width int, height int) {
  323. s.m.Lock()
  324. defer s.m.Unlock()
  325. if s.width == width && s.height == height {
  326. return
  327. }
  328. s.width = width
  329. s.height = height
  330. s.output(s.view())
  331. }
  332. func (s *State) loadSurroundings() {
  333. page := s.h.Current()
  334. context := s.config.Context
  335. if !page.loadingUp && !page.feed.Contains(-context) && page.frontier != nil {
  336. page.loadingUp = true
  337. go func() {
  338. parents, newFrontier := page.frontier.Parents(uint(context))
  339. s.m.Lock()
  340. page.feed.Prepend(parents)
  341. page.frontier = newFrontier
  342. page.loadingUp = false
  343. s.output(s.view())
  344. s.m.Unlock()
  345. }()
  346. }
  347. if !page.loadingDown && !page.feed.Contains(context) && page.children != nil {
  348. page.loadingDown = true
  349. go func() {
  350. // TODO: need to do a new renaming, maybe upperFrontier, lowerFrontier
  351. children, nextCollection, newBasepoint := page.children.Harvest(uint(context), page.basepoint)
  352. s.m.Lock()
  353. page.feed.Append(children)
  354. page.children = nextCollection
  355. page.basepoint = newBasepoint
  356. page.loadingDown = false
  357. s.output(s.view())
  358. s.m.Unlock()
  359. }()
  360. }
  361. }
  362. func (s *State) openUserInput(input string) {
  363. s.mode = loading
  364. s.buffer = ""
  365. s.output(s.view())
  366. go func() {
  367. result := pub.FetchUserInput(input)
  368. s.m.Lock()
  369. s.switchTo(result)
  370. s.output(s.view())
  371. s.m.Unlock()
  372. }()
  373. }
  374. func (s *State) openInternally(input string) {
  375. s.mode = loading
  376. s.buffer = ""
  377. s.output(s.view())
  378. go func() {
  379. result := pub.New(input, nil)
  380. s.m.Lock()
  381. s.switchTo(result)
  382. s.output(s.view())
  383. s.m.Unlock()
  384. }()
  385. }
  386. func (s *State) openFeed(input string) {
  387. inputs, present := s.config.Feeds[input]
  388. if !present {
  389. s.mode = problem
  390. s.buffer = "Failed to open feed: " + input + " is not a known feed"
  391. s.output(s.view())
  392. s.mode = normal
  393. s.buffer = ""
  394. return
  395. }
  396. s.mode = loading
  397. s.buffer = ""
  398. s.output(s.view())
  399. go func() {
  400. result := splicer.NewSplicer(inputs)
  401. s.switchTo(result)
  402. s.output(s.view())
  403. }()
  404. }
  405. func NewState(config *config.Config, width int, height int, output func(string)) *State {
  406. s := &State{
  407. h: history.History[*Page]{},
  408. config: config,
  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. err := s.subcommand(name, argument)
  420. if err != nil {
  421. /* Here I hold the lock indefinitely intentionally, to stop the ui thread and allow main.go to do cleanup */
  422. return err
  423. }
  424. s.m.Unlock()
  425. return nil
  426. }
  427. func (s *State) subcommand(name, argument string) error {
  428. switch name {
  429. case "open":
  430. s.openUserInput(argument)
  431. case "feed":
  432. s.openFeed(argument)
  433. default:
  434. return fmt.Errorf("unrecognized subcommand: %s", name)
  435. }
  436. return nil
  437. }
  438. func (s *State) openExternally(link string, mediaType *mime.MediaType) {
  439. s.mode = opening
  440. s.buffer = link
  441. s.output(s.view())
  442. command := make([]string, len(s.config.MediaHook))
  443. copy(command, s.config.MediaHook)
  444. foundPercentU := false
  445. for i, field := range command {
  446. if i == 0 {
  447. continue
  448. }
  449. switch field {
  450. case "%u":
  451. command[i] = link
  452. foundPercentU = true
  453. case "%m":
  454. command[i] = mediaType.Essence
  455. case "%s":
  456. command[i] = mediaType.Subtype
  457. case "%t":
  458. command[i] = mediaType.Supertype
  459. }
  460. }
  461. cmd := exec.Command(command[0], command[1:]...)
  462. if !foundPercentU {
  463. cmd.Stdin = strings.NewReader(link)
  464. }
  465. go func() {
  466. outputBytes, err := cmd.CombinedOutput()
  467. output := string(outputBytes)
  468. s.m.Lock()
  469. defer s.m.Unlock()
  470. if s.mode != opening {
  471. return
  472. }
  473. if err != nil {
  474. s.mode = problem
  475. s.buffer = "Failed to open link: " + output
  476. s.output(s.view())
  477. s.mode = normal
  478. s.buffer = ""
  479. return
  480. }
  481. s.mode = normal
  482. s.buffer = ""
  483. s.output(s.view())
  484. }()
  485. }