Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d7633484b | ||
|
|
5ee0ade54b | ||
|
|
e637f0814d | ||
|
|
1a169fdb4f | ||
|
|
3dc31697cd | ||
|
|
242a68080a | ||
|
|
8c7e1c1a3d | ||
|
|
47ddbed665 | ||
|
|
fd7ae77a61 | ||
|
|
3e794f57e0 | ||
|
|
30f74583ff | ||
|
|
f7b9aa2181 | ||
|
|
766b0f95a4 | ||
|
|
8bc4ed68d4 | ||
|
|
d534825e92 | ||
|
|
08d6492df1 | ||
|
|
a156b6ad10 | ||
|
|
3bb92f79b2 | ||
|
|
65cae0d822 |
@@ -44,6 +44,7 @@ import (
|
|||||||
"hamlog/internal/gridcache"
|
"hamlog/internal/gridcache"
|
||||||
"hamlog/internal/integrations/udp"
|
"hamlog/internal/integrations/udp"
|
||||||
"hamlog/internal/kpa"
|
"hamlog/internal/kpa"
|
||||||
|
"hamlog/internal/labels"
|
||||||
"hamlog/internal/lookup"
|
"hamlog/internal/lookup"
|
||||||
"hamlog/internal/lotwusers"
|
"hamlog/internal/lotwusers"
|
||||||
"hamlog/internal/netctl"
|
"hamlog/internal/netctl"
|
||||||
@@ -402,6 +403,7 @@ const (
|
|||||||
|
|
||||||
keyExtLoTWTQSLPath = "extsvc.lotw.tqsl_path"
|
keyExtLoTWTQSLPath = "extsvc.lotw.tqsl_path"
|
||||||
keyExtLoTWStationLoc = "extsvc.lotw.station_location"
|
keyExtLoTWStationLoc = "extsvc.lotw.station_location"
|
||||||
|
keyExtLoTWQSLDetail = "extsvc.lotw.qsl_detail" // ask LoTW for the QSL dates and station details (an order of magnitude slower)
|
||||||
keyExtLoTWAllCalls = "extsvc.lotw.download_all_calls" // download confirmations for EVERY call on the account, not just this profile's
|
keyExtLoTWAllCalls = "extsvc.lotw.download_all_calls" // download confirmations for EVERY call on the account, not just this profile's
|
||||||
keyExtLoTWForceCall = "extsvc.lotw.force_station_callsign" // override STATION_CALLSIGN at sign time (e.g. F4BPO/P on the F4BPO cert)
|
keyExtLoTWForceCall = "extsvc.lotw.force_station_callsign" // override STATION_CALLSIGN at sign time (e.g. F4BPO/P on the F4BPO cert)
|
||||||
keyExtLoTWKeyPassword = "extsvc.lotw.key_password"
|
keyExtLoTWKeyPassword = "extsvc.lotw.key_password"
|
||||||
@@ -734,6 +736,7 @@ type App struct {
|
|||||||
uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened
|
uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened
|
||||||
awardRefs *awardref.Repo
|
awardRefs *awardref.Repo
|
||||||
qslTemplates *qslcard.Repo
|
qslTemplates *qslcard.Repo
|
||||||
|
labelRepo *labels.Repo // label designer (stocks + templates)
|
||||||
operating *operating.Repo
|
operating *operating.Repo
|
||||||
udp *udp.Manager
|
udp *udp.Manager
|
||||||
udpRepo *udp.Repo
|
udpRepo *udp.Repo
|
||||||
@@ -1184,6 +1187,7 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
a.awardRefs = awardref.NewRepo(conn)
|
a.awardRefs = awardref.NewRepo(conn)
|
||||||
a.qslTemplates = qslcard.NewRepo(conn)
|
a.qslTemplates = qslcard.NewRepo(conn)
|
||||||
|
a.labelRepo = labels.NewRepo(conn)
|
||||||
a.migrateAwardDefs() // upgrade legacy award definitions (enable + new fields)
|
a.migrateAwardDefs() // upgrade legacy award definitions (enable + new fields)
|
||||||
a.seedBuiltinReferences() // first-run: populate built-in award reference lists
|
a.seedBuiltinReferences() // first-run: populate built-in award reference lists
|
||||||
a.mirrorAwards() // keep <data>/awards/*.json in step with the database
|
a.mirrorAwards() // keep <data>/awards/*.json in step with the database
|
||||||
@@ -2123,6 +2127,21 @@ func (a *App) saveWindowState() {
|
|||||||
// position — which options can't express — remains, and it is set here while the
|
// position — which options can't express — remains, and it is set here while the
|
||||||
// window is still hidden, so there is no visible jump. Nothing to do for a
|
// window is still hidden, so there is no visible jump. Nothing to do for a
|
||||||
// maximised or first-run window.
|
// maximised or first-run window.
|
||||||
|
// moveWindowTo places the window at an ABSOLUTE desktop coordinate — the same
|
||||||
|
// coordinate system WindowGetPosition reports and window.json stores.
|
||||||
|
//
|
||||||
|
// Wails' WindowSetPosition is relative to the current monitor's work area (see
|
||||||
|
// windowpos_windows.go), so on a monitor left of the primary one it added that
|
||||||
|
// monitor's negative origin to an already-absolute value and the window walked
|
||||||
|
// one screen further off the desktop at every launch. Fall back to it only when
|
||||||
|
// we cannot place the window ourselves — on the primary monitor the two agree.
|
||||||
|
func (a *App) moveWindowTo(x, y int) {
|
||||||
|
if setWindowPosAbsolute(x, y) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wruntime.WindowSetPosition(a.ctx, x, y)
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) restoreWindowPosition() {
|
func (a *App) restoreWindowPosition() {
|
||||||
if a.ctx == nil {
|
if a.ctx == nil {
|
||||||
return
|
return
|
||||||
@@ -2150,7 +2169,7 @@ func (a *App) restoreWindowPosition() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
wruntime.WindowUnmaximise(a.ctx)
|
wruntime.WindowUnmaximise(a.ctx)
|
||||||
wruntime.WindowSetPosition(a.ctx, ws.X, ws.Y)
|
a.moveWindowTo(ws.X, ws.Y)
|
||||||
wruntime.WindowMaximise(a.ctx)
|
wruntime.WindowMaximise(a.ctx)
|
||||||
gx, gy := wruntime.WindowGetPosition(a.ctx)
|
gx, gy := wruntime.WindowGetPosition(a.ctx)
|
||||||
applog.Printf("window: re-maximised at the saved corner — now at %d,%d", gx, gy)
|
applog.Printf("window: re-maximised at the saved corner — now at %d,%d", gx, gy)
|
||||||
@@ -2178,10 +2197,13 @@ func (a *App) restoreWindowPosition() {
|
|||||||
}
|
}
|
||||||
applog.Printf("window: saved position %d,%d is off every monitor (%s) — moved to %d,%d",
|
applog.Printf("window: saved position %d,%d is off every monitor (%s) — moved to %d,%d",
|
||||||
ws.X, ws.Y, describeMonitors(monitorRects()), nx, ny)
|
ws.X, ws.Y, describeMonitors(monitorRects()), nx, ny)
|
||||||
wruntime.WindowSetPosition(a.ctx, nx, ny)
|
a.moveWindowTo(nx, ny)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
wruntime.WindowSetPosition(a.ctx, ws.X, ws.Y)
|
a.moveWindowTo(ws.X, ws.Y)
|
||||||
|
if gx, gy := wruntime.WindowGetPosition(a.ctx); gx != ws.X || gy != ws.Y {
|
||||||
|
applog.Printf("window: asked for %d,%d and the window reports %d,%d", ws.X, ws.Y, gx, gy)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// onSomeMonitor reports whether a window at these coordinates would land on the
|
// onSomeMonitor reports whether a window at these coordinates would land on the
|
||||||
@@ -7233,7 +7255,9 @@ func (a *App) SetCompactMode(on bool) {
|
|||||||
wruntime.WindowSetMinSize(a.ctx, normalMinW, normalMinH)
|
wruntime.WindowSetMinSize(a.ctx, normalMinW, normalMinH)
|
||||||
if a.preCompactValid {
|
if a.preCompactValid {
|
||||||
wruntime.WindowSetSize(a.ctx, a.preCompactW, a.preCompactH)
|
wruntime.WindowSetSize(a.ctx, a.preCompactW, a.preCompactH)
|
||||||
wruntime.WindowSetPosition(a.ctx, a.preCompactX, a.preCompactY)
|
// Absolute, like the capture — see moveWindowTo. Leaving compact mode on a
|
||||||
|
// monitor left of the primary one moved the window a screen further out.
|
||||||
|
a.moveWindowTo(a.preCompactX, a.preCompactY)
|
||||||
if a.preCompactMax {
|
if a.preCompactMax {
|
||||||
wruntime.WindowMaximise(a.ctx)
|
wruntime.WindowMaximise(a.ctx)
|
||||||
}
|
}
|
||||||
@@ -11305,11 +11329,19 @@ func (a *App) runManualUpload(svc extsvc.Service, ids []int64, cfg extsvc.Extern
|
|||||||
}
|
}
|
||||||
res, err := extsvc.UploadLoTW(ctx, cfg.LoTW, "", strings.Join(recs, "\n"))
|
res, err := extsvc.UploadLoTW(ctx, cfg.LoTW, "", strings.Join(recs, "\n"))
|
||||||
if err != nil || !res.OK {
|
if err != nil || !res.OK {
|
||||||
msg := res.Message
|
// The DETAIL wins over the error string. UploadLoTW returns both: a
|
||||||
if err != nil {
|
// terse error ("no QSOs processed") and a Message carrying TQSL's own
|
||||||
|
// account of what happened to the contacts ("…already uploaded", "…out
|
||||||
|
// of date range"). Taking the error whenever there was one threw the
|
||||||
|
// answer away and showed the operator the half that explains nothing.
|
||||||
|
msg := strings.TrimSpace(res.Message)
|
||||||
|
if msg == "" && err != nil {
|
||||||
msg = err.Error()
|
msg = err.Error()
|
||||||
|
} else if err != nil && !strings.Contains(msg, err.Error()) {
|
||||||
|
msg = msg + " (" + err.Error() + ")"
|
||||||
}
|
}
|
||||||
emit("LoTW upload failed: " + msg)
|
emit("LoTW upload failed: " + msg)
|
||||||
|
emit(" The station location OpsLog signs with must match the callsign on these contacts, and their dates must fall inside the certificate's validity — TQSL refuses the whole batch otherwise.")
|
||||||
// The qslmgr:log console is only visible in the QSL Manager — a failure
|
// The qslmgr:log console is only visible in the QSL Manager — a failure
|
||||||
// triggered from the Recent QSOs right-click was completely silent, which
|
// triggered from the Recent QSOs right-click was completely silent, which
|
||||||
// read as "send to LoTW does nothing". Surface it as a toast too.
|
// read as "send to LoTW does nothing". Surface it as a toast too.
|
||||||
@@ -11547,6 +11579,10 @@ func (a *App) runManualUpload(svc extsvc.Service, ids []int64, cfg extsvc.Extern
|
|||||||
// with award-style NEW flags computed against the log's prior confirmations.
|
// with award-style NEW flags computed against the log's prior confirmations.
|
||||||
type ConfirmationItem struct {
|
type ConfirmationItem struct {
|
||||||
Callsign string `json:"callsign"`
|
Callsign string `json:"callsign"`
|
||||||
|
// Station is the callsign the QSO was made UNDER, which the download can now
|
||||||
|
// span ("All my callsigns"): a list mixing F4BPO, F4BPO/P and TM2Q says
|
||||||
|
// nothing useful unless each line says which of them it belongs to.
|
||||||
|
Station string `json:"station"`
|
||||||
QSODate string `json:"qso_date"` // ISO UTC
|
QSODate string `json:"qso_date"` // ISO UTC
|
||||||
Band string `json:"band"`
|
Band string `json:"band"`
|
||||||
Mode string `json:"mode"`
|
Mode string `json:"mode"`
|
||||||
@@ -12097,6 +12133,16 @@ func manualRefFor(existing, code string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetLoTWQSLDetail reports whether the download asks LoTW for the QSL detail.
|
||||||
|
func (a *App) GetLoTWQSLDetail() bool {
|
||||||
|
return a.settingOr(keyExtLoTWQSLDetail, "") == "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLoTWQSLDetail stores that choice.
|
||||||
|
func (a *App) SetLoTWQSLDetail(on bool) {
|
||||||
|
a.setSetting(keyExtLoTWQSLDetail, map[bool]string{true: "1", false: "0"}[on])
|
||||||
|
}
|
||||||
|
|
||||||
// GetLoTWDownloadAllCalls reports whether the LoTW download ignores the
|
// GetLoTWDownloadAllCalls reports whether the LoTW download ignores the
|
||||||
// profile's own call and pulls every callsign on the account.
|
// profile's own call and pulls every callsign on the account.
|
||||||
func (a *App) GetLoTWDownloadAllCalls() bool {
|
func (a *App) GetLoTWDownloadAllCalls() bool {
|
||||||
@@ -12215,7 +12261,14 @@ func (a *App) runDownloadConfirmations(ctx context.Context, svc extsvc.Service,
|
|||||||
// The report arrives over minutes, and a window that says nothing while it
|
// The report arrives over minutes, and a window that says nothing while it
|
||||||
// does is indistinguishable from one that has hung — which is what it was
|
// does is indistinguishable from one that has hung — which is what it was
|
||||||
// being reported as. Every half-megabyte, say how much has landed.
|
// being reported as. Every half-megabyte, say how much has landed.
|
||||||
adifText, err := extsvc.DownloadLoTWConfirmations(ctx, nil, cfg.LoTW, sinceDate, ownCall, emit)
|
// Adding the QSOs LoTW knows and we do not is the one job that needs the
|
||||||
|
// slow report: without the detail those records would come in with no
|
||||||
|
// grid, state or county, and nothing else would ever fill them.
|
||||||
|
detail := addNotFound || a.settingOr(keyExtLoTWQSLDetail, "") == "1"
|
||||||
|
if detail {
|
||||||
|
emit("Asking for the QSL details too — LoTW takes considerably longer to build that report.")
|
||||||
|
}
|
||||||
|
adifText, err := extsvc.DownloadLoTWConfirmations(ctx, nil, cfg.LoTW, sinceDate, ownCall, detail, emit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
emit("Download failed: " + err.Error())
|
emit("Download failed: " + err.Error())
|
||||||
done(matched, total)
|
done(matched, total)
|
||||||
@@ -12319,6 +12372,7 @@ func (a *App) runDownloadConfirmations(ctx context.Context, svc extsvc.Service,
|
|||||||
}
|
}
|
||||||
it := ConfirmationItem{
|
it := ConfirmationItem{
|
||||||
Callsign: q.Callsign,
|
Callsign: q.Callsign,
|
||||||
|
Station: strings.ToUpper(strings.TrimSpace(rec["station_callsign"])),
|
||||||
QSODate: q.QSODate.UTC().Format(time.RFC3339),
|
QSODate: q.QSODate.UTC().Format(time.RFC3339),
|
||||||
Band: q.Band,
|
Band: q.Band,
|
||||||
Mode: q.Mode,
|
Mode: q.Mode,
|
||||||
@@ -14581,6 +14635,36 @@ func (a *App) FlexBackspaceCW(n int) error {
|
|||||||
return a.cat.FlexDo(func(fc cat.FlexController) error { return fc.BackspaceCW(n) })
|
return a.cat.FlexDo(func(fc cat.FlexController) error { return fc.BackspaceCW(n) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TCISendCW keys a CW message through the SunSDR's own macro keyer, so a TCI
|
||||||
|
// station needs no WinKeyer and no second serial port. Text is already
|
||||||
|
// variable-resolved by the UI.
|
||||||
|
func (a *App) TCISendCW(text string) error {
|
||||||
|
if a.cat == nil {
|
||||||
|
return fmt.Errorf("cat not initialized")
|
||||||
|
}
|
||||||
|
err := a.cat.TCICWDo(func(tc cat.TCICWController) error { return tc.SendCW(text) })
|
||||||
|
if err != nil {
|
||||||
|
applog.Printf("tci cw: TCISendCW(%q) failed: %v", text, err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TCIStopCW aborts whatever the keyer is sending.
|
||||||
|
func (a *App) TCIStopCW() error {
|
||||||
|
if a.cat == nil {
|
||||||
|
return fmt.Errorf("cat not initialized")
|
||||||
|
}
|
||||||
|
return a.cat.TCICWDo(func(tc cat.TCICWController) error { return tc.StopCW() })
|
||||||
|
}
|
||||||
|
|
||||||
|
// TCISetKeySpeed sets the macro keyer speed in WPM.
|
||||||
|
func (a *App) TCISetKeySpeed(wpm int) error {
|
||||||
|
if a.cat == nil {
|
||||||
|
return fmt.Errorf("cat not initialized")
|
||||||
|
}
|
||||||
|
return a.cat.TCICWDo(func(tc cat.TCICWController) error { return tc.SetCWSpeed(wpm) })
|
||||||
|
}
|
||||||
|
|
||||||
// IcomStopCW aborts the CW message currently being sent.
|
// IcomStopCW aborts the CW message currently being sent.
|
||||||
func (a *App) IcomStopCW() error {
|
func (a *App) IcomStopCW() error {
|
||||||
if a.cat == nil {
|
if a.cat == nil {
|
||||||
|
|||||||
+208
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// The label PRINT path: pick the paper-QSL queue, review each address, choose
|
||||||
|
// the routing, and export PDFs whose pages are the exact label size — one PDF
|
||||||
|
// per label kind, because a roll printer holds one stock at a time and a file
|
||||||
|
// mixing 29 mm addresses with 62 mm QSO labels could not be printed at all.
|
||||||
|
//
|
||||||
|
// The pages arrive from the frontend already rasterised: the designer's canvas
|
||||||
|
// renderer draws them at the stock's dpi, so what was previewed is — pixel for
|
||||||
|
// pixel — what lands in the PDF. Go only carries them to disk.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"hamlog/internal/applog"
|
||||||
|
"hamlog/internal/pdf"
|
||||||
|
"hamlog/internal/qso"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LabelPaperQueue returns the contacts whose paper QSL is REQUESTED or QUEUED
|
||||||
|
// (ADIF qsl_sent R/Q) — the natural worklist for a labelling session. The
|
||||||
|
// frontend groups them by callsign.
|
||||||
|
func (a *App) LabelPaperQueue() ([]qso.QSO, error) {
|
||||||
|
if a.qso == nil {
|
||||||
|
return nil, fmt.Errorf("db not initialized")
|
||||||
|
}
|
||||||
|
return a.qso.List(a.ctx, qso.ListFilter{
|
||||||
|
QSLSentIn: []string{"R", "Q"},
|
||||||
|
Limit: 10_000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LabelPDFPage is one page of the session's output: a rasterised label and its
|
||||||
|
// physical size. Sizes vary WITHIN one document — the operator asked for a
|
||||||
|
// single PDF holding QSO labels, addresses and return labels together, and PDF
|
||||||
|
// pages each carry their own MediaBox, so a 90×29 page can follow a 100×62 one.
|
||||||
|
type LabelPDFPage struct {
|
||||||
|
PNG string `json:"png"` // base64, data-URL prefix tolerated
|
||||||
|
WMm float64 `json:"w_mm"`
|
||||||
|
HMm float64 `json:"h_mm"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LabelOpenPDF writes the session's labels to ONE temporary PDF and opens it in
|
||||||
|
// the system viewer, from which the operator prints. No save dialog by choice:
|
||||||
|
// the file is a print run, not a document to keep — anyone who wants to keep it
|
||||||
|
// saves from the viewer.
|
||||||
|
func (a *App) LabelOpenPDF(pages []LabelPDFPage) (string, error) {
|
||||||
|
if len(pages) == 0 {
|
||||||
|
return "", fmt.Errorf("nothing to print")
|
||||||
|
}
|
||||||
|
var doc pdf.Doc
|
||||||
|
for i, pg := range pages {
|
||||||
|
if pg.WMm < 5 || pg.HMm < 5 || pg.WMm > 400 || pg.HMm > 400 {
|
||||||
|
return "", fmt.Errorf("page %d: label size out of range", i+1)
|
||||||
|
}
|
||||||
|
p := pg.PNG
|
||||||
|
if idx := strings.Index(p, ","); idx >= 0 && strings.Contains(p[:idx], "base64") {
|
||||||
|
p = p[idx+1:]
|
||||||
|
}
|
||||||
|
raw, err := base64.StdEncoding.DecodeString(p)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("page %d: %w", i+1, err)
|
||||||
|
}
|
||||||
|
if err := doc.AddImagePage(raw, pg.WMm, pg.HMm); err != nil {
|
||||||
|
return "", fmt.Errorf("page %d: %w", i+1, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out, err := doc.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
// A timestamped name in the temp dir: two sessions in one evening must not
|
||||||
|
// fight over the file, least of all while a viewer holds the first one open.
|
||||||
|
path := filepath.Join(os.TempDir(), fmt.Sprintf("opslog-labels-%s.pdf", time.Now().Format("20060102-150405")))
|
||||||
|
if err := os.WriteFile(path, out, 0o644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
applog.Printf("labels: wrote %d page(s) to %s", len(pages), path)
|
||||||
|
if err := exec.Command("rundll32", "url.dll,FileProtocolHandler", path).Start(); err != nil {
|
||||||
|
applog.Printf("labels: could not open the PDF viewer: %v", err)
|
||||||
|
return "", fmt.Errorf("the PDF was written to %s but no viewer opened: %w", path, err)
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
@@ -1,4 +1,44 @@
|
|||||||
[
|
[
|
||||||
|
{
|
||||||
|
"version": "0.26.22",
|
||||||
|
"date": "",
|
||||||
|
"en": [
|
||||||
|
"LoTW download: the QSL details (QSL date, grid, state, county) are now optional and off by default — LoTW takes about ten times longer to build that report, twenty minutes against two on the same account, and marking a confirmation needs none of it. Still asked for automatically when adding the QSOs not found in the log.",
|
||||||
|
"Band map: the tooltip now also names a new prefix or a new grid square. They stay off the 22-pixel colour strip, but leaving them out of the text made the two panels look as though they disagreed — the cluster said NEW PFX about a spot the map called Worked, and both were right. The map’s “Worked” also says whose: it is the ENTITY that was worked on that band and mode, not the callsign, which is what made the two readings look contradictory.",
|
||||||
|
"TCI (SunSDR): clicking a cluster spot no longer needs a second click to get the mode right — the sideband was chosen from the frequency the radio had last reported instead of the one just asked for. The log also names the ExpertSDR version now, and says so when it is older than the 1.5 that panorama spots need.",
|
||||||
|
"Two screens: OpsLog no longer walks off the desktop. On a monitor placed left of the primary one, the saved position was being added to that monitor’s own origin at every launch, so the window moved one screen further out each time until it was invisible.",
|
||||||
|
"CW over TCI: a SunSDR can now be keyed through its own macro keyer — pick TCI as the keyer engine (Settings → CW Keyer) and macros, auto-call and the speed control all work over the link already open, with no WinKeyer and no second serial port. NOT TESTED on the air yet.",
|
||||||
|
"LoTW upload: a refusal now shows TQSL’s own explanation — which contacts were already uploaded, which fell outside the certificate’s dates — instead of the bare “no QSOs processed”, and names the two settings that cause it.",
|
||||||
|
"Main tab: the docked cluster now has ONE header row — its title, live count and Filters button sit with Clear filters and Columns, as Recent QSOs beside it already did. The pane is titled DX Cluster.",
|
||||||
|
"A busy cluster no longer makes the rest of the interface sluggish: incoming spots are grouped into fewer, larger updates as the feed gets faster (up to half a second), instead of redrawing the window twenty times a second. A quiet cluster still shows each spot as it lands.",
|
||||||
|
"SunSDR console: the meters work. The S-meter, transmit power and SWR are pushed by the radio only to a client that subscribes, and OpsLog never did — it was reading commands ExpertSDR3 does not send.",
|
||||||
|
"Cluster: the “N new spots” counter no longer jumps to the whole buffer. It was looking for the row it had frozen on, and a station spotted again replaces its row — so the count fell through to “everything is new”.",
|
||||||
|
"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.",
|
||||||
|
"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.",
|
||||||
|
"Label printing (Tools → Print QSL labels): a three-step session — pick from the paper-QSL queue (sent status R/Q), check each address with a routing choice (direct / bureau / via manager) and a QRZ fetch (the MANAGER’s address when routing says via), then ONE PDF holding every label at its exact size, opened straight in the viewer to print from. Finishing marks the contacts sent with the date and the via."
|
||||||
|
],
|
||||||
|
"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.",
|
||||||
|
"Carte des bandes : l'infobulle indique aussi un nouveau préfixe ou un nouveau locator. Ils restent hors de la bande de couleur de 22 pixels, mais les omettre du texte donnait l'impression que les deux panneaux se contredisaient — le cluster annonçait NOUVEAU PFX pour un spot que la carte disait contacté, et les deux avaient raison. Le « Contacté » de la carte dit aussi de qui il parle : c'est l'ENTITÉ qui a été contactée sur cette bande et ce mode, pas l'indicatif — d'où l'impression de contradiction.",
|
||||||
|
"TCI (SunSDR) : cliquer un spot du cluster ne demande plus un second clic pour obtenir le bon mode — la bande latérale était choisie d'après la fréquence encore annoncée par la radio au lieu de celle qu'on venait de demander. Le journal indique aussi la version d'ExpertSDR, et signale si elle est antérieure à la 1.5 qu'exigent les spots sur le panorama.",
|
||||||
|
"Deux écrans : OpsLog ne s'échappe plus du bureau. Sur un écran placé à gauche de l'écran principal, la position enregistrée était ajoutée à l'origine de cet écran à chaque lancement, si bien que la fenêtre s'éloignait d'un écran à chaque fois jusqu'à devenir invisible.",
|
||||||
|
"CW en TCI : un SunSDR peut désormais être manipulé par son propre keyer à macros — choisissez TCI comme moteur (Réglages → Manipulateur CW) et les macros, l'appel automatique et le réglage de vitesse passent par la liaison déjà ouverte, sans WinKeyer ni second port série. PAS ENCORE TESTÉ sur l'air.",
|
||||||
|
"Envoi LoTW : un refus affiche désormais l'explication de TQSL — quels contacts étaient déjà envoyés, lesquels tombaient hors des dates du certificat — au lieu du seul « no QSOs processed », et nomme les deux réglages qui en sont la cause.",
|
||||||
|
"Onglet Main : le cluster ancré n'a plus qu'UNE ligne d'en-tête — son titre, le compteur live et le bouton Filtres rejoignent Effacer les filtres et Colonnes, comme le faisait déjà la liste des QSO récents à côté. Le panneau s'intitule DX Cluster.",
|
||||||
|
"Un cluster chargé ne ralentit plus le reste de l'interface : les spots entrants sont regroupés en mises à jour moins nombreuses à mesure que le flux s'accélère (jusqu'à une demi-seconde), au lieu de redessiner la fenêtre vingt fois par seconde. Sur un cluster calme, chaque spot s'affiche toujours dès son arrivée.",
|
||||||
|
"Console SunSDR : les mesures fonctionnent. Le S-mètre, la puissance et le ROS ne sont envoyés qu'à un client qui s'abonne, ce qu'OpsLog ne faisait pas — il lisait des commandes qu'ExpertSDR3 n'envoie pas.",
|
||||||
|
"Cluster : le compteur « N nouveaux spots » ne saute plus à la taille du tampon. Il cherchait la ligne sur laquelle il s'était figé, or une station re-spottée remplace sa ligne — le compte basculait donc sur « tout est nouveau ».",
|
||||||
|
"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.",
|
||||||
|
"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.",
|
||||||
|
"Impression des étiquettes (Outils → Imprimer les étiquettes QSL) : une session en trois étapes — choisir dans la file QSL papier (statut envoyé R/Q), vérifier chaque adresse avec le routage (direct / bureau / via manager) et une récupération QRZ (l'adresse du MANAGER quand le routage le dit), puis UN PDF contenant toutes les étiquettes à leur taille exacte, ouvert directement dans le lecteur pour impression. La fin de session marque les contacts envoyés avec la date et le moyen."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "0.26.21",
|
"version": "0.26.21",
|
||||||
"date": "",
|
"date": "",
|
||||||
|
|||||||
+60
-14
@@ -41,6 +41,7 @@ import {
|
|||||||
IcomSendCW, YaesuSendCW, YaesuStopCW, SetYaesuKeySpeed, IcomStopCW, IcomSetKeySpeed, IcomSetBreakIn, GetIcomState,
|
IcomSendCW, YaesuSendCW, YaesuStopCW, SetYaesuKeySpeed, IcomStopCW, IcomSetKeySpeed, IcomSetBreakIn, GetIcomState,
|
||||||
KenwoodSendCW, KenwoodStopCW, SetKenwoodKeySpeed,
|
KenwoodSendCW, KenwoodStopCW, SetKenwoodKeySpeed,
|
||||||
FlexSendCW, FlexStopCW, FlexSetKeySpeed, FlexBackspaceCW,
|
FlexSendCW, FlexStopCW, FlexSetKeySpeed, FlexBackspaceCW,
|
||||||
|
TCISendCW, TCIStopCW, TCISetKeySpeed,
|
||||||
GetDVKMessages, GetDVKStatus, DVKPlay, DVKStop,
|
GetDVKMessages, GetDVKStatus, DVKPlay, DVKStop,
|
||||||
StartCWDecoder, StopCWDecoder, SetCWDecoderPitch,
|
StartCWDecoder, StopCWDecoder, SetCWDecoderPitch,
|
||||||
ChatAvailable, GetChatHistory, SendChatMessage, GetOnlineOperators,
|
ChatAvailable, GetChatHistory, SendChatMessage, GetOnlineOperators,
|
||||||
@@ -69,6 +70,8 @@ import {
|
|||||||
import { APP_VERSION, APP_AUTHOR } from '@/version';
|
import { APP_VERSION, APP_AUTHOR } from '@/version';
|
||||||
import { QSLManagerPanel } from '@/components/QSLManagerModal';
|
import { QSLManagerPanel } from '@/components/QSLManagerModal';
|
||||||
import { QslDesignerModal } from '@/components/qsl/QslDesignerModal';
|
import { QslDesignerModal } from '@/components/qsl/QslDesignerModal';
|
||||||
|
import { LabelDesignerModal } from '@/components/labels/LabelDesignerModal';
|
||||||
|
import { LabelPrintModal } from '@/components/labels/LabelPrintModal';
|
||||||
import { SendEQSLModal } from '@/components/qsl/SendEQSLModal';
|
import { SendEQSLModal } from '@/components/qsl/SendEQSLModal';
|
||||||
import { AutoEQSL } from '@/components/qsl/AutoEQSL';
|
import { AutoEQSL } from '@/components/qsl/AutoEQSL';
|
||||||
import { ConfirmDialog } from '@/components/ConfirmDialog';
|
import { ConfirmDialog } from '@/components/ConfirmDialog';
|
||||||
@@ -1266,6 +1269,8 @@ export default function App() {
|
|||||||
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
|
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
|
||||||
}
|
}
|
||||||
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
|
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
|
||||||
|
const [labelDesignerOpen, setLabelDesignerOpen] = useState(false);
|
||||||
|
const [labelPrintOpen, setLabelPrintOpen] = useState(false);
|
||||||
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
|
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
|
||||||
function closeQslTab() {
|
function closeQslTab() {
|
||||||
setQslTabOpen(false);
|
setQslTabOpen(false);
|
||||||
@@ -1490,7 +1495,7 @@ export default function App() {
|
|||||||
// CI-V 0x17 (no extra hardware — sends over the CAT connection). Macros,
|
// CI-V 0x17 (no extra hardware — sends over the CAT connection). Macros,
|
||||||
// auto-call and <LOGQSO> are shared; only the transport differs.
|
// auto-call and <LOGQSO> are shared; only the transport differs.
|
||||||
const [wkEngine, setWkEngine] = useState<string>('winkeyer');
|
const [wkEngine, setWkEngine] = useState<string>('winkeyer');
|
||||||
const cwSource: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood' = wkEngine === 'icom' ? 'icom' : wkEngine === 'flex' ? 'flex' : wkEngine === 'yaesu' ? 'yaesu' : wkEngine === 'kenwood' ? 'kenwood' : 'winkeyer';
|
const cwSource: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood' | 'tci' = wkEngine === 'icom' ? 'icom' : wkEngine === 'flex' ? 'flex' : wkEngine === 'yaesu' ? 'yaesu' : wkEngine === 'kenwood' ? 'kenwood' : wkEngine === 'tci' ? 'tci' : 'winkeyer';
|
||||||
// Setting the CW speed has to reach the keyer that is ACTUALLY sending, and
|
// Setting the CW speed has to reach the keyer that is ACTUALLY sending, and
|
||||||
// both the CW panel and the Yaesu console can ask for it. With DTR/RTS line
|
// both the CW panel and the Yaesu console can ask for it. With DTR/RTS line
|
||||||
// keying the PC does the timing, so the rig's internal keyer speed changes
|
// keying the PC does the timing, so the rig's internal keyer speed changes
|
||||||
@@ -1504,6 +1509,7 @@ export default function App() {
|
|||||||
else if (src === 'flex') FlexSetKeySpeed(w).catch(() => {});
|
else if (src === 'flex') FlexSetKeySpeed(w).catch(() => {});
|
||||||
else if (src === 'yaesu') SetYaesuKeySpeed(w).catch(() => {});
|
else if (src === 'yaesu') SetYaesuKeySpeed(w).catch(() => {});
|
||||||
else if (src === 'kenwood') SetKenwoodKeySpeed(w).catch(() => {});
|
else if (src === 'kenwood') SetKenwoodKeySpeed(w).catch(() => {});
|
||||||
|
else if (src === 'tci') TCISetKeySpeed(w).catch(() => {});
|
||||||
else WinkeyerSetSpeed(w).catch(() => {});
|
else WinkeyerSetSpeed(w).catch(() => {});
|
||||||
// The rig's own keyer follows too whenever a Yaesu is on CAT, even when it is
|
// The rig's own keyer follows too whenever a Yaesu is on CAT, even when it is
|
||||||
// not the sending engine: its front panel and OpsLog then agree.
|
// not the sending engine: its front panel and OpsLog then agree.
|
||||||
@@ -1548,6 +1554,7 @@ export default function App() {
|
|||||||
: cwSource === 'flex' ? (catState.backend === 'flex' && catState.connected)
|
: cwSource === 'flex' ? (catState.backend === 'flex' && catState.connected)
|
||||||
: cwSource === 'yaesu' ? (catState.backend === 'yaesu' && catState.connected)
|
: cwSource === 'yaesu' ? (catState.backend === 'yaesu' && catState.connected)
|
||||||
: cwSource === 'kenwood' ? (catState.backend === 'kenwood' && catState.connected)
|
: cwSource === 'kenwood' ? (catState.backend === 'kenwood' && catState.connected)
|
||||||
|
: cwSource === 'tci' ? (catState.backend === 'tci' && catState.connected)
|
||||||
: wkStatus.connected;
|
: wkStatus.connected;
|
||||||
wkActiveRef.current = wkEnabled && connected;
|
wkActiveRef.current = wkEnabled && connected;
|
||||||
}, [wkEnabled, wkStatus.connected, cwSource, catState.backend, catState.connected]);
|
}, [wkEnabled, wkStatus.connected, cwSource, catState.backend, catState.connected]);
|
||||||
@@ -2065,6 +2072,9 @@ export default function App() {
|
|||||||
useEffect(() => { spotStatusRef.current = spotStatus; }, [spotStatus]);
|
useEffect(() => { spotStatusRef.current = spotStatus; }, [spotStatus]);
|
||||||
// Mirror of spots so the log-triggered refresh reads the current list without
|
// Mirror of spots so the log-triggered refresh reads the current list without
|
||||||
// a stale closure.
|
// a stale closure.
|
||||||
|
// Arrival times of the last second's spots, for the adaptive batching window
|
||||||
|
// in the cluster:spot listener.
|
||||||
|
const spotRateRef = useRef<number[]>([]);
|
||||||
const spotsRef = useRef(spots);
|
const spotsRef = useRef(spots);
|
||||||
useEffect(() => { spotsRef.current = spots; }, [spots]);
|
useEffect(() => { spotsRef.current = spots; }, [spots]);
|
||||||
// The decoded stations, for the same reason: the status refresh and the cache
|
// The decoded stations, for the same reason: the status refresh and the cache
|
||||||
@@ -3592,11 +3602,24 @@ export default function App() {
|
|||||||
const unsubSpot = EventsOn('cluster:spot', (sp: ClusterSpot) => {
|
const unsubSpot = EventsOn('cluster:spot', (sp: ClusterSpot) => {
|
||||||
// Stage the spot; a short timer resolves its status then commits it.
|
// Stage the spot; a short timer resolves its status then commits it.
|
||||||
pendingSpotsRef.current.push(sp);
|
pendingSpotsRef.current.push(sp);
|
||||||
// 50 ms is enough to coalesce an RBN burst into one status lookup (the
|
// The window WIDENS with the rate of the feed.
|
||||||
// worked-index is in memory, so resolving is near-instant) while staying
|
//
|
||||||
// imperceptible.
|
// Every flush commits state that the whole window re-renders on, so a
|
||||||
|
// fixed 50 ms means twenty full renders a second under an RBN firehose —
|
||||||
|
// and that is felt everywhere else: a dropdown highlighting its entries a
|
||||||
|
// beat late as the mouse moves down them, which is what was reported.
|
||||||
|
//
|
||||||
|
// A quiet cluster keeps the 50 ms: a handful of spots an hour should
|
||||||
|
// appear the moment they arrive. A busy one is coalesced instead, and half
|
||||||
|
// a second's delay on a line in a list that is already scrolling past is
|
||||||
|
// not something anyone can see.
|
||||||
|
const now = Date.now();
|
||||||
|
spotRateRef.current = spotRateRef.current.filter((t) => now - t < 1000);
|
||||||
|
spotRateRef.current.push(now);
|
||||||
|
const perSec = spotRateRef.current.length;
|
||||||
|
const window_ms = perSec > 20 ? 500 : perSec > 5 ? 200 : 50;
|
||||||
if (pendingSpotTimer.current === undefined) {
|
if (pendingSpotTimer.current === undefined) {
|
||||||
pendingSpotTimer.current = window.setTimeout(flushPendingSpots, 50);
|
pendingSpotTimer.current = window.setTimeout(flushPendingSpots, window_ms);
|
||||||
}
|
}
|
||||||
// Self-spot: someone spotted OUR callsign — show it in the shared header
|
// Self-spot: someone spotted OUR callsign — show it in the shared header
|
||||||
// toast (same place as the other notifications), not a separate banner.
|
// toast (same place as the other notifications), not a separate banner.
|
||||||
@@ -3968,7 +3991,7 @@ export default function App() {
|
|||||||
// segment AFTER the <LOGQSO> (which logs and clears the form) still expands its
|
// segment AFTER the <LOGQSO> (which logs and clears the form) still expands its
|
||||||
// variables correctly.
|
// variables correctly.
|
||||||
const parts = rawText.split(/<LOGQSO>/i).map((pt) => resolveCW(pt));
|
const parts = rawText.split(/<LOGQSO>/i).map((pt) => resolveCW(pt));
|
||||||
const isRig = cwSourceRef.current === 'icom' || cwSourceRef.current === 'flex' || cwSourceRef.current === 'yaesu' || cwSourceRef.current === 'kenwood';
|
const isRig = cwSourceRef.current === 'icom' || cwSourceRef.current === 'flex' || cwSourceRef.current === 'yaesu' || cwSourceRef.current === 'kenwood' || cwSourceRef.current === 'tci';
|
||||||
for (let p = 0; p < parts.length; p++) {
|
for (let p = 0; p < parts.length; p++) {
|
||||||
if (aborted()) return; // ESC / Stop before this segment → stop sending, don't log
|
if (aborted()) return; // ESC / Stop before this segment → stop sending, don't log
|
||||||
const resolved = parts[p];
|
const resolved = parts[p];
|
||||||
@@ -3980,7 +4003,7 @@ export default function App() {
|
|||||||
// current WPM, so it scales automatically.
|
// current WPM, so it scales automatically.
|
||||||
const keyed = resolved + ' ';
|
const keyed = resolved + ' ';
|
||||||
setWkSent(resolved);
|
setWkSent(resolved);
|
||||||
const sendFn = cwSourceRef.current === 'flex' ? FlexSendCW : cwSourceRef.current === 'icom' ? IcomSendCW : cwSourceRef.current === 'yaesu' ? YaesuSendCW : cwSourceRef.current === 'kenwood' ? KenwoodSendCW : null;
|
const sendFn = cwSourceRef.current === 'flex' ? FlexSendCW : cwSourceRef.current === 'icom' ? IcomSendCW : cwSourceRef.current === 'yaesu' ? YaesuSendCW : cwSourceRef.current === 'kenwood' ? KenwoodSendCW : cwSourceRef.current === 'tci' ? TCISendCW : null;
|
||||||
if (sendFn) await sendFn(keyed).catch((e) => setError(String(e?.message ?? e)));
|
if (sendFn) await sendFn(keyed).catch((e) => setError(String(e?.message ?? e)));
|
||||||
else await WinkeyerSend(keyed).catch((e) => setError(String(e?.message ?? e)));
|
else await WinkeyerSend(keyed).catch((e) => setError(String(e?.message ?? e)));
|
||||||
// WAIT for THIS segment's CW to finish before moving on — so a <LOGQSO>
|
// WAIT for THIS segment's CW to finish before moving on — so a <LOGQSO>
|
||||||
@@ -4023,6 +4046,7 @@ export default function App() {
|
|||||||
else if (cwSourceRef.current === 'flex') FlexStopCW().catch(() => {});
|
else if (cwSourceRef.current === 'flex') FlexStopCW().catch(() => {});
|
||||||
else if (cwSourceRef.current === 'yaesu') YaesuStopCW().catch(() => {});
|
else if (cwSourceRef.current === 'yaesu') YaesuStopCW().catch(() => {});
|
||||||
else if (cwSourceRef.current === 'kenwood') KenwoodStopCW().catch(() => {});
|
else if (cwSourceRef.current === 'kenwood') KenwoodStopCW().catch(() => {});
|
||||||
|
else if (cwSourceRef.current === 'tci') TCIStopCW().catch(() => {});
|
||||||
else WinkeyerStop().catch(() => {});
|
else WinkeyerStop().catch(() => {});
|
||||||
}
|
}
|
||||||
// runAutoCall sends macro i, waits for the keyer to finish, waits the chosen
|
// runAutoCall sends macro i, waits for the keyer to finish, waits the chosen
|
||||||
@@ -4071,6 +4095,10 @@ export default function App() {
|
|||||||
// send-on-type: key the typed chars verbatim (no variable substitution).
|
// send-on-type: key the typed chars verbatim (no variable substitution).
|
||||||
function wkSendRaw(chars: string) {
|
function wkSendRaw(chars: string) {
|
||||||
if (cwSourceRef.current === 'flex') { FlexSendCW(chars).catch(() => {}); return; }
|
if (cwSourceRef.current === 'flex') { FlexSendCW(chars).catch(() => {}); return; }
|
||||||
|
// TCI keys the character as a macro of its own. There is no un-typing it
|
||||||
|
// afterwards — the radio can stop the message but not shorten it — so the
|
||||||
|
// backspace below leaves the TCI engine alone rather than pretending.
|
||||||
|
if (cwSourceRef.current === 'tci') { TCISendCW(chars).catch(() => {}); return; }
|
||||||
WinkeyerSend(chars).catch(() => {});
|
WinkeyerSend(chars).catch(() => {});
|
||||||
}
|
}
|
||||||
function wkBackspace() {
|
function wkBackspace() {
|
||||||
@@ -4974,6 +5002,8 @@ export default function App() {
|
|||||||
{ type: 'item', label: t('dec.tab'), action: 'tools.decodes' },
|
{ type: 'item', label: t('dec.tab'), action: 'tools.decodes' },
|
||||||
{ type: 'item', label: t('gsm.title'), action: 'tools.grids' },
|
{ type: 'item', label: t('gsm.title'), action: 'tools.grids' },
|
||||||
{ type: 'item', label: t('tools.qslDesigner'), action: 'tools.qsldesigner' },
|
{ type: 'item', label: t('tools.qslDesigner'), action: 'tools.qsldesigner' },
|
||||||
|
{ type: 'item', label: t('tools.labelDesigner'), action: 'tools.labeldesigner' },
|
||||||
|
{ type: 'item', label: t('tools.labelPrint'), action: 'tools.labelprint' },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ type: 'item', label: (wkEnabled ? '✓ ' : '') + t('tools.winkeyer'), action: 'tools.winkeyer' },
|
{ type: 'item', label: (wkEnabled ? '✓ ' : '') + t('tools.winkeyer'), action: 'tools.winkeyer' },
|
||||||
{ type: 'item', label: (dvkEnabled ? '✓ ' : '') + t('tools.dvk'), action: 'tools.dvk' },
|
{ type: 'item', label: (dvkEnabled ? '✓ ' : '') + t('tools.dvk'), action: 'tools.dvk' },
|
||||||
@@ -5027,6 +5057,8 @@ export default function App() {
|
|||||||
case 'tools.decodes': openDecodesTab(); break;
|
case 'tools.decodes': openDecodesTab(); break;
|
||||||
case 'tools.grids': openGridsTab(); break;
|
case 'tools.grids': openGridsTab(); break;
|
||||||
case 'tools.qsldesigner': setQslDesignerOpen(true); break;
|
case 'tools.qsldesigner': setQslDesignerOpen(true); break;
|
||||||
|
case 'tools.labeldesigner': setLabelDesignerOpen(true); break;
|
||||||
|
case 'tools.labelprint': setLabelPrintOpen(true); break;
|
||||||
case 'tools.winkeyer': wkSetEnabled(!wkEnabled); break;
|
case 'tools.winkeyer': wkSetEnabled(!wkEnabled); break;
|
||||||
case 'tools.dvk': setDvkEnabled((v) => !v); break;
|
case 'tools.dvk': setDvkEnabled((v) => !v); break;
|
||||||
case 'tools.cwdecoder': toggleCwDecoder(); break;
|
case 'tools.cwdecoder': toggleCwDecoder(); break;
|
||||||
@@ -5902,11 +5934,17 @@ export default function App() {
|
|||||||
});
|
});
|
||||||
let rendered = list as (ClusterSpot & { repeats?: number })[];
|
let rendered = list as (ClusterSpot & { repeats?: number })[];
|
||||||
if (clusterGroup) {
|
if (clusterGroup) {
|
||||||
|
// A DUPLICATE is the same station on the same band AND mode — the dozen
|
||||||
|
// skimmers that all heard one CQ. The same station on another band is the
|
||||||
|
// opposite of a duplicate: it is the line a DX chaser is scanning for, and
|
||||||
|
// grouping on the callsign alone deleted it. RI1FJL spotted on five bands
|
||||||
|
// showed as one row, so four slots simply vanished from the list.
|
||||||
const seen = new Map<string, ClusterSpot & { repeats: number }>();
|
const seen = new Map<string, ClusterSpot & { repeats: number }>();
|
||||||
for (const s of list) {
|
for (const s of list) {
|
||||||
const e = seen.get(s.dx_call);
|
const key = `${(s.dx_call ?? '').toUpperCase()}|${(s.band ?? '').toLowerCase()}|${inferSpotMode(s.comment ?? '', s.freq_hz)}`;
|
||||||
|
const e = seen.get(key);
|
||||||
if (e) { e.repeats++; }
|
if (e) { e.repeats++; }
|
||||||
else seen.set(s.dx_call, { ...s, repeats: 1 });
|
else seen.set(key, { ...s, repeats: 1 });
|
||||||
}
|
}
|
||||||
rendered = Array.from(seen.values());
|
rendered = Array.from(seen.values());
|
||||||
}
|
}
|
||||||
@@ -6228,13 +6266,19 @@ export default function App() {
|
|||||||
case 'cluster':
|
case 'cluster':
|
||||||
return (
|
return (
|
||||||
<div className="h-full w-full min-h-0 flex flex-col bg-card border border-border rounded-lg overflow-hidden">
|
<div className="h-full w-full min-h-0 flex flex-col bg-card border border-border rounded-lg overflow-hidden">
|
||||||
<div className="flex items-center justify-between px-2 py-1 border-b border-border/60 shrink-0">
|
|
||||||
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">Cluster</span>
|
|
||||||
{clusterFiltersToggleBtn}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-h-0 flex">
|
<div className="flex-1 min-h-0 flex">
|
||||||
<div className="flex-1 min-w-0 flex flex-col min-h-0">
|
<div className="flex-1 min-w-0 flex flex-col min-h-0">
|
||||||
<ClusterGrid key={`clg-${activeProfileId ?? 'x'}`} rows={clusterRenderedRows as any} spotStatus={spotStatus} onSpotClick={handleSpotClick} onSpotSelect={handleSpotSelect} />
|
{/* Title, count and Filters ride INSIDE the grid's toolbar: two
|
||||||
|
header rows cost a pane that is often only a few spots tall
|
||||||
|
one of the few lines it has. */}
|
||||||
|
<ClusterGrid key={`clg-${activeProfileId ?? 'x'}`} rows={clusterRenderedRows as any} spotStatus={spotStatus} onSpotClick={handleSpotClick} onSpotSelect={handleSpotSelect}
|
||||||
|
headerLeft={(
|
||||||
|
<>
|
||||||
|
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground shrink-0">DX Cluster</span>
|
||||||
|
<Badge variant="secondary" className="text-[10px] shrink-0">{spots.length} live</Badge>
|
||||||
|
{clusterFiltersToggleBtn}
|
||||||
|
</>
|
||||||
|
)} />
|
||||||
</div>
|
</div>
|
||||||
{clusterShowFilters && renderClusterFilters()}
|
{clusterShowFilters && renderClusterFilters()}
|
||||||
</div>
|
</div>
|
||||||
@@ -8676,6 +8720,8 @@ export default function App() {
|
|||||||
onError={(msg) => showToast(msg)}
|
onError={(msg) => showToast(msg)}
|
||||||
/>
|
/>
|
||||||
<QslDesignerModal open={qslDesignerOpen} onClose={() => setQslDesignerOpen(false)} />
|
<QslDesignerModal open={qslDesignerOpen} onClose={() => setQslDesignerOpen(false)} />
|
||||||
|
<LabelDesignerModal open={labelDesignerOpen} onClose={() => setLabelDesignerOpen(false)} />
|
||||||
|
<LabelPrintModal open={labelPrintOpen} onClose={() => setLabelPrintOpen(false)} />
|
||||||
<SendEQSLModal
|
<SendEQSLModal
|
||||||
open={eqslQsoId !== null}
|
open={eqslQsoId !== null}
|
||||||
qsoId={eqslQsoId}
|
qsoId={eqslQsoId}
|
||||||
|
|||||||
@@ -76,6 +76,13 @@ const BMP_MARKER_LABEL: Record<string, string> = {
|
|||||||
new_pota: 'bmp.legendNewPota',
|
new_pota: 'bmp.legendNewPota',
|
||||||
new_county: 'bmp.legendNewCounty',
|
new_county: 'bmp.legendNewCounty',
|
||||||
worked_call: 'bmp.legendWorkedCall',
|
worked_call: 'bmp.legendWorkedCall',
|
||||||
|
// Not on the strip — the pill is 22 px and a fourth segment turns it into a
|
||||||
|
// colour code nobody reads — but the TOOLTIP has room, and leaving them out of
|
||||||
|
// it made the two panels contradict each other: the cluster said NEW PFX about
|
||||||
|
// a spot the map called "Worked". Both were true (the entity is worked on this
|
||||||
|
// slot, the WPX prefix never has been) and neither view said so.
|
||||||
|
new_pfx: 'clg2.newPfx',
|
||||||
|
new_grid: 'clg2.newGrid',
|
||||||
};
|
};
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -737,7 +744,7 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
|
|||||||
'hover:translate-x-0.5 hover:shadow',
|
'hover:translate-x-0.5 hover:shadow',
|
||||||
style.pill,
|
style.pill,
|
||||||
)}
|
)}
|
||||||
title={`${p.spot.dx_call}${entry?.country ? ' · ' + entry.country : ''} · ${p.spot.freq_khz.toFixed(1)} kHz · ${statusLabel(st, t)}${markersFor(entry).map((m) => ' · ' + t(BMP_MARKER_LABEL[m.key])).join('')}${p.spot.comment ? ' · ' + p.spot.comment : ''}${p.spot.spotter ? ' · de ' + p.spot.spotter : ''}`}
|
title={`${p.spot.dx_call}${entry?.country ? ' · ' + entry.country : ''} · ${p.spot.freq_khz.toFixed(1)} kHz · ${statusLabel(st, t)}${activeMarkers(entry).map((m) => ' · ' + t(BMP_MARKER_LABEL[m.key])).join('')}${p.spot.comment ? ' · ' + p.spot.comment : ''}${p.spot.spotter ? ' · de ' + p.spot.spotter : ''}`}
|
||||||
>
|
>
|
||||||
{/* Left accent strip. With no extra marker it repeats the status
|
{/* Left accent strip. With no extra marker it repeats the status
|
||||||
colour, exactly as before; otherwise it splits into one
|
colour, exactly as before; otherwise it splits into one
|
||||||
|
|||||||
@@ -84,6 +84,11 @@ type Props = {
|
|||||||
// stray click while looking took the operator off the station they were
|
// stray click while looking took the operator off the station they were
|
||||||
// working. Looking and going are now two different gestures.
|
// working. Looking and going are now two different gestures.
|
||||||
onSpotSelect?: (s: ClusterSpot) => void;
|
onSpotSelect?: (s: ClusterSpot) => void;
|
||||||
|
// Anything the caller wants on the LEFT of the toolbar — the pane's title, its
|
||||||
|
// live count, its Filters button. Docked in a pane, the title used to sit on a
|
||||||
|
// row of its own above this one, so the cluster ate two lines of a short pane
|
||||||
|
// where Recent QSOs beside it ate one. Reported by VK4DX.
|
||||||
|
headerLeft?: React.ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
const COL_STATE_KEY = 'hamlog.clusterColState.v1';
|
const COL_STATE_KEY = 'hamlog.clusterColState.v1';
|
||||||
@@ -523,7 +528,7 @@ const GROUP_ORDER = ['Spot', 'Geo'];
|
|||||||
const CLG_GRP_KEYS: Record<string, string> = { Spot: 'clg2.grpSpot', Geo: 'clg2.grpGeo' };
|
const CLG_GRP_KEYS: Record<string, string> = { Spot: 'clg2.grpSpot', Geo: 'clg2.grpGeo' };
|
||||||
const groupLabel = (t: TFn, g: string): string => t(CLG_GRP_KEYS[g] ?? g);
|
const groupLabel = (t: TFn, g: string): string => t(CLG_GRP_KEYS[g] ?? g);
|
||||||
|
|
||||||
export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Props) {
|
export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect, headerLeft }: Props) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const gridRef = useRef<any>(null);
|
const gridRef = useRef<any>(null);
|
||||||
const [pickerOpen, setPickerOpen] = useState(false);
|
const [pickerOpen, setPickerOpen] = useState(false);
|
||||||
@@ -622,16 +627,27 @@ export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Pro
|
|||||||
const [held, setHeld] = useState<ClusterSpot[] | null>(null);
|
const [held, setHeld] = useState<ClusterSpot[] | null>(null);
|
||||||
const shown = held ?? rows;
|
const shown = held ?? rows;
|
||||||
|
|
||||||
// How many arrived since the freeze. Counted by finding the frozen top row in
|
// How many arrived since the freeze — counted by TIME, not by finding the
|
||||||
// the live list rather than by comparing lengths: the list is a ring buffer,
|
// frozen top row again.
|
||||||
// so once it is full the length stops growing and a length comparison would
|
//
|
||||||
// report nothing new for the rest of the evening.
|
// Looking for that row was wrong in the ordinary case: a station spotted again
|
||||||
const spotID = (r: ClusterSpot) => `${(r as any).received_at}-${r.dx_call}-${(r as any).source_id}`;
|
// REPLACES its row (that is the de-dupe), so the row we froze on disappears
|
||||||
|
// from the live list the moment somebody re-spots it — and the count fell
|
||||||
|
// through to "everything is new", jumping from 4 to the buffer cap. Reported
|
||||||
|
// as "it shows 4, 5 new spots and then 500 all at once".
|
||||||
|
//
|
||||||
|
// A timestamp survives both the replacement and the ring buffer, which was the
|
||||||
|
// reason the length was not used either.
|
||||||
|
const spotTime = (r: ClusterSpot) => Date.parse(String((r as any).received_at ?? '')) || 0;
|
||||||
const waiting = useMemo(() => {
|
const waiting = useMemo(() => {
|
||||||
if (!held || held.length === 0) return 0;
|
if (!held || held.length === 0) return 0;
|
||||||
const top = spotID(held[0]);
|
const since = spotTime(held[0]);
|
||||||
const i = rows.findIndex((r) => spotID(r) === top);
|
if (!since) return 0; // no usable timestamp — say nothing rather than a number
|
||||||
return i < 0 ? rows.length : i; // fell out of the buffer: everything is new
|
let n = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
if (spotTime(r) > since) n++;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
}, [held, rows]);
|
}, [held, rows]);
|
||||||
|
|
||||||
const onBodyScroll = (e: { top: number }) => {
|
const onBodyScroll = (e: { top: number }) => {
|
||||||
@@ -689,7 +705,9 @@ export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Pro
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center justify-end gap-2 px-2.5 py-1 border-b border-border/60 bg-muted/20">
|
<div className="flex items-center gap-2 px-2.5 py-1 border-b border-border/60 bg-muted/20">
|
||||||
|
{headerLeft}
|
||||||
|
<div className="flex-1" />
|
||||||
<Button variant="ghost" size="sm" className="h-7 text-[11px]" onClick={() => gridRef.current?.api?.setFilterModel(null)}
|
<Button variant="ghost" size="sm" className="h-7 text-[11px]" onClick={() => gridRef.current?.api?.setFilterModel(null)}
|
||||||
title={t('clg2.clearFiltersTitle')}>
|
title={t('clg2.clearFiltersTitle')}>
|
||||||
<FilterX className="size-3.5" /> {t('clg2.clearFilters')}
|
<FilterX className="size-3.5" /> {t('clg2.clearFilters')}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Select, SelectTrigger, SelectValue, SelectContent, SelectItem,
|
Select, SelectTrigger, SelectValue, SelectContent, SelectItem,
|
||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { GetLoTWDownloadAllCalls, SetLoTWDownloadAllCalls, OpenExternalURL, FindQSOsForUpload, UploadQSOsManual, DownloadConfirmations, CancelConfirmations, ImportHamlogConfirmations, ExportHamlogUnmatched, OpenADIFFile, SaveADIFFile, SyncPOTAHunterLog, ListQSO, BulkUpdateQSL, UploadCallsign, GetSlotStats } from '../../wailsjs/go/main/App';
|
import { GetLoTWQSLDetail, SetLoTWQSLDetail, GetLoTWDownloadAllCalls, SetLoTWDownloadAllCalls, OpenExternalURL, FindQSOsForUpload, UploadQSOsManual, DownloadConfirmations, CancelConfirmations, ImportHamlogConfirmations, ExportHamlogUnmatched, OpenADIFFile, SaveADIFFile, SyncPOTAHunterLog, ListQSO, BulkUpdateQSL, UploadCallsign, GetSlotStats } from '../../wailsjs/go/main/App';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { RecentQSOsGrid } from '@/components/RecentQSOsGrid';
|
import { RecentQSOsGrid } from '@/components/RecentQSOsGrid';
|
||||||
import { EventsOn } from '../../wailsjs/runtime/runtime';
|
import { EventsOn } from '../../wailsjs/runtime/runtime';
|
||||||
@@ -31,7 +31,7 @@ const UPLOAD_COLS: ColDef<UploadRow>[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
type Confirmation = {
|
type Confirmation = {
|
||||||
callsign: string; qso_date: string; band: string; mode: string; country: string;
|
callsign: string; station?: string; qso_date: string; band: string; mode: string; country: string;
|
||||||
new_dxcc: boolean; new_band: boolean; new_mode: boolean; new_slot: boolean;
|
new_dxcc: boolean; new_band: boolean; new_mode: boolean; new_slot: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -257,7 +257,13 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
|
|||||||
const [addNotFound, setAddNotFound] = useState(false);
|
const [addNotFound, setAddNotFound] = useState(false);
|
||||||
// LoTW only: pull the whole account rather than this profile's callsign.
|
// LoTW only: pull the whole account rather than this profile's callsign.
|
||||||
const [lotwAllCalls, setLotwAllCalls] = useState(false);
|
const [lotwAllCalls, setLotwAllCalls] = useState(false);
|
||||||
useEffect(() => { GetLoTWDownloadAllCalls().then((v: boolean) => setLotwAllCalls(!!v)).catch(() => {}); }, []);
|
// LoTW only: ask for the QSL dates and station details. Ten times slower to
|
||||||
|
// build, so it is a choice rather than the default it used to be.
|
||||||
|
const [lotwDetail, setLotwDetail] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
GetLoTWDownloadAllCalls().then((v: boolean) => setLotwAllCalls(!!v)).catch(() => {});
|
||||||
|
GetLoTWQSLDetail().then((v: boolean) => setLotwDetail(!!v)).catch(() => {});
|
||||||
|
}, []);
|
||||||
// Download date window: 'last' = incremental since last pull, 'date' = from a
|
// Download date window: 'last' = incremental since last pull, 'date' = from a
|
||||||
// chosen date, 'all' = everything.
|
// chosen date, 'all' = everything.
|
||||||
const [sinceMode, setSinceMode] = useState<'last' | 'date' | 'all'>('last');
|
const [sinceMode, setSinceMode] = useState<'last' | 'date' | 'all'>('last');
|
||||||
@@ -613,6 +619,10 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
|
|||||||
<thead className="sticky top-0 bg-card">
|
<thead className="sticky top-0 bg-card">
|
||||||
<tr className="text-left text-muted-foreground border-b border-border">
|
<tr className="text-left text-muted-foreground border-b border-border">
|
||||||
<th className="py-1.5 px-2">{t('qslm.thDateUtc')}</th><th className="py-1.5 px-2">{t('qslm.thCallsign')}</th>
|
<th className="py-1.5 px-2">{t('qslm.thDateUtc')}</th><th className="py-1.5 px-2">{t('qslm.thCallsign')}</th>
|
||||||
|
{/* Which of the operator's callsigns the contact was made
|
||||||
|
under. Only worth a column when the list can hold more than
|
||||||
|
one — see "All my callsigns" on the download. */}
|
||||||
|
{shownConfs.some((c) => c.station) && <th className="py-1.5 px-2">{t('qslm.thStation')}</th>}
|
||||||
<th className="py-1.5 px-2">{t('qslm.thBand')}</th><th className="py-1.5 px-2">{t('qslm.thMode')}</th>
|
<th className="py-1.5 px-2">{t('qslm.thBand')}</th><th className="py-1.5 px-2">{t('qslm.thMode')}</th>
|
||||||
<th className="py-1.5 px-2">{t('qslm.thCountry')}</th><th className="py-1.5 px-2">{t('qslm.thNew')}</th>
|
<th className="py-1.5 px-2">{t('qslm.thCountry')}</th><th className="py-1.5 px-2">{t('qslm.thNew')}</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -622,6 +632,9 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
|
|||||||
<tr key={i} className="border-b border-border/40">
|
<tr key={i} className="border-b border-border/40">
|
||||||
<td className="py-1 px-2 font-mono">{fmtDate(c.qso_date)}</td>
|
<td className="py-1 px-2 font-mono">{fmtDate(c.qso_date)}</td>
|
||||||
<td className="py-1 px-2 font-mono font-bold">{c.callsign}</td>
|
<td className="py-1 px-2 font-mono font-bold">{c.callsign}</td>
|
||||||
|
{shownConfs.some((x) => x.station) && (
|
||||||
|
<td className="py-1 px-2 font-mono text-muted-foreground">{c.station ?? ''}</td>
|
||||||
|
)}
|
||||||
<td className="py-1 px-2">{c.band}</td>
|
<td className="py-1 px-2">{c.band}</td>
|
||||||
<td className="py-1 px-2">{c.mode}</td>
|
<td className="py-1 px-2">{c.mode}</td>
|
||||||
<td className="py-1 px-2 text-muted-foreground">{c.country}</td>
|
<td className="py-1 px-2 text-muted-foreground">{c.country}</td>
|
||||||
@@ -751,6 +764,13 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
|
|||||||
<Checkbox checked={addNotFound} onCheckedChange={(c) => setAddNotFound(!!c)} />
|
<Checkbox checked={addNotFound} onCheckedChange={(c) => setAddNotFound(!!c)} />
|
||||||
{t('qslm.addNotFound')}
|
{t('qslm.addNotFound')}
|
||||||
</label>
|
</label>
|
||||||
|
{service === 'lotw' && (
|
||||||
|
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer" title={t('qslm.lotwDetailTitle')}>
|
||||||
|
<Checkbox checked={lotwDetail || addNotFound} disabled={addNotFound}
|
||||||
|
onCheckedChange={(c) => { setLotwDetail(!!c); SetLoTWQSLDetail(!!c); }} />
|
||||||
|
{t('qslm.lotwDetail')}
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
{service === 'lotw' && (
|
{service === 'lotw' && (
|
||||||
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer" title={t('qslm.lotwAllCallsTitle')}>
|
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer" title={t('qslm.lotwAllCallsTitle')}>
|
||||||
<Checkbox checked={lotwAllCalls} onCheckedChange={(c) => { setLotwAllCalls(!!c); SetLoTWDownloadAllCalls(!!c); }} />
|
<Checkbox checked={lotwAllCalls} onCheckedChange={(c) => { setLotwAllCalls(!!c); SetLoTWDownloadAllCalls(!!c); }} />
|
||||||
|
|||||||
@@ -4867,7 +4867,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
<SelectItem value="yaesu">{t('wk.engYaesu')}</SelectItem>
|
<SelectItem value="yaesu">{t('wk.engYaesu')}</SelectItem>
|
||||||
<SelectItem value="kenwood">{t('wk.engKenwood')}</SelectItem>
|
<SelectItem value="kenwood">{t('wk.engKenwood')}</SelectItem>
|
||||||
<SelectItem value="flex">{t('wk.engFlex')}</SelectItem>
|
<SelectItem value="flex">{t('wk.engFlex')}</SelectItem>
|
||||||
<SelectItem value="tci" disabled>{t('wk.engTci')}</SelectItem>
|
<SelectItem value="tci">{t('wk.engTci')}</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
@@ -4928,6 +4928,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
) : wk.engine === 'tci' ? (
|
||||||
|
<>
|
||||||
|
{(!catCfg.enabled || catCfg.backend !== 'tci') && (
|
||||||
|
<p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5">
|
||||||
|
<span aria-hidden>⚠</span>
|
||||||
|
<span>{t('wk.catWarnTci', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="text-xs text-muted-foreground -mt-1">{t('wk.tciHint')}</p>
|
||||||
|
<div className="grid grid-cols-4 gap-3">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Label>{t('wk.speed')}</Label>
|
||||||
|
<Input type="number" min={5} max={60} value={wk.wpm} onChange={(e) => setWkField({ wpm: num(e.target.value, 25) })} className="font-mono" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
) : wk.engine === 'flex' ? (
|
) : wk.engine === 'flex' ? (
|
||||||
<>
|
<>
|
||||||
{(!catCfg.enabled || catCfg.backend !== 'flex') && (
|
{(!catCfg.enabled || catCfg.backend !== 'flex') && (
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ interface Props {
|
|||||||
wpm: number;
|
wpm: number;
|
||||||
macros: WKMacro[];
|
macros: WKMacro[];
|
||||||
sent: string; // text echoed back by the keyer as it transmits
|
sent: string; // text echoed back by the keyer as it transmits
|
||||||
source: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood'; // CW output engine (chosen in Settings → CW Keyer)
|
source: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood' | 'tci'; // CW output engine (chosen in Settings → CW Keyer)
|
||||||
breakIn?: number; // Icom CW break-in: 0=OFF, 1=SEMI, 2=FULL
|
breakIn?: number; // Icom CW break-in: 0=OFF, 1=SEMI, 2=FULL
|
||||||
onSetBreakIn?: (mode: number) => void;
|
onSetBreakIn?: (mode: number) => void;
|
||||||
onSelectPort: (p: string) => void;
|
onSelectPort: (p: string) => void;
|
||||||
@@ -109,16 +109,16 @@ export function WinkeyerPanel({
|
|||||||
<Radio className="size-4 text-primary shrink-0" />
|
<Radio className="size-4 text-primary shrink-0" />
|
||||||
{/* CW output engine (chosen in Settings → CW Keyer). */}
|
{/* CW output engine (chosen in Settings → CW Keyer). */}
|
||||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0">
|
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0">
|
||||||
{source === 'icom' ? 'Icom CW' : source === 'flex' ? 'Flex CWX' : source === 'yaesu' ? 'Yaesu CW' : source === 'kenwood' ? 'Kenwood CW' : 'WinKeyer'}
|
{source === 'icom' ? 'Icom CW' : source === 'flex' ? 'Flex CWX' : source === 'yaesu' ? 'Yaesu CW' : source === 'kenwood' ? 'Kenwood CW' : source === 'tci' ? 'TCI CW' : 'WinKeyer'}
|
||||||
</span>
|
</span>
|
||||||
<span className={cn('size-2 rounded-full', connected ? (status.busy ? 'bg-warning animate-pulse' : 'bg-success') : 'bg-muted-foreground/40')}
|
<span className={cn('size-2 rounded-full', connected ? (status.busy ? 'bg-warning animate-pulse' : 'bg-success') : 'bg-muted-foreground/40')}
|
||||||
title={connected ? (status.busy ? t('wkp.sending') : t('wkp.connectedV', { version: status.version })) : t('wkp.disconnected')} />
|
title={connected ? (status.busy ? t('wkp.sending') : t('wkp.connectedV', { version: status.version })) : t('wkp.disconnected')} />
|
||||||
<div className="flex-1" />
|
<div className="flex-1" />
|
||||||
{source === 'icom' || source === 'flex' || source === 'yaesu' || source === 'kenwood' ? (
|
{source === 'icom' || source === 'flex' || source === 'yaesu' || source === 'kenwood' || source === 'tci' ? (
|
||||||
<span className="text-[11px] font-medium text-muted-foreground">
|
<span className="text-[11px] font-medium text-muted-foreground">
|
||||||
{source === 'flex'
|
{source === 'flex'
|
||||||
? (connected ? t('wkp.cwxReady') : t('wkp.cwxOffline'))
|
? (connected ? t('wkp.cwxReady') : t('wkp.cwxOffline'))
|
||||||
: source === 'yaesu' || source === 'kenwood'
|
: source === 'yaesu' || source === 'kenwood' || source === 'tci'
|
||||||
? (connected ? t('wkp.rigReady') : t('wkp.rigOffline'))
|
? (connected ? t('wkp.rigReady') : t('wkp.rigOffline'))
|
||||||
: (connected ? t('wkp.civReady') : t('wkp.civOffline'))}
|
: (connected ? t('wkp.civReady') : t('wkp.civOffline'))}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -0,0 +1,555 @@
|
|||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The preview fills whatever room the centre pane offers — a label cut off at
|
||||||
|
// the edge cannot be judged, and 90 mm across a fixed 720 px wasted half the
|
||||||
|
// window. Measured live so a resize re-fits.
|
||||||
|
const PREVIEW_MIN_SCALE = 2;
|
||||||
|
|
||||||
|
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 paneRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [paneSize, setPaneSize] = useState({ w: 720, h: 420 });
|
||||||
|
useEffect(() => {
|
||||||
|
const el = paneRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const ro = new ResizeObserver(() => {
|
||||||
|
setPaneSize({ w: el.clientWidth, h: el.clientHeight });
|
||||||
|
});
|
||||||
|
ro.observe(el);
|
||||||
|
return () => ro.disconnect();
|
||||||
|
}, [open, tpl != 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;
|
||||||
|
// Leave room for the pane's padding and the two control strips above and
|
||||||
|
// below the canvas; never shrink below a scale where 8 pt is readable.
|
||||||
|
const availW = Math.max(200, paneSize.w - 56);
|
||||||
|
const availH = Math.max(120, paneSize.h - 130);
|
||||||
|
return Math.max(PREVIEW_MIN_SCALE, Math.min(availW / stock.w_mm, availH / stock.h_mm));
|
||||||
|
}, [stock, paneSize]);
|
||||||
|
|
||||||
|
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 ref={paneRef} 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,502 @@
|
|||||||
|
// Label printing — the paper-QSL labelling session, in three steps:
|
||||||
|
//
|
||||||
|
// 1. PICK the contacts (preloaded with the R/Q paper queue), grouped by
|
||||||
|
// callsign — several QSOs of the same station share one card.
|
||||||
|
// 2. REVIEW each recipient: routing (direct / bureau / via manager), the
|
||||||
|
// address checked and edited by hand, a QRZ fetch to fill it.
|
||||||
|
// 3. PRINT ONE PDF holding every label of the session (each page at its
|
||||||
|
// own physical size), opened straight in the system viewer — the
|
||||||
|
// operator prints from there — then mark the contacts sent
|
||||||
|
// (date + via) in the log.
|
||||||
|
//
|
||||||
|
// The pages are rasterised by the designer's own renderer at the stock's dpi:
|
||||||
|
// what the designer previewed is what the PDF carries.
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import { X, Printer, RefreshCw, ChevronRight, ChevronLeft, Check, Loader2 } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
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 {
|
||||||
|
LabelPaperQueue, LabelListStocks, LabelListTemplates, LabelGetTemplate,
|
||||||
|
LabelOpenPDF, LookupCallsignFresh, BulkUpdateQSL, GetActiveProfile,
|
||||||
|
} from '../../../wailsjs/go/main/App';
|
||||||
|
import type { LabelSample, LabelStock, LabelTemplate } from './labelTypes';
|
||||||
|
import { rasterize } from './labelRender';
|
||||||
|
|
||||||
|
interface Props { open: boolean; onClose: () => void }
|
||||||
|
|
||||||
|
type Routing = 'direct' | 'bureau' | 'via';
|
||||||
|
|
||||||
|
interface Station {
|
||||||
|
call: string;
|
||||||
|
qsos: any[]; // raw QSO rows, newest first
|
||||||
|
checked: boolean;
|
||||||
|
routing: Routing;
|
||||||
|
via: string; // manager callsign when routing = via
|
||||||
|
address: string; // multiline, the text that will be printed — verbatim
|
||||||
|
// Whose address the box holds: the DX's prefill, the manager's fetch, or the
|
||||||
|
// operator's own edit. Routing changes recompute the first two and must never
|
||||||
|
// touch the third — an address typed by hand is not the app's to replace.
|
||||||
|
addrFor: 'dx' | 'mgr' | 'user' | 'none';
|
||||||
|
fetching?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TplInfo { id: number; name: string; kind: string; stock_id: number; is_default: boolean }
|
||||||
|
|
||||||
|
// One label's worth of QSO rows, in the designer's sample shape.
|
||||||
|
function toSample(q: any): LabelSample {
|
||||||
|
const d = new Date(q.qso_date);
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return {
|
||||||
|
callsign: q.callsign ?? '',
|
||||||
|
qso_date: `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`,
|
||||||
|
time_on: `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`,
|
||||||
|
band: q.band ?? '', mode: q.mode ?? '',
|
||||||
|
freq: q.freq_hz ? (q.freq_hz / 1e6).toFixed(3) : '',
|
||||||
|
rst_sent: q.rst_sent ?? '', rst_rcvd: q.rst_rcvd ?? '',
|
||||||
|
name: q.name ?? '', qth: q.qth ?? '', country: q.country ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedupeLines drops empties and any line already CONTAINED in an earlier one:
|
||||||
|
// the log often holds "20370 Casablanca Morocco" as the address AND "20370
|
||||||
|
// CASABLANCA" as the QTH AND "Morocco" as the country, and printing all three
|
||||||
|
// stacks the same city three times on the envelope.
|
||||||
|
function dedupeLines(lines: Array<any>): string[] {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const raw of lines) {
|
||||||
|
const l = String(raw ?? '').trim();
|
||||||
|
if (!l) continue;
|
||||||
|
const low = l.toLowerCase();
|
||||||
|
if (out.some((prev) => prev.toLowerCase().includes(low))) continue;
|
||||||
|
out.push(l);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function initialAddress(q: any): string {
|
||||||
|
return dedupeLines([q.name, q.address, q.qth, q.country]).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LabelPrintModal({ open, onClose }: Props) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const [step, setStep] = useState<'pick' | 'review' | 'print'>('pick');
|
||||||
|
const [stations, setStations] = useState<Station[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const [stocks, setStocks] = useState<LabelStock[]>([]);
|
||||||
|
const [tpls, setTpls] = useState<TplInfo[]>([]);
|
||||||
|
const [doQso, setDoQso] = useState(true);
|
||||||
|
const [doAddr, setDoAddr] = useState(true);
|
||||||
|
const [doReturn, setDoReturn] = useState(false);
|
||||||
|
const [qsoTplId, setQsoTplId] = useState(0);
|
||||||
|
const [addrTplId, setAddrTplId] = useState(0);
|
||||||
|
const [retTplId, setRetTplId] = useState(0);
|
||||||
|
const [myAddress, setMyAddress] = useState('');
|
||||||
|
const [myVars, setMyVars] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
|
// Rasterised pages per kind — kept separate for the previews, concatenated
|
||||||
|
// (with each page's own mm size) into the single PDF.
|
||||||
|
type Page = { png: string; w_mm: number; h_mm: number };
|
||||||
|
const [pages, setPages] = useState<{ qso: Page[]; addr: Page[]; ret: Page[] }>({ qso: [], addr: [], ret: [] });
|
||||||
|
const [building, setBuilding] = useState(false);
|
||||||
|
const [pdfPath, setPdfPath] = useState('');
|
||||||
|
const [markDate, setMarkDate] = useState(() => new Date().toISOString().slice(0, 10));
|
||||||
|
const [marked, setMarked] = useState(0);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true); setError('');
|
||||||
|
try {
|
||||||
|
const rows: any[] = (await LabelPaperQueue()) ?? [];
|
||||||
|
// Group by callsign, newest first inside each group.
|
||||||
|
const by = new Map<string, any[]>();
|
||||||
|
for (const q of rows) {
|
||||||
|
const c = String(q.callsign ?? '').toUpperCase();
|
||||||
|
if (!by.has(c)) by.set(c, []);
|
||||||
|
by.get(c)!.push(q);
|
||||||
|
}
|
||||||
|
setStations([...by.entries()].map(([call, qsos]) => {
|
||||||
|
const via = String(qsos[0]?.qsl_via ?? '').trim();
|
||||||
|
// Via a manager, the DX's own address is exactly the wrong thing to
|
||||||
|
// print on the envelope — start empty and let the QRZ fetch fill in the
|
||||||
|
// MANAGER's.
|
||||||
|
const address = via ? '' : initialAddress(qsos[0]);
|
||||||
|
return {
|
||||||
|
call, qsos, checked: true,
|
||||||
|
routing: via ? 'via' as Routing : (address.split('\n').length >= 3 ? 'direct' as Routing : 'bureau' as Routing),
|
||||||
|
via, address, addrFor: (via ? 'none' : 'dx') as Station['addrFor'],
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
const st = (await LabelListStocks()) as any as LabelStock[];
|
||||||
|
setStocks(st);
|
||||||
|
const tl = ((await LabelListTemplates()) ?? []) as any as TplInfo[];
|
||||||
|
setTpls(tl);
|
||||||
|
const def = (kind: string) => tl.find((x) => x.kind === kind && x.is_default) ?? tl.find((x) => x.kind === kind);
|
||||||
|
setQsoTplId(def('qso')?.id ?? 0);
|
||||||
|
setAddrTplId(def('address')?.id ?? 0);
|
||||||
|
setRetTplId(def('address')?.id ?? 0);
|
||||||
|
const p: any = await GetActiveProfile().catch(() => null);
|
||||||
|
const mv = {
|
||||||
|
MYCALL: p?.callsign ?? '', MYNAME: p?.op_name ?? p?.operator ?? '',
|
||||||
|
MYSTREET: p?.my_street ?? '', MYZIP: p?.my_postal_code ?? '',
|
||||||
|
MYCITY: p?.my_city ?? '', MYCOUNTRY: p?.my_country ?? '',
|
||||||
|
};
|
||||||
|
setMyVars(mv);
|
||||||
|
setMyAddress([mv.MYNAME && `${mv.MYNAME} · ${mv.MYCALL}` || mv.MYCALL, mv.MYSTREET,
|
||||||
|
[mv.MYZIP, mv.MYCITY].filter(Boolean).join(' '), mv.MYCOUNTRY]
|
||||||
|
.map((x) => String(x ?? '').trim()).filter(Boolean).join('\n'));
|
||||||
|
} catch (e: any) { setError(String(e?.message ?? e)); }
|
||||||
|
setLoading(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setStep('pick'); setPages({ qso: [], addr: [], ret: [] }); setPdfPath(''); setMarked(0);
|
||||||
|
void load();
|
||||||
|
}, [open, load]);
|
||||||
|
|
||||||
|
const patchStation = (i: number, p: Partial<Station>) =>
|
||||||
|
setStations((l) => l.map((s, j) => (j === i ? { ...s, ...p } : s)));
|
||||||
|
|
||||||
|
async function fetchAddress(i: number) {
|
||||||
|
const s = stations[i];
|
||||||
|
const target = s.routing === 'via' && s.via.trim() ? s.via.trim().toUpperCase() : s.call;
|
||||||
|
patchStation(i, { fetching: true });
|
||||||
|
try {
|
||||||
|
const r: any = await LookupCallsignFresh(target, '');
|
||||||
|
// A postal address needs a STREET (or at least a name and a town). A
|
||||||
|
// lookup that fell back to cty.dat answers with a country alone —
|
||||||
|
// overwriting a reviewed address with a bare country is strictly worse
|
||||||
|
// than saying nothing was found, and losing the address is what was
|
||||||
|
// reported.
|
||||||
|
const street = String(r?.address ?? '').trim();
|
||||||
|
if (!street && !(String(r?.name ?? '').trim() && String(r?.qth ?? '').trim())) {
|
||||||
|
patchStation(i, { fetching: false });
|
||||||
|
setError(t('lpr.noAddress', { call: target }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lines = dedupeLines([
|
||||||
|
r?.name, street,
|
||||||
|
[r?.zip, r?.qth].filter(Boolean).join(' '),
|
||||||
|
r?.country,
|
||||||
|
]);
|
||||||
|
patchStation(i, {
|
||||||
|
address: lines.join('\n'), fetching: false,
|
||||||
|
addrFor: target === s.call ? 'dx' : 'mgr',
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
patchStation(i, { fetching: false });
|
||||||
|
setError(String(e?.message ?? e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const picked = stations.filter((s) => s.checked);
|
||||||
|
const needAddress = picked.filter((s) => s.routing !== 'bureau');
|
||||||
|
|
||||||
|
// ── step 3: build the pages ───────────────────────────────────────────
|
||||||
|
async function buildPages() {
|
||||||
|
setBuilding(true); setError('');
|
||||||
|
try {
|
||||||
|
const getTpl = async (id: number): Promise<{ tpl: LabelTemplate; stock: LabelStock } | null> => {
|
||||||
|
if (!id) return null;
|
||||||
|
const tpl = JSON.parse(await LabelGetTemplate(id)) as LabelTemplate;
|
||||||
|
const stock = stocks.find((x) => x.id === tpl.stock_id) ?? stocks[0];
|
||||||
|
return stock ? { tpl, stock } : null;
|
||||||
|
};
|
||||||
|
const out = { qso: [] as Page[], addr: [] as Page[], ret: [] as Page[] };
|
||||||
|
const page = (png: string, stock: LabelStock): Page => ({ png, w_mm: stock.w_mm, h_mm: stock.h_mm });
|
||||||
|
if (doQso) {
|
||||||
|
const got = await getTpl(qsoTplId);
|
||||||
|
if (!got) throw new Error(t('lpr.noQsoTpl'));
|
||||||
|
const table = got.tpl.elements.find((e) => e.type === 'qso_table');
|
||||||
|
const per = Math.max(1, table?.rows_max ?? 4);
|
||||||
|
for (const s of picked) {
|
||||||
|
const vars = { CALL: s.call, NAME: s.qsos[0]?.name ?? '', QTH: s.qsos[0]?.qth ?? '', COUNTRY: s.qsos[0]?.country ?? '', VIA: s.via, ...myVars };
|
||||||
|
for (let i = 0; i < s.qsos.length; i += per) {
|
||||||
|
out.qso.push(page(rasterize(got.tpl, got.stock, { vars, qsos: s.qsos.slice(i, i + per).map(toSample) }), got.stock));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (doAddr) {
|
||||||
|
const got = await getTpl(addrTplId);
|
||||||
|
if (!got) throw new Error(t('lpr.noAddrTpl'));
|
||||||
|
for (const s of needAddress) {
|
||||||
|
// The REVIEWED text wins: the template's address block prints these
|
||||||
|
// lines verbatim — that is what "check the address first" means.
|
||||||
|
const tpl: LabelTemplate = {
|
||||||
|
...got.tpl,
|
||||||
|
elements: got.tpl.elements.map((e) =>
|
||||||
|
e.type === 'addr_block' ? { ...e, lines: s.address.split('\n') } : e),
|
||||||
|
};
|
||||||
|
const vars = { CALL: s.call, VIA: s.via, ...myVars };
|
||||||
|
out.addr.push(page(rasterize(tpl, got.stock, { vars, qsos: [] }), got.stock));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (doReturn) {
|
||||||
|
const got = await getTpl(retTplId);
|
||||||
|
if (!got) throw new Error(t('lpr.noAddrTpl'));
|
||||||
|
const tpl: LabelTemplate = {
|
||||||
|
...got.tpl,
|
||||||
|
elements: got.tpl.elements.map((e) =>
|
||||||
|
e.type === 'addr_block' ? { ...e, lines: myAddress.split('\n') } : e),
|
||||||
|
};
|
||||||
|
// One per envelope that needs a return slip — the direct/via ones.
|
||||||
|
const n = Math.max(1, needAddress.length);
|
||||||
|
const one = page(rasterize(tpl, got.stock, { vars: { ...myVars, CALL: myVars.MYCALL }, qsos: [] }), got.stock);
|
||||||
|
for (let i = 0; i < n; i++) out.ret.push(one);
|
||||||
|
}
|
||||||
|
setPages(out);
|
||||||
|
} catch (e: any) { setError(String(e?.message ?? e)); }
|
||||||
|
setBuilding(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allPages = [...pages.qso, ...pages.addr, ...pages.ret];
|
||||||
|
|
||||||
|
async function openPdf() {
|
||||||
|
try {
|
||||||
|
const path = await LabelOpenPDF(allPages as any);
|
||||||
|
if (path) setPdfPath(path as string);
|
||||||
|
} catch (e: any) { setError(String(e?.message ?? e)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function markSent() {
|
||||||
|
try {
|
||||||
|
const date = markDate.replace(/-/g, '');
|
||||||
|
let n = 0;
|
||||||
|
const groups: Array<[Station[], string]> = [
|
||||||
|
[picked.filter((s) => s.routing === 'bureau'), 'B'],
|
||||||
|
[picked.filter((s) => s.routing !== 'bureau'), 'D'],
|
||||||
|
];
|
||||||
|
for (const [list, via] of groups) {
|
||||||
|
const ids = list.flatMap((s) => s.qsos.map((q) => q.id));
|
||||||
|
if (ids.length === 0) continue;
|
||||||
|
n += (await BulkUpdateQSL(ids, { sent_status: 'Y', sent_date: date, via, rcvd_status: '', rcvd_date: '', rcvd_via: '', notes: '', comment: '' } as any)) as number;
|
||||||
|
}
|
||||||
|
setMarked(n);
|
||||||
|
} catch (e: any) { setError(String(e?.message ?? e)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const kindBlock = (kind: 'qso' | 'addr' | 'ret', title: string) => {
|
||||||
|
const pg = pages[kind];
|
||||||
|
if (pg.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-border p-3 space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-semibold">{title}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{t('lpr.pageCount', { n: pg.length })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 overflow-x-auto pb-1">
|
||||||
|
{pg.slice(0, 8).map((p, i) => (
|
||||||
|
<img key={i} src={p.png} className="h-20 border border-border rounded-sm bg-white shrink-0" />
|
||||||
|
))}
|
||||||
|
{pg.length > 8 && <span className="text-xs text-muted-foreground self-center">+{pg.length - 8}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
const sumQsos = picked.reduce((a, s) => a + s.qsos.length, 0);
|
||||||
|
|
||||||
|
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-5xl h-[90vh] flex flex-col overflow-hidden">
|
||||||
|
<div className="flex items-center gap-3 px-4 py-2.5 border-b border-border shrink-0">
|
||||||
|
<Printer className="size-4 text-primary" />
|
||||||
|
<span className="font-semibold text-sm">{t('lpr.title')}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{step === 'pick' ? t('lpr.step1') : step === 'review' ? t('lpr.step2') : t('lpr.step3')}
|
||||||
|
</span>
|
||||||
|
<div className="flex-1" />
|
||||||
|
<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 overflow-y-auto p-4">
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center h-full text-muted-foreground gap-2">
|
||||||
|
<Loader2 className="size-4 animate-spin" /> …
|
||||||
|
</div>
|
||||||
|
) : step === 'pick' ? (
|
||||||
|
stations.length === 0 ? (
|
||||||
|
<div className="text-sm text-muted-foreground text-center pt-16 max-w-md mx-auto leading-relaxed">
|
||||||
|
{t('lpr.emptyQueue')}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center gap-2 pb-1 text-xs text-muted-foreground">
|
||||||
|
<button type="button" className="underline underline-offset-2" onClick={() => setStations((l) => l.map((s) => ({ ...s, checked: true })))}>{t('lpr.all')}</button>
|
||||||
|
<button type="button" className="underline underline-offset-2" onClick={() => setStations((l) => l.map((s) => ({ ...s, checked: false })))}>{t('lpr.none')}</button>
|
||||||
|
<div className="flex-1" />
|
||||||
|
<span>{t('lpr.pickSummary', { s: picked.length, q: sumQsos })}</span>
|
||||||
|
</div>
|
||||||
|
{stations.map((s, i) => (
|
||||||
|
<label key={s.call} className="flex items-center gap-2.5 rounded-md border border-border/60 px-2.5 py-1.5 text-sm cursor-pointer hover:bg-muted/40">
|
||||||
|
<Checkbox checked={s.checked} onCheckedChange={(c) => patchStation(i, { checked: !!c })} />
|
||||||
|
<span className="font-mono font-bold w-28">{s.call}</span>
|
||||||
|
<span className="text-xs text-muted-foreground w-16">{s.qsos.length} QSO{s.qsos.length > 1 ? 's' : ''}</span>
|
||||||
|
<span className="text-xs text-muted-foreground flex-1 truncate">
|
||||||
|
{s.qsos.map((q) => `${q.band ?? ''} ${q.mode ?? ''}`).slice(0, 5).join(' · ')}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground truncate max-w-40">{s.qsos[0]?.country ?? ''}</span>
|
||||||
|
{s.via && <span className="text-[10px] px-1.5 rounded bg-info-muted text-info-muted-foreground">via {s.via}</span>}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
) : step === 'review' ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{picked.map((s) => {
|
||||||
|
const i = stations.indexOf(s);
|
||||||
|
return (
|
||||||
|
<div key={s.call} className="rounded-lg border border-border p-2.5 flex gap-3">
|
||||||
|
<div className="w-64 shrink-0 space-y-1.5">
|
||||||
|
<div className="font-mono font-bold">{s.call}
|
||||||
|
<span className="ml-2 text-xs font-normal text-muted-foreground">{s.qsos.length} QSO{s.qsos.length > 1 ? 's' : ''}</span>
|
||||||
|
</div>
|
||||||
|
<Select value={s.routing} onValueChange={(v) => {
|
||||||
|
const routing = v as Routing;
|
||||||
|
const patch: Partial<Station> = { routing };
|
||||||
|
if (s.addrFor !== 'user') {
|
||||||
|
// The box follows the routing while the operator has
|
||||||
|
// not typed in it: via → empty (fetch the manager),
|
||||||
|
// direct → the DX's own prefill.
|
||||||
|
patch.address = routing === 'via' ? '' : initialAddress(s.qsos[0]);
|
||||||
|
patch.addrFor = routing === 'via' ? 'none' : 'dx';
|
||||||
|
}
|
||||||
|
patchStation(i, patch);
|
||||||
|
}}>
|
||||||
|
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="direct">{t('lpr.direct')}</SelectItem>
|
||||||
|
<SelectItem value="bureau">{t('lpr.bureau')}</SelectItem>
|
||||||
|
<SelectItem value="via">{t('lpr.viaMgr')}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
{s.routing === 'via' && (
|
||||||
|
<Input className="h-7 text-xs font-mono uppercase" placeholder={t('lpr.mgrPh')}
|
||||||
|
value={s.via} onChange={(ev) => patchStation(i, { via: ev.target.value })} />
|
||||||
|
)}
|
||||||
|
{s.routing !== 'bureau' && (
|
||||||
|
<Button size="sm" variant="outline" className="h-7 text-xs w-full"
|
||||||
|
disabled={s.fetching}
|
||||||
|
onClick={() => void fetchAddress(i)}>
|
||||||
|
{s.fetching ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
|
||||||
|
{t('lpr.fetchQrz')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{s.routing === 'bureau' ? (
|
||||||
|
<div className="flex-1 text-xs text-muted-foreground self-center">{t('lpr.bureauHint')}</div>
|
||||||
|
) : (
|
||||||
|
<textarea
|
||||||
|
className={cn('flex-1 rounded-md border bg-background px-2 py-1 text-sm font-mono',
|
||||||
|
s.address.trim() ? 'border-input' : 'border-danger')}
|
||||||
|
rows={4}
|
||||||
|
placeholder={s.routing === 'via' ? t('lpr.mgrAddressPh') : t('lpr.addressPh')}
|
||||||
|
value={s.address}
|
||||||
|
onChange={(ev) => patchStation(i, { address: ev.target.value, addrFor: 'user' })} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* what to print */}
|
||||||
|
<div className="rounded-lg border border-border p-3 space-y-2">
|
||||||
|
<div className="text-sm font-semibold">{t('lpr.whatToPrint')}</div>
|
||||||
|
{([
|
||||||
|
['qso', doQso, setDoQso, qsoTplId, setQsoTplId, 'qso', t('lpr.kQso')],
|
||||||
|
['addr', doAddr, setDoAddr, addrTplId, setAddrTplId, 'address', t('lpr.kAddr')],
|
||||||
|
['ret', doReturn, setDoReturn, retTplId, setRetTplId, 'address', t('lpr.kRet')],
|
||||||
|
] as const).map(([key, on, setOn, tplId, setTplId, kind, label]) => (
|
||||||
|
<div key={key} className="flex items-center gap-2">
|
||||||
|
<label className="flex items-center gap-1.5 text-sm cursor-pointer w-64">
|
||||||
|
<Checkbox checked={on} onCheckedChange={(c) => (setOn as any)(!!c)} /> {label}
|
||||||
|
</label>
|
||||||
|
<Select value={String(tplId || '')} onValueChange={(v) => (setTplId as any)(parseInt(v, 10))}>
|
||||||
|
<SelectTrigger className="h-7 text-xs w-72"><SelectValue placeholder={t('lpr.pickTpl')} /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{tpls.filter((x) => x.kind === kind).map((x) => (
|
||||||
|
<SelectItem key={x.id} value={String(x.id)}>{x.name}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{doReturn && (
|
||||||
|
<div className="flex items-start gap-2 pl-6">
|
||||||
|
<span className="text-xs text-muted-foreground pt-1 w-24">{t('lpr.myAddress')}</span>
|
||||||
|
<textarea className="flex-1 max-w-96 rounded-md border border-input bg-background px-2 py-1 text-xs font-mono" rows={4}
|
||||||
|
value={myAddress} onChange={(ev) => setMyAddress(ev.target.value)} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Button size="sm" className="h-8" onClick={() => void buildPages()} disabled={building || (!doQso && !doAddr && !doReturn)}>
|
||||||
|
{building ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}
|
||||||
|
{t('lpr.build')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{kindBlock('qso', t('lpr.kQso'))}
|
||||||
|
{kindBlock('addr', t('lpr.kAddr'))}
|
||||||
|
{kindBlock('ret', t('lpr.kRet'))}
|
||||||
|
{allPages.length > 0 && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button size="sm" className="h-8" onClick={() => void openPdf()}>
|
||||||
|
<Printer className="size-3.5" /> {t('lpr.openPdf', { n: allPages.length })}
|
||||||
|
</Button>
|
||||||
|
{pdfPath && <span className="text-xs text-success flex items-center gap-1"><Check className="size-3.5" />{pdfPath}</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* mark as sent */}
|
||||||
|
{(pages.qso.length > 0 || pages.addr.length > 0) && (
|
||||||
|
<div className="rounded-lg border border-border p-3 space-y-2">
|
||||||
|
<div className="text-sm font-semibold">{t('lpr.markTitle')}</div>
|
||||||
|
<div className="text-xs text-muted-foreground">{t('lpr.markHint')}</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input type="date" className="h-8 rounded-md border border-input bg-background px-2 text-xs"
|
||||||
|
value={markDate} onChange={(ev) => setMarkDate(ev.target.value)} />
|
||||||
|
<Button size="sm" className="h-8" onClick={() => void markSent()} disabled={marked > 0}>
|
||||||
|
<Check className="size-3.5" /> {t('lpr.markBtn', { n: sumQsos })}
|
||||||
|
</Button>
|
||||||
|
{marked > 0 && <span className="text-xs text-success">{t('lpr.markDone', { n: marked })}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* footer nav */}
|
||||||
|
<div className="flex items-center gap-2 px-4 py-2.5 border-t border-border shrink-0">
|
||||||
|
{step !== 'pick' && (
|
||||||
|
<Button variant="outline" size="sm" className="h-8"
|
||||||
|
onClick={() => setStep(step === 'print' ? 'review' : 'pick')}>
|
||||||
|
<ChevronLeft className="size-3.5" /> {t('lpr.back')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<div className="flex-1" />
|
||||||
|
{step === 'pick' && (
|
||||||
|
<Button size="sm" className="h-8" disabled={picked.length === 0} onClick={() => setStep('review')}>
|
||||||
|
{t('lpr.next')} <ChevronRight className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{step === 'review' && (
|
||||||
|
<Button size="sm" className="h-8"
|
||||||
|
disabled={needAddress.some((s) => !s.address.trim())}
|
||||||
|
title={needAddress.some((s) => !s.address.trim()) ? t('lpr.missingAddr') : undefined}
|
||||||
|
onClick={() => setStep('print')}>
|
||||||
|
{t('lpr.next')} <ChevronRight className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
// 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// rasterize renders one label at the stock's dpi and returns a PNG data URL —
|
||||||
|
// the pages handed to the PDF exporter. Same renderer as the preview, only the
|
||||||
|
// scale changes, which is the whole guarantee of the feature.
|
||||||
|
export function rasterize(
|
||||||
|
t: LabelTemplate, stock: LabelStock, data: RenderData,
|
||||||
|
): string {
|
||||||
|
const scale = (stock.dpi || 300) / 25.4; // px per mm
|
||||||
|
const cv = document.createElement('canvas');
|
||||||
|
cv.width = Math.round(stock.w_mm * scale);
|
||||||
|
cv.height = Math.round(stock.h_mm * scale);
|
||||||
|
const ctx = cv.getContext('2d')!;
|
||||||
|
render(ctx, t, stock, data, scale);
|
||||||
|
return cv.toDataURL('image/png');
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
+102
-4
@@ -128,8 +128,57 @@ const en: Dict = {
|
|||||||
'mx.tipDxConf': 'Entity confirmed (other callsign)', 'mx.tipDxWork': 'Entity worked (other callsign)',
|
'mx.tipDxConf': 'Entity confirmed (other callsign)', 'mx.tipDxWork': 'Entity worked (other callsign)',
|
||||||
'mx.tipNone': 'Never worked', 'mx.tipClick': 'click to list the QSOs',
|
'mx.tipNone': 'Never worked', 'mx.tipClick': 'click to list the QSOs',
|
||||||
'icmp.scopeNoStream': 'This radio does not send its scope over CI-V — its own screen still works.',
|
'icmp.scopeNoStream': 'This radio does not send its scope over CI-V — its own screen still works.',
|
||||||
|
'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)',
|
'gen.miles': 'Distances in miles', 'gen.milesHint': '(instead of kilometres)',
|
||||||
|
'tools.labelDesigner': "Label Designer…",
|
||||||
|
'tools.labelPrint': "Print QSL labels…",
|
||||||
|
'lpr.title': "Print QSL labels",
|
||||||
|
'lpr.step1': "1 · pick the contacts", 'lpr.step2': "2 · check the addresses", 'lpr.step3': "3 · print and record",
|
||||||
|
'lpr.emptyQueue': "No paper QSL is waiting. Mark contacts as Requested or Queued (QSL sent status R/Q) — in the QSL Manager's Paper QSL view or the QSO editor — and they will appear here.",
|
||||||
|
'lpr.all': "all", 'lpr.none': "none", 'lpr.pickSummary': "{s} station(s) · {q} QSO(s)",
|
||||||
|
'lpr.direct': "Direct", 'lpr.bureau': "Bureau", 'lpr.viaMgr': "Via manager", 'lpr.mgrPh': "Manager callsign",
|
||||||
|
'lpr.fetchQrz': "Fetch address (QRZ)", 'lpr.noAddress': "No address found for {call}.",
|
||||||
|
'lpr.bureauHint': "Bureau: no envelope, so no address label — the QSO label is enough.",
|
||||||
|
'lpr.addressPh': "Name\nStreet\nZIP City\nCountry",
|
||||||
|
'lpr.missingAddr': "A direct or via-manager station still has an empty address.",
|
||||||
|
'lpr.whatToPrint': "Labels to print", 'lpr.pickTpl': "Pick a template…",
|
||||||
|
'lpr.kQso': "QSO labels", 'lpr.kAddr': "Address labels", 'lpr.kRet': "My return-address labels",
|
||||||
|
'lpr.myAddress': "My address", 'lpr.build': "Build the labels",
|
||||||
|
'lpr.noQsoTpl': "No QSO label template — create one in the Label Designer first.",
|
||||||
|
'lpr.noAddrTpl': "No address label template — create one in the Label Designer first.",
|
||||||
|
'lpr.pageCount': "{n} label(s) — one PDF page each",
|
||||||
|
'lpr.savePdf': "Save PDF & open",
|
||||||
|
'lpr.openPdf': "Open the PDF ({n} labels)", 'lpr.mgrAddressPh': "Manager address — use Fetch (QRZ)",
|
||||||
|
'lpr.markTitle': "Record in the log", 'lpr.markBtn': "Mark {n} QSO(s) sent",
|
||||||
|
'lpr.markHint': "Sets QSL sent = Y with this date; via becomes B for bureau and D for direct or manager.",
|
||||||
|
'lpr.markDone': "{n} QSO(s) updated.",
|
||||||
|
'lpr.back': "Back", 'lpr.next': "Next",
|
||||||
|
'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.qrzTitle': 'Open this callsign on QRZ.com',
|
||||||
|
'qslm.lotwDetail': 'QSL details',
|
||||||
|
'qslm.lotwDetailTitle': 'Ask LoTW for the QSL date and the station details (grid, state, county) as well as the confirmation. LoTW takes about ten times longer to build that report — two minutes against twenty on the same account — and marking a confirmation needs none of it. Forced on when adding the QSOs not found, which have no other source for those fields.',
|
||||||
'qslm.lotwAllCalls': 'All my callsigns',
|
'qslm.lotwAllCalls': 'All my callsigns',
|
||||||
'qslm.lotwAllCallsTitle': "Download the confirmations of every callsign on the LoTW account, not just this profile's. A QSO made as F4BPO/P or TM2Q is confirmed at LoTW but never reaches an F4BPO profile without this.",
|
'qslm.lotwAllCallsTitle': "Download the confirmations of every callsign on the LoTW account, not just this profile's. A QSO made as F4BPO/P or TM2Q is confirmed at LoTW but never reaches an F4BPO profile without this.",
|
||||||
'awp.filterSlotsNotCfmd': 'Slots to confirm', 'awp.slotGap': 'slots to confirm',
|
'awp.filterSlotsNotCfmd': 'Slots to confirm', 'awp.slotGap': 'slots to confirm',
|
||||||
@@ -409,10 +458,10 @@ const en: Dict = {
|
|||||||
'chp.noPriorQso': 'No prior QSO with this callsign.', 'chp.first': 'First', 'chp.last': 'Last', 'chp.dateUtc': 'Date UTC', 'chp.band': 'Band', 'chp.mode': 'Mode',
|
'chp.noPriorQso': 'No prior QSO with this callsign.', 'chp.first': 'First', 'chp.last': 'Last', 'chp.dateUtc': 'Date UTC', 'chp.band': 'Band', 'chp.mode': 'Mode',
|
||||||
'chp.lotwRcvd': 'LoTW rcvd', 'chp.bureauRcvd': 'Bureau rcvd', 'chp.olderQsos': '+ {n} older QSOs',
|
'chp.lotwRcvd': 'LoTW rcvd', 'chp.bureauRcvd': 'Bureau rcvd', 'chp.olderQsos': '+ {n} older QSOs',
|
||||||
'bmp.statusNew': 'NEW DXCC (entity never worked)', 'bmp.statusNewBandMode': 'NEW BAND+MODE (neither worked with this entity)', 'bmp.statusNewBand': 'NEW BAND (entity not worked on this band)', 'bmp.statusNewSlot': 'NEW SLOT (mode not worked on this band)', 'bmp.statusNewCall': 'NEW CALL (this callsign never worked on this band and mode)', 'bmp.statusNewMode': 'NEW MODE (mode never worked for this entity)',
|
'bmp.statusNew': 'NEW DXCC (entity never worked)', 'bmp.statusNewBandMode': 'NEW BAND+MODE (neither worked with this entity)', 'bmp.statusNewBand': 'NEW BAND (entity not worked on this band)', 'bmp.statusNewSlot': 'NEW SLOT (mode not worked on this band)', 'bmp.statusNewCall': 'NEW CALL (this callsign never worked on this band and mode)', 'bmp.statusNewMode': 'NEW MODE (mode never worked for this entity)',
|
||||||
'bmp.statusWorked': 'Worked (this band + mode already in log)', 'bmp.statusUnresolved': 'Entity not resolved', 'bmp.bandMap': 'Band map', 'bmp.notConfigured': 'Not configured for {band}.',
|
'bmp.statusWorked': 'Entity worked on this band and mode', 'bmp.statusUnresolved': 'Entity not resolved', 'bmp.bandMap': 'Band map', 'bmp.notConfigured': 'Not configured for {band}.',
|
||||||
'bmp.zoomOut': 'Zoom out', 'bmp.zoomIn': 'Zoom in', 'bmp.scrollToRig': 'Scroll to current rig frequency', 'bmp.moveLeft': 'Move band map to the left', 'bmp.moveRight': 'Move band map to the right', 'bmp.hide': 'Hide band map',
|
'bmp.zoomOut': 'Zoom out', 'bmp.zoomIn': 'Zoom in', 'bmp.scrollToRig': 'Scroll to current rig frequency', 'bmp.moveLeft': 'Move band map to the left', 'bmp.moveRight': 'Move band map to the right', 'bmp.hide': 'Hide band map',
|
||||||
'bmp.bandsLabel': 'Bands:', 'bmp.fit': 'FIT', 'bmp.ftx': 'FTx', 'bmp.hideFt': 'Hide FTx', 'bmp.hideFtTitle': 'Hide all digital (FT8/FT4/JS8/…) spots on every band map', 'bmp.fitBand': 'Fit to band', 'bmp.widthTip': 'Drag to resize — double-click to reset', 'bmp.fitTitle': 'Size each band map to show the whole band edge-to-edge',
|
'bmp.bandsLabel': 'Bands:', 'bmp.fit': 'FIT', 'bmp.ftx': 'FTx', 'bmp.hideFt': 'Hide FTx', 'bmp.hideFtTitle': 'Hide all digital (FT8/FT4/JS8/…) spots on every band map', 'bmp.fitBand': 'Fit to band', 'bmp.widthTip': 'Drag to resize — double-click to reset', 'bmp.fitTitle': 'Size each band map to show the whole band edge-to-edge',
|
||||||
'bmp.legendNewDxcc': 'New DXCC', 'bmp.legendNewBand': 'New band', 'bmp.legendNewSlot': 'New slot (mode)', 'bmp.openUnusual': 'unusual for the season', 'bmp.legendWorked': 'Worked', 'bmp.legendNewPota': 'New POTA', 'bmp.legendNewCounty': 'New county', 'bmp.legendWorkedCall': 'Callsign already worked', 'bmp.legendCW': 'CW', 'bmp.legendData': 'Data', 'bmp.legendPhone': 'Phone', 'bmp.footerHint': 'scroll · ctrl+wheel = zoom · ◎ = jump to rig', 'bmp.spotsHidden': '{n} FT8/FT4 spots hidden — top {max} kept (CW/SSB all shown)',
|
'bmp.legendNewDxcc': 'New DXCC', 'bmp.legendNewBand': 'New band', 'bmp.legendNewSlot': 'New slot (mode)', 'bmp.openUnusual': 'unusual for the season', 'bmp.legendWorked': 'Entity worked', 'bmp.legendNewPota': 'New POTA', 'bmp.legendNewCounty': 'New county', 'bmp.legendWorkedCall': 'Callsign already worked', 'bmp.legendCW': 'CW', 'bmp.legendData': 'Data', 'bmp.legendPhone': 'Phone', 'bmp.footerHint': 'scroll · ctrl+wheel = zoom · ◎ = jump to rig', 'bmp.spotsHidden': '{n} FT8/FT4 spots hidden — top {max} kept (CW/SSB all shown)',
|
||||||
'frm.welcome': 'Welcome to OpsLog', 'frm.intro': 'Set up your station to start logging. These fields stamp every QSO and can be changed later in Preferences → Station Information (and per profile).',
|
'frm.welcome': 'Welcome to OpsLog', 'frm.intro': 'Set up your station to start logging. These fields stamp every QSO and can be changed later in Preferences → Station Information (and per profile).',
|
||||||
'frm.callsign': 'Callsign', 'frm.locator': 'Locator', 'frm.operator': 'Operator', 'frm.operatorPh': 'same as callsign', 'frm.owner': 'Owner', 'frm.ownerPh': 'station owner callsign', 'frm.name': 'Name', 'frm.namePh': 'your first name',
|
'frm.callsign': 'Callsign', 'frm.locator': 'Locator', 'frm.operator': 'Operator', 'frm.operatorPh': 'same as callsign', 'frm.owner': 'Owner', 'frm.ownerPh': 'station owner callsign', 'frm.name': 'Name', 'frm.namePh': 'your first name',
|
||||||
'frm.awardRefs': 'Award reference lists', 'frm.awardRefsHint': 'IOTA · POTA · WWFF · SOTA — names & totals for those awards (optional, can take a minute).', 'frm.downloading': 'Downloading…', 'frm.reDownload': 'Re-download', 'frm.download': 'Download', 'frm.required': 'Callsign and locator are required.', 'frm.saving': 'Saving…', 'frm.startLogging': 'Start logging',
|
'frm.awardRefs': 'Award reference lists', 'frm.awardRefsHint': 'IOTA · POTA · WWFF · SOTA — names & totals for those awards (optional, can take a minute).', 'frm.downloading': 'Downloading…', 'frm.reDownload': 'Re-download', 'frm.download': 'Download', 'frm.required': 'Callsign and locator are required.', 'frm.saving': 'Saving…', 'frm.startLogging': 'Start logging',
|
||||||
@@ -624,8 +673,57 @@ const fr: Dict = {
|
|||||||
'mx.tipDxConf': 'Entité confirmée (autre indicatif)', 'mx.tipDxWork': 'Entité contactée (autre indicatif)',
|
'mx.tipDxConf': 'Entité confirmée (autre indicatif)', 'mx.tipDxWork': 'Entité contactée (autre indicatif)',
|
||||||
'mx.tipNone': 'Jamais contacté', 'mx.tipClick': 'cliquer pour lister les QSO',
|
'mx.tipNone': 'Jamais contacté', 'mx.tipClick': 'cliquer pour lister les QSO',
|
||||||
'icmp.scopeNoStream': "Cette radio n'envoie pas son scope en CI-V — son propre écran fonctionne toujours.",
|
'icmp.scopeNoStream': "Cette radio n'envoie pas son scope en CI-V — son propre écran fonctionne toujours.",
|
||||||
|
'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)',
|
'gen.miles': 'Distances en miles', 'gen.milesHint': '(au lieu des kilomètres)',
|
||||||
|
'tools.labelDesigner': "Créateur d'étiquettes…",
|
||||||
|
'tools.labelPrint': "Imprimer les étiquettes QSL…",
|
||||||
|
'lpr.title': "Imprimer les étiquettes QSL",
|
||||||
|
'lpr.step1': "1 · choisir les contacts", 'lpr.step2': "2 · vérifier les adresses", 'lpr.step3': "3 · imprimer et enregistrer",
|
||||||
|
'lpr.emptyQueue': "Aucune QSL papier en attente. Marquez des contacts Demandée ou En file (statut QSL envoyée R/Q) — dans la vue QSL papier du gestionnaire ou l'éditeur de QSO — et ils apparaîtront ici.",
|
||||||
|
'lpr.all': "tout", 'lpr.none': "aucun", 'lpr.pickSummary': "{s} station(s) · {q} QSO",
|
||||||
|
'lpr.direct': "Direct", 'lpr.bureau': "Bureau", 'lpr.viaMgr': "Via manager", 'lpr.mgrPh': "Indicatif du manager",
|
||||||
|
'lpr.fetchQrz': "Récupérer l'adresse (QRZ)", 'lpr.noAddress': "Aucune adresse trouvée pour {call}.",
|
||||||
|
'lpr.bureauHint': "Bureau : pas d'enveloppe, donc pas d'étiquette adresse — l'étiquette QSO suffit.",
|
||||||
|
'lpr.addressPh': "Nom\nRue\nCP Ville\nPays",
|
||||||
|
'lpr.missingAddr': "Une station en direct ou via manager n'a pas encore d'adresse.",
|
||||||
|
'lpr.whatToPrint': "Étiquettes à imprimer", 'lpr.pickTpl': "Choisir un modèle…",
|
||||||
|
'lpr.kQso': "Étiquettes QSO", 'lpr.kAddr': "Étiquettes adresse", 'lpr.kRet': "Mes étiquettes adresse retour",
|
||||||
|
'lpr.myAddress': "Mon adresse", 'lpr.build': "Composer les étiquettes",
|
||||||
|
'lpr.noQsoTpl': "Aucun modèle d'étiquette QSO — créez-en un dans le Créateur d'étiquettes.",
|
||||||
|
'lpr.noAddrTpl': "Aucun modèle d'étiquette adresse — créez-en un dans le Créateur d'étiquettes.",
|
||||||
|
'lpr.pageCount': "{n} étiquette(s) — une page PDF chacune",
|
||||||
|
'lpr.savePdf': "Enregistrer le PDF et ouvrir",
|
||||||
|
'lpr.openPdf': "Ouvrir le PDF ({n} étiquettes)", 'lpr.mgrAddressPh': "Adresse du manager — utilisez Récupérer (QRZ)",
|
||||||
|
'lpr.markTitle': "Enregistrer dans le log", 'lpr.markBtn': "Marquer {n} QSO envoyés",
|
||||||
|
'lpr.markHint': "Passe QSL envoyée = Y à cette date ; le moyen devient B pour bureau et D pour direct ou manager.",
|
||||||
|
'lpr.markDone': "{n} QSO mis à jour.",
|
||||||
|
'lpr.back': "Retour", 'lpr.next': "Suivant",
|
||||||
|
'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.qrzTitle': 'Ouvrir cet indicatif sur QRZ.com',
|
||||||
|
'qslm.lotwDetail': 'Détails QSL',
|
||||||
|
'qslm.lotwDetailTitle': "Demander à LoTW la date du QSL et les détails de la station (locator, état, comté) en plus de la confirmation. LoTW met environ dix fois plus longtemps à construire ce rapport — deux minutes contre vingt sur le même compte — et marquer une confirmation n'en a pas besoin. Forcé quand on ajoute les QSO absents, qui n'ont pas d'autre source pour ces champs.",
|
||||||
'qslm.lotwAllCalls': 'Tous mes indicatifs',
|
'qslm.lotwAllCalls': 'Tous mes indicatifs',
|
||||||
'qslm.lotwAllCallsTitle': "Télécharger les confirmations de tous les indicatifs du compte LoTW, pas seulement celui du profil. Un QSO fait en F4BPO/P ou TM2Q est confirmé chez LoTW mais n'atteint jamais un profil F4BPO sans cette option.",
|
'qslm.lotwAllCallsTitle': "Télécharger les confirmations de tous les indicatifs du compte LoTW, pas seulement celui du profil. Un QSO fait en F4BPO/P ou TM2Q est confirmé chez LoTW mais n'atteint jamais un profil F4BPO sans cette option.",
|
||||||
'awp.filterSlotsNotCfmd': 'Slots à confirmer', 'awp.slotGap': 'slots à confirmer',
|
'awp.filterSlotsNotCfmd': 'Slots à confirmer', 'awp.slotGap': 'slots à confirmer',
|
||||||
@@ -892,10 +990,10 @@ const fr: Dict = {
|
|||||||
'chp.noPriorQso': 'Aucun QSO antérieur avec cet indicatif.', 'chp.first': 'Premier', 'chp.last': 'Dernier', 'chp.dateUtc': 'Date UTC', 'chp.band': 'Bande', 'chp.mode': 'Mode',
|
'chp.noPriorQso': 'Aucun QSO antérieur avec cet indicatif.', 'chp.first': 'Premier', 'chp.last': 'Dernier', 'chp.dateUtc': 'Date UTC', 'chp.band': 'Bande', 'chp.mode': 'Mode',
|
||||||
'chp.lotwRcvd': 'LoTW reçue', 'chp.bureauRcvd': 'Bureau reçue', 'chp.olderQsos': '+ {n} QSO plus anciens',
|
'chp.lotwRcvd': 'LoTW reçue', 'chp.bureauRcvd': 'Bureau reçue', 'chp.olderQsos': '+ {n} QSO plus anciens',
|
||||||
'bmp.statusNew': 'NOUVEAU DXCC (entité jamais contactée)', 'bmp.statusNewBandMode': 'NOUVEAU BANDE+MODE (ni l’un ni l’autre fait avec cette entité)', 'bmp.statusNewBand': 'NOUVELLE BANDE (entité non contactée sur cette bande)', 'bmp.statusNewSlot': 'NOUVEAU MODE (mode non contacté sur cette bande)', 'bmp.statusNewCall': "CALL NEUF (indicatif jamais contacté sur cette bande et ce mode)", 'bmp.statusNewMode': 'NOUVEAU MODE (mode jamais contacté pour cette entité)',
|
'bmp.statusNew': 'NOUVEAU DXCC (entité jamais contactée)', 'bmp.statusNewBandMode': 'NOUVEAU BANDE+MODE (ni l’un ni l’autre fait avec cette entité)', 'bmp.statusNewBand': 'NOUVELLE BANDE (entité non contactée sur cette bande)', 'bmp.statusNewSlot': 'NOUVEAU MODE (mode non contacté sur cette bande)', 'bmp.statusNewCall': "CALL NEUF (indicatif jamais contacté sur cette bande et ce mode)", 'bmp.statusNewMode': 'NOUVEAU MODE (mode jamais contacté pour cette entité)',
|
||||||
'bmp.statusWorked': 'Contacté (cette bande + mode déjà au log)', 'bmp.statusUnresolved': 'Entité non résolue', 'bmp.bandMap': 'Carte de bande', 'bmp.notConfigured': 'Non configurée pour {band}.',
|
'bmp.statusWorked': 'Entité contactée sur cette bande et ce mode', 'bmp.statusUnresolved': 'Entité non résolue', 'bmp.bandMap': 'Carte de bande', 'bmp.notConfigured': 'Non configurée pour {band}.',
|
||||||
'bmp.zoomOut': 'Dézoomer', 'bmp.zoomIn': 'Zoomer', 'bmp.scrollToRig': 'Aller à la fréquence actuelle du poste', 'bmp.moveLeft': 'Déplacer la carte de bande à gauche', 'bmp.moveRight': 'Déplacer la carte de bande à droite', 'bmp.hide': 'Masquer la carte de bande',
|
'bmp.zoomOut': 'Dézoomer', 'bmp.zoomIn': 'Zoomer', 'bmp.scrollToRig': 'Aller à la fréquence actuelle du poste', 'bmp.moveLeft': 'Déplacer la carte de bande à gauche', 'bmp.moveRight': 'Déplacer la carte de bande à droite', 'bmp.hide': 'Masquer la carte de bande',
|
||||||
'bmp.bandsLabel': 'Bandes :', 'bmp.fit': 'FIT', 'bmp.ftx': 'FTx', 'bmp.hideFt': 'Masquer FTx', 'bmp.hideFtTitle': 'Masquer tous les spots numériques (FT8/FT4/JS8/…) sur toutes les cartes', 'bmp.fitBand': 'Ajuster à la bande', 'bmp.widthTip': 'Glisser pour redimensionner — double-clic pour réinitialiser', 'bmp.fitTitle': 'Dimensionner chaque carte pour afficher toute la bande',
|
'bmp.bandsLabel': 'Bandes :', 'bmp.fit': 'FIT', 'bmp.ftx': 'FTx', 'bmp.hideFt': 'Masquer FTx', 'bmp.hideFtTitle': 'Masquer tous les spots numériques (FT8/FT4/JS8/…) sur toutes les cartes', 'bmp.fitBand': 'Ajuster à la bande', 'bmp.widthTip': 'Glisser pour redimensionner — double-clic pour réinitialiser', 'bmp.fitTitle': 'Dimensionner chaque carte pour afficher toute la bande',
|
||||||
'bmp.legendNewDxcc': 'Nouveau DXCC', 'bmp.legendNewBand': 'Nouvelle bande', 'bmp.legendNewSlot': 'Nouveau mode', 'bmp.openUnusual': 'inhabituel pour la saison', 'bmp.legendWorked': 'Contacté', 'bmp.legendNewPota': 'Nouveau POTA', 'bmp.legendNewCounty': 'Nouveau comté', 'bmp.legendWorkedCall': 'Indicatif déjà contacté', 'bmp.legendCW': 'CW', 'bmp.legendData': 'Numérique', 'bmp.legendPhone': 'Phonie', 'bmp.footerHint': 'défiler · ctrl+molette = zoom · ◎ = aller au poste', 'bmp.spotsHidden': '{n} spots FT8/FT4 masqués — {max} meilleurs conservés (CW/SSB tous affichés)',
|
'bmp.legendNewDxcc': 'Nouveau DXCC', 'bmp.legendNewBand': 'Nouvelle bande', 'bmp.legendNewSlot': 'Nouveau mode', 'bmp.openUnusual': 'inhabituel pour la saison', 'bmp.legendWorked': 'Entité contactée', 'bmp.legendNewPota': 'Nouveau POTA', 'bmp.legendNewCounty': 'Nouveau comté', 'bmp.legendWorkedCall': 'Indicatif déjà contacté', 'bmp.legendCW': 'CW', 'bmp.legendData': 'Numérique', 'bmp.legendPhone': 'Phonie', 'bmp.footerHint': 'défiler · ctrl+molette = zoom · ◎ = aller au poste', 'bmp.spotsHidden': '{n} spots FT8/FT4 masqués — {max} meilleurs conservés (CW/SSB tous affichés)',
|
||||||
'frm.welcome': 'Bienvenue dans OpsLog', 'frm.intro': 'Configure ta station pour commencer à logger. Ces champs sont inscrits sur chaque QSO et peuvent être modifiés plus tard dans Préférences → Informations station (et par profil).',
|
'frm.welcome': 'Bienvenue dans OpsLog', 'frm.intro': 'Configure ta station pour commencer à logger. Ces champs sont inscrits sur chaque QSO et peuvent être modifiés plus tard dans Préférences → Informations station (et par profil).',
|
||||||
'frm.callsign': 'Indicatif', 'frm.locator': 'Locator', 'frm.operator': 'Opérateur', 'frm.operatorPh': "identique à l'indicatif", 'frm.owner': 'Propriétaire', 'frm.ownerPh': 'indicatif du propriétaire de la station', 'frm.name': 'Nom', 'frm.namePh': 'ton prénom',
|
'frm.callsign': 'Indicatif', 'frm.locator': 'Locator', 'frm.operator': 'Opérateur', 'frm.operatorPh': "identique à l'indicatif", 'frm.owner': 'Propriétaire', 'frm.ownerPh': 'indicatif du propriétaire de la station', 'frm.name': 'Nom', 'frm.namePh': 'ton prénom',
|
||||||
'frm.awardRefs': 'Listes de références des diplômes', 'frm.awardRefsHint': 'IOTA · POTA · WWFF · SOTA — noms et totaux pour ces diplômes (optionnel, peut prendre une minute).', 'frm.downloading': 'Téléchargement…', 'frm.reDownload': 'Retélécharger', 'frm.download': 'Télécharger', 'frm.required': "L'indicatif et le locator sont obligatoires.", 'frm.saving': 'Enregistrement…', 'frm.startLogging': 'Commencer à logger',
|
'frm.awardRefs': 'Listes de références des diplômes', 'frm.awardRefsHint': 'IOTA · POTA · WWFF · SOTA — noms et totaux pour ces diplômes (optionnel, peut prendre une minute).', 'frm.downloading': 'Téléchargement…', 'frm.reDownload': 'Retélécharger', 'frm.download': 'Télécharger', 'frm.required': "L'indicatif et le locator sont obligatoires.", 'frm.saving': 'Enregistrement…', 'frm.startLogging': 'Commencer à logger',
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Single source of truth for the app version shown in the UI (header + About).
|
// Single source of truth for the app version shown in the UI (header + About).
|
||||||
// Bump this on a release (the release script updates it alongside telemetry.go).
|
// Bump this on a release (the release script updates it alongside telemetry.go).
|
||||||
export const APP_VERSION = '0.26.21';
|
export const APP_VERSION = '0.26.22';
|
||||||
|
|
||||||
// Author / credits, shown in Help -> About.
|
// Author / credits, shown in Help -> About.
|
||||||
export const APP_AUTHOR = 'F4BPO';
|
export const APP_AUTHOR = 'F4BPO';
|
||||||
|
|||||||
Vendored
+33
@@ -21,6 +21,7 @@ import {solar} from '../models';
|
|||||||
import {tunergenius} from '../models';
|
import {tunergenius} from '../models';
|
||||||
import {webpub} from '../models';
|
import {webpub} from '../models';
|
||||||
import {winkeyer} from '../models';
|
import {winkeyer} from '../models';
|
||||||
|
import {labels} from '../models';
|
||||||
import {alerts} from '../models';
|
import {alerts} from '../models';
|
||||||
import {audio} from '../models';
|
import {audio} from '../models';
|
||||||
import {contest} from '../models';
|
import {contest} from '../models';
|
||||||
@@ -505,6 +506,8 @@ export function GetLiveStations():Promise<Array<main.LiveStation>>;
|
|||||||
|
|
||||||
export function GetLoTWDownloadAllCalls():Promise<boolean>;
|
export function GetLoTWDownloadAllCalls():Promise<boolean>;
|
||||||
|
|
||||||
|
export function GetLoTWQSLDetail():Promise<boolean>;
|
||||||
|
|
||||||
export function GetLoTWUsersStatus():Promise<main.LoTWUsersStatus>;
|
export function GetLoTWUsersStatus():Promise<main.LoTWUsersStatus>;
|
||||||
|
|
||||||
export function GetLogFilePath():Promise<string>;
|
export function GetLogFilePath():Promise<string>;
|
||||||
@@ -723,6 +726,28 @@ export function KenwoodSendCW(arg1:string):Promise<void>;
|
|||||||
|
|
||||||
export function KenwoodStopCW():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 LabelOpenPDF(arg1:Array<main.LabelPDFPage>):Promise<string>;
|
||||||
|
|
||||||
|
export function LabelPaperQueue():Promise<Array<qso.QSO>>;
|
||||||
|
|
||||||
|
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 LaunchAutostartProgram(arg1:string):Promise<main.AutostartLaunchResult>;
|
||||||
|
|
||||||
export function LaunchAutostartPrograms():Promise<Array<main.AutostartLaunchResult>>;
|
export function LaunchAutostartPrograms():Promise<Array<main.AutostartLaunchResult>>;
|
||||||
@@ -1161,6 +1186,8 @@ export function SetLinkedAmps(arg1:Array<string>):Promise<void>;
|
|||||||
|
|
||||||
export function SetLoTWDownloadAllCalls(arg1:boolean):Promise<void>;
|
export function SetLoTWDownloadAllCalls(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function SetLoTWQSLDetail(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
export function SetMotorFollow(arg1:boolean,arg2:number,arg3:string):Promise<void>;
|
export function SetMotorFollow(arg1:boolean,arg2:number,arg3:string):Promise<void>;
|
||||||
|
|
||||||
export function SetOpsLogQSLReceived(arg1:number,arg2:boolean):Promise<void>;
|
export function SetOpsLogQSLReceived(arg1:number,arg2:boolean):Promise<void>;
|
||||||
@@ -1275,6 +1302,12 @@ export function SyncFolderNow():Promise<number>;
|
|||||||
|
|
||||||
export function SyncPOTAHunterLog(arg1:boolean,arg2:boolean):Promise<main.POTASyncResult>;
|
export function SyncPOTAHunterLog(arg1:boolean,arg2:boolean):Promise<main.POTASyncResult>;
|
||||||
|
|
||||||
|
export function TCISendCW(arg1:string):Promise<void>;
|
||||||
|
|
||||||
|
export function TCISetKeySpeed(arg1:number):Promise<void>;
|
||||||
|
|
||||||
|
export function TCIStopCW():Promise<void>;
|
||||||
|
|
||||||
export function TailLogFile(arg1:number):Promise<string>;
|
export function TailLogFile(arg1:number):Promise<string>;
|
||||||
|
|
||||||
export function TestCloudlogUpload():Promise<string>;
|
export function TestCloudlogUpload():Promise<string>;
|
||||||
|
|||||||
@@ -950,6 +950,10 @@ export function GetLoTWDownloadAllCalls() {
|
|||||||
return window['go']['main']['App']['GetLoTWDownloadAllCalls']();
|
return window['go']['main']['App']['GetLoTWDownloadAllCalls']();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GetLoTWQSLDetail() {
|
||||||
|
return window['go']['main']['App']['GetLoTWQSLDetail']();
|
||||||
|
}
|
||||||
|
|
||||||
export function GetLoTWUsersStatus() {
|
export function GetLoTWUsersStatus() {
|
||||||
return window['go']['main']['App']['GetLoTWUsersStatus']();
|
return window['go']['main']['App']['GetLoTWUsersStatus']();
|
||||||
}
|
}
|
||||||
@@ -1386,6 +1390,50 @@ export function KenwoodStopCW() {
|
|||||||
return window['go']['main']['App']['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 LabelOpenPDF(arg1) {
|
||||||
|
return window['go']['main']['App']['LabelOpenPDF'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LabelPaperQueue() {
|
||||||
|
return window['go']['main']['App']['LabelPaperQueue']();
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
export function LaunchAutostartProgram(arg1) {
|
||||||
return window['go']['main']['App']['LaunchAutostartProgram'](arg1);
|
return window['go']['main']['App']['LaunchAutostartProgram'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2262,6 +2310,10 @@ export function SetLoTWDownloadAllCalls(arg1) {
|
|||||||
return window['go']['main']['App']['SetLoTWDownloadAllCalls'](arg1);
|
return window['go']['main']['App']['SetLoTWDownloadAllCalls'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function SetLoTWQSLDetail(arg1) {
|
||||||
|
return window['go']['main']['App']['SetLoTWQSLDetail'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function SetMotorFollow(arg1, arg2, arg3) {
|
export function SetMotorFollow(arg1, arg2, arg3) {
|
||||||
return window['go']['main']['App']['SetMotorFollow'](arg1, arg2, arg3);
|
return window['go']['main']['App']['SetMotorFollow'](arg1, arg2, arg3);
|
||||||
}
|
}
|
||||||
@@ -2490,6 +2542,18 @@ export function SyncPOTAHunterLog(arg1, arg2) {
|
|||||||
return window['go']['main']['App']['SyncPOTAHunterLog'](arg1, arg2);
|
return window['go']['main']['App']['SyncPOTAHunterLog'](arg1, arg2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function TCISendCW(arg1) {
|
||||||
|
return window['go']['main']['App']['TCISendCW'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TCISetKeySpeed(arg1) {
|
||||||
|
return window['go']['main']['App']['TCISetKeySpeed'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TCIStopCW() {
|
||||||
|
return window['go']['main']['App']['TCIStopCW']();
|
||||||
|
}
|
||||||
|
|
||||||
export function TailLogFile(arg1) {
|
export function TailLogFile(arg1) {
|
||||||
return window['go']['main']['App']['TailLogFile'](arg1);
|
return window['go']['main']['App']['TailLogFile'](arg1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 namespace lookup {
|
||||||
|
|
||||||
export class Result {
|
export class Result {
|
||||||
@@ -2936,6 +2969,78 @@ export namespace main {
|
|||||||
this.samples = source["samples"];
|
this.samples = source["samples"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class LabelPDFPage {
|
||||||
|
png: string;
|
||||||
|
w_mm: number;
|
||||||
|
h_mm: number;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new LabelPDFPage(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.png = source["png"];
|
||||||
|
this.w_mm = source["w_mm"];
|
||||||
|
this.h_mm = source["h_mm"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 {
|
export class ModePreset {
|
||||||
name: string;
|
name: string;
|
||||||
default_rst_sent?: string;
|
default_rst_sent?: string;
|
||||||
@@ -5138,6 +5243,7 @@ export namespace qso {
|
|||||||
band?: string;
|
band?: string;
|
||||||
mode?: string;
|
mode?: string;
|
||||||
station_callsign?: string;
|
station_callsign?: string;
|
||||||
|
qsl_sent_in?: string[];
|
||||||
limit?: number;
|
limit?: number;
|
||||||
offset?: number;
|
offset?: number;
|
||||||
|
|
||||||
@@ -5151,6 +5257,7 @@ export namespace qso {
|
|||||||
this.band = source["band"];
|
this.band = source["band"];
|
||||||
this.mode = source["mode"];
|
this.mode = source["mode"];
|
||||||
this.station_callsign = source["station_callsign"];
|
this.station_callsign = source["station_callsign"];
|
||||||
|
this.qsl_sent_in = source["qsl_sent_in"];
|
||||||
this.limit = source["limit"];
|
this.limit = source["limit"];
|
||||||
this.offset = source["offset"];
|
this.offset = source["offset"];
|
||||||
}
|
}
|
||||||
|
|||||||
+87
-6
@@ -27,6 +27,14 @@ type TCI struct {
|
|||||||
|
|
||||||
digitalDefault string // surfaced when the rig reports a digital mode (FT8/…)
|
digitalDefault string // surfaced when the rig reports a digital mode (FT8/…)
|
||||||
spotsEnabled bool // mirror cluster spots onto the TCI panorama
|
spotsEnabled bool // mirror cluster spots onto the TCI panorama
|
||||||
|
// wantFreq is the frequency last COMMANDED and not yet echoed back, used to
|
||||||
|
// pick the sideband before the radio has confirmed the move.
|
||||||
|
wantFreq int64
|
||||||
|
// What the server said it is, from its "protocol:" announcement.
|
||||||
|
serverName string
|
||||||
|
serverVersion string
|
||||||
|
// How many spots have been logged verbatim (the first few only).
|
||||||
|
spotsSent int
|
||||||
|
|
||||||
// OnSpotClick is called when the user clicks one of our spots on the TCI
|
// OnSpotClick is called when the user clicks one of our spots on the TCI
|
||||||
// panorama (callsign + freq), so the host can fill the entry form. Set before
|
// panorama (callsign + freq), so the host can fill the entry form. Set before
|
||||||
@@ -149,6 +157,16 @@ func (t *TCI) Connect() error {
|
|||||||
t.mu.Unlock()
|
t.mu.Unlock()
|
||||||
debugLog.Printf("TCI: connected to %s", url)
|
debugLog.Printf("TCI: connected to %s", url)
|
||||||
go t.reader(conn)
|
go t.reader(conn)
|
||||||
|
// Ask for the meters. Nothing measures anything until this goes out: the
|
||||||
|
// S-meter, the transmit power and the SWR are all pushed by the radio, and
|
||||||
|
// only to a client that has subscribed. 200 ms is the rate the protocol's own
|
||||||
|
// examples use — fast enough for a needle, slow enough not to flood a socket
|
||||||
|
// that also carries audio.
|
||||||
|
if t.spotsEnabled {
|
||||||
|
debugLog.Printf("TCI: panorama spots are ON — spots will be sent to the radio")
|
||||||
|
}
|
||||||
|
_ = t.send("rx_sensors_enable:true,200;")
|
||||||
|
_ = t.send("tx_sensors_enable:true,200;")
|
||||||
if t.spotsEnabled {
|
if t.spotsEnabled {
|
||||||
// Forget what we thought was on the panorama at the same moment the radio
|
// Forget what we thought was on the panorama at the same moment the radio
|
||||||
// is told to drop it. Kept, the memory would suppress the next spot for
|
// is told to drop it. Kept, the memory would suppress the next spot for
|
||||||
@@ -228,11 +246,19 @@ func (t *TCI) SendSpot(s SpotInfo) error {
|
|||||||
// other two matching what already works here.
|
// other two matching what already works here.
|
||||||
_ = t.send(fmt.Sprintf("spot_delete:%s;", call))
|
_ = t.send(fmt.Sprintf("spot_delete:%s;", call))
|
||||||
}
|
}
|
||||||
// TCI's SPOT command wants the colour as a signed 32-bit DECIMAL integer in
|
// The colour is a DECIMAL ARGB integer, and an UNSIGNED one.
|
||||||
// 0xAARRGGBB order — NOT a "0x…" hex string (e.g. "spot:UN7GK,cw,14025000,
|
//
|
||||||
// -16776961,test;"). ExpertSDR silently drops a spot whose colour field it
|
// Expert Electronics' own protocol document gives the whole command:
|
||||||
// can't parse as a number, which is why spots never showed on the panorama
|
//
|
||||||
// while tuning (a separate command) still worked.
|
// SPOT:RN6LHF,CW,7100000,16711680,ANY_TEXT;
|
||||||
|
//
|
||||||
|
// 16711680 is 0x00FF0000 — positive, alpha zero. This backend was sending
|
||||||
|
// the same number as a SIGNED 32-bit value, taken from a third-party
|
||||||
|
// example: with the alpha byte set to FF for opacity, 0xFFFFA500 becomes
|
||||||
|
// -22336, and a spot whose colour field ExpertSDR cannot read is dropped in
|
||||||
|
// silence. Reported on ExpertSDR3 1.3 (which speaks TCI 2.x, so the version
|
||||||
|
// was never the problem): everything else worked and the panorama stayed
|
||||||
|
// empty.
|
||||||
hex := strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(s.Color), "#"), "0x")
|
hex := strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(s.Color), "#"), "0x")
|
||||||
if hex == "" {
|
if hex == "" {
|
||||||
hex = "FFFFA500" // opaque orange default
|
hex = "FFFFA500" // opaque orange default
|
||||||
@@ -253,7 +279,15 @@ func (t *TCI) SendSpot(s SpotInfo) error {
|
|||||||
}
|
}
|
||||||
// Commas/semicolons would break TCI's comma-separated argument parsing.
|
// Commas/semicolons would break TCI's comma-separated argument parsing.
|
||||||
text := strings.NewReplacer(",", " ", ";", " ").Replace(s.Comment)
|
text := strings.NewReplacer(",", " ", ";", " ").Replace(s.Comment)
|
||||||
return t.send(fmt.Sprintf("spot:%s,%s,%d,%d,%s;", call, mode, s.FreqHz, int32(argb), text))
|
cmd := fmt.Sprintf("spot:%s,%s,%d,%d,%s;", call, mode, s.FreqHz, argb, text)
|
||||||
|
// The first few, verbatim. A spot that the radio ignores leaves no trace at
|
||||||
|
// all — no reply, no error — so the only evidence that OpsLog sent one, and
|
||||||
|
// in what shape, is this line.
|
||||||
|
if n := t.spotsSent; n < 3 {
|
||||||
|
t.spotsSent = n + 1
|
||||||
|
debugLog.Printf("TCI: sending spot #%d: %s", n+1, strings.TrimSuffix(cmd, ";"))
|
||||||
|
}
|
||||||
|
return t.send(cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Disconnect closes the WebSocket; the reader goroutine then exits.
|
// Disconnect closes the WebSocket; the reader goroutine then exits.
|
||||||
@@ -334,6 +368,11 @@ func (t *TCI) ReadState() (RigState, error) {
|
|||||||
|
|
||||||
// SetFrequency tunes VFO A (the main/RX VFO).
|
// SetFrequency tunes VFO A (the main/RX VFO).
|
||||||
func (t *TCI) SetFrequency(hz int64) error {
|
func (t *TCI) SetFrequency(hz int64) error {
|
||||||
|
// Remember what we ASKED for. SetMode reads it to choose the sideband, and
|
||||||
|
// the radio's own echo can be a moment behind — see SetMode.
|
||||||
|
t.mu.Lock()
|
||||||
|
t.wantFreq = hz
|
||||||
|
t.mu.Unlock()
|
||||||
return t.send(fmt.Sprintf("vfo:0,0,%d;", hz))
|
return t.send(fmt.Sprintf("vfo:0,0,%d;", hz))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,6 +381,17 @@ func (t *TCI) SetFrequency(hz int64) error {
|
|||||||
func (t *TCI) SetMode(mode string) error {
|
func (t *TCI) SetMode(mode string) error {
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
freq := t.freqA
|
freq := t.freqA
|
||||||
|
// Prefer the frequency we just COMMANDED over the one the radio has echoed.
|
||||||
|
//
|
||||||
|
// Clicking a spot sets the frequency and then the mode, and the sideband is
|
||||||
|
// chosen from the frequency (below 10 MHz → LSB). Read from the echo, that
|
||||||
|
// is the frequency we were on BEFORE the click whenever the echo has not
|
||||||
|
// landed yet: a 14 MHz spot clicked from 7 MHz got LSB, and clicking the same
|
||||||
|
// spot again — now that the echo has arrived — got USB. Reported from a
|
||||||
|
// SunSDR as "the frequency is right, the mode is wrong until I click twice".
|
||||||
|
if t.wantFreq > 0 {
|
||||||
|
freq = t.wantFreq
|
||||||
|
}
|
||||||
t.mu.Unlock()
|
t.mu.Unlock()
|
||||||
m := adifToTCIMode(mode, freq)
|
m := adifToTCIMode(mode, freq)
|
||||||
if m == "" {
|
if m == "" {
|
||||||
@@ -493,6 +543,18 @@ func (t *TCI) handle(msg string) {
|
|||||||
switch lower {
|
switch lower {
|
||||||
case "device":
|
case "device":
|
||||||
t.device = strings.TrimSpace(args)
|
t.device = strings.TrimSpace(args)
|
||||||
|
// The server's own announcement: "protocol:ExpertSDR3,1.9;" — its name and
|
||||||
|
// the TCI version it speaks. Worth keeping rather than filing under
|
||||||
|
// "unhandled": panorama spots need a version that HAS the spot command, and
|
||||||
|
// without this an operator on an older ExpertSDR sees nothing on the
|
||||||
|
// waterfall and nothing anywhere saying why.
|
||||||
|
case "protocol":
|
||||||
|
t.serverName, t.serverVersion = get(0), get(1)
|
||||||
|
debugLog.Printf("TCI: server is %s, TCI %s", t.serverName, t.serverVersion)
|
||||||
|
if t.spotsEnabled && tciSpotsUnsupported(t.serverVersion) {
|
||||||
|
debugLog.Printf("TCI: this server speaks TCI %s — panorama spots need 1.5 or later, so they will not appear",
|
||||||
|
t.serverVersion)
|
||||||
|
}
|
||||||
// The radio ANNOUNCES its audio format at connect —
|
// The radio ANNOUNCES its audio format at connect —
|
||||||
// "audio_stream_sample_type:float32" and "audio_stream_channels:2" — which
|
// "audio_stream_sample_type:float32" and "audio_stream_channels:2" — which
|
||||||
// is better evidence than anything derived from a frame, and it arrives
|
// is better evidence than anything derived from a frame, and it arrives
|
||||||
@@ -516,6 +578,10 @@ func (t *TCI) handle(msg string) {
|
|||||||
switch get(1) {
|
switch get(1) {
|
||||||
case "0":
|
case "0":
|
||||||
t.freqA = hz
|
t.freqA = hz
|
||||||
|
// The radio has caught up: from here the echo IS the truth.
|
||||||
|
if t.wantFreq != 0 && absInt64(hz-t.wantFreq) < 100 {
|
||||||
|
t.wantFreq = 0
|
||||||
|
}
|
||||||
case "1":
|
case "1":
|
||||||
t.freqB = hz
|
t.freqB = hz
|
||||||
}
|
}
|
||||||
@@ -651,3 +717,18 @@ func adifToTCIMode(mode string, freqHz int64) string {
|
|||||||
return "digu"
|
return "digu"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tciSpotsUnsupported reports whether a TCI version predates the spot commands.
|
||||||
|
//
|
||||||
|
// SPOT / SPOT_DELETE / SPOT_CLEAR arrived in TCI 1.5. An older ExpertSDR accepts
|
||||||
|
// the connection, answers frequency and mode perfectly, and silently ignores
|
||||||
|
// every spot — which is indistinguishable from a bug in the logger unless
|
||||||
|
// somebody says so. Anything unparseable is treated as supported: refusing to
|
||||||
|
// draw on a doubt would be the worse mistake.
|
||||||
|
func tciSpotsUnsupported(version string) bool {
|
||||||
|
var maj, min int
|
||||||
|
if n, err := fmt.Sscanf(strings.TrimSpace(version), "%d.%d", &maj, &min); n < 2 || err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return maj < 1 || (maj == 1 && min < 5)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package cat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CW keying over TCI — a sixth CW engine, so a SunSDR needs no WinKeyer and no
|
||||||
|
// second serial port: the radio's own macro keyer is driven over the WebSocket
|
||||||
|
// that already carries the CAT.
|
||||||
|
//
|
||||||
|
// The commands, from the TCI command table (confirmed against ars-ka0s/eesdr-tci,
|
||||||
|
// the same source that settled SPOT):
|
||||||
|
//
|
||||||
|
// CW_MACROS:<trx>,<text>; send text through the radio's keyer
|
||||||
|
// CW_MACROS_SPEED:<wpm>; the speed those macros are keyed at
|
||||||
|
// CW_MACROS_STOP; abort what is being keyed
|
||||||
|
// CW_MACROS_EMPTY; the radio saying the buffer has run dry
|
||||||
|
//
|
||||||
|
// CW_MSG (TCI 2.0) does the same with separate before/after callsign fields.
|
||||||
|
// CW_MACROS is used instead because it exists from 1.6 and OpsLog resolves the
|
||||||
|
// variables itself — the text handed here is already what should go on the air.
|
||||||
|
//
|
||||||
|
// Notably absent: there is no backspace. The FlexRadio CWX keyer can un-type
|
||||||
|
// what has not been sent yet; TCI can only stop. So the type-ahead correction
|
||||||
|
// the Flex engine offers is not offered here rather than faked.
|
||||||
|
|
||||||
|
// tciCWTextLimit caps one macro. A runaway paste down a WebSocket that also
|
||||||
|
// carries audio is worth refusing, and no real CW message is this long.
|
||||||
|
const tciCWTextLimit = 512
|
||||||
|
|
||||||
|
// SendCW keys a message through the radio's macro keyer.
|
||||||
|
func (t *TCI) SendCW(text string) error {
|
||||||
|
msg := sanitiseTCICW(text)
|
||||||
|
if msg == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return t.send(fmt.Sprintf("cw_macros:0,%s;", msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopCW aborts the message being keyed.
|
||||||
|
func (t *TCI) StopCW() error { return t.send("cw_macros_stop;") }
|
||||||
|
|
||||||
|
// SetCWSpeed sets the macro keyer speed in words per minute.
|
||||||
|
//
|
||||||
|
// Only the MACRO speed: the paddle keyer has its own (CW_KEYER_SPEED) and an
|
||||||
|
// operator who has set their paddle to 28 wpm did not ask the logger to change
|
||||||
|
// it because a macro went out at 25.
|
||||||
|
func (t *TCI) SetCWSpeed(wpm int) error {
|
||||||
|
if wpm < 5 {
|
||||||
|
wpm = 5
|
||||||
|
}
|
||||||
|
if wpm > 60 {
|
||||||
|
wpm = 60
|
||||||
|
}
|
||||||
|
return t.send(fmt.Sprintf("cw_macros_speed:%d;", wpm))
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitiseTCICW makes a message safe to put in a TCI command.
|
||||||
|
//
|
||||||
|
// Commas and semicolons are the protocol's own separators — a comma inside the
|
||||||
|
// text would be read as another argument and a semicolon would end the command
|
||||||
|
// early, keying half a message and leaving the rest to be parsed as a command of
|
||||||
|
// its own. Neither belongs in Morse anyway.
|
||||||
|
func sanitiseTCICW(text string) string {
|
||||||
|
s := strings.ToUpper(strings.TrimSpace(text))
|
||||||
|
s = strings.NewReplacer(",", " ", ";", " ", "\r", " ", "\n", " ").Replace(s)
|
||||||
|
if len(s) > tciCWTextLimit {
|
||||||
|
s = s[:tciCWTextLimit]
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(s)
|
||||||
|
}
|
||||||
@@ -96,3 +96,26 @@ func (m *Manager) TCIPanelDo(fn func(TCIPanelController) error) error {
|
|||||||
return fn(tc)
|
return fn(tc)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TCICWController is the radio's CW keyer, as the CW engine uses it.
|
||||||
|
//
|
||||||
|
// Three methods, and no backspace: TCI can stop a message but cannot un-type one
|
||||||
|
// (see tci_cw.go). Kept as its own interface rather than folded into the console
|
||||||
|
// one so a CW engine does not have to depend on forty panel setters to key a
|
||||||
|
// message.
|
||||||
|
type TCICWController interface {
|
||||||
|
SendCW(text string) error
|
||||||
|
StopCW() error
|
||||||
|
SetCWSpeed(wpm int) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// TCICWDo dispatches one keyer command onto the CAT goroutine.
|
||||||
|
func (m *Manager) TCICWDo(fn func(TCICWController) error) error {
|
||||||
|
return m.exec(func(b Backend) error {
|
||||||
|
tc, ok := b.(TCICWController)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("the active CAT backend is not a TCI radio")
|
||||||
|
}
|
||||||
|
return fn(tc)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -233,6 +233,42 @@ func (t *TCI) handlePanel(name string, get func(int) string, args string) bool {
|
|||||||
if n, ok := num(get(1)); ok && forRX0() {
|
if n, ok := num(get(1)); ok && forRX0() {
|
||||||
p.SMeter = n
|
p.SMeter = n
|
||||||
}
|
}
|
||||||
|
// The meters of ExpertSDR3. The S-meter used to be read only from RX_SMETER
|
||||||
|
// and the transmit ones from TX_POWER / TX_SWR — commands this radio simply
|
||||||
|
// never sends, which is why the console's meters sat empty on a SunSDR in
|
||||||
|
// both RX and TX while everything else worked.
|
||||||
|
//
|
||||||
|
// The protocol's own answer (TCI Protocol.pdf, §4.4) is a SUBSCRIPTION:
|
||||||
|
//
|
||||||
|
// RX_SENSORS:<rx>,<dBm>; (deprecated in 2.0)
|
||||||
|
// RX_CHANNEL_SENSORS:<rx>,<channel>,<dBm>; (its replacement)
|
||||||
|
// TX_SENSORS:<trx>,<mic dBm>,<power W>,<peak W>,<SWR>;
|
||||||
|
//
|
||||||
|
// none of which arrives until the client asks with RX_SENSORS_ENABLE and
|
||||||
|
// TX_SENSORS_ENABLE — see Connect.
|
||||||
|
case "rx_sensors":
|
||||||
|
if v, err := strconv.ParseFloat(strings.TrimSpace(get(1)), 64); err == nil && forRX0() {
|
||||||
|
p.SMeter = int(v)
|
||||||
|
}
|
||||||
|
case "rx_channel_sensors":
|
||||||
|
// Main channel (A) of receiver 0: the one the console is showing.
|
||||||
|
if v, err := strconv.ParseFloat(strings.TrimSpace(get(2)), 64); err == nil &&
|
||||||
|
get(0) == "0" && get(1) == "0" {
|
||||||
|
p.SMeter = int(v)
|
||||||
|
}
|
||||||
|
case "tx_sensors":
|
||||||
|
if get(0) != "0" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// arg3 is RMS power, arg4 the peak. The peak is what a power meter's
|
||||||
|
// needle does on speech; the RMS is what the operator is asked to keep
|
||||||
|
// under the amplifier's limit — so RMS is the number, as elsewhere.
|
||||||
|
if v, err := strconv.ParseFloat(strings.TrimSpace(get(2)), 64); err == nil {
|
||||||
|
p.TXPowerW = v
|
||||||
|
}
|
||||||
|
if v, err := strconv.ParseFloat(strings.TrimSpace(get(4)), 64); err == nil {
|
||||||
|
p.TXSWR = v
|
||||||
|
}
|
||||||
case "tune":
|
case "tune":
|
||||||
if forRX0() {
|
if forRX0() {
|
||||||
p.Tuning = yes(get(1))
|
p.Tuning = yes(get(1))
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package cat
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestTCISpotsUnsupported(t *testing.T) {
|
||||||
|
// SPOT arrived in TCI 1.5. The SunSDR2 PRO report that prompted this was an
|
||||||
|
// ExpertSDR announcing 1.3 — spots accepted and silently dropped.
|
||||||
|
for _, c := range []struct {
|
||||||
|
version string
|
||||||
|
old bool
|
||||||
|
}{
|
||||||
|
{"1.3", true},
|
||||||
|
{"1.4", true},
|
||||||
|
{"1.5", false},
|
||||||
|
{"1.9", false},
|
||||||
|
{"2.0", false},
|
||||||
|
{"", false}, // unparseable → assume it works
|
||||||
|
{"weird", false}, // refusing to draw on a doubt is the worse mistake
|
||||||
|
} {
|
||||||
|
if got := tciSpotsUnsupported(c.version); got != c.old {
|
||||||
|
t.Errorf("tciSpotsUnsupported(%q) = %v, want %v", c.version, got, c.old)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSanitiseTCICW(t *testing.T) {
|
||||||
|
// The separators must never survive: a comma would become another argument
|
||||||
|
// and a semicolon would end the command with the message half sent.
|
||||||
|
for _, c := range []struct{ in, want string }{
|
||||||
|
{"cq cq de f4bpo", "CQ CQ DE F4BPO"},
|
||||||
|
{" tu 599 ", "TU 599"},
|
||||||
|
{"73, gl", "73 GL"},
|
||||||
|
{"test;cw_macros_stop", "TEST CW_MACROS_STOP"},
|
||||||
|
{"line\r\nbreak", "LINE BREAK"},
|
||||||
|
{" ", ""},
|
||||||
|
} {
|
||||||
|
if got := sanitiseTCICW(c.in); got != c.want {
|
||||||
|
t.Errorf("sanitiseTCICW(%q) = %q, want %q", c.in, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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'))
|
||||||
|
);
|
||||||
@@ -51,6 +51,8 @@ var settingsTables = []string{
|
|||||||
"operating_stations_new",
|
"operating_stations_new",
|
||||||
"award_references",
|
"award_references",
|
||||||
"qsl_templates",
|
"qsl_templates",
|
||||||
|
"label_stocks",
|
||||||
|
"label_templates",
|
||||||
"cluster_servers",
|
"cluster_servers",
|
||||||
"integrations_udp",
|
"integrations_udp",
|
||||||
"callsign_cache",
|
"callsign_cache",
|
||||||
|
|||||||
+33
-2
@@ -5,6 +5,7 @@ package email
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/wneessen/go-mail"
|
"github.com/wneessen/go-mail"
|
||||||
@@ -86,12 +87,42 @@ func SendFiles(cfg Config, to, subject, body string, attachPaths []string) error
|
|||||||
return fmt.Errorf("smtp client: %w", err)
|
return fmt.Errorf("smtp client: %w", err)
|
||||||
}
|
}
|
||||||
if err := client.DialAndSend(m); err != nil {
|
if err := client.DialAndSend(m); err != nil {
|
||||||
return fmt.Errorf("send via %s:%d (%s, %s): %w",
|
return fmt.Errorf("send via %s:%d (%s, %s): %w%s",
|
||||||
cfg.Host, cfg.Port, cfg.Encryption, describeSize(attachPaths), err)
|
cfg.Host, cfg.Port, cfg.Encryption, describeSize(attachPaths), err, explainSMTP(err))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// explainSMTP turns a server's refusal into the thing to go and do.
|
||||||
|
//
|
||||||
|
// A rejection is quoted verbatim above it — the server's own words are the
|
||||||
|
// evidence — but several of them name a policy rather than a mistake, and no
|
||||||
|
// amount of re-checking the password will fix those. Microsoft's is the one
|
||||||
|
// operators keep hitting: basic authentication for SMTP is switched off across
|
||||||
|
// Microsoft 365 and outlook.com, and an app password does not bring it back.
|
||||||
|
func explainSMTP(err error) string {
|
||||||
|
msg := strings.ToLower(err.Error())
|
||||||
|
switch {
|
||||||
|
case strings.Contains(msg, "basic authentication is disabled"),
|
||||||
|
strings.Contains(msg, "5.7.139"):
|
||||||
|
return "\n\nMicrosoft has switched off password-based SMTP for this account. " +
|
||||||
|
"An app password does not restore it — the server refuses the password itself, not the one you typed. " +
|
||||||
|
"On a Microsoft 365 tenant an administrator can re-enable it for this mailbox " +
|
||||||
|
"(Set-CASMailbox -SmtpClientAuthenticationDisabled $false, plus the tenant-wide setting); " +
|
||||||
|
"otherwise use another provider for alerts (a Gmail account with an app password works, so does any ordinary IMAP/SMTP host)."
|
||||||
|
case strings.Contains(msg, "application-specific password"),
|
||||||
|
strings.Contains(msg, "5.7.9"):
|
||||||
|
return "\n\nThis account needs an APP PASSWORD rather than the one you sign in with " +
|
||||||
|
"(Google, Yahoo and others require it once two-factor authentication is on)."
|
||||||
|
case strings.Contains(msg, "5.7.8"), strings.Contains(msg, "authentication failed"),
|
||||||
|
strings.Contains(msg, "535"):
|
||||||
|
return "\n\nThe server rejected the username or the password."
|
||||||
|
case strings.Contains(msg, "must issue a starttls"):
|
||||||
|
return "\n\nThe server requires encryption: set STARTTLS (usually port 587) or SSL (465)."
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// describeSize reports what was attached, in bytes.
|
// describeSize reports what was attached, in bytes.
|
||||||
//
|
//
|
||||||
// "An existing connection was forcibly closed" during DATA is the same message
|
// "An existing connection was forcibly closed" during DATA is the same message
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExplainSMTP(t *testing.T) {
|
||||||
|
// The real refusal, from an operator's Outlook account.
|
||||||
|
outlook := errors.New("SMTP AUTH failed: 535 5.7.139 Authentication unsuccessful, basic authentication is disabled.")
|
||||||
|
if got := explainSMTP(outlook); !strings.Contains(got, "Microsoft has switched off") {
|
||||||
|
t.Errorf("the Microsoft policy refusal is not explained: %q", got)
|
||||||
|
}
|
||||||
|
// A plain wrong password must NOT claim a policy: the advice would send the
|
||||||
|
// operator to an administrator over a typo.
|
||||||
|
wrong := errors.New("535 5.7.8 authentication failed")
|
||||||
|
got := explainSMTP(wrong)
|
||||||
|
if strings.Contains(got, "Microsoft") {
|
||||||
|
t.Errorf("a wrong password was explained as a Microsoft policy: %q", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(got, "rejected the username") {
|
||||||
|
t.Errorf("a wrong password is not explained: %q", got)
|
||||||
|
}
|
||||||
|
// Anything else is left to speak for itself.
|
||||||
|
if got := explainSMTP(errors.New("dial tcp: i/o timeout")); got != "" {
|
||||||
|
t.Errorf("an unrelated error got an explanation: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-3
@@ -89,7 +89,7 @@ func readWithProgress(ctx context.Context, r io.Reader, note func(string)) ([]by
|
|||||||
// non-empty, only confirmations for that station callsign are returned (an
|
// non-empty, only confirmations for that station callsign are returned (an
|
||||||
// LoTW account holds every call you operate — F4BPO, F4BPO/P, TM2Q — so this
|
// LoTW account holds every call you operate — F4BPO, F4BPO/P, TM2Q — so this
|
||||||
// scopes the pull to the active profile's call).
|
// scopes the pull to the active profile's call).
|
||||||
func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg ServiceConfig, since, ownCall string, note func(string)) (string, error) {
|
func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg ServiceConfig, since, ownCall string, detail bool, note func(string)) (string, error) {
|
||||||
user := strings.TrimSpace(cfg.Username)
|
user := strings.TrimSpace(cfg.Username)
|
||||||
if user == "" || cfg.Password == "" {
|
if user == "" || cfg.Password == "" {
|
||||||
return "", fmt.Errorf("lotw: website login (username/password) not set")
|
return "", fmt.Errorf("lotw: website login (username/password) not set")
|
||||||
@@ -99,7 +99,18 @@ func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg Ser
|
|||||||
q.Set("password", cfg.Password)
|
q.Set("password", cfg.Password)
|
||||||
q.Set("qso_query", "1")
|
q.Set("qso_query", "1")
|
||||||
q.Set("qso_qsl", "yes") // only QSLed (confirmed) records
|
q.Set("qso_qsl", "yes") // only QSLed (confirmed) records
|
||||||
q.Set("qso_qsldetail", "yes") // include QSL_RCVD / QSLRDATE detail
|
// qso_qsldetail is what LoTW charges for: it adds the QSL date and the
|
||||||
|
// station's own DXCC / grid / state / county to every record, and takes an
|
||||||
|
// order of magnitude longer to build — a report that arrives in two minutes
|
||||||
|
// without it takes twenty with it, measured on the same account.
|
||||||
|
//
|
||||||
|
// What we actually need to mark a confirmation is call, date, band and mode.
|
||||||
|
// The rest is worth its price only when the download is also ADDING the QSOs
|
||||||
|
// it cannot find, which is the one case where the extra fields are the only
|
||||||
|
// source for them.
|
||||||
|
if detail {
|
||||||
|
q.Set("qso_qsldetail", "yes")
|
||||||
|
}
|
||||||
if c := strings.TrimSpace(ownCall); c != "" {
|
if c := strings.TrimSpace(ownCall); c != "" {
|
||||||
q.Set("qso_owncall", c) // restrict to this station callsign
|
q.Set("qso_owncall", c) // restrict to this station callsign
|
||||||
}
|
}
|
||||||
@@ -507,7 +518,7 @@ func TestLoTW(cfg ServiceConfig, stationDataPath string) (string, error) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if _, err := DownloadLoTWConfirmations(ctx, nil, cfg, "2099-01-01", "", nil); err != nil {
|
if _, err := DownloadLoTWConfirmations(ctx, nil, cfg, "2099-01-01", "", false, nil); err != nil {
|
||||||
return "", fmt.Errorf("%s — but the DOWNLOAD login failed: %w", up, err)
|
return "", fmt.Errorf("%s — but the DOWNLOAD login failed: %w", up, err)
|
||||||
}
|
}
|
||||||
return up + ". Download login accepted.", nil
|
return up + ". Download login accepted.", nil
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// Package pdf writes the one kind of PDF the label printer needs: a document
|
||||||
|
// whose every page is a single full-bleed image at an exact physical size.
|
||||||
|
//
|
||||||
|
// Written by hand rather than through a library for two reasons. The build is
|
||||||
|
// pure Go with no room for cgo, and the need is tiny: the pages arrive as
|
||||||
|
// PNGs rasterised by the SAME canvas renderer the designer's preview uses, so
|
||||||
|
// this file only has to carry pixels to paper without touching them. Fonts,
|
||||||
|
// vectors, compression profiles — all already decided upstream.
|
||||||
|
//
|
||||||
|
// The images are stored as 8-bit DeviceGray with FlateDecode: labels are
|
||||||
|
// monochrome, grey keeps antialiased text edges smooth on a 300 dpi thermal
|
||||||
|
// head, and flate is lossless — JPEG artefacts around small print are exactly
|
||||||
|
// what a QSL label cannot afford.
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"compress/zlib"
|
||||||
|
"fmt"
|
||||||
|
"image/png"
|
||||||
|
)
|
||||||
|
|
||||||
|
const mmToPt = 72.0 / 25.4
|
||||||
|
|
||||||
|
// Doc accumulates pages; Bytes() renders the file.
|
||||||
|
type Doc struct {
|
||||||
|
pages []pageData
|
||||||
|
}
|
||||||
|
|
||||||
|
type pageData struct {
|
||||||
|
wPt, hPt float64
|
||||||
|
imgW int
|
||||||
|
imgH int
|
||||||
|
gray []byte // zlib-compressed 8-bit samples
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddImagePage appends one page of wMm×hMm entirely covered by the PNG.
|
||||||
|
// The PNG's aspect ratio is not checked against the page's: the caller
|
||||||
|
// rasterised it AT this size, and a mismatch would be its bug to see.
|
||||||
|
func (d *Doc) AddImagePage(pngBytes []byte, wMm, hMm float64) error {
|
||||||
|
img, err := png.Decode(bytes.NewReader(pngBytes))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("page image: %w", err)
|
||||||
|
}
|
||||||
|
b := img.Bounds()
|
||||||
|
w, h := b.Dx(), b.Dy()
|
||||||
|
if w <= 0 || h <= 0 {
|
||||||
|
return fmt.Errorf("page image is empty")
|
||||||
|
}
|
||||||
|
// To 8-bit grey. Luminance weights, not an average: blue text on a designer
|
||||||
|
// screen should darken the way a photocopier would darken it.
|
||||||
|
gray := make([]byte, w*h)
|
||||||
|
i := 0
|
||||||
|
for y := b.Min.Y; y < b.Max.Y; y++ {
|
||||||
|
for x := b.Min.X; x < b.Max.X; x++ {
|
||||||
|
r, g, bb, _ := img.At(x, y).RGBA()
|
||||||
|
gray[i] = byte((299*r + 587*g + 114*bb) / 1000 >> 8)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
zw := zlib.NewWriter(&buf)
|
||||||
|
if _, err := zw.Write(gray); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
d.pages = append(d.pages, pageData{
|
||||||
|
wPt: wMm * mmToPt, hPt: hMm * mmToPt,
|
||||||
|
imgW: w, imgH: h, gray: buf.Bytes(),
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bytes renders the whole document.
|
||||||
|
func (d *Doc) Bytes() ([]byte, error) {
|
||||||
|
if len(d.pages) == 0 {
|
||||||
|
return nil, fmt.Errorf("no pages")
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
offsets := []int{0} // object 0 is the free-list head
|
||||||
|
obj := func(body func()) int {
|
||||||
|
offsets = append(offsets, out.Len())
|
||||||
|
n := len(offsets) - 1
|
||||||
|
fmt.Fprintf(&out, "%d 0 obj\n", n)
|
||||||
|
body()
|
||||||
|
out.WriteString("endobj\n")
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
out.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
||||||
|
|
||||||
|
// Objects 1 (catalog) and 2 (pages) reference their children by number, so
|
||||||
|
// the numbering is laid out first: 3 objects per page after the two roots.
|
||||||
|
nPages := len(d.pages)
|
||||||
|
pageObj := func(i int) int { return 3 + i*3 }
|
||||||
|
|
||||||
|
obj(func() { out.WriteString("<< /Type /Catalog /Pages 2 0 R >>\n") }) // 1
|
||||||
|
obj(func() { // 2
|
||||||
|
out.WriteString("<< /Type /Pages /Kids [")
|
||||||
|
for i := 0; i < nPages; i++ {
|
||||||
|
fmt.Fprintf(&out, "%d 0 R ", pageObj(i))
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&out, "] /Count %d >>\n", nPages)
|
||||||
|
})
|
||||||
|
for i, p := range d.pages {
|
||||||
|
content := fmt.Sprintf("q %.4f 0 0 %.4f 0 0 cm /Im0 Do Q", p.wPt, p.hPt)
|
||||||
|
obj(func() { // page
|
||||||
|
fmt.Fprintf(&out, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.4f %.4f] /Contents %d 0 R /Resources << /XObject << /Im0 %d 0 R >> >> >>\n",
|
||||||
|
p.wPt, p.hPt, pageObj(i)+1, pageObj(i)+2)
|
||||||
|
})
|
||||||
|
obj(func() { // contents
|
||||||
|
fmt.Fprintf(&out, "<< /Length %d >>\nstream\n%s\nendstream\n", len(content), content)
|
||||||
|
})
|
||||||
|
obj(func() { // image
|
||||||
|
fmt.Fprintf(&out, "<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length %d >>\nstream\n",
|
||||||
|
p.imgW, p.imgH, len(p.gray))
|
||||||
|
out.Write(p.gray)
|
||||||
|
out.WriteString("\nendstream\n")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
xref := out.Len()
|
||||||
|
fmt.Fprintf(&out, "xref\n0 %d\n0000000000 65535 f \n", len(offsets))
|
||||||
|
for _, off := range offsets[1:] {
|
||||||
|
fmt.Fprintf(&out, "%010d 00000 n \n", off)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&out, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(offsets), xref)
|
||||||
|
return out.Bytes(), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testPNG(t *testing.T, w, h int) []byte {
|
||||||
|
t.Helper()
|
||||||
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||||
|
for x := 0; x < w; x++ {
|
||||||
|
img.Set(x, h/2, color.Black)
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := png.Encode(&buf, img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDocShape(t *testing.T) {
|
||||||
|
var d Doc
|
||||||
|
// A 90×29 mm label at 300 dpi is 1063×343 px.
|
||||||
|
if err := d.AddImagePage(testPNG(t, 1063, 343), 90, 29); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.AddImagePage(testPNG(t, 1063, 343), 90, 29); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, err := d.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Not a PDF parser — the shape a viewer needs to find its way in.
|
||||||
|
for _, want := range []string{"%PDF-1.4", "/Count 2", "/DeviceGray", "startxref", "%%EOF"} {
|
||||||
|
if !bytes.Contains(b, []byte(want)) {
|
||||||
|
t.Errorf("missing %q in output", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 90 mm = 255.118 pt — the page size a driver prints 1:1 on the roll.
|
||||||
|
if !bytes.Contains(b, []byte("/MediaBox [0 0 255.1181 82.2047]")) {
|
||||||
|
t.Errorf("media box is not the label size")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyDocRefused(t *testing.T) {
|
||||||
|
var d Doc
|
||||||
|
if _, err := d.Bytes(); err == nil {
|
||||||
|
t.Fatal("an empty document should refuse to render")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -232,6 +232,9 @@ type ListFilter struct {
|
|||||||
Band string `json:"band,omitempty"`
|
Band string `json:"band,omitempty"`
|
||||||
Mode string `json:"mode,omitempty"`
|
Mode string `json:"mode,omitempty"`
|
||||||
StationCallsign string `json:"station_callsign,omitempty"`
|
StationCallsign string `json:"station_callsign,omitempty"`
|
||||||
|
// QSLSentIn keeps only rows whose paper-QSL sent status is one of these
|
||||||
|
// values — 'R' (requested) and 'Q' (queued) are the label printer's queue.
|
||||||
|
QSLSentIn []string `json:"qsl_sent_in,omitempty"`
|
||||||
Limit int `json:"limit,omitempty"`
|
Limit int `json:"limit,omitempty"`
|
||||||
Offset int `json:"offset,omitempty"`
|
Offset int `json:"offset,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -1211,6 +1214,12 @@ func (r *Repo) List(ctx context.Context, f ListFilter) ([]QSO, error) {
|
|||||||
q += " AND station_callsign = ?"
|
q += " AND station_callsign = ?"
|
||||||
args = append(args, f.StationCallsign)
|
args = append(args, f.StationCallsign)
|
||||||
}
|
}
|
||||||
|
if len(f.QSLSentIn) > 0 {
|
||||||
|
q += " AND qsl_sent IN (?" + strings.Repeat(",?", len(f.QSLSentIn)-1) + ")"
|
||||||
|
for _, v := range f.QSLSentIn {
|
||||||
|
args = append(args, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
q += " ORDER BY qso_date DESC, id DESC"
|
q += " ORDER BY qso_date DESC, id DESC"
|
||||||
if f.Limit <= 0 {
|
if f.Limit <= 0 {
|
||||||
f.Limit = 500
|
f.Limit = 500
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
// appVersion is stamped on every heartbeat (and could feed the About box).
|
// appVersion is stamped on every heartbeat (and could feed the About box).
|
||||||
appVersion = "0.26.21"
|
appVersion = "0.26.22"
|
||||||
|
|
||||||
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
|
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
|
||||||
// to https://us.i.posthog.com for a US project.
|
// to https://us.i.posthog.com for a US project.
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// Placing a window at an absolute desktop coordinate is Windows-specific; every
|
||||||
|
// caller falls back to the toolkit's own call when this says no.
|
||||||
|
func setWindowPosAbsolute(x, y int) bool { return false }
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"hamlog/internal/applog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Moving the window to an ABSOLUTE virtual-desktop position.
|
||||||
|
//
|
||||||
|
// Wails' own WindowSetPosition cannot do it. Its Windows implementation reads:
|
||||||
|
//
|
||||||
|
// func (cba *ControlBase) SetPos(x, y int) {
|
||||||
|
// info := getMonitorInfo(cba.hwnd)
|
||||||
|
// w32.SetWindowPos(cba.hwnd, HWND_TOP, int(info.RcWork.Left)+x, int(info.RcWork.Top)+y, ...)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// — the coordinates are relative to the CURRENT monitor's work area, while
|
||||||
|
// WindowGetPosition returns GetWindowRect, which is absolute. Saving one and
|
||||||
|
// restoring the other is only harmless on the primary monitor, where the work
|
||||||
|
// area starts at 0.
|
||||||
|
//
|
||||||
|
// On a second monitor to the LEFT it compounds at every launch. Reported from a
|
||||||
|
// two-screen station with the left monitor at x = -3840: OpsLog saved -3844,
|
||||||
|
// reopened on that monitor, added the monitor's own origin, and stored -7684 —
|
||||||
|
// then -11524, each launch one screen further into nowhere.
|
||||||
|
//
|
||||||
|
// So we place the window ourselves. Same call the toolkit makes, without the
|
||||||
|
// offset.
|
||||||
|
const (
|
||||||
|
swpNoSize = 0x0001
|
||||||
|
swpNoZOrder = 0x0004
|
||||||
|
swpNoActivate = 0x0010
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
procSetWindowPos = user32Dll.NewProc("SetWindowPos")
|
||||||
|
procEnumWindows = user32Dll.NewProc("EnumWindows")
|
||||||
|
procGetWindowThreadProcessID = user32Dll.NewProc("GetWindowThreadProcessId")
|
||||||
|
procGetWindowTextLengthW = user32Dll.NewProc("GetWindowTextLengthW")
|
||||||
|
procGetWindow = user32Dll.NewProc("GetWindow")
|
||||||
|
kernel32Dll = syscall.NewLazyDLL("kernel32.dll")
|
||||||
|
procGetCurrentProcessIDWinPos = kernel32Dll.NewProc("GetCurrentProcessId")
|
||||||
|
)
|
||||||
|
|
||||||
|
// mainWindowHandle finds this process's own top-level window.
|
||||||
|
//
|
||||||
|
// Wails does not expose the handle, so it is looked up: the first top-level
|
||||||
|
// window belonging to this process id that has no owner and a title. The window
|
||||||
|
// is created hidden (StartHidden), and EnumWindows lists hidden windows too,
|
||||||
|
// which is what makes this usable before the window is shown.
|
||||||
|
func mainWindowHandle() uintptr {
|
||||||
|
self, _, _ := procGetCurrentProcessIDWinPos.Call()
|
||||||
|
var found uintptr
|
||||||
|
cb := syscall.NewCallback(func(hwnd uintptr, _ uintptr) uintptr {
|
||||||
|
var pid uint32
|
||||||
|
procGetWindowThreadProcessID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
|
||||||
|
if uintptr(pid) != self {
|
||||||
|
return 1 // keep going
|
||||||
|
}
|
||||||
|
// GW_OWNER = 4: skip tool windows and dialogs owned by the main one.
|
||||||
|
if owner, _, _ := procGetWindow.Call(hwnd, 4); owner != 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if n, _, _ := procGetWindowTextLengthW.Call(hwnd); n == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
found = hwnd
|
||||||
|
return 0 // stop
|
||||||
|
})
|
||||||
|
procEnumWindows.Call(cb, 0)
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
// setWindowPosAbsolute moves the window to a virtual-desktop coordinate.
|
||||||
|
// Reports whether it could; the caller falls back to the toolkit's own call.
|
||||||
|
func setWindowPosAbsolute(x, y int) bool {
|
||||||
|
hwnd := mainWindowHandle()
|
||||||
|
if hwnd == 0 {
|
||||||
|
applog.Printf("window: could not find our own window handle — falling back to the toolkit's placement")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
r, _, err := procSetWindowPos.Call(hwnd, 0, uintptr(int32(x)), uintptr(int32(y)), 0, 0,
|
||||||
|
swpNoSize|swpNoZOrder|swpNoActivate)
|
||||||
|
if r == 0 {
|
||||||
|
applog.Printf("window: SetWindowPos(%d,%d) failed: %v", x, y, err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user