ui.go 11 KB

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