-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathPhotonActionSheetProtocol.swift
353 lines (298 loc) · 19.1 KB
/
PhotonActionSheetProtocol.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
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
/* 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 Foundation
import Shared
import Storage
import Deferred
protocol PhotonActionSheetProtocol {
var tabManager: TabManager { get }
var profile: Profile { get }
}
private let log = Logger.browserLogger
extension PhotonActionSheetProtocol {
typealias PresentableVC = UIViewController & UIPopoverPresentationControllerDelegate
typealias MenuAction = () -> Void
typealias IsPrivateTab = Bool
typealias URLOpenAction = (URL?, IsPrivateTab) -> Void
func presentSheetWith(title: String? = nil, actions: [[PhotonActionSheetItem]], on viewController: PresentableVC, from view: UIView, supressPopover: Bool = false) {
let sheet = PhotonActionSheet(title: title, actions: actions)
sheet.modalPresentationStyle = (UIDevice.current.userInterfaceIdiom == .pad && !supressPopover) ? .popover : .overCurrentContext
sheet.photonTransitionDelegate = PhotonActionSheetAnimator()
if let popoverVC = sheet.popoverPresentationController, sheet.modalPresentationStyle == .popover {
popoverVC.delegate = viewController
popoverVC.sourceView = view
popoverVC.sourceRect = CGRect(x: view.frame.width/2, y: view.frame.size.height * 0.75, width: 1, height: 1)
popoverVC.permittedArrowDirections = .up
popoverVC.backgroundColor = UIConstants.AppBackgroundColor.withAlphaComponent(0.7)
}
viewController.present(sheet, animated: true, completion: nil)
}
//Returns a list of actions which is used to build a menu
//OpenURL is a closure that can open a given URL in some view controller. It is up to the class using the menu to know how to open it
func getHomePanelActions() -> [PhotonActionSheetItem] {
guard let tab = self.tabManager.selectedTab else { return [] }
let openTopSites = PhotonActionSheetItem(title: Strings.AppMenuTopSitesTitleString, iconString: "menu-panel-TopSites") { action in
tab.loadRequest(PrivilegedRequest(url: HomePanelType.topSites.localhostURL) as URLRequest)
}
let openBookmarks = PhotonActionSheetItem(title: Strings.AppMenuBookmarksTitleString, iconString: "menu-panel-Bookmarks") { action in
tab.loadRequest(PrivilegedRequest(url: HomePanelType.bookmarks.localhostURL) as URLRequest)
UnifiedTelemetry.recordEvent(category: .action, method: .view, object: .bookmarksPanel, value: .appMenu)
}
let openHistory = PhotonActionSheetItem(title: Strings.AppMenuHistoryTitleString, iconString: "menu-panel-History") { action in
tab.loadRequest(PrivilegedRequest(url: HomePanelType.history.localhostURL) as URLRequest)
}
let openReadingList = PhotonActionSheetItem(title: Strings.AppMenuReadingListTitleString, iconString: "menu-panel-ReadingList") { action in
tab.loadRequest(PrivilegedRequest(url: HomePanelType.readingList.localhostURL) as URLRequest)
}
let openHomePage = PhotonActionSheetItem(title: Strings.AppMenuOpenHomePageTitleString, iconString: "menu-Home") { _ in
HomePageHelper(prefs: self.profile.prefs).openHomePage(tab)
}
var actions = [openTopSites, openBookmarks, openReadingList, openHistory]
if HomePageHelper(prefs: self.profile.prefs).isHomePageAvailable {
actions.insert(openHomePage, at: 0)
}
return actions
}
/*
Returns a list of actions which is used to build the general browser menu
These items repersent global options that are presented in the menu
TODO: These icons should all have the icons and use Strings.swift
*/
typealias PageOptionsVC = QRCodeViewControllerDelegate & SettingsDelegate & PresentingModalViewControllerDelegate & UIViewController
func getOtherPanelActions(vcDelegate: PageOptionsVC) -> [PhotonActionSheetItem] {
var noImageMode: PhotonActionSheetItem? = nil
if #available(iOS 11, *) {
let noImageEnabled = NoImageModeHelper.isActivated(profile.prefs)
let noImageText = noImageEnabled ? Strings.AppMenuNoImageModeDisable : Strings.AppMenuNoImageModeEnable
noImageMode = PhotonActionSheetItem(title: noImageText, iconString: "menu-NoImageMode", isEnabled: noImageEnabled) { action in
NoImageModeHelper.toggle(profile: self.profile, tabManager: self.tabManager)
}
}
let nightModeEnabled = NightModeHelper.isActivated(profile.prefs)
let nightModeText = nightModeEnabled ? Strings.AppMenuNightModeDisable : Strings.AppMenuNightModeEnable
let nightMode = PhotonActionSheetItem(title: nightModeText, iconString: "menu-NightMode", isEnabled: nightModeEnabled) { action in
NightModeHelper.toggle(self.profile.prefs, tabManager: self.tabManager)
}
let openSettings = PhotonActionSheetItem(title: Strings.AppMenuSettingsTitleString, iconString: "menu-Settings") { action in
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = self.profile
settingsTableViewController.tabManager = self.tabManager
settingsTableViewController.settingsDelegate = vcDelegate
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = vcDelegate
controller.modalPresentationStyle = .formSheet
vcDelegate.present(controller, animated: true, completion: nil)
}
if let noImageMode = noImageMode {
return [noImageMode, nightMode, openSettings]
}
return [nightMode, openSettings]
}
func getTabActions(tab: Tab, buttonView: UIView,
presentShareMenu: @escaping (URL, Tab, UIView, UIPopoverArrowDirection) -> Void,
findInPage: @escaping () -> Void,
presentableVC: PresentableVC,
isBookmarked: Bool,
success: @escaping (String) -> Void) -> Array<[PhotonActionSheetItem]> {
let toggleActionTitle = tab.desktopSite ? Strings.AppMenuViewMobileSiteTitleString : Strings.AppMenuViewDesktopSiteTitleString
let toggleDesktopSite = PhotonActionSheetItem(title: toggleActionTitle, iconString: "menu-RequestDesktopSite") { action in
tab.toggleDesktopSite()
}
let addReadingList = PhotonActionSheetItem(title: Strings.AppMenuAddToReadingListTitleString, iconString: "addToReadingList") { action in
guard let url = tab.url?.displayURL else { return }
self.profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name)
UnifiedTelemetry.recordEvent(category: .action, method: .add, object: .readingListItem, value: .pageActionMenu)
success(Strings.AppMenuAddToReadingListConfirmMessage)
}
let findInPageAction = PhotonActionSheetItem(title: Strings.AppMenuFindInPageTitleString, iconString: "menu-FindInPage") { action in
findInPage()
}
let bookmarkPage = PhotonActionSheetItem(title: Strings.AppMenuAddBookmarkTitleString, iconString: "menu-Bookmark") { action in
//TODO: can all this logic go somewhere else?
guard let url = tab.canonicalURL?.displayURL else { return }
let absoluteString = url.absoluteString
let shareItem = ShareItem(url: absoluteString, title: tab.title, favicon: tab.displayFavicon)
_ = self.profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: .shared)
UnifiedTelemetry.recordEvent(category: .action, method: .add, object: .bookmark, value: .pageActionMenu)
success(Strings.AppMenuAddBookmarkConfirmMessage)
}
let removeBookmark = PhotonActionSheetItem(title: Strings.AppMenuRemoveBookmarkTitleString, iconString: "menu-Bookmark-Remove") { action in
//TODO: can all this logic go somewhere else?
guard let url = tab.url?.displayURL else { return }
let absoluteString = url.absoluteString
self.profile.bookmarks.modelFactory >>== {
$0.removeByURL(absoluteString).uponQueue(.main) { res in
if res.isSuccess {
UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .bookmark, value: .pageActionMenu)
success(Strings.AppMenuRemoveBookmarkConfirmMessage)
}
}
}
}
let pinToTopSites = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin") { action in
guard let url = tab.url?.displayURL,
let sql = self.profile.history as? SQLiteHistory else { return }
let absoluteString = url.absoluteString
sql.getSitesForURLs([absoluteString]) >>== { result in
guard let siteOp = result.asArray().first, let site = siteOp else {
log.warning("Could not get site for \(absoluteString)")
return
}
_ = self.profile.history.addPinnedTopSite(site).value
}
}
let sendToDevice = PhotonActionSheetItem(title: Strings.SendToDeviceTitle, iconString: "menu-Send-to-Device") { action in
guard let bvc = presentableVC as? PresentableVC & InstructionsViewControllerDelegate & ClientPickerViewControllerDelegate else { return }
if !self.profile.hasAccount() {
let instructionsViewController = InstructionsViewController()
instructionsViewController.delegate = bvc
let navigationController = UINavigationController(rootViewController: instructionsViewController)
navigationController.modalPresentationStyle = .formSheet
bvc.present(navigationController, animated: true, completion: nil)
return
}
let clientPickerViewController = ClientPickerViewController()
clientPickerViewController.clientPickerDelegate = bvc
clientPickerViewController.profile = self.profile
clientPickerViewController.profileNeedsShutdown = false
let navigationController = UINavigationController(rootViewController: clientPickerViewController)
navigationController.modalPresentationStyle = .formSheet
bvc.present(navigationController, animated: true, completion: nil)
}
let share = PhotonActionSheetItem(title: Strings.AppMenuSharePageTitleString, iconString: "action_share") { action in
guard let url = tab.canonicalURL?.displayURL else { return }
presentShareMenu(url, tab, buttonView, .up)
}
let copyURL = PhotonActionSheetItem(title: Strings.AppMenuCopyURLTitleString, iconString: "menu-Copy-Link") { _ in
UIPasteboard.general.url = tab.canonicalURL?.displayURL
success(Strings.AppMenuCopyURLConfirmMessage)
}
var mainActions = [share]
// Disable bookmarking and reading list if the URL is too long.
if !tab.urlIsTooLong {
mainActions.append(isBookmarked ? removeBookmark : bookmarkPage)
if tab.readerModeAvailableOrActive {
mainActions.append(addReadingList)
}
}
mainActions.append(contentsOf: [sendToDevice, copyURL])
return [mainActions, [findInPageAction, toggleDesktopSite, pinToTopSites]]
}
func fetchBookmarkStatus(for url: String) -> Deferred<Maybe<Bool>> {
return self.profile.bookmarks.modelFactory.bind {
guard let factory = $0.successValue else {
return deferMaybe(false)
}
return factory.isBookmarked(url)
}
}
func getLongPressLocationBarActions(with urlBar: URLBarView) -> [PhotonActionSheetItem] {
let pasteGoAction = PhotonActionSheetItem(title: Strings.PasteAndGoTitle, iconString: "menu-PasteAndGo") { action in
if let pasteboardContents = UIPasteboard.general.string {
urlBar.delegate?.urlBar(urlBar, didSubmitText: pasteboardContents)
}
}
let pasteAction = PhotonActionSheetItem(title: Strings.PasteTitle, iconString: "menu-Paste") { action in
if let pasteboardContents = UIPasteboard.general.string {
urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true)
}
}
let copyAddressAction = PhotonActionSheetItem(title: Strings.CopyAddressTitle, iconString: "menu-Copy-Link") { action in
if let url = urlBar.currentURL {
UIPasteboard.general.url = url as URL
}
}
if UIPasteboard.general.string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
@available(iOS 11.0, *)
private func menuActionsForNotBlocking() -> [PhotonActionSheetItem] {
return [PhotonActionSheetItem(title: Strings.SettingsTrackingProtectionSectionName, text: Strings.TPNoBlockingDescription, iconString: "menu-TrackingProtection")]
}
@available(iOS 11.0, *)
private func menuActionsForTrackingProtectionDisabled(for tab: Tab, presentingOn urlBar: URLBarView) -> [PhotonActionSheetItem] {
let enableTP = PhotonActionSheetItem(title: Strings.EnableTPBlocking, iconString: "menu-TrackingProtection") { _ in
// TODO: Enable Tracking protection for the current browsing mode
}
let moreInfo = PhotonActionSheetItem(title: Strings.TPBlockingMoreInfo, iconString: "menu-Info") { _ in
let url = SupportUtils.URLForTopic("tracking-protection-ios")!
tab.loadRequest(PrivilegedRequest(url: url) as URLRequest)
}
let tpBlocking = PhotonActionSheetItem(title: Strings.SettingsTrackingProtectionSectionName, text: Strings.TPBlockingDisabledDescription, iconString: "menu-TrackingProtection", isEnabled: false, accessory: .None) { _ in
// guard let bvc = self as? PresentableVC else { return }
// self.presentSheetWith(title: Strings.SettingsTrackingProtectionSectionName, actions: [[moreInfo], [enableTP]], on: bvc, from: urlBar)
}
return [tpBlocking]
}
@available(iOS 11.0, *)
private func menuActionsForTrackingProtectionEnabled(for tab: Tab, presentingOn urlBar: URLBarView) -> [PhotonActionSheetItem] {
guard let blocker = tab.contentBlocker as? ContentBlockerHelper, let currentURL = tab.url else {
return []
}
let stats = blocker.stats
let totalCount = PhotonActionSheetItem(title: Strings.TrackingProtectionTotalBlocked, accessory: .Text, accessoryText: "\(stats.total)", bold: true)
let adCount = PhotonActionSheetItem(title: Strings.TrackingProtectionAdsBlocked, accessory: .Text, accessoryText: "\(stats.adCount)")
let analyticsCount = PhotonActionSheetItem(title: Strings.TrackingProtectionAnalyticsBlocked, accessory: .Text, accessoryText: "\(stats.analyticCount)")
let socialCount = PhotonActionSheetItem(title: Strings.TrackingProtectionSocialBlocked, accessory: .Text, accessoryText: "\(stats.socialCount)")
let contentCount = PhotonActionSheetItem(title: Strings.TrackingProtectionContentBlocked, accessory: .Text, accessoryText: "\(stats.contentCount)")
let statList = [totalCount, adCount, analyticsCount, socialCount, contentCount]
let addToWhitelist = PhotonActionSheetItem(title: Strings.TrackingProtectionDisableTitle, iconString: "menu-TrackingProtection-Off") { _ in
if let domain = currentURL.baseDomain, !domain.isEmpty {
blocker.whitelist(enable: true, forDomain: domain)
}
}
// when tracking protection is on and content was blocked
let tpBlocking = PhotonActionSheetItem(title: Strings.SettingsTrackingProtectionSectionName, text: Strings.TPBlockingDescription, iconString: "menu-TrackingProtection-Off", isEnabled: false, accessory: .None) { _ in
// guard let bvc = self as? PresentableVC else { return }
// self.presentSheetWith(title: Strings.SettingsTrackingProtectionSectionName, actions: [statList, [addToWhitelist]], on: bvc, from: urlBar)
}
return [tpBlocking]
}
@available(iOS 11.0, *)
private func menuActionsForWhitelistedSite(for tab: Tab, presentingOn urlBar: URLBarView) -> [PhotonActionSheetItem] {
guard let blocker = tab.contentBlocker as? ContentBlockerHelper, let currentURL = tab.url else {
return []
}
let removeFromWhitelist = PhotonActionSheetItem(title: Strings.TrackingProtectionWhiteListRemove, iconString: "menu-TrackingProtection") { _ in
if let domain = currentURL.baseDomain, !domain.isEmpty {
blocker.whitelist(enable: false, forDomain: domain)
}
}
let tpBlocking = PhotonActionSheetItem(title: Strings.SettingsTrackingProtectionSectionName, text: Strings.TrackingProtectionWhiteListOn, iconString: "menu-TrackingProtection", isEnabled: false, accessory: .None) { _ in
// guard let bvc = self as? PresentableVC else { return }
// self.presentSheetWith(title: Strings.SettingsTrackingProtectionSectionName, actions: [[removeFromWhitelist]], on: bvc, from: urlBar)
}
return [tpBlocking]
}
@available(iOS 11.0, *)
func getTrackingMenu(for tab: Tab, presentingOn urlBar: URLBarView) -> [PhotonActionSheetItem] {
guard let blocker = tab.contentBlocker as? ContentBlockerHelper, let currentURL = tab.url else {
return []
}
if blocker.stats.total == 0, blocker.isEnabled, !blocker.isURLWhitelisted(url: currentURL) {
// When ad blocking is enabled but no content was blocked on the page
return menuActionsForNotBlocking()
} else if !blocker.isEnabled {
// when tracking protection is disabled
return menuActionsForTrackingProtectionDisabled(for: tab, presentingOn: urlBar)
} else if blocker.stats.total > 0 {
// When tracking protection is enabled and content is blocked on the page
return menuActionsForTrackingProtectionEnabled(for: tab, presentingOn: urlBar)
} else if blocker.isEnabled, blocker.isURLWhitelisted(url: currentURL) {
// When tracking protection is enabled but the site is in the whitelist
return menuActionsForWhitelistedSite(for: tab, presentingOn: urlBar)
}
return []
}
}