forked from qodo-benchmark/firefox-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadToast.swift
More file actions
261 lines (211 loc) · 10.4 KB
/
DownloadToast.swift
File metadata and controls
261 lines (211 loc) · 10.4 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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Common
import Shared
import UIKit
class DownloadToast: Toast, DownloadProgressDelegate {
lazy var progressView: UIView = .build { view in
view.layer.cornerRadius = Toast.UX.toastCornerRadius
}
private var contentStackView: UIStackView = .build { stackView in
stackView.spacing = ButtonToast.UX.stackViewSpacing
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
}
private var imageView: UIImageView = .build { imageView in
imageView.image = UIImage.templateImageNamed(StandardImageIdentifiers.Large.download)
}
private var labelStackView: UIStackView = .build { stackView in
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .leading
}
private var titleLabel: UILabel = .build { label in
label.font = FXFontStyles.Regular.subheadline.scaledFont()
label.numberOfLines = 0
}
private var descriptionLabel: UILabel = .build { label in
label.font = FXFontStyles.Regular.footnote.scaledFont()
label.numberOfLines = 0
}
private lazy var closeButton: UIButton = .build { button in
button.setImage(UIImage.templateImageNamed(StandardImageIdentifiers.Medium.cross), for: [])
button.addTarget(self, action: #selector(self.buttonPressed), for: .touchUpInside)
}
var progressWidthConstraint: NSLayoutConstraint?
var downloadProgressManager: DownloadProgressManager
// Returns true if one or more downloads have encoded data (indicated via response `Content-Encoding` header).
// If at least one download has encoded data, we cannot get a correct total estimate for all the downloads.
// In that case, we do not show descriptive text. This will be improved in a later rework of the download manager.
// FXIOS-9039
var hasContentEncoding: Bool {
return downloadProgressManager.downloads.contains(where: { $0.hasContentEncoding ?? false })
}
var percent: CGFloat? = 0.0 {
didSet {
UIView.animate(withDuration: 0.05) {
self.descriptionLabel.text = self.descriptionText
if let percent = self.percent {
self.progressView.isHidden = false
self.progressWidthConstraint?.constant = self.toastView.frame.width * percent
} else {
self.progressView.isHidden = true
}
self.layoutIfNeeded()
}
}
}
var descriptionText: String {
guard !hasContentEncoding else {
// We cannot get a correct estimate of encoded downloaded bytes (FXIOS-9039)
return String()
}
let downloadedSize = ByteCountFormatter.string(
fromByteCount: downloadProgressManager.combinedBytesDownloaded,
countStyle: .file
)
let expectedSize = downloadProgressManager.combinedTotalBytesExpected != nil ? ByteCountFormatter.string(
fromByteCount: downloadProgressManager.combinedTotalBytesExpected!,
countStyle: .file
) : nil
let descriptionText = expectedSize != nil ? String(
format: .DownloadProgressToastDescriptionText,
downloadedSize,
expectedSize!
) : downloadedSize
guard downloadProgressManager.downloads.count > 1 else {
return descriptionText
}
let fileCountDescription = String(format: .DownloadMultipleFilesToastDescriptionText,
downloadProgressManager.downloads.count)
return String(
format: .DownloadMultipleFilesAndProgressToastDescriptionText,
fileCountDescription,
descriptionText
)
}
init(
downloadProgressManager: DownloadProgressManager,
theme: Theme,
completion: @MainActor @escaping (Bool) -> Void
) {
self.downloadProgressManager = downloadProgressManager
super.init(frame: .zero)
self.completionHandler = completion
self.clipsToBounds = true
let download = downloadProgressManager.downloads[0]
updatePercent()
self.addSubview(createView(download.filename, descriptionText: self.descriptionText))
NSLayoutConstraint.activate([
toastView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Toast.UX.shadowVerticalSpacing),
toastView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Toast.UX.shadowVerticalSpacing),
toastView.heightAnchor.constraint(equalTo: heightAnchor, constant: -Toast.UX.shadowHorizontalSpacing),
heightAnchor.constraint(greaterThanOrEqualToConstant: Toast.UX.toastHeightWithShadow)
])
animationConstraint = toastView.topAnchor.constraint(greaterThanOrEqualTo: topAnchor,
constant: Toast.UX.toastHeightWithShadow)
animationConstraint?.isActive = true
applyTheme(theme: theme)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updatePercent() {
DispatchQueue.main.async {
guard !self.hasContentEncoding else {
// We cannot get a correct estimate of encoded downloaded bytes (FXIOS-9039)
self.percent = nil
return
}
guard let combinedTotalBytesExpected = self.downloadProgressManager.combinedTotalBytesExpected else {
self.percent = 0.0
return
}
let combinedBytesDownloaded = self.downloadProgressManager.combinedBytesDownloaded
self.percent = CGFloat(combinedBytesDownloaded) / CGFloat(combinedTotalBytesExpected)
}
}
func createView(_ labelText: String, descriptionText: String) -> UIView {
contentStackView.addArrangedSubview(imageView)
titleLabel.text = labelText
descriptionLabel.text = descriptionText
labelStackView.addArrangedSubview(titleLabel)
labelStackView.addArrangedSubview(descriptionLabel)
contentStackView.addArrangedSubview(labelStackView)
contentStackView.addArrangedSubview(closeButton)
toastView.addSubview(progressView)
toastView.addSubview(contentStackView)
NSLayoutConstraint.activate(
[
progressView.leadingAnchor.constraint(equalTo: toastView.leadingAnchor),
progressView.centerYAnchor.constraint(equalTo: toastView.centerYAnchor),
progressView.heightAnchor.constraint(equalTo: toastView.heightAnchor),
contentStackView.leadingAnchor.constraint(equalTo: toastView.leadingAnchor,
constant: ButtonToast.UX.spacing),
contentStackView.trailingAnchor.constraint(equalTo: toastView.trailingAnchor,
constant: -ButtonToast.UX.spacing),
contentStackView.bottomAnchor.constraint(equalTo: toastView.bottomAnchor,
constant: -ButtonToast.UX.spacing),
contentStackView.topAnchor.constraint(equalTo: toastView.topAnchor,
constant: ButtonToast.UX.spacing),
closeButton.heightAnchor.constraint(equalToConstant: 40),
closeButton.widthAnchor.constraint(equalToConstant: 40),
]
)
progressWidthConstraint = progressView.widthAnchor.constraint(equalToConstant: 0)
progressWidthConstraint?.isActive = true
return toastView
}
@objc
func buttonPressed(_ gestureRecognizer: UIGestureRecognizer) {
let alert = AlertController(title: .CancelDownloadDialogTitle,
message: .CancelDownloadDialogMessage,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: .CancelDownloadDialogResume, style: .cancel, handler: nil),
accessibilityIdentifier: AccessibilityIdentifiers.Alert.cancelDownloadResume)
alert.addAction(UIAlertAction(title: .CancelDownloadDialogCancel,
style: .default,
handler: { action in
self.completionHandler?(true)
self.dismiss(true)
TelemetryWrapper.recordEvent(category: .action, method: .cancel, object: .download)
}), accessibilityIdentifier: AccessibilityIdentifiers.Alert.cancelDownloadCancel)
viewController?.present(alert, animated: true, completion: nil)
}
override func applyTheme(theme: Theme) {
super.applyTheme(theme: theme)
titleLabel.textColor = theme.colors.textInverted
descriptionLabel.textColor = theme.colors.textInverted
imageView.tintColor = theme.colors.textInverted
closeButton.tintColor = theme.colors.textInverted
progressView.backgroundColor = theme.colors.actionPrimaryHover
}
override func adjustLayoutForA11ySizeCategory() {
let contentSizeCategory = UIApplication.shared.preferredContentSizeCategory
if contentSizeCategory.isAccessibilityCategory {
// Description label changes with progress and if this isn't clipped the height of the
// toast changes continually while loading
descriptionLabel.numberOfLines = 1
descriptionLabel.lineBreakMode = .byTruncatingTail
} else {
descriptionLabel.numberOfLines = 0
descriptionLabel.lineBreakMode = .byWordWrapping
}
setNeedsLayout()
}
override func handleTap(_ gestureRecognizer: UIGestureRecognizer) {
// Intentional NOOP to override superclass behaviour for dismissing the toast.
}
override func dismiss(_ buttonPressed: Bool) {
// Delay toast dismiss to handle download of small files
// where the toast is presented and dismiss right away
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
super.dismiss(buttonPressed)
}
}
func updateCombinedBytesDownloaded(value: Int64) {
updatePercent()
}
}