-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebugScan.swift
More file actions
223 lines (205 loc) · 8.48 KB
/
DebugScan.swift
File metadata and controls
223 lines (205 loc) · 8.48 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import Foundation
import OSLog
import SwiftUI
private let logger = Logger(subsystem: "com.swift.ui.debug.scan", category: "SwiftUI")
private let processInfo = ProcessInfo.processInfo
private let isVerbose: Bool = {
guard let value = processInfo.environment["SWIFTUI_DEBUG_SCAN_VERBOSE"]?.lowercased() else {
return false
}
return ["1", "true", "yes"].contains(value)
}()
#if DEBUG
@_silgen_name("swift_demangle")
private func swift_demangle(
mangledName: UnsafePointer<CChar>?,
mangledNameLength: UInt,
outputBuffer: UnsafeMutablePointer<CChar>?,
outputBufferSize: UnsafeMutablePointer<UInt>?,
flags: UInt32
) -> UnsafeMutablePointer<CChar>?
internal extension String {
var demangled: String? {
utf8CString.withUnsafeBufferPointer {
guard let ptr = swift_demangle(
mangledName: $0.baseAddress,
mangledNameLength: UInt($0.count - 1),
outputBuffer: nil,
outputBufferSize: nil,
flags: 0
)
else { return nil }
defer { free(ptr) }
return String(cString: ptr)
}
}
}
internal extension TaskPriority {
var label: String {
switch self.rawValue {
case 9: "background"
case 17: "utility"
case 21: "default"
case 25: "userInitiated"
case 33: "userInteractive"
case 0: "unspecified"
default: "❓ unknown (\(rawValue))"
}
}
}
#endif
func __dumpSUIDebugInfo() {
#if DEBUG
let initialUptime = processInfo.systemUptime
var lastThreadInfo = "N/A", lastStackSize = "N/A", lastTaskPriority = "N/A"
let callStack = Thread.callStackSymbols
for (idx, symbol) in zip(callStack.indices, callStack) {
let mangled = symbol.utf8.drop { $0 != UInt8(ascii: "$") }.prefix { $0 != UInt8(ascii: " ") }
guard
mangled.starts(with: "$s7SwiftUI".utf8),
let demangled = String(Substring(mangled)).demangled
else {
continue
}
let elapsed = (processInfo.systemUptime - initialUptime) * 1000
let frameNumber = String(format: "%02d", idx + 1)
let threadID = if Thread.isMainThread {
"main"
} else {
(Thread.current.name?.isEmpty == true ? "\(Thread.current.description)" : Thread.current.name) ?? "unknown"
}
logger.debug("""
🧩 Stack #\(frameNumber)
• 🧵 threadID: \(threadID)
• ⏱️ elapsed: \(String(format: "%.3f", elapsed)) ms
• ⒡ function: \(demangled)
"""
)
lastThreadInfo = Thread.isMainThread ? "main" : String(reflecting: Thread.current)
lastStackSize = ByteCountFormatter().string(for: Thread.current.stackSize)!
lastTaskPriority = Task.currentPriority.label
}
let osThreadInfo = """
💻 OS
• 🧵 thread: \(lastThreadInfo)
• 💾 stack size: \(lastStackSize)
• 🚦 priority: \(lastTaskPriority)
• ⚙️ processors: \(processInfo.activeProcessorCount) (Active) / \(processInfo.processorCount) (Total)
• 📦 memory: \(ByteCountFormatter().string(fromByteCount: Int64(processInfo.physicalMemory)))
• ⬆️ uptime: \(String(format: "%.3f", processInfo.systemUptime / 3600)) hours
"""
logger.debug("\(osThreadInfo)")
#endif
}
internal actor RenderState: ObservableObject {
private var renderCount = 0
func record() -> Int {
renderCount += 1
return renderCount
}
}
struct ViewInstrumentationModifier: ViewModifier {
@StateObject private var renderState = RenderState()
var label: String
var file: String
var filePath: String
var module: String
private var fileForDisplay: String {
isVerbose ? "open \(filePath)" : file
}
init(label: String, file: StaticString, fileID: StaticString, filePath: StaticString) {
self.label = label
self.filePath = "\(filePath)"
self.file = "\(file)".components(separatedBy: "/").last ?? "unknown.swift"
self.module = "\(fileID)".components(separatedBy: "/").first ?? "unknown"
if isVerbose {
__dumpSUIDebugInfo()
}
}
@ViewBuilder
func body(content: Content) -> some View {
content
.task {
let count = await renderState.record()
logger.debug("""
🧩 [\(label)]
• 📂 file: \(fileForDisplay)
• 📚 module: \(module)
• 🎨 redraws: \(count)
• ⏱️ timestamp: \(Date())
"""
)
}
}
}
public extension View {
/// Adds a debug instrumentation modifier to the view for logging and tracking render information.
///
/// Use this modifier to gain insights into the rendering behavior of your SwiftUI views. It logs details such as
/// the file, module, redraw count, and timestamp for each render pass. This can be particularly useful for debugging
/// and discoverability analysis during development.
///
/// - Important: For the best logging experience, it is recommended to apply this modifier to **root views**
/// (e.g., the top-level view in your view hierarchy) rather than leaf views. Applying it to root views ensures
/// that you capture the most meaningful and comprehensive debug information.
///
/// - Parameters:
/// - label: A descriptive label for the view being debugged. This label will appear in the logs to help identify the view.
/// - file: The file where the view is defined. Defaults to the current file (`#file`).
/// - fileID: The file ID where the view is defined. Defaults to the current file ID (`#fileID`).
/// - filePath: The full file path where the view is defined. Defaults to the current file path (`#filePath`).
///
/// - Returns: A modified view with debug instrumentation applied.
///
/// - SeeAlso: `debugScan(_:file:fileID:filePath:)` for the type-based variant that automatically derives labels from view types.
func debugScan(
_ label: String,
file: StaticString = #file,
fileID: StaticString = #fileID,
filePath: StaticString = #filePath
) -> some View {
modifier(
ViewInstrumentationModifier(
label: label,
file: file,
fileID: fileID,
filePath: filePath
)
)
}
/// Adds a debug instrumentation modifier to the view for logging and tracking render information using type-based labeling.
///
/// This type-safe variant of `debugScan` derives the debug label from the specified view type, providing
/// a more robust and refactor-friendly approach to view debugging. The modifier logs details such as the file,
/// module, redraw count, and timestamp for each render pass, using the view's type name as the identifier.
///
/// - Important: For the best logging experience, it is recommended to apply this modifier to **root views**
/// (e.g., the top-level view in your view hierarchy) rather than leaf views. Applying it to root views ensures
/// that you capture the most meaningful and comprehensive debug information.
///
/// - Parameters:
/// - label: The type to use for generating the debug label. The label will be generated using `String(describing: label)`.
/// Pass the view's type (e.g., `Text.self`, `MyCustomView.self`) to get meaningful debug labels.
/// - file: The file where the view is defined. Defaults to the current file (`#file`).
/// - fileID: The file ID where the view is defined. Defaults to the current file ID (`#fileID`).
/// - filePath: The full file path where the view is defined. Defaults to the current file path (`#filePath`).
///
/// - Returns: A modified view with debug instrumentation applied, using the type-derived label.
///
/// - SeeAlso: `debugScan(_:file:fileID:filePath:)` for the string-based variant that allows custom labels.
func debugScan(
_ label: (some View).Type,
file: StaticString = #file,
fileID: StaticString = #fileID,
filePath: StaticString = #filePath
) -> some View {
modifier(
ViewInstrumentationModifier(
label: String(describing: label),
file: file,
fileID: fileID,
filePath: filePath
)
)
}
}