Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/Madeira/ClaudeHelp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ enum ClaudeHelp {
// Chats take .txt files more readily than .cfg ones.
let cfg = docs.appendingPathComponent(MadeiraConfig.fileName)
let cfgCopy = folder.appendingPathComponent("madeira.cfg.txt")
if let text = try? String(contentsOf: cfg, encoding: .utf8),
// Lossy, as MadeiraConfig reads it: a byte that is not UTF-8 must not leave the file out of the help.
if let text = (try? Data(contentsOf: cfg)).map({ String(decoding: $0, as: UTF8.self) }),
(try? ("# Documents/madeira.cfg (global settings)\n" + text).write(to: cfgCopy, atomically: true, encoding: .utf8)) != nil {
out.append(cfgCopy)
}
Expand Down
14 changes: 12 additions & 2 deletions app/Madeira/GameIniFiles.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,23 @@ struct IniDocument: Equatable {
var text: String { lines.joined(separator: newline) + (endsWithNewline ? newline : "") }
}

/// A file's bytes as text, and back in the same encoding (UTF-8, with or
/// without a byte order mark, else Windows Latin 1, which every byte decodes as).
/// A file's bytes as text, and back in the same encoding (UTF-16 LE with its
/// byte order mark, UTF-8 with or without one, else Windows Latin 1, which
/// every byte decodes as).
struct IniFileText: Equatable {
var text: String
let bom: Bool
let utf8: Bool
let utf16: Bool

init?(data: Data) {
// FF FE is what Windows calls "Unicode"; WritePrivateProfileStringW keeps writing such a file as UTF-16 LE.
if data.starts(with: [0xFF, 0xFE]) {
guard let s = String(data: Data(data.dropFirst(2)), encoding: .utf16LittleEndian) else { return nil }
text = s; bom = true; utf8 = false; utf16 = true
return
}
utf16 = false
let marker = Data([0xEF, 0xBB, 0xBF])
bom = data.starts(with: marker)
let body = bom ? data.dropFirst(3) : data[...]
Expand All @@ -118,6 +127,7 @@ struct IniFileText: Equatable {
}

func data(_ text: String) -> Data? {
if utf16 { return text.data(using: .utf16LittleEndian).map { Data([0xFF, 0xFE]) + $0 } }
guard let body = text.data(using: utf8 ? .utf8 : .windowsCP1252) ?? text.data(using: .isoLatin1) else { return nil }
return (bom ? Data([0xEF, 0xBB, 0xBF]) : Data()) + body
}
Expand Down
29 changes: 21 additions & 8 deletions app/Madeira/MadeiraConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ enum MadeiraConfig {
cache.lock.lock()
defer { cache.lock.unlock() }
if let hit = cache.value, cache.stamp == stamp { return hit }
let parsed = stamp.isEmpty ? [:] : ((try? String(contentsOf: u, encoding: .utf8)).map(parse) ?? [:])
// A byte that is not UTF-8 reads as U+FFFD rather than hiding the whole file: build/madeira_cfg.h still applies it.
let parsed = stamp.isEmpty ? [:] : ((try? Data(contentsOf: u)).map { parse(String(decoding: $0, as: UTF8.self)) } ?? [:])
cache.value = parsed; cache.stamp = stamp; cache.exists = !stamp.isEmpty
return parsed
}
Expand Down Expand Up @@ -184,22 +185,34 @@ enum MadeiraConfig {
/// value is appended; a nil value removes the key. Without madeira.cfg the
/// legacy files are migrated first, so writing one key never hides the
/// switches that still live in madeira-*.txt files.
///
/// Works on bytes, like build/madeira_cfg.h: a line that is not UTF-8 (a
/// comment saved as Windows-1252 by a PC editor) is kept byte for byte, and
/// a file that exists but cannot be read is left alone (returns false)
/// instead of being rewritten with only this key.
@discardableResult
static func set(_ key: String, _ value: String?) -> Bool {
guard let u = url else { return false }
if !present { migrateLegacy(log: { _ in }) }
let text = (try? String(contentsOf: u, encoding: .utf8)) ?? ""
var lines = text.split(omittingEmptySubsequences: false, whereSeparator: { $0 == "\n" || $0 == "\r\n" }).map(String.init)
if lines.last == "" { lines.removeLast() }
var data = Data()
if FileManager.default.fileExists(atPath: u.path) {
guard let d = try? Data(contentsOf: u) else { return false }
data = d
}
var lines = data.split(separator: 0x0A, omittingEmptySubsequences: false).map { line -> Data in
line.last == 0x0D ? Data(line.dropLast()) : Data(line)
}
if lines.last?.isEmpty == true { lines.removeLast() }
lines.removeAll { line in
let t = line.trimmingCharacters(in: .whitespaces)
let t = String(decoding: line, as: UTF8.self).trimmingCharacters(in: .whitespaces)
guard !t.hasPrefix("#"), let eq = t.firstIndex(of: "=") else { return false }
return t[..<eq].trimmingCharacters(in: .whitespaces) == key
}
if let value { lines.append("\(key) = \(value)") }
let out = lines.joined(separator: "\n") + (lines.isEmpty ? "" : "\n")
if let value { lines.append(Data("\(key) = \(value)".utf8)) }
var out = Data(lines.joined(separator: [0x0A]))
if !lines.isEmpty { out.append(0x0A) }
defer { invalidate() }
do { try out.write(to: u, atomically: true, encoding: .utf8); return true } catch { return false }
do { try out.write(to: u, options: .atomic); return true } catch { return false }
}

/// An app-side switch spelled like the native ones: `env.NAME = value` in
Expand Down
8 changes: 7 additions & 1 deletion app/Madeira/WineProcessBridge.m
Original file line number Diff line number Diff line change
Expand Up @@ -1915,7 +1915,13 @@ static int madeira_split_launch_args(const char *input, char *storage, size_t st
NSString *text = nil;
if (madeira_cfg_present()) {
NSMutableString *acc = [NSMutableString string];
NSString *cfg = [NSString stringWithContentsOfFile:[docs stringByAppendingPathComponent:@MADEIRA_CFG_FILE] encoding:NSUTF8StringEncoding error:nil];
/* A byte that is not UTF-8 (a comment saved as Windows-1252) used to make the whole
* file nil, so no env line was exported though madeira_cfg.h applied the rest.
* shortcut: such a file is read as Latin 1, so a non-ASCII value in it is exported
* re-encoded rather than byte for byte; fine while env values are ASCII. */
NSData *cfgData = [NSData dataWithContentsOfFile:[docs stringByAppendingPathComponent:@MADEIRA_CFG_FILE]];
NSString *cfg = cfgData ? ([[NSString alloc] initWithData:cfgData encoding:NSUTF8StringEncoding]
?: [[NSString alloc] initWithData:cfgData encoding:NSISOLatin1StringEncoding]) : nil;
for (NSString *raw in [cfg componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
NSString *line = [raw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange eq = [line rangeOfString:@"="];
Expand Down
10 changes: 10 additions & 0 deletions tests/host/check-ini-editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ def check(condition, label):
let bom = Data([0xEF, 0xBB, 0xBF, 0x61, 0x3D, 0x31, 0x0A])
let u = IniFileText(data: bom)!
print("bom=\(u.bom),\(u.text == "a=1\n"),\(u.data(u.text) == bom)")
let wide = Data([0xFF, 0xFE]) + "[Display]\r\niSize W=1280\r\niSize H=720\r\n".data(using: .utf16LittleEndian)!
let w = IniFileText(data: wide)!
var wd = IniDocument(text: w.text)
let wideOpened = wd.sections.map(\.name) == ["Display"] && wd.value(section: "Display", key: "iSize W") == "1280"
wd.set(line: 1, to: "1600")
let wideSaved = w.data(wd.text)
print("utf16=\(w.utf16),\(wideOpened),\(w.data(w.text) == wide),\(wideSaved == Data([0xFF, 0xFE]) + "[Display]\r\niSize W=1600\r\niSize H=720\r\n".data(using: .utf16LittleEndian)!)")
print("utf16odd=\(IniFileText(data: Data([0xFF, 0xFE, 0x61])) == nil)")
print("label=" + GameIniFiles.label("users/steamuser/Documents/My Games/FalloutNV/Fallout.ini", gameFolder: nil) + "|" +
GameIniFiles.label("Program Files (x86)/Steam/steamapps/common/Fallout New Vegas/Fallout_default.ini",
gameFolder: "Program Files (x86)/Steam/steamapps/common/Fallout New Vegas"))
Expand Down Expand Up @@ -132,6 +140,8 @@ def check(condition, label):
check(out['switch'] == 'true,false,false', 'Bethesda 0/1 switches (bName) show as switches')
check(out['latin'] == 'false,true,true', 'a Windows Latin 1 file is saved in Latin 1')
check(out['bom'] == 'true,true,true', 'a UTF-8 byte order mark is kept')
check(out['utf16'] == 'true,true,true,true', 'a UTF-16 LE file (FF FE) opens with its sections and is saved as UTF-16 LE')
check(out['utf16odd'] == 'true', 'a broken UTF-16 file does not open, so it is never saved damaged')
check(out['label'] == 'My Games\\FalloutNV\\Fallout.ini|Fallout New Vegas\\Fallout_default.ini', 'short names')
check(out['folder'] == 'Games/NV|Games/NV', "the game's folder: the program's, or a Steam install folder")
check(out['list'] == 'x/B.ini', 'each game keeps its own list, once per file')
Expand Down
14 changes: 14 additions & 0 deletions tests/host/check-runtime-settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ def check(cond, what):
expect(SyncEngine.current == .wine, "inproc-sync = 0 without MADEIRA_FASTSYNC stays Wine standard sync (as written before)")
MadeiraConfig.set("inproc-sync", nil)
expect(SyncEngine.current == .fastsync, "neither key: Fastsync")

// A byte that is not UTF-8 (a comment saved as Windows-1252, 0xE9 = é) neither hides
// madeira.cfg from Settings nor lets set() rewrite it with only the new key.
var latin = Data("# r".utf8); latin.append(0xE9)
latin.append(contentsOf: Data("glages\r\nswap-mb = 4096\r\nvram-mb = 3072\nenv.MADEIRA_STEAM_LANGUAGE = french\n".utf8))
try! latin.write(to: cfg)
expect(MadeiraConfig.get("swap-mb") == "4096" && MadeiraConfig.get("env.MADEIRA_STEAM_LANGUAGE") == "french",
"a byte that is not UTF-8 does not hide madeira.cfg")
expect(MadeiraConfig.set("env.MADEIRA_STEAM_CLOUD", "0"), "set() on such a file succeeds")
let rewritten = try! Data(contentsOf: cfg)
expect(rewritten.starts(with: Data([0x23, 0x20, 0x72, 0xE9, 0x67])), "set() keeps the comment byte for byte")
expect(MadeiraConfig.get("swap-mb") == "4096" && MadeiraConfig.get("vram-mb") == "3072"
&& MadeiraConfig.get("env.MADEIRA_STEAM_LANGUAGE") == "french" && MadeiraConfig.get("env.MADEIRA_STEAM_CLOUD") == "0",
"set() keeps every other key of such a file")
exit(failed == 0 ? 0 : 1)
'''

Expand Down