/
DefaultRenderer.swift
93 lines (84 loc) · 2.66 KB
/
DefaultRenderer.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Foundation
extension Graphics {
public static var bestAvailableRenderer: Renderer {
#if os(macOS)
return CocoaRenderer()
#elseif os(iOS) || os(watchOS) || os(tvOS)
return UIKitRenderer()
#else
return DefaultRenderer()
#endif
}
}
// A fallback renderer when we don't have an actual graphics system, only
// supporting SVG and JSON output.
//
// This substitutes every font with *Courier New* and measures strings using
// hardwired metrics, assuming there is a one-to-one mapping between characters
// and glyphs.
public struct DefaultRenderer: Renderer {
public func resolve(_ font: Font) -> Font {
var substitute = font
substitute.family = "Courier New"
return substitute
}
public func measure(
_ font: Font,
_ text: String
) -> (width: Double, height: Double, descender: Double) {
let unitAdvancement = Vector(dx: 0.60009765625, dy: 1.1328125)
let unitDescender = 0.30029296875
let width = Double(text.count) * font.size * unitAdvancement.dx
let height = font.size * unitAdvancement.dy
let descender = unitDescender * font.size
return (
width: width.rounded(.up),
height: height.rounded(.up),
descender: descender)
}
public var supportedImageFormats: [ImageFormat] { [.json, .svg, .html] }
public var defaultImageFormat: ImageFormat { .svg }
public func render(
_ graphics: Graphics,
format: String,
bitmapScale: Double
) throws -> Data {
switch format.lowercased() {
case "json":
let encoder = JSONEncoder()
return try encoder.encode(graphics)
case "svg":
let text = graphics.svgString()
return text.data(using: .utf8)!
case "html":
let text = graphics.htmlString()
return text.data(using: .utf8)!
default:
throw Benchmark.Error(
"Can't generate output for unknown file format '\(format)'")
}
}
public func documentRenderer(
title: String,
format: ImageFormat,
style: DocumentStyle
) throws -> DocumentRenderer {
switch format {
case .html:
return HTMLDocumentRenderer(title: title, style: style, lang: "en")
default:
throw Benchmark.Error(
"Can't generate output for unknown file format '\(format)'")
}
}
}