Compare commits
58 Commits
3080194dc1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
9db00dd64c
|
|||
|
3832ca749f
|
|||
|
f37c194ab8
|
|||
|
269e6514df
|
|||
|
9734cdd16e
|
|||
|
8215b59834
|
|||
|
6fc00ba3dd
|
|||
|
93b29a5346
|
|||
|
696ea89530
|
|||
|
e56482d73f
|
|||
|
2f47b3f5da
|
|||
|
154f3147e3
|
|||
|
5cef6b240a
|
|||
|
81927e9017
|
|||
|
88560a8fbf
|
|||
|
301d035425
|
|||
|
04e66d7888
|
|||
|
7d2ca09d1b
|
|||
|
4ad4bcf9e7
|
|||
|
2d1e01a1a2
|
|||
|
1bd7a9d735
|
|||
|
6c6cec6298
|
|||
|
cbf8678681
|
|||
|
0936963aaf
|
|||
|
e4ae5d0001
|
|||
|
21d01f4c4b
|
|||
|
885d161cf5
|
|||
|
a4a399b812
|
|||
|
2bd4f5921c
|
|||
|
1713bd1f06
|
|||
|
f8bb344aab
|
|||
|
0b32fa576f
|
|||
|
82c6c34ea5
|
|||
|
5b7113905e
|
|||
|
dc0536c011
|
|||
|
37b7edb2ef
|
|||
|
608ba10eec
|
|||
|
8d9b6f75d0
|
|||
|
1331f3b564
|
|||
|
7d9410c6b3
|
|||
|
32ad36a287
|
|||
|
412efcb1ae
|
|||
|
39e2c5b76d
|
|||
|
ea45784554
|
|||
|
4dade55387
|
|||
|
3d98454543
|
|||
|
fbb76679f3
|
|||
|
e003427f9f
|
|||
|
7eb84cd937
|
|||
|
bcfb9fbc2b
|
|||
|
f5790dbff9
|
|||
|
401ed71323
|
|||
|
8c3aaa8261
|
|||
|
3fe6d7d071
|
|||
|
fd347fa1eb
|
|||
|
10380a7901
|
|||
|
b287ba5500
|
|||
|
fab0a52189
|
12
LICENSE
Normal file
12
LICENSE
Normal file
@@ -0,0 +1,12 @@
|
||||
Copyright (c) 2019 - 2021, Přemysl Eric Janouch <p@janouch.name>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
52
README.adoc
Normal file
52
README.adoc
Normal file
@@ -0,0 +1,52 @@
|
||||
sklad
|
||||
=====
|
||||
|
||||
'sklad' is a simple personal warehouse management system or, let's rather say,
|
||||
"stuff management system", employing a web UI for easy mobile access from
|
||||
a smartphone. The templates are currently localised only in the Czech language.
|
||||
|
||||
The project also contains reusable Go packages with a Brother QL-series USB
|
||||
printer driver and a simple BDF bitmap font renderer, as well as a few related
|
||||
utilities for previewing, printing and debugging.
|
||||
|
||||
image::sklad.png[align="center"]
|
||||
|
||||
Building and Running
|
||||
--------------------
|
||||
Build dependencies: Go +
|
||||
Runtime dependencies: Linux, a Brother QL label printer connected over USB
|
||||
|
||||
$ go get -u https://janouch.name/sklad/cmd/sklad
|
||||
|
||||
You will need to bootstrap the database by writing a minimal 'db.json':
|
||||
|
||||
....
|
||||
{
|
||||
"Password": "login-password",
|
||||
"Prefix": "A",
|
||||
"BDPPath": "font.bdf",
|
||||
"BDFScale": 3
|
||||
}
|
||||
....
|
||||
|
||||
Decent Unicode fonts in the BDF format can be obtained from
|
||||
https://www.cl.cam.ac.uk/~mgk25/ucs-fonts.html
|
||||
though they will need some upscaling because of the printer's high DPI.
|
||||
|
||||
After placing the templates and the BDF font file in the current working
|
||||
directory, run the application as follows:
|
||||
|
||||
$ sklad :8000 db.json
|
||||
|
||||
Contributing and Support
|
||||
------------------------
|
||||
Use https://git.janouch.name/p/sklad to report any bugs, request features,
|
||||
or submit pull requests. `git send-email` is tolerated. If you want to discuss
|
||||
the project, feel free to join me at ircs://irc.janouch.name, channel #dev.
|
||||
|
||||
Bitcoin donations are accepted at: 12r5uEWEgcHC46xd64tt3hHt9EUvYYDHe9
|
||||
|
||||
License
|
||||
-------
|
||||
This software is released under the terms of the 0BSD license, the text of which
|
||||
is included within the package along with the list of authors.
|
||||
34
bdf/bdf.go
34
bdf/bdf.go
@@ -49,6 +49,8 @@ func (g *glyph) At(x, y int) color.Color {
|
||||
// Font represents a particular bitmap font.
|
||||
type Font struct {
|
||||
Name string
|
||||
Ascent int // needn't be present in the font
|
||||
Descent int // needn't be present in the font
|
||||
glyphs map[rune]glyph
|
||||
fallback glyph
|
||||
}
|
||||
@@ -64,11 +66,13 @@ func (f *Font) FindGlyph(r rune) (glyph, bool) {
|
||||
|
||||
// DrawString draws the specified text string onto dst horizontally along
|
||||
// the baseline starting at dp, using black color.
|
||||
func (f *Font) DrawString(dst draw.Image, dp image.Point, s string) {
|
||||
func (f *Font) DrawString(dst draw.Image, dp image.Point,
|
||||
color color.Color, s string) {
|
||||
src := image.NewUniform(color)
|
||||
for _, r := range s {
|
||||
g, _ := f.FindGlyph(r)
|
||||
draw.DrawMask(dst, g.bounds.Add(dp),
|
||||
image.Black, image.ZP, &g, g.bounds.Min, draw.Over)
|
||||
src, image.ZP, &g, g.bounds.Min, draw.Over)
|
||||
dp.X += g.advance
|
||||
}
|
||||
}
|
||||
@@ -192,17 +196,23 @@ func (p *bdfParser) readLine() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *bdfParser) readCharEncoding() int {
|
||||
func (p *bdfParser) readIntegerArgument() int {
|
||||
if len(p.tokens) < 2 {
|
||||
panic("insufficient arguments")
|
||||
}
|
||||
if i, err := strconv.Atoi(p.tokens[1]); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
return i // Some fonts even use -1 for things outside the encoding.
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
// Some fonts even use -1 for things outside the encoding.
|
||||
func (p *bdfParser) readCharEncoding() int { return p.readIntegerArgument() }
|
||||
|
||||
// XXX: Ignoring vertical advance since we only expect purely horizontal fonts.
|
||||
func (p *bdfParser) readDwidth() int { return p.readIntegerArgument() }
|
||||
|
||||
func (p *bdfParser) parseProperties() {
|
||||
// The wording in the specification suggests that the argument
|
||||
// with the number of properties to follow isn't reliable.
|
||||
@@ -210,22 +220,14 @@ func (p *bdfParser) parseProperties() {
|
||||
switch p.tokens[0] {
|
||||
case "DEFAULT_CHAR":
|
||||
p.defaultChar = p.readCharEncoding()
|
||||
case "FONT_ASCENT":
|
||||
p.font.Ascent = p.readIntegerArgument()
|
||||
case "FONT_DESCENT":
|
||||
p.font.Descent = p.readIntegerArgument()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// XXX: Ignoring vertical advance since we only expect purely horizontal fonts.
|
||||
func (p *bdfParser) readDwidth() int {
|
||||
if len(p.tokens) < 2 {
|
||||
panic("insufficient arguments")
|
||||
}
|
||||
if i, err := strconv.Atoi(p.tokens[1]); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
func (p *bdfParser) readBBX() image.Rectangle {
|
||||
if len(p.tokens) < 5 {
|
||||
panic("insufficient arguments")
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"html/template"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"log"
|
||||
@@ -20,21 +21,21 @@ type fontItem struct {
|
||||
var fonts = map[string]fontItem{}
|
||||
|
||||
var tmpl = template.Must(template.New("list").Parse(`
|
||||
<!DOCTYPE html>
|
||||
<html><body>
|
||||
<table border='1' cellpadding='3' style='border-collapse: collapse'>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Preview</th>
|
||||
<tr>
|
||||
{{range $k, $v := . }}
|
||||
<tr>
|
||||
<td>{{$k}}</td>
|
||||
<td><img src='?name={{$k}}'></td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</table>
|
||||
</body></html>
|
||||
<!DOCTYPE html>
|
||||
<html><body>
|
||||
<table border='1' cellpadding='3' style='border-collapse: collapse'>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Preview</th>
|
||||
<tr>
|
||||
{{- range $k, $v := . }}
|
||||
<tr>
|
||||
<td>{{ $k }}</td>
|
||||
<td><img src='?name={{ $k }}'></td>
|
||||
</tr>
|
||||
{{- end }}
|
||||
</table>
|
||||
</body></html>
|
||||
`))
|
||||
|
||||
func handle(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -82,12 +83,12 @@ func main() {
|
||||
|
||||
img := image.NewRGBA(super)
|
||||
draw.Draw(img, super, image.White, image.ZP, draw.Src)
|
||||
font.DrawString(img, image.ZP, font.Name)
|
||||
font.DrawString(img, image.ZP, color.Black, font.Name)
|
||||
|
||||
fonts[filename] = fontItem{Font: font, Preview: img}
|
||||
}
|
||||
|
||||
log.Println("Starting server")
|
||||
log.Println("starting server")
|
||||
http.HandleFunc("/", handle)
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
@@ -2,11 +2,13 @@ package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"janouch.name/sklad/bdf"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"janouch.name/sklad/bdf"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -25,7 +27,7 @@ func main() {
|
||||
|
||||
img := image.NewRGBA(super)
|
||||
draw.Draw(img, super, image.White, image.ZP, draw.Src)
|
||||
font.DrawString(img, image.ZP, font.Name)
|
||||
font.DrawString(img, image.ZP, color.Black, font.Name)
|
||||
|
||||
fo, err := os.Create("out.png")
|
||||
if err != nil {
|
||||
272
cmd/label-tool/main.go
Normal file
272
cmd/label-tool/main.go
Normal file
@@ -0,0 +1,272 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"html/template"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"janouch.name/sklad/bdf"
|
||||
"janouch.name/sklad/imgutil"
|
||||
"janouch.name/sklad/label"
|
||||
"janouch.name/sklad/ql"
|
||||
)
|
||||
|
||||
var tmplFont = template.Must(template.New("font").Parse(`
|
||||
<!DOCTYPE html>
|
||||
<html><body>
|
||||
<h1>PT-CBP label printing tool</h1>
|
||||
<h2>Choose font</h2>
|
||||
{{ range $i, $f := . }}
|
||||
<p><a href='?font={{ $i }}'>
|
||||
<img src='?font={{ $i }}&preview' title='{{ $f.Path }}'></a>
|
||||
{{ end }}
|
||||
</body></html>
|
||||
`))
|
||||
|
||||
var tmplForm = template.Must(template.New("form").Parse(`
|
||||
<!DOCTYPE html>
|
||||
<html><body>
|
||||
<h1>PT-CBP label printing tool</h1>
|
||||
<table><tr>
|
||||
<td valign=top>
|
||||
<img border=1 src='?font={{ .FontIndex }}&scale={{ .Scale }}{{/*
|
||||
*/}}&text={{ .Text }}&render'>
|
||||
</td>
|
||||
<td valign=top><form>
|
||||
<fieldset>
|
||||
{{ if .Printer }}
|
||||
|
||||
<p>Printer: {{ .Printer.Manufacturer }} {{ .Printer.Model }}
|
||||
<p>Tape:
|
||||
{{ if .Printer.LastStatus }}
|
||||
{{ .Printer.LastStatus.MediaWidthMM }} mm ×
|
||||
{{ .Printer.LastStatus.MediaLengthMM }} mm
|
||||
|
||||
{{ if .MediaInfo }}
|
||||
(offset: {{ .MediaInfo.SideMarginPins }} pt,
|
||||
print area: {{ .MediaInfo.PrintAreaPins }} pt)
|
||||
{{ else }}
|
||||
(unknown media)
|
||||
{{ end }}
|
||||
|
||||
{{ if .Printer.LastStatus.Errors }}
|
||||
{{ range .Printer.LastStatus.Errors }}
|
||||
<p>Error: {{ . }}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ if .InitErr }}
|
||||
{{ .InitErr }}
|
||||
{{ end }}
|
||||
|
||||
{{ else }}
|
||||
<p>Error: {{ .PrinterErr }}
|
||||
{{ end }}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Font</legend>
|
||||
<p>{{ .Font.Name }} <a href='?'>Change</a>
|
||||
<input type=hidden name=font value='{{ .FontIndex }}'>
|
||||
<p><label for=scale>Scale:</label>
|
||||
<input id=scale name=scale value='{{.Scale}}' size=1>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Label</legend>
|
||||
<p><textarea name=text>{{.Text}}</textarea>
|
||||
<p>Kind:
|
||||
<input type=radio id=kind-text name=kind value=text
|
||||
{{ if eq .Kind "text" }} checked{{ end }}>
|
||||
<label for=kind-text>plain text (horizontal)</label>
|
||||
<input type=radio id=kind-qr name=kind value=qr
|
||||
{{ if eq .Kind "qr" }} checked{{ end }}>
|
||||
<label for=kind-qr>QR code (vertical)</label>
|
||||
<p><input type=submit value='Update'>
|
||||
<input type=submit name=print value='Update and Print'>
|
||||
</fieldset>
|
||||
</form></td>
|
||||
</tr></table>
|
||||
</body></html>
|
||||
`))
|
||||
|
||||
type fontItem struct {
|
||||
Path string
|
||||
Font *bdf.Font
|
||||
Preview image.Image
|
||||
}
|
||||
|
||||
var fonts = []*fontItem{}
|
||||
|
||||
func getPrinter() (*ql.Printer, error) {
|
||||
printer, err := ql.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if printer == nil {
|
||||
return nil, errors.New("no suitable printer found")
|
||||
}
|
||||
return printer, nil
|
||||
}
|
||||
|
||||
func getStatus(printer *ql.Printer) error {
|
||||
if err := printer.Initialize(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := printer.UpdateStatus(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handle(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
|
||||
var (
|
||||
font *fontItem
|
||||
fontIndex int
|
||||
err error
|
||||
)
|
||||
if fontIndex, err = strconv.Atoi(r.FormValue("font")); err == nil {
|
||||
font = fonts[fontIndex]
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := tmplFont.Execute(w, fonts); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := r.Form["preview"]; ok {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
if err := png.Encode(w, font.Preview); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
initErr error
|
||||
mediaInfo *ql.MediaInfo
|
||||
)
|
||||
printer, printerErr := getPrinter()
|
||||
if printerErr == nil {
|
||||
defer printer.Close()
|
||||
printer.StatusNotify = func(status *ql.Status) {
|
||||
log.Printf("\x1b[1mreceived status\x1b[m\n%s", status)
|
||||
}
|
||||
|
||||
if initErr = getStatus(printer); initErr == nil {
|
||||
mediaInfo = ql.GetMediaInfo(
|
||||
printer.LastStatus.MediaWidthMM(),
|
||||
printer.LastStatus.MediaLengthMM(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var params = struct {
|
||||
Printer *ql.Printer
|
||||
PrinterErr error
|
||||
InitErr error
|
||||
MediaInfo *ql.MediaInfo
|
||||
Font *bdf.Font
|
||||
FontIndex int
|
||||
Text string
|
||||
Scale int
|
||||
Kind string
|
||||
}{
|
||||
Printer: printer,
|
||||
PrinterErr: printerErr,
|
||||
InitErr: initErr,
|
||||
MediaInfo: mediaInfo,
|
||||
Font: font.Font,
|
||||
FontIndex: fontIndex,
|
||||
Text: r.FormValue("text"),
|
||||
Kind: r.FormValue("kind"),
|
||||
}
|
||||
|
||||
params.Scale, err = strconv.Atoi(r.FormValue("scale"))
|
||||
if err != nil {
|
||||
params.Scale = 3
|
||||
}
|
||||
if params.Kind == "" {
|
||||
params.Kind = "text"
|
||||
}
|
||||
|
||||
var img image.Image
|
||||
if mediaInfo != nil {
|
||||
if params.Kind == "qr" {
|
||||
img = &imgutil.LeftRotate{Image: label.GenLabelForHeight(
|
||||
font.Font, params.Text, mediaInfo.PrintAreaPins, params.Scale)}
|
||||
} else {
|
||||
img = label.GenLabelForWidth(
|
||||
font.Font, params.Text, mediaInfo.PrintAreaPins, params.Scale)
|
||||
}
|
||||
if r.FormValue("print") != "" {
|
||||
if err := printer.Print(img, false); err != nil {
|
||||
log.Println("print error:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := r.Form["render"]; !ok {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := tmplForm.Execute(w, ¶ms); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if mediaInfo == nil {
|
||||
http.Error(w, "unknown media", 500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
if err := png.Encode(w, img); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 3 {
|
||||
log.Fatalf("usage: %s ADDRESS BDF-FILE...\n", os.Args[0])
|
||||
}
|
||||
|
||||
address, bdfPaths := os.Args[1], os.Args[2:]
|
||||
for _, path := range bdfPaths {
|
||||
fi, err := os.Open(path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
font, err := bdf.NewFromBDF(fi)
|
||||
if err != nil {
|
||||
log.Fatalf("%s: %s\n", path, err)
|
||||
}
|
||||
if err := fi.Close(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
r, _ := font.BoundString(font.Name)
|
||||
super := r.Inset(-3)
|
||||
|
||||
img := image.NewRGBA(super)
|
||||
draw.Draw(img, super, image.White, image.ZP, draw.Src)
|
||||
font.DrawString(img, image.ZP, color.Black, font.Name)
|
||||
|
||||
fonts = append(fonts, &fontItem{Path: path, Font: font, Preview: img})
|
||||
}
|
||||
|
||||
log.Println("starting server")
|
||||
http.HandleFunc("/", handle)
|
||||
log.Fatalln(http.ListenAndServe(address, nil))
|
||||
}
|
||||
89
cmd/ql-print/main.go
Normal file
89
cmd/ql-print/main.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"janouch.name/sklad/imgutil"
|
||||
"janouch.name/sklad/ql"
|
||||
)
|
||||
|
||||
var scale = flag.Int("scale", 1, "integer upscaling")
|
||||
var rotate = flag.Bool("rotate", false, "print sideways")
|
||||
var redblack = flag.Bool("redblack", false, "red and black print")
|
||||
|
||||
func main() {
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s IMAGE\n", os.Args[0])
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
flag.Parse()
|
||||
if flag.NArg() != 1 {
|
||||
flag.Usage()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Open the picture.
|
||||
f, err := os.Open(flag.Arg(0))
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Load and eventually transform the picture.
|
||||
img, _, err := image.Decode(f)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if *scale > 1 {
|
||||
img = &imgutil.Scale{Image: img, Scale: *scale}
|
||||
}
|
||||
if *rotate {
|
||||
img = &imgutil.LeftRotate{Image: img}
|
||||
}
|
||||
|
||||
// Open and initialize the printer.
|
||||
p, err := ql.Open()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if p == nil {
|
||||
log.Fatalln("no suitable printer found")
|
||||
}
|
||||
if err := p.Initialize(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := p.UpdateStatus(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
// Check the picture against the media in the printer.
|
||||
mi := ql.GetMediaInfo(
|
||||
p.LastStatus.MediaWidthMM(),
|
||||
p.LastStatus.MediaLengthMM(),
|
||||
)
|
||||
if mi == nil {
|
||||
log.Fatalln("unknown media")
|
||||
}
|
||||
|
||||
bounds := img.Bounds()
|
||||
dx, dy := bounds.Dx(), bounds.Dy()
|
||||
if dx > mi.PrintAreaPins {
|
||||
log.Fatalln("the image is too wide,", dx, ">", mi.PrintAreaPins, "pt")
|
||||
}
|
||||
if dy > mi.PrintAreaLength && mi.PrintAreaLength != 0 {
|
||||
log.Fatalln("the image is too high,", dy, ">", mi.PrintAreaLength, "pt")
|
||||
}
|
||||
|
||||
if err := p.Print(img, *redblack); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
68
cmd/sklad/base.tmpl
Normal file
68
cmd/sklad/base.tmpl
Normal file
@@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ template "Title" . }} - sklad</title>
|
||||
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
|
||||
<meta name=viewport content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
html, body { min-height: 100vh; }
|
||||
body { padding: 1rem; box-sizing: border-box;
|
||||
margin: 0 auto; max-width: 50rem;
|
||||
border-left: 1px solid #ccc; border-right: 1px solid #ccc;
|
||||
font-family: sans-serif; }
|
||||
|
||||
section { border: 1px outset #ccc; padding: 0 .5rem; margin: 1rem 0; }
|
||||
section > p { margin: 0 0 .5rem 0; }
|
||||
|
||||
header, footer { display: flex; justify-content: space-between;
|
||||
align-items: center; flex-wrap: wrap; padding-top: .5em; }
|
||||
header { margin: 0 -.5rem; padding: .5rem .5rem 0 .5rem;
|
||||
background: linear-gradient(0deg, transparent, #f8f8f8); }
|
||||
body > header { margin: -1rem -1rem 0 -1rem; padding: 1rem 1rem 0 1rem;
|
||||
background: linear-gradient(0deg, transparent, #eeeeee); }
|
||||
|
||||
header *,
|
||||
footer * { display: inline-block; }
|
||||
header > *,
|
||||
footer > * { margin: 0 0 .5rem 0; }
|
||||
header > *:not(:last-child),
|
||||
footer > *:not(:last-child) { margin-right: .5rem; }
|
||||
|
||||
header > h2,
|
||||
header > h3 { flex-grow: 1; }
|
||||
|
||||
/* Don't ask me why this is an improvement on mobile browsers. */
|
||||
input[type=submit], input[type=text], input[type=password],
|
||||
select, textarea { border: 1px inset #ccc; padding: .25rem; }
|
||||
input[type=submit] { border-style: outset; }
|
||||
select { border-style: solid; }
|
||||
|
||||
a { color: inherit; }
|
||||
textarea { padding: .5rem; box-sizing: border-box; width: 100%;
|
||||
font-family: inherit; resize: vertical; }
|
||||
select { max-width: 15rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header>
|
||||
<h1>sklad</h1>
|
||||
|
||||
{{ block "HeaderControls" . }}
|
||||
<a href="container">Obaly</a>
|
||||
<a href="series">Řady</a>
|
||||
|
||||
<form method=get action="search">
|
||||
<input type=text name=q autofocus><input type=submit value="Hledat">
|
||||
</form>
|
||||
|
||||
<form method=post action="logout">
|
||||
<input type=submit value="Odhlásit">
|
||||
</form>
|
||||
{{ end }}
|
||||
|
||||
</header>
|
||||
|
||||
{{ template "Content" . }}
|
||||
</body>
|
||||
</html>
|
||||
140
cmd/sklad/container.tmpl
Normal file
140
cmd/sklad/container.tmpl
Normal file
@@ -0,0 +1,140 @@
|
||||
{{ define "Title" }}{{/*
|
||||
*/}}{{ if .Container }}{{ .Container.Id }}{{ else }}Obaly{{ end }}{{ end }}
|
||||
{{ define "Content" }}
|
||||
|
||||
{{ if .ErrorNoSuchSeries }}
|
||||
<p>Chyba: Řada neexistuje.
|
||||
{{ else if .ErrorContainerAlreadyExists }}
|
||||
<p>Chyba: Obal s tímto ID už existuje.
|
||||
{{ else if .ErrorNoSuchContainer }}
|
||||
<p>Chyba: Obal neexistuje.
|
||||
{{ else if .ErrorCannotChangeSeriesNotEmpty }}
|
||||
<p>Chyba: Řadu u neprázdných obalů nelze měnit.
|
||||
{{ else if .ErrorCannotChangeNumber }}
|
||||
<p>Chyba: Číslo obalu v řadě nelze měnit.
|
||||
{{ else if .ErrorWouldContainItself }}
|
||||
<p>Chyba: Obal by obsahoval sám sebe.
|
||||
{{ else if .ErrorContainerInUse }}
|
||||
<p>Chyba: Obal se používá.
|
||||
{{ else if .Error }}
|
||||
<p>Chyba: {{ .Error }}
|
||||
{{ end }}
|
||||
|
||||
{{ if .Container }}
|
||||
<section>
|
||||
<header>
|
||||
<h2><a href="container?id={{ .Container.Id }}">{{ .Container.Id }}</a>
|
||||
{{- range .Container.Path }}
|
||||
<small>« <a href="container?id={{ . }}">{{ . }}</a></small>
|
||||
{{- end }}
|
||||
</h2>
|
||||
<form method=post action="label?id={{ .Container.Id }}" target=_blank>
|
||||
<input type=submit value="Vytisknout štítek">
|
||||
</form>
|
||||
<form method=post action="container?id={{ .Container.Id }}&remove">
|
||||
<input type=submit value="Odstranit">
|
||||
</form>
|
||||
</header>
|
||||
<form method=post action="container?id={{ .Container.Id }}">
|
||||
{{- $description := or .NewDescription .Container.Description }}
|
||||
<textarea name=description rows="{{ max 5 (lines $description) }}"
|
||||
placeholder="Popis obalu nebo jeho obsahu">
|
||||
{{- $description -}}
|
||||
</textarea>
|
||||
<footer>
|
||||
<div>
|
||||
<label for=series>Řada:</label>
|
||||
<select name=series id=series>
|
||||
{{- $preselect := or .NewSeries .Container.Series }}
|
||||
{{- range $prefix, $desc := .AllSeries }}
|
||||
<option value="{{ $prefix }}"
|
||||
{{ if eq $prefix $preselect }}selected{{ end -}}
|
||||
>{{ $prefix }} — {{ $desc }}</option>
|
||||
{{- end }}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for=parent>Nadobal:</label>
|
||||
<input type=text name=parent id=parent
|
||||
value="{{ or .NewParent .Container.Parent }}">
|
||||
</div>
|
||||
<input type=submit value="Uložit">
|
||||
</footer>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<h2>Podobaly</h3>
|
||||
{{ else }}
|
||||
<section>
|
||||
<header>
|
||||
<h2>Nový obal</h2>
|
||||
</header>
|
||||
<form method=post action="container">
|
||||
{{- $description := or .NewDescription "" }}
|
||||
<textarea name=description rows="{{ max 5 (lines $description) }}"
|
||||
placeholder="Popis obalu nebo jeho obsahu">
|
||||
{{- $description -}}
|
||||
</textarea>
|
||||
<footer>
|
||||
<div>
|
||||
<label for=series>Řada:</label>
|
||||
<select name=series id=series>
|
||||
{{- $preselect := or .NewSeries "" }}
|
||||
{{- range $prefix, $desc := .AllSeries }}
|
||||
<option value="{{ $prefix }}"
|
||||
{{ if eq $prefix $preselect }}selected{{ end -}}
|
||||
>{{ $prefix }} — {{ $desc }}</option>
|
||||
{{- end }}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for=parent>Nadobal:</label>
|
||||
<input type=text name=parent id=parent
|
||||
value="{{ or .NewParent "" }}">
|
||||
</div>
|
||||
<input type=submit value="Uložit">
|
||||
</footer>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<h2>Obaly nejvyšší úrovně</h2>
|
||||
{{ end }}
|
||||
|
||||
{{ range .Children }}
|
||||
<section>
|
||||
<header>
|
||||
<h3><a href="container?id={{ .Id }}">{{ .Id }}</a>
|
||||
{{- range .Path }}
|
||||
<small>« <a href="container?id={{ . }}">{{ . }}</a></small>
|
||||
{{- end }}
|
||||
</h3>
|
||||
<form method=post action="label?id={{ .Id }}" target=_blank>
|
||||
{{- if $.Container }}
|
||||
<input type=hidden name=context value="{{ $.Container.Id }}">
|
||||
{{- end }}
|
||||
<input type=submit value="Vytisknout štítek">
|
||||
</form>
|
||||
<form method=post action="container?id={{ .Id }}&remove">
|
||||
{{- if $.Container }}
|
||||
<input type=hidden name=context value="{{ $.Container.Id }}">
|
||||
{{- end }}
|
||||
<input type=submit value="Odstranit">
|
||||
</form>
|
||||
</header>
|
||||
|
||||
{{- if .Description }}
|
||||
<p>{{ .Description }}
|
||||
{{- end }}
|
||||
|
||||
{{- if .Children }}
|
||||
<p>
|
||||
{{- range .Children }}
|
||||
<a href="container?id={{ .Id }}">{{ .Id }}</a>
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
</section>
|
||||
{{ else }}
|
||||
<p>Obal je prázdný.
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
374
cmd/sklad/db.go
Normal file
374
cmd/sklad/db.go
Normal file
@@ -0,0 +1,374 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"janouch.name/sklad/bdf"
|
||||
)
|
||||
|
||||
type Series struct {
|
||||
Prefix string // PK: prefix
|
||||
Description string // what kind of containers this is for
|
||||
Counter uint // last used container number
|
||||
}
|
||||
|
||||
func (s *Series) Containers() []*Container {
|
||||
return indexMembers[s.Prefix]
|
||||
}
|
||||
|
||||
type ContainerId string
|
||||
|
||||
type Container struct {
|
||||
Series string // PK: what series does this belong to
|
||||
Number uint // PK: order within the series
|
||||
Parent ContainerId // the container we're in, if any, otherwise ""
|
||||
Description string // description and/or contents of this container
|
||||
}
|
||||
|
||||
func (c *Container) Id() ContainerId {
|
||||
return ContainerId(fmt.Sprintf("%s%s%d", db.Prefix, c.Series, c.Number))
|
||||
}
|
||||
|
||||
func (c *Container) Children() []*Container {
|
||||
// TODO: Sort this by Id, or maybe even return a map[string]*Container,
|
||||
// text/template would sort that automatically.
|
||||
return indexChildren[c.Id()]
|
||||
}
|
||||
|
||||
func (c *Container) Path() (result []ContainerId) {
|
||||
for c != nil && c.Parent != "" {
|
||||
c = indexContainer[c.Parent]
|
||||
result = append(result, c.Id())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Password string // password for web users
|
||||
Prefix string // prefix for all container IDs
|
||||
Series []*Series // all known series
|
||||
Containers []*Container // all known containers
|
||||
|
||||
BDFPath string // path to bitmap font file
|
||||
BDFScale int // integer scaling for the bitmap font
|
||||
}
|
||||
|
||||
var (
|
||||
dbPath string
|
||||
db Database
|
||||
dbLast Database
|
||||
dbLog *os.File
|
||||
|
||||
indexSeries = map[string]*Series{}
|
||||
indexMembers = map[string][]*Container{}
|
||||
indexContainer = map[ContainerId]*Container{}
|
||||
indexChildren = map[ContainerId][]*Container{}
|
||||
|
||||
labelFont *bdf.Font
|
||||
)
|
||||
|
||||
func dbSearchSeries(query string) (result []*Series) {
|
||||
query = strings.ToLower(query)
|
||||
added := map[string]bool{}
|
||||
for _, s := range db.Series {
|
||||
if query == strings.ToLower(s.Prefix) {
|
||||
result = append(result, s)
|
||||
added[s.Prefix] = true
|
||||
}
|
||||
}
|
||||
for _, s := range db.Series {
|
||||
if strings.Contains(
|
||||
strings.ToLower(s.Description), query) && !added[s.Prefix] {
|
||||
result = append(result, s)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func dbSearchContainers(query string) (result []*Container) {
|
||||
query = strings.ToLower(query)
|
||||
added := map[ContainerId]bool{}
|
||||
for id, c := range indexContainer {
|
||||
if query == strings.ToLower(string(id)) {
|
||||
result = append(result, c)
|
||||
added[id] = true
|
||||
}
|
||||
}
|
||||
for id, c := range indexContainer {
|
||||
if strings.Contains(
|
||||
strings.ToLower(c.Description), query) && !added[id] {
|
||||
result = append(result, c)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var errInvalidPrefix = errors.New("invalid prefix")
|
||||
var errSeriesAlreadyExists = errors.New("series already exists")
|
||||
var errCannotChangePrefix = errors.New("cannot change the prefix")
|
||||
var errNoSuchSeries = errors.New("no such series")
|
||||
var errSeriesInUse = errors.New("series is in use")
|
||||
|
||||
// Find and filter out the series in O(n).
|
||||
func filterSeries(slice []*Series, s *Series) (filtered []*Series) {
|
||||
for _, series := range slice {
|
||||
if s != series {
|
||||
filtered = append(filtered, series)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func dbSeriesCreate(s *Series) error {
|
||||
if s.Prefix == "" {
|
||||
return errInvalidPrefix
|
||||
}
|
||||
if _, ok := indexSeries[s.Prefix]; ok {
|
||||
return errSeriesAlreadyExists
|
||||
}
|
||||
db.Series = append(db.Series, s)
|
||||
indexSeries[s.Prefix] = s
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
func dbSeriesUpdate(s *Series, updated Series) error {
|
||||
// It might be easily possible with no members, though this
|
||||
// is not reachable from the UI and can be solved by deletion.
|
||||
if updated.Prefix != s.Prefix {
|
||||
return errCannotChangePrefix
|
||||
}
|
||||
*s = updated
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
func dbSeriesRemove(s *Series) error {
|
||||
if len(s.Containers()) > 0 {
|
||||
return errSeriesInUse
|
||||
}
|
||||
|
||||
db.Series = filterSeries(db.Series, s)
|
||||
|
||||
delete(indexSeries, s.Prefix)
|
||||
delete(indexMembers, s.Prefix)
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
var errContainerAlreadyExists = errors.New("container already exists")
|
||||
var errNoSuchContainer = errors.New("no such container")
|
||||
var errCannotChangeSeriesNotEmpty = errors.New(
|
||||
"cannot change the series of a non-empty container")
|
||||
var errCannotChangeNumber = errors.New("cannot change the number")
|
||||
var errWouldContainItself = errors.New("container would contain itself")
|
||||
var errContainerInUse = errors.New("container is in use")
|
||||
|
||||
// Find and filter out the container in O(n).
|
||||
func filterContainer(slice []*Container, c *Container) (filtered []*Container) {
|
||||
for _, container := range slice {
|
||||
if c != container {
|
||||
filtered = append(filtered, container)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func dbContainerCreate(c *Container) error {
|
||||
if series, ok := indexSeries[c.Series]; !ok {
|
||||
return errNoSuchSeries
|
||||
} else if c.Number == 0 {
|
||||
c.Number = series.Counter
|
||||
for {
|
||||
c.Number++
|
||||
if _, ok := indexContainer[c.Id()]; !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
series.Counter = c.Number
|
||||
}
|
||||
if _, ok := indexContainer[c.Id()]; ok {
|
||||
return errContainerAlreadyExists
|
||||
}
|
||||
if c.Parent != "" && indexContainer[c.Parent] == nil {
|
||||
return errNoSuchContainer
|
||||
}
|
||||
|
||||
db.Containers = append(db.Containers, c)
|
||||
|
||||
indexMembers[c.Series] = append(indexMembers[c.Series], c)
|
||||
indexChildren[c.Parent] = append(indexChildren[c.Parent], c)
|
||||
indexContainer[c.Id()] = c
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
func dbContainerUpdate(c *Container, updated Container) error {
|
||||
if _, ok := indexSeries[updated.Series]; !ok {
|
||||
return errNoSuchSeries
|
||||
}
|
||||
if updated.Parent != "" && indexContainer[updated.Parent] == nil {
|
||||
return errNoSuchContainer
|
||||
}
|
||||
|
||||
newID := updated.Id()
|
||||
if updated.Series != c.Series && len(c.Children()) > 0 {
|
||||
return errCannotChangeSeriesNotEmpty
|
||||
}
|
||||
if updated.Number != c.Number {
|
||||
return errCannotChangeNumber
|
||||
}
|
||||
if _, ok := indexContainer[newID]; ok && newID != c.Id() {
|
||||
return errContainerAlreadyExists
|
||||
}
|
||||
if updated.Parent != c.Parent {
|
||||
// Relying on the invariant that we can't change the ID
|
||||
// of a non-empty container.
|
||||
for pv := &updated; pv.Parent != ""; pv = indexContainer[pv.Parent] {
|
||||
if pv.Parent == updated.Id() {
|
||||
return errWouldContainItself
|
||||
}
|
||||
}
|
||||
|
||||
indexChildren[c.Parent] = filterContainer(indexChildren[c.Parent], c)
|
||||
indexChildren[updated.Parent] = append(indexChildren[updated.Parent], c)
|
||||
}
|
||||
*c = updated
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
func dbContainerRemove(c *Container) error {
|
||||
if len(indexChildren[c.Id()]) > 0 {
|
||||
return errContainerInUse
|
||||
}
|
||||
|
||||
db.Containers = filterContainer(db.Containers, c)
|
||||
indexMembers[c.Series] = filterContainer(indexMembers[c.Series], c)
|
||||
indexChildren[c.Parent] = filterContainer(indexChildren[c.Parent], c)
|
||||
|
||||
delete(indexContainer, c.Id())
|
||||
delete(indexChildren, c.Id())
|
||||
return dbCommit()
|
||||
}
|
||||
|
||||
func dbCommit() error {
|
||||
// Write a timestamp.
|
||||
e := json.NewEncoder(dbLog)
|
||||
e.SetIndent("", " ")
|
||||
if err := e.Encode(time.Now().Format(time.RFC3339)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Back up the current database contents.
|
||||
if err := e.Encode(&dbLast); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dbLog.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Atomically replace the current database file.
|
||||
tempPath := dbPath + ".new"
|
||||
temp, err := os.OpenFile(tempPath, os.O_WRONLY|os.O_CREATE, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer temp.Close()
|
||||
|
||||
e = json.NewEncoder(temp)
|
||||
e.SetIndent("", " ")
|
||||
if err := e.Encode(&db); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Rename(tempPath, dbPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dbLast = db
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadDatabase loads the database from a simple JSON file. We do not use
|
||||
// any SQL stuff or even external KV storage because there is no real need
|
||||
// for our trivial use case, with our general amount of data.
|
||||
func loadDatabase() error {
|
||||
dbFile, err := os.Open(dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dbFile.Close()
|
||||
if err := json.NewDecoder(dbFile).Decode(&db); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Further validate the database.
|
||||
if db.Prefix == "" {
|
||||
return errors.New("misconfigured prefix")
|
||||
}
|
||||
|
||||
// Construct indexes for primary keys, validate against duplicates.
|
||||
for _, pv := range db.Series {
|
||||
if _, ok := indexSeries[pv.Prefix]; ok {
|
||||
return fmt.Errorf("duplicate series: %s", pv.Prefix)
|
||||
}
|
||||
indexSeries[pv.Prefix] = pv
|
||||
}
|
||||
for _, pv := range db.Containers {
|
||||
id := pv.Id()
|
||||
if _, ok := indexContainer[id]; ok {
|
||||
return fmt.Errorf("duplicate container: %s", id)
|
||||
}
|
||||
indexContainer[id] = pv
|
||||
}
|
||||
|
||||
// Construct an index that goes from parent containers to their children.
|
||||
for _, pv := range db.Containers {
|
||||
if pv.Parent != "" {
|
||||
if _, ok := indexContainer[pv.Parent]; !ok {
|
||||
return fmt.Errorf("container %s has a nonexistent parent %s",
|
||||
pv.Id(), pv.Parent)
|
||||
}
|
||||
}
|
||||
indexChildren[pv.Parent] = append(indexChildren[pv.Parent], pv)
|
||||
indexMembers[pv.Series] = append(indexMembers[pv.Series], pv)
|
||||
}
|
||||
|
||||
// Validate that no container is a parent of itself on any level.
|
||||
// This could probably be optimized but it would stop being obvious.
|
||||
for _, pv := range db.Containers {
|
||||
parents := map[ContainerId]bool{pv.Id(): true}
|
||||
for pv.Parent != "" {
|
||||
if parents[pv.Parent] {
|
||||
return fmt.Errorf("%s contains itself", pv.Parent)
|
||||
}
|
||||
parents[pv.Parent] = true
|
||||
pv = indexContainer[pv.Parent]
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare label printing.
|
||||
if db.BDFScale <= 0 {
|
||||
db.BDFScale = 1
|
||||
}
|
||||
|
||||
if f, err := os.Open(db.BDFPath); err != nil {
|
||||
return fmt.Errorf("cannot load label font: %s", err)
|
||||
} else {
|
||||
defer f.Close()
|
||||
if labelFont, err = bdf.NewFromBDF(f); err != nil {
|
||||
return fmt.Errorf("cannot load label font: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Open database log file for appending.
|
||||
if dbLog, err = os.OpenFile(dbPath+".log",
|
||||
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remember the current state of the database.
|
||||
dbLast = db
|
||||
return nil
|
||||
}
|
||||
14
cmd/sklad/label.tmpl
Normal file
14
cmd/sklad/label.tmpl
Normal file
@@ -0,0 +1,14 @@
|
||||
{{ define "Title" }}Tisk štítku{{ end }}
|
||||
{{ define "Content" }}
|
||||
|
||||
<h2>Tisk štítku pro <a href="container?id={{ .Id }}">{{ .Id }}</a></h2>
|
||||
|
||||
{{ if .UnknownId }}
|
||||
<p>Neznámý obal.
|
||||
{{ else if .Error }}
|
||||
<p>Tisk selhal: {{ .Error }}
|
||||
{{ else }}
|
||||
<p>Tisk proběhl úspěšně.
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
17
cmd/sklad/login.tmpl
Normal file
17
cmd/sklad/login.tmpl
Normal file
@@ -0,0 +1,17 @@
|
||||
{{ define "Title" }}Přihlášení{{ end }}
|
||||
{{ define "HeaderControls" }}<!-- text/template requires content -->{{ end }}
|
||||
{{ define "Content" }}
|
||||
|
||||
<h2>Přihlášení</h2>
|
||||
|
||||
<form method=post>
|
||||
<label for=password>Heslo:</label>
|
||||
<input type=password name=password id=password autofocus
|
||||
><input type=submit value="Přihlásit">
|
||||
</form>
|
||||
|
||||
{{ if .IncorrectPassword }}
|
||||
<p>Bylo zadáno nesprávné heslo.
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
444
cmd/sklad/main.go
Normal file
444
cmd/sklad/main.go
Normal file
@@ -0,0 +1,444 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"html"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"janouch.name/sklad/imgutil"
|
||||
"janouch.name/sklad/label"
|
||||
"janouch.name/sklad/ql"
|
||||
)
|
||||
|
||||
var templates = map[string]*template.Template{}
|
||||
|
||||
func executeTemplate(name string, w io.Writer, data interface{}) {
|
||||
if err := templates[name].Execute(w, data); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
redirect := r.FormValue("redirect")
|
||||
if redirect == "" {
|
||||
redirect = "container"
|
||||
}
|
||||
|
||||
session := sessionGet(w, r)
|
||||
if session.LoggedIn {
|
||||
http.Redirect(w, r, redirect, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
params := struct {
|
||||
IncorrectPassword bool
|
||||
}{}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
// We're just going to render the template.
|
||||
case http.MethodPost:
|
||||
if r.FormValue("password") == db.Password {
|
||||
session.LoggedIn = true
|
||||
http.Redirect(w, r, redirect, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
params.IncorrectPassword = true
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
executeTemplate("login.tmpl", w, ¶ms)
|
||||
}
|
||||
|
||||
func handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
session := r.Context().Value(sessionContextKey{}).(*Session)
|
||||
session.LoggedIn = false
|
||||
http.Redirect(w, r, "login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleContainerPost(r *http.Request) error {
|
||||
id := ContainerId(r.FormValue("id"))
|
||||
description := strings.TrimSpace(r.FormValue("description"))
|
||||
series := r.FormValue("series")
|
||||
parent := ContainerId(strings.TrimSpace(r.FormValue("parent")))
|
||||
_, remove := r.Form["remove"]
|
||||
|
||||
if container, ok := indexContainer[id]; ok {
|
||||
if remove {
|
||||
return dbContainerRemove(container)
|
||||
} else {
|
||||
c := *container
|
||||
c.Description = description
|
||||
c.Series = series
|
||||
c.Parent = parent
|
||||
return dbContainerUpdate(container, c)
|
||||
}
|
||||
} else if remove {
|
||||
return errNoSuchContainer
|
||||
} else {
|
||||
return dbContainerCreate(&Container{
|
||||
Series: series,
|
||||
Parent: parent,
|
||||
Description: description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleContainer(w http.ResponseWriter, r *http.Request) {
|
||||
// When deleting, do not try to show the deleted entry but the context.
|
||||
shownId := r.FormValue("context")
|
||||
if shownId == "" {
|
||||
shownId = r.FormValue("id")
|
||||
}
|
||||
|
||||
var err error
|
||||
if r.Method == http.MethodPost {
|
||||
if err = handleContainerPost(r); err == nil {
|
||||
redirect := r.URL.EscapedPath()
|
||||
if shownId != "" {
|
||||
redirect += "?id=" + url.QueryEscape(shownId)
|
||||
}
|
||||
http.Redirect(w, r, redirect, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
} else if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
allSeries := map[string]string{}
|
||||
for _, s := range indexSeries {
|
||||
allSeries[s.Prefix] = s.Description
|
||||
}
|
||||
|
||||
params := struct {
|
||||
Error error
|
||||
ErrorNoSuchSeries bool
|
||||
ErrorContainerAlreadyExists bool
|
||||
ErrorNoSuchContainer bool
|
||||
ErrorCannotChangeSeriesNotEmpty bool
|
||||
ErrorCannotChangeNumber bool
|
||||
ErrorWouldContainItself bool
|
||||
ErrorContainerInUse bool
|
||||
Container *Container
|
||||
NewDescription *string
|
||||
NewSeries string
|
||||
NewParent *string
|
||||
Children []*Container
|
||||
AllSeries map[string]string
|
||||
}{
|
||||
Error: err,
|
||||
ErrorNoSuchSeries: err == errNoSuchSeries,
|
||||
ErrorContainerAlreadyExists: err == errContainerAlreadyExists,
|
||||
ErrorNoSuchContainer: err == errNoSuchContainer,
|
||||
ErrorCannotChangeSeriesNotEmpty: err == errCannotChangeSeriesNotEmpty,
|
||||
ErrorCannotChangeNumber: err == errCannotChangeNumber,
|
||||
ErrorWouldContainItself: err == errWouldContainItself,
|
||||
ErrorContainerInUse: err == errContainerInUse,
|
||||
Children: indexChildren[""],
|
||||
AllSeries: allSeries,
|
||||
}
|
||||
if c, ok := indexContainer[ContainerId(shownId)]; ok {
|
||||
params.Children = c.Children()
|
||||
params.Container = c
|
||||
}
|
||||
if description, ok := r.Form["description"]; ok {
|
||||
params.NewDescription = &description[0]
|
||||
}
|
||||
if series, ok := r.Form["series"]; ok {
|
||||
// It seems impossible to dereference strings in text/template so that
|
||||
// `eq` can be used, and we don't actually need a null value here.
|
||||
params.NewSeries = series[0]
|
||||
}
|
||||
if parent, ok := r.Form["parent"]; ok {
|
||||
params.NewParent = &parent[0]
|
||||
}
|
||||
|
||||
executeTemplate("container.tmpl", w, ¶ms)
|
||||
}
|
||||
|
||||
func handleSeriesPost(r *http.Request) error {
|
||||
prefix := strings.TrimSpace(r.FormValue("prefix"))
|
||||
description := strings.TrimSpace(r.FormValue("description"))
|
||||
_, remove := r.Form["remove"]
|
||||
|
||||
if series, ok := indexSeries[prefix]; ok {
|
||||
if remove {
|
||||
return dbSeriesRemove(series)
|
||||
} else {
|
||||
s := *series
|
||||
s.Description = description
|
||||
return dbSeriesUpdate(series, s)
|
||||
}
|
||||
} else if remove {
|
||||
return errNoSuchSeries
|
||||
} else {
|
||||
return dbSeriesCreate(&Series{
|
||||
Prefix: prefix,
|
||||
Description: description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func handleSeries(w http.ResponseWriter, r *http.Request) {
|
||||
var err error
|
||||
if r.Method == http.MethodPost {
|
||||
if err = handleSeriesPost(r); err == nil {
|
||||
http.Redirect(w, r, r.URL.EscapedPath(), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
// XXX: This is rather ugly.
|
||||
r.Form = url.Values{}
|
||||
} else if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
allSeries := map[string]*Series{}
|
||||
for _, s := range indexSeries {
|
||||
allSeries[s.Prefix] = s
|
||||
}
|
||||
|
||||
prefix := r.FormValue("prefix")
|
||||
description := ""
|
||||
|
||||
if prefix == "" {
|
||||
} else if series, ok := indexSeries[prefix]; ok {
|
||||
description = series.Description
|
||||
} else {
|
||||
err = errNoSuchSeries
|
||||
}
|
||||
|
||||
params := struct {
|
||||
Error error
|
||||
ErrorInvalidPrefix bool
|
||||
ErrorSeriesAlreadyExists bool
|
||||
ErrorCannotChangePrefix bool
|
||||
ErrorNoSuchSeries bool
|
||||
ErrorSeriesInUse bool
|
||||
Prefix string
|
||||
Description string
|
||||
AllSeries map[string]*Series
|
||||
}{
|
||||
Error: err,
|
||||
ErrorInvalidPrefix: err == errInvalidPrefix,
|
||||
ErrorSeriesAlreadyExists: err == errSeriesAlreadyExists,
|
||||
ErrorCannotChangePrefix: err == errCannotChangePrefix,
|
||||
ErrorNoSuchSeries: err == errNoSuchSeries,
|
||||
ErrorSeriesInUse: err == errSeriesInUse,
|
||||
Prefix: prefix,
|
||||
Description: description,
|
||||
AllSeries: allSeries,
|
||||
}
|
||||
|
||||
executeTemplate("series.tmpl", w, ¶ms)
|
||||
}
|
||||
|
||||
func handleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
query := r.FormValue("q")
|
||||
params := struct {
|
||||
Query string
|
||||
Series []*Series
|
||||
Containers []*Container
|
||||
}{
|
||||
Query: query,
|
||||
Series: dbSearchSeries(query),
|
||||
Containers: dbSearchContainers(query),
|
||||
}
|
||||
|
||||
executeTemplate("search.tmpl", w, ¶ms)
|
||||
}
|
||||
|
||||
func printLabel(id string) error {
|
||||
printer, err := ql.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if printer == nil {
|
||||
return errors.New("no suitable printer found")
|
||||
}
|
||||
defer printer.Close()
|
||||
|
||||
/*
|
||||
printer.StatusNotify = func(status *ql.Status) {
|
||||
log.Printf("\x1b[1mreceived status\x1b[m\n%+v\n%s",
|
||||
status[:], status)
|
||||
}
|
||||
*/
|
||||
|
||||
if err := printer.Initialize(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := printer.UpdateStatus(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mediaInfo := ql.GetMediaInfo(
|
||||
printer.LastStatus.MediaWidthMM(),
|
||||
printer.LastStatus.MediaLengthMM(),
|
||||
)
|
||||
if mediaInfo == nil {
|
||||
return errors.New("unknown media")
|
||||
}
|
||||
|
||||
return printer.Print(&imgutil.LeftRotate{Image: label.GenLabelForHeight(
|
||||
labelFont, id, mediaInfo.PrintAreaPins, db.BDFScale)}, false)
|
||||
}
|
||||
|
||||
func handleLabel(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
params := struct {
|
||||
Id string
|
||||
UnknownId bool
|
||||
Error error
|
||||
}{
|
||||
Id: r.FormValue("id"),
|
||||
}
|
||||
|
||||
if c := indexContainer[ContainerId(params.Id)]; c == nil {
|
||||
params.UnknownId = true
|
||||
} else {
|
||||
params.Error = printLabel(params.Id)
|
||||
}
|
||||
|
||||
executeTemplate("label.tmpl", w, ¶ms)
|
||||
}
|
||||
|
||||
var mutex sync.Mutex
|
||||
|
||||
func handle(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
switch _, base := path.Split(r.URL.Path); base {
|
||||
case "login":
|
||||
handleLogin(w, r)
|
||||
case "logout":
|
||||
sessionWrap(handleLogout)(w, r)
|
||||
|
||||
case "container":
|
||||
sessionWrap(handleContainer)(w, r)
|
||||
case "series":
|
||||
sessionWrap(handleSeries)(w, r)
|
||||
case "search":
|
||||
sessionWrap(handleSearch)(w, r)
|
||||
case "label":
|
||||
sessionWrap(handleLabel)(w, r)
|
||||
|
||||
case "":
|
||||
http.Redirect(w, r, "container", http.StatusSeeOther)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
var funcMap = template.FuncMap{
|
||||
"max": func(i, j int) int {
|
||||
if i > j {
|
||||
return i
|
||||
}
|
||||
return j
|
||||
},
|
||||
"lines": func(s string) int {
|
||||
return strings.Count(s, "\n") + 1
|
||||
},
|
||||
"highlight": func(highlight, s string) template.HTML {
|
||||
b, last := strings.Builder{}, 0
|
||||
for _, m := range regexp.MustCompile(
|
||||
`(?i:`+regexp.QuoteMeta(highlight)+`)`).FindAllStringIndex(s, -1) {
|
||||
b.WriteString(html.EscapeString(s[last:m[0]]))
|
||||
b.WriteString(`<mark>`)
|
||||
b.WriteString(html.EscapeString(s[m[0]:m[1]]))
|
||||
b.WriteString(`</mark>`)
|
||||
last = m[1]
|
||||
}
|
||||
b.WriteString(html.EscapeString(s[last:]))
|
||||
return template.HTML(b.String())
|
||||
},
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Randomize the RNG for session string generation.
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
if len(os.Args) != 3 {
|
||||
log.Fatalf("Usage: %s ADDRESS DATABASE-FILE\n", os.Args[0])
|
||||
}
|
||||
|
||||
var address string
|
||||
address, dbPath = os.Args[1], os.Args[2]
|
||||
|
||||
// Load database.
|
||||
if err := loadDatabase(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
// Load HTML templates from the current working directory.
|
||||
m, err := filepath.Glob("*.tmpl")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
for _, name := range m {
|
||||
templates[name] = template.Must(template.New("base.tmpl").
|
||||
Funcs(funcMap).ParseFiles("base.tmpl", name))
|
||||
}
|
||||
|
||||
http.HandleFunc("/", handle)
|
||||
server := &http.Server{Addr: address}
|
||||
|
||||
sigs := make(chan os.Signal, 1)
|
||||
errs := make(chan error, 1)
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
|
||||
go func() { errs <- server.ListenAndServe() }()
|
||||
|
||||
select {
|
||||
case <-sigs:
|
||||
case err := <-errs:
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
// Wait for all HTTP goroutines to finish so that not even the database
|
||||
// log gets corrupted by an interrupted update.
|
||||
if err := server.Shutdown(context.Background()); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
38
cmd/sklad/search.tmpl
Normal file
38
cmd/sklad/search.tmpl
Normal file
@@ -0,0 +1,38 @@
|
||||
{{ define "Title" }}„{{ .Query }}“ — Vyhledávání{{ end }}
|
||||
{{ define "Content" }}
|
||||
|
||||
<h2>Vyhledávání: „{{ .Query }}“</h2>
|
||||
|
||||
<h3>Řady</h3>
|
||||
|
||||
{{ range .Series }}
|
||||
<section>
|
||||
<header>
|
||||
<h3><a href="series?prefix={{ .Prefix }}">{{ .Prefix }}</a></h3>
|
||||
<p>{{ .Description | highlight $.Query }}
|
||||
</header>
|
||||
</section>
|
||||
{{ else }}
|
||||
<p>Neodpovídají žádné řady.
|
||||
{{ end }}
|
||||
|
||||
<h3>Obaly</h3>
|
||||
|
||||
{{ range .Containers }}
|
||||
<section>
|
||||
<header>
|
||||
<h3><a href="container?id={{ .Id }}">{{ .Id }}</a>
|
||||
{{- range .Path }}
|
||||
<small>« <a href="container?id={{ . }}">{{ . }}</a></small>
|
||||
{{- end }}
|
||||
</h3>
|
||||
</header>
|
||||
{{- if .Description }}
|
||||
<p>{{ .Description | highlight $.Query }}
|
||||
{{- end }}
|
||||
</section>
|
||||
{{ else }}
|
||||
<p>Neodpovídají žádné obaly.
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
63
cmd/sklad/series.tmpl
Normal file
63
cmd/sklad/series.tmpl
Normal file
@@ -0,0 +1,63 @@
|
||||
{{ define "Title" }}{{ or .Prefix "Řady" }}{{ end }}
|
||||
{{ define "Content" }}
|
||||
|
||||
{{ if .ErrorInvalidPrefix }}
|
||||
<p>Chyba: Neplatný prefix.
|
||||
{{ else if .ErrorSeriesAlreadyExists }}
|
||||
<p>Chyba: Řada s tímto prefixem už existuje.
|
||||
{{ else if .ErrorCannotChangePrefix }}
|
||||
<p>Chyba: Prefix nelze měnit.
|
||||
{{ else if .ErrorNoSuchSeries }}
|
||||
<p>Chyba: Řada neexistuje.
|
||||
{{ else if .ErrorSeriesInUse }}
|
||||
<p>Chyba: Řada se používá.
|
||||
{{ else if .Error }}
|
||||
<p>Chyba: {{ .Error }}
|
||||
{{ end }}
|
||||
|
||||
{{ if .Prefix }}
|
||||
<h2>{{ .Prefix }}</h2>
|
||||
|
||||
{{ if .Description }}
|
||||
<p>{{ .Description }}
|
||||
{{ end }}
|
||||
{{ else }}
|
||||
<section>
|
||||
<form method=post action="series">
|
||||
<header>
|
||||
<h3>Nová řada</h3>
|
||||
<input type=text name=prefix placeholder="Prefix řady">
|
||||
<input type=text name=description placeholder="Popis řady"
|
||||
><input type=submit value="Uložit">
|
||||
</header>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{{ range .AllSeries }}
|
||||
<section>
|
||||
<header>
|
||||
<h3><a href="series?prefix={{ .Prefix }}">{{ .Prefix }}</a></h3>
|
||||
{{- with $count := len .Containers }}
|
||||
{{- if eq $count 1 }}
|
||||
<p>{{ $count }} obal
|
||||
{{- else if and (ge $count 2) (le $count 4) }}
|
||||
<p>{{ $count }} obaly
|
||||
{{- else if gt $count 0 }}
|
||||
<p>{{ $count }} obalů
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
<form method=post action="series?prefix={{ .Prefix }}">
|
||||
<input type=text name=description value="{{ .Description }}"
|
||||
><input type=submit value="Uložit">
|
||||
</form>
|
||||
<form method=post action="series?prefix={{ .Prefix }}&remove">
|
||||
<input type=submit value="Odstranit">
|
||||
</form>
|
||||
</header>
|
||||
</section>
|
||||
{{ else }}
|
||||
<p>Nejsou žádné řady.
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
66
cmd/sklad/session.go
Normal file
66
cmd/sklad/session.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// session storage indexed by a random UUID
|
||||
var sessions = map[string]*Session{}
|
||||
|
||||
type Session struct {
|
||||
LoggedIn bool // may access the DB
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func sessionGenId() string {
|
||||
u := make([]byte, 16)
|
||||
if _, err := rand.Read(u); err != nil {
|
||||
panic("cannot generate random bytes")
|
||||
}
|
||||
return hex.EncodeToString(u)
|
||||
}
|
||||
|
||||
// TODO: We don't want to keep an unlimited amount of cookies in the storage.
|
||||
// - The essential question is: how do we avoid DoS?
|
||||
// - Which cookies are worth keeping?
|
||||
// - Definitely logged-in users, only one person should know the password.
|
||||
// - Evict by FIFO? LRU?
|
||||
func sessionGet(w http.ResponseWriter, r *http.Request) (session *Session) {
|
||||
if c, _ := r.Cookie("sessionid"); c != nil {
|
||||
session, _ = sessions[c.Value]
|
||||
}
|
||||
if session == nil {
|
||||
id := sessionGenId()
|
||||
session = &Session{LoggedIn: false}
|
||||
sessions[id] = session
|
||||
http.SetCookie(w, &http.Cookie{Name: "sessionid", Value: id})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func sessionWrap(inner func(http.ResponseWriter, *http.Request)) func(
|
||||
http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// We might also try no-cache with an ETag for the whole database,
|
||||
// though I don't expect any substantial improvements of anything.
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
|
||||
redirect := "login"
|
||||
if r.RequestURI != "/" && r.Method == http.MethodGet {
|
||||
redirect += "?redirect=" + url.QueryEscape(r.RequestURI)
|
||||
}
|
||||
|
||||
session := sessionGet(w, r)
|
||||
if !session.LoggedIn {
|
||||
http.Redirect(w, r, redirect, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
inner(w, r.WithContext(
|
||||
context.WithValue(r.Context(), sessionContextKey{}, session)))
|
||||
}
|
||||
}
|
||||
27
go.mod
27
go.mod
@@ -1,28 +1,5 @@
|
||||
module janouch.name/sklad
|
||||
|
||||
go 1.12
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/boombuler/barcode v1.0.0
|
||||
github.com/cosiner/argv v0.0.1 // indirect
|
||||
github.com/cpuguy83/go-md2man v1.0.10 // indirect
|
||||
github.com/go-delve/delve v1.2.0 // indirect
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.7 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.4 // indirect
|
||||
github.com/peterh/liner v1.1.0 // indirect
|
||||
github.com/pkg/profile v1.3.0 // indirect
|
||||
github.com/russross/blackfriday v2.0.0+incompatible // indirect
|
||||
github.com/sirupsen/logrus v1.4.1 // indirect
|
||||
github.com/spf13/cobra v0.0.3 // indirect
|
||||
github.com/spf13/pflag v1.0.3 // indirect
|
||||
github.com/stretchr/objx v0.2.0 // indirect
|
||||
golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c // indirect
|
||||
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a // indirect
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 // indirect
|
||||
golang.org/x/sys v0.0.0-20190411185658-b44545bcd369 // indirect
|
||||
golang.org/x/tools v0.0.0-20190411180116-681f9ce8ac52 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.2 // indirect
|
||||
)
|
||||
require github.com/boombuler/barcode v1.0.1
|
||||
|
||||
72
go.sum
72
go.sum
@@ -1,70 +1,2 @@
|
||||
github.com/boombuler/barcode v1.0.0 h1:s1TvRnXwL2xJRaccrdcBQMZxq6X7DvsMogtmJeHDdrc=
|
||||
github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/cosiner/argv v0.0.0-20170225145430-13bacc38a0a5/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ=
|
||||
github.com/cosiner/argv v0.0.1 h1:2iAFN+sWPktbZ4tvxm33Ei8VY66FPCxdOxpncUGpAXE=
|
||||
github.com/cosiner/argv v0.0.1/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ=
|
||||
github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY=
|
||||
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-delve/delve v1.2.0 h1:uwGyfYO0WsWqbnDWvxCBKOr2qFLpii3tLxwM+fTJs70=
|
||||
github.com/go-delve/delve v1.2.0/go.mod h1:yP+LD36s/ud5nm4lsQY0TwNhYu2PAwk6xItz+442j74=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/mattn/go-colorable v0.0.0-20170327083344-ded68f7a9561/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.7 h1:UvyT9uN+3r7yLEYSlJsbQGdsaB/a0DlgWP3pql6iwOc=
|
||||
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
|
||||
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/peterh/liner v0.0.0-20170317030525-88609521dc4b/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
|
||||
github.com/peterh/liner v1.1.0 h1:f+aAedNJA6uk7+6rXsYBnhdo4Xux7ESLe+kcuVUF5os=
|
||||
github.com/peterh/liner v1.1.0/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0=
|
||||
github.com/pkg/profile v0.0.0-20170413231811-06b906832ed0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pkg/profile v1.3.0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday v0.0.0-20180428102519-11635eb403ff/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/russross/blackfriday v2.0.0+incompatible/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/sirupsen/logrus v0.0.0-20180523074243-ea8897e79973/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
|
||||
github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/spf13/cobra v0.0.0-20170417170307-b6cb39589372/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/pflag v0.0.0-20170417173400-9e4c21054fa1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
golang.org/x/arch v0.0.0-20171004143515-077ac972c2e4/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
|
||||
golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c h1:Rx/HTKi09myZ25t1SOlDHmHOy/mKxNAcu0hP1oPX9qM=
|
||||
golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4=
|
||||
golang.org/x/crypto v0.0.0-20180614174826-fd5f17ee7299/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20180614134839-8883426083c0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190411185658-b44545bcd369 h1:aBlRBZoCuZNRDClvfkDoklQqdLzBaA3uViASg2z2p24=
|
||||
golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/tools v0.0.0-20181120060634-fc4f04983f62/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190411180116-681f9ce8ac52/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.0.0-20170407172122-cd8b52f8269e/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs=
|
||||
github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
|
||||
57
imgutil/imgutil.go
Normal file
57
imgutil/imgutil.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package imgutil
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// Scale is a scaling image.Image wrapper.
|
||||
type Scale struct {
|
||||
Image image.Image
|
||||
Scale int
|
||||
}
|
||||
|
||||
// ColorModel implements image.Image.
|
||||
func (s *Scale) ColorModel() color.Model {
|
||||
return s.Image.ColorModel()
|
||||
}
|
||||
|
||||
// Bounds implements image.Image.
|
||||
func (s *Scale) Bounds() image.Rectangle {
|
||||
r := s.Image.Bounds()
|
||||
return image.Rect(r.Min.X*s.Scale, r.Min.Y*s.Scale,
|
||||
r.Max.X*s.Scale, r.Max.Y*s.Scale)
|
||||
}
|
||||
|
||||
// At implements image.Image.
|
||||
func (s *Scale) At(x, y int) color.Color {
|
||||
if x < 0 {
|
||||
x = x - s.Scale + 1
|
||||
}
|
||||
if y < 0 {
|
||||
y = y - s.Scale + 1
|
||||
}
|
||||
return s.Image.At(x/s.Scale, y/s.Scale)
|
||||
}
|
||||
|
||||
// LeftRotate is a 90 degree rotating image.Image wrapper.
|
||||
type LeftRotate struct {
|
||||
Image image.Image
|
||||
}
|
||||
|
||||
// ColorModel implements image.Image.
|
||||
func (lr *LeftRotate) ColorModel() color.Model {
|
||||
return lr.Image.ColorModel()
|
||||
}
|
||||
|
||||
// Bounds implements image.Image.
|
||||
func (lr *LeftRotate) Bounds() image.Rectangle {
|
||||
r := lr.Image.Bounds()
|
||||
// Min is inclusive, Max is exclusive.
|
||||
return image.Rect(r.Min.Y, -(r.Max.X - 1), r.Max.Y, -(r.Min.X - 1))
|
||||
}
|
||||
|
||||
// At implements image.Image.
|
||||
func (lr *LeftRotate) At(x, y int) color.Color {
|
||||
return lr.Image.At(-y, x)
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"html/template"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/boombuler/barcode"
|
||||
"github.com/boombuler/barcode/qr"
|
||||
|
||||
"janouch.name/sklad/bdf"
|
||||
"janouch.name/sklad/ql"
|
||||
)
|
||||
|
||||
// scaler is a scaling image.Image wrapper.
|
||||
type scaler struct {
|
||||
image image.Image
|
||||
scale int
|
||||
}
|
||||
|
||||
// ColorModel implements image.Image.
|
||||
func (s *scaler) ColorModel() color.Model {
|
||||
return s.image.ColorModel()
|
||||
}
|
||||
|
||||
// Bounds implements image.Image.
|
||||
func (s *scaler) Bounds() image.Rectangle {
|
||||
r := s.image.Bounds()
|
||||
return image.Rect(r.Min.X*s.scale, r.Min.Y*s.scale,
|
||||
r.Max.X*s.scale, r.Max.Y*s.scale)
|
||||
}
|
||||
|
||||
// At implements image.Image.
|
||||
func (s *scaler) At(x, y int) color.Color {
|
||||
if x < 0 {
|
||||
x = x - s.scale + 1
|
||||
}
|
||||
if y < 0 {
|
||||
y = y - s.scale + 1
|
||||
}
|
||||
return s.image.At(x/s.scale, y/s.scale)
|
||||
}
|
||||
|
||||
// leftRotate is a 90 degree rotating image.Image wrapper.
|
||||
type leftRotate struct {
|
||||
image image.Image
|
||||
}
|
||||
|
||||
// ColorModel implements image.Image.
|
||||
func (lr *leftRotate) ColorModel() color.Model {
|
||||
return lr.image.ColorModel()
|
||||
}
|
||||
|
||||
// Bounds implements image.Image.
|
||||
func (lr *leftRotate) Bounds() image.Rectangle {
|
||||
r := lr.image.Bounds()
|
||||
// Min is inclusive, Max is exclusive.
|
||||
return image.Rect(r.Min.Y, -(r.Max.X - 1), r.Max.Y, -(r.Min.X - 1))
|
||||
}
|
||||
|
||||
// At implements image.Image.
|
||||
func (lr *leftRotate) At(x, y int) color.Color {
|
||||
return lr.image.At(-y, x)
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
var font *bdf.Font
|
||||
|
||||
func genLabelForHeight(text string, height, scale int) image.Image {
|
||||
// Create a scaled bitmap of the text label.
|
||||
textRect, _ := font.BoundString(text)
|
||||
textImg := image.NewRGBA(textRect)
|
||||
draw.Draw(textImg, textRect, image.White, image.ZP, draw.Src)
|
||||
font.DrawString(textImg, image.ZP, text)
|
||||
|
||||
scaledTextImg := scaler{image: textImg, scale: scale}
|
||||
scaledTextRect := scaledTextImg.Bounds()
|
||||
|
||||
remains := height - scaledTextRect.Dy() - 20
|
||||
|
||||
width := scaledTextRect.Dx()
|
||||
if remains > width {
|
||||
width = remains
|
||||
}
|
||||
|
||||
// Create a scaled bitmap of the QR code.
|
||||
qrImg, _ := qr.Encode(text, qr.H, qr.Auto)
|
||||
qrImg, _ = barcode.Scale(qrImg, remains, remains)
|
||||
qrRect := qrImg.Bounds()
|
||||
|
||||
// Combine.
|
||||
combinedRect := image.Rect(0, 0, width, height)
|
||||
combinedImg := image.NewRGBA(combinedRect)
|
||||
draw.Draw(combinedImg, combinedRect, image.White, image.ZP, draw.Src)
|
||||
draw.Draw(combinedImg,
|
||||
combinedRect.Add(image.Point{X: (width - qrRect.Dx()) / 2, Y: 0}),
|
||||
qrImg, image.ZP, draw.Src)
|
||||
|
||||
target := image.Rect(
|
||||
(width-scaledTextRect.Dx())/2, qrRect.Dy()+20,
|
||||
combinedRect.Max.X, combinedRect.Max.Y)
|
||||
draw.Draw(combinedImg, target, &scaledTextImg, scaledTextRect.Min, draw.Src)
|
||||
return combinedImg
|
||||
}
|
||||
|
||||
var tmpl = template.Must(template.New("form").Parse(`
|
||||
<!DOCTYPE html>
|
||||
<html><body>
|
||||
<h1>PT-CBP label printing tool</h1>
|
||||
<table><tr>
|
||||
<td valign=top>
|
||||
<img border=1 src='?img&scale={{.Scale}}&text={{.Text}}'>
|
||||
</td>
|
||||
<td valign=top>
|
||||
<fieldset>
|
||||
{{ if .Printer }}
|
||||
|
||||
<p>Printer: {{ .Printer.Manufacturer }} {{ .Printer.Model }}
|
||||
<p>Tape:
|
||||
{{ if .Printer.LastStatus }}
|
||||
{{ .Printer.LastStatus.MediaWidthMM }} mm ×
|
||||
{{ .Printer.LastStatus.MediaLengthMM }} mm
|
||||
|
||||
{{ if .MediaInfo }}
|
||||
(offset: {{ .MediaInfo.SideMarginPins }} pt,
|
||||
print area: {{ .MediaInfo.PrintAreaPins }} pt)
|
||||
{{ else }}
|
||||
(unknown media)
|
||||
{{ end }}
|
||||
|
||||
{{ if .Printer.LastStatus.Errors }}
|
||||
{{ range .Printer.LastStatus.Errors }}
|
||||
<p>Error: {{ . }}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ end }}
|
||||
{{ if .InitErr }}
|
||||
{{ .InitErr }}
|
||||
{{ end }}
|
||||
|
||||
{{ else }}
|
||||
<p>Error: {{ .PrinterErr }}
|
||||
{{ end }}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<p>Font: {{ .Font.Name }}
|
||||
</fieldset>
|
||||
<form><fieldset>
|
||||
<p><label for=text>Text:</label>
|
||||
<input id=text name=text value='{{.Text}}'>
|
||||
<label for=scale>Scale:</label>
|
||||
<input id=scale name=scale value='{{.Scale}}' size=1>
|
||||
<p><input type=submit value='Update'>
|
||||
<input type=submit name=print value='Update and Print'>
|
||||
</fieldset></form>
|
||||
</td>
|
||||
</tr></table>
|
||||
</body></html>
|
||||
`))
|
||||
|
||||
func getPrinter() (*ql.Printer, error) {
|
||||
printer, err := ql.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if printer == nil {
|
||||
return nil, errors.New("no suitable printer found")
|
||||
}
|
||||
return printer, nil
|
||||
}
|
||||
|
||||
func getStatus(printer *ql.Printer) error {
|
||||
if err := printer.Initialize(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := printer.UpdateStatus(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handle(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
initErr error
|
||||
mediaInfo *ql.MediaInfo
|
||||
)
|
||||
printer, printerErr := getPrinter()
|
||||
if printerErr == nil {
|
||||
defer printer.Close()
|
||||
printer.StatusNotify = func(status *ql.Status) {
|
||||
log.Printf("\x1b[1mreceived status\x1b[m\n%s", status)
|
||||
}
|
||||
|
||||
if initErr = getStatus(printer); initErr == nil {
|
||||
mediaInfo = ql.GetMediaInfo(
|
||||
printer.LastStatus.MediaWidthMM(),
|
||||
printer.LastStatus.MediaLengthMM(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
var params = struct {
|
||||
Printer *ql.Printer
|
||||
PrinterErr error
|
||||
InitErr error
|
||||
MediaInfo *ql.MediaInfo
|
||||
Font *bdf.Font
|
||||
Text string
|
||||
Scale int
|
||||
}{
|
||||
Printer: printer,
|
||||
PrinterErr: printerErr,
|
||||
InitErr: initErr,
|
||||
MediaInfo: mediaInfo,
|
||||
Font: font,
|
||||
Text: r.FormValue("text"),
|
||||
}
|
||||
|
||||
var err error
|
||||
params.Scale, err = strconv.Atoi(r.FormValue("scale"))
|
||||
if err != nil {
|
||||
params.Scale = 3
|
||||
}
|
||||
|
||||
var label image.Image
|
||||
if mediaInfo != nil {
|
||||
label = &leftRotate{image: genLabelForHeight(
|
||||
params.Text, mediaInfo.PrintAreaPins, params.Scale)}
|
||||
if r.FormValue("print") != "" {
|
||||
if err := printer.Print(label); err != nil {
|
||||
log.Println("print error:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := r.Form["img"]; !ok {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
tmpl.Execute(w, ¶ms)
|
||||
return
|
||||
}
|
||||
|
||||
if mediaInfo == nil {
|
||||
http.Error(w, "unknown media", 500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
if err := png.Encode(w, label); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
log.Fatalf("usage: %s ADDRESS BDF-FILE\n", os.Args[0])
|
||||
}
|
||||
|
||||
address, bdf_path := os.Args[1], os.Args[2]
|
||||
|
||||
var err error
|
||||
fi, err := os.Open(bdf_path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
font, err = bdf.NewFromBDF(fi)
|
||||
if err := fi.Close(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
log.Println("starting server")
|
||||
http.HandleFunc("/", handle)
|
||||
log.Fatal(http.ListenAndServe(address, nil))
|
||||
}
|
||||
108
label/label.go
Normal file
108
label/label.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package label
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"strings"
|
||||
|
||||
"janouch.name/sklad/bdf"
|
||||
"janouch.name/sklad/imgutil"
|
||||
|
||||
"github.com/boombuler/barcode"
|
||||
"github.com/boombuler/barcode/qr"
|
||||
)
|
||||
|
||||
// TODO: Rename to GenQRLabelForHeight.
|
||||
func GenLabelForHeight(font *bdf.Font,
|
||||
text string, height, scale int) image.Image {
|
||||
// Create a scaled bitmap of the text label.
|
||||
textRect, _ := font.BoundString(text)
|
||||
textImg := image.NewRGBA(textRect)
|
||||
draw.Draw(textImg, textRect, image.White, image.ZP, draw.Src)
|
||||
font.DrawString(textImg, image.ZP, color.Black, text)
|
||||
|
||||
scaledTextImg := imgutil.Scale{Image: textImg, Scale: scale}
|
||||
scaledTextRect := scaledTextImg.Bounds()
|
||||
|
||||
remains := height - scaledTextRect.Dy() - 20
|
||||
|
||||
width := scaledTextRect.Dx()
|
||||
if remains > width {
|
||||
width = remains
|
||||
}
|
||||
|
||||
// Create a scaled bitmap of the QR code.
|
||||
qrImg, _ := qr.Encode(text, qr.H, qr.Auto)
|
||||
qrImg, _ = barcode.Scale(qrImg, remains, remains)
|
||||
qrRect := qrImg.Bounds()
|
||||
|
||||
// Combine.
|
||||
combinedRect := image.Rect(0, 0, width, height)
|
||||
combinedImg := image.NewRGBA(combinedRect)
|
||||
draw.Draw(combinedImg, combinedRect, image.White, image.ZP, draw.Src)
|
||||
draw.Draw(combinedImg,
|
||||
combinedRect.Add(image.Point{X: (width - qrRect.Dx()) / 2, Y: 0}),
|
||||
qrImg, image.ZP, draw.Src)
|
||||
|
||||
target := image.Rect(
|
||||
(width-scaledTextRect.Dx())/2, qrRect.Dy()+20,
|
||||
combinedRect.Max.X, combinedRect.Max.Y)
|
||||
draw.Draw(combinedImg, target, &scaledTextImg, scaledTextRect.Min, draw.Src)
|
||||
return combinedImg
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func GenLabelForWidth(font *bdf.Font,
|
||||
text string, width, scale int) image.Image {
|
||||
var lines []string
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
lines = append(lines, strings.TrimSuffix(line, "\r"))
|
||||
}
|
||||
|
||||
// Respect font ascent and descent so that there are gaps between lines.
|
||||
rects := make([]image.Rectangle, len(lines))
|
||||
jumps := make([]int, len(lines))
|
||||
for i, line := range lines {
|
||||
r, _ := font.BoundString(line)
|
||||
rects[i] = r
|
||||
|
||||
if i > 0 {
|
||||
deficitD := font.Descent - rects[i-1].Max.Y
|
||||
jumps[i] += max(0, deficitD)
|
||||
deficitA := font.Ascent - (-r.Min.Y)
|
||||
jumps[i] += max(0, deficitA)
|
||||
}
|
||||
}
|
||||
|
||||
height := 0
|
||||
for i := range lines {
|
||||
height += jumps[i] + rects[i].Dy()
|
||||
}
|
||||
|
||||
imgRect := image.Rect(0, 0, width, height*scale)
|
||||
img := image.NewRGBA(imgRect)
|
||||
draw.Draw(img, imgRect, image.White, image.ZP, draw.Src)
|
||||
|
||||
y := 0
|
||||
for i, line := range lines {
|
||||
textImg := image.NewRGBA(rects[i])
|
||||
draw.Draw(textImg, rects[i], image.White, image.ZP, draw.Src)
|
||||
font.DrawString(textImg, image.ZP, color.Black, line)
|
||||
|
||||
scaledImg := imgutil.Scale{Image: textImg, Scale: scale}
|
||||
scaledRect := scaledImg.Bounds()
|
||||
|
||||
y += jumps[i]
|
||||
target := image.Rect(0, y*scale, imgRect.Max.X, imgRect.Max.Y)
|
||||
draw.Draw(img, target, &scaledImg, scaledRect.Min, draw.Src)
|
||||
y += rects[i].Dy()
|
||||
}
|
||||
return img
|
||||
}
|
||||
106
ql/ql.go
106
ql/ql.go
@@ -120,9 +120,67 @@ const (
|
||||
printPins = printBytes * 8
|
||||
)
|
||||
|
||||
// pack packs a bool array into a byte array for the printer to print out.
|
||||
func pack(data [printPins]bool, out *[]byte) {
|
||||
for i := 0; i < printBytes; i++ {
|
||||
var b byte
|
||||
for j := 0; j < 8; j++ {
|
||||
b <<= 1
|
||||
if data[i*8+j] {
|
||||
b |= 1
|
||||
}
|
||||
}
|
||||
*out = append(*out, b)
|
||||
}
|
||||
}
|
||||
|
||||
// makeBitmapDataRB converts an image to the printer's red-black raster format.
|
||||
func makeBitmapDataRB(src image.Image, margin, length int) []byte {
|
||||
data, bounds := []byte{}, src.Bounds()
|
||||
if bounds.Dy() > length {
|
||||
bounds.Max.Y = bounds.Min.Y + length
|
||||
}
|
||||
if bounds.Dx() > printPins-margin {
|
||||
bounds.Max.X = bounds.Min.X + printPins
|
||||
}
|
||||
|
||||
redcells, blackcells := [printPins]bool{}, [printPins]bool{}
|
||||
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
|
||||
length--
|
||||
|
||||
// The graphics needs to be inverted horizontally, iterating backwards.
|
||||
offset := margin
|
||||
for x := bounds.Max.X - 1; x >= bounds.Min.X; x-- {
|
||||
r, g, b, a := src.At(x, y).RGBA()
|
||||
redcells[offset] = r >= 0xc000 && g < 0x4000 && b < 0x4000 &&
|
||||
a >= 0x8000
|
||||
blackcells[offset] = r < 0x4000 && g < 0x4000 && b < 0x4000 &&
|
||||
a >= 0x8000
|
||||
offset++
|
||||
}
|
||||
|
||||
data = append(data, 'w', 0x01, printBytes)
|
||||
pack(blackcells, &data)
|
||||
data = append(data, 'w', 0x02, printBytes)
|
||||
pack(redcells, &data)
|
||||
}
|
||||
for ; length > 0; length-- {
|
||||
data = append(data, 'w', 0x01, printBytes)
|
||||
data = append(data, make([]byte, printBytes)...)
|
||||
data = append(data, 'w', 0x02, printBytes)
|
||||
data = append(data, make([]byte, printBytes)...)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// makeBitmapData converts an image to the printer's raster format.
|
||||
func makeBitmapData(src image.Image, margin, length int) (data []byte) {
|
||||
bounds := src.Bounds()
|
||||
func makeBitmapData(src image.Image, rb bool, margin, length int) []byte {
|
||||
// It's a necessary nuisance, so just copy and paste.
|
||||
if rb {
|
||||
return makeBitmapDataRB(src, margin, length)
|
||||
}
|
||||
|
||||
data, bounds := []byte{}, src.Bounds()
|
||||
if bounds.Dy() > length {
|
||||
bounds.Max.Y = bounds.Min.Y + length
|
||||
}
|
||||
@@ -138,30 +196,24 @@ func makeBitmapData(src image.Image, margin, length int) (data []byte) {
|
||||
offset := margin
|
||||
for x := bounds.Max.X - 1; x >= bounds.Min.X; x-- {
|
||||
r, g, b, a := src.At(x, y).RGBA()
|
||||
pixels[offset] = r == 0 && g == 0 && b == 0 && a >= 0x8000
|
||||
pixels[offset] = r < 0x4000 && g < 0x4000 && b < 0x4000 &&
|
||||
a >= 0x8000
|
||||
offset++
|
||||
}
|
||||
|
||||
data = append(data, 'g', 0x00, printBytes)
|
||||
for i := 0; i < printBytes; i++ {
|
||||
var b byte
|
||||
for j := 0; j < 8; j++ {
|
||||
b <<= 1
|
||||
if pixels[i*8+j] {
|
||||
b |= 1
|
||||
}
|
||||
}
|
||||
data = append(data, b)
|
||||
}
|
||||
pack(pixels, &data)
|
||||
}
|
||||
for ; length > 0; length-- {
|
||||
data = append(data, 'g', 0x00, printBytes)
|
||||
data = append(data, make([]byte, printBytes)...)
|
||||
}
|
||||
return
|
||||
return data
|
||||
}
|
||||
|
||||
func makePrintData(status *Status, image image.Image) (data []byte) {
|
||||
// XXX: It would be preferrable to know for certain if this is a red-black tape,
|
||||
// because the printer refuses to print on a mismatch.
|
||||
func makePrintData(status *Status, image image.Image, rb bool) (data []byte) {
|
||||
mediaInfo := GetMediaInfo(
|
||||
status.MediaWidthMM(),
|
||||
status.MediaLengthMM(),
|
||||
@@ -188,8 +240,17 @@ func makePrintData(status *Status, image image.Image) (data []byte) {
|
||||
mediaType = byte(0x0b)
|
||||
}
|
||||
|
||||
data = append(data, 0x1b, 0x69, 0x7a, 0x02|0x04|0x40|0x80, mediaType,
|
||||
byte(status.MediaWidthMM()), byte(status.MediaLengthMM()),
|
||||
const (
|
||||
flagValidMediaType = 0x02
|
||||
flagValidMediaWidth = 0x04
|
||||
flagValidMediaLength = 0x08
|
||||
flagPriorityToQuality = 0x40
|
||||
flagRecoveryAlwaysOn = 0x80
|
||||
)
|
||||
data = append(data, 0x1b, 0x69, 0x7a, flagValidMediaType|
|
||||
flagValidMediaWidth|flagValidMediaLength|
|
||||
flagPriorityToQuality|flagRecoveryAlwaysOn,
|
||||
mediaType, byte(status.MediaWidthMM()), byte(status.MediaLengthMM()),
|
||||
byte(dy), byte(dy>>8), byte(dy>>16), byte(dy>>24), 0, 0x00)
|
||||
|
||||
// Auto cut, each 1 label.
|
||||
@@ -198,9 +259,13 @@ func makePrintData(status *Status, image image.Image) (data []byte) {
|
||||
|
||||
// Cut at end (though it's the default).
|
||||
// Not sure what it means, doesn't seem to have any effect to turn it off.
|
||||
data = append(data, 0x1b, 0x69, 0x4b, 0x08)
|
||||
if rb {
|
||||
data = append(data, 0x1b, 0x69, 0x4b, 0x08|0x01)
|
||||
} else {
|
||||
data = append(data, 0x1b, 0x69, 0x4b, 0x08)
|
||||
}
|
||||
|
||||
if status.MediaLengthMM() != 0 {
|
||||
if status.MediaLengthMM() == 0 {
|
||||
// 3mm margins along the direction of feed. 0x23 = 35 dots, the minimum.
|
||||
data = append(data, 0x1b, 0x69, 0x64, 0x23, 0x00)
|
||||
} else {
|
||||
@@ -213,7 +278,8 @@ func makePrintData(status *Status, image image.Image) (data []byte) {
|
||||
data = append(data, 0x4d, 0x00)
|
||||
|
||||
// The graphics data itself.
|
||||
data = append(data, makeBitmapData(image, mediaInfo.SideMarginPins, dy)...)
|
||||
bitmapData := makeBitmapData(image, rb, mediaInfo.SideMarginPins, dy)
|
||||
data = append(data, bitmapData...)
|
||||
|
||||
// Print command with feeding.
|
||||
return append(data, 0x1a)
|
||||
|
||||
@@ -108,16 +108,14 @@ func (p *Printer) Initialize() error {
|
||||
|
||||
// Flush any former responses in the printer's queue.
|
||||
//
|
||||
// I'm not sure if this is necessary, or rather whether the kernel driver
|
||||
// does any buffering that could cause data to be returned at this point.
|
||||
/*
|
||||
var dummy [32]byte
|
||||
for {
|
||||
if _, err := f.Read(dummy[:]); err == io.EOF {
|
||||
break
|
||||
}
|
||||
// I haven't checked if this is the kernel driver or the printer doing
|
||||
// the buffering that causes data to be returned at this point.
|
||||
var dummy [32]byte
|
||||
for {
|
||||
if _, err := p.File.Read(dummy[:]); err == io.EOF {
|
||||
break
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -174,8 +172,8 @@ var errErrorOccurred = errors.New("error occurred")
|
||||
var errUnexpectedStatus = errors.New("unexpected status")
|
||||
var errUnknownMedia = errors.New("unknown media")
|
||||
|
||||
func (p *Printer) Print(image image.Image) error {
|
||||
data := makePrintData(p.LastStatus, image)
|
||||
func (p *Printer) Print(image image.Image, rb bool) error {
|
||||
data := makePrintData(p.LastStatus, image, rb)
|
||||
if data == nil {
|
||||
return errUnknownMedia
|
||||
}
|
||||
|
||||
20
ql/status.go
20
ql/status.go
@@ -151,28 +151,28 @@ func (s *Status) Dump(f io.Writer) {
|
||||
fmt.Fprintln(f, "media length:", s[17], "mm")
|
||||
|
||||
// Status type.
|
||||
switch t := s[18]; t {
|
||||
case 0x00:
|
||||
switch t := s[18]; StatusType(t) {
|
||||
case StatusTypeReplyToRequest:
|
||||
fmt.Fprintln(f, "status type: reply to status request")
|
||||
case 0x01:
|
||||
case StatusTypePrintingCompleted:
|
||||
fmt.Fprintln(f, "status type: printing completed")
|
||||
case 0x02:
|
||||
case StatusTypeErrorOccurred:
|
||||
fmt.Fprintln(f, "status type: error occurred")
|
||||
case 0x04:
|
||||
case StatusTypeTurnedOff:
|
||||
fmt.Fprintln(f, "status type: turned off")
|
||||
case 0x05:
|
||||
case StatusTypeNotification:
|
||||
fmt.Fprintln(f, "status type: notification")
|
||||
case 0x06:
|
||||
case StatusTypePhaseChange:
|
||||
fmt.Fprintln(f, "status type: phase change")
|
||||
default:
|
||||
fmt.Fprintln(f, "status type:", t)
|
||||
}
|
||||
|
||||
// Phase type.
|
||||
switch t := s[19]; t {
|
||||
case 0x00:
|
||||
switch t := s[19]; StatusPhase(t) {
|
||||
case StatusPhaseReceiving:
|
||||
fmt.Fprintln(f, "phase state: receiving state")
|
||||
case 0x01:
|
||||
case StatusPhasePrinting:
|
||||
fmt.Fprintln(f, "phase state: printing state")
|
||||
default:
|
||||
fmt.Fprintln(f, "phase state:", t)
|
||||
|
||||
Reference in New Issue
Block a user