Testing ground for GUI

xgb-xrender.go 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package main
  2. // We could also easily use x/image/font/basicfont to load some glyphs into X,
  3. // relying on the fact that it is a vertical array of A8 masks. Though it only
  4. // supports ASCII and has but one size. Best just make a custom BDF loader,
  5. // those fonts have larger coverages and we would be in control. Though again,
  6. // they don't seem to be capable of antialiasing.
  7. import (
  8. "fmt"
  9. "github.com/BurntSushi/xgb"
  10. "github.com/BurntSushi/xgb/render"
  11. "github.com/BurntSushi/xgb/xproto"
  12. // golang.org/x/image/font/opentype cannot render yet but the API is
  13. // more or less the same.
  14. "github.com/golang/freetype"
  15. "github.com/golang/freetype/truetype"
  16. "golang.org/x/image/font"
  17. "golang.org/x/image/font/gofont/goregular"
  18. "golang.org/x/image/math/fixed"
  19. "image"
  20. "image/draw"
  21. "log"
  22. "math/rand"
  23. )
  24. func F64ToFixed(f float64) render.Fixed { return render.Fixed(f * 65536) }
  25. func FixedToF64(f render.Fixed) float64 { return float64(f) / 65536 }
  26. func glyphListBytes(buf []byte, runes []rune, size int) int {
  27. b := 0
  28. for _, r := range runes {
  29. switch size {
  30. default:
  31. buf[b] = byte(r)
  32. b += 1
  33. case 2:
  34. xgb.Put16(buf[b:], uint16(r))
  35. b += 2
  36. case 4:
  37. xgb.Put32(buf[b:], uint32(r))
  38. b += 4
  39. }
  40. }
  41. return xgb.Pad(b)
  42. }
  43. // When the len is 255, a GLYPHABLE follows, otherwise a list of CARD8/16/32.
  44. func glyphEltHeaderBytes(buf []byte, len byte, deltaX, deltaY int16) int {
  45. b := 0
  46. buf[b] = len
  47. b += 4
  48. xgb.Put16(buf[b:], uint16(deltaX))
  49. b += 2
  50. xgb.Put16(buf[b:], uint16(deltaY))
  51. b += 2
  52. return xgb.Pad(b)
  53. }
  54. type xgbCookie interface{ Check() error }
  55. // TODO: We actually need a higher-level function that also keeps track of
  56. // and loads glyphs into the X server.
  57. // TODO: We also need a way to use kerning tables with this, inserting/removing
  58. // advance pixels between neighboring characters.
  59. // compositeString makes an appropriate render.CompositeGlyphs request,
  60. // assuming that glyphs equal Unicode codepoints.
  61. func compositeString(c *xgb.Conn, op byte, src, dst render.Picture,
  62. maskFormat render.Pictformat, glyphset render.Glyphset, srcX, srcY int16,
  63. destX, destY int16, text string) xgbCookie {
  64. runes := []rune(text)
  65. var highest rune
  66. for _, r := range runes {
  67. if r > highest {
  68. highest = r
  69. }
  70. }
  71. size := 1
  72. switch {
  73. case highest > 1<<16:
  74. size = 4
  75. case highest > 1<<8:
  76. size = 2
  77. }
  78. // They gave up on the XCB protocol API and we need to serialize explicitly.
  79. // To spare us from caring about the padding, use the largest number lesser
  80. // than 255 that is divisible by 4 (for size 2 and 4 the requirements are
  81. // less strict but this works in the general case).
  82. const maxPerChunk = 252
  83. buf := make([]byte, (len(runes)+maxPerChunk-1)/maxPerChunk*8+len(runes)*size)
  84. b := 0
  85. for len(runes) > maxPerChunk {
  86. b += glyphEltHeaderBytes(buf[b:], maxPerChunk, 0, 0)
  87. b += glyphListBytes(buf[b:], runes[:maxPerChunk], size)
  88. runes = runes[maxPerChunk:]
  89. }
  90. if len(runes) > 0 {
  91. b += glyphEltHeaderBytes(buf[b:], byte(len(runes)), destX, destY)
  92. b += glyphListBytes(buf[b:], runes, size)
  93. }
  94. switch size {
  95. default:
  96. return render.CompositeGlyphs8(c, op, src, dst, maskFormat, glyphset,
  97. srcX, srcY, buf)
  98. case 2:
  99. return render.CompositeGlyphs16(c, op, src, dst, maskFormat, glyphset,
  100. srcX, srcY, buf)
  101. case 4:
  102. return render.CompositeGlyphs32(c, op, src, dst, maskFormat, glyphset,
  103. srcX, srcY, buf)
  104. }
  105. }
  106. func main() {
  107. X, err := xgb.NewConn()
  108. if err != nil {
  109. log.Fatalln(err)
  110. }
  111. if err := render.Init(X); err != nil {
  112. log.Fatalln(err)
  113. }
  114. setup := xproto.Setup(X)
  115. screen := setup.DefaultScreen(X)
  116. var visual xproto.Visualid
  117. var depth byte
  118. for _, i := range screen.AllowedDepths {
  119. if i.Depth == 32 {
  120. // TODO: Could/should check other parameters.
  121. for _, v := range i.Visuals {
  122. if v.Class == xproto.VisualClassTrueColor {
  123. visual = v.VisualId
  124. depth = i.Depth
  125. break
  126. }
  127. }
  128. }
  129. }
  130. if visual == 0 {
  131. log.Fatalln("cannot find an RGBA TrueColor visual")
  132. }
  133. mid, err := xproto.NewColormapId(X)
  134. if err != nil {
  135. log.Fatalln(err)
  136. }
  137. _ = xproto.CreateColormap(
  138. X, xproto.ColormapAllocNone, mid, screen.Root, visual)
  139. wid, err := xproto.NewWindowId(X)
  140. if err != nil {
  141. log.Fatalln(err)
  142. }
  143. // Border pixel and colormap are required when depth differs from parent.
  144. _ = xproto.CreateWindow(X, depth, wid, screen.Root,
  145. 0, 0, 500, 500, 0, xproto.WindowClassInputOutput,
  146. visual, xproto.CwBorderPixel|xproto.CwColormap,
  147. []uint32{0, uint32(mid)})
  148. // This could be included in CreateWindow parameters.
  149. _ = xproto.ChangeWindowAttributes(X, wid,
  150. xproto.CwBackPixel|xproto.CwEventMask, []uint32{0x80808080,
  151. xproto.EventMaskStructureNotify | xproto.EventMaskKeyPress |
  152. xproto.EventMaskExposure})
  153. title := []byte("Gradient")
  154. _ = xproto.ChangeProperty(X, xproto.PropModeReplace, wid, xproto.AtomWmName,
  155. xproto.AtomString, 8, uint32(len(title)), title)
  156. _ = xproto.MapWindow(X, wid)
  157. /*
  158. rfilters, err := render.QueryFilters(X, xproto.Drawable(wid)).Reply()
  159. if err != nil {
  160. log.Fatalln(err)
  161. }
  162. filters := []string{}
  163. for _, f := range rfilters.Filters {
  164. filters = append(filters, f.Name)
  165. }
  166. log.Printf("filters: %v\n", filters)
  167. */
  168. pformats, err := render.QueryPictFormats(X).Reply()
  169. if err != nil {
  170. log.Fatalln(err)
  171. }
  172. /*
  173. for _, pf := range pformats.Formats {
  174. log.Printf("format %2d: depth %2d, RGBA %3x %3x %3x %3x\n",
  175. pf.Id, pf.Depth,
  176. pf.Direct.RedMask, pf.Direct.GreenMask, pf.Direct.BlueMask,
  177. pf.Direct.AlphaMask)
  178. }
  179. */
  180. // Similar to XRenderFindVisualFormat.
  181. // The DefaultScreen is almost certain to be zero.
  182. var pformat render.Pictformat
  183. for _, pd := range pformats.Screens[X.DefaultScreen].Depths {
  184. // This check seems to be slightly extraneous.
  185. if pd.Depth != depth {
  186. continue
  187. }
  188. for _, pv := range pd.Visuals {
  189. if pv.Visual == visual {
  190. pformat = pv.Format
  191. }
  192. }
  193. }
  194. // ...or just scan through pformats.Formats and look for matches, which is
  195. // what XRenderFindStandardFormat in Xlib does as well as exp/shiny.
  196. f, err := freetype.ParseFont(goregular.TTF)
  197. if err != nil {
  198. log.Fatalln(err)
  199. }
  200. // LCD subpixel rendering isn't supported. :(
  201. opts := &truetype.Options{
  202. Size: 10,
  203. DPI: 96, // TODO: Take this from the screen or monitor.
  204. Hinting: font.HintingFull,
  205. }
  206. face := truetype.NewFace(f, opts)
  207. bounds := f.Bounds(fixed.Int26_6(opts.Size * float64(opts.DPI) *
  208. (64.0 / 72.0)))
  209. var rgbFormat render.Pictformat
  210. for _, pf := range pformats.Formats {
  211. // Hopefully. Might want to check byte order.
  212. if pf.Depth == 32 && pf.Direct.AlphaMask != 0 {
  213. rgbFormat = pf.Id
  214. break
  215. }
  216. }
  217. gsid, err := render.NewGlyphsetId(X)
  218. if err != nil {
  219. log.Fatalln(err)
  220. }
  221. // NOTE: A depth of 24 will not work, the server always rejects it.
  222. // Composite alpha doesn't make sense since golang/freetype can't use it.
  223. // We use RGBA here just so that lines are padded to 32 bits.
  224. _ = render.CreateGlyphSet(X, gsid, rgbFormat)
  225. // NOTE: We could do gamma post-correction in higher precision if we
  226. // implemented our own clone of the image.Image implementation.
  227. nrgb := image.NewRGBA(image.Rect(
  228. +bounds.Min.X.Floor(),
  229. -bounds.Min.Y.Floor(),
  230. +bounds.Max.X.Ceil(),
  231. -bounds.Max.Y.Ceil(),
  232. ))
  233. for r := rune(32); r < 128; r++ {
  234. dr, mask, maskp, advance, ok := face.Glyph(
  235. fixed.P(0, 0) /* subpixel destination location */, r)
  236. if !ok {
  237. log.Println("skip")
  238. continue
  239. }
  240. for i := 0; i < len(nrgb.Pix); i++ {
  241. nrgb.Pix[i] = 0
  242. }
  243. draw.Draw(nrgb, dr, mask, maskp, draw.Src)
  244. _ = render.AddGlyphs(X, gsid, 1, []uint32{uint32(r)},
  245. []render.Glyphinfo{{
  246. Width: uint16(nrgb.Rect.Size().X),
  247. Height: uint16(nrgb.Rect.Size().Y),
  248. X: int16(-bounds.Min.X.Floor()),
  249. Y: int16(+bounds.Max.Y.Ceil()),
  250. XOff: int16(advance.Ceil()),
  251. YOff: int16(0),
  252. }}, []byte(nrgb.Pix))
  253. }
  254. pid, err := render.NewPictureId(X)
  255. if err != nil {
  256. log.Fatalln(err)
  257. }
  258. // Dithering is not supported. :(
  259. render.CreatePicture(X, pid, xproto.Drawable(wid), pformat, 0, []uint32{})
  260. // Reserve an ID for the gradient.
  261. gid, err := render.NewPictureId(X)
  262. if err != nil {
  263. log.Fatalln(err)
  264. }
  265. whiteid, err := render.NewPictureId(X)
  266. if err != nil {
  267. log.Fatalln(err)
  268. }
  269. _ = render.CreateSolidFill(X, whiteid, render.Color{
  270. Red: 0xffff,
  271. Green: 0xffff,
  272. Blue: 0xffff,
  273. Alpha: 0xffff,
  274. })
  275. var from, to render.Color
  276. var start, end uint32
  277. recolor := func() {
  278. start = rand.Uint32() & 0xffffff
  279. from = render.Color{
  280. Red: 0x101 * uint16((start>>16)&0xff),
  281. Green: 0x101 * uint16((start>>8)&0xff),
  282. Blue: 0x101 * uint16(start&0xff),
  283. Alpha: 0xffff,
  284. }
  285. end = rand.Uint32() & 0xffffff
  286. to = render.Color{
  287. Red: 0x101 * uint16((end>>16)&0xff),
  288. Green: 0x101 * uint16((end>>8)&0xff),
  289. Blue: 0x101 * uint16(end&0xff),
  290. Alpha: 0xffff,
  291. }
  292. }
  293. var w, h uint16
  294. gradient := func() {
  295. if w < 100 || h < 100 {
  296. return
  297. }
  298. // We could also use a transformation matrix for changes in size.
  299. _ = render.CreateLinearGradient(X, gid,
  300. render.Pointfix{F64ToFixed(0), F64ToFixed(0)},
  301. render.Pointfix{F64ToFixed(0), F64ToFixed(float64(h) - 100)},
  302. 2, []render.Fixed{F64ToFixed(0), F64ToFixed(1)},
  303. []render.Color{from, to})
  304. _ = render.Composite(X, render.PictOpSrc, gid, render.PictureNone, pid,
  305. 0, 0, 0, 0, 50, 50, w-100, h-100)
  306. _ = render.FreePicture(X, gid)
  307. _ = compositeString(X, render.PictOpOver, whiteid, pid,
  308. 0 /* TODO: mask Pictureformat? */, gsid, 0, 0, 100, 100,
  309. fmt.Sprintf("%#06x - %#06x", start, end))
  310. _ = compositeString(X, render.PictOpOver, whiteid, pid,
  311. 0 /* TODO: mask Pictureformat? */, gsid, 0, 0, 100, 150,
  312. "The quick brown fox jumps over the lazy dog.")
  313. }
  314. for {
  315. ev, xerr := X.WaitForEvent()
  316. if xerr != nil {
  317. log.Printf("Error: %s\n", xerr)
  318. return
  319. }
  320. if ev == nil {
  321. return
  322. }
  323. log.Printf("Event: %s\n", ev)
  324. switch e := ev.(type) {
  325. case xproto.UnmapNotifyEvent:
  326. return
  327. case xproto.ConfigureNotifyEvent:
  328. w, h = e.Width, e.Height
  329. recolor()
  330. case xproto.KeyPressEvent:
  331. recolor()
  332. gradient()
  333. case xproto.ExposeEvent:
  334. gradient()
  335. }
  336. }
  337. }