-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSNTMessageView.swift
More file actions
428 lines (369 loc) · 12.6 KB
/
Copy pathSNTMessageView.swift
File metadata and controls
428 lines (369 loc) · 12.6 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/// Copyright 2024 North Pole Security, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
import SwiftUI
import santa_common_SNTConfigurator
import santa_gui_SNTAuthorizationHelper
public let MAX_OUTER_VIEW_WIDTH = 560.0
public let MAX_OUTER_VIEW_HEIGHT = 340.0
extension Date {
public static var overrideDate: Date? = nil
public static func now() -> Date {
return overrideDate ?? Date()
}
}
public struct SNTMessageView<Content: View>: View {
let blockMessage: NSAttributedString?
@ViewBuilder let content: Content
let enableFunFonts: Bool = SNTConfigurator.configurator().funFontsOnSpecificDays
public init(_ blockMessage: NSAttributedString? = nil, @ViewBuilder content: () -> Content) {
self.content = content()
self.blockMessage = blockMessage
}
func SpecialDateIs(month: Int, day: Int) -> Bool {
return enableFunFonts
&& Calendar.current.dateComponents([.month, .day], from: Date.now()) == DateComponents(month: month, day: day)
}
public var body: some View {
VStack {
HStack {
let image = Image(nsImage: NSImage(named: "MessageIcon") ?? NSImage())
.resizable()
.scaledToFill()
.frame(width: 32, height: 32)
.saturation(0.9)
if SpecialDateIs(month: 4, day: 1) {
image
Text(verbatim: " Santa ").font(Font.custom("ComicSansMS", size: 34.0))
image.hidden()
} else if SpecialDateIs(month: 5, day: 4) {
// $ is the Rebel Alliance logo in the StarJedi font.
Text(verbatim: "$ Santa ").font(Font.custom("StarJedi", size: 34.0))
} else if SpecialDateIs(month: 10, day: 31) {
Text(verbatim: "🎃 Santa ").font(Font.custom("HelveticaNeue-UltraLight", size: 34.0))
} else {
image
Text(verbatim: " Santa ").font(Font.custom("HelveticaNeue-UltraLight", size: 34.0))
image.hidden()
}
}
}.fixedSize()
VStack(spacing: 10.0) {
if let blockMessage = blockMessage {
AttributedText(blockMessage)
.multilineTextAlignment(.center)
.padding([.leading, .trailing], 15.0)
.fixedSize(horizontal: false, vertical: true)
}
Spacer()
content
}
.padding([.leading, .trailing], 40.0)
.frame(maxWidth: MAX_OUTER_VIEW_WIDTH)
SNTBrandingView()
.frame(maxWidth: MAX_OUTER_VIEW_WIDTH)
}
}
// Special struct to help ensure an image is appropriately sized and
// the bounding box is appropriately limited to the final image size.
struct ConstrainedImage: View {
let image: NSImage
let maxWidth: CGFloat
let maxHeight: CGFloat
private var constrainedSize: (width: CGFloat, height: CGFloat) {
let size = image.size
let aspectRatio = size.width / size.height
if size.width / maxWidth > size.height / maxHeight {
// Width is the limiting factor
let width = min(size.width, maxWidth)
let height = width / aspectRatio
return (width, height)
} else {
// Height is the limiting factor
let height = min(size.height, maxHeight)
let width = height * aspectRatio
return (width, height)
}
}
var body: some View {
Image(nsImage: image)
.resizable()
.frame(width: constrainedSize.width, height: constrainedSize.height)
}
}
public struct SNTBrandingView: View {
let c = SNTConfigurator.configurator()
@Environment(\.colorScheme) var colorScheme
@ViewBuilder
private var brandingContent: some View {
// Select the appropriate logo based on color scheme
let logoImage: NSImage? = {
if colorScheme == .dark, let url = c.brandingCompanyLogoDark {
return NSImage(contentsOf: url)
} else if let url = c.brandingCompanyLogo {
return NSImage(contentsOf: url)
}
return nil
}()
if let nsi = logoImage {
ConstrainedImage(image: nsi, maxWidth: 84.0, maxHeight: 28.0)
} else if let companyName = c.brandingCompanyName {
TextWithLimit(companyName).font(.footnote).fontWeight(.bold).fixedSize()
}
}
public var body: some View {
if c.brandingCompanyLogoDark != nil || c.brandingCompanyLogo != nil || c.brandingCompanyName != nil {
HStack {
Spacer()
VStack(spacing: 4.0) {
Text("Managed by:", comment: "Label shown before company branding").font(.footnote).fixedSize()
brandingContent
}
Spacer()
}
.padding(.top, 10.0)
.padding(.bottom, 28.0)
} else {
Spacer()
.frame(height: 28.0)
}
}
}
public let NotificationSilencePeriods: [TimeInterval] = [86400, 604800, 2_678_400]
public struct SNTNotificationSilenceView: View {
@Binding var silence: Bool
@Binding var period: TimeInterval
let dateFormatter: DateComponentsFormatter = {
let df = DateComponentsFormatter()
df.unitsStyle = .spellOut
df.allowedUnits = [.day, .month, .weekOfMonth]
return df
}()
public init(silence: Binding<Bool>, period: Binding<TimeInterval>) {
_silence = silence
_period = period
}
public var body: some View {
// Create a wrapper binding around $preventFutureNotificationsPeriod so that we can automatically
// check the checkbox if the user has selected a new period.
let pi = Binding<TimeInterval>(
get: { return period },
set: {
silence = true
period = $0
}
)
Toggle(isOn: $silence) {
HStack(spacing: 5.0) {
Text("Label before time period picker").font(Font.system(size: 11.0))
Picker("", selection: pi) {
ForEach(NotificationSilencePeriods, id: \.self) { period in
let text = dateFormatter.string(from: period) ?? "unknown"
Text(text).font(Font.system(size: 11.0))
}
}.fixedSize()
Text("Label after time period picker").font(Font.system(size: 11.0))
}
}
}
}
public struct ScalingButtonStyle: ButtonStyle {
public init() {}
public func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.cornerRadius(40)
.scaleEffect(configuration.isPressed ? 0.8 : 0.9)
}
}
public func MoreDetailsButton(_ showDetails: Binding<Bool>) -> some View {
Button(action: { showDetails.wrappedValue = true }) {
HStack(spacing: 2.0) {
Text("More Details", comment: "More Details button").foregroundColor(.blue)
Image(systemName: "info.circle").foregroundColor(.blue)
}
}
.buttonStyle(ScalingButtonStyle())
.keyboardShortcut("m", modifiers: .command)
.help("⌘ m")
}
public func OpenEventButton(
customText: String? = nil,
disabled: Bool? = false,
action: @escaping () -> Void
) -> some View {
Button(
action: action,
label: {
let t = customText ?? NSLocalizedString("Open...", comment: "Default text for Open button")
Text(t).frame(maxWidth: 200.0)
}
)
.disabled(disabled ?? false)
.keyboardShortcut(.return, modifiers: .command)
.help("⌘ Return")
}
public struct CopyDetailsButton: View {
let action: () -> Void
@State private var showCopyConfirmation = false
public init(action: @escaping () -> Void) {
self.action = action
}
public var body: some View {
Button(action: {
action()
withAnimation {
showCopyConfirmation = true
}
// Hide after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
withAnimation {
showCopyConfirmation = false
}
}
}) {
HStack(spacing: 2.0) {
Text("Copy Details", comment: "Copy Details")
.foregroundColor(.blue)
Image(systemName: "pencil.and.list.clipboard")
.foregroundColor(.blue)
// Reserve space for the checkmark to maintain consistent width
ZStack {
// Invisible placeholder with the same size as the checkmark
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.clear)
// Actual checkmark that appears and fades
if showCopyConfirmation {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.blue)
.transition(.opacity)
}
}
}
}
.buttonStyle(ScalingButtonStyle())
.keyboardShortcut("c", modifiers: [.command, .shift])
.help("⇧ ⌘ c")
}
}
// CanAuthorizeWithTouchID checks if TouchID is available on the current device
// and returns an error if it is not.
public func CanAuthorizeWithTouchID() -> (Bool, NSError?) {
do {
try SNTAuthorizationHelper.canAuthorizeWithTouchID()
return (true, nil)
} catch let error as NSError {
return (false, error)
}
}
// StandaloneButton is only used in Standalone mode. It's a replacement for the
// Open event button.
//
// It is intended to be used for all approvals in the future if in standalone
// mode.
public func StandaloneButton(action: @escaping () -> Void) -> some View {
Button(
action: action,
label: {
Text(NSLocalizedString("Approve", comment: "Default text for Approve")).frame(maxWidth: 200.0)
}
)
.keyboardShortcut(.return, modifiers: .command)
.help("⌘ Return")
}
public func DismissButton(
customText: String? = nil,
silence: Bool?,
action: @escaping () -> Void
)
-> some View
{
Button(
action: action,
label: {
let t =
customText
?? (silence ?? false
? NSLocalizedString("Dismiss & Silence", comment: "")
: NSLocalizedString("Dismiss", comment: ""))
Text(t).frame(maxWidth: 200.0)
}
)
.keyboardShortcut("w", modifiers: .command)
.help("⌘ W")
}
// TextWithLimit is like Text() but it supports a limit on the number of characters in the
// string before truncating with an ellipsis. Text() technically handles this by setting
// lineLimit(1) and a maxWidth on frame but if the text is selectable, when selected it
// will expand out of the limits of the frame right up to the edge of the window.
public struct TextWithLimit: View {
private var text: String
private var limit: Int
public init(_ text: String, _ limit: Int = 50) {
self.text = text
self.limit = limit
}
public var body: some View {
if self.text.count > self.limit {
let truncatedText = "\(self.text.prefix(self.limit/2))…\(self.text.suffix(self.limit/2))"
Text(verbatim: truncatedText).help(self.text)
} else {
Text(self.text)
}
}
}
// AttributedText is like Text() but it supports all the features of NSAttributedString()
// by using NSTextField under the hood.
struct AttributedText: NSViewRepresentable {
private let attributedString: NSAttributedString
init(_ attributedString: NSAttributedString) {
self.attributedString = attributedString
}
func makeNSView(context: Context) -> TextFieldWithCursors {
TextFieldWithCursors(labelWithAttributedString: self.attributedString)
}
func updateNSView(_ textView: TextFieldWithCursors, context: Context) {
textView.maximumNumberOfLines = 15
textView.translatesAutoresizingMaskIntoConstraints = false
textView.allowsEditingTextAttributes = true
textView.isSelectable = true
textView.isEditable = false
}
}
class TextFieldWithCursors: NSTextField {
override func resetCursorRects() {
super.resetCursorRects()
let attributedString = self.attributedStringValue
attributedString.enumerateAttribute(
.link,
in: NSRange(location: 0, length: attributedString.length),
options: [],
using: { value, range, stop in
if value != nil {
let textStorage = NSTextStorage(attributedString: attributedString)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: bounds.size)
textContainer.lineFragmentPadding = 0.0
layoutManager.addTextContainer(textContainer)
var glyphRange = NSRange()
// Convert the range for glyphs.
layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)
let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
// Set the cursor to a pointing hand where this link is.
addCursorRect(rect, cursor: NSCursor.pointingHand)
}
}
)
}
}