~sircmpwn/lpsh

ref: d703e1f195eae895b6852dd7152bc3871237bf80 lpsh/lpsh.go -rw-r--r-- 1.3 KiB View raw
                                                                                
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
package main

import (
	"os"
	"os/exec"
	"time"

	"git.sr.ht/~sircmpwn/pty"
)

// TODO: Talk directly to CUPS/the printer?
func lpr(data []byte) {
	lpr := exec.Command("/usr/bin/lpr", "-l")
	pipe, err := lpr.StdinPipe()
	if err != nil {
		panic(err)
	}
	go func() {
		defer pipe.Close()
		pipe.Write(data)
	}()
	lpr.Run()
}

func lprmgr(out chan ([]byte)) {
	lpr([]byte("\n\n\n\r"))
	feed := false

	for {
		select {
		case data := <-out:
			if feed {
				lpr([]byte("\x1Bj\xD8\x1Bj\xD8\x1Bj\x6C"))
				feed = false
			}
			lpr(data)
		case <-time.After(250 * time.Millisecond):
			if !feed {
				feed = true
				lpr([]byte("\x1BJ\xD8\x1BJ\xD8\x1BJ\x6C"))
			}
		}
	}
}

func main() {
	winsize := pty.Winsize{
		Cols: 160,
		Rows: 24,
	}
	cmd := exec.Command("/bin/sh")
	cmd.Env = append(os.Environ(), "TERM=lp")
	tty, err := pty.StartWithSize(cmd, &winsize)
	if err != nil {
		panic(err)
	}

	exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()

	lprch := make(chan ([]byte))
	go lprmgr(lprch)

	inbuf := make([]byte, 4096)
	go func() {
		for {
			n, err := os.Stdin.Read(inbuf)
			if err != nil {
				panic(err)
			}
			tty.Write(inbuf[:n])
		}
	}()

	outbuf := make([]byte, 4096)
	for {
		n, err := tty.Read(outbuf)
		if err != nil {
			panic(err)
		}
		b := make([]byte, n)
		copy(b, outbuf[:n])
		lprch <- b
	}
}