ui.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. s.mode = loading
  300. s.buffer = ""
  301. s.output(s.view())
  302. children, nextCollection, newBasepoint := narrowed.Harvest(uint(s.config.Context), 0)
  303. s.h.Add(&Page{
  304. basepoint: newBasepoint,
  305. children: nextCollection,
  306. feed: feed.CreateAndAppend(children),
  307. })
  308. default:
  309. panic("can't switch to non-Tangible non-Container")
  310. }
  311. s.mode = normal
  312. s.buffer = ""
  313. s.loadSurroundings()
  314. }
  315. func (s *State) SetWidthHeight(width int, height int) {
  316. s.m.Lock()
  317. defer s.m.Unlock()
  318. if s.width == width && s.height == height {
  319. return
  320. }
  321. s.width = width
  322. s.height = height
  323. s.output(s.view())
  324. }
  325. func (s *State) loadSurroundings() {
  326. page := s.h.Current()
  327. context := s.config.Context
  328. if !page.loadingUp && !page.feed.Contains(-context) && page.frontier != nil {
  329. page.loadingUp = true
  330. go func() {
  331. parents, newFrontier := page.frontier.Parents(uint(context))
  332. s.m.Lock()
  333. page.feed.Prepend(parents)
  334. page.frontier = newFrontier
  335. page.loadingUp = false
  336. s.output(s.view())
  337. s.m.Unlock()
  338. }()
  339. }
  340. if !page.loadingDown && !page.feed.Contains(context) && page.children != nil {
  341. page.loadingDown = true
  342. go func() {
  343. // TODO: need to do a new renaming, maybe upperFrontier, lowerFrontier
  344. children, nextCollection, newBasepoint := page.children.Harvest(uint(context), page.basepoint)
  345. s.m.Lock()
  346. page.feed.Append(children)
  347. page.children = nextCollection
  348. page.basepoint = newBasepoint
  349. page.loadingDown = false
  350. s.output(s.view())
  351. s.m.Unlock()
  352. }()
  353. }
  354. }
  355. func (s *State) openUserInput(input string) {
  356. s.mode = loading
  357. s.buffer = ""
  358. s.output(s.view())
  359. go func() {
  360. result := pub.FetchUserInput(input)
  361. s.m.Lock()
  362. s.switchTo(result)
  363. s.output(s.view())
  364. s.m.Unlock()
  365. }()
  366. }
  367. func (s *State) openInternally(input string) {
  368. s.mode = loading
  369. s.buffer = ""
  370. s.output(s.view())
  371. go func() {
  372. result := pub.New(input, nil)
  373. s.m.Lock()
  374. s.switchTo(result)
  375. s.output(s.view())
  376. s.m.Unlock()
  377. }()
  378. }
  379. func (s *State) openFeed(input string) {
  380. inputs, present := s.config.Feeds[input]
  381. if !present {
  382. s.mode = problem
  383. s.buffer = "Failed to open feed: " + input + " is not a known feed"
  384. s.output(s.view())
  385. s.mode = normal
  386. s.buffer = ""
  387. return
  388. }
  389. s.mode = loading
  390. s.buffer = ""
  391. s.output(s.view())
  392. go func() {
  393. result := splicer.NewSplicer(inputs)
  394. s.switchTo(result)
  395. s.output(s.view())
  396. }()
  397. }
  398. func NewState(config *config.Config, width int, height int, output func(string)) *State {
  399. s := &State{
  400. h: history.History[*Page]{},
  401. config: config,
  402. width: width,
  403. height: height,
  404. output: output,
  405. m: &sync.Mutex{},
  406. mode: loading,
  407. }
  408. return s
  409. }
  410. func (s *State) Subcommand(name, argument string) error {
  411. s.m.Lock()
  412. err := s.subcommand(name, argument)
  413. if err != nil {
  414. /* Here I hold the lock indefinitely intentionally, to stop the ui thread and allow main.go to do cleanup */
  415. return err
  416. }
  417. s.m.Unlock()
  418. return nil
  419. }
  420. func (s *State) subcommand(name, argument string) error {
  421. switch name {
  422. case "open":
  423. s.openUserInput(argument)
  424. case "feed":
  425. s.openFeed(argument)
  426. default:
  427. return fmt.Errorf("unrecognized subcommand: %s", name)
  428. }
  429. return nil
  430. }
  431. func (s *State) openExternally(link string, mediaType *mime.MediaType) {
  432. s.mode = opening
  433. s.buffer = link
  434. s.output(s.view())
  435. command := make([]string, len(s.config.MediaHook))
  436. copy(command, s.config.MediaHook)
  437. foundPercentU := false
  438. for i, field := range command {
  439. if i == 0 {
  440. continue
  441. }
  442. switch field {
  443. case "%u":
  444. command[i] = link
  445. foundPercentU = true
  446. case "%m":
  447. command[i] = mediaType.Essence
  448. case "%s":
  449. command[i] = mediaType.Subtype
  450. case "%t":
  451. command[i] = mediaType.Supertype
  452. }
  453. }
  454. cmd := exec.Command(command[0], command[1:]...)
  455. if !foundPercentU {
  456. cmd.Stdin = strings.NewReader(link)
  457. }
  458. go func() {
  459. err := cmd.Run()
  460. s.m.Lock()
  461. defer s.m.Unlock()
  462. if s.mode != opening {
  463. return
  464. }
  465. if err != nil {
  466. s.mode = problem
  467. s.buffer = "Failed to open link: " + ansi.Squash(err.Error())
  468. s.output(s.view())
  469. s.mode = normal
  470. s.buffer = ""
  471. return
  472. }
  473. s.mode = normal
  474. s.buffer = ""
  475. s.output(s.view())
  476. }()
  477. }