taler-ios

iOS apps for GNU Taler (wallet)
Log | Files | Refs | README | LICENSE

CurrencySpecification.swift (20852B)


      1 /*
      2  * This file is part of GNU Taler, ©2022-26 Taler Systems S.A.
      3  * See LICENSE.md
      4  */
      5 /**
      6  * @author Marc Stibane
      7  */
      8 import Foundation
      9 import SwiftUI
     10 import taler_swift
     11 
     12 extension Locale {
     13     static var preferredLanguageCode: String {
     14         guard let preferredLanguage = preferredLanguages.first,
     15               let code = Locale(identifier: preferredLanguage).languageCode else {
     16             return "en"
     17         }
     18         return code
     19     }
     20 
     21     static var preferredLanguageCodes: [String] {
     22         return Locale.preferredLanguages.compactMap({Locale(identifier: $0).languageCode})
     23     }
     24 }
     25 // MARK: -
     26 extension Locale {
     27     func leadingCurrencySymbol() -> Bool {
     28         let currencyFormatter = NumberFormatter()
     29         currencyFormatter.numberStyle = .currency
     30         currencyFormatter.locale = self
     31 
     32         let positiveFormat = currencyFormatter.positiveFormat as NSString
     33         let currencySymbolLocation = positiveFormat.range(of: "¤").location
     34 
     35         return currencySymbolLocation == 0
     36     }
     37 }
     38 // MARK: -
     39 extension Amount {
     40     func formatted(_ currencyInfo: CurrencyInfo?, isNegative: Bool = false,
     41                            useISO: Bool = false, a11yDecSep: String? = nil
     42     ) -> (String, String) {
     43         if let currencyInfo {
     44             let a11y = currencyInfo.string(for: valueAsFloatTuple,
     45                                     isNegative: isNegative,
     46                                       currency: currencyStr,
     47                                         useISO: true,
     48                                     a11yDecSep: a11yDecSep)
     49             let strg = currencyInfo.string(for: valueAsFloatTuple,
     50                                     isNegative: isNegative,
     51                                       currency: currencyStr,
     52                                         useISO: useISO,
     53                                     a11yDecSep: nil)
     54             return (strg, a11y)
     55         } else {
     56             return (valueStr, valueStr)
     57         }
     58     }
     59 
     60     // this is the function to use
     61     func formatted(_ scope: ScopeInfo?, isNegative: Bool,
     62                     useISO: Bool = false, a11yDecSep: String? = nil
     63     ) -> (String, String) {
     64         let controller = Controller.shared
     65         if let scope {
     66             if let currencyInfo = controller.info(for: scope) {
     67                 return self.formatted(currencyInfo, isNegative: isNegative, useISO: useISO, a11yDecSep: a11yDecSep)
     68             }
     69         }
     70         return (self.readableDescription, self.readableDescription)
     71     }
     72 
     73     func formatted(specs: CurrencySpecification?, isNegative: Bool,
     74                    scope: ScopeInfo? = nil, useISO: Bool = false
     75     ) -> (String, String) {
     76         if let specs {
     77             let formatter = CurrencyFormatter.formatter(currency: currencyStr, specs: specs)
     78             let currencyInfo = CurrencyInfo(specs: specs, formatter: formatter)
     79             return formatted(currencyInfo, isNegative: isNegative, useISO: useISO)
     80         } else if let scope {
     81             return formatted(scope, isNegative: isNegative, useISO: useISO)
     82         }
     83         return (self.readableDescription, self.readableDescription)
     84     }
     85 
     86     func fractionalDigits(_ currencyInfo: CurrencyInfo) -> UInt {
     87         let inputDigits = currencyInfo.specs.fractionalInputDigits
     88         if inputDigits < 0 { return 0 }
     89         if inputDigits > 8 { return 8}
     90         return UInt(inputDigits)
     91     }
     92 
     93     func addDigit(_ digit: UInt8, currencyInfo: CurrencyInfo) {
     94         shiftLeft(add: digit, fractionalDigits(currencyInfo))
     95     }
     96 
     97     func removeDigit(_ currencyInfo: CurrencyInfo) {
     98         shiftRight()                        // divide by 10
     99         mask(fractionalDigits(currencyInfo))     // replace all digits after #inputDigit with 0
    100     }
    101 
    102     func plainString(_ currencyInfo: CurrencyInfo) -> String {
    103         return plainString(inputDigits: fractionalDigits(currencyInfo))
    104     }
    105 }
    106 // MARK: -
    107 public struct CurrencyInfo: Sendable {
    108 //    let scope: ScopeInfo
    109     let specs: CurrencySpecification
    110     let formatter: CurrencyFormatter
    111 
    112 //    public static func zero(_ currency: String) -> CurrencyInfo {
    113     public static func zero(_ currency: String, nu: Bool = false) -> CurrencyInfo {
    114         let null = nu ? "ヌ"                // use `nu´ for Null
    115                       : EMPTYSTRING
    116         let specs = CurrencySpecification(name: currency,
    117                                  commonAmounts: nil,
    118                          fractionalInputDigits: 0,
    119                         fractionalNormalDigits: 0,
    120                   fractionalTrailingZeroDigits: 0,
    121                                   altUnitNames: [0 : null])
    122         let formatter = CurrencyFormatter.formatter(currency: currency, specs: specs)
    123         return CurrencyInfo(specs: specs, formatter: formatter)
    124     }
    125 
    126     public static func euro() -> CurrencyInfo {
    127         let currency = EUR_4217
    128         let specs = CurrencySpecification(name: "Euro",
    129                                  commonAmounts: nil,
    130                          fractionalInputDigits: 2,
    131                         fractionalNormalDigits: 2,
    132                   fractionalTrailingZeroDigits: 2,
    133                                   altUnitNames: [0 : "€"])                      // ensure altUnitSymbol
    134         let formatter = CurrencyFormatter.formatter(currency: currency, specs: specs)
    135     print(formatter.name ?? formatter.altUnitSymbol ?? formatter.altUnitName0 ?? formatter.currency)
    136         return CurrencyInfo(specs: specs, formatter: formatter)
    137     }
    138 
    139     public static func francs() -> CurrencyInfo {
    140         let currency = CHF_4217
    141         let specs = CurrencySpecification(name: "Franken",
    142                                  commonAmounts: nil,
    143                          fractionalInputDigits: 2,
    144                         fractionalNormalDigits: 2,
    145                   fractionalTrailingZeroDigits: 2,
    146                                   altUnitNames: [0 : " Fr."])                   // ensure altUnitName0
    147         let formatter = CurrencyFormatter.formatter(currency: currency, specs: specs)
    148     print(formatter.name ?? formatter.altUnitSymbol ?? formatter.altUnitName0 ?? formatter.currency)
    149         return CurrencyInfo(specs: specs, formatter: formatter)
    150     }
    151 
    152 
    153     var currency: String { formatter.currency }
    154     private var altUnitName0: String? { formatter.altUnitName0 }
    155     private var altUnitSymbol: String? { formatter.altUnitSymbol }
    156     var name: String { specs.name }
    157     var symbol: String { altUnitSymbol ?? name }      // fall back to name if no symbol defined
    158     var hasSymbol: Bool {
    159         if symbol != name {
    160             let count = symbol.count
    161             return count > 0 && count <= 3
    162         }
    163         return false
    164     }
    165     var commonAmounts: [Amount]? { specs.commonAmounts }
    166 
    167     /// returns all characters left from the decimalSeparator
    168     func integerPartStr(_ integerStr: String, decimalSeparator: String) -> String {
    169         if let integerIndex = integerStr.endIndex(of: decimalSeparator) {
    170             // decimalSeparator was found ==> return all characters left of it
    171             return String(integerStr[..<integerIndex])
    172         }
    173         guard let firstChar = integerStr.first else { return "0" }    // TODO: should NEVER happen! Show error
    174         let digitSet = CharacterSet.decimalDigits
    175         if digitSet.contains(firstChar) {
    176             // Currency Symbol is after the amount ==> return only the digits
    177             return String(integerStr.unicodeScalars.filter { digitSet.contains($0) })
    178         } else {
    179             // Currency Symbol is in front of the amount ==> return everything
    180             return integerStr
    181         }
    182     }
    183 
    184     private func replacingCurrencyMarkers(in aString: String,
    185                                     with replacement: String) -> String {
    186         var result = aString
    187         if let symbol = formatter.currencySymbol, !symbol.isEmpty {
    188             result = result.replacingOccurrences(of: symbol, with: replacement)
    189         }
    190         if let code = formatter.currencyCode, !code.isEmpty,
    191                code != formatter.currencySymbol {
    192             result = result.replacingOccurrences(of: code, with: replacement)
    193         }
    194         return result
    195     }
    196 
    197     func currencyString(_ aString: String, useISO: Bool = false) -> String {
    198         if !useISO {
    199             if let aSymbol = altUnitSymbol {
    200                 return replacingCurrencyMarkers(in: aString, with: aSymbol)
    201             }
    202             if let aName = altUnitName0 {
    203                 let spacedName = formatter.leadingCurrencySymbol ? aName + SPACE
    204                                                                  : SPACE + aName
    205                 let spaced = replacingCurrencyMarkers(in: aString, with: spacedName)
    206                 return spaced.replacingOccurrences(of: "  ", with: " ")  // ensure we have only 1 space
    207             }
    208         }
    209         let currency = formatter.currency
    210         if !currency.isEmpty {
    211             let spacedName = formatter.leadingCurrencySymbol ? currency + SPACE
    212                                                              : SPACE + currency
    213             let spaced = replacingCurrencyMarkers(in: aString, with: spacedName)
    214             return spaced.replacingOccurrences(of: "  ", with: " ")  // ensure we have only 1 space
    215         }
    216         return aString
    217     }
    218 
    219     // TODO: use valueAsDecimalTuple instead of valueAsFloatTuple
    220     func string(for valueTuple: (Double, Double), isNegative: Bool, currency: String,
    221                         useISO: Bool = false, a11yDecSep: String? = nil) -> String {
    222         formatter.setUseISO(useISO)
    223         let (integer, fraction) = valueTuple
    224         if let integerStr = formatter.string(for: isNegative ? -integer : integer) {
    225             let integerSpaced = integerStr.spaced
    226             if fraction == 0 {
    227                 return currencyString(integerSpaced, useISO: useISO)   // formatter already added trailing zeroes
    228             }
    229             if let fractionStr = formatter.string(for: fraction) {
    230                 let fractionSpaced = fractionStr.spaced
    231                 if let decimalSeparator = formatter.currencyDecimalSeparator {
    232                     if let fractionIndex = fractionSpaced.endIndex(of: decimalSeparator) {
    233                         var fractionPartStr = String(fractionSpaced[fractionIndex...])
    234                         var resultStr = integerPartStr(integerSpaced, decimalSeparator: decimalSeparator)
    235                         if !resultStr.contains(decimalSeparator) {
    236                             resultStr += decimalSeparator
    237                         }
    238 //            print(resultStr, fractionPartStr)
    239                         var fractionCnt = 1
    240                         for character in fractionPartStr {
    241                             let isSuper = fractionCnt > specs.fractionalNormalDigits
    242                             let charStr = String(character)
    243                             if let digit = Int(charStr) {
    244                                 let digitStr = isSuper ? SuperScriptDigits(charStr) : charStr
    245                                 resultStr += digitStr
    246                                 if (fractionCnt > 0) { fractionCnt += 1 }
    247                             } else {
    248                                 // probably the Currency Code or Symbol. Just pass it on...
    249                                 resultStr += charStr
    250                                 // make sure any following digits (part of the currency name) are not converted to SuperScript
    251                                 fractionCnt = 0
    252                             }
    253                         }
    254 //            print(resultStr)
    255                         if let a11yDecSep {
    256                             resultStr = resultStr.replacingOccurrences(of: decimalSeparator, with: a11yDecSep)
    257                         }
    258                         return currencyString(resultStr, useISO: useISO)
    259                     }
    260                     // if we arrive here then fractionStr doesn't have a decimal separator. Yikes!
    261                 }
    262                 // if we arrive here then the formatter doesn't have a currencyDecimalSeparator
    263             }
    264             // if we arrive here then we do not get a formatted string for fractionStr. Yikes!
    265         }
    266         // if we arrive here then we do not get a formatted string for integerStr. Yikes!
    267         // TODO: log.error(formatter doesn't work)
    268         // we need to format ourselves
    269 //        var currencyName = scope.currency
    270         var currencyName = currency
    271         if !useISO {
    272             if let altUnitName0 {
    273                 currencyName = altUnitName0
    274             }
    275         }
    276         var madeUpStr = currencyName + (isNegative ? " -" + String(integer)
    277                                                    : " " + String(integer))
    278 //        let homeCurrency = Locale.current.currency      //'currency' is only available in iOS 16 or newer
    279         madeUpStr += formatter.currencyDecimalSeparator ?? Locale.current.decimalSeparator ?? "."
    280         // String(fraction) can be "0.5" (its own '.' would double up the separator we just
    281         // appended) or scientific notation for tiny values (e.g. "5e-08").
    282         // Format with a fixed number of digits, then drop the leading "0."
    283         let fixedFractionStr = String(format: "%.8f", fraction)
    284         madeUpStr += String(fixedFractionStr.dropFirst(2))
    285         // TODO: fractionalNormalDigits, fractionalTrailingZeroDigits
    286         return madeUpStr
    287     }
    288 }
    289 // MARK: -
    290 public struct CurrencySpecification: Codable, Equatable, Hashable, Sendable {
    291     enum CodingKeys: String, CodingKey {
    292         case name
    293         case commonAmounts = "common_amounts"
    294         case fractionalInputDigits = "num_fractional_input_digits"
    295         case fractionalNormalDigits = "num_fractional_normal_digits"
    296         case fractionalTrailingZeroDigits = "num_fractional_trailing_zero_digits"
    297         case altUnitNames = "alt_unit_names"
    298     }
    299     /// some name for this CurrencySpecification
    300     let name: String
    301     let commonAmounts: [Amount]?
    302     /// how much digits the user may enter after the decimal separator
    303     let fractionalInputDigits: Int
    304     /// €,$,£: 2;  some arabic currencies: 3,  ¥: 0
    305     let fractionalNormalDigits: Int
    306     /// usually same as numFractionalNormalDigits, but e.g. might be 2 for ¥
    307     let fractionalTrailingZeroDigits: Int
    308     /// map of powers of 10 to alternative currency names / symbols
    309     /// must always have an entry under "0" that defines the base name
    310     /// e.g.  "0 => €" or "3 => k€". For BTC, would be "0 => BTC, -3 => mBTC".
    311     /// This way, we can also communicate the currency symbol to be used.
    312     let altUnitNames: [Int : String]?
    313 }
    314 // MARK: -
    315 /// `name` and `altUnitNames` come from the exchange's /keys response and are rendered
    316 /// verbatim into nav titles and accessibility labels on money-movement screens, so strip
    317 /// Unicode formatting control characters (bidi overrides, isolates, zero-width joiners):
    318 /// a malicious or misconfigured exchange must not be able to reorder what the user reads.
    319 ///
    320 /// This lives in an extension on purpose. A custom `init(from:)` written inside the struct's
    321 /// own declaration would suppress the synthesized memberwise initializer, which
    322 /// `CurrencyInfo.zero(_:nu:)` and three other call sites in this file rely on.
    323 extension CurrencySpecification {
    324     private static func sanitized(_ text: String) -> String {
    325         String(String.UnicodeScalarView(text.unicodeScalars.filter {
    326             $0.properties.generalCategory != .format
    327         }))
    328     }
    329 
    330     public init(from decoder: Decoder) throws {
    331         let container = try decoder.container(keyedBy: CodingKeys.self)
    332         name = Self.sanitized(try container.decode(String.self, forKey: .name))
    333         commonAmounts = try container.decodeIfPresent([Amount].self, forKey: .commonAmounts)
    334         fractionalInputDigits = try container.decode(Int.self, forKey: .fractionalInputDigits)
    335         fractionalNormalDigits = try container.decode(Int.self, forKey: .fractionalNormalDigits)
    336         fractionalTrailingZeroDigits = try container.decode(Int.self, forKey: .fractionalTrailingZeroDigits)
    337         if let rawAltUnitNames = try container.decodeIfPresent([Int : String].self, forKey: .altUnitNames) {
    338             altUnitNames = rawAltUnitNames.mapValues(Self.sanitized)
    339         } else {
    340             altUnitNames = nil
    341         }
    342     }
    343 }
    344 // MARK: -
    345 public class CurrencyFormatter: NumberFormatter, @unchecked Sendable {
    346 
    347     var name: String?
    348     var altUnitName0: String?           // specs.altUnitNames[0] should have either the name
    349     var altUnitSymbol: String?          // specs.altUnitNames[0] should have the Symbol ($,€,¥)
    350     var currency: String
    351     var leadingCurrencySymbol: Bool
    352     /// factory
    353 
    354     static func formatter(currency: String, specs: CurrencySpecification) -> CurrencyFormatter {
    355         let formatter = CurrencyFormatter()
    356         if let altUnitNameZero = specs.altUnitNames?[0] {
    357             if altUnitNameZero.hasPrefix(SPACE) {
    358                 formatter.altUnitName0 = String(altUnitNameZero.dropFirst())
    359             } else {
    360                 formatter.altUnitSymbol = altUnitNameZero
    361             }
    362         }
    363         formatter.name = specs.name
    364         formatter.currency = currency
    365         if (formatter.currencyCode as String?)?.isEmpty ?? true, !currency.isEmpty {
    366             formatter.currencyCode = currency
    367         }
    368 //        formatter.setCode(to: EUR_4217)
    369 //        formatter.setSymbol(to: "€")
    370         // clamp: specs comes from the exchange and is untrusted; an out-of-range or negative
    371         // value here would make NumberFormatter try to render millions of fractional digits
    372         let trailingZeroDigits = min(max(specs.fractionalTrailingZeroDigits, 0), 8)
    373         formatter.setMinimumFractionDigits(trailingZeroDigits)
    374         return formatter
    375     }
    376 
    377     public override init() {
    378         self.name = nil
    379         self.altUnitName0 = nil
    380         self.altUnitSymbol = nil
    381         self.currency = EMPTYSTRING
    382         self.leadingCurrencySymbol = false
    383         super.init()
    384 //        self.currencyCode = EUR_4217
    385 //        self.currencySymbol = "€"
    386         self.locale = Locale.autoupdatingCurrent                                // TODO: Yikes, might override my currency! Needs testing!
    387         if #available(iOS 16.4, *) {
    388             let currency = self.locale.currency
    389             if let currencyCode = currency?.identifier {
    390                 self.name = self.locale.localizedString(forCurrencyCode: currencyCode)
    391             }
    392         } else {
    393             if let currencyCode = self.locale.currencyCode {
    394                 self.name = self.locale.localizedString(forCurrencyCode: currencyCode)
    395             }
    396         }
    397         self.usesGroupingSeparator = true
    398         self.numberStyle = .currencyISOCode         // .currency
    399         self.maximumFractionDigits = 8              // ensure that formatter will not round
    400 
    401 //        self.currencyCode = code              // EUR, USD, JPY, GBP
    402 //        self.currencySymbol = symbol
    403 //        self.internationalCurrencySymbol =
    404 //        self.minimumFractionDigits = fractionDigits
    405 //        self.maximumFractionDigits = fractionDigits
    406 //        self.groupingSize = 3                 // thousands
    407 //        self.groupingSeparator = ","
    408 //        self.decimalSeparator = "."
    409         let positiveFormat = self.positiveFormat as NSString
    410         let currencySymbolLocation = positiveFormat.range(of: "¤").location
    411         self.leadingCurrencySymbol = currencySymbolLocation == 0
    412     }
    413 
    414     func setUseISO(_ useISO: Bool) {
    415         numberStyle = useISO ? .currencyISOCode : .currency     // currencyPlural or currencyAccounting
    416     }
    417 
    418 //    func setCode(to code:String) {
    419 //        currencyCode = code
    420 //    }
    421 
    422 //    func setSymbol(to symbol:String) {
    423 //        currencySymbol = symbol
    424 //    }
    425 
    426     func setMinimumFractionDigits(_ digits: Int) {
    427         minimumFractionDigits = digits
    428     }
    429 
    430     func setLocale(to newLocale: String) {
    431         locale = Locale(identifier: newLocale)
    432         maximumFractionDigits = 8               // ensure that formatter will not round
    433 //        NumberFormatter.RoundingMode
    434     }
    435 
    436     @available(*, unavailable)
    437     required init?(coder aDecoder: NSCoder) {
    438         fatalError("init(coder:) has not been implemented")
    439     }
    440 }
    441 // MARK: -
    442 #if DEBUG
    443 func PreviewCurrencyInfo(_ currency: String, digits: Int) -> CurrencyInfo {
    444     let unitName = digits == 0 ? "テ" : "ク"  // do not use real currency symbols like "¥" : "€"
    445     let specs = CurrencySpecification(name: currency,
    446                              commonAmounts: nil,
    447                      fractionalInputDigits: digits,
    448                     fractionalNormalDigits: digits,
    449               fractionalTrailingZeroDigits: digits,
    450                               altUnitNames: [0 : unitName])
    451     let previewFormatter = CurrencyFormatter.formatter(currency: currency, specs: specs)
    452     return CurrencyInfo(specs: specs, formatter: previewFormatter)
    453 }
    454 #endif