aboutsummaryrefslogtreecommitdiff
path: root/prototypes/xgb-image.go
blob: e93fe6053745a17c3907c6d080f4a259e7b733f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package main

import (
	"encoding/binary"
	"log"
	"os"
	"reflect"
	"time"
	"unsafe"

	"github.com/BurntSushi/xgb"
	"github.com/BurntSushi/xgb/render"
	"github.com/BurntSushi/xgb/shm"
	"github.com/BurntSushi/xgb/xproto"

	"image"
	"image/color"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)

// #include <sys/ipc.h>
// #include <sys/shm.h>
import "C"

func F64ToFixed(f float64) render.Fixed { return render.Fixed(f * 65536) }
func FixedToF64(f render.Fixed) float64 { return float64(f) / 65536 }

var formats = map[byte]struct {
	format    render.Directformat
	transform func(color.Color) uint32
}{
	32: {
		format: render.Directformat{
			RedShift:   16,
			RedMask:    0xff,
			GreenShift: 8,
			GreenMask:  0xff,
			BlueShift:  0,
			BlueMask:   0xff,
			AlphaShift: 24,
			AlphaMask:  0xff,
		},
		transform: func(color color.Color) uint32 {
			r, g, b, a := color.RGBA()
			return (a>>8)<<24 | (r>>8)<<16 | (g>>8)<<8 | (b >> 8)
		},
	},
	30: {
		/*
			// Alpha makes compositing unbearably slow.
			AlphaShift: 30,
			AlphaMask:  0x3,
		*/
		format: render.Directformat{
			RedShift:   20,
			RedMask:    0x3ff,
			GreenShift: 10,
			GreenMask:  0x3ff,
			BlueShift:  0,
			BlueMask:   0x3ff,
		},
		transform: func(color color.Color) uint32 {
			r, g, b, a := color.RGBA()
			return (a>>14)<<30 | (r>>6)<<20 | (g>>6)<<10 | (b >> 6)
		},
	},
}

func main() {
	/*
		pf, err := os.Create("pprof.out")
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(pf)
		defer pprof.StopCPUProfile()
	*/

	// Load a picture from the command line.
	f, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatalln(err)
	}
	defer f.Close()

	img, name, err := image.Decode(f)
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("image type is", name)

	// Miscellaneous X11 initialization.
	X, err := xgb.NewConn()
	if err != nil {
		log.Fatalln(err)
	}

	if err := render.Init(X); err != nil {
		log.Fatalln(err)
	}

	setup := xproto.Setup(X)
	screen := setup.DefaultScreen(X)

	visual, depth := screen.RootVisual, screen.RootDepth

	// Only go for 10-bit when the picture can make use of that range.
	prefer30 := false
	switch img.(type) {
	case *image.Gray16, *image.RGBA64, *image.NRGBA64:
		prefer30 = true
	}

	// XXX: We don't /need/ alpha here, it's just a minor improvement--affects
	// the backpixel value. (And we reject it in 30-bit depth anyway.)
Depths:
	for _, i := range screen.AllowedDepths {
		for _, v := range i.Visuals {
			// TODO: Could/should check other parameters, e.g., the RGB masks.
			if v.Class != xproto.VisualClassTrueColor {
				continue
			}
			if i.Depth == 32 || i.Depth == 30 && prefer30 {
				visual, depth = v.VisualId, i.Depth
				if !prefer30 || i.Depth == 30 {
					break Depths
				}
			}
		}
	}

	format, ok := formats[depth]
	if !ok {
		log.Fatalln("unsupported bit depth")
	}

	mid, err := xproto.NewColormapId(X)
	if err != nil {
		log.Fatalln(err)
	}

	_ = xproto.CreateColormap(
		X, xproto.ColormapAllocNone, mid, screen.Root, visual)

	wid, err := xproto.NewWindowId(X)
	if err != nil {
		log.Fatalln(err)
	}

	// Border pixel and colormap are required when depth differs from parent.
	_ = xproto.CreateWindow(X, depth, wid, screen.Root,
		0, 0, 500, 500, 0, xproto.WindowClassInputOutput,
		visual, xproto.CwBackPixel|xproto.CwBorderPixel|xproto.CwEventMask|
			xproto.CwColormap, []uint32{format.transform(color.Alpha{0x80}), 0,
			xproto.EventMaskStructureNotify | xproto.EventMaskExposure,
			uint32(mid)})

	title := []byte("Image")
	_ = xproto.ChangeProperty(X, xproto.PropModeReplace, wid, xproto.AtomWmName,
		xproto.AtomString, 8, uint32(len(title)), title)

	_ = xproto.MapWindow(X, wid)

	pformats, err := render.QueryPictFormats(X).Reply()
	if err != nil {
		log.Fatalln(err)
	}

	// Similar to XRenderFindVisualFormat.
	// The DefaultScreen is almost certain to be zero.
	var pformat render.Pictformat
	for _, pd := range pformats.Screens[X.DefaultScreen].Depths {
		// This check seems to be slightly extraneous.
		if pd.Depth != depth {
			continue
		}
		for _, pv := range pd.Visuals {
			if pv.Visual == visual {
				pformat = pv.Format
			}
		}
	}

	// Wrap the window's surface in a picture.
	pid, err := render.NewPictureId(X)
	if err != nil {
		log.Fatalln(err)
	}
	render.CreatePicture(X, pid, xproto.Drawable(wid), pformat, 0, []uint32{})

	// setup.BitmapFormatScanline{Pad,Unit} and setup.BitmapFormatBitOrder
	// don't interest us here since we're only using Z format pixmaps.
	for _, pf := range setup.PixmapFormats {
		if pf.Depth == depth {
			if pf.BitsPerPixel != 32 || pf.ScanlinePad != 32 {
				log.Fatalln("unsuported X server")
			}
		}
	}

	pixid, err := xproto.NewPixmapId(X)
	if err != nil {
		log.Fatalln(err)
	}
	_ = xproto.CreatePixmap(X, depth, pixid, xproto.Drawable(screen.Root),
		uint16(img.Bounds().Dx()), uint16(img.Bounds().Dy()))

	var bgraFormat render.Pictformat
	for _, pf := range pformats.Formats {
		if pf.Depth == depth && pf.Direct == format.format {
			bgraFormat = pf.Id
			break
		}
	}
	if bgraFormat == 0 {
		log.Fatalln("picture format not found")
	}

	// We could also look for the inverse pictformat.
	var encoding binary.ByteOrder
	if setup.ImageByteOrder == xproto.ImageOrderMSBFirst {
		encoding = binary.BigEndian
	} else {
		encoding = binary.LittleEndian
	}

	pixpicid, err := render.NewPictureId(X)
	if err != nil {
		log.Fatalln(err)
	}
	render.CreatePicture(X, pixpicid, xproto.Drawable(pixid), bgraFormat,
		0, []uint32{})

	// Do we really need this? :/
	cid, err := xproto.NewGcontextId(X)
	if err != nil {
		log.Fatalln(err)
	}
	_ = xproto.CreateGC(X, cid, xproto.Drawable(pixid),
		xproto.GcGraphicsExposures, []uint32{0})

	bounds := img.Bounds()
	Lstart := time.Now()

	if err := shm.Init(X); err != nil {
		log.Println("MIT-SHM unavailable")

		// We're being lazy and resolve the 1<<16 limit of requests by sending
		// a row at a time. The encoding is also done inefficiently.
		// Also see xgbutil/xgraphics/xsurface.go.
		row := make([]byte, bounds.Dx()*4)
		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
			for x := bounds.Min.X; x < bounds.Max.X; x++ {
				encoding.PutUint32(row[x*4:], format.transform(img.At(x, y)))
			}
			_ = xproto.PutImage(X, xproto.ImageFormatZPixmap,
				xproto.Drawable(pixid), cid, uint16(bounds.Dx()), 1,
				0, int16(y),
				0, depth, row)
		}
	} else {
		rep, err := shm.QueryVersion(X).Reply()
		if err != nil {
			log.Fatalln(err)
		}
		if rep.PixmapFormat != xproto.ImageFormatZPixmap ||
			!rep.SharedPixmaps {
			log.Fatalln("MIT-SHM configuration unfit")
		}

		shmSize := bounds.Dx() * bounds.Dy() * 4

		// As a side note, to clean up unreferenced segments (orphans):
		//  ipcs -m | awk '$6 == "0" { print $2 }' | xargs ipcrm shm
		shmID := int(C.shmget(C.IPC_PRIVATE,
			C.size_t(shmSize), C.IPC_CREAT|0777))
		if shmID == -1 {
			// TODO: We should handle this case by falling back to PutImage,
			// if only because the allocation may hit a system limit.
			log.Fatalln("memory allocation failed")
		}

		dataRaw := C.shmat(C.int(shmID), nil, 0)
		defer C.shmdt(dataRaw)
		defer C.shmctl(C.int(shmID), C.IPC_RMID, nil)

		data := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
			Data: uintptr(dataRaw), Len: shmSize, Cap: shmSize}))
		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
			row := data[y*bounds.Dx()*4:]
			for x := bounds.Min.X; x < bounds.Max.X; x++ {
				encoding.PutUint32(row[x*4:], format.transform(img.At(x, y)))
			}
		}

		segid, err := shm.NewSegId(X)
		if err != nil {
			log.Fatalln(err)
		}

		// Need to have it attached on the server before we unload the segment.
		c := shm.AttachChecked(X, segid, uint32(shmID), true /* RO */)
		if err := c.Check(); err != nil {
			log.Fatalln(err)
		}

		_ = shm.PutImage(X, xproto.Drawable(pixid), cid,
			uint16(bounds.Dx()), uint16(bounds.Dy()), 0, 0,
			uint16(bounds.Dx()), uint16(bounds.Dy()), 0, 0,
			depth, xproto.ImageFormatZPixmap,
			0 /* SendEvent */, segid, 0 /* Offset */)
	}

	log.Println("uploading took", time.Now().Sub(Lstart))

	var scale float64 = 1
	for {
		ev, xerr := X.WaitForEvent()
		if xerr != nil {
			log.Printf("Error: %s\n", xerr)
			return
		}
		if ev == nil {
			return
		}

		log.Printf("Event: %s\n", ev)
		switch e := ev.(type) {
		case xproto.UnmapNotifyEvent:
			return

		case xproto.ConfigureNotifyEvent:
			w, h := e.Width, e.Height

			scaleX := float64(bounds.Dx()) / float64(w)
			scaleY := float64(bounds.Dy()) / float64(h)

			if scaleX < scaleY {
				scale = scaleY
			} else {
				scale = scaleX
			}

			_ = render.SetPictureTransform(X, pixpicid, render.Transform{
				F64ToFixed(scale), F64ToFixed(0), F64ToFixed(0),
				F64ToFixed(0), F64ToFixed(scale), F64ToFixed(0),
				F64ToFixed(0), F64ToFixed(0), F64ToFixed(1),
			})
			_ = render.SetPictureFilter(X, pixpicid, 8, "bilinear", nil)

		case xproto.ExposeEvent:
			_ = render.Composite(X, render.PictOpSrc,
				pixpicid, render.PictureNone, pid,
				0, 0, 0, 0, 0 /* dst-x */, 0, /* dst-y */
				uint16(float64(img.Bounds().Dx())/scale),
				uint16(float64(img.Bounds().Dy())/scale))
		}
	}
}