Author SHA1 Message Date
gronodandDevin e8678586bd fix(print): deterministic PPD locale precedence for media labels (#181)
macOS CI / build-and-test (push) Skipped
Refs #181

Co-Authored-By: Devin <devin@cognition.ai>
2026-09-15 19:25:46 +01:00
gronod c9b423b229 Merge pull request 'fix(print): enumerate all EPIJ_Qual quality options (#180)' (#194) from feat/180-epson-qual-options into milestone/m11-print-settings
macOS CI / build-and-test (push) Skipped
2026-09-15 19:07:18 +01:00
gronodandDevin 79209eb911 fix(print): enumerate all EPIJ_Qual quality options (#180)
macOS CI / build-and-test (push) Skipped
The Phase 1 (#183) quality plumbing already covers detection,
extraction, capture, and lp emission — this change proves the Epson
path end-to-end with recorded fixtures.

- CupsParserTests: replace the synthetic cupsPrintQuality listing with
  the recorded XP-55 line (301 302 *303 308 304 305 307 — driver order,
  308 between 303 and 304); assert all seven ids enumerate unsorted,
  the * default is 303, all seven PPD labels resolve, and EPIJ_Qual
  wins detection over OutputMode/Resolution (R11).
- CupsOptionsFilterTests: captured EPIJ_Qual + canonical quality keys
  survive the filter (roster verified complete post-#183 — no source
  change needed; EPIJ_Quality kept as harmless alias, R16).
- LpArgsTests: explicit quality 305 emits -o EPIJ_Qual=305.
- PrintSessionViewModelTests + UI lpoptions fixture: recorded
  seven-choice line feeds the picker; Stage 2 picker lists all seven
  entries in driver order (new UI test).

Devin-AI: Devin <devin@cognition.ai>
Co-authored-by: Devin <devin@cognition.ai>
2026-09-15 19:06:47 +01:00
gronod 51c30737c7 Merge pull request 'feat(print): Stage 2 paper size + quality selection (#183)' (#193) from feat/183-stage2-print-settings into milestone/m11-print-settings
macOS CI / build-and-test (push) Skipped
2026-09-15 18:43:19 +01:00
8 changed files with 326 additions and 24 deletions
@@ -174,8 +174,13 @@ public enum CupsParsers {
/// PPD `*<key> <id>/<Human Label>:` lines `id label` map.
/// Language-qualified forms (`*en_US.<key> id/Label:`) also match.
/// Precedence is deterministic, not positional (#181): unqualified
/// `*Key` > `en_US.` > `en.` > first-qualified-seen, so a trailing
/// locale block (Canon `th.CNIJMediaType`) can never overwrite the
/// base English labels and a qualified-only id still gets its
/// first-seen qualified label (R9).
public static func ppdChoiceLabels(_ ppd: String, key: String) -> [String: String] {
var map: [String: String] = [:]
var hits: [String: [(qualifier: String?, label: String)]] = [:]
for rawLine in ppd.split(separator: "\n") {
var line = rawLine.trimmingCharacters(in: .whitespaces)
guard line.hasPrefix("*"), !line.hasPrefix("**") else { continue }
@@ -183,7 +188,9 @@ public enum CupsParsers {
// Optional locale qualifier: `en_US.InputSlot` `InputSlot`.
// Only strip when the part before the first `.` looks like
// a locale (short `xx`/`xx_YY`); real keys containing dots
// are left alone.
// are left alone. The qualifier is recorded for precedence
// rather than dropped (#181).
var qualifier: String?
if let dot = line.firstIndex(of: ".") {
let prefix = line[..<dot]
let looksLikeLocale = (2...5).contains(prefix.count)
@@ -191,6 +198,7 @@ public enum CupsParsers {
&& (prefix.count == 2 || prefix.contains("_"))
let candidate = line[line.index(after: dot)...]
if looksLikeLocale && candidate.hasPrefix(key) {
qualifier = prefix.lowercased()
line = String(candidate)
}
}
@@ -201,15 +209,50 @@ public enum CupsParsers {
rest = String(rest[..<colon])
// `<id>/<Human label>` human label after the last `/`.
guard let slash = rest.firstIndex(of: "/") else { continue }
let id = String(rest[..<slash])
.trimmingCharacters(in: .whitespaces)
let human = String(rest[rest.index(after: slash)...])
.trimmingCharacters(in: .whitespaces)
if !id.isEmpty { map[id] = human.isEmpty ? id : human }
let id = ppdUnescape(String(rest[..<slash])
.trimmingCharacters(in: .whitespaces))
let human = ppdUnescape(String(rest[rest.index(after: slash)...])
.trimmingCharacters(in: .whitespaces))
guard !id.isEmpty else { continue }
hits[id, default: []].append(
(qualifier, human.isEmpty ? id : human))
}
var map: [String: String] = [:]
for (id, candidates) in hits {
// First occurrence wins inside each qualifier class, in
// file order same as the old sequential behaviour.
map[id] = candidates.first { $0.qualifier == nil }?.label
?? candidates.first { $0.qualifier == "en_us" }?.label
?? candidates.first { $0.qualifier == "en" }?.label
?? candidates[0].label
}
return map
}
/// PPD `<XX>` hex escapes the literal byte (`<2F>` `/`,
/// `<20>` space). Anything that is not `<` + two hex digits +
/// `>` passes through untouched (#181).
private static func ppdUnescape(_ text: String) -> String {
var result = ""
var index = text.startIndex
while index < text.endIndex {
guard text[index] == "<",
let hexEnd = text.index(
index, offsetBy: 3, limitedBy: text.endIndex),
hexEnd < text.endIndex, text[hexEnd] == ">",
let byte = UInt8(
text[text.index(after: index)..<hexEnd], radix: 16)
else {
result.append(text[index])
index = text.index(after: index)
continue
}
result.append(Character(UnicodeScalar(byte)))
index = text.index(after: hexEnd)
}
return result
}
// MARK: - Detection (docs/11)
/// Media-type option key in preference order used both to read a
@@ -187,7 +187,11 @@ public struct CupsService: Sendable {
private func loadPPD(for queue: String) -> String? {
let url = ppdDir.appendingPathComponent("\(queue).ppd")
return try? String(contentsOf: url, encoding: .utf8)
// UTF-8 first the Canon Thai labels are UTF-8 and a blanket
// Latin-1 read would mojibake them (#181, R10). Latin-1 only
// when UTF-8 decoding fails outright.
return (try? String(contentsOf: url, encoding: .utf8))
?? (try? String(contentsOf: url, encoding: .isoLatin1))
}
// MARK: - Spawn
@@ -24,6 +24,18 @@ final class CupsOptionsFilterTests: XCTestCase {
XCTAssertEqual(CupsOptionsFilter.filter(raw), raw)
}
/// #180 a captured `EPIJ_Qual` (and the other canonical quality
/// keys) survives the filter so it wins over the Stage 2 explicit
/// quality in `LpArgs`.
func testKeepsQualityKeys() {
let raw = "EPIJ_Qual=304 CNIJPrintQuality=3 PrintQuality=2 "
+ "cupsPrintQuality=High Quality=Best "
+ "com.apple.print.JobTicket.PMTotalSidesImaged=0"
XCTAssertEqual(CupsOptionsFilter.filter(raw),
"EPIJ_Qual=304 CNIJPrintQuality=3 PrintQuality=2 "
+ "cupsPrintQuality=High Quality=Best")
}
func testKeepsUnknown() {
let raw = "VendorFooBar=baz MediaType=Plain"
XCTAssertEqual(CupsOptionsFilter.filter(raw), raw)
+222 -10
View File
@@ -30,7 +30,7 @@ final class CupsParserTests: XCTestCase {
MediaType/Media Type: *Stationery PhotographicHighGloss Photographic PhotographicMatte Envelope
ColorModel/Output Mode: *RGB Gray
Duplex/Duplex: *None DuplexNoTumble DuplexTumble
cupsPrintQuality/cupsPrintQuality: Draft *Normal High
EPIJ_Qual/Print Quality: 301 302 *303 308 304 305 307
"""
func testDestinations() {
@@ -124,6 +124,12 @@ final class CupsParserTests: XCTestCase {
// last (they are colour-ish keys on some drivers #183/#180).
XCTAssertEqual(CupsParsers.detectQualityKey(
optionKeys: ["EPIJ_Qual", "Quality", "OutputMode"]), "EPIJ_Qual")
// A full Epson key set EPIJ_Qual wins over the colour-mode
// key, the generic keys, and Resolution (#180, R11).
XCTAssertEqual(CupsParsers.detectQualityKey(
optionKeys: ["EPIJ_Qual", "OutputMode", "Resolution",
"cupsPrintQuality", "PrintQuality",
"ColorModel"]), "EPIJ_Qual")
XCTAssertEqual(CupsParsers.detectQualityKey(
optionKeys: ["Quality", "OutputMode", "Resolution"]), "Quality")
XCTAssertEqual(CupsParsers.detectQualityKey(
@@ -141,32 +147,65 @@ final class CupsParserTests: XCTestCase {
let listings = CupsParsers.lpoptionsList(lpoptionsL)
let caps = service.capabilities(from: listings, ppd: nil)
// The fixture's only roster member is cupsPrintQuality.
XCTAssertEqual(caps.qualityKey, "cupsPrintQuality")
XCTAssertEqual(caps.qualities.map(\.id), ["Draft", "Normal", "High"])
XCTAssertEqual(caps.qualityDefault, "Normal")
// EPIJ_Qual is the roster member all seven Epson codes
// enumerate in the driver's own (non-sorted) order (#180).
XCTAssertEqual(caps.qualityKey, "EPIJ_Qual")
XCTAssertEqual(caps.qualities.map(\.id),
["301", "302", "303", "308", "304", "305", "307"])
XCTAssertEqual(caps.qualityDefault, "303")
}
func testCapabilitiesQualityPpdLabels() {
// Epson XP-55 PPD fragment the seven `*EPIJ_Qual id/Label`
// lines in the driver's own order (#180).
let ppd = """
*EPIJ_Qual 301/Draft: ""
*OpenUI *EPIJ_Qual/Print Quality: PickOne
*DefaultEPIJ_Qual: 303
*EPIJ_Qual 301/Fast Economy: ""
*EPIJ_Qual 302/Economy: ""
*EPIJ_Qual 303/Normal: ""
*EPIJ_Qual 308/High Speed: ""
*EPIJ_Qual 308/Draft: ""
*EPIJ_Qual 304/Fine: ""
*EPIJ_Qual 305/Quality: ""
*EPIJ_Qual 307/Best Quality: ""
*CloseUI: *EPIJ_Qual
"""
let service = CupsService()
let listings = CupsParsers.lpoptionsList(
"EPIJ_Qual/Print Quality: 301 *303 308\n")
"EPIJ_Qual/Print Quality: 301 302 *303 308 304 305 307\n")
let caps = service.capabilities(from: listings, ppd: ppd)
XCTAssertEqual(caps.qualityKey, "EPIJ_Qual")
XCTAssertEqual(caps.qualities, [
PrinterQuality(id: "301", name: "Draft"),
PrinterQuality(id: "301", name: "Fast Economy"),
PrinterQuality(id: "302", name: "Economy"),
PrinterQuality(id: "303", name: "Normal"),
PrinterQuality(id: "308", name: "High Speed"),
PrinterQuality(id: "308", name: "Draft"),
PrinterQuality(id: "304", name: "Fine"),
PrinterQuality(id: "305", name: "Quality"),
PrinterQuality(id: "307", name: "Best Quality"),
])
XCTAssertEqual(caps.qualityDefault, "303")
}
/// #180 the Epson listing also carries `OutputMode` (a colour
/// mode) and `Resolution`; detection must still pick `EPIJ_Qual`.
func testCapabilitiesQualityEpsonDetection() {
let service = CupsService()
let listings = CupsParsers.lpoptionsList("""
PageSize/Media Size: *A4 Letter
EPIJ_Qual/Print Quality: 301 302 *303 308 304 305 307
OutputMode/Color Mode: *Color Mono
Resolution/Resolution: *360dpi 720dpi
""")
let caps = service.capabilities(from: listings, ppd: nil)
XCTAssertEqual(caps.qualityKey, "EPIJ_Qual")
XCTAssertEqual(caps.qualities.count, 7)
XCTAssertEqual(caps.qualityDefault, "303")
XCTAssertFalse(caps.qualities.contains { $0.id == "Color" })
}
func testExtractOption() {
let options = "PageSize=A4 EPIJ_Qual=303 printer-info='EPSON XP-55'"
XCTAssertEqual(CupsParsers.extractOption(
@@ -207,4 +246,177 @@ final class CupsParserTests: XCTestCase {
XCTAssertEqual(pair(["EpsonColorMode"]), "EpsonColorMode=Off")
XCTAssertNil(pair(["PageSize"]))
}
// MARK: - #181 Canon media locale precedence + PPD encoding
/// The 18 Canon Pro9500 media types named in the issue the ids
/// are the numeric codes the driver enumerates via `lpoptions -l`.
private let canonMedia: [(id: String, label: String)] = [
("0", "Plain Paper"),
("1", "Photo Paper Plus Glossy II"),
("2", "Photo Paper Pro Platinum N"),
("3", "Photo Paper Pro Platinum"),
("4", "Photo Paper Pro Luster"),
("5", "Photo Paper Plus Semi-gloss"),
("6", "Matte Photo Paper"),
("7", "Fine Art \"Photo Rag\""),
("8", "Fine Art \"Museum Etching\""),
("9", "Photo Paper Pro Premium Matte"),
("10", "Fine Art Premium Matte"),
("11", "Other Fine Art Paper"),
("12", "Canvas"),
("13", "Board Paper"),
("14", "Ink Jet Hagaki"),
("15", "Hagaki"),
("16", "Printable disc"),
("17", "Printable disc (bleed-proof)"),
]
/// Canon Pro9500-shaped fragment: the unqualified base block comes
/// early and the `th.` block trails at the end the ordering that
/// let Thai overwrite English under last-write-wins (#181).
private var canonPPD: String {
var lines = [
"*OpenUI *CNIJMediaType/Media Type: PickOne",
"*DefaultCNIJMediaType: 0",
]
for media in canonMedia {
lines.append(
"*CNIJMediaType \(media.id)/\(media.label): \"\"")
}
lines.append("*CloseUI: *CNIJMediaType")
for media in canonMedia {
lines.append(
"*th.CNIJMediaType \(media.id)/กระดาษ\(media.id): \"\"")
}
return lines.joined(separator: "\n")
}
func testPpdLabelsUnqualifiedSurvivesTrailingThai() {
let labels = CupsParsers.ppdChoiceLabels(
canonPPD, key: "CNIJMediaType")
XCTAssertEqual(labels["0"], "Plain Paper")
XCTAssertEqual(labels["17"], "Printable disc (bleed-proof)")
}
func testPpdLabelsUnqualifiedWinsRegardlessOfOrder() {
// `th.` block first precedence is deterministic, not
// positional (#181, E3).
let ppd = """
*th.CNIJMediaType 0/กระดาษธรรมดา: ""
*CNIJMediaType 0/Plain Paper: ""
"""
let labels = CupsParsers.ppdChoiceLabels(ppd, key: "CNIJMediaType")
XCTAssertEqual(labels["0"], "Plain Paper")
}
func testPpdLabelsQualifiedFallbackOrder() {
// en_US > en > first-qualified-seen (#181, E3).
let ppd = """
*en.CNIJMediaType 1/English Label: ""
*en_US.CNIJMediaType 1/US English Label: ""
*th.CNIJMediaType 1/กระดาษ: ""
*fr.CNIJMediaType 2/Français: ""
*de.CNIJMediaType 2/Deutsch: ""
"""
let labels = CupsParsers.ppdChoiceLabels(ppd, key: "CNIJMediaType")
XCTAssertEqual(labels["1"], "US English Label")
// A qualified-only id still gets its first-seen qualified
// label never left unlabeled (R9).
XCTAssertEqual(labels["2"], "Français")
}
func testPpdLabelsHexEscapeDecoding() {
let ppd = """
*CNIJMediaType 3/Photo Paper Plus Glossy<2F>Matte: ""
*CNIJMediaType 4/Plain<20>Paper: ""
*CNIJMediaType 5/Bad<ZZ>Escape: ""
"""
let labels = CupsParsers.ppdChoiceLabels(ppd, key: "CNIJMediaType")
XCTAssertEqual(labels["3"], "Photo Paper Plus Glossy/Matte")
XCTAssertEqual(labels["4"], "Plain Paper")
XCTAssertEqual(labels["5"], "Bad<ZZ>Escape")
}
/// Every `CNIJMediaType` choice enumerated by `lpoptions -l` gets a
/// non-Thai label (E1 the true count is the hardware gate's, so
/// no count is hardcoded here); the 18 named AC labels are
/// spot-checked.
func testCapabilitiesCanonMediaAllNonThai() {
var choices = canonMedia.map(\.id)
choices[0] = "*\(choices[0])"
let listings = CupsParsers.lpoptionsList(
"CNIJMediaType/Media Type: \(choices.joined(separator: " "))\n")
let caps = CupsService().capabilities(from: listings, ppd: canonPPD)
XCTAssertEqual(caps.mediaTypes.count, canonMedia.count)
for type in caps.mediaTypes {
XCTAssertFalse(type.name.unicodeScalars.contains {
(0x0E00...0x0E7F).contains($0.value)
}, "Thai label leaked into \(type.id): \(type.name)")
}
for media in canonMedia {
XCTAssertEqual(
caps.mediaTypes.first { $0.id == media.id }?.name,
media.label)
}
}
/// UTF-8 PPD carrying Thai labels decodes intact the English
/// base block wins precedence and no mojibake leaks through (#181,
/// R10). Exercises `loadPPD` through `capabilities(for:)`.
func testLoadPPDUtf8ThaiSurvivesDecode() async throws {
let (service, root) = try makeCupsService(
ppdData: Data(canonPPD.utf8),
listing: "CNIJMediaType/Media Type: *0 1")
defer { try? FileManager.default.removeItem(at: root) }
let caps = try await service.capabilities(for: "Canon_Test")
XCTAssertEqual(caps.mediaTypes.map(\.name),
["Plain Paper", "Photo Paper Plus Glossy II"])
}
/// A PPD that is not valid UTF-8 (lone `0xE9` for `é`) falls back
/// to ISO-Latin-1 instead of yielding nil raw ids (#181, R10).
func testLoadPPDLatin1Fallback() async throws {
let ppd = "*CNIJMediaType 0/Papier Couché: \"\"\n"
let (service, root) = try makeCupsService(
ppdData: ppd.data(using: .isoLatin1)!,
listing: "CNIJMediaType/Media Type: *0")
defer { try? FileManager.default.removeItem(at: root) }
let caps = try await service.capabilities(for: "Canon_Test")
XCTAssertEqual(caps.mediaTypes,
[PrinterMediaType(id: "0", name: "Papier Couché")])
}
/// Fixture `lpoptions` + `ppdDir` so `capabilities(for:)` reaches
/// the private `loadPPD` same mock style as
/// `MediaLibraryViewModelTests.installMockCups`.
private func makeCupsService(
ppdData: Data,
listing: String,
queue: String = "Canon_Test"
) throws -> (CupsService, URL) {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("iccery-ppd-\(UUID().uuidString)")
let bin = root.appendingPathComponent("bin")
let ppdDir = root.appendingPathComponent("ppd")
for dir in [bin, ppdDir] {
try FileManager.default.createDirectory(
at: dir, withIntermediateDirectories: true)
}
let lpoptions = """
#!/bin/sh
printf '%s\\n' '\(listing)'
"""
let scriptURL = bin.appendingPathComponent("lpoptions")
try lpoptions.write(to: scriptURL, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes(
[.posixPermissions: 0o755], ofItemAtPath: scriptURL.path)
try ppdData.write(to: ppdDir.appendingPathComponent("\(queue).ppd"))
return (CupsService(
processManager: ProcessManager(),
binaryDir: bin, ppdDir: ppdDir), root)
}
}
+3 -3
View File
@@ -106,12 +106,12 @@ final class LpArgsTests: XCTestCase {
func testQualityDerived() throws {
let argv = try build(
options: PrintOptions(
orientation: "portrait", mediaType: "Photo", quality: "303"),
orientation: "portrait", mediaType: "Photo", quality: "305"),
optionKeys: ["EPIJ_Qual", "MediaType"])
XCTAssertTrue(argv.contains("EPIJ_Qual=303"))
XCTAssertTrue(argv.contains("EPIJ_Qual=305"))
// Emit order: after the media option, before orientation.
let media = argv.firstIndex(of: "MediaType=Photo")!
let quality = argv.firstIndex(of: "EPIJ_Qual=303")!
let quality = argv.firstIndex(of: "EPIJ_Qual=305")!
let orient = argv.firstIndex(of: "orientation-requested=3")!
XCTAssertTrue(media < quality && quality < orient)
}
@@ -50,7 +50,7 @@ final class PrintSessionViewModelTests: XCTestCase {
printf 'PageSize/Media Size: 4x6 5x7 *A4 Letter Legal Custom.WIDTHxHEIGHT\\n'
printf 'InputSlot/Media Source: Auto *Main Rear\\n'
printf 'MediaType/Media Type: *Stationery Glossy Matte\\n'
printf 'EPIJ_Qual/Print Quality: 301 302 *303 304\\n'
printf 'EPIJ_Qual/Print Quality: 301 302 *303 308 304 305 307\\n'
exit 0
fi
printf "printer-info='Mock %s' printer-type=42\\n" "$queue"
@@ -106,6 +106,9 @@ final class PrintSessionViewModelTests: XCTestCase {
XCTAssertEqual(workflow.print.selectedPaperSize, 3)
// Quality seeds from the `*` default on caps load.
XCTAssertEqual(workflow.print.selectedQuality, "303")
// All seven Epson codes enumerate in driver order (#180).
XCTAssertEqual(workflow.print.printerCaps.qualities.map(\.id),
["301", "302", "303", "308", "304", "305", "307"])
}
/// `.custom` synthetic `id: 0` entry whose token is the
+4 -2
View File
@@ -1,6 +1,8 @@
#!/bin/sh
# Mock lpoptions for Milestone3UITests. `-p <q>` prints printer-info;
# `-p <q> -l` prints Key/Label listings incl. Epson bypass keys.
# `-p <q> -l` prints Key/Label listings incl. Epson bypass keys and the
# recorded XP-55 EPIJ_Qual line — the driver's own non-sorted order
# (308 sits between 303 and 304, #180).
queue=""
list=0
for arg in "$@"; do
@@ -15,7 +17,7 @@ if [ "$list" = "1" ]; then
printf 'PageSize/Media Size: 4x6 5x7 *A4 Letter Legal\n'
printf 'InputSlot/Media Source: Auto *Main Rear\n'
printf 'MediaType/Media Type: *Stationery PhotographicGlossy PhotographicMatte\n'
printf 'EPIJ_Qual/Print Quality: 301 302 *303 304 305 307 308\n'
printf 'EPIJ_Qual/Print Quality: 301 302 *303 308 304 305 307\n'
printf 'EPIJ_CMat/Color Adjust: *0 1 2 3\n'
printf 'ColorModel/Output Mode: *RGB Gray\n'
exit 0
@@ -136,6 +136,32 @@ final class Milestone11PrintSettingsUITests: XCTestCase {
XCTAssertEqual(selection(of: "printerQualitySelect"), "303")
}
/// #180 the quality picker lists all seven Epson `EPIJ_Qual`
/// codes in the driver's own order (308 between 303 and 304); no
/// PPD is injected under UI testing so items show raw tokens.
func testQualityPickerListsAllSevenDriverOptions() throws {
launchAppWithDefaults()
reachPrintPanel()
_ = waitFor("printerStatusBadge")
let picker = app.popUpButtons["printerQualitySelect"]
XCTAssertTrue(picker.waitForExistence(timeout: 10))
picker.click()
let expected = ["301", "302", "303", "308", "304", "305", "307"]
for token in expected {
XCTAssertTrue(
app.menuItems[token].waitForExistence(timeout: 5),
"Missing quality menu item \(token)")
}
let titles = app.menuItems.allElementsBoundByIndex
.map(\.title)
.filter { expected.contains($0) }
XCTAssertEqual(titles, expected)
app.typeKey(XCUIKeyboardKey.escape, modifierFlags: [])
}
/// The stubbed panel result's captured `PageSize=`/`EPIJ_Qual=`
/// apply back into the Stage 2 pickers and reach the `lp` argv
/// (R15 the real modal is never driven).