-
Notifications
You must be signed in to change notification settings - Fork 4
/
connection.go
81 lines (63 loc) · 1.63 KB
/
connection.go
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
package cups
/*
#cgo LDFLAGS: -lcups
#include "cups/cups.h"
*/
import "C"
import (
"unsafe"
)
// Connection is a struct containing information about a CUPS connection
type Connection struct {
isDefault bool
address string
NumDests int
Dests []*Dest
}
// Is there a better way to do this?
// I manually calculated the size in C
//
const cupsDestTSize = 32
const cupsOptionTSize = 16
var enumDestsChan chan *Dest
// Refresh updates the list of destinations and their state
func (c *Connection) Refresh() {
updateDefaultConnection(c)
}
// NewDefaultConnection creates a new default CUPS connection
func NewDefaultConnection() *Connection {
connection := &Connection{
isDefault: true,
}
updateDefaultConnection(connection)
return connection
}
// TODO: check for memory leaks
func updateDefaultConnection(c *Connection) {
var dests *C.cups_dest_t
destCount := C.cupsGetDests(&dests)
goDestCount := int(destCount)
var destsArr []*Dest
destPtr := uintptr(unsafe.Pointer(dests))
for i := 0; i < goDestCount; i++ {
// is this ok?
dest := (*C.cups_dest_t)(unsafe.Pointer(destPtr))
d := &Dest{
Name: C.GoString(dest.name),
}
destOptPtr := uintptr(unsafe.Pointer(dest.options))
options := make(map[string]string)
for j := 0; j < int(dest.num_options)-1; j++ {
opt := (*C.cups_option_t)(unsafe.Pointer(destOptPtr))
options[C.GoString(opt.name)] = C.GoString(opt.value)
destOptPtr += uintptr(cupsOptionTSize)
}
d.options = options
destsArr = append(destsArr, d)
destPtr += uintptr(cupsDestTSize)
}
// free the pointers
C.cupsFreeDests(destCount, dests)
c.NumDests = goDestCount
c.Dests = destsArr
}