feat(labels): the Label Designer — QSO and address labels for paper QSL

The designer's data model lives in internal/labels: STOCKS are the physical
roll in the printer (geometry in mm, margins, dpi — seeded with the common
Brother DK sizes, the QL family being what prompted the feature), TEMPLATES are
one design each, of two kinds: the QSO label glued on the card, whose repeating
table carries several contacts of the same station, and the address label for
the envelope, whose lines collapse when a variable is empty.

Everything is measured in millimetres — labels are sold in mm, and an operator
lining a design up against a physical sticker thinks in mm; pixels exist only in
the renderer, at the stock's dpi. The canvas renderer is shared between the
editor's preview and the future print path, so there is no second
implementation for the preview to disagree with.

The preview is fed with the log's latest contacts rather than lorem ipsum: real
data shows a too-narrow column immediately.

Printing (PDF, one page per label at exact size) is the next module; nothing
here prints yet.
This commit is contained in:
2026-08-28 19:41:15 +02:00
parent 3dc31697cd
commit 1a169fdb4f
16 changed files with 1730 additions and 2 deletions
+3
View File
@@ -44,6 +44,7 @@ import (
"hamlog/internal/gridcache"
"hamlog/internal/integrations/udp"
"hamlog/internal/kpa"
"hamlog/internal/labels"
"hamlog/internal/lookup"
"hamlog/internal/lotwusers"
"hamlog/internal/netctl"
@@ -735,6 +736,7 @@ type App struct {
uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened
awardRefs *awardref.Repo
qslTemplates *qslcard.Repo
labelRepo *labels.Repo // label designer (stocks + templates)
operating *operating.Repo
udp *udp.Manager
udpRepo *udp.Repo
@@ -1185,6 +1187,7 @@ func (a *App) startup(ctx context.Context) {
}
a.awardRefs = awardref.NewRepo(conn)
a.qslTemplates = qslcard.NewRepo(conn)
a.labelRepo = labels.NewRepo(conn)
a.migrateAwardDefs() // upgrade legacy award definitions (enable + new fields)
a.seedBuiltinReferences() // first-run: populate built-in award reference lists
a.mirrorAwards() // keep <data>/awards/*.json in step with the database
+208
View File
@@ -0,0 +1,208 @@
package main
// Label designer — the Wails boundary for internal/labels.
//
// The designer edits two things: STOCKS (the physical roll in the printer,
// geometry in mm) and TEMPLATES (one design per label kind: the QSO label glued
// on a card, the address label for the envelope). Printing — a later module —
// will ask for the default template of each kind and hand the rasterised pages
// to a PDF; nothing here prints.
import (
"fmt"
"strings"
"hamlog/internal/applog"
"hamlog/internal/labels"
"hamlog/internal/qso"
)
// LabelTemplateInfo is one row of the designer's template list.
type LabelTemplateInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
StockID int64 `json:"stock_id"`
ProfileID *int64 `json:"profile_id,omitempty"`
IsDefault bool `json:"is_default"`
UpdatedAt string `json:"updated_at"`
}
// LabelListStocks returns every label stock, seeding the builtin Brother rolls
// on first use.
func (a *App) LabelListStocks() ([]labels.Stock, error) {
if a.labelRepo == nil {
return nil, fmt.Errorf("db not initialized")
}
if err := a.labelRepo.SeedStocks(a.ctx); err != nil {
applog.Printf("labels: seeding stocks failed: %v", err)
}
return a.labelRepo.Stocks(a.ctx)
}
// LabelSaveStock creates or updates one stock and returns its id.
func (a *App) LabelSaveStock(s labels.Stock) (int64, error) {
if a.labelRepo == nil {
return 0, fmt.Errorf("db not initialized")
}
if err := a.labelRepo.SaveStock(a.ctx, &s); err != nil {
return 0, err
}
return s.ID, nil
}
// LabelDeleteStock removes a stock; designs pointing at it keep their content.
func (a *App) LabelDeleteStock(id int64) error {
if a.labelRepo == nil {
return fmt.Errorf("db not initialized")
}
return a.labelRepo.DeleteStock(a.ctx, id)
}
// LabelListTemplates lists the designs visible to the active profile.
func (a *App) LabelListTemplates() ([]LabelTemplateInfo, error) {
if a.labelRepo == nil {
return nil, fmt.Errorf("db not initialized")
}
var recs []labels.Record
var err error
if p, e := a.profiles.Active(a.ctx); e == nil {
recs, err = a.labelRepo.ListFor(a.ctx, p.ID)
} else {
recs, err = a.labelRepo.List(a.ctx)
}
if err != nil {
return nil, err
}
out := make([]LabelTemplateInfo, 0, len(recs))
for _, r := range recs {
info := LabelTemplateInfo{
ID: r.ID, Name: r.Name, Kind: r.Kind, ProfileID: r.ProfileID,
IsDefault: r.IsDefault, UpdatedAt: r.UpdatedAt.Format("2006-01-02 15:04"),
}
if r.StockID != nil {
info.StockID = *r.StockID
}
out = append(out, info)
}
return out, nil
}
// LabelGetTemplate returns one stored design document (JSON).
func (a *App) LabelGetTemplate(id int64) (string, error) {
if a.labelRepo == nil {
return "", fmt.Errorf("db not initialized")
}
rec, err := a.labelRepo.Get(a.ctx, id)
if err != nil {
return "", err
}
return rec.JSON, nil
}
// LabelSaveTemplate validates and stores a design; id 0 creates. Returns the id.
func (a *App) LabelSaveTemplate(id int64, name string, doc string, forActiveProfile bool) (int64, error) {
if a.labelRepo == nil {
return 0, fmt.Errorf("db not initialized")
}
name = strings.TrimSpace(name)
if name == "" {
return 0, fmt.Errorf("template name required")
}
t, err := labels.Parse([]byte(doc))
if err != nil {
return 0, err
}
if err := labels.Validate(t); err != nil {
return 0, err
}
rec := labels.Record{ID: id, Name: name, Kind: t.Kind, JSON: doc}
if t.StockID != 0 {
sid := t.StockID
rec.StockID = &sid
}
if forActiveProfile {
if p, err := a.profiles.Active(a.ctx); err == nil {
rec.ProfileID = &p.ID
}
}
if err := a.labelRepo.Save(a.ctx, &rec); err != nil {
return 0, err
}
applog.Printf("labels: template %q (%s) saved (id %d)", name, t.Kind, rec.ID)
return rec.ID, nil
}
// LabelDeleteTemplate removes a design.
func (a *App) LabelDeleteTemplate(id int64) error {
if a.labelRepo == nil {
return fmt.Errorf("db not initialized")
}
return a.labelRepo.Delete(a.ctx, id)
}
// LabelSetDefaultTemplate marks a design as the default for its kind.
func (a *App) LabelSetDefaultTemplate(id int64) error {
if a.labelRepo == nil {
return fmt.Errorf("db not initialized")
}
return a.labelRepo.SetDefault(a.ctx, id)
}
// LabelSampleQSO is one row of preview data for the designer's QSO table.
type LabelSampleQSO struct {
Callsign string `json:"callsign"`
QSODate string `json:"qso_date"` // YYYY-MM-DD
TimeOn string `json:"time_on"` // HH:MM
Band string `json:"band"`
FreqMHz string `json:"freq"`
Mode string `json:"mode"`
RSTSent string `json:"rst_sent"`
RSTRcvd string `json:"rst_rcvd"`
Name string `json:"name"`
QTH string `json:"qth"`
Country string `json:"country"`
}
// LabelSampleQSOs returns the last few real contacts for the designer's live
// preview — real data shows a too-narrow column immediately ("14074.0" does not
// fit where "7.1" did). Falls back to plausible fakes on an empty log; the
// preview must never be blank.
func (a *App) LabelSampleQSOs(limit int) []LabelSampleQSO {
if limit <= 0 || limit > 20 {
limit = 4
}
fake := []LabelSampleQSO{
{Callsign: "DL1ABC", QSODate: "2026-08-01", TimeOn: "14:32", Band: "20m", FreqMHz: "14.074", Mode: "FT8", RSTSent: "-08", RSTRcvd: "-12", Name: "Hans", QTH: "Berlin", Country: "Germany"},
{Callsign: "VK3XYZ", QSODate: "2026-08-02", TimeOn: "09:15", Band: "15m", FreqMHz: "21.245", Mode: "SSB", RSTSent: "59", RSTRcvd: "57", Name: "Bruce", QTH: "Melbourne", Country: "Australia"},
{Callsign: "JA1TOK", QSODate: "2026-08-03", TimeOn: "21:47", Band: "40m", FreqMHz: "7.012", Mode: "CW", RSTSent: "599", RSTRcvd: "579", Name: "Ken", QTH: "Tokyo", Country: "Japan"},
{Callsign: "W1AW", QSODate: "2026-08-04", TimeOn: "18:03", Band: "10m", FreqMHz: "28.480", Mode: "SSB", RSTSent: "59", RSTRcvd: "59", Name: "Hiram", QTH: "Newington", Country: "United States"},
}
if a.qso == nil {
return fake[:min(limit, len(fake))]
}
rows, err := a.qso.List(a.ctx, qso.ListFilter{Limit: limit})
if err != nil || len(rows) == 0 {
return fake[:min(limit, len(fake))]
}
out := make([]LabelSampleQSO, 0, len(rows))
for _, q := range rows {
s := LabelSampleQSO{
Callsign: q.Callsign,
QSODate: q.QSODate.UTC().Format("2006-01-02"),
TimeOn: q.QSODate.UTC().Format("15:04"),
Band: q.Band,
Mode: q.Mode,
RSTSent: q.RSTSent,
RSTRcvd: q.RSTRcvd,
Name: q.Name,
QTH: q.QTH,
Country: q.Country,
}
if q.FreqHz != nil && *q.FreqHz > 0 {
s.FreqMHz = fmt.Sprintf("%.3f", float64(*q.FreqHz)/1e6)
}
out = append(out, s)
}
return out
}
+4 -2
View File
@@ -16,7 +16,8 @@
"E-mail: a refused SMTP login now says what to do about it — Microsoft 365 and outlook.com have switched off password-based SMTP, and an app password does not bring it back.",
"TCI panorama spots: the colour was sent as a negative number and ExpertSDR dropped every spot in silence. It now goes out as the unsigned ARGB integer the protocol document uses, and the first few spots are written to the log verbatim.",
"Cluster: “Group duplicates” was hiding the same station on OTHER bands and modes — a DXpedition spotted on five bands showed as one line and four slots disappeared. A duplicate is now what it should always have been: the same station on the same band and mode.",
"LoTW: the downloaded confirmations list gains a Station column, so a list spanning several callsigns says which one each confirmation belongs to. Shown only when the report actually carries more than the one station."
"LoTW: the downloaded confirmations list gains a Station column, so a list spanning several callsigns says which one each confirmation belongs to. Shown only when the report actually carries more than the one station.",
"Label Designer (Tools): design the labels for paper QSL work — a QSO label for the card (repeating QSO table, several contacts of the same station per label) and address labels for the envelope. Label sizes are profiles in millimetres with margins, seeded with the common Brother DK rolls; elements are dragged in place on a millimetre-true preview fed with your latest contacts. Printing to PDF comes next."
],
"fr": [
"Téléchargement LoTW : les détails QSL (date du QSL, locator, état, comté) deviennent optionnels et désactivés par défaut — LoTW met environ dix fois plus longtemps à construire ce rapport, vingt minutes contre deux sur le même compte, et marquer une confirmation n'en a pas besoin. Toujours demandés automatiquement quand on ajoute les QSO absents du log.",
@@ -32,7 +33,8 @@
"E-mail : un refus d'authentification SMTP explique désormais quoi faire — Microsoft 365 et outlook.com ont désactivé le SMTP par mot de passe, et un mot de passe d'application ne le rétablit pas.",
"Spots sur le panorama TCI : la couleur partait en nombre négatif et ExpertSDR écartait chaque spot en silence. Elle est désormais envoyée en entier ARGB non signé, comme dans la documentation du protocole, et les premiers spots sont écrits tels quels dans le journal.",
"Cluster : « Grouper les doublons » masquait la même station sur les AUTRES bandes et modes — une expédition spottée sur cinq bandes n'affichait qu'une ligne et quatre créneaux disparaissaient. Un doublon est désormais ce qu'il aurait toujours dû être : la même station sur la même bande et le même mode.",
"LoTW : la liste des confirmations téléchargées gagne une colonne Station, pour savoir à quel indicatif appartient chaque confirmation quand le téléchargement en couvre plusieurs. Affichée seulement si le rapport en contient effectivement."
"LoTW : la liste des confirmations téléchargées gagne une colonne Station, pour savoir à quel indicatif appartient chaque confirmation quand le téléchargement en couvre plusieurs. Affichée seulement si le rapport en contient effectivement.",
"Créateur d'étiquettes (Outils) : dessinez les étiquettes de vos QSL papier — étiquette QSO pour la carte (tableau de QSO répétable, plusieurs contacts de la même station par étiquette) et étiquettes adresse pour l'enveloppe. Les formats sont des profils en millimètres avec marges, préremplis avec les rouleaux Brother DK courants ; les éléments se placent à la souris sur un aperçu fidèle au millimètre nourri de vos derniers contacts. L'impression en PDF viendra ensuite."
]
},
{
+5
View File
@@ -70,6 +70,7 @@ import {
import { APP_VERSION, APP_AUTHOR } from '@/version';
import { QSLManagerPanel } from '@/components/QSLManagerModal';
import { QslDesignerModal } from '@/components/qsl/QslDesignerModal';
import { LabelDesignerModal } from '@/components/labels/LabelDesignerModal';
import { SendEQSLModal } from '@/components/qsl/SendEQSLModal';
import { AutoEQSL } from '@/components/qsl/AutoEQSL';
import { ConfirmDialog } from '@/components/ConfirmDialog';
@@ -1267,6 +1268,7 @@ export default function App() {
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
}
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
const [labelDesignerOpen, setLabelDesignerOpen] = useState(false);
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
function closeQslTab() {
setQslTabOpen(false);
@@ -4998,6 +5000,7 @@ export default function App() {
{ type: 'item', label: t('dec.tab'), action: 'tools.decodes' },
{ type: 'item', label: t('gsm.title'), action: 'tools.grids' },
{ type: 'item', label: t('tools.qslDesigner'), action: 'tools.qsldesigner' },
{ type: 'item', label: t('tools.labelDesigner'), action: 'tools.labeldesigner' },
{ type: 'separator' },
{ type: 'item', label: (wkEnabled ? '✓ ' : '') + t('tools.winkeyer'), action: 'tools.winkeyer' },
{ type: 'item', label: (dvkEnabled ? '✓ ' : '') + t('tools.dvk'), action: 'tools.dvk' },
@@ -5051,6 +5054,7 @@ export default function App() {
case 'tools.decodes': openDecodesTab(); break;
case 'tools.grids': openGridsTab(); break;
case 'tools.qsldesigner': setQslDesignerOpen(true); break;
case 'tools.labeldesigner': setLabelDesignerOpen(true); break;
case 'tools.winkeyer': wkSetEnabled(!wkEnabled); break;
case 'tools.dvk': setDvkEnabled((v) => !v); break;
case 'tools.cwdecoder': toggleCwDecoder(); break;
@@ -8712,6 +8716,7 @@ export default function App() {
onError={(msg) => showToast(msg)}
/>
<QslDesignerModal open={qslDesignerOpen} onClose={() => setQslDesignerOpen(false)} />
<LabelDesignerModal open={labelDesignerOpen} onClose={() => setLabelDesignerOpen(false)} />
<SendEQSLModal
open={eqslQsoId !== null}
qsoId={eqslQsoId}
@@ -0,0 +1,538 @@
// Label Designer — QSO labels for QSL cards and address labels for envelopes.
//
// Same architecture as the QSL card designer, stripped to what a monochrome
// sticker needs: saved templates on the left, a mm-true canvas on the right,
// click to select, drag to move. The canvas renderer (labelRender) is shared
// with the future print path, so what the preview shows is what the PDF gets.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { X, Plus, Trash2, Star, Tag, MapPin } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import {
LabelListStocks, LabelSaveStock, LabelDeleteStock,
LabelListTemplates, LabelGetTemplate, LabelSaveTemplate, LabelDeleteTemplate,
LabelSetDefaultTemplate, LabelSampleQSOs, GetActiveProfile,
} from '../../../wailsjs/go/main/App';
import type { LabelElement, LabelSample, LabelStock, LabelTemplate } from './labelTypes';
import { LABEL_VARS, TABLE_FIELDS, starterTemplate } from './labelTypes';
import { drawMargins, render, type ElementBox } from './labelRender';
interface Props { open: boolean; onClose: () => void }
interface TplInfo {
id: number; name: string; kind: string; stock_id: number;
is_default: boolean; updated_at: string;
}
const PREVIEW_MAX_W = 720;
const PREVIEW_MAX_H = 420;
export function LabelDesignerModal({ open, onClose }: Props) {
const { t } = useI18n();
const [stocks, setStocks] = useState<LabelStock[]>([]);
const [saved, setSaved] = useState<TplInfo[]>([]);
const [samples, setSamples] = useState<LabelSample[]>([]);
const [myVars, setMyVars] = useState<Record<string, string>>({});
const [error, setError] = useState('');
// The design being edited (null = nothing open yet).
const [tplId, setTplId] = useState(0);
const [tpl, setTpl] = useState<LabelTemplate | null>(null);
const [tplName, setTplName] = useState('');
const [forProfile, setForProfile] = useState(true);
const [sel, setSel] = useState<number | null>(null);
const [dirty, setDirty] = useState(false);
const [deleteArm, setDeleteArm] = useState(0);
// Stock editor (collapsed by default — geometry is set once per roll).
const [stockOpen, setStockOpen] = useState(false);
const [stockDraft, setStockDraft] = useState<LabelStock | null>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const boxesRef = useRef<ElementBox[]>([]);
const dragRef = useRef<{ idx: number; dxMm: number; dyMm: number } | null>(null);
const stock = useMemo(
() => stocks.find((s) => s.id === tpl?.stock_id) ?? stocks[0],
[stocks, tpl?.stock_id]);
const refresh = useCallback(async () => {
try {
setStocks((await LabelListStocks()) as any as LabelStock[]);
setSaved(((await LabelListTemplates()) ?? []) as any as TplInfo[]);
} catch (e: any) { setError(String(e?.message ?? e)); }
}, []);
useEffect(() => {
if (!open) return;
setError(''); setTpl(null); setTplId(0); setSel(null); setDirty(false);
void refresh();
LabelSampleQSOs(5).then((r: any) => setSamples(r ?? [])).catch(() => {});
// The preview resolves <MY*> from the active profile so the address label
// reads like the finished sticker, not like a form.
GetActiveProfile().then((p: any) => setMyVars({
MYCALL: p?.callsign ?? 'MYCALL', MYNAME: p?.op_name ?? p?.operator ?? '',
MYSTREET: p?.my_street ?? '', MYZIP: p?.my_postal_code ?? '', MYCITY: p?.my_city ?? '',
MYCOUNTRY: p?.my_country ?? '',
})).catch(() => setMyVars({ MYCALL: 'MYCALL' }));
}, [open, refresh]);
// Preview variable values: the first sample QSO plays the DX station.
const vars = useMemo(() => {
const q = samples[0];
return {
CALL: q?.callsign ?? 'DL1ABC', NAME: q?.name ?? 'Hans', QTH: q?.qth ?? 'Berlin',
COUNTRY: q?.country ?? 'Germany', VIA: 'DJ5XX',
STREET: 'Funkerstrasse 12', ZIP: '10115', CITY: q?.qth || 'Berlin', STATE: '',
...myVars,
} as Record<string, string>;
}, [samples, myVars]);
// ── canvas ────────────────────────────────────────────────────────────
const scale = useMemo(() => {
if (!stock) return 4;
return Math.min(PREVIEW_MAX_W / stock.w_mm, PREVIEW_MAX_H / stock.h_mm);
}, [stock]);
const paint = useCallback(() => {
const cv = canvasRef.current;
if (!cv || !tpl || !stock) return;
const dpr = window.devicePixelRatio || 1;
cv.width = Math.round(stock.w_mm * scale * dpr);
cv.height = Math.round(stock.h_mm * scale * dpr);
cv.style.width = `${stock.w_mm * scale}px`;
cv.style.height = `${stock.h_mm * scale}px`;
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
boxesRef.current = render(ctx, tpl, stock, { vars, qsos: samples }, scale);
drawMargins(ctx, stock, scale);
// Selection outline, drawn after everything: the editor's own chrome.
if (sel != null && boxesRef.current[sel]) {
const b = boxesRef.current[sel];
ctx.save();
ctx.scale(scale, scale);
ctx.strokeStyle = 'rgba(255,140,0,0.9)';
ctx.lineWidth = 0.3;
ctx.setLineDash([1, 0.8]);
ctx.strokeRect(b.x - 0.6, b.y - 0.6, b.w + 1.2, b.h + 1.2);
ctx.restore();
}
}, [tpl, stock, vars, samples, scale, sel]);
useEffect(() => { paint(); }, [paint]);
const mmFromEvent = (ev: React.MouseEvent): { x: number; y: number } => {
const r = canvasRef.current!.getBoundingClientRect();
return { x: (ev.clientX - r.left) / scale, y: (ev.clientY - r.top) / scale };
};
const onCanvasDown = (ev: React.MouseEvent) => {
if (!tpl) return;
const p = mmFromEvent(ev);
// Topmost element under the pointer wins — iterate backwards.
for (let i = boxesRef.current.length - 1; i >= 0; i--) {
const b = boxesRef.current[i];
if (p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h) {
setSel(i);
dragRef.current = { idx: i, dxMm: p.x - tpl.elements[i].x_mm, dyMm: p.y - tpl.elements[i].y_mm };
return;
}
}
setSel(null);
};
const onCanvasMove = (ev: React.MouseEvent) => {
const d = dragRef.current;
if (!d || !tpl) return;
const p = mmFromEvent(ev);
// Snapped to 0.5 mm: free pixels look precise on screen and print ragged.
const x = Math.round((p.x - d.dxMm) * 2) / 2;
const y = Math.round((p.y - d.dyMm) * 2) / 2;
patchEl(d.idx, { x_mm: x, y_mm: y });
};
const onCanvasUp = () => { dragRef.current = null; };
// ── template edits ────────────────────────────────────────────────────
function patchEl(idx: number, patch: Partial<LabelElement>) {
setTpl((cur) => {
if (!cur) return cur;
const elements = cur.elements.map((e, i) => (i === idx ? { ...e, ...patch } : e));
return { ...cur, elements };
});
setDirty(true);
}
function addElement(e: LabelElement) {
setTpl((cur) => (cur ? { ...cur, elements: [...cur.elements, e] } : cur));
setSel(tpl ? tpl.elements.length : 0);
setDirty(true);
}
function removeSelected() {
if (sel == null) return;
setTpl((cur) => (cur ? { ...cur, elements: cur.elements.filter((_, i) => i !== sel) } : cur));
setSel(null);
setDirty(true);
}
function newTemplate(kind: 'qso' | 'address') {
const s = stocks[0];
if (!s) { setError(t('lbl.noStock')); return; }
setTpl(starterTemplate(kind, s));
setTplId(0);
setTplName(kind === 'qso' ? t('lbl.newQsoName') : t('lbl.newAddrName'));
setSel(null);
setDirty(true);
}
async function openTemplate(info: TplInfo) {
try {
const doc = await LabelGetTemplate(info.id);
setTpl(JSON.parse(doc) as LabelTemplate);
setTplId(info.id);
setTplName(info.name);
setSel(null);
setDirty(false);
} catch (e: any) { setError(String(e?.message ?? e)); }
}
async function save() {
if (!tpl) return;
try {
const id = await LabelSaveTemplate(tplId, tplName.trim() || 'Label', JSON.stringify(tpl), forProfile);
setTplId(id as number);
setDirty(false);
await refresh();
} catch (e: any) { setError(String(e?.message ?? e)); }
}
async function removeTemplate(id: number) {
if (deleteArm !== id) { setDeleteArm(id); window.setTimeout(() => setDeleteArm(0), 2500); return; }
try {
await LabelDeleteTemplate(id);
if (id === tplId) { setTpl(null); setTplId(0); }
await refresh();
} catch (e: any) { setError(String(e?.message ?? e)); }
}
// ── stock editor ──────────────────────────────────────────────────────
async function saveStock() {
if (!stockDraft) return;
try {
await LabelSaveStock(stockDraft as any);
setStockDraft(null);
await refresh();
} catch (e: any) { setError(String(e?.message ?? e)); }
}
if (!open) return null;
const e = sel != null && tpl ? tpl.elements[sel] : undefined;
const numField = (label: string, value: number, set: (v: number) => void, step = 0.5, w = 'w-20') => (
<div className="space-y-0.5">
<Label className="text-[10px] text-muted-foreground">{label}</Label>
<Input type="number" step={step} value={value} className={cn('h-7 text-xs font-mono', w)}
onChange={(ev) => set(parseFloat(ev.target.value) || 0)} />
</div>
);
return (
<div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-6xl h-[92vh] flex flex-col overflow-hidden">
{/* header */}
<div className="flex items-center gap-3 px-4 py-2.5 border-b border-border shrink-0">
<Tag className="size-4 text-primary" />
<span className="font-semibold text-sm">{t('lbl.title')}</span>
<div className="flex-1" />
{tpl && (
<>
<Input className="h-8 w-56 text-sm" value={tplName} onChange={(ev) => { setTplName(ev.target.value); setDirty(true); }}
placeholder={t('lbl.namePh')} />
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<Checkbox checked={forProfile} onCheckedChange={(c) => setForProfile(!!c)} />
{t('lbl.forProfile')}
</label>
<Button size="sm" className="h-8" onClick={save} disabled={!dirty && tplId !== 0}>
{t('lbl.save')}
</Button>
</>
)}
<Button variant="ghost" size="sm" className="h-8" onClick={onClose}><X className="size-4" /></Button>
</div>
{error && <div className="px-4 py-1.5 text-xs text-danger border-b border-border/60">{error}</div>}
<div className="flex-1 min-h-0 flex">
{/* left: saved templates + stocks */}
<div className="w-64 border-r border-border flex flex-col min-h-0 shrink-0">
<div className="p-2 flex gap-1.5">
<Button size="sm" variant="outline" className="h-8 flex-1" onClick={() => newTemplate('qso')}>
<Plus className="size-3.5" /> {t('lbl.newQso')}
</Button>
<Button size="sm" variant="outline" className="h-8 flex-1" onClick={() => newTemplate('address')}>
<Plus className="size-3.5" /> {t('lbl.newAddr')}
</Button>
</div>
<div className="flex-1 overflow-y-auto px-2 pb-2 space-y-1">
{saved.map((s) => (
<div key={s.id}
className={cn('rounded-md border px-2 py-1.5 cursor-pointer text-xs',
s.id === tplId ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted/50')}
onClick={() => void openTemplate(s)}>
<div className="flex items-center gap-1.5">
{s.kind === 'qso' ? <Tag className="size-3 shrink-0 text-muted-foreground" /> : <MapPin className="size-3 shrink-0 text-muted-foreground" />}
<span className="font-medium truncate flex-1">{s.name}</span>
<button type="button" title={t('lbl.setDefault')}
onClick={(ev) => { ev.stopPropagation(); void LabelSetDefaultTemplate(s.id).then(refresh); }}>
<Star className={cn('size-3.5', s.is_default ? 'text-warning fill-warning' : 'text-muted-foreground/40')} />
</button>
<button type="button" title={t('lbl.delete')}
onClick={(ev) => { ev.stopPropagation(); void removeTemplate(s.id); }}>
<Trash2 className={cn('size-3.5', deleteArm === s.id ? 'text-danger' : 'text-muted-foreground/40')} />
</button>
</div>
<div className="text-[10px] text-muted-foreground pl-4">
{s.kind === 'qso' ? t('lbl.kindQso') : t('lbl.kindAddr')} · {s.updated_at}
</div>
</div>
))}
{saved.length === 0 && (
<div className="text-xs text-muted-foreground px-1 py-3">{t('lbl.empty')}</div>
)}
</div>
{/* stocks */}
<div className="border-t border-border p-2 space-y-1.5">
<button type="button" className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground"
onClick={() => setStockOpen((v) => !v)}>
{t('lbl.stocks')} {stockOpen ? '▾' : '▸'}
</button>
{stockOpen && (
<div className="space-y-1.5">
<Select value={String(stockDraft?.id ?? '')} onValueChange={(v) => {
const s = stocks.find((x) => String(x.id) === v);
if (s) setStockDraft({ ...s });
}}>
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder={t('lbl.pickStock')} /></SelectTrigger>
<SelectContent>
{stocks.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
</SelectContent>
</Select>
<div className="flex gap-1.5">
<Button size="sm" variant="outline" className="h-7 text-xs flex-1"
onClick={() => setStockDraft({ name: t('lbl.customStock'), w_mm: 90, h_mm: 29, margin_top_mm: 1.5, margin_right_mm: 3, margin_bottom_mm: 1.5, margin_left_mm: 3, dpi: 300 })}>
<Plus className="size-3" /> {t('lbl.newStock')}
</Button>
{stockDraft?.id ? (
<Button size="sm" variant="ghost" className="h-7 text-xs text-danger"
onClick={() => { void LabelDeleteStock(stockDraft.id!).then(() => { setStockDraft(null); return refresh(); }); }}>
<Trash2 className="size-3" />
</Button>
) : null}
</div>
{stockDraft && (
<div className="space-y-1.5">
<Input className="h-7 text-xs" value={stockDraft.name}
onChange={(ev) => setStockDraft({ ...stockDraft, name: ev.target.value })} />
<div className="grid grid-cols-2 gap-1.5">
{numField(t('lbl.widthMm'), stockDraft.w_mm, (v) => setStockDraft({ ...stockDraft, w_mm: v }), 0.5, 'w-full')}
{numField(t('lbl.heightMm'), stockDraft.h_mm, (v) => setStockDraft({ ...stockDraft, h_mm: v }), 0.5, 'w-full')}
</div>
<div className="grid grid-cols-4 gap-1.5">
{numField('↑', stockDraft.margin_top_mm, (v) => setStockDraft({ ...stockDraft, margin_top_mm: v }), 0.5, 'w-full')}
{numField('→', stockDraft.margin_right_mm, (v) => setStockDraft({ ...stockDraft, margin_right_mm: v }), 0.5, 'w-full')}
{numField('↓', stockDraft.margin_bottom_mm, (v) => setStockDraft({ ...stockDraft, margin_bottom_mm: v }), 0.5, 'w-full')}
{numField('←', stockDraft.margin_left_mm, (v) => setStockDraft({ ...stockDraft, margin_left_mm: v }), 0.5, 'w-full')}
</div>
<Button size="sm" className="h-7 text-xs w-full" onClick={() => void saveStock()}>{t('lbl.saveStock')}</Button>
</div>
)}
</div>
)}
</div>
</div>
{/* centre: preview */}
<div className="flex-1 min-w-0 flex flex-col items-center justify-center bg-muted/30 overflow-auto p-6 gap-3">
{tpl && stock ? (
<>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>{t('lbl.stock')}:</span>
<Select value={String(tpl.stock_id || stock.id)} onValueChange={(v) => {
setTpl({ ...tpl, stock_id: parseInt(v, 10) }); setDirty(true);
}}>
<SelectTrigger className="h-7 text-xs w-72"><SelectValue /></SelectTrigger>
<SelectContent>
{stocks.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
</SelectContent>
</Select>
<span className="font-mono">{stock.w_mm}×{stock.h_mm} mm</span>
</div>
<canvas ref={canvasRef} className="shadow-lg rounded-sm cursor-move"
onMouseDown={onCanvasDown} onMouseMove={onCanvasMove}
onMouseUp={onCanvasUp} onMouseLeave={onCanvasUp} />
<div className="flex items-center gap-1.5">
<Button size="sm" variant="outline" className="h-7 text-xs"
onClick={() => addElement({ type: 'text', x_mm: stock.margin_left_mm, y_mm: stock.h_mm / 2, text: t('lbl.newText'), size_pt: 9 })}>
<Plus className="size-3" /> {t('lbl.addText')}
</Button>
<Button size="sm" variant="outline" className="h-7 text-xs"
onClick={() => addElement({ type: 'line', x_mm: stock.margin_left_mm, y_mm: stock.h_mm / 2, w_mm: stock.w_mm - stock.margin_left_mm - stock.margin_right_mm, thickness_mm: 0.3 })}>
<Plus className="size-3" /> {t('lbl.addLine')}
</Button>
{tpl.kind === 'address' && (
<Button size="sm" variant="outline" className="h-7 text-xs"
onClick={() => addElement({ type: 'addr_block', x_mm: stock.margin_left_mm + 2, y_mm: stock.margin_top_mm + 2, lines: ['<NAME>', '<STREET>', '<ZIP> <CITY>', '<COUNTRY>'], size_pt: 11, line_gap_mm: 1.6 })}>
<Plus className="size-3" /> {t('lbl.addAddr')}
</Button>
)}
{tpl.kind === 'qso' && !tpl.elements.some((x) => x.type === 'qso_table') && (
<Button size="sm" variant="outline" className="h-7 text-xs"
onClick={() => addElement({ type: 'qso_table', x_mm: stock.margin_left_mm, y_mm: stock.margin_top_mm + 7, w_mm: stock.w_mm - stock.margin_left_mm - stock.margin_right_mm, rows_max: 4, row_h_mm: 4, header: true, size_pt: 7.5, columns: TABLE_FIELDS.slice(0, 6).map((c) => ({ ...c })) })}>
<Plus className="size-3" /> {t('lbl.addTable')}
</Button>
)}
{sel != null && (
<Button size="sm" variant="ghost" className="h-7 text-xs text-danger" onClick={removeSelected}>
<Trash2 className="size-3" /> {t('lbl.removeEl')}
</Button>
)}
</div>
</>
) : (
<div className="text-sm text-muted-foreground text-center max-w-sm leading-relaxed">
{t('lbl.intro')}
</div>
)}
</div>
{/* right: properties of the selection */}
{tpl && (
<div className="w-72 border-l border-border overflow-y-auto p-3 space-y-3 shrink-0">
{!e ? (
<div className="text-xs text-muted-foreground leading-relaxed">{t('lbl.selectHint')}</div>
) : (
<>
<div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
{t(`lbl.el_${e.type}` as any)}
</div>
<div className="flex gap-2">
{numField('X mm', e.x_mm, (v) => patchEl(sel!, { x_mm: v }))}
{numField('Y mm', e.y_mm, (v) => patchEl(sel!, { y_mm: v }))}
{(e.type === 'text' || e.type === 'line' || e.type === 'qso_table') &&
numField('W mm', e.w_mm ?? 0, (v) => patchEl(sel!, { w_mm: v }))}
</div>
{e.type === 'text' && (
<>
<div className="space-y-0.5">
<Label className="text-[10px] text-muted-foreground">{t('lbl.text')}</Label>
<Input className="h-7 text-xs" value={e.text ?? ''} onChange={(ev) => patchEl(sel!, { text: ev.target.value })} />
</div>
<VarPicker onPick={(v) => patchEl(sel!, { text: `${e.text ?? ''}<${v}>` })} t={t} />
<div className="flex gap-2 items-end">
{numField('pt', e.size_pt ?? 9, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
<label className="flex items-center gap-1 text-xs cursor-pointer pb-1.5">
<Checkbox checked={!!e.bold} onCheckedChange={(c) => patchEl(sel!, { bold: !!c })} /> B
</label>
<label className="flex items-center gap-1 text-xs italic cursor-pointer pb-1.5">
<Checkbox checked={!!e.italic} onCheckedChange={(c) => patchEl(sel!, { italic: !!c })} /> I
</label>
<Select value={e.align ?? 'left'} onValueChange={(v) => patchEl(sel!, { align: v as any })}>
<SelectTrigger className="h-7 text-xs w-24"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="left">{t('lbl.alignLeft')}</SelectItem>
<SelectItem value="center">{t('lbl.alignCenter')}</SelectItem>
<SelectItem value="right">{t('lbl.alignRight')}</SelectItem>
</SelectContent>
</Select>
</div>
</>
)}
{e.type === 'line' && numField(t('lbl.thickness'), e.thickness_mm ?? 0.3, (v) => patchEl(sel!, { thickness_mm: v }), 0.1)}
{e.type === 'addr_block' && (
<>
<div className="space-y-0.5">
<Label className="text-[10px] text-muted-foreground">{t('lbl.addrLines')}</Label>
<textarea
className="w-full h-28 rounded-md border border-input bg-background px-2 py-1 text-xs font-mono"
value={(e.lines ?? []).join('\n')}
onChange={(ev) => patchEl(sel!, { lines: ev.target.value.split('\n') })} />
<div className="text-[10px] text-muted-foreground">{t('lbl.addrHint')}</div>
</div>
<VarPicker onPick={(v) => patchEl(sel!, { lines: [...(e.lines ?? []), `<${v}>`] })} t={t} />
<div className="flex gap-2">
{numField('pt', e.size_pt ?? 11, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
{numField(t('lbl.lineGap'), e.line_gap_mm ?? 1.5, (v) => patchEl(sel!, { line_gap_mm: v }), 0.1, 'w-20')}
</div>
</>
)}
{e.type === 'qso_table' && (
<>
<div className="flex gap-2">
{numField(t('lbl.rows'), e.rows_max ?? 4, (v) => patchEl(sel!, { rows_max: Math.max(1, Math.round(v)) }), 1, 'w-16')}
{numField(t('lbl.rowH'), e.row_h_mm ?? 4, (v) => patchEl(sel!, { row_h_mm: v }), 0.1, 'w-20')}
{numField('pt', e.size_pt ?? 7.5, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
</div>
<label className="flex items-center gap-1.5 text-xs cursor-pointer">
<Checkbox checked={!!e.header} onCheckedChange={(c) => patchEl(sel!, { header: !!c })} />
{t('lbl.header')}
</label>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground">{t('lbl.columns')}</Label>
{(e.columns ?? []).map((c, ci) => (
<div key={ci} className="flex items-center gap-1">
<Select value={c.field} onValueChange={(v) => {
const f = TABLE_FIELDS.find((x) => x.field === v);
const columns = e.columns!.map((x, i) => (i === ci ? { ...x, field: v, label: f?.label ?? v } : x));
patchEl(sel!, { columns });
}}>
<SelectTrigger className="h-6 text-[11px] flex-1"><SelectValue /></SelectTrigger>
<SelectContent>
{TABLE_FIELDS.map((f) => <SelectItem key={f.field} value={f.field}>{f.label}</SelectItem>)}
</SelectContent>
</Select>
<Input type="number" step={0.5} className="h-6 w-14 text-[11px] font-mono" value={c.w_mm}
onChange={(ev) => {
const columns = e.columns!.map((x, i) => (i === ci ? { ...x, w_mm: parseFloat(ev.target.value) || 1 } : x));
patchEl(sel!, { columns });
}} />
<button type="button" onClick={() => patchEl(sel!, { columns: e.columns!.filter((_, i) => i !== ci) })}>
<Trash2 className="size-3 text-muted-foreground/60" />
</button>
</div>
))}
<Button size="sm" variant="outline" className="h-6 text-[11px] w-full"
onClick={() => patchEl(sel!, { columns: [...(e.columns ?? []), { ...TABLE_FIELDS[0] }] })}>
<Plus className="size-3" /> {t('lbl.addColumn')}
</Button>
</div>
</>
)}
</>
)}
</div>
)}
</div>
</div>
</div>
);
}
// VarPicker inserts a <VARIABLE> — a menu beats remembering the exact spelling.
function VarPicker({ onPick, t }: { onPick: (v: string) => void; t: (k: string) => string }) {
return (
<Select value="" onValueChange={(v) => { if (v) onPick(v); }}>
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder={t('lbl.insertVar')} /></SelectTrigger>
<SelectContent>
{LABEL_VARS.map((v) => <SelectItem key={v} value={v}>{`<${v}>`}</SelectItem>)}
</SelectContent>
</Select>
);
}
@@ -0,0 +1,175 @@
// labelRender draws a label template onto a canvas. It is THE renderer: the
// designer's preview and (later) the pages rasterised into the print PDF both
// come through here, which is what makes the preview trustworthy — there is no
// second implementation to disagree with it.
//
// The canvas is scaled so that 1 mm = `scale` px; print passes dpi/25.4, the
// preview passes whatever fits its box. All layout maths stays in mm.
import type { LabelElement, LabelSample, LabelStock, LabelTemplate } from './labelTypes';
export interface RenderData {
// Variable values for text/address elements (<CALL> → value). Missing keys
// render as the bare <NAME> so the designer can SEE an unresolved variable.
vars: Record<string, string>;
// Rows for the qso_table element.
qsos: LabelSample[];
}
export interface ElementBox { x: number; y: number; w: number; h: number } // mm
const PT_TO_MM = 25.4 / 72;
// resolveVars substitutes <VAR> markers, collapsing to '' only when the value
// is known-empty; unknown markers stay visible on purpose.
export function resolveVars(text: string, vars: Record<string, string>): string {
return text.replace(/<([A-Z_]+)>/g, (m, k) => (k in vars ? vars[k] : m));
}
// render draws the whole label and returns each element's bounding box in mm —
// the editor's hit-testing works off these, so a drag grabs exactly what was
// painted, table rows included.
export function render(
ctx: CanvasRenderingContext2D,
t: LabelTemplate,
stock: LabelStock,
data: RenderData,
scale: number,
): ElementBox[] {
const W = stock.w_mm, H = stock.h_mm;
ctx.save();
ctx.scale(scale, scale);
// The physical label: white, whatever the app theme — this is paper.
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#000';
// The canvas thinks in mm from here on; fonts are set per element in pt and
// drawn with an unscaled-pt trick: setTransform back to px for text quality.
const boxes: ElementBox[] = [];
for (const e of t.elements) {
boxes.push(drawElement(ctx, e, t, data, scale));
}
ctx.restore();
return boxes;
}
// drawMargins paints the unprintable border as a dashed guide — editor only,
// never part of a print rasterisation.
export function drawMargins(ctx: CanvasRenderingContext2D, stock: LabelStock, scale: number): void {
ctx.save();
ctx.scale(scale, scale);
ctx.strokeStyle = 'rgba(80,140,255,0.55)';
ctx.lineWidth = 0.15;
ctx.setLineDash([1.2, 1.2]);
ctx.strokeRect(
stock.margin_left_mm, stock.margin_top_mm,
stock.w_mm - stock.margin_left_mm - stock.margin_right_mm,
stock.h_mm - stock.margin_top_mm - stock.margin_bottom_mm,
);
ctx.restore();
}
function drawText(
ctx: CanvasRenderingContext2D, text: string, xMm: number, yTopMm: number,
wMm: number | undefined, sizePt: number, scale: number,
opts: { bold?: boolean; italic?: boolean; align?: string; face?: string },
): number {
// Text is drawn in PX space (resetting the mm scale) so the browser rasterises
// the font at device resolution instead of scaling a 1-mm-tall glyph up.
const hMm = sizePt * PT_TO_MM;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
// The font is specified in px = (pt → mm) × scale, so a 10 pt line measures
// exactly 10 pt on the printed label whatever the preview zoom is.
ctx.font = `${opts.italic ? 'italic ' : ''}${opts.bold ? 'bold ' : ''}${hMm * scale}px ${opts.face && opts.face.trim() ? opts.face : 'Arial, Helvetica, sans-serif'}`;
ctx.fillStyle = '#000';
ctx.textBaseline = 'top';
let x = xMm * scale;
if (wMm && opts.align === 'center') {
ctx.textAlign = 'center';
x = (xMm + wMm / 2) * scale;
} else if (wMm && opts.align === 'right') {
ctx.textAlign = 'right';
x = (xMm + wMm) * scale;
} else {
ctx.textAlign = 'left';
}
ctx.fillText(text, x, yTopMm * scale);
ctx.restore();
return hMm;
}
function drawElement(
ctx: CanvasRenderingContext2D, e: LabelElement, t: LabelTemplate,
data: RenderData, scale: number,
): ElementBox {
switch (e.type) {
case 'text': {
const size = e.size_pt || 9;
const text = resolveVars(e.text ?? '', data.vars);
drawText(ctx, text, e.x_mm, e.y_mm, e.w_mm, size, scale,
{ bold: e.bold, italic: e.italic, align: e.align, face: t.font });
const h = size * PT_TO_MM * 1.25;
return { x: e.x_mm, y: e.y_mm, w: e.w_mm || Math.max(20, text.length * size * PT_TO_MM * 0.55), h };
}
case 'line': {
const th = e.thickness_mm || 0.3;
ctx.fillStyle = '#000';
ctx.fillRect(e.x_mm, e.y_mm, e.w_mm || 10, th);
// A hairline is a 0.3 mm target nobody can grab; the box pads it.
return { x: e.x_mm, y: e.y_mm - 0.8, w: e.w_mm || 10, h: th + 1.6 };
}
case 'addr_block': {
const size = e.size_pt || 11;
const gap = e.line_gap_mm ?? 1.5;
// Collapse-empty is the point of the block: a missing street must pull
// the city UP, not leave a hole in the middle of an address.
const lines = (e.lines ?? [])
.map((l) => resolveVars(l, data.vars).trim())
.filter((l) => l !== '');
let y = e.y_mm;
let maxW = 0;
for (const l of lines) {
const h = drawText(ctx, l, e.x_mm, y, undefined, size, scale,
{ bold: e.bold, italic: e.italic, face: t.font });
y += h + gap;
maxW = Math.max(maxW, l.length * size * PT_TO_MM * 0.55);
}
return { x: e.x_mm, y: e.y_mm, w: Math.max(20, maxW), h: Math.max(4, y - e.y_mm) };
}
case 'qso_table': {
const cols = e.columns ?? [];
const size = e.size_pt || 7.5;
const rowH = e.row_h_mm || 4;
const wTot = cols.reduce((a, c) => a + c.w_mm, 0);
let y = e.y_mm;
if (e.header) {
let x = e.x_mm;
for (const c of cols) {
drawText(ctx, c.label, x + 0.6, y + (rowH - size * PT_TO_MM) / 2, c.w_mm - 1.2, size, scale,
{ bold: true, align: c.align, face: t.font });
x += c.w_mm;
}
// Rule under the header, not a full grid: on a 29 mm label the grid IS
// the noise.
ctx.fillStyle = '#000';
ctx.fillRect(e.x_mm, y + rowH - 0.25, wTot, 0.25);
y += rowH;
}
const rows = data.qsos.slice(0, e.rows_max || 4);
for (const q of rows) {
let x = e.x_mm;
for (const c of cols) {
const v = String((q as any)[c.field] ?? '');
drawText(ctx, v, x + 0.6, y + (rowH - size * PT_TO_MM) / 2, c.w_mm - 1.2, size, scale,
{ align: c.align, face: t.font });
x += c.w_mm;
}
y += rowH;
}
return { x: e.x_mm, y: e.y_mm, w: wTot, h: y - e.y_mm };
}
}
return { x: e.x_mm, y: e.y_mm, w: 10, h: 4 };
}
@@ -0,0 +1,118 @@
// TypeScript mirror of the label template schema (v1) defined in
// internal/labels/labels.go. Documents cross the Wails boundary as JSON
// strings; these types are the frontend's contract with that schema.
//
// Everything is in MILLIMETRES — pixels only exist inside labelRender, at the
// stock's dpi. See the Go package comment for why.
export interface LabelStock {
id?: number;
name: string;
w_mm: number;
h_mm: number;
margin_top_mm: number;
margin_right_mm: number;
margin_bottom_mm: number;
margin_left_mm: number;
dpi: number;
}
export interface LabelColumn {
field: string;
label: string;
w_mm: number;
align?: 'left' | 'center' | 'right';
}
export interface LabelElement {
type: 'text' | 'line' | 'qso_table' | 'addr_block';
x_mm: number;
y_mm: number;
w_mm?: number;
// text
text?: string;
size_pt?: number;
bold?: boolean;
italic?: boolean;
align?: 'left' | 'center' | 'right';
// line
thickness_mm?: number;
// qso_table
columns?: LabelColumn[];
rows_max?: number;
row_h_mm?: number;
header?: boolean;
// addr_block
lines?: string[];
line_gap_mm?: number;
}
export interface LabelTemplate {
version: 1;
kind: 'qso' | 'address';
name?: string;
stock_id: number;
font?: string;
elements: LabelElement[];
}
export interface LabelSample {
callsign: string; qso_date: string; time_on: string; band: string;
freq: string; mode: string; rst_sent: string; rst_rcvd: string;
name: string; qth: string; country: string;
}
// The QSO-table columns the designer offers, with default widths that fit their
// content at 8 pt — the operator adjusts from there against real data.
export const TABLE_FIELDS: { field: string; label: string; w_mm: number }[] = [
{ field: 'qso_date', label: 'Date', w_mm: 17 },
{ field: 'time_on', label: 'UTC', w_mm: 10 },
{ field: 'band', label: 'Band', w_mm: 10 },
{ field: 'freq', label: 'MHz', w_mm: 13 },
{ field: 'mode', label: 'Mode', w_mm: 11 },
{ field: 'rst_sent', label: 'RST', w_mm: 9 },
{ field: 'rst_rcvd', label: 'RST rx', w_mm: 9 },
];
// The variables a text or address element may carry. Resolution at PRINT time
// uses the real QSO/profile; the designer resolves them against the sample so
// the preview reads like a finished label.
export const LABEL_VARS = [
'CALL', 'NAME', 'QTH', 'COUNTRY', 'VIA',
'STREET', 'ZIP', 'CITY', 'STATE',
'MYCALL', 'MYNAME', 'MYSTREET', 'MYZIP', 'MYCITY', 'MYCOUNTRY',
] as const;
// Starter documents for a fresh template — a usable label, not a blank page:
// an empty canvas asks the operator to invent the feature, a finished-looking
// starter only asks them to adjust it.
export function starterTemplate(kind: 'qso' | 'address', stock: LabelStock): LabelTemplate {
const w = stock.w_mm - stock.margin_left_mm - stock.margin_right_mm;
const x = stock.margin_left_mm;
if (kind === 'qso') {
return {
version: 1, kind, stock_id: stock.id ?? 0,
elements: [
{ type: 'text', x_mm: x, y_mm: stock.margin_top_mm + 1, w_mm: w, text: 'To Radio <CALL>', size_pt: 10, bold: true },
{ type: 'line', x_mm: x, y_mm: stock.margin_top_mm + 6.2, w_mm: w, thickness_mm: 0.3 },
{
type: 'qso_table', x_mm: x, y_mm: stock.margin_top_mm + 7.5, w_mm: w,
rows_max: Math.max(1, Math.min(5, Math.floor((stock.h_mm - stock.margin_top_mm - stock.margin_bottom_mm - 12) / 4))),
row_h_mm: 4, header: true, size_pt: 7.5,
columns: TABLE_FIELDS.slice(0, 6).map((c) => ({ ...c })),
} as LabelElement,
{ type: 'text', x_mm: x, y_mm: stock.h_mm - stock.margin_bottom_mm - 4, w_mm: w, text: 'PSE QSL · 73 de <MYCALL>', size_pt: 8 },
],
};
}
return {
version: 1, kind, stock_id: stock.id ?? 0,
elements: [
{
type: 'addr_block', x_mm: x + 2, y_mm: stock.margin_top_mm + 3,
lines: ['<NAME> · <CALL>', '<STREET>', '<ZIP> <CITY>', '<COUNTRY>'],
size_pt: 11, line_gap_mm: 1.6,
},
],
};
}
+44
View File
@@ -131,6 +131,28 @@ const en: Dict = {
'wk.catWarnTci': 'The CW keyer is set to the radio, but the CAT backend is "{backend}". Pick TCI in Settings → CAT, or another keying engine.',
'wk.tciHint': "Keying goes through the radio's own macro keyer, over the link already open — no WinKeyer and no second serial port. The radio can stop a message but cannot un-type one, so there is no type-ahead correction here.",
'gen.miles': 'Distances in miles', 'gen.milesHint': '(instead of kilometres)',
'tools.labelDesigner': "Label Designer…",
'lbl.title': "Label Designer",
'lbl.newQso': "QSO label", 'lbl.newAddr': "Address label",
'lbl.newQsoName': "QSO label", 'lbl.newAddrName': "Address label",
'lbl.kindQso': "QSO label", 'lbl.kindAddr': "Address label",
'lbl.namePh': "Template name", 'lbl.forProfile': "this profile only",
'lbl.save': "Save", 'lbl.delete': "Delete", 'lbl.setDefault': "Use as the default for its kind",
'lbl.empty': "No label yet — create a QSO label for the card, an address label for the envelope.",
'lbl.intro': "Design the labels for your paper QSL work: the QSO label glued on the card, the address labels for the envelope. Pick a saved design on the left or create one.",
'lbl.stocks': "Label sizes", 'lbl.pickStock': "Pick a size to edit…", 'lbl.newStock': "New size",
'lbl.customStock': "Custom label", 'lbl.saveStock': "Save size", 'lbl.noStock': "Define a label size first.",
'lbl.widthMm': "Width mm", 'lbl.heightMm': "Height mm", 'lbl.stock': "Label",
'lbl.addText': "Text", 'lbl.addLine': "Line", 'lbl.addAddr': "Address block", 'lbl.addTable': "QSO table",
'lbl.removeEl': "Remove element", 'lbl.newText': "New text",
'lbl.selectHint': "Click an element on the label to edit it; drag to move it. Positions are in millimetres, snapped to 0.5 mm.",
'lbl.el_text': "Text", 'lbl.el_line': "Line", 'lbl.el_qso_table': "QSO table", 'lbl.el_addr_block': "Address block",
'lbl.text': "Text", 'lbl.insertVar': "Insert a variable…",
'lbl.alignLeft': "Left", 'lbl.alignCenter': "Center", 'lbl.alignRight': "Right",
'lbl.thickness': "Thickness mm",
'lbl.addrLines': "Address lines", 'lbl.addrHint': "One line each; a line whose variables are empty is skipped.",
'lbl.lineGap': "Gap mm",
'lbl.rows': "Rows", 'lbl.rowH': "Row mm", 'lbl.header': "Header row", 'lbl.columns': "Columns", 'lbl.addColumn': "Add column",
'qslm.thStation': 'Station',
'qslm.qrzTitle': 'Open this callsign on QRZ.com',
'qslm.lotwDetail': 'QSL details',
@@ -632,6 +654,28 @@ const fr: Dict = {
'wk.catWarnTci': "Le manipulateur CW est réglé sur la radio, mais le backend CAT est « {backend} ». Choisissez TCI dans Réglages → CAT, ou un autre moteur de manipulation.",
'wk.tciHint': "La manipulation passe par le keyer à macros de la radio, sur la liaison déjà ouverte — ni WinKeyer ni second port série. La radio sait interrompre un message mais pas en effacer la fin, donc pas de correction en frappe anticipée ici.",
'gen.miles': 'Distances en miles', 'gen.milesHint': '(au lieu des kilomètres)',
'tools.labelDesigner': "Créateur d'étiquettes…",
'lbl.title': "Créateur d'étiquettes",
'lbl.newQso': "Étiquette QSO", 'lbl.newAddr': "Étiquette adresse",
'lbl.newQsoName': "Étiquette QSO", 'lbl.newAddrName': "Étiquette adresse",
'lbl.kindQso': "Étiquette QSO", 'lbl.kindAddr': "Étiquette adresse",
'lbl.namePh': "Nom du modèle", 'lbl.forProfile': "ce profil seulement",
'lbl.save': "Enregistrer", 'lbl.delete': "Supprimer", 'lbl.setDefault': "Modèle par défaut pour son type",
'lbl.empty': "Aucune étiquette — créez une étiquette QSO pour la carte, une étiquette adresse pour l'enveloppe.",
'lbl.intro': "Dessinez les étiquettes de vos QSL papier : l'étiquette QSO collée sur la carte, les étiquettes adresse pour l'enveloppe. Choisissez un modèle à gauche ou créez-en un.",
'lbl.stocks': "Formats d'étiquette", 'lbl.pickStock': "Choisir un format à modifier…", 'lbl.newStock': "Nouveau format",
'lbl.customStock': "Étiquette personnalisée", 'lbl.saveStock': "Enregistrer le format", 'lbl.noStock': "Définissez d'abord un format d'étiquette.",
'lbl.widthMm': "Largeur mm", 'lbl.heightMm': "Hauteur mm", 'lbl.stock': "Étiquette",
'lbl.addText': "Texte", 'lbl.addLine': "Trait", 'lbl.addAddr': "Bloc adresse", 'lbl.addTable': "Tableau QSO",
'lbl.removeEl': "Supprimer l'élément", 'lbl.newText': "Nouveau texte",
'lbl.selectHint': "Cliquez un élément de l'étiquette pour le modifier ; glissez pour le déplacer. Positions en millimètres, au demi-millimètre.",
'lbl.el_text': "Texte", 'lbl.el_line': "Trait", 'lbl.el_qso_table': "Tableau QSO", 'lbl.el_addr_block': "Bloc adresse",
'lbl.text': "Texte", 'lbl.insertVar': "Insérer une variable…",
'lbl.alignLeft': "Gauche", 'lbl.alignCenter': "Centré", 'lbl.alignRight': "Droite",
'lbl.thickness': "Épaisseur mm",
'lbl.addrLines': "Lignes d'adresse", 'lbl.addrHint': "Une ligne par ligne ; une ligne dont les variables sont vides est sautée.",
'lbl.lineGap': "Interligne mm",
'lbl.rows': "Lignes", 'lbl.rowH': "Ligne mm", 'lbl.header': "Ligne d'en-tête", 'lbl.columns': "Colonnes", 'lbl.addColumn': "Ajouter une colonne",
'qslm.thStation': 'Station',
'qslm.qrzTitle': 'Ouvrir cet indicatif sur QRZ.com',
'qslm.lotwDetail': 'Détails QSL',
+19
View File
@@ -21,6 +21,7 @@ import {solar} from '../models';
import {tunergenius} from '../models';
import {webpub} from '../models';
import {winkeyer} from '../models';
import {labels} from '../models';
import {alerts} from '../models';
import {audio} from '../models';
import {contest} from '../models';
@@ -725,6 +726,24 @@ export function KenwoodSendCW(arg1:string):Promise<void>;
export function KenwoodStopCW():Promise<void>;
export function LabelDeleteStock(arg1:number):Promise<void>;
export function LabelDeleteTemplate(arg1:number):Promise<void>;
export function LabelGetTemplate(arg1:number):Promise<string>;
export function LabelListStocks():Promise<Array<labels.Stock>>;
export function LabelListTemplates():Promise<Array<main.LabelTemplateInfo>>;
export function LabelSampleQSOs(arg1:number):Promise<Array<main.LabelSampleQSO>>;
export function LabelSaveStock(arg1:labels.Stock):Promise<number>;
export function LabelSaveTemplate(arg1:number,arg2:string,arg3:string,arg4:boolean):Promise<number>;
export function LabelSetDefaultTemplate(arg1:number):Promise<void>;
export function LaunchAutostartProgram(arg1:string):Promise<main.AutostartLaunchResult>;
export function LaunchAutostartPrograms():Promise<Array<main.AutostartLaunchResult>>;
+36
View File
@@ -1390,6 +1390,42 @@ export function KenwoodStopCW() {
return window['go']['main']['App']['KenwoodStopCW']();
}
export function LabelDeleteStock(arg1) {
return window['go']['main']['App']['LabelDeleteStock'](arg1);
}
export function LabelDeleteTemplate(arg1) {
return window['go']['main']['App']['LabelDeleteTemplate'](arg1);
}
export function LabelGetTemplate(arg1) {
return window['go']['main']['App']['LabelGetTemplate'](arg1);
}
export function LabelListStocks() {
return window['go']['main']['App']['LabelListStocks']();
}
export function LabelListTemplates() {
return window['go']['main']['App']['LabelListTemplates']();
}
export function LabelSampleQSOs(arg1) {
return window['go']['main']['App']['LabelSampleQSOs'](arg1);
}
export function LabelSaveStock(arg1) {
return window['go']['main']['App']['LabelSaveStock'](arg1);
}
export function LabelSaveTemplate(arg1, arg2, arg3, arg4) {
return window['go']['main']['App']['LabelSaveTemplate'](arg1, arg2, arg3, arg4);
}
export function LabelSetDefaultTemplate(arg1) {
return window['go']['main']['App']['LabelSetDefaultTemplate'](arg1);
}
export function LaunchAutostartProgram(arg1) {
return window['go']['main']['App']['LaunchAutostartProgram'](arg1);
}
+89
View File
@@ -1617,6 +1617,39 @@ export namespace kpa {
}
export namespace labels {
export class Stock {
id?: number;
name: string;
w_mm: number;
h_mm: number;
margin_top_mm: number;
margin_right_mm: number;
margin_bottom_mm: number;
margin_left_mm: number;
dpi: number;
static createFrom(source: any = {}) {
return new Stock(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.w_mm = source["w_mm"];
this.h_mm = source["h_mm"];
this.margin_top_mm = source["margin_top_mm"];
this.margin_right_mm = source["margin_right_mm"];
this.margin_bottom_mm = source["margin_bottom_mm"];
this.margin_left_mm = source["margin_left_mm"];
this.dpi = source["dpi"];
}
}
}
export namespace lookup {
export class Result {
@@ -2936,6 +2969,62 @@ export namespace main {
this.samples = source["samples"];
}
}
export class LabelSampleQSO {
callsign: string;
qso_date: string;
time_on: string;
band: string;
freq: string;
mode: string;
rst_sent: string;
rst_rcvd: string;
name: string;
qth: string;
country: string;
static createFrom(source: any = {}) {
return new LabelSampleQSO(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.callsign = source["callsign"];
this.qso_date = source["qso_date"];
this.time_on = source["time_on"];
this.band = source["band"];
this.freq = source["freq"];
this.mode = source["mode"];
this.rst_sent = source["rst_sent"];
this.rst_rcvd = source["rst_rcvd"];
this.name = source["name"];
this.qth = source["qth"];
this.country = source["country"];
}
}
export class LabelTemplateInfo {
id: number;
name: string;
kind: string;
stock_id: number;
profile_id?: number;
is_default: boolean;
updated_at: string;
static createFrom(source: any = {}) {
return new LabelTemplateInfo(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.kind = source["kind"];
this.stock_id = source["stock_id"];
this.profile_id = source["profile_id"];
this.is_default = source["is_default"];
this.updated_at = source["updated_at"];
}
}
export class ModePreset {
name: string;
default_rst_sent?: string;
@@ -0,0 +1,30 @@
-- Label designer: printable labels for paper QSL work.
--
-- Two tables because the two things have different lifetimes. A STOCK is the
-- physical roll in the printer (width, height, margins) — one per label size,
-- shared by every design printed on it. A TEMPLATE is one design (what goes on
-- the label) and points at the stock it was drawn for. Deleting a design must
-- never take the roll definition of the other designs with it.
--
-- kind separates the two families the operator designs: 'qso' (the label glued
-- on the QSL card, with its repeating QSO table) and 'address' (destination or
-- return address). is_default is per (kind, profile scope) — printing wants
-- "the QSO label" and "the address label" without asking every time.
CREATE TABLE label_stocks (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
json TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
CREATE TABLE label_templates (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
kind TEXT NOT NULL,
profile_id INTEGER REFERENCES station_profiles(id) ON DELETE SET NULL,
stock_id INTEGER REFERENCES label_stocks(id) ON DELETE SET NULL,
json TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
+2
View File
@@ -51,6 +51,8 @@ var settingsTables = []string{
"operating_stations_new",
"award_references",
"qsl_templates",
"label_stocks",
"label_templates",
"cluster_servers",
"integrations_udp",
"callsign_cache",
+194
View File
@@ -0,0 +1,194 @@
// Package labels holds the label designer's data model: the printable labels
// an operator sticks on a QSL card (the QSO table) or an envelope (addresses).
//
// Everything is measured in MILLIMETRES. Label stock is sold in mm (a Brother
// DK-11201 is 29×90), printer margins are quoted in mm, and an operator lining
// a design up against a physical label thinks in mm — pixels only exist at
// render time, where the frontend rasterises at the stock's dpi. Storing mm
// keeps a template meaningful if it is ever printed at another resolution.
//
// The document is deliberately much simpler than the QSL card designer's: a
// label is monochrome text on a small sticker, so there are no photos, no
// effects, no presets — four element types and a geometry.
package labels
import (
"encoding/json"
"fmt"
"strings"
)
// Stock is one physical label size — the roll in the printer. Designs point at
// a stock rather than embedding the geometry so that changing "my printer's
// margins are actually 2 mm" fixes every design at once.
type Stock struct {
ID int64 `json:"id,omitempty"`
Name string `json:"name"`
WMm float64 `json:"w_mm"`
HMm float64 `json:"h_mm"`
// Margins are the unprintable border, in mm from each edge.
MarginTop float64 `json:"margin_top_mm"`
MarginRight float64 `json:"margin_right_mm"`
MarginBottom float64 `json:"margin_bottom_mm"`
MarginLeft float64 `json:"margin_left_mm"`
DPI int `json:"dpi"`
}
// BuiltinStocks are the label sizes seeded on first run — the common Brother DK
// rolls (the QL family is what prompted the feature) plus a 62 mm continuous
// strip. Ordinary rows once seeded: an operator with different margins edits
// them like any stock.
func BuiltinStocks() []Stock {
m := func(name string, w, h float64) Stock {
return Stock{Name: name, WMm: w, HMm: h,
MarginTop: 1.5, MarginRight: 3, MarginBottom: 1.5, MarginLeft: 3, DPI: 300}
}
return []Stock{
m("Brother DK-11201 · 29×90 mm (address)", 90, 29),
m("Brother DK-11202 · 62×100 mm (shipping)", 100, 62),
m("Brother DK-11208 · 38×90 mm (large address)", 90, 38),
m("Brother DK-22205 · 62 mm continuous (cut 100 mm)", 100, 62),
}
}
// Element is one thing drawn on the label. Type selects which fields matter:
//
// text X/Y/W, Text (with <VARIABLES>), Size, Bold, Align
// line X/Y/W, Thickness — a horizontal rule
// qso_table X/Y/W, Columns, RowsMax, RowH, Header — the repeating QSO block
// addr_block X/Y, Lines, Size, Bold, LineGap — address lines, blanks collapsed
//
// One struct with optional fields rather than a type per element: the document
// crosses the Wails boundary as JSON and the frontend edits it in place, and a
// closed union would buy safety here at the price of a parallel hierarchy on
// both sides of that boundary.
type Element struct {
Type string `json:"type"`
XMm float64 `json:"x_mm"`
YMm float64 `json:"y_mm"`
WMm float64 `json:"w_mm,omitempty"`
// text
Text string `json:"text,omitempty"`
SizePt float64 `json:"size_pt,omitempty"`
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
Align string `json:"align,omitempty"` // left | center | right
// line
ThicknessMm float64 `json:"thickness_mm,omitempty"`
// qso_table
Columns []Column `json:"columns,omitempty"`
RowsMax int `json:"rows_max,omitempty"`
RowHMm float64 `json:"row_h_mm,omitempty"`
Header bool `json:"header,omitempty"`
// addr_block
Lines []string `json:"lines,omitempty"`
LineGap float64 `json:"line_gap_mm,omitempty"`
}
// Column is one column of the QSO table. Field names the QSO field (the same
// lower-case keys the grids use: qso_date, time_on, band, freq, mode, rst_sent,
// rst_rcvd, …); Label is the printed header.
type Column struct {
Field string `json:"field"`
Label string `json:"label"`
WMm float64 `json:"w_mm"`
Align string `json:"align,omitempty"`
}
// Template is one label design.
type Template struct {
Version int `json:"version"`
Kind string `json:"kind"` // qso | address
Name string `json:"name,omitempty"`
StockID int64 `json:"stock_id"`
FontName string `json:"font,omitempty"` // one face for the whole label; "" = the renderer's default
Elements []Element `json:"elements"`
}
// Parse decodes a template document.
func Parse(doc []byte) (Template, error) {
var t Template
if err := json.Unmarshal(doc, &t); err != nil {
return t, fmt.Errorf("label template: %w", err)
}
return t, nil
}
// Encode is the inverse of Parse.
func Encode(t Template) ([]byte, error) { return json.MarshalIndent(t, "", " ") }
// Validate rejects a document that could not be rendered or printed sensibly.
// Geometry beyond the stock is NOT an error — the editor lets an element be
// dragged around freely and clips at render time — but nonsense that would make
// rendering undefined (unknown types, absurd sizes) is refused at save.
func Validate(t Template) error {
if t.Version != 1 {
return fmt.Errorf("unsupported label template version %d", t.Version)
}
if t.Kind != "qso" && t.Kind != "address" {
return fmt.Errorf("unknown label kind %q", t.Kind)
}
if len(t.Elements) == 0 {
return fmt.Errorf("the label has no elements")
}
if len(t.Elements) > 64 {
return fmt.Errorf("too many elements (%d)", len(t.Elements))
}
for i, e := range t.Elements {
switch e.Type {
case "text":
if strings.TrimSpace(e.Text) == "" {
return fmt.Errorf("element %d: empty text", i+1)
}
case "line":
if e.WMm <= 0 {
return fmt.Errorf("element %d: a line needs a width", i+1)
}
case "qso_table":
if len(e.Columns) == 0 {
return fmt.Errorf("element %d: the QSO table has no columns", i+1)
}
if e.RowsMax < 1 || e.RowsMax > 20 {
return fmt.Errorf("element %d: rows must be 1-20", i+1)
}
for _, c := range e.Columns {
if strings.TrimSpace(c.Field) == "" || c.WMm <= 0 {
return fmt.Errorf("element %d: every column needs a field and a width", i+1)
}
}
case "addr_block":
if len(e.Lines) == 0 {
return fmt.Errorf("element %d: the address block has no lines", i+1)
}
default:
return fmt.Errorf("element %d: unknown type %q", i+1, e.Type)
}
if e.SizePt < 0 || e.SizePt > 72 {
return fmt.Errorf("element %d: font size out of range", i+1)
}
}
return nil
}
// ValidStock rejects geometry no label printer produces.
func ValidStock(s Stock) error {
if strings.TrimSpace(s.Name) == "" {
return fmt.Errorf("the stock needs a name")
}
if s.WMm < 10 || s.WMm > 300 || s.HMm < 6 || s.HMm > 300 {
return fmt.Errorf("label size out of range (10-300 mm wide, 6-300 mm high)")
}
for _, m := range []float64{s.MarginTop, s.MarginRight, s.MarginBottom, s.MarginLeft} {
if m < 0 || m*2 >= s.HMm || m*2 >= s.WMm {
return fmt.Errorf("margins leave no printable area")
}
}
if s.DPI != 0 && (s.DPI < 72 || s.DPI > 1200) {
return fmt.Errorf("dpi out of range")
}
return nil
}
+252
View File
@@ -0,0 +1,252 @@
package labels
import (
"context"
"database/sql"
"fmt"
"time"
)
// Record is one stored template row; JSON holds the Template document.
type Record struct {
ID int64 `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
ProfileID *int64 `json:"profile_id,omitempty"`
StockID *int64 `json:"stock_id,omitempty"`
JSON string `json:"json"`
IsDefault bool `json:"is_default"`
UpdatedAt time.Time `json:"updated_at"`
}
// Repo accesses the label_stocks and label_templates tables. Same shape as the
// QSL template repo it is modelled on — the label designer is that feature's
// smaller sibling and the storage questions were settled there.
type Repo struct{ db *sql.DB }
func NewRepo(db *sql.DB) *Repo { return &Repo{db: db} }
// ── stocks ──────────────────────────────────────────────────────────────
// Stocks lists every stored label stock, oldest first (the seeded Brother rolls
// keep their familiar order at the top).
func (r *Repo) Stocks(ctx context.Context) ([]Stock, error) {
rows, err := r.db.QueryContext(ctx, `SELECT id, json FROM label_stocks ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Stock
for rows.Next() {
var id int64
var doc string
if err := rows.Scan(&id, &doc); err != nil {
return nil, err
}
var s Stock
if err := parseStock(doc, &s); err != nil {
continue // one corrupt row must not hide the rest
}
s.ID = id
out = append(out, s)
}
return out, rows.Err()
}
// SaveStock upserts one stock (ID 0 creates) and writes the id back.
func (r *Repo) SaveStock(ctx context.Context, s *Stock) error {
if err := ValidStock(*s); err != nil {
return err
}
doc, err := encodeStock(*s)
if err != nil {
return err
}
now := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
if s.ID == 0 {
res, err := r.db.ExecContext(ctx,
`INSERT INTO label_stocks (name, json, created_at, updated_at) VALUES (?,?,?,?)`,
s.Name, doc, now, now)
if err != nil {
return fmt.Errorf("insert stock: %w", err)
}
s.ID, _ = res.LastInsertId()
return nil
}
_, err = r.db.ExecContext(ctx,
`UPDATE label_stocks SET name = ?, json = ?, updated_at = ? WHERE id = ?`,
s.Name, doc, now, s.ID)
return err
}
// DeleteStock removes a stock. Templates pointing at it keep their design and
// fall back to "pick a stock" in the editor (the FK nulls the reference).
func (r *Repo) DeleteStock(ctx context.Context, id int64) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM label_stocks WHERE id = ?`, id)
return err
}
// SeedStocks inserts the builtin rolls when the table is empty — first run, or
// an operator who deleted everything and wants the presets back gets them by
// emptying the table.
func (r *Repo) SeedStocks(ctx context.Context) error {
var n int
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM label_stocks`).Scan(&n); err != nil {
return err
}
if n > 0 {
return nil
}
for _, s := range BuiltinStocks() {
st := s
if err := r.SaveStock(ctx, &st); err != nil {
return err
}
}
return nil
}
// ── templates ───────────────────────────────────────────────────────────
const tplCols = `id, name, kind, profile_id, stock_id, json, is_default, updated_at`
// ListFor returns the templates visible to a profile (its own plus shared),
// defaults first.
func (r *Repo) ListFor(ctx context.Context, profileID int64) ([]Record, error) {
rows, err := r.db.QueryContext(ctx, `SELECT `+tplCols+` FROM label_templates
WHERE profile_id = ? OR profile_id IS NULL
ORDER BY is_default DESC, id DESC`, profileID)
if err != nil {
return nil, err
}
return scanRecords(rows)
}
// List returns every template (no active profile yet).
func (r *Repo) List(ctx context.Context) ([]Record, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT `+tplCols+` FROM label_templates ORDER BY is_default DESC, id DESC`)
if err != nil {
return nil, err
}
return scanRecords(rows)
}
// Get returns one template.
func (r *Repo) Get(ctx context.Context, id int64) (Record, error) {
row := r.db.QueryRowContext(ctx, `SELECT `+tplCols+` FROM label_templates WHERE id = ?`, id)
return scanRecord(row)
}
// Save upserts a template (ID 0 creates); the id is written back.
func (r *Repo) Save(ctx context.Context, rec *Record) error {
if rec.Name == "" {
return fmt.Errorf("template name required")
}
now := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
if rec.ID == 0 {
res, err := r.db.ExecContext(ctx, `INSERT INTO label_templates
(name, kind, profile_id, stock_id, json, is_default, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?)`,
rec.Name, rec.Kind, nullID(rec.ProfileID), nullID(rec.StockID), rec.JSON,
boolInt(rec.IsDefault), now, now)
if err != nil {
return fmt.Errorf("insert label template: %w", err)
}
rec.ID, _ = res.LastInsertId()
return nil
}
_, err := r.db.ExecContext(ctx, `UPDATE label_templates
SET name = ?, kind = ?, profile_id = ?, stock_id = ?, json = ?, updated_at = ?
WHERE id = ?`,
rec.Name, rec.Kind, nullID(rec.ProfileID), nullID(rec.StockID), rec.JSON, now, rec.ID)
return err
}
// Delete removes a template.
func (r *Repo) Delete(ctx context.Context, id int64) error {
_, err := r.db.ExecContext(ctx, `DELETE FROM label_templates WHERE id = ?`, id)
return err
}
// SetDefault marks one template as the default FOR ITS KIND within its profile
// scope: printing asks for "the QSO label" and "the address label" separately,
// so the two defaults must not compete.
func (r *Repo) SetDefault(ctx context.Context, id int64) error {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() //nolint:errcheck
var kind string
var profileID sql.NullInt64
if err := tx.QueryRowContext(ctx,
`SELECT kind, profile_id FROM label_templates WHERE id = ?`, id).Scan(&kind, &profileID); err != nil {
return err
}
if profileID.Valid {
_, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 0
WHERE kind = ? AND (profile_id = ? OR profile_id IS NULL)`, kind, profileID.Int64)
} else {
_, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 0 WHERE kind = ?`, kind)
}
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 1 WHERE id = ?`, id); err != nil {
return err
}
return tx.Commit()
}
// ── scanning helpers ────────────────────────────────────────────────────
type rowScanner interface{ Scan(dest ...any) error }
func scanRecord(row rowScanner) (Record, error) {
var rec Record
var pid, sid sql.NullInt64
var def int
var updated string
if err := row.Scan(&rec.ID, &rec.Name, &rec.Kind, &pid, &sid, &rec.JSON, &def, &updated); err != nil {
return rec, err
}
if pid.Valid {
v := pid.Int64
rec.ProfileID = &v
}
if sid.Valid {
v := sid.Int64
rec.StockID = &v
}
rec.IsDefault = def != 0
rec.UpdatedAt, _ = time.Parse(time.RFC3339, updated)
return rec, nil
}
func scanRecords(rows *sql.Rows) ([]Record, error) {
defer rows.Close()
var out []Record
for rows.Next() {
rec, err := scanRecord(rows)
if err != nil {
return nil, err
}
out = append(out, rec)
}
return out, rows.Err()
}
func nullID(p *int64) any {
if p == nil || *p == 0 {
return nil
}
return *p
}
func boolInt(b bool) int {
if b {
return 1
}
return 0
}
+13
View File
@@ -0,0 +1,13 @@
package labels
import "encoding/json"
// The stock row stores its geometry as JSON so adding a field never needs a
// migration; the name is duplicated into its own column for listing.
func parseStock(doc string, s *Stock) error { return json.Unmarshal([]byte(doc), s) }
func encodeStock(s Stock) (string, error) {
s.ID = 0 // the row id is authoritative; never persist a stale copy inside the blob
b, err := json.Marshal(s)
return string(b), err
}