hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
eb04fa4055190c16be8094c2d647fd7d39bf2165
11,129
// // SettingsViewController.swift // Freetime // // Created by Ryan Nystrom on 7/31/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import GitHubAPI import GitHubSession import Squawk final class SettingsViewController: UITableViewController, NewIssueTableViewControllerDelegate, DefaultReactionDelegate, GitHubSessionListener { // must be injected var sessionManager: GitHubSessionManager! { didSet { sessionManager.addListener(listener: self) } } var client: GithubClient! @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var reviewAccessCell: StyledTableCell! @IBOutlet weak var githubStatusCell: StyledTableCell! @IBOutlet weak var reviewOnAppStoreCell: StyledTableCell! @IBOutlet weak var tryTestFlightBetaCell: StyledTableCell! @IBOutlet weak var reportBugCell: StyledTableCell! @IBOutlet weak var viewSourceCell: StyledTableCell! @IBOutlet weak var setDefaultReaction: StyledTableCell! @IBOutlet weak var signOutCell: StyledTableCell! @IBOutlet weak var badgeSwitch: UISwitch! @IBOutlet weak var badgeSettingsButton: UIButton! @IBOutlet weak var badgeCell: UITableViewCell! @IBOutlet weak var markReadSwitch: UISwitch! @IBOutlet weak var accountsCell: StyledTableCell! @IBOutlet weak var apiStatusLabel: UILabel! @IBOutlet weak var apiStatusView: UIImageView! @IBOutlet weak var signatureSwitch: UISwitch! @IBOutlet weak var defaultReactionLabel: UILabel! @IBOutlet weak var pushSwitch: UISwitch! @IBOutlet weak var pushCell: UITableViewCell! @IBOutlet weak var pushSettingsButton: UIButton! @IBOutlet weak var openExternalLinksSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() versionLabel.text = Bundle.main.prettyVersionString markReadSwitch.isOn = NotificationModelController.readOnOpen apiStatusView.layer.cornerRadius = 7 apiStatusView.image = .from(color: Styles.Colors.Gray.border.color) signatureSwitch.isOn = Signature.enabled openExternalLinksSwitch.isOn = UserDefaults.standard.shouldOpenExternalLinksInSafari pushSettingsButton.accessibilityLabel = NSLocalizedString("How we send push notifications in GitHawk", comment: "") updateBadge() NotificationCenter.default.addObserver( self, selector: #selector(SettingsViewController.updateBadge), name: .UIApplicationDidBecomeActive, object: nil ) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateDefaultReaction() rz_smoothlyDeselectRows(tableView: tableView) updateActiveAccount() client.client.send(GitHubAPIStatusRequest()) { [weak self] result in guard let strongSelf = self else { return } switch result { case .failure: strongSelf.apiStatusView.isHidden = true strongSelf.apiStatusLabel.text = NSLocalizedString("error", comment: "") case .success(let response): let text = response.data.status.description let color: UIColor switch response.data.status.indicator { case .none: color = Styles.Colors.Green.medium.color case .minor: color = Styles.Colors.Yellow.medium.color case .major: color = Styles.Colors.Red.medium.color case .critical: color = Styles.Colors.Red.dark.color } strongSelf.apiStatusView.isHidden = false strongSelf.apiStatusView.image = .from(color: color) strongSelf.apiStatusLabel.text = text strongSelf.apiStatusLabel.textColor = color } } } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: trueUnlessReduceMotionEnabled) let cell = tableView.cellForRow(at: indexPath) switch cell { case reviewAccessCell: onReviewAccess() case accountsCell: onAccounts() case githubStatusCell: onGitHubStatus() case reviewOnAppStoreCell: onReviewOnAppStore() case reportBugCell: onReportBug() case viewSourceCell: onViewSource() case setDefaultReaction: onSetDefaultReaction() case signOutCell: onSignOut() case tryTestFlightBetaCell: onTryTestFlightBeta() default: break } } // MARK: Private API private func updateDefaultReaction() { defaultReactionLabel.text = ReactionContent.defaultReaction?.emoji ?? NSLocalizedString("Off", comment: "") } private func onReviewAccess() { UIApplication.shared.openReviewAccess() } private func onAccounts() { if let navigationController = UIStoryboard(name: "Settings", bundle: nil).instantiateViewController(withIdentifier: "accountsNavigationController") as? UINavigationController, let accountsController = navigationController.topViewController as? SettingsAccountsViewController, let client = self.client { accountsController.config(client: client.client, sessionManager: sessionManager) route_detail(to: navigationController) } } private func onGitHubStatus() { guard let url = URLBuilder(host: "www.githubstatus.com").url else { return } presentSafari(url: url) } private func onReviewOnAppStore() { UIApplication.shared.openWriteReview() } private func onReportBug() { guard let viewController = NewIssueTableViewController.create( client: GithubClient(userSession: sessionManager.focusedUserSession), owner: "GitHawkApp", repo: "GitHawk", signature: .bugReport ) else { Squawk.showGenericError() return } viewController.delegate = self let navController = UINavigationController(rootViewController: viewController) navController.modalPresentationStyle = .formSheet route_present(to: navController) } private func onViewSource() { guard let client = client else { Squawk.showGenericError() return } let repo = RepositoryDetails( owner: "GitHawkApp", name: "GitHawk" ) route_detail(to: RepositoryViewController(client: client, repo: repo)) } private func onSetDefaultReaction() { let storyboard = UIStoryboard(name: "Settings", bundle: nil) guard let viewController = storyboard.instantiateViewController(withIdentifier: "DefaultReactionDetailController") as? DefaultReactionDetailController else { fatalError("Cannot instantiate DefaultReactionDetailController instance") } viewController.delegate = self route_detail(to: viewController) } private func onTryTestFlightBeta() { #if TESTFLIGHT Squawk.showAlreadyOnBeta() #else guard let url = URLBuilder.init(host: "testflight.apple.com").add(paths: ["join", "QIVXLkkn"]).url else { return } presentSafari(url: url) #endif } private func onSignOut() { let title = NSLocalizedString("Are you sure?", comment: "") let message = NSLocalizedString("You will be signed out from all of your accounts. Do you want to sign out?", comment: "") let alert = UIAlertController.configured(title: title, message: message, preferredStyle: .actionSheet) alert.addActions([ AlertAction.cancel(), AlertAction(AlertActionBuilder { $0.title = Constants.Strings.signout $0.style = .destructive }).get { [weak self] _ in self?.signout() } ]) present(alert, animated: trueUnlessReduceMotionEnabled) } private func signout() { sessionManager.logout() } @objc private func updateBadge() { BadgeNotifications.check { result in let showSwitches: Bool let pushEnabled: Bool let badgeEnabled: Bool switch result { case .error: showSwitches = false pushEnabled = false badgeEnabled = false case .success(let badge, let push): showSwitches = true pushEnabled = push badgeEnabled = badge } self.badgeCell.accessoryType = showSwitches ? .none : .disclosureIndicator self.badgeSettingsButton.isHidden = showSwitches self.badgeSwitch.isHidden = !showSwitches self.badgeSwitch.isOn = badgeEnabled self.pushCell.accessoryType = showSwitches ? .none : .disclosureIndicator self.pushSettingsButton.isHidden = showSwitches self.pushSwitch.isHidden = !showSwitches self.pushSwitch.isOn = pushEnabled } } private func updateActiveAccount() { accountsCell.detailTextLabel?.text = sessionManager.focusedUserSession?.username ?? Constants.Strings.unknown } @IBAction private func onBadgeChanged() { BadgeNotifications.isBadgeEnabled = badgeSwitch.isOn BadgeNotifications.configure { _ in self.updateBadge() } } @IBAction private func onPushChanged() { BadgeNotifications.isLocalNotificationEnabled = pushSwitch.isOn BadgeNotifications.configure { _ in self.updateBadge() } } @IBAction private func onSettings(_ sender: Any) { guard let url = URL(string: UIApplicationOpenSettingsURLString) else { return } UIApplication.shared.open(url) } @IBAction private func onMarkRead(_ sender: Any) { NotificationModelController.setReadOnOpen(open: markReadSwitch.isOn) } @IBAction private func onSignature(_ sender: Any) { Signature.enabled = signatureSwitch.isOn } @IBAction private func onPushNotificationsInfo(_ sender: Any) { showContextualMenu(PushNotificationsDisclaimerViewController()) } @IBAction private func onOpenExternalLinks(_ sender: Any) { UserDefaults.standard.shouldOpenExternalLinksInSafari = openExternalLinksSwitch.isOn } // MARK: NewIssueTableViewControllerDelegate func didDismissAfterCreatingIssue(model: IssueDetailsModel) { route_detail(to: IssuesViewController(client: client, model: model)) } // MARK: DefaultReactionDelegate func didUpdateDefaultReaction() { updateDefaultReaction() } // MARK: GitHubSessionListener func didFocus(manager: GitHubSessionManager, userSession: GitHubUserSession, isSwitch: Bool) { updateActiveAccount() } func didLogout(manager: GitHubSessionManager) {} }
35.669872
183
0.661335
fbe0a71e0a571895449f24c0d8ec6454ba63cfa5
7,117
//===----------------------------------------------------------------------===// // // This source file is part of the swift-cluster-membership open source project // // Copyright (c) 2018 Apple Inc. and the swift-cluster-membership project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of swift-cluster-membership project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import ClusterMembership extension SWIM { /// The SWIM membership status reflects how a node is perceived by the distributed failure detector. /// /// ### Modification: Unreachable status (opt-in) /// If the unreachable status extension is enabled, it is set / when a classic SWIM implementation would have /// declared a node `.dead`, / yet since we allow for the higher level membership to decide when and how to eject /// members from a cluster, / only the `.unreachable` state is set and an `Cluster.ReachabilityChange` cluster event /// is emitted. / In response to this a high-level membership protocol MAY confirm the node as dead by issuing /// `Instance.confirmDead`, / which will promote the node to `.dead` in SWIM terms. /// /// > The additional `.unreachable` status is only used it enabled explicitly by setting `settings.unreachable` /// > to enabled. Otherwise, the implementation performs its failure checking as usual and directly marks detected /// > to be failed members as `.dead`. /// /// ### Legal transitions: /// - `alive -> suspect` /// - `alive -> suspect`, with next `SWIM.Incarnation`, e.g. during flaky network situations, we suspect and un-suspect a node depending on probing /// - `suspect -> unreachable | alive`, if in SWIM terms, a node is "most likely dead" we declare it `.unreachable` instead, and await for high-level confirmation to mark it `.dead`. /// - `unreachable -> alive | suspect`, with next `SWIM.Incarnation` optional) /// - `alive | suspect | unreachable -> dead` /// /// - SeeAlso: `SWIM.Incarnation` public enum Status: Hashable { /// Indicates an `alive` member of the cluster, i.e. if is reachable and properly replies to all probes on time. case alive(incarnation: Incarnation) /// Indicates a `suspect` member of the cluster, meaning that it did not reply on time to probing and MAY be unreachable. /// Further probing and indirect probing will be performed to test if it really is unreachable/dead, /// or just had a small glitch (or network issues). case suspect(incarnation: Incarnation, suspectedBy: Set<Node>) /// Extension from traditional SWIM states: indicates an unreachable node, under traditional SWIM it would have /// already been marked `.dead`, however unreachability allows for a final extra step including a `swim.confirmDead()` /// call, to move the unreachable node to dead state. /// /// This only matters for multi layer membership protocols which use SWIM as their failure detection mechanism. /// /// This state is DISABLED BY DEFAULT, and if a node receives such unreachable status about another member while /// this setting is disabled it will immediately treat such member as `.dead`. Do not run in mixed mode clusters, /// as this can yield unexpected consequences. case unreachable(incarnation: Incarnation) /// Indicates /// Note: In the original paper this state was referred to as "confirm", which we found slightly confusing, thus the rename. case dead } } extension SWIM.Status: Comparable { public static func < (lhs: SWIM.Status, rhs: SWIM.Status) -> Bool { switch (lhs, rhs) { case (.alive(let selfIncarnation), .alive(let rhsIncarnation)): return selfIncarnation < rhsIncarnation case (.alive(let selfIncarnation), .suspect(let rhsIncarnation, _)): return selfIncarnation <= rhsIncarnation case (.alive(let selfIncarnation), .unreachable(let rhsIncarnation)): return selfIncarnation <= rhsIncarnation case (.suspect(let selfIncarnation, let selfSuspectedBy), .suspect(let rhsIncarnation, let rhsSuspectedBy)): return selfIncarnation < rhsIncarnation || (selfIncarnation == rhsIncarnation && selfSuspectedBy.isStrictSubset(of: rhsSuspectedBy)) case (.suspect(let selfIncarnation, _), .alive(let rhsIncarnation)): return selfIncarnation < rhsIncarnation case (.suspect(let selfIncarnation, _), .unreachable(let rhsIncarnation)): return selfIncarnation <= rhsIncarnation case (.unreachable(let selfIncarnation), .alive(let rhsIncarnation)): return selfIncarnation < rhsIncarnation case (.unreachable(let selfIncarnation), .suspect(let rhsIncarnation, _)): return selfIncarnation < rhsIncarnation case (.unreachable(let selfIncarnation), .unreachable(let rhsIncarnation)): return selfIncarnation < rhsIncarnation case (.dead, _): return false case (_, .dead): return true } } } extension SWIM.Status { /// Only `alive` or `suspect` members carry an incarnation number. public var incarnation: SWIM.Incarnation? { switch self { case .alive(let incarnation): return incarnation case .suspect(let incarnation, _): return incarnation case .unreachable(let incarnation): return incarnation case .dead: return nil } } /// - Returns: true if the underlying member status is `.alive`, false otherwise. public var isAlive: Bool { switch self { case .alive: return true case .suspect, .unreachable, .dead: return false } } /// - Returns: true if the underlying member status is `.suspect`, false otherwise. public var isSuspect: Bool { switch self { case .suspect: return true case .alive, .unreachable, .dead: return false } } /// - Returns: true if the underlying member status is `.unreachable`, false otherwise. public var isUnreachable: Bool { switch self { case .unreachable: return true case .alive, .suspect, .dead: return false } } /// - Returns: `true` if the underlying member status is `.unreachable`, false otherwise. public var isDead: Bool { switch self { case .dead: return true case .alive, .suspect, .unreachable: return false } } /// - Returns `true` if `self` is greater than or equal to `other` based on the /// following ordering: `alive(N)` < `suspect(N)` < `alive(N+1)` < `suspect(N+1)` < `dead` public func supersedes(_ other: SWIM.Status) -> Bool { self >= other } }
46.822368
186
0.63805
7a129603d6043e4e364dfa6eca8a08e6adbfb7ae
91,700
// Converted to Swift 4 by Swiftify v4.1.6613 - https://objectivec2swift.com/ // // PVGameLibraryViewController.swift // Provenance // // Created by James Addyman on 07/04/2013. // Copyright (c) 2013 JamSoft. All rights reserved. // #if os(iOS) import Photos import SafariServices #endif import CoreSpotlight import GameController import PVLibrary import PVSupport import QuartzCore import Reachability import RealmSwift import RxCocoa import RxDataSources import RxSwift import UIKit let PVGameLibraryHeaderViewIdentifier = "PVGameLibraryHeaderView" let PVGameLibraryFooterViewIdentifier = "PVGameLibraryFooterView" let PVGameLibraryCollectionViewCellIdentifier = "PVGameLibraryCollectionViewCell" let PVGameLibraryCollectionViewSaveStatesCellIdentifier = "SaveStateCollectionCell" let PVGameLibraryCollectionViewGamesCellIdentifier = "RecentlyPlayedCollectionCell" let PVRequiresMigrationKey = "PVRequiresMigration" // should we use the "new" context menus added in iOS 13, or use an action sheet let useModernContextMenus = true // For Obj-C public extension NSNotification { @objc static var PVRefreshLibraryNotification: NSString { return "kRefreshLibraryNotification" } } public extension Notification.Name { static let PVRefreshLibrary = Notification.Name("kRefreshLibraryNotification") static let PVInterfaceDidChangeNotification = Notification.Name("kInterfaceDidChangeNotification") } #if os(iOS) final class PVDocumentPickerViewController: UIDocumentPickerViewController { override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.barStyle = Theme.currentTheme.navigationBarStyle } } #endif final class PVGameLibraryViewController: GCEventViewController, UITextFieldDelegate, UINavigationControllerDelegate, GameLaunchingViewController, GameSharingViewController, WebServerActivatorController { lazy var collectionViewZoom: CGFloat = CGFloat(PVSettingsModel.shared.gameLibraryScale) let disposeBag = DisposeBag() var updatesController: PVGameLibraryUpdatesController! var gameLibrary: PVGameLibrary! var gameImporter: GameImporter! var filePathsToImport = [URL]() // selected (aka hilighted) item selected via game controller UX #if os(iOS) // NOTE this may not be a *real* indexPath, if it is for a section with a nexted collection view var _selectedIndexPath:IndexPath? var _selectedIndexPathView:UIView! #endif var collectionView: UICollectionView? { didSet { guard let collectionView = collectionView else { return } #if os(iOS) if #available(iOS 14.0, *) { collectionView.selectionFollowsFocus = true } #endif collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } } #if os(iOS) var photoLibrary: PHPhotoLibrary? #endif var gameForCustomArt: PVGame? @IBOutlet var settingsBarButtonItem: UIBarButtonItem! @IBOutlet var getMoreRomsBarButtonItem: UIBarButtonItem! @IBOutlet var sortOptionBarButtonItem: UIBarButtonItem! @IBOutlet var conflictsBarButtonItem: UIBarButtonItem! #if os(iOS) @IBOutlet var libraryInfoContainerView: UIStackView! @IBOutlet var libraryInfoLabel: UILabel! #endif var isInitialAppearance = false // add or remove the conflict button (iff it is in the storyboard) func updateConflictsButton(_ hasConflicts: Bool) { if let conflictsBarButtonItem = conflictsBarButtonItem { conflictsBarButtonItem.isEnabled = hasConflicts #if os(tvOS) let items: [UIBarButtonItem] = hasConflicts ? [ getMoreRomsBarButtonItem, conflictsBarButtonItem ] : [getMoreRomsBarButtonItem] #else let items: [UIBarButtonItem] = hasConflicts ? [ settingsBarButtonItem, conflictsBarButtonItem ] : [settingsBarButtonItem] #endif navigationItem.leftBarButtonItems = items } } @IBOutlet var sortOptionsTableView: UITableView! lazy var sortOptionsTableViewController: SortOptionsTableViewController = { let avc = SortOptionsTableViewController(withTableView: sortOptionsTableView) avc.title = "Library Options" return avc }() let currentSort = BehaviorSubject(value: PVSettingsModel.shared.sort) let collapsedSystems = BehaviorSubject(value: PVSettingsModel.shared.collapsedSystems) let showSaveStates = BehaviorSubject(value: PVSettingsModel.shared.showRecentSaveStates) let showRecentGames = BehaviorSubject(value: PVSettingsModel.shared.showRecentGames) // MARK: - Lifecycle #if os(iOS) override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } #endif deinit { NotificationCenter.default.removeObserver(self) } @objc func handleAppDidBecomeActive(_: Notification) { loadGameFromShortcut() } struct Section: SectionModelType { let header: String let items: [Item] let collapsable: Collapsable? enum Item { case game(PVGame) case favorites([PVGame]) case saves([PVSaveState]) case recents([PVRecentGame]) } enum Collapsable { case collapsed(systemToken: String) case notCollapsed(systemToken: String) } init(header: String, items: [Item], collapsable: Collapsable?) { self.header = header self.items = items self.collapsable = collapsable } init(original: PVGameLibraryViewController.Section, items: [Item]) { self.init(header: original.header, items: items, collapsable: original.collapsable) } } #if os(iOS) var searchController: UISearchController! #endif override func viewDidLoad() { super.viewDidLoad() isInitialAppearance = true definesPresentationContext = true NotificationCenter.default.addObserver(self, selector: #selector(PVGameLibraryViewController.databaseMigrationStarted(_:)), name: NSNotification.Name.DatabaseMigrationStarted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(PVGameLibraryViewController.databaseMigrationFinished(_:)), name: NSNotification.Name.DatabaseMigrationFinished, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(PVGameLibraryViewController.handleCacheEmptied(_:)), name: NSNotification.Name.PVMediaCacheWasEmptied, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(PVGameLibraryViewController.handleArchiveInflationFailed(_:)), name: NSNotification.Name.PVArchiveInflationFailed, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(PVGameLibraryViewController.handleAppDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) #if os(iOS) navigationController?.navigationBar.tintColor = Theme.currentTheme.barButtonItemTint navigationItem.leftBarButtonItem?.tintColor = Theme.currentTheme.barButtonItemTint NotificationCenter.default.addObserver(forName: NSNotification.Name.PVInterfaceDidChangeNotification, object: nil, queue: nil, using: { (_: Notification) -> Void in DispatchQueue.main.async { self.collectionView?.collectionViewLayout.invalidateLayout() self.collectionView?.reloadData() } }) #else navigationController?.navigationBar.isTranslucent = false let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = (self.navigationController?.navigationBar.bounds)! self.navigationController?.navigationBar.addSubview(blurEffectView) self.navigationController?.navigationBar.sendSubviewToBack(blurEffectView) navigationController?.navigationBar.backgroundColor = UIColor.black.withAlphaComponent(0.5) // ironicaly BarButtonItems (unselected background) look better when forced to LightMode if #available(tvOS 13.0, *) { navigationController?.overrideUserInterfaceStyle = .light self.overrideUserInterfaceStyle = .dark } #endif // Handle migrating library DispatchQueue.main.async { self.handleLibraryMigration() } let searchText: Observable<String?> #if os(iOS) // Navigation bar large titles navigationController?.navigationBar.prefersLargeTitles = false navigationItem.title = nil // Create a search controller let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.placeholder = "Search" searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false if #available(iOS 13.0, *) { searchController.automaticallyShowsCancelButton = true } navigationItem.hidesSearchBarWhenScrolling = true navigationItem.searchController = searchController self.searchController = searchController searchText = Observable.merge(searchController.rx.searchText, searchController.rx.didDismiss.map { _ in nil }) #else searchText = .never() #endif // create a Logo as the title #if os(iOS) let font = UIFont.boldSystemFont(ofSize: 20) let icon = "AppIcon" let icon_size = font.pointSize #else let font = UIFont.boldSystemFont(ofSize: 48) let icon = "pv_dark_logo" let icon_size = font.capHeight #endif if let icon = UIImage(named:icon)?.resize(to:CGSize(width:0,height:icon_size)) { let logo = UIImageView(image:icon) logo.layer.cornerRadius = 4.0; logo.layer.masksToBounds = true let name = UILabel() name.text = " Provenance" name.font = font name.textColor = .white name.sizeToFit() let stack = UIStackView(arrangedSubviews:[logo,name]) stack.alignment = .center stack.frame = CGRect(origin:.zero, size:stack.systemLayoutSizeFitting(.zero)) navigationItem.titleView = stack } // we cant use a SF Symbol in the Storyboard cuz of back version support, so change it here in code. if #available(iOS 13.0, tvOS 13.0, *) { if let bbi = settingsBarButtonItem { bbi.image = UIImage(systemName:"gear", withConfiguration:UIImage.SymbolConfiguration(font:font)) } } // Persist some settings, could probably be done in a better way collapsedSystems.bind(onNext: { PVSettingsModel.shared.collapsedSystems = $0 }).disposed(by: disposeBag) currentSort.bind(onNext: { PVSettingsModel.shared.sort = $0 }).disposed(by: disposeBag) showSaveStates.bind(onNext: { PVSettingsModel.shared.showRecentSaveStates = $0 }).disposed(by: disposeBag) showRecentGames.bind(onNext: { PVSettingsModel.shared.showRecentGames = $0 }).disposed(by: disposeBag) let layout = PVGameLibraryCollectionFlowLayout() layout.scrollDirection = .vertical let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) self.collectionView = collectionView typealias Playable = (PVGame, UICollectionViewCell?, PVCore?, PVSaveState?) let selectedPlayable = PublishSubject<Playable>() let dataSource = RxCollectionViewSectionedReloadDataSource<Section>(configureCell: { _, collectionView, indexPath, item in switch item { case .game(let game): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PVGameLibraryCollectionViewCellIdentifier, for: indexPath) as! PVGameLibraryCollectionViewCell cell.game = game return cell case .favorites(let games): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewInCollectionViewCell<PVGame>.identifier, for: indexPath) as! CollectionViewInCollectionViewCell<PVGame> cell.items.onNext(games) cell.internalCollectionView.rx.itemSelected .map { indexPath in (try cell.internalCollectionView.rx.model(at: indexPath), cell.internalCollectionView.cellForItem(at: indexPath)) } .map { ($0, $1, nil, nil) } .bind(to: selectedPlayable) .disposed(by: cell.disposeBag) return cell case .saves(let saves): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewInCollectionViewCell<PVSaveState>.identifier, for: indexPath) as! CollectionViewInCollectionViewCell<PVSaveState> cell.items.onNext(saves) cell.internalCollectionView.rx.itemSelected .map { indexPath in (try cell.internalCollectionView.rx.model(at: indexPath), cell.internalCollectionView.cellForItem(at: indexPath)) } .map { ($0.game, $1, $0.core, $0) } .bind(to: selectedPlayable) .disposed(by: cell.disposeBag) return cell case .recents(let games): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewInCollectionViewCell<PVRecentGame>.identifier, for: indexPath) as! CollectionViewInCollectionViewCell<PVRecentGame> cell.items.onNext(games) cell.internalCollectionView.rx.itemSelected .map { indexPath -> (PVRecentGame, UICollectionViewCell?) in (try cell.internalCollectionView.rx.model(at: indexPath), cell.internalCollectionView.cellForItem(at: indexPath)) } .map { ($0.game, $1, $0.core, nil) } .bind(to: selectedPlayable) .disposed(by: cell.disposeBag) return cell } }) collectionView.rx.itemSelected .map { indexPath in (try! collectionView.rx.model(at: indexPath) as Section.Item, collectionView.cellForItem(at: indexPath)) } .compactMap({ item, cell -> Playable? in switch item { case .game(let game): return (game, cell, nil, nil) case .saves, .favorites, .recents: // Handled in another place return nil } }) .bind(to: selectedPlayable) .disposed(by: disposeBag) selectedPlayable.bind(onNext: self.load).disposed(by: disposeBag) dataSource.configureSupplementaryView = { dataSource, collectionView, kind, indexPath in switch kind { case UICollectionView.elementKindSectionHeader: let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: PVGameLibraryHeaderViewIdentifier, for: indexPath) as! PVGameLibrarySectionHeaderView let section = dataSource.sectionModels[indexPath.section] let collapsed: Bool = { if case .collapsed = section.collapsable { return true } return false }() header.viewModel = .init(title: section.header, collapsable: section.collapsable != nil, collapsed: collapsed) #if os(iOS) header.collapseButton.rx.tap .withLatestFrom(self.collapsedSystems) .map({ (collapsedSystems: Set<String>) in switch section.collapsable { case .collapsed(let token): return collapsedSystems.subtracting([token]) case .notCollapsed(let token): return collapsedSystems.union([token]) case nil: return collapsedSystems } }) .bind(to: self.collapsedSystems) .disposed(by: header.disposeBag) #endif #if os(tvOS) header.collapseButton.rx.primaryAction .withLatestFrom(self.collapsedSystems) .map({ (collapsedSystems: Set<String>) in switch section.collapsable { case .collapsed(let token): return collapsedSystems.subtracting([token]) case .notCollapsed(let token): return collapsedSystems.union([token]) case nil: return collapsedSystems } }) .bind(to: self.collapsedSystems) .disposed(by: header.disposeBag) header.updateFocusIfNeeded() #endif return header case UICollectionView.elementKindSectionFooter: return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: PVGameLibraryFooterViewIdentifier, for: indexPath) default: fatalError("Don't support type \(kind)") } } let favoritesSection = gameLibrary.favorites .map { favorites in favorites.isEmpty ? nil : Section(header: "Favorites", items: [.favorites(favorites)], collapsable: nil)} let saveStateSection = Observable.combineLatest(showSaveStates, gameLibrary.saveStates) { $0 ? $1 : [] } .map { saveStates in saveStates.isEmpty ? nil : Section(header: "Recently Saved", items: [.saves(saveStates)], collapsable: nil) } let recentsSection = Observable.combineLatest(showRecentGames, gameLibrary.recents) { $0 ? $1 : [] } .map { recentGames in recentGames.isEmpty ? nil : Section(header: "Recently Played", items: [.recents(recentGames)], collapsable: nil) } let topSections = Observable.combineLatest(favoritesSection, saveStateSection, recentsSection) { [$0, $1, $2] } // MARK: DataSource sections let searchSection = searchText .flatMap({ text -> Observable<[PVGame]?> in guard let text = text else { return .just(nil) } return self.gameLibrary.search(for: text).map(Optional.init) }) .map({ games -> Section? in guard let games = games else { return nil } return Section(header: "Search Results", items: games.map { .game($0) }, collapsable: nil) }) .startWith(nil) let systemSections = currentSort .flatMapLatest { Observable.combineLatest(self.gameLibrary.systems(sortedBy: $0), self.collapsedSystems) } .map({ systems, collapsedSystems in systems.map { system in (system: system, isCollapsed: collapsedSystems.contains(system.identifier) )} }) .mapMany({ system, isCollapsed -> Section? in guard !system.sortedGames.isEmpty else { return nil } let header = "\(system.manufacturer) : \(system.shortName)" + (system.isBeta ? " ⚠️ Beta" : "") let items = isCollapsed ? [] : system.sortedGames.map { Section.Item.game($0) } return Section(header: header, items: items, collapsable: isCollapsed ? .collapsed(systemToken: system.identifier) : .notCollapsed(systemToken: system.identifier)) }) let nonSearchSections = Observable.combineLatest(topSections, systemSections) { $0 + $1 } // Remove empty sections .map { sections in sections.compactMap { $0 }} let sections: Observable<[Section]> = Observable .combineLatest(searchSection, nonSearchSections) { searchSection, nonSearchSections in if let searchSection = searchSection { return [searchSection] } else { return nonSearchSections } } sections.observe(on: MainScheduler.instance).bind(to: collectionView.rx.items(dataSource: dataSource)).disposed(by: disposeBag) #if os(iOS) sections.map { !$0.isEmpty }.bind(to: libraryInfoContainerView.rx.isHidden).disposed(by: disposeBag) #endif // attach long press gesture only on pre-iOS 13, and tvOS if useModernContextMenus == false || NSClassFromString("UIContextMenuConfiguration") == nil { collectionView.rx.longPressed(Section.Item.self) .bind(onNext: self.longPressed) .disposed(by: disposeBag) } collectionView.rx.setDelegate(self).disposed(by: disposeBag) collectionView.bounces = true collectionView.alwaysBounceVertical = true collectionView.delaysContentTouches = false collectionView.keyboardDismissMode = .interactive collectionView.register(PVGameLibrarySectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: PVGameLibraryHeaderViewIdentifier) collectionView.register(PVGameLibrarySectionFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: PVGameLibraryFooterViewIdentifier) #if os(tvOS) // collectionView.contentInset = UIEdgeInsets(top: 0, left: 80, bottom: 0, right: 80) collectionView.remembersLastFocusedIndexPath = true collectionView.clipsToBounds = false collectionView.backgroundColor = .black #else collectionView.backgroundColor = Theme.currentTheme.gameLibraryBackground let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(PVGameLibraryViewController.didReceivePinchGesture(gesture:))) pinchGesture.cancelsTouchesInView = true collectionView.addGestureRecognizer(pinchGesture) #endif view.addSubview(collectionView) // Cells that are a collection view themsevles collectionView.register(CollectionViewInCollectionViewCell<PVGame>.self, forCellWithReuseIdentifier: CollectionViewInCollectionViewCell<PVGame>.identifier) collectionView.register(CollectionViewInCollectionViewCell<PVSaveState>.self, forCellWithReuseIdentifier: CollectionViewInCollectionViewCell<PVSaveState>.identifier) collectionView.register(CollectionViewInCollectionViewCell<PVRecentGame>.self, forCellWithReuseIdentifier: CollectionViewInCollectionViewCell<PVRecentGame>.identifier) // TODO: Use nib for cell once we drop iOS 8 and can use layouts #if os(iOS) collectionView.register(UINib(nibName: "PVGameLibraryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: PVGameLibraryCollectionViewCellIdentifier) #else collectionView.register(UINib(nibName: "PVGameLibraryCollectionViewCell~tvOS", bundle: nil), forCellWithReuseIdentifier: PVGameLibraryCollectionViewCellIdentifier) #endif // Adjust collection view layout for iPhone X Safe areas // Can remove this when we go iOS 9+ and just use safe areas // in the story board directly - jm #if os(iOS) collectionView.translatesAutoresizingMaskIntoConstraints = false let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.trailingAnchor.constraint(equalTo: guide.trailingAnchor), collectionView.leadingAnchor.constraint(equalTo: guide.leadingAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) layout.sectionInsetReference = .fromSafeArea #endif // Force touch #if os(iOS) registerForPreviewing(with: self, sourceView: collectionView) #endif #if os(iOS) view.bringSubviewToFront(libraryInfoContainerView) #endif let hud = MBProgressHUD(view: view)! hud.isUserInteractionEnabled = false view.addSubview(hud) updatesController.hudState .observe(on: MainScheduler.instance) .subscribe(onNext: { state in switch state { case .hidden: hud.hide(true) case .title(let title): hud.show(true) hud.mode = .indeterminate hud.labelText = title case .titleAndProgress(let title, let progress): hud.show(true) hud.mode = .annularDeterminate hud.progress = progress hud.labelText = title } }) .disposed(by: disposeBag) updatesController.conflicts .map { !$0.isEmpty } .observe(on: MainScheduler.instance) .subscribe(onNext: { hasConflicts in self.updateConflictsButton(hasConflicts) if hasConflicts { self.showConflictsAlert() } }) .disposed(by: disposeBag) loadGameFromShortcut() becomeFirstResponder() } #if os(tvOS) var focusedGame: PVGame? #endif #if os(iOS) @objc func didReceivePinchGesture(gesture: UIPinchGestureRecognizer) { guard let collectionView = collectionView else { return } let minScale: CGFloat = 0.4 let maxScale: CGFloat = traitCollection.horizontalSizeClass == .compact ? 1.5 : 2.0 struct Holder { static var scaleStart: CGFloat = 1.0 static var normalisedY: CGFloat = 0.0 } switch gesture.state { case .began: Holder.scaleStart = collectionViewZoom collectionView.isScrollEnabled = false guard collectionView.collectionViewLayout.collectionViewContentSize.height != 0 else { ELOG("collectionView.collectionViewLayout.collectionViewContentSize.height is 0") return } Holder.normalisedY = gesture.location(in: collectionView).y / collectionView.collectionViewLayout.collectionViewContentSize.height case .changed: var newScale = Holder.scaleStart * gesture.scale if newScale < minScale { newScale = minScale } else if newScale > maxScale { newScale = maxScale } if newScale != collectionViewZoom { collectionViewZoom = newScale collectionView.collectionViewLayout.invalidateLayout() let dragCenter = gesture.location(in: collectionView.superview ?? collectionView) let currentY = Holder.normalisedY * collectionView.collectionViewLayout.collectionViewContentSize.height collectionView.setContentOffset(CGPoint(x: 0, y: currentY - dragCenter.y), animated: false) } case .ended, .cancelled: collectionView.isScrollEnabled = true PVSettingsModel.shared.gameLibraryScale = Double(collectionViewZoom) default: break } } #endif func loadGameFromShortcut() { let appDelegate = UIApplication.shared.delegate as! PVAppDelegate if let shortcutItemGame = appDelegate.shortcutItemGame { load(shortcutItemGame, sender: collectionView, core: nil) appDelegate.shortcutItemGame = nil } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let indexPaths = collectionView?.indexPathsForSelectedItems indexPaths?.forEach({ indexPath in (self.collectionView?.deselectItem(at: indexPath, animated: true))! }) guard RomDatabase.databaseInitilized else { return } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) #if os(iOS) PVControllerManager.shared.controllerUserInteractionEnabled = false #else self.controllerUserInteractionEnabled = false #endif } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _ = PVControllerManager.shared #if os(iOS) PVControllerManager.shared.controllerUserInteractionEnabled = true #else self.controllerUserInteractionEnabled = true #endif if isInitialAppearance { isInitialAppearance = false #if os(tvOS) let cell: UICollectionViewCell? = collectionView?.cellForItem(at: IndexPath(item: 0, section: 0)) cell?.setNeedsFocusUpdate() cell?.updateFocusIfNeeded() #endif } guard RomDatabase.databaseInitilized else { return } // Warn non core dev users if they're running in debug mode #if DEBUG && !targetEnvironment(simulator) if !PVSettingsModel.shared.haveWarnedAboutDebug, !officialBundleID { #if os(tvOS) let releaseScheme = "ProvenanceTV-Release" #else let releaseScheme = "Provenance-Release" #endif let alert = UIAlertController(title: "Debug Mode Detected", message: "⚠️ Detected app built in 'Debug' mode. Build with the " + releaseScheme + " scheme in XCode for best performance. This alert will only be presented this one time.", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { _ in PVSettingsModel.shared.haveWarnedAboutDebug = true } alert.addAction(ok) present(alert, animated: true) } #endif } fileprivate lazy var officialBundleID: Bool = Bundle.main.bundleIdentifier!.contains("org.provenance-emu.") var transitioningToSize: CGSize? override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) transitioningToSize = size collectionView?.collectionViewLayout.invalidateLayout() coordinator.notifyWhenInteractionChanges { [weak self] _ in self?.transitioningToSize = nil } } #if os(iOS) override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } #endif override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SettingsSegue" { let settingsVC = (segue.destination as! UINavigationController).topViewController as! PVSettingsViewController settingsVC.conflictsController = updatesController } else if segue.identifier == "SplitSettingsSegue" { #if os(tvOS) let splitVC = segue.destination as! PVTVSplitViewController let navVC = splitVC.viewControllers[1] as! UINavigationController let settingsVC = navVC.topViewController as! PVSettingsViewController settingsVC.conflictsController = updatesController #endif } else if segue.identifier == "gameMoreInfoSegue" { let game = sender as! PVGame let moreInfoVC = segue.destination as! PVGameMoreInfoViewController moreInfoVC.game = game } else if segue.identifier == "gameMoreInfoPageVCSegue" { let game = sender as! PVGame let firstVC = UIStoryboard(name: "Provenance", bundle: nil).instantiateViewController(withIdentifier: "gameMoreInfoVC") as! PVGameMoreInfoViewController firstVC.game = game let moreInfoCollectionVC = segue.destination as! GameMoreInfoPageViewController moreInfoCollectionVC.setViewControllers([firstVC], direction: .forward, animated: false, completion: nil) } } #if os(iOS) // Show web server (stays on) func showServer() { let ipURL: String = PVWebServer.shared.urlString let url = URL(string: ipURL)! #if targetEnvironment(macCatalyst) UIApplication.shared.open(url, options: [:]) { completed in ILOG("Completed: \(completed ? "Yes":"No")") } #else let config = SFSafariViewController.Configuration() config.entersReaderIfAvailable = false let safariVC = SFSafariViewController(url: url, configuration: config) safariVC.delegate = self present(safariVC, animated: true) { () -> Void in } #endif // targetEnvironment(macCatalyst) } #if !targetEnvironment(macCatalyst) func safariViewController(_: SFSafariViewController, didCompleteInitialLoad _: Bool) { // Load finished } // Dismiss and shut down web server func safariViewControllerDidFinish(_: SFSafariViewController) { // Done button pressed navigationController?.popViewController(animated: true) PVWebServer.shared.stopServers() } #endif // !targetEnvironment(macCatalyst) #endif // os(iOS) @IBAction func conflictsButtonTapped(_: Any) { displayConflictVC() } #if os(tvOS) @IBAction func searchButtonTapped(_ sender: Any) { let searchNavigationController = PVSearchViewController.createEmbeddedInNavigationController(gameLibrary: gameLibrary) present(searchNavigationController, animated: true) { () -> Void in } } #endif @IBAction func sortButtonTapped(_ sender: Any?) { if self.presentedViewController != nil { return; } sortOptionsTableView.reloadData() #if os(iOS) // Add done button to iPhone // iPad is a popover do no done button needed if traitCollection.userInterfaceIdiom != .pad || traitCollection.horizontalSizeClass == .compact || !(sender is UIBarButtonItem) { let navController = UINavigationController(rootViewController: sortOptionsTableViewController) sortOptionsTableViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(PVGameLibraryViewController.dismissVC)) present(navController, animated: true, completion: nil) } else { sortOptionsTableViewController.modalPresentationStyle = .popover sortOptionsTableViewController.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem sortOptionsTableViewController.popoverPresentationController?.sourceView = collectionView sortOptionsTableViewController.preferredContentSize = CGSize(width:300, height:sortOptionsTableView.contentSize.height); present(sortOptionsTableViewController, animated: true, completion: nil) } #else sortOptionsTableViewController.preferredContentSize = CGSize(width:675, height:sortOptionsTableView.contentSize.height); let pvc = TVFullscreenController(rootViewController:sortOptionsTableViewController) present(pvc, animated: true, completion: nil) #endif } @objc func dismissVC() { dismiss(animated: true, completion: nil) } lazy var reachability = try! Reachability() // MARK: - Filesystem Helpers @IBAction func getMoreROMs(_ sender: Any?) { do { try reachability.startNotifier() } catch { ELOG("Unable to start notifier") } #if os(iOS) // connected via wifi, let's continue let actionSheet = UIAlertController(title: "Select Import Source", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Cloud & Local Files", style: .default, handler: { _ in let extensions = [UTI.rom, UTI.artwork, UTI.savestate, UTI.zipArchive, UTI.sevenZipArchive, UTI.gnuZipArchive, UTI.image, UTI.jpeg, UTI.png, UTI.bios, UTI.data].map { $0.rawValue } // let documentMenu = UIDocumentMenuViewController(documentTypes: extensions, in: .import) // documentMenu.delegate = self // present(documentMenu, animated: true, completion: nil) let documentPicker = PVDocumentPickerViewController(documentTypes: extensions, in: .import) documentPicker.allowsMultipleSelection = true documentPicker.delegate = self self.present(documentPicker, animated: true, completion: nil) })) let webServerAction = UIAlertAction(title: "Web Server", style: .default, handler: { _ in self.startWebServer() }) actionSheet.addAction(webServerAction) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) reachability.whenReachable = { reachability in if reachability.connection == .wifi { webServerAction.isEnabled = true } else { webServerAction.isEnabled = false } } reachability.whenUnreachable = { _ in webServerAction.isEnabled = false } if let barButtonItem = sender as? UIBarButtonItem { actionSheet.popoverPresentationController?.barButtonItem = barButtonItem actionSheet.popoverPresentationController?.sourceView = collectionView } else if let button = sender as? UIButton { actionSheet.popoverPresentationController?.sourceView = collectionView actionSheet.popoverPresentationController?.sourceRect = view.convert(libraryInfoContainerView.convert(button.frame, to: view), to: collectionView) } actionSheet.preferredContentSize = CGSize(width: 300, height: 150) present(actionSheet, animated: true, completion: nil) (actionSheet as UIViewController).rx.deallocating.asObservable().bind { [weak self] in self?.reachability.stopNotifier() }.disposed(by: disposeBag) #else // tvOS defer { reachability.stopNotifier() } if reachability.connection != .wifi { let alert = UIAlertController(title: "Unable to start web server!", message: "Your device needs to be connected to a network to continue!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_: UIAlertAction) -> Void in })) present(alert, animated: true) { () -> Void in } } else { startWebServer() } #endif } func startWebServer() { // start web transfer service if PVWebServer.shared.startServers() { // show alert view showServerActiveAlert() } else { #if targetEnvironment(simulator) || targetEnvironment(macCatalyst) let message = "Check your network connection or settings and free up ports: 8080, 8081." #else let message = "Check your network connection or settings and free up ports: 80, 81." #endif let alert = UIAlertController(title: "Unable to start web server!", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_: UIAlertAction) -> Void in })) present(alert, animated: true) { () -> Void in } } } // MARK: - Game Library Management // TODO: It would be nice to move this and the importer-logic out of the ViewController at some point func handleLibraryMigration() { UserDefaults.standard.register(defaults: [PVRequiresMigrationKey: true]) if UserDefaults.standard.bool(forKey: PVRequiresMigrationKey) { let hud = MBProgressHUD.showAdded(to: view, animated: true)! gameLibrary.migrate() .observe(on: MainScheduler.instance) .subscribe(onNext: { event in switch event { case .starting: hud.isUserInteractionEnabled = false hud.mode = .indeterminate hud.labelText = "Migrating Game Library" hud.detailsLabelText = "Please be patient, this may take a while…" case .pathsToImport(let paths): hud.hide(true) _ = self.gameImporter.importFiles(atPaths: paths) } }, onError: { error in ELOG(error.localizedDescription) }, onCompleted: { hud.hide(true) UserDefaults.standard.set(false, forKey: PVRequiresMigrationKey) }) .disposed(by: disposeBag) } } fileprivate func showConflictsAlert() { let alert = UIAlertController(title: "Oops!", message: "There was a conflict while importing your game.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Let's go fix it!", style: .default, handler: { [unowned self] (_: UIAlertAction) -> Void in self.displayConflictVC() })) alert.addAction(UIAlertAction(title: "Nah, I'll do it later…", style: .cancel, handler: nil)) self.present(alert, animated: true) { () -> Void in } ILOG("Encountered conflicts, should be showing message") } fileprivate func displayConflictVC() { let conflictViewController = PVConflictViewController(conflictsController: updatesController) let navController = UINavigationController(rootViewController: conflictViewController) present(navController, animated: true) { () -> Void in } } @objc func handleCacheEmptied(_: NotificationCenter) { DispatchQueue.global(qos: .userInitiated).async(execute: { () -> Void in let database = RomDatabase.sharedInstance database.refresh() do { try database.writeTransaction { for game: PVGame in database.allGames { game.customArtworkURL = "" self.gameImporter?.getArtwork(forGame: game) } } } catch { ELOG("Failed to empty cache \(error.localizedDescription)") } DispatchQueue.main.async(execute: { () -> Void in RomDatabase.sharedInstance.refresh() }) }) } @objc func handleArchiveInflationFailed(_: Notification) { let alert = UIAlertController(title: "Failed to extract archive", message: "There was a problem extracting the archive. Perhaps the download was corrupt? Try downloading it again.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true) { () -> Void in } } private func longPressed(item: Section.Item, at indexPath: IndexPath, point: CGPoint) { let cell = collectionView!.cellForItem(at: indexPath)! let actionSheet = contextMenu(for: item, cell: cell, point: point) actionSheet.popoverPresentationController?.sourceView = cell actionSheet.popoverPresentationController?.sourceRect = cell.bounds present(actionSheet, animated: true) } #if os(iOS) @available(iOS 13.0, *) func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard useModernContextMenus, let cell = collectionView.cellForItem(at: indexPath), let item: Section.Item = try? collectionView.rx.model(at: indexPath) else { return nil } if let actionSheet = contextMenu(for: item, cell: cell, point: point) as? UIAlertControllerProtocol { return UIContextMenuConfiguration(identifier:nil) { return nil // use default } actionProvider: {_ in return actionSheet.convertToMenu() } } return nil } #endif private func contextMenu(for item: Section.Item, cell: UICollectionViewCell, point: CGPoint) -> UIViewController { switch item { case .game(let game): return contextMenu(for: game, sender: cell) case .favorites: let game: PVGame = (cell as! CollectionViewInCollectionViewCell).item(at: point)! return contextMenu(for: game, sender: cell) case .saves: let saveState: PVSaveState = (cell as! CollectionViewInCollectionViewCell).item(at: point)! return contextMenu(for: saveState) case .recents: let game: PVRecentGame = (cell as! CollectionViewInCollectionViewCell).item(at: point)! return contextMenu(for: game.game, sender: cell) } } private func showCoreOptions(forCore core: CoreOptional.Type, withTitle title:String) { let optionsVC = CoreOptionsViewController(withCore: core) optionsVC.title = title #if os(iOS) self.navigationController?.pushViewController(optionsVC, animated: true) #else let nav = UINavigationController(rootViewController: optionsVC) present(TVFullscreenController(rootViewController: nav), animated: true, completion: nil) #endif } private func contextMenu(for game: PVGame, sender: UIView) -> UIViewController { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheet.title = game.title // If game.system has multiple cores, add actions to manage if let system = game.system, system.cores.count > 1 { // If user has select a core for this game, actio to reset if let userPreferredCoreID = game.userPreferredCoreID { // Action to play for default core actionSheet.addAction(UIAlertAction(title: "Play", symbol:"gamecontroller", style: .default, handler: { [unowned self] _ in self.load(game, sender: sender, core: nil, saveState: nil) })) actionSheet.preferredAction = actionSheet.actions.last // Find the core for the current id let userSelectedCore = RomDatabase.sharedInstance.object(ofType: PVCore.self, wherePrimaryKeyEquals: userPreferredCoreID) let coreName = userSelectedCore?.projectName ?? "nil" // Add reset action actionSheet.addAction(UIAlertAction(title: "Reset default core selection (\(coreName))", symbol:"bolt.circle", style: .default, handler: { [unowned self] _ in let resetAlert = UIAlertController(title: "Reset core?", message: "Are you sure you want to reset \(game.title) to no longer default to use \(coreName)?", preferredStyle: .alert) resetAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) resetAlert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { _ in try! RomDatabase.sharedInstance.writeTransaction { game.userPreferredCoreID = nil } })) self.present(resetAlert, animated: true, completion: nil) })) } // Action to Open with... actionSheet.addAction(UIAlertAction(title: "Play with…", symbol: "ellipsis.circle", style: .default, handler: { [unowned self] _ in self.presentCoreSelection(forGame: game, sender: sender) })) } else { // Action to play for single core games actionSheet.addAction(UIAlertAction(title: "Play", symbol:"gamecontroller", style: .default, handler: { [unowned self] _ in self.load(game, sender: sender, core: nil, saveState: nil) })) actionSheet.preferredAction = actionSheet.actions.last } if let system = game.system, system.cores.count == 1, let pvcore = system.cores.first, let coreClass = NSClassFromString(pvcore.principleClass) as? CoreOptional.Type { actionSheet.addAction(UIAlertAction(title: "\(pvcore.projectName) options", symbol: "slider.horizontal.3", style: .default, handler: { (_: UIAlertAction) -> Void in self.showCoreOptions(forCore: coreClass, withTitle:pvcore.projectName) })) } actionSheet.addAction(UIAlertAction(title: "Game Info", symbol: "info.circle", style: .default, handler: { (_: UIAlertAction) -> Void in self.moreInfo(for: game) })) var favoriteTitle = "Favorite" var favoriteSymbol = "heart" if game.isFavorite { favoriteTitle = "Unfavorite" favoriteSymbol = "heart.fill" } actionSheet.addAction(UIAlertAction(title: favoriteTitle, symbol:favoriteSymbol, style: .default, handler: { (_: UIAlertAction) -> Void in self.toggleFavorite(for: game) })) actionSheet.addAction(UIAlertAction(title: "Rename", symbol: "rectangle.and.pencil.and.ellipsis", style: .default, handler: { (_: UIAlertAction) -> Void in self.renameGame(game) })) #if os(iOS) actionSheet.addAction(UIAlertAction(title: "Copy MD5 URL", symbol: "arrow.up.doc", style: .default, handler: { (_: UIAlertAction) -> Void in let md5URL = "provenance://open?md5=\(game.md5Hash)" UIPasteboard.general.string = md5URL let alert = UIAlertController(title: nil, message: "URL copied to clipboard.", preferredStyle: .alert) self.present(alert, animated: true) DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: { alert.dismiss(animated: true, completion: nil) }) })) actionSheet.addAction(UIAlertAction(title: "Choose Cover", symbol:"folder", style: .default) { [weak self] _ in self?.chooseCustomArtwork(for: game, sourceView: sender) }) if UIPasteboard.general.hasImages || UIPasteboard.general.hasURLs { actionSheet.addAction(UIAlertAction(title: "Paste Cover", symbol:"arrow.down.doc", style: .default, handler: { (_: UIAlertAction) -> Void in self.pasteCustomArtwork(for: game) })) } if !game.saveStates.isEmpty { actionSheet.addAction(UIAlertAction(title: "View Save States", symbol:"archivebox", style: .default, handler: { (_: UIAlertAction) -> Void in guard let saveStatesNavController = UIStoryboard(name: "SaveStates", bundle: nil).instantiateViewController(withIdentifier: "PVSaveStatesViewControllerNav") as? UINavigationController else { return } if let saveStatesViewController = saveStatesNavController.viewControllers.first as? PVSaveStatesViewController { saveStatesViewController.saveStates = game.saveStates saveStatesViewController.delegate = self } saveStatesNavController.modalPresentationStyle = .overCurrentContext #if os(iOS) if self.traitCollection.userInterfaceIdiom == .pad { saveStatesNavController.modalPresentationStyle = .formSheet } #endif #if os(tvOS) if #available(tvOS 11, *) { saveStatesNavController.modalPresentationStyle = .blurOverFullScreen } #endif self.present(saveStatesNavController, animated: true) })) } // conditionally show Restore Original Artwork if !game.originalArtworkURL.isEmpty, !game.customArtworkURL.isEmpty, game.originalArtworkURL != game.customArtworkURL { actionSheet.addAction(UIAlertAction(title: "Restore Cover", symbol:"photo", style: .default, handler: { (_: UIAlertAction) -> Void in try! PVMediaCache.deleteImage(forKey: game.customArtworkURL) try! RomDatabase.sharedInstance.writeTransaction { game.customArtworkURL = "" } let gameRef = ThreadSafeReference(to: game) DispatchQueue.global(qos: .userInitiated).async { let realm = try! Realm() guard let game = realm.resolve(gameRef) else { return // person was deleted } self.gameImporter?.getArtwork(forGame: game) } })) } actionSheet.addAction(UIAlertAction(title: "Share", symbol:"square.and.arrow.up", style: .default, handler: { (_: UIAlertAction) -> Void in self.share(for: game, sender: sender) })) #endif actionSheet.addAction(UIAlertAction(title: "Delete", symbol:"trash", style: .destructive, handler: { (_: UIAlertAction) -> Void in let alert = UIAlertController(title: "Delete \(game.title)", message: "Any save states and battery saves will also be deleted, are you sure?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (_: UIAlertAction) -> Void in // Delete from Realm do { try self.delete(game: game) } catch { self.presentError(error.localizedDescription) } })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) self.present(alert, animated: true) { () -> Void in } })) if actionSheet.preferredAction == nil { actionSheet.preferredAction = actionSheet.actions.first } actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) return actionSheet } private func contextMenu(for saveState: PVSaveState) -> UIViewController { let actionSheet = UIAlertController(title: "Delete this save state?", message: nil, preferredStyle: .alert) actionSheet.addAction(UIAlertAction(title: "Yes", style: .destructive) { [unowned self] _ in do { try PVSaveState.delete(saveState) } catch { self.presentError("Error deleting save state: \(error.localizedDescription)") } }) actionSheet.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil)) actionSheet.preferredAction = actionSheet.actions.last return actionSheet } func toggleFavorite(for game: PVGame) { gameLibrary.toggleFavorite(for: game) .observe(on: MainScheduler.instance) .subscribe(onCompleted: { self.collectionView?.reloadData() }, onError: { error in ELOG("Failed to toggle Favorite for game \(game.title)") }) .disposed(by: disposeBag) } func moreInfo(for game: PVGame) { #if os(iOS) performSegue(withIdentifier: "gameMoreInfoPageVCSegue", sender: game) #else performSegue(withIdentifier: "gameMoreInfoSegue", sender: game) #endif } func renameGame(_ game: PVGame) { let alert = UIAlertController(title: "Rename", message: "Enter a new name for \(game.title):", preferredStyle: .alert) alert.addTextField(configurationHandler: { (_ textField: UITextField) -> Void in textField.placeholder = game.title textField.text = game.title }) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_: UIAlertAction) -> Void in if let title = alert.textFields?.first?.text { guard !title.isEmpty else { self.presentError("Cannot set a blank title.") return } RomDatabase.sharedInstance.renameGame(game, toTitle: title) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true) { () -> Void in } } func delete(game: PVGame) throws { try RomDatabase.sharedInstance.delete(game: game) } #if os(iOS) private func chooseCustomArtwork(for game: PVGame, sourceView: UIView) { weak var weakSelf: PVGameLibraryViewController? = self let imagePickerActionSheet = UIAlertController(title: "Choose Artwork", message: "Choose the location of the artwork.\n\nUse Latest Photo: Use the last image in the camera roll.\nTake Photo: Use the camera to take a photo.\nChoose Photo: Use the camera roll to choose an image.", preferredStyle: .actionSheet) let cameraIsAvailable: Bool = UIImagePickerController.isSourceTypeAvailable(.camera) let photoLibraryIsAvaialble: Bool = UIImagePickerController.isSourceTypeAvailable(.photoLibrary) let cameraAction = UIAlertAction(title: "Take Photo", style: .default, handler: { action in self.gameForCustomArt = game let pickerController = UIImagePickerController() pickerController.delegate = weakSelf pickerController.allowsEditing = false pickerController.sourceType = .camera self.present(pickerController, animated: true) { () -> Void in } }) let libraryAction = UIAlertAction(title: "Choose Photo", style: .default, handler: { action in self.gameForCustomArt = game let pickerController = UIImagePickerController() pickerController.delegate = weakSelf pickerController.allowsEditing = false pickerController.sourceType = .photoLibrary self.present(pickerController, animated: true) { () -> Void in } }) let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) // swiftlint:disable:next empty_count if fetchResult.count > 0 { let lastPhoto = fetchResult.lastObject imagePickerActionSheet.addAction(UIAlertAction(title: "Use Latest Photo", style: .default, handler: { (action) in PHImageManager.default().requestImage(for: lastPhoto!, targetSize: CGSize(width: lastPhoto!.pixelWidth, height: lastPhoto!.pixelHeight), contentMode: .aspectFill, options: PHImageRequestOptions(), resultHandler: { (image, _) in let orientation: UIImage.Orientation = UIImage.Orientation(rawValue: (image?.imageOrientation)!.rawValue)! let lastPhoto2 = UIImage(cgImage: image!.cgImage!, scale: CGFloat(image!.scale), orientation: orientation) lastPhoto!.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in do { try PVMediaCache.writeImage(toDisk: lastPhoto2, withKey: (input?.fullSizeImageURL!.absoluteString)!) try RomDatabase.sharedInstance.writeTransaction { game.customArtworkURL = (input?.fullSizeImageURL!.absoluteString)! } } catch { ELOG("Failed to set custom artwork URL for game \(game.title) \n \(error.localizedDescription)") } } }) })) } if cameraIsAvailable || photoLibraryIsAvaialble { if cameraIsAvailable { imagePickerActionSheet.addAction(cameraAction) } if photoLibraryIsAvaialble { imagePickerActionSheet.addAction(libraryAction) } } imagePickerActionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in imagePickerActionSheet.dismiss(animated: true, completion: nil) })) presentActionSheetViewControllerForPopoverPresentation(imagePickerActionSheet, sourceView: sourceView) } private func presentActionSheetViewControllerForPopoverPresentation(_ alertController: UIViewController, sourceView: UIView) { if traitCollection.userInterfaceIdiom == .pad { alertController.popoverPresentationController?.sourceView = sourceView alertController.popoverPresentationController?.sourceRect = sourceView.bounds } present(alertController, animated: true) } private func pasteCustomArtwork(for game: PVGame) { let pb = UIPasteboard.general var pastedImageMaybe: UIImage? = pb.image let pastedURL: URL? = pb.url if pastedImageMaybe == nil { if let pastedURL = pastedURL { do { let data = try Data(contentsOf: pastedURL) pastedImageMaybe = UIImage(data: data) } catch { ELOG("Failed to read pasteboard URL: \(error.localizedDescription)") } } else { ELOG("No image or image url in pasteboard") return } } if let pastedImage = pastedImageMaybe { var key: String if let pastedURL = pastedURL { key = pastedURL.lastPathComponent } else { key = UUID().uuidString } do { try PVMediaCache.writeImage(toDisk: pastedImage, withKey: key) try RomDatabase.sharedInstance.writeTransaction { game.customArtworkURL = key } } catch { ELOG("Failed to set custom artwork URL for game \(game.title).\n\(error.localizedDescription)") } } else { ELOG("No pasted image") } } #endif func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, referenceSizeForHeaderInSection _: Int) -> CGSize { #if os(tvOS) return CGSize(width: view.bounds.size.width, height: 40) #else return CGSize(width: view.bounds.size.width, height: 40) #endif } // MARK: - Image Picker Delegate #if os(iOS) func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) guard let gameForCustomArt = self.gameForCustomArt else { ELOG("gameForCustomArt pointer was null.") return } dismiss(animated: true) { () -> Void in } let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage if let image = image, let scaledImage = image.scaledImage(withMaxResolution: Int(PVThumbnailMaxResolution)), let imageData = scaledImage.jpegData(compressionQuality: 0.85) { let hash = (imageData as NSData).md5Hash do { try PVMediaCache.writeData(toDisk: imageData, withKey: hash) try RomDatabase.sharedInstance.writeTransaction { gameForCustomArt.customArtworkURL = hash } } catch { ELOG("Failed to set custom artwork for game \(gameForCustomArt.title)\n\(error.localizedDescription)") } } self.gameForCustomArt = nil } func imagePickerControllerDidCancel(_: UIImagePickerController) { dismiss(animated: true) { () -> Void in } gameForCustomArt = nil } #endif } // MARK: Database Migration extension PVGameLibraryViewController { @objc public func databaseMigrationStarted(_: Notification) { let hud = MBProgressHUD.showAdded(to: view, animated: true)! hud.isUserInteractionEnabled = false hud.mode = .indeterminate hud.labelText = "Migrating Game Library" hud.detailsLabelText = "Please be patient, this may take a while…" } @objc public func databaseMigrationFinished(_: Notification) { MBProgressHUD.hide(for: view!, animated: true) } } // MARK: UIDocumentMenuDelegate #if os(iOS) extension PVGameLibraryViewController: UIDocumentMenuDelegate { func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self documentPicker.popoverPresentationController?.sourceView = view present(documentMenu, animated: true, completion: nil) } func documentMenuWasCancelled(_: UIDocumentMenuViewController) { ILOG("DocumentMenu was cancelled") } } // MARK: UIDocumentPickerDelegate extension PVGameLibraryViewController: UIDocumentPickerDelegate { func documentPicker(_: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { // If directory, map out sub directories if folder let urls: [URL] = urls.compactMap { (url) -> [URL]? in if url.hasDirectoryPath { ILOG("Trying to import directory \(url.path). Scanning subcontents") do { _ = url.startAccessingSecurityScopedResource() let subFiles = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey, URLResourceKey.parentDirectoryURLKey, URLResourceKey.fileSecurityKey], options: .skipsHiddenFiles) url.stopAccessingSecurityScopedResource() return subFiles } catch { ELOG("Subdir scan failed. \(error)") return [url] } } else { return [url] } }.joined().map { $0 } let sortedUrls = PVEmulatorConfiguration.sortImportURLs(urls: urls) let importPath = PVEmulatorConfiguration.Paths.romsImportPath sortedUrls.forEach { url in defer { url.stopAccessingSecurityScopedResource() } // Doesn't seem we need access in dev builds? _ = url.startAccessingSecurityScopedResource() // if access { let fileName = url.lastPathComponent let destination: URL destination = importPath.appendingPathComponent(fileName, isDirectory: url.hasDirectoryPath) do { // Since we're in UIDocumentPickerModeImport, these URLs are temporary URLs so a move is what we want try FileManager.default.moveItem(at: url, to: destination) ILOG("Document picker to moved file from \(url.path) to \(destination.path)") } catch { ELOG("Failed to move file from \(url.path) to \(destination.path)") } } // Test for moving directory subcontents // if #available(iOS 9.0, *) { // if url.hasDirectoryPath { // ILOG("Tryingn to import directory \(url.path)") // let subFiles = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) // for subFile in subFiles { // _ = subFile.startAccessingSecurityScopedResource() // try FileManager.default.moveItem(at: subFile, to: destination) // subFile.stopAccessingSecurityScopedResource() // ILOG("Moved \(subFile.path) to \(destination.path)") // } // } else { // try FileManager.default.moveItem(at: url, to: destination) // } // } else { // try FileManager.default.moveItem(at: url, to: destination) // } // } catch { // ELOG("Failed to move file from \(url.path) to \(destination.path)") // } // } else { // ELOG("Wasn't granded access to \(url.path)") // } } func documentPickerWasCancelled(_: UIDocumentPickerViewController) { ILOG("Document picker was cancelled") } } #endif #if os(iOS) extension PVGameLibraryViewController: UIImagePickerControllerDelegate, SFSafariViewControllerDelegate {} #endif // MARK: Sort Options extension PVGameLibraryViewController: UITableViewDataSource { func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Sort By" case 1: return "View Options" default: return nil } } func numberOfSections(in _: UITableView) -> Int { return 2 } func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? SortOptions.count : 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // NOTE: cell setup is done in willDisplayCell if indexPath.section == 0 { return tableView.dequeueReusableCell(withIdentifier: "sortCell", for: indexPath) } else if indexPath.section == 1 { return tableView.dequeueReusableCell(withIdentifier: "viewOptionsCell", for: indexPath) } else { fatalError("Invalid section") } } } extension PVGameLibraryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { #if os(tvOS) cell.layer.cornerRadius = 12 #endif if indexPath.section == 0 { let sortOption = SortOptions.allCases[indexPath.row] cell.textLabel?.text = sortOption.description cell.accessoryType = indexPath.row == (try! currentSort.value()).row ? .checkmark : .none } else if indexPath.section == 1 { switch indexPath.row { case 0: cell.textLabel?.text = "Show Game Titles" cell.accessoryType = PVSettingsModel.shared.showGameTitles ? .checkmark : .none case 1: cell.textLabel?.text = "Show Recently Played Games" cell.accessoryType = PVSettingsModel.shared.showRecentGames ? .checkmark : .none case 2: cell.textLabel?.text = "Show Recent Save States" cell.accessoryType = PVSettingsModel.shared.showRecentSaveStates ? .checkmark : .none case 3: cell.textLabel?.text = "Show Game Badges" cell.accessoryType = PVSettingsModel.shared.showGameBadges ? .checkmark : .none default: fatalError("Invalid row") } } else { fatalError("Invalid section") } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { currentSort.onNext(SortOptions.optionForRow(UInt(indexPath.row))) //dont call reloadSections or we will loose focus on tvOS //tableView.reloadSections([indexPath.section], with: .automatic) for row in 0..<(self.tableView(tableView, numberOfRowsInSection: indexPath.section)) { let indexPath = IndexPath(row:row, section:indexPath.section) self.tableView(tableView, willDisplay:tableView.cellForRow(at:indexPath)!, forRowAt:indexPath) } //dismiss(animated: true, completion: nil) } else if indexPath.section == 1 { switch indexPath.row { case 0: PVSettingsModel.shared.showGameTitles = !PVSettingsModel.shared.showGameTitles case 1: showRecentGames.onNext(!PVSettingsModel.shared.showRecentGames) case 2: showSaveStates.onNext(!PVSettingsModel.shared.showRecentSaveStates) case 3: PVSettingsModel.shared.showGameBadges = !PVSettingsModel.shared.showGameBadges default: fatalError("Invalid row") } //dont call reloadRows or we will loose focus on tvOS //tableView.reloadRows(at: [indexPath], with:.automatic) self.tableView(tableView, willDisplay:tableView.cellForRow(at:indexPath)!, forRowAt:indexPath) collectionView?.reloadData() } } } extension PVGameLibraryViewController: PVSaveStatesViewControllerDelegate { func saveStatesViewControllerDone(_: PVSaveStatesViewController) { dismiss(animated: true, completion: nil) } func saveStatesViewControllerCreateNewState(_: PVSaveStatesViewController, completion _: @escaping SaveCompletion) { // TODO: Should be a different protocol for loading / saving states then really. assertionFailure("Shouldn't be here. Can't create save states in game library") } func saveStatesViewControllerOverwriteState(_: PVSaveStatesViewController, state _: PVSaveState, completion _: @escaping SaveCompletion) { assertionFailure("Shouldn't be here. Can't create save states in game library") } func saveStatesViewController(_: PVSaveStatesViewController, load state: PVSaveState) { dismiss(animated: true, completion: nil) load(state.game, sender: self, core: state.core, saveState: state) } } // Keyboard shortcuts extension PVGameLibraryViewController { // MARK: - Keyboard actions public override var keyCommands: [UIKeyCommand]? { var sectionCommands = [UIKeyCommand]() /* TODO: .reserveCapacity(sectionInfo.count + 2) */ // Simulator Command + number has shorcuts already #if targetEnvironment(simulator) let flags: UIKeyModifierFlags = [.control, .command] #else let flags: UIKeyModifierFlags = .command #endif if let dataSource = collectionView?.rx.dataSource.forwardToDelegate() as? CollectionViewSectionedDataSource<Section> { for (i, section) in dataSource.sectionModels.enumerated() { let input = "\(i)" let title = section.header let command = UIKeyCommand(input: input, modifierFlags: flags, action: #selector(PVGameLibraryViewController.selectSection(_:)), discoverabilityTitle: title) sectionCommands.append(command) } } #if os(tvOS) if focusedGame != nil { let toggleFavoriteCommand = UIKeyCommand(input: "=", modifierFlags: flags, action: #selector(PVGameLibraryViewController.toggleFavoriteCommand), discoverabilityTitle: "Toggle Favorite") sectionCommands.append(toggleFavoriteCommand) let showMoreInfo = UIKeyCommand(input: "i", modifierFlags: flags, action: #selector(PVGameLibraryViewController.showMoreInfoCommand), discoverabilityTitle: "More info…") sectionCommands.append(showMoreInfo) let renameCommand = UIKeyCommand(input: "r", modifierFlags: flags, action: #selector(PVGameLibraryViewController.renameCommand), discoverabilityTitle: "Rename…") sectionCommands.append(renameCommand) let deleteCommand = UIKeyCommand(input: "x", modifierFlags: flags, action: #selector(PVGameLibraryViewController.deleteCommand), discoverabilityTitle: "Delete…") sectionCommands.append(deleteCommand) let sortCommand = UIKeyCommand(input: "s", modifierFlags: flags, action: #selector(PVGameLibraryViewController.sortButtonTapped(_:)), discoverabilityTitle: "Sorting") sectionCommands.append(sortCommand) } #elseif os(iOS) let findCommand = UIKeyCommand(input: "f", modifierFlags: flags, action: #selector(PVGameLibraryViewController.selectSearch(_:)), discoverabilityTitle: "Find…") sectionCommands.append(findCommand) let sortCommand = UIKeyCommand(input: "s", modifierFlags: flags, action: #selector(PVGameLibraryViewController.sortButtonTapped(_:)), discoverabilityTitle: "Sorting") sectionCommands.append(sortCommand) let settingsCommand = UIKeyCommand(input: ",", modifierFlags: flags, action: #selector(PVGameLibraryViewController.settingsCommand), discoverabilityTitle: "Settings") sectionCommands.append(settingsCommand) #endif return sectionCommands } @objc func selectSearch(_: UIKeyCommand) { #if os(iOS) navigationItem.searchController?.isActive = true #endif } @objc func selectSection(_ sender: UIKeyCommand) { if let input = sender.input, let section = Int(input) { collectionView?.scrollToItem(at: IndexPath(item: 0, section: section), at: .top, animated: true) } } override var canBecomeFirstResponder: Bool { return true } #if os(tvOS) @objc func showMoreInfoCommand() { guard let focusedGame = focusedGame else { return } moreInfo(for: focusedGame) } @objc func toggleFavoriteCommand() { guard let focusedGame = focusedGame else { return } toggleFavorite(for: focusedGame) } @objc func renameCommand() { guard let focusedGame = focusedGame else { return } renameGame(focusedGame) } @objc func deleteCommand() { guard let focusedGame = focusedGame else { return } promptToDeleteGame(focusedGame) } func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with _: UIFocusAnimationCoordinator) { focusedGame = getFocusedGame(in: collectionView, focusContext: context) } private func getFocusedGame(in collectionView: UICollectionView, focusContext context: UICollectionViewFocusUpdateContext) -> PVGame? { guard let indexPath = context.nextFocusedIndexPath, let item: Section.Item = try? collectionView.rx.model(at: indexPath) else { return nil } switch item { case .game(let game): return game case .favorites(let games): if let outerCell = collectionView.cellForItem(at: indexPath) as? CollectionViewInCollectionViewCell<PVGame>, let innerCell = context.nextFocusedItem as? UICollectionViewCell, let innerIndexPath = outerCell.internalCollectionView.indexPath(for: innerCell) { return games[innerIndexPath.row] } return nil case .recents(let games): if let outerCell = collectionView.cellForItem(at: indexPath) as? CollectionViewInCollectionViewCell<PVRecentGame>, let innerCell = context.nextFocusedItem as? UICollectionViewCell, let innerIndexPath = outerCell.internalCollectionView.indexPath(for: innerCell) { return games[innerIndexPath.row].game } return nil case .saves: return nil } } #endif #if os(iOS) @objc func settingsCommand() { performSegue(withIdentifier: "SettingsSegue", sender: self) } #endif } #if os(iOS) extension PVGameLibraryViewController: UIPopoverControllerDelegate {} #endif extension PVGameLibraryViewController: GameLibraryCollectionViewDelegate { func promptToDeleteGame(_ game: PVGame, completion: ((Bool) -> Void)? = nil) { let alert = UIAlertController(title: "Delete \(game.title)", message: "Any save states and battery saves will also be deleted, are you sure?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (_: UIAlertAction) -> Void in // Delete from Realm do { try self.delete(game: game) completion?(true) } catch { completion?(false) self.presentError(error.localizedDescription) } })) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { (_: UIAlertAction) -> Void in completion?(false) })) present(alert, animated: true) { () -> Void in } } } // Helper function inserted by Swift 4.2 migrator. #if os(iOS) private func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (key.rawValue, value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue } #endif private extension UIImage { func resize(to size:CGSize) -> UIImage { var size = size if size.height == 0 {size.height = floor(size.width * self.size.height / self.size.width)} if size.width == 0 {size.width = floor(size.height * self.size.width / self.size.height)} return UIGraphicsImageRenderer(size:size).image { (context) in self.draw(in: CGRect(origin:.zero, size:size)) } } } // MARK: ControllerButtonPress #if os(iOS) extension PVGameLibraryViewController: ControllerButtonPress { func controllerButtonPress(_ type: ButtonType) { switch type { case .select: select() case .up: moveVert(-1) case .down: moveVert(+1) case .left: moveHorz(-1) case .right: moveHorz(+1) case .options: options() case .menu: menu() case .x: settingsCommand() // case .y: // Bad merge? // longPress() case .r1: getMoreROMs(self) case .l1: sortButtonTapped(self) default: break } } private func moveVert(_ dir:Int) { guard var indexPath = _selectedIndexPath else { return select(IndexPath(item:0, section:0)) } indexPath.item = indexPath.item + dir * itemsPerRow(indexPath) if indexPath.item < 0 { indexPath.section = indexPath.section-1 indexPath.item = collectionView!.numberOfItems(inSection: indexPath.section)-1 } if indexPath.item >= collectionView!.numberOfItems(inSection: indexPath.section) { indexPath.section = indexPath.section+1 indexPath.item = 0 } if indexPath.section >= 0 && indexPath.section < collectionView!.numberOfSections { select(indexPath) } } private func moveHorz(_ dir:Int) { guard var indexPath = _selectedIndexPath else { return select(IndexPath(item:0, section:0)) } indexPath.item = indexPath.item + dir select(indexPath) } // access cell(s) in nested collectionView private func getNestedCollectionView(_ indexPath:IndexPath) -> UICollectionView? { if let cell = collectionView?.cellForItem(at: IndexPath(item: 0, section: indexPath.section)), let cv = (cell as? CollectionViewInCollectionViewCell<PVGame>)?.internalCollectionView ?? (cell as? CollectionViewInCollectionViewCell<PVSaveState>)?.internalCollectionView ?? (cell as? CollectionViewInCollectionViewCell<PVRecentGame>)?.internalCollectionView { return cv } return nil } private func itemsPerRow(_ indexPath:IndexPath) -> Int { guard let rect = collectionView!.layoutAttributesForItem(at: IndexPath(item: 0, section: indexPath.section))?.frame else { return 1 } // TODO: this math is probably wrong let layout = (collectionView!.collectionViewLayout as! UICollectionViewFlowLayout) let space = layout.minimumInteritemSpacing let width = collectionView!.bounds.width // + space // - (layout.sectionInset.left + layout.sectionInset.right) let n = width / (rect.width + space) return max(1, Int(n)) } // just hilight (with a cheesy overlay) the item private func select(_ indexPath:IndexPath?) { guard var indexPath = indexPath else { _selectedIndexPath = nil _selectedIndexPathView?.frame = .zero return } // TODO: this is a hack, a cell should be selected by setting isSelected and the cell class should handle it indexPath.section = max(0, min(collectionView!.numberOfSections-1,indexPath.section)) let rect:CGRect if let cv = getNestedCollectionView(indexPath) { collectionView?.scrollToItem(at: IndexPath(item:0, section: indexPath.section), at: [], animated: false) indexPath.item = max(0, min(cv.numberOfItems(inSection:0)-1,indexPath.item)) let idx = IndexPath(item:indexPath.item, section:0) cv.scrollToItem(at:idx , at:[], animated: false) rect = cv.convert(cv.layoutAttributesForItem(at:idx)?.frame ?? .zero, to: collectionView) } else { indexPath.item = max(0, min(collectionView!.numberOfItems(inSection:indexPath.section)-1,indexPath.item)) collectionView?.scrollToItem(at: indexPath, at: [], animated: false) rect = collectionView!.layoutAttributesForItem(at: indexPath)?.frame ?? .zero } _selectedIndexPath = indexPath // TODO: this is a hack, a cell should be selected by setting isSelected and the cell class should handle it if !rect.isEmpty { _selectedIndexPathView = _selectedIndexPathView ?? UIView() collectionView!.addSubview(_selectedIndexPathView) collectionView!.bringSubviewToFront(_selectedIndexPathView) _selectedIndexPathView.frame = rect.insetBy(dx: -4.0, dy: -4.0) _selectedIndexPathView.backgroundColor = navigationController?.view.tintColor _selectedIndexPathView.alpha = 0.5 _selectedIndexPathView.layer.cornerRadius = 16.0 } } // actually *push* the selected item private func select() { guard let indexPath = _selectedIndexPath else { return } if let collectionView = getNestedCollectionView(indexPath) { let indexPath = IndexPath(item: indexPath.item, section:0) collectionView.delegate?.collectionView?(collectionView, didSelectItemAt: indexPath) } else { collectionView!.delegate?.collectionView?(collectionView!, didSelectItemAt: indexPath) } } private func contextMenu(for indexPath:IndexPath?) -> UIViewController? { guard var indexPath = indexPath else { return nil } if let _ = getNestedCollectionView(indexPath) { indexPath = IndexPath(item:0, section:indexPath.section) } if let item: Section.Item = try? collectionView!.rx.model(at: indexPath), let cell = collectionView!.cellForItem(at: indexPath) { return contextMenu(for: item, cell: cell, point: _selectedIndexPathView.center) } return nil } private func menu() { if let menu = contextMenu(for: _selectedIndexPath) { present(menu, animated: true) } } private func options() { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if _selectedIndexPath != nil { // get the title of the game from the contextMenu! if let menu = contextMenu(for: _selectedIndexPath), let title = menu.title, !title.isEmpty { actionSheet.addAction(UIAlertAction(title: "Play \(title)", symbol:"gamecontroller", style: .default, handler: { _ in self.select() })) } } actionSheet.addAction(UIAlertAction(title: "Settings", symbol:"gear", style: .default, handler: { _ in self.settingsCommand() })) actionSheet.addAction(UIAlertAction(title: "Sort Options", symbol:"list.bullet", style: .default, handler: { _ in self.sortButtonTapped(nil) })) actionSheet.addAction(UIAlertAction(title: "Add ROMs", symbol:"plus", style: .default, handler: { _ in self.getMoreROMs(nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) actionSheet.preferredAction = actionSheet.actions.first present(actionSheet, animated: true) } } #endif
45.351137
321
0.622737
2f0570438cf2459c9ba8f0781b6419f21027bb9e
2,868
// // WWContainerAnimationContentView.swift // WWDC // // Created by Maxim Eremenko on 4/1/17. // Copyright © 2017 Maxim Eremenko. All rights reserved. // import UIKit class WWContainerAnimationContentView: UIView { let animator = WWPlaneAnimator() let planeImageView = UIImageView() let finalImageView = UIImageView() } internal extension WWContainerAnimationContentView { func animatePlane(completion: CodeBlock) { if planeImageView.superview == nil { self.addSubview(planeImageView) planeImageView.image = UIImage(named: "plane") } self.bringSubview(toFront: planeImageView) let size = WWFinalConstants.planeSize let origin = WWFinalConstants.startPoint planeImageView.frame = CGRect(origin: origin, size: size) let startPoint = WWFinalConstants.startPoint animator.animate(view: planeImageView, startPoint: startPoint, duration: WWFinalConstants.planeAnimationDuration) DispatchBlockAfter(delay: WWFinalConstants.completionDuration) { completion?() } } func animatedFinalScene(completion: CodeBlock?) { if finalImageView.superview == nil { self.addSubview(finalImageView) finalImageView.image = UIImage(named: "final_header_2") } self.bringSubview(toFront: finalImageView) let startFrame = CGRect(origin: WWContainerConstants.childFrame.origin, size: WWContainerConstants.collectionSize) let endFrame = CGRect(origin: .zero, size: WWContainerConstants.collectionSize) finalImageView.frame = startFrame DispatchBlockToMainQueue { UIView.animate(withDuration: WWFinalConstants.sceneAnimationDuration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: .curveEaseOut, animations: { self.finalImageView.frame = endFrame }) { (finished) in completion??() } } } func dissmissAnimatedViews(completion: CodeBlock?) { DispatchBlockToMainQueue { UIView.animate(withDuration: WWFinalConstants.dismissDuration, animations: { self.finalImageView.center = WWFinalConstants.dismissScenePoint }) { (finished) in self.finalImageView.removeFromSuperview() self.planeImageView.removeFromSuperview() completion??() } } } }
32.590909
91
0.575662
e81c4fe468b21261533d00842e44b5de3cefe7cd
897
// // Copyright 2021 New Vector Ltd // // 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 class SpaceCreationMatrixItemChooserViewProvider: MatrixItemChooserCoordinatorViewProvider { @available(iOS 14, *) func view(with viewModel: MatrixItemChooserViewModelType.Context) -> AnyView { return AnyView(SpaceCreationMatrixItemChooser(viewModel: viewModel)) } }
35.88
92
0.759197
bf610a9a582eb9299cdddf0d30bc411f06a7df77
1,651
// // MeSection0TableViewCell.swift // XMPP_iOS // // Created by 澳蜗科技 on 2017/10/20. // Copyright © 2017年 AnswerXu. All rights reserved. // import UIKit let meSection0CellIdent = "meSection0CellIdent" class MeSection0TableViewCell: UITableViewCell { private lazy var codeImageView : UIImageView = { let imageView = UIImageView.init(image: #imageLiteral(resourceName: "setting_myQR")) imageView.sizeToFit() return imageView }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) selectionStyle = .none imageView?.layer.cornerRadius = 5 imageView?.clipsToBounds = true textLabel?.font = UIFont.systemFont(ofSize: 15) textLabel?.textColor = UIColor.black detailTextLabel?.font = UIFont.systemFont(ofSize: 13) detailTextLabel?.textColor = UIColor.black self.contentView.addSubview(codeImageView) self.accessoryType = .disclosureIndicator } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() self.imageView?.size(60, height: 60).centerY(self.height * 0.5) self.textLabel?.x((self.imageView?.rightX)! + 10).y((self.imageView?.y)! + 10) self.detailTextLabel?.x((self.textLabel?.x)!).bottomY((self.imageView?.bottomY)! - 10) self.codeImageView.snp.makeConstraints { (make) in make.right.equalTo(-5) make.centerY.equalTo(self.height * 0.5) } } }
33.693878
94
0.653543
622b6d6d56bbe12f2cf89a04859992c4e4626cec
4,120
// // AppDelegate.swift // Flix // // Created by Pedro Sandoval Segura on 6/15/16. // Copyright © 2016 Pedro Sandoval Segura. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) let storyboard = UIStoryboard(name: "Main", bundle: nil) let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController nowPlayingViewController.endpoint = "now_playing" nowPlayingNavigationController.tabBarItem.title = "Now Playing" nowPlayingNavigationController.tabBarItem.image = UIImage(named: "now_playingpng") let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController topRatedViewController.endpoint = "top_rated" topRatedNavigationController.tabBarItem.title = "Top Rated" topRatedNavigationController.tabBarItem.image = UIImage(named: "top_ratedpng") let upcomingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController let upcomingViewController = upcomingNavigationController.topViewController as! MoviesViewController upcomingViewController.endpoint = "upcoming" upcomingNavigationController.tabBarItem.title = "Upcoming" upcomingNavigationController.tabBarItem.image = UIImage(named: "upcomingpng") let tabBarController = UITabBarController() tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController, upcomingNavigationController] tabBarController.tabBar.barTintColor = UIColor.clearColor() window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
54.210526
285
0.76068
4abae129c18fe1f8039b3d87825438358b70755a
2,763
// // ViewController.swift // OnTheMap // // Created by Matthias Wagner on 10.12.17. // Copyright © 2017 Michael Wagner. All rights reserved. // import UIKit import PKHUD import Result import ReactiveSwift import ReactiveCocoa import SimpleButton class LoginViewController: UIViewController, KeyboardNotificationProtocol, DesignableButtonProtocol { // MARK: - IBOutlets @IBOutlet weak var loginButton: DesignableButton! @IBOutlet weak var emailTextfield: UITextField! @IBOutlet weak var passwordTextfield: UITextField! // MARK: - KeyboardLinkedVC Property var lowestViewOverTheKeyboard: UIView? // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() /// KeyboardNotificationProtocol lowestViewOverTheKeyboard = loginButton bindViewOnKeyboardNotifications() /// DesignableButtonProtocol setupDesignableButton(loginButton) disableButton(loginButton, untilTextFieldNotEmpty: [emailTextfield, passwordTextfield]) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardOnTab)) view.addGestureRecognizer(tap) } // MARK: - Navigation private func goToMain() { let mainTabbarViewController: UINavigationController = UIStoryboard(.main).instantiateViewController() setRootViewController(mainTabbarViewController) } // MARK: - IBActions @IBAction func onSignIn(_ sender: Any) { guard let email = emailTextfield.text, !email.isEmpty, let password = passwordTextfield.text, !password.isEmpty else { HUD.flash(.error, delay: 0.5) return } login(credentials: (email, password)) } @IBAction func onSignUp(_ sender: Any) { let url = API.signUp.url UIApplication.shared.open(url, options: [:]) } // MARK: - Login private func login(credentials: LoginCredentials) { loginButton.isLoading = true UserController.shared.login.apply(credentials).startWithResult { [weak self] (result) in guard let `self` = self else { return } self.loginButton.isLoading = false switch result { case .success(_): HUD.flash(.success, delay: 0.5) self.goToMain() case .failure(let error): if case .producerFailed(let error) = error { HUD.flash(.label(error.localizedError), delay: 1.0) } else { HUD.flash(.error, delay: 0.5) } } } } // MARK: - Keyboard @objc private func hideKeyboardOnTab() { view.endEditing(true) } }
26.825243
116
0.636989
dde33b5e96c78a6fb99e7cc978f3b7b24defbf72
480
// // SearchSuggestion.swift // iMarvel // // Created by Ricardo Casanova on 17/12/2018. // Copyright © 2018 Wallapop. All rights reserved. // import Foundation import RealmSwift class SearchSuggestion: Object { @objc dynamic var suggestionId: String? @objc dynamic var suggestion: String = "" @objc dynamic var timestamp: TimeInterval = NSDate().timeIntervalSince1970 override class func primaryKey() -> String? { return "suggestionId" } }
22.857143
78
0.695833
03e5e8d78bac7666c15a2227f22d60b3be6e6c75
1,469
// Copyright 2022 Itty Bitty Apps Pty Ltd. See LICENSE file. import Foundation struct GitHubActionsFormatStyle: FormatStyle { let pathsRelativeTo: String init(pathsRelativeTo: String?) { self.pathsRelativeTo = pathsRelativeTo ?? "" } /// Creates a `FormatOutput` instance from `value`. func format(_ value: Diagnostic) -> String { let severity: String switch value.severity { case .error: severity = "error" case .warning: severity = "warning" case .info: severity = "notice" default: severity = "debug" } let file = value.location.path.hasPrefix(pathsRelativeTo) ? value.location.path.dropFirst(pathsRelativeTo.count) : value.location.path.suffix(from: value.location.path.startIndex) let line = value.location.range.start.line let column = value.location.range.start.column return "::\(severity) file=\(file),line=\(line),col=\(column)::\(value.message)" } /// If the format allows selecting a locale, returns a copy of this format with the new locale set. Default implementation returns an unmodified self. func locale(_ locale: Locale) -> Self { self } } extension FormatStyle where Self == GitHubActionsFormatStyle { static func githubActions(pathsRelativeTo: String? = nil) -> Self { Self(pathsRelativeTo: pathsRelativeTo) } }
31.934783
154
0.640572
1c42113d87988deb0ef21aab3ec05e7fed26cac7
2,333
// // AppDelegate.swift // MovieList // // Created by Leonardo Saragiotto on 1/19/17. // Copyright © 2017 Leonardo Saragiotto. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().backgroundColor = UIColor.clear UINavigationBar.appearance().isTranslucent = true return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.745098
285
0.750107
79c902cc3fdd5a33de496e4310a2988d32d90ca1
2,877
public class CastExpression: Expression { public var exp: Expression { didSet { oldValue.parent = nil; exp.parent = self } } public var type: SwiftType public var isOptionalCast: Bool public override var subExpressions: [Expression] { [exp] } public override var description: String { "\(exp) \(isOptionalCast ? "as?" : "as") \(type)" } public override var requiresParens: Bool { true } public init(exp: Expression, type: SwiftType, isOptionalCast: Bool = true) { self.exp = exp self.type = type self.isOptionalCast = isOptionalCast super.init() exp.parent = self } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) exp = try container.decodeExpression(forKey: .exp) type = try container.decode(SwiftType.self, forKey: .type) isOptionalCast = try container.decode(Bool.self, forKey: .isOptionalCast) try super.init(from: container.superDecoder()) exp.parent = self } @inlinable public override func copy() -> CastExpression { CastExpression(exp: exp.copy(), type: type).copyTypeAndMetadata(from: self) } @inlinable public override func accept<V: ExpressionVisitor>(_ visitor: V) -> V.ExprResult { visitor.visitCast(self) } public override func isEqual(to other: Expression) -> Bool { switch other { case let rhs as CastExpression: return self == rhs default: return false } } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeExpression(exp, forKey: .exp) try container.encode(type, forKey: .type) try container.encode(isOptionalCast, forKey: .isOptionalCast) try super.encode(to: container.superEncoder()) } public static func == (lhs: CastExpression, rhs: CastExpression) -> Bool { if lhs === rhs { return true } return lhs.exp == rhs.exp && lhs.type == rhs.type && lhs.isOptionalCast == rhs.isOptionalCast } private enum CodingKeys: String, CodingKey { case exp case type case isOptionalCast } } public extension Expression { @inlinable var asCast: CastExpression? { cast() } } extension CastExpression { public func copyTypeAndMetadata(from other: CastExpression) -> Self { _ = (self as Expression).copyTypeAndMetadata(from: other) self.isOptionalCast = other.isOptionalCast return self } }
27.663462
85
0.594717
f559fb0ed7668f2415c7c8027c5871dad9d2f709
263
/** Defines an HTTP endpoint. */ struct HTTPEndpoint: HTTPRequestable { let method: HTTPMethodType let path: String let headerParameters: HTTPHeaderParameters let queryParameters: HTTPQueryParameters let bodyParameters: HTTPBodyParameters }
23.909091
46
0.764259
383fe77e4b3731e5fdae53d2705d3d0be341cc64
13,948
/// // DemoApp // // Copyright © 2018 mkerekes. All rights reserved. // import IosCore import UIKit class DemoControlsStyle: ControlsProvider { var popupStyle: PopUpViewStyle = DemoPopUpViewStyle() var roundedImageView: RoundedImageViewStyle = DemoRoundedImageViewStyle() var roundedButton: RoundedButtonStyle = DemoRoundedButtonStyle() var roundedActionButton: RoundedButtonStyle = DemoRoundedActionButtonStyle() var toastMessage: ToastStyle = DemoToastStyle() var linkView: LinkViewStyle = DemoLinkViewStyle() var shareView: ShareViewStyle = DemoShareViewStyle() var chatInputView: ChatInputViewStyle = DemoChatInputViewStyle() var popUpView: PopUpViewStyle = DemoPopUpViewStyle() var segmentedTabsView: SegmentedTabsViewStyle = DemoSegmentedTabsViewStyle() var placeholderTextView: PlaceholderTextViewStyle = DemoPlaceholderTextViewStyle() var imageContentStyle: ImageContentCellStyle = ImageContentTableViewCellStyle() var titleStyle: LabelStyle = TitleStyle() var primaryLabel: LabelStyle = PrimaryLabelStyle() var secondaryLabel: LabelStyle = SecondaryLabelStyle() var primaryActionButton: ActionButtonStyle = PrimaryActionSemiboldRegularButton() var secondaryActionButton: ActionButtonStyle = DemoSecondaryActionButtonStyle() } class TitleStyle: LabelStyle { var color: UIColor? = Color.black var font: UIFont? = Font.regularTitle2 } class PlaceholderLabel: LabelStyle { var backgroundColor: UIColor? = Color.clear var color: UIColor? = Color.neutralMedium var font: UIFont? = Font.regularSubhead } class DemoPlaceholderTextViewStyle: PlaceholderTextViewStyle { var color: UIColor? = Color.neutralDark var font: UIFont? = Font.regularSubhead var placeholderTextAlignment: NSTextAlignment = .left var placeholderBackgroundColor: UIColor? = Color.clear var placeholderLabel: LabelStyle = PlaceholderLabel() } class DemoSegmentedTabsViewStyle: SegmentedTabsViewStyle { var indicatorColor: UIColor = Color.primary var item: ButtonStyle? = SegmentedControlItemStyle() var unselectedItem: ButtonStyle? = UnselectedSegmentedControlItemStyle() var borderColor: UIColor = Color.terciary } class PrimaryLabelStyle: LabelStyle{ var color: UIColor? { return Color.primaryText } var font: UIFont? { return Font.regularSubhead } } class SecondaryLabelStyle: LabelStyle{ var color: UIColor? { return Color.secondaryText } var font: UIFont? { return Font.regularSubhead } } class DemoRoundedButtonStyle: RoundedButtonStyle { var backgroundColor: UIColor? = .clear var titleColor: UIColor = Color.primary var titleFont: UIFont = Font.regularCaption2 var borderColor: UIColor? var borderWidth: CGFloat? = 0 var cornerRadius: CGFloat? = 4 } class DemoRoundedActionSecondarySmallButtonStyle: RoundedButtonStyle { var titleColor: UIColor = Color.neutralDark var titleFont: UIFont = Font.regularFootnote var backgroundColor: UIColor? = Color.clear var borderColor: UIColor? = Color.neutralLight var borderWidth: CGFloat? = 1.0 var cornerRadius: CGFloat? = 4.0 } class DemoRoundedActionSecondaryMediumButtonStyle: RoundedButtonStyle { var titleColor: UIColor = Color.neutralDark var titleFont: UIFont = Font.regularSubhead var backgroundColor: UIColor? = Color.clear var borderColor: UIColor? = Color.neutralLight var borderWidth: CGFloat? = 1.0 var cornerRadius: CGFloat? = 4.0 } class DemoRoundedActionButtonStyle: RoundedButtonStyle { var titleColor: UIColor = Color.neutralDark var titleFont: UIFont = Font.regularBody var backgroundColor: UIColor? = Color.clear var borderColor: UIColor? = Color.neutralLight var borderWidth: CGFloat? = 1.0 var cornerRadius: CGFloat? = 4.0 } class PrimaryActionSemiboldRegularButton: ActionButtonStyle { var font: UIFont = Font.semiBoldSubhead var borderWidth: CGFloat = 1 var cornerRadius: CGFloat = 5 var activeFontColor: UIColor = Color.primaryButtonText // Color.neutralMedium var activeBackgroundColor: UIColor = Color.primary var activeBorderColor: UIColor = Color.primary var selectedFontColor: UIColor = Color.primaryButtonText var selectedBackgroundColor: UIColor = .clear var selectedBorderColor: UIColor = Color.primaryButtonText var disabledFontColor: UIColor = Color.primaryTextDark var disabledBackgroundColor: UIColor = Color.separatorDark var disabledBorderColor: UIColor = Color.neutralTint // Will dissapear var activeFontFillColor: UIColor = Color.white var activeFillColor: UIColor = Color.primary var disabledFontFillColor: UIColor = Color.inactiveLight var disabledFillColor: UIColor = Color.primary var alertFontColor: UIColor = Color.error var alertBackgroundColor: UIColor = Color.base var alertBorderColor: UIColor = Color.error var inactiveBackgroundColor: UIColor = .clear var inactiveFontFillColor: UIColor = .clear var inactiveFillColor: UIColor = .clear } class DemoSecondaryActionButtonStyle: ActionButtonStyle { var font: UIFont = Font.semiBoldFootnote var borderWidth: CGFloat = 1 var cornerRadius: CGFloat = 4 var activeFontColor: UIColor = Color.neutralDark var activeFontFillColor: UIColor = Color.neutralDark var activeBackgroundColor: UIColor = Color.white var activeFillColor: UIColor = Color.neutralDark var activeBorderColor: UIColor = Color.separatorDark var selectedFontColor: UIColor = Color.secondaryButtonText var selectedBackgroundColor: UIColor = Color.secondaryButtonBackground var selectedBorderColor: UIColor = Color.separatorDark var inactiveFontColor: UIColor = Color.neutralMedium var inactiveFontFillColor: UIColor = Color.neutralMedium var inactiveBackgroundColor: UIColor = Color.white var inactiveFillColor: UIColor = Color.neutralMedium var disabledFontColor: UIColor = Color.neutralGray var disabledFontFillColor: UIColor = Color.neutralGray var disabledBackgroundColor: UIColor = Color.neutralLight var disabledFillColor: UIColor = Color.neutralMedium var disabledBorderColor: UIColor = Color.separatorDark var alertFontColor: UIColor = Color.error var alertBackgroundColor: UIColor = Color.base var alertBorderColor: UIColor = Color.error } class DemoPrimaryActionCellButtonStyle: ActionButtonStyle { var font: UIFont = Font.semiBoldSubhead var borderWidth: CGFloat = 1 var cornerRadius: CGFloat = 4 var activeFontColor: UIColor = Color.white var activeFontFillColor: UIColor = Color.white var activeBackgroundColor: UIColor = Color.clear var activeFillColor: UIColor = Color.primary var activeBorderColor: UIColor = UIColor.clear var selectedFontColor: UIColor = .clear var selectedBackgroundColor: UIColor = .clear var selectedBorderColor: UIColor = .clear var inactiveFontColor: UIColor = Color.neutralMedium var inactiveFontFillColor: UIColor = Color.neutralMedium var inactiveBackgroundColor: UIColor = Color.white var inactiveFillColor: UIColor = Color.neutralMedium var disabledFontColor: UIColor = Color.neutralGray var disabledFontFillColor: UIColor = Color.neutralGray var disabledBackgroundColor: UIColor = Color.neutralTint var disabledFillColor: UIColor = Color.neutralMedium var disabledBorderColor: UIColor = UIColor.clear var alertFontColor: UIColor = Color.error var alertBackgroundColor: UIColor = Color.base var alertBorderColor: UIColor = Color.error } class DemoSecondaryActionCellButtonStyle: ActionButtonStyle { var font: UIFont = Font.semiBoldSubhead var borderWidth: CGFloat = 1 var cornerRadius: CGFloat = 4 var activeFontColor: UIColor = Color.primary var activeFontFillColor: UIColor = Color.white var activeBackgroundColor: UIColor = Color.clear var activeFillColor: UIColor = Color.primary var activeBorderColor: UIColor = UIColor.clear var selectedFontColor: UIColor = .clear var selectedBackgroundColor: UIColor = .clear var selectedBorderColor: UIColor = .clear var inactiveFontColor: UIColor = Color.neutralMedium var inactiveFontFillColor: UIColor = Color.neutralMedium var inactiveBackgroundColor: UIColor = Color.white var inactiveFillColor: UIColor = Color.neutralMedium var disabledFontColor: UIColor = Color.neutralGray var disabledFontFillColor: UIColor = Color.neutralGray var disabledBackgroundColor: UIColor = Color.neutralTint var disabledFillColor: UIColor = Color.neutralMedium var disabledBorderColor: UIColor = UIColor.clear var alertFontColor: UIColor = Color.error var alertBackgroundColor: UIColor = Color.base var alertBorderColor: UIColor = Color.error } class ConnectSeparatorStyle: ViewStyle { var backgroundColor: UIColor? { return Color.neutralLight } } class DemoToastStyle: ToastStyle { var backgroundColor: UIColor? = Color.primary var messageBackgroundColor: UIColor? = Color.primary var errorBackgroundColor: UIColor? = Color.error var loadingBackgroundColor: UIColor? = Color.neutralMedium.withAlphaComponent(0.3) var label: LabelStyle? = BaseRegularFootnote() } class DemoDoubleTitleViewStyle: DoubleTitleViewStyle { var titleLabel: LabelStyle = NeutralGraySemiBoldSubhead() var descriptionLabel: LabelStyle = NeutralGrayRegularCaption2() var backgroundColor: UIColor? = .clear } class DemoLinkViewStyle: LinkViewStyle { var backgroundColor: UIColor? = Color.neutralLight var titleLabel: LabelStyle = NeutralDarkSemiBoldSubHead() var descriptionLabel: LabelStyle = NeutralDarkRegularFootnote() var linkLabel: LabelStyle = NeutralMediumRegularFootnote() var border: BorderStyle = LinkViewBorderStyle() class LinkViewBorderStyle: BorderStyle { var width: CGFloat? = 0.5 var color: UIColor? = Color.inactiveLight var cornerRadius: CGFloat? = 12.0 } } class DemoChatInputViewStyle: ChatInputViewStyle { var backgroundColor: UIColor? = Color.clear var borderColor: UIColor? = Color.neutralMedium var placeholderTextView: PlaceholderTextViewStyle = DemoPlaceholderTextViewStyle() } class DemoPopUpViewStyle: PopUpViewStyle { var cellStyle: CommonCellStyle = DemoCommonCellStyle() var separatorColor: UIColor? = Color.neutralGray var backgroundColor: UIColor? = Color.base } class DemoShareViewStyle: ShareViewStyle { var backgroundColor: UIColor? = Color.neutralLight var titleLabel: LabelStyle = NeutralDarkSemiBoldSubHead() var descriptionLabel: LabelStyle = NeutralDarkRegularFootnote() var contentLabel: LabelStyle = NeutralDarkRegularFootnote() var border: BorderStyle = ShareViewBorderStyle() class ShareViewBorderStyle: BorderStyle { var width: CGFloat? = 0.5 var color: UIColor? = Color.inactiveLight var cornerRadius: CGFloat? = 12.0 } } class DemoRoundedImageViewStyle: RoundedImageViewStyle { var backgroundColor: UIColor? = Color.base var borderColor: UIColor? var borderWidth: CGFloat = 0 } class SegmentedControlItemStyle: ButtonStyle { var backgroundColor: UIColor? = Color.terciary var color: UIColor? = Color.primaryTextDark var font: UIFont? = Font.semiBoldFootnote } class UnselectedSegmentedControlItemStyle: ButtonStyle { var backgroundColor: UIColor? = Color.base var color: UIColor? = Color.neutralMedium var font: UIFont? = Font.regularFootnote } class DemoTableHeaderViewStyle: TableHeaderViewStyle { var titleLabel: LabelStyle = NeutralDarkBoldTitle3() var backgroundColor: UIColor? = Color.white } class DemoProfileHeaderStyle: ProfileHeaderStyle { var titleOneLabel: LabelStyle = TertiaryRegularFootnote() var titleTwoLabel: LabelStyle = NeutralMediumRegularFootnote() var nameLabel: LabelStyle = NeutralDarkSemiBoldHeadline() var descriptionLabel: LabelStyle = NeutralDarkSemiBoldHeadline() var followLabel: LabelStyle = NeutralMediumRegularCaption2() var followValueLabel: LabelStyle = NeutralDarkRegularFootnote() }
40.428986
92
0.669558
14a39ad41d3e0174d8f4765e255e6c1de27a3ffd
1,988
// // VIMLiveChat.swift // VimeoNetworking // // Created by Van Nguyen on 10/10/2017. // Copyright (c) Vimeo (https://vimeo.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // /// An object representing the `chat` field in a `live` response. This /// `live` response is part of the `clip` representation. public class VIMLiveChat: VIMModelObject { private struct Constants { static let UserKey = "user" } /// The ID of the live event chat room. @objc public private(set) var roomId: NSNumber? /// JWT for the user to access the live event chat room. @objc public private(set) var token: String? /// The current user. @objc public private(set) var user: VIMLiveChatUser? @objc public override func getClassForObjectKey(_ key: String!) -> AnyClass? { if key == Constants.UserKey { return VIMLiveChatUser.self } return nil } }
38.980392
82
0.700704
3962fb52a797505d3ee12bddfc7112155f12837a
3,295
// // Movie.swift // BandeAnnonce // // Created by on 03/03/2020. // Copyright © 2020 Anthony chaussin. All rights reserved. // import Foundation /// Movie struct public struct Movie { var id: Int var movieTitle: String var subTitle: String var poster: String let basePath: String = "https://image.tmdb.org/t/p/w200" var duration: Int var outDate: String var resum: String var cat: [Genre]? = nil var backdropPath: String var urlVideo: String /// Transform a MovieResponse into Movie object /// - Parameter data: One object of type MovieResponse init(data: MovieResponse) throws { self.id = data.id! self.movieTitle = data.title ?? "" self.poster = (data.posterPath != nil) ? "\(self.basePath)\(data.posterPath!)" : "" self.resum = (data.overview == nil || data.overview == "") ? "..." : data.overview! self.outDate = data.releaseDate ?? "" self.subTitle = (data.title != data.originalTitle || data.originalTitle != nil) ? "(\(String(describing: data.originalTitle!)))" : "" self.backdropPath = (data.backdropPath != nil) ? "\(self.basePath)\(data.backdropPath!)" : self.poster self.cat = data.genres self.urlVideo = "https://www.youtube.com/watch?v=\(String(describing: data.videos?.results?.first?.key ?? ""))" self.duration = data.runtime ?? 0 } /// Constructor /// - Parameters: /// - movieTitle: The title of movie /// - poster: The poster movie /// - duration: The total movie duration /// - outDate: The date of movie was published /// - resum: E short resum of movie /// - cat: All cat of movie init(movieTitle: String, poster: String, duration: Int, outDate: String, resum: String, cat: [Genre]) { self.movieTitle = movieTitle if poster.contains("placeholder") || poster == "" { self.poster = poster } else{ self.poster = "\(self.basePath)\(poster)" } self.duration = duration self.outDate = outDate self.resum = resum self.cat = cat self.backdropPath = self.poster self.urlVideo = "" self.id = 0 self.subTitle = movieTitle } /// Generate a fake data for a movie public static func getFakeData() ->Movie{ let indexTab: Int = Int.random(in: 0...4) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" //Use for testing nil image return //let poster: String = Bool.random() ? "https://via.placeholder.com/\(Int32.random(in: 25...2500))" : "" let poster: String = "https://via.placeholder.com/\(Int32.random(in: 25...2500))" var cat: [Genre] = [] for i in 1...UInt8.random(in: 1...8){ cat.append(Genre(id: Int(i), name: Env.bddCat[Int.random(in: 1...8)])) } return Movie.init( movieTitle: Env.bddName[indexTab], poster: poster, duration: Int.random(in: 0...180), outDate: formatter.string(from: (Date.init().addingTimeInterval(TimeInterval.random(in: -200...200)*1000000))), resum: Env.bddResum[indexTab], cat: cat) } }
36.208791
141
0.579363
9011c069e0afdbf959be8462f9cb7806b1a11600
9,284
// // ResourceSpecBase.swift // Siesta // // Created by Paul on 2015/6/20. // Copyright © 2016 Bust Out Solutions. All rights reserved. // @testable import Siesta import Foundation import Quick import Nimble import Alamofire #if canImport(Siesta_Alamofire) // SwiftPM builds it as a separate module import Siesta_Alamofire #endif private let _fakeNowLock = NSObject() private var _fakeNow: Double? private var fakeNow: Double? { get { objc_sync_enter(_fakeNowLock) defer { objc_sync_exit(_fakeNowLock) } return _fakeNow } set { objc_sync_enter(_fakeNowLock) defer { objc_sync_exit(_fakeNowLock) } _fakeNow = newValue } } class ResourceSpecBase: SiestaSpec { func resourceSpec(_ service: @escaping () -> Service, _ resource: @escaping () -> Resource) { } override final func spec() { super.spec() beforeEach { NetworkStub.clearAll() } let realNow = Siesta.now Siesta.now = { fakeNow ?? realNow() } afterEach { fakeNow = nil } if SiestaSpec.envFlag("TestMultipleNetworkProviders") { runSpecsWithNetworkingProvider("default URLSession", networking: NetworkStub.wrap(URLSessionConfiguration.default)) runSpecsWithNetworkingProvider("ephemeral URLSession", networking: NetworkStub.wrap(URLSessionConfiguration.ephemeral)) runSpecsWithNetworkingProvider("threaded URLSession", networking: { let backgroundQueue = OperationQueue() return URLSession( configuration: NetworkStub.wrap(URLSessionConfiguration.default), delegate: nil, delegateQueue: backgroundQueue) }()) #if canImport(Alamofire) let afSession = Alamofire.Session( configuration: NetworkStub.wrap( Alamofire.Session.default.session.configuration), startRequestsImmediately: false) runSpecsWithNetworkingProvider("Alamofire networking", networking: afSession) #endif } else { runSpecsWithDefaultProvider() } } private func runSpecsWithNetworkingProvider(_ description: String?, networking: NetworkingProviderConvertible) { context(debugStr(["with", description])) { self.runSpecsWithService { Service(baseURL: self.baseURL, networking: networking) } } } private func runSpecsWithDefaultProvider() { runSpecsWithService { Service(baseURL: self.baseURL, networking: NetworkStub.defaultConfiguration) } } private func runSpecsWithService(_ serviceBuilder: @escaping () -> Service) { weak var weakService: Service? // Make sure that Service is deallocated after each spec (which also catches Resource and Request leaks, // since they ultimately retain their associated service) // // NB: This must come _after_ the specVars above, which use afterEach to clear the service and resource. afterEach { exampleMetadata in for attempt in 0... { if weakService == nil { break } // yay! if attempt > 4 { fail("Service instance leaked by test") weakService = nil break } if attempt > 0 // waiting for one cleanup cycle is normal { print("Test may have leaked service instance; will wait for cleanup and check again (attempt \(attempt))") Thread.sleep(forTimeInterval: 0.02 * pow(3, Double(attempt))) } awaitObserverCleanup() weakService?.flushUnusedResources() } } aroundEach { example in autoreleasepool { example() } // Alamofire relies on autorelease, so each spec needs its own pool for leak checking } // Standard service and resource test instances // (These use configurable net provider and embed the spec name in the baseURL.) let service = specVar { () -> Service in let result = serviceBuilder() weakService = result return result } let resource = specVar { service().resource("/a/b") } // Run the actual specs context("") // Make specVars above run in a separate context so their afterEach cleans up _before_ the leak check { resourceSpec(service, resource) } } var baseURL: String { // Embedding the spec name in the API’s URL makes it easier to track down unstubbed requests, which sometimes // don’t arrive until a following spec has already started. return "test://" + QuickSpec.current.description .replacing(regex: "_[A-Za-z]+Specswift_\\d+\\]$", with: "") .replacing(regex: "[^A-Za-z0-9_]+", with: ".") .replacing(regex: "^\\.+|\\.+$", with: "") } } // MARK: - Awaiting requests func awaitNewData(_ req: Siesta.Request, initialState: RequestState = .inProgress) { expect(req.state) == initialState let responseExpectation = QuickSpec.current.expectation(description: "awaiting response callback: \(req)") let successExpectation = QuickSpec.current.expectation(description: "awaiting success callback: \(req)") let newDataExpectation = QuickSpec.current.expectation(description: "awaiting newData callback: \(req)") req.onCompletion { _ in responseExpectation.fulfill() } .onSuccess { _ in successExpectation.fulfill() } .onFailure { _ in fail("error callback should not be called") } .onNewData { _ in newDataExpectation.fulfill() } .onNotModified { fail("notModified callback should not be called") } QuickSpec.current.waitForExpectations(timeout: 1) expect(req.state) == .completed } func awaitNotModified(_ req: Siesta.Request) { expect(req.state) == .inProgress let responseExpectation = QuickSpec.current.expectation(description: "awaiting response callback: \(req)") let successExpectation = QuickSpec.current.expectation(description: "awaiting success callback: \(req)") let notModifiedExpectation = QuickSpec.current.expectation(description: "awaiting notModified callback: \(req)") req.onCompletion { _ in responseExpectation.fulfill() } .onSuccess { _ in successExpectation.fulfill() } .onFailure { _ in fail("error callback should not be called") } .onNewData { _ in fail("newData callback should not be called") } .onNotModified { notModifiedExpectation.fulfill() } QuickSpec.current.waitForExpectations(timeout: 1) expect(req.state) == .completed } func awaitFailure(_ req: Siesta.Request, initialState: RequestState = .inProgress) { expect(req.state) == initialState let responseExpectation = QuickSpec.current.expectation(description: "awaiting response callback: \(req)") let errorExpectation = QuickSpec.current.expectation(description: "awaiting failure callback: \(req)") req.onCompletion { _ in responseExpectation.fulfill() } .onFailure { _ in errorExpectation.fulfill() } .onSuccess { _ in fail("success callback should not be called") } .onNewData { _ in fail("newData callback should not be called") } .onNotModified { fail("notModified callback should not be called") } QuickSpec.current.waitForExpectations(timeout: 1) expect(req.state) == .completed } func stubAndAwaitRequest(for resource: Resource, expectSuccess: Bool = true) { NetworkStub.add( .get, { resource }, returning: HTTPResponse(body: "🍕")) let awaitRequest = expectSuccess ? awaitNewData : awaitFailure awaitRequest(resource.load(), .inProgress) } // MARK: - Siesta internals func setResourceTime(_ time: TimeInterval) { fakeNow = time } // Checks for removed observers normally get batched up and run later after a delay. // This call waits for that to finish so we can check who’s left observing and who isn’t. // // Since there’s no way to directly detect the cleanup, and thus no positive indicator to // wait for, we just wait for all tasks currently queued on the main thread to complete. // func awaitObserverCleanup(for resource: Resource? = nil) { let cleanupExpectation = QuickSpec.current.expectation(description: "awaitObserverCleanup") DispatchQueue.main.async { cleanupExpectation.fulfill() } QuickSpec.current.waitForExpectations(timeout: 1) } extension Error { var unwrapAlamofireError: NSError { if case .sessionTaskFailed(let wrappedError) = self as? AFError { return wrappedError as NSError } else { return self as NSError } } }
36.124514
131
0.625377
bf5a190c59e8756d7e2cfddb0c08e4bc08373e92
1,051
// // ViewController.swift // Day10-VideoBackground // // Created by 王林 on 2019/5/16. // Copyright © 2019 王林. All rights reserved. // import UIKit class ViewController: VideoSplashViewController { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var signupButton: UIButton! override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLoad() { super.viewDidLoad() loginButton.layer.cornerRadius = 4 signupButton.layer.cornerRadius = 4 setupVideoBackground() } func setupVideoBackground() { let url = URL(fileURLWithPath: Bundle.main.path(forResource: "moments", ofType: "mp4")!) videoFrame = view.frame fillMode = .resizeAspectFill alwaysRepeat = true sound = true startTime = 2.0 alpha = 0.8 contentURL = url // view.isUserInteractionEnabled = false } }
21.895833
96
0.607041
e5deab7058dcfe819ad3a71b06d11945f595b79a
31
struct ClearNewNote: Action {}
15.5
30
0.774194
5baa518fabb06a0620a8a66e8ee6bdb6195894d4
11,058
import SwiftUI import PhoenixShared import os.log #if DEBUG && true fileprivate var log = Logger( subsystem: Bundle.main.bundleIdentifier!, category: "ScanView" ) #else fileprivate var log = Logger(OSLog.disabled) #endif struct ScanView: View { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @ObservedObject var toast: Toast @Binding var paymentRequest: String? @State var clipboardHasString = UIPasteboard.general.hasStrings @State var showingImagePicker = false @State var imagePickerSelection: UIImage? = nil @State var displayWarning: Bool = false @State var ignoreScanner: Bool = false @Environment(\.colorScheme) var colorScheme: ColorScheme @Environment(\.shortSheetState) private var shortSheetState: ShortSheetState @Environment(\.popoverState) var popoverState: PopoverState let willEnterForegroundPublisher = NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification ) // Subtle timing bug: // // Steps to reproduce: // - scan payment without amount (and without trampoline support) // - warning popup is displayed // - keep QRcode within camera screen while tapping Confirm button // // What happens: // - the validate screen is not displayed as it should be // // Why: // - the warning popup is displayed // - user taps "confirm" // - we send IntentConfirmEmptyAmount to library // - QrCodeScannerView fires // - we send IntentParse to library // - library sends us ModelValidate // - library sends us ModelRequestWithoutAmount @ViewBuilder var body: some View { ZStack { Color.primaryBackground .edgesIgnoringSafeArea(.all) if AppDelegate.showTestnetBackground { Image("testnet_bg") .resizable(resizingMode: .tile) .edgesIgnoringSafeArea([.horizontal, .bottom]) // not underneath status bar } content if mvi.model is Scan.Model_LnurlServiceFetch { LnurlFetchNotice( title: NSLocalizedString("Fetching Lightning URL", comment: "Progress title"), onCancel: { didCancelLnurlServiceFetch() } ) .ignoresSafeArea(.keyboard) // disable keyboard avoidance on this view } } .frame(maxHeight: .infinity) .navigationBarTitle( NSLocalizedString("Scan a QR code", comment: "Navigation bar title"), displayMode: .inline ) .transition( .asymmetric( insertion: .identity, removal: .move(edge: .bottom) ) ) .onReceive(willEnterForegroundPublisher) { _ in willEnterForeground() } .onChange(of: mvi.model) { newModel in modelDidChange(newModel) } .onChange(of: displayWarning) { newValue in if newValue { showWarning() } } } @ViewBuilder var content: some View { VStack { QrCodeScannerView {(request: String) in didScanQRCode(request) } Button { manualInput() } label: { Label { Text("Manual input") } icon: { Image(systemName: "square.and.pencil") } } .font(.title3) .padding(.top, 10) Divider() .padding([.top, .bottom], 10) Button { pasteFromClipboard() } label: { Label { Text("Paste from clipboard") } icon: { Image(systemName: "arrow.right.doc.on.clipboard") } } .font(.title3) .disabled(!clipboardHasString) Divider() .padding([.top, .bottom], 10) Button { showingImagePicker = true } label: { Label { Text("Choose image") } icon: { Image(systemName: "photo") } } .font(.title3) .padding(.bottom, 10) .onChange(of: imagePickerSelection) { _ in imagePickerDidChooseImage() } } .ignoresSafeArea(.keyboard) // disable keyboard avoidance on this view .sheet(isPresented: $showingImagePicker) { ImagePicker(image: $imagePickerSelection) } } func willEnterForeground() { log.trace("willEnterForeground()") clipboardHasString = UIPasteboard.general.hasStrings } func modelDidChange(_ newModel: Scan.Model) { log.trace("modelDidChange()") if ignoreScanner { // Flow: // - User taps "manual input" // - User types in something and taps "OK" // - We send Scan.Intent.Parse() // - We just got back a response from our request // ignoreScanner = false } if let _ = newModel as? Scan.Model_InvoiceFlow_DangerousRequest { displayWarning = true } } func didScanQRCode(_ request: String) { var isFetchingLnurl = false if let _ = mvi.model as? Scan.Model_LnurlServiceFetch { isFetchingLnurl = true } if !ignoreScanner && !isFetchingLnurl { mvi.intent(Scan.Intent_Parse(request: request)) } } func didCancelLnurlServiceFetch() { log.trace("didCancelLnurlServiceFetch()") mvi.intent(Scan.Intent_CancelLnurlServiceFetch()) } func manualInput() { log.trace("manualInput()") ignoreScanner = true shortSheetState.display(dismissable: true) { ManualInput(mvi: mvi, ignoreScanner: $ignoreScanner) } } func pasteFromClipboard() { log.trace("pasteFromClipboard()") if let request = UIPasteboard.general.string { mvi.intent(Scan.Intent_Parse(request: request)) } } func showWarning() { log.trace("showWarning()") guard let model = mvi.model as? Scan.Model_InvoiceFlow_DangerousRequest else { return } displayWarning = false ignoreScanner = true popoverState.display(dismissable: false) { DangerousInvoiceAlert( model: model, intent: mvi.intent, ignoreScanner: $ignoreScanner ) } } func imagePickerDidChooseImage() { log.trace("imagePickerDidChooseImage()") guard let uiImage = imagePickerSelection else { return } imagePickerSelection = nil if let ciImage = CIImage(image: uiImage) { var options: [String: Any] let context = CIContext() options = [CIDetectorAccuracy: CIDetectorAccuracyHigh] let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options) if let orientation = ciImage.properties[(kCGImagePropertyOrientation as String)] { options = [CIDetectorImageOrientation: orientation] } else { options = [CIDetectorImageOrientation: 1] } let features = qrDetector?.features(in: ciImage, options: options) var qrCodeString: String? = nil if let features = features { for case let row as CIQRCodeFeature in features { if qrCodeString == nil { qrCodeString = row.messageString } } } if let qrCodeString = qrCodeString { mvi.intent(Scan.Intent_Parse(request: qrCodeString)) } else { toast.pop( Text("Image doesn't contain a readable QR code.").multilineTextAlignment(.center).anyView, colorScheme: colorScheme.opposite, style: .chrome, duration: 10.0, location: .middle, showCloseButton: true ) } } } } struct ManualInput: View, ViewName { @ObservedObject var mvi: MVIState<Scan.Model, Scan.Intent> @Binding var ignoreScanner: Bool @State var input = "" @Environment(\.shortSheetState) private var shortSheetState: ShortSheetState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Manual Input") .font(.title2) .padding(.bottom) Text( """ Enter a Lightning invoice, LNURL, or Lightning address \ you want to send money to. """ ) .padding(.bottom) HStack(alignment: VerticalAlignment.center, spacing: 0) { TextField("", text: $input) // Clear button (appears when TextField's text is non-empty) Button { input = "" } label: { Image(systemName: "multiply.circle.fill") .foregroundColor(.secondary) } .isHidden(input == "") } .padding(.all, 8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color(UIColor.separator), lineWidth: 1) ) .padding(.bottom) .padding(.bottom) HStack(alignment: VerticalAlignment.center, spacing: 0) { Spacer() Button("Cancel") { didCancel() } .font(.title3) Divider() .frame(maxHeight: 20, alignment: Alignment.center) .padding([.leading, .trailing]) Button("OK") { didConfirm() } .font(.title3) } } // </VStack> .padding() } func didCancel() -> Void { log.trace("[\(viewName)] didCancel()") shortSheetState.close { ignoreScanner = false } } func didConfirm() -> Void { log.trace("[\(viewName)] didConfirm()") let request = input.trimmingCharacters(in: .whitespacesAndNewlines) if request.count > 0 { mvi.intent(Scan.Intent_Parse(request: request)) } shortSheetState.close() } } struct DangerousInvoiceAlert: View, ViewName { let model: Scan.Model_InvoiceFlow_DangerousRequest let intent: (Scan.Intent) -> Void @Binding var ignoreScanner: Bool @Environment(\.popoverState) var popoverState: PopoverState @ViewBuilder var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Warning") .font(.title2) .padding(.bottom) if model.reason is Scan.DangerousRequestReasonIsAmountlessInvoice { content_amountlessInvoice } else if model.reason is Scan.DangerousRequestReasonIsOwnInvoice { content_ownInvoice } else { content_unknown } HStack(alignment: VerticalAlignment.center, spacing: 0) { Spacer() Button("Cancel") { didCancel() } .font(.title3) .padding(.trailing) Button("Continue") { didConfirm() } .font(.title3) .disabled(isUnknownType()) } .padding(.top, 30) } // </VStack> .padding() } @ViewBuilder var content_amountlessInvoice: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text(styled: NSLocalizedString( """ The invoice doesn't include an amount. This can be dangerous: \ malicious nodes may be able to steal your payment. To be safe, \ **ask the payee to specify an amount** in the payment request. """, comment: "SendView" )) .padding(.bottom) Text("Are you sure you want to pay this invoice?") } } @ViewBuilder var content_ownInvoice: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("The invoice is for you. You are about to pay yourself.") } } @ViewBuilder var content_unknown: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 0) { Text("Something is amiss with this invoice...") } } func isUnknownType() -> Bool { if model.reason is Scan.DangerousRequestReasonIsAmountlessInvoice { return false } else if model.reason is Scan.DangerousRequestReasonIsOwnInvoice { return false } else { return true } } func didCancel() -> Void { log.trace("[\(viewName)] didCancel()") popoverState.close { ignoreScanner = false } } func didConfirm() -> Void { log.trace("[\(viewName)] didConfirm()") intent(Scan.Intent_InvoiceFlow_ConfirmDangerousRequest( request: model.request, paymentRequest: model.paymentRequest )) popoverState.close() } }
22.567347
96
0.67164
7aef7bb430913c2a73886e1edaa34c136e8baf36
2,043
// // UIColor.swift // BabyTime // // Created by 宋磊 on 2018/9/3. // Copyright © 2018年 songlei. All rights reserved. // import UIKit public extension UIColor{ /// 主题黄色 static var mainYellowColor : UIColor { return UIColor(hex: 0xff8a00) } /// 分割色 static var separatorColor : UIColor { return UIColor(hex: 0xdfdfdf) } /// 分割色 static var disableColor : UIColor { return UIColor(hex: 0xbcbcbc) } /// 半透明颜色 static var translucentColor : UIColor { return UIColor(hex: 0x000000, alpha: 0.6) } /// viewControler 背景颜色 static var vcBgColor : UIColor { return UIColor(hex: 0xf4f4f4) } } extension UIColor { convenience init(r: CGFloat, g: CGFloat, b: CGFloat) { self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0) } class func randomColor() -> UIColor { return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256))) } } public extension UIColor{ /// 随机色 static var random: UIColor { let maxValue: UInt32 = 24 return UIColor(red: CGFloat(arc4random() % maxValue) / CGFloat(maxValue), green: CGFloat(arc4random() % maxValue) / CGFloat(maxValue) , blue: CGFloat(arc4random() % maxValue) / CGFloat(maxValue) , alpha: 1) } /// 十六进制颜色 - 可设置透明度 /// /// - Parameters: /// - hex: 十六进制 /// - alpha: 透明度 convenience init(hex: Int, alpha: Float) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat.init(alpha) ) } /// 十六进制颜色 /// /// - Parameters: /// - hex: 十六进制 convenience init(hex:Int) { self.init(hex: hex, alpha: 1) } }
21.505263
133
0.537445
fbb0906028ce7fcf20e9d2ff2d687b530aacbe45
16,460
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import TrustWalletCore import XCTest extension HDWallet { static let test = HDWallet(mnemonic: "ripple scissors kick mammal hire column oak again sun offer wealth tomorrow wagon turn fatal", passphrase: "TREZOR") } class HDWalletTests: XCTestCase { func testSeed() { let wallet = HDWallet.test XCTAssertEqual(wallet.seed.hexString, "7ae6f661157bda6492f6162701e570097fc726b6235011ea5ad09bf04986731ed4d92bc43cbdee047b60ea0dd1b1fa4274377c9bf5bd14ab1982c272d8076f29") } func testSeedNoPassword() { let wallet = HDWallet(mnemonic: HDWallet.test.mnemonic, passphrase: "") XCTAssertEqual(wallet.seed.hexString, "354c22aedb9a37407adc61f657a6f00d10ed125efa360215f36c6919abd94d6dbc193a5f9c495e21ee74118661e327e84a5f5f11fa373ec33b80897d4697557d") } func testDerive() { let wallet = HDWallet.test let key0 = wallet.getKeyBIP44(coin: .ethereum, account: 0, change: 0, address: 0) let key1 = wallet.getKeyBIP44(coin: .ethereum, account: 0, change: 0, address: 1) XCTAssertEqual(EthereumAddress(publicKey: key0.getPublicKeySecp256k1(compressed: false)).description, "0x27Ef5cDBe01777D62438AfFeb695e33fC2335979") XCTAssertEqual(EthereumAddress(publicKey: key1.getPublicKeySecp256k1(compressed: false)).description, "0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47") } func testWanchain() { let wanChain = CoinType.wanchain let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: wanChain) let address = wanChain.deriveAddress(privateKey: key) XCTAssertEqual(address, "0x4ddA26870b4B3FA3fBa32222159359038F588318") } func testDeriveBitcoin() { let bitcoin = CoinType.bitcoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: bitcoin) let address = bitcoin.deriveAddress(privateKey: key) XCTAssertEqual("bc1qumwjg8danv2vm29lp5swdux4r60ezptzz7ce85", address) } func testDeriveDigiByte() { let digibye = CoinType.digiByte let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: digibye) let address = digibye.deriveAddress(privateKey: key) XCTAssertEqual("dgb1q7qk2vvetgldgq0eeh3ytsky2380l9wuessmhe3", address) } func testDeriveEthereum() { let ethereum = CoinType.ethereum let key = HDWallet.test.getKeyForCoin(coin: ethereum) let address = ethereum.deriveAddress(privateKey: key) XCTAssertEqual("0x27Ef5cDBe01777D62438AfFeb695e33fC2335979", address) } func testDeriveLitecoin() { let litecoin = CoinType.litecoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: litecoin) let address = litecoin.deriveAddress(privateKey: key) XCTAssertEqual("ltc1qmj6hw649d7q2teduv599zv9ls9akz60gkdwnp7", address) } func testDeriveTron() { let tron = CoinType.tron let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: tron) let address = tron.deriveAddress(privateKey: key) XCTAssertEqual("THJrqfbBhoB1vX97da6S6nXWkafCxpyCNB", address) } func testDeriveIcon() { let icon = CoinType.icon let wallet = HDWallet.test let key0 = wallet.getKeyForCoin(coin: icon) let key1 = wallet.getKeyBIP44(coin: icon, account: 0, change: 0, address: 1) let address0 = icon.deriveAddress(privateKey: key0) let address1 = icon.deriveAddress(privateKey: key1) XCTAssertEqual("hx78c6f744c68d48793cd64716189c181c66907b24", address0) XCTAssertEqual("hx92373c16531761b31a7124c94718da43db8c9d89", address1) } func testDeriveOntology() { let ontology = CoinType.ontology let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: ontology) let address = ontology.deriveAddress(privateKey: key) XCTAssertEqual("AH11LGtFk6VU9Z7suuM5eNpho1bAoE5Gbz", address) } func testDeriveBitcoinCash() { let bitcoinCash = CoinType.bitcoinCash let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: bitcoinCash) let address = bitcoinCash.deriveAddress(privateKey: key) XCTAssertEqual("bitcoincash:qqxktqe0pzf0yepvap9rf2g8zxq8t5mqx50dwpqlxl", address) } func testDeriveDash() { let dash = CoinType.dash let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: dash) let address = dash.deriveAddress(privateKey: key) XCTAssertEqual("XsJg3pJaoyKEf5jMYTb5wGf3TKp9W3KX5a", address) } func testDeriveZcoin() { let zcoin = CoinType.zcoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: zcoin) let address = zcoin.deriveAddress(privateKey: key) XCTAssertEqual("a5jgmKczLE7fbgBmVkDTvvAQx8pYZKL7LP", address) } func testDeriveBinanceChain() { let binance = CoinType.binance let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: binance) let address = CosmosAddress(hrp: .binance, publicKey: key.getPublicKeySecp256k1(compressed: true)) XCTAssertEqual("bnb1wk7kxw0qrvxe2pj9mk6ydjx0t4j9jla8pja0td", address?.description) } func testDeriveZcash() { let zcash = CoinType.zcash let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: zcash) let address = zcash.deriveAddress(privateKey: key) XCTAssertEqual("t1RygJmrLdNGgi98gUgEJDTVaELTAYWoMBy", address) } func testDeriveRipple() { let ripple = CoinType.xrp let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: ripple) let address = ripple.deriveAddress(privateKey: key) XCTAssertEqual("r36yxStAh7qgTQNHTzjZvXybCTzUFhrfav", address) } func testDeriveAion() { let aion = CoinType.aion let key = HDWallet.test.getKeyForCoin(coin: aion) let address = aion.deriveAddress(privateKey: key) XCTAssertEqual("0xa0dcc9e5e3bbd6a5a092f6b4975f6c5856e8eb750f37b7079bf7888e8cc1deb8", address) } func testDevieStellar() { let stellar = CoinType.stellar let key = HDWallet.test.getKeyForCoin(coin: stellar) let address = stellar.deriveAddress(privateKey: key) XCTAssertEqual(key.data.hexString, "4fd1cb3c9c15c171b7b90dc3fefc7b2fc54de09b869cc9d6708d26b114e8d9a5") XCTAssertEqual(address.description, "GCRWFRVQP5XS7I4SFCL374VKV6OHJ3L3H3SDVGH7FW73N7LSNYJXOLDK") } func testDeriveTezos() { let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: .tezos) let pubkey = key.getPublicKeyEd25519() let address = TezosAddress(publicKey: pubkey) XCTAssertEqual(pubkey.data.hexString, "c834147f97bcf95bf01f234455646a197f70b25e93089591ffde8122370ad371") XCTAssertEqual("tz1RsC3AREfrMwh6Hdu7qGKxBwb1VgwJv1qw", address.description) } func testDeriveTezos2() { let wallet = HDWallet(mnemonic: "kidney setup media hat relief plastic ghost census mouse science expect movie", passphrase: "") let key = wallet.getKeyForCoin(coin: .tezos) let address = CoinType.tezos.deriveAddress(privateKey: key) XCTAssertEqual("tz1M9ZMG1kthqQFK5dFi8rDCahqw6gHr1zoZ", address.description) } func testDeriveNimiq() { // mnemonic is from https://github.com/Eligioo/nimiq-hd-wallet, compatible with ledger // but it's not compatible with safe.nimiq.com (can't import) let wallet = HDWallet(mnemonic: "insane mixed health squeeze physical trust pipe possible garage hero flock stand profit power tooth review note camera express vicious clock machine entire heavy", passphrase: "") let coin = CoinType.nimiq let key = wallet.getKeyForCoin(coin: coin) let address = coin.deriveAddress(privateKey: key) XCTAssertEqual("NQ77 XYYH YUNC V52U 5ADV 5JAY QXMD 2F9C Q440", address.description) } func testDeriveDecred() { let wallet = HDWallet.test let coin = CoinType.decred let key = wallet.getKeyForCoin(coin: coin) let address = coin.deriveAddress(privateKey: key) XCTAssertEqual("DsksmLD2wDoA8g8QfFvm99ASg8KsZL8eJFd", address.description) } func testDeriveGroestlcoin() { let groestlcoin = CoinType.groestlcoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: groestlcoin) let address = groestlcoin.deriveAddress(privateKey: key) XCTAssertEqual("grs1qsjpmsmm4x34wlt6kk4zef9u0jtculguktwgwg4", address) } func testDeriveDoge() { let doge = CoinType.dogecoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: doge) let address = doge.deriveAddress(privateKey: key) XCTAssertEqual("DJRoWqKj6hVmZMEMPahJ7UsqaYCtEJ3xv9", address) } func testDeriveZilliqa() { let zil = CoinType.zilliqa let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: .zilliqa) let address = zil.deriveAddress(privateKey: key) XCTAssertEqual(key.data.hexString, "b49a9fb16cd2b46ee538be807f712073009ea528e407a25a4bf91a63c3e49f99") XCTAssertEqual(address.description, "zil1vhs6jdq7prgsumeuqzfse6recklesqcesfe685") } func testSignHash() { let eth = CoinType.ethereum let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: eth) let hash = Data(hexString: "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F")! let result = key.sign(digest: hash, curve: .secp256k1)! let publicKey = key.getPublicKeySecp256k1(compressed: false) XCTAssertEqual(result.count, 65) XCTAssertTrue(publicKey.verify(signature: result, message: hash)) } func testExtendedKeys() { let wallet = HDWallet(mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", passphrase: "") let xprv = wallet.getExtendedPrivateKey(purpose: .bip44, coin: .bitcoin, version: .xprv) let xpub = wallet.getExtendedPublicKey(purpose: .bip44, coin: .bitcoin, version: .xpub) XCTAssertEqual(xprv, "xprv9xpXFhFpqdQK3TmytPBqXtGSwS3DLjojFhTGht8gwAAii8py5X6pxeBnQ6ehJiyJ6nDjWGJfZ95WxByFXVkDxHXrqu53WCRGypk2ttuqncb") XCTAssertEqual(xpub, "xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj") let yprv = wallet.getExtendedPrivateKey(purpose: .bip49, coin: .bitcoin, version: .yprv) let ypub = wallet.getExtendedPublicKey(purpose: .bip49, coin: .bitcoin, version: .ypub) XCTAssertEqual(yprv, "yprvAHwhK6RbpuS3dgCYHM5jc2ZvEKd7Bi61u9FVhYMpgMSuZS613T1xxQeKTffhrHY79hZ5PsskBjcc6C2V7DrnsMsNaGDaWev3GLRQRgV7hxF") XCTAssertEqual(ypub, "ypub6Ww3ibxVfGzLrAH1PNcjyAWenMTbbAosGNB6VvmSEgytSER9azLDWCxoJwW7Ke7icmizBMXrzBx9979FfaHxHcrArf3zbeJJJUZPf663zsP") let zprv = wallet.getExtendedPrivateKey(purpose: .bip84, coin: .bitcoin, version: .zprv) let zpub = wallet.getExtendedPublicKey(purpose: .bip84, coin: .bitcoin, version: .zpub) XCTAssertEqual(zprv, "zprvAdG4iTXWBoARxkkzNpNh8r6Qag3irQB8PzEMkAFeTRXxHpbF9z4QgEvBRmfvqWvGp42t42nvgGpNgYSJA9iefm1yYNZKEm7z6qUWCroSQnE") XCTAssertEqual(zpub, "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs") } func testDeriveFromXPub() { let xpub = "xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj" let bitcoin = CoinType.bitcoinCash let xpub2 = HDWallet.derive(from: xpub, at: DerivationPath(purpose: .bip44, coinType: bitcoin, account: 0, change: 0, address: 2))! let xpub9 = HDWallet.derive(from: xpub, at: DerivationPath(purpose: .bip44, coinType: bitcoin, account: 0, change: 0, address: 9))! let xpubAddr2 = BitcoinAddress(publicKey: xpub2, prefix: CoinType.bitcoin.p2pkhPrefix)! let xpubAddr9 = BitcoinAddress(publicKey: xpub9, prefix: CoinType.bitcoin.p2pkhPrefix)! XCTAssertEqual(xpubAddr2.description, "1MNF5RSaabFwcbtJirJwKnDytsXXEsVsNb") XCTAssertEqual(xpubAddr9.description, "1DUrqK4hj6vNNUTWXADpbqyjVWUYFD7xTZ") } func testDeriveFromYPub() { let ypub = "ypub6Ww3ibxVfGzLrAH1PNcjyAWenMTbbAosGNB6VvmSEgytSER9azLDWCxoJwW7Ke7icmizBMXrzBx9979FfaHxHcrArf3zbeJJJUZPf663zsP" let bitcoin = CoinType.bitcoin let ypub3 = HDWallet.derive(from: ypub, at: DerivationPath(purpose: .bip49, coinType: bitcoin, account: 0, change: 0, address: 3))! let ypub10 = HDWallet.derive(from: ypub, at: DerivationPath(purpose: .bip49, coinType: bitcoin, account: 0, change: 0, address: 10))! let ypubAddr3 = BitcoinAddress.compatibleAddress(publicKey: ypub3, prefix: CoinType.bitcoin.p2shPrefix) let ypubAddr10 = BitcoinAddress.compatibleAddress(publicKey: ypub10, prefix: CoinType.bitcoin.p2shPrefix) XCTAssertEqual(ypubAddr3.description, "38CahkVftQneLonbWtfWxiiaT2fdnzsEAN") XCTAssertEqual(ypubAddr10.description, "38mWd5D48ShYPJMZngtmxPQVYhQR5DGgfF") } func testDeriveFromZPub() { let zpub = "zpub6rFR7y4Q2AijBEqTUquhVz398htDFrtymD9xYYfG1m4wAcvPhXNfE3EfH1r1ADqtfSdVCToUG868RvUUkgDKf31mGDtKsAYz2oz2AGutZYs" let bitcoin = CoinType.bitcoin let zpubAddr4 = HDWallet.derive(from: zpub, at: DerivationPath(purpose: bitcoin.purpose, coinType: bitcoin, account: 0, change: 0, address: 4))! let zpubAddr11 = HDWallet.derive(from: zpub, at: DerivationPath(purpose: bitcoin.purpose, coinType: bitcoin, account: 0, change: 0, address: 11))! XCTAssertEqual(bitcoin.deriveAddressFromPublicKey(publicKey: zpubAddr4).description, "bc1qm97vqzgj934vnaq9s53ynkyf9dgr05rargr04n") XCTAssertEqual(bitcoin.deriveAddressFromPublicKey(publicKey: zpubAddr11).description, "bc1qxr4fjkvnxjqphuyaw5a08za9g6qqh65t8qwgum") } func testDeriveFromZPub2() { let zpub = "zpub6qeA5j9oSq8tZaYEBTp1X61ZSjeen6HbiUBSG4KLPD8d65Pi7eSMPNuxCqgbLdtnim2hgnJEzmE6jhFoJXtJdRxRKRdNFQBJ6iidx9BHGyk" let bitcoin = CoinType.bitcoin let path = DerivationPath(purpose: bitcoin.purpose, coinType: bitcoin, account: 0, change: 0, address: 0) let pubkey = HDWallet.derive(from: zpub, at: path)! let address = bitcoin.deriveAddressFromPublicKey(publicKey: pubkey) XCTAssertEqual(pubkey.data.hexString, "039fdd3652495d01b6a363f8db8b3adce09f83ea5c43ff872ad0a39192340256b0") XCTAssertEqual(address.description, "bc1qearv5ezm3xfgy2t98denkzxwst4f35fvz608wa") } func testDeriveRavencoin() { let ravencoin = CoinType.ravencoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: ravencoin) let address = ravencoin.deriveAddress(privateKey: key) XCTAssertEqual("RHQmrg7nNFnRUwg2mH7GafhRY3ZaF6FB2x", address) } func testDeriveTerra() { let coin = CoinType.terra let key = HDWallet.test.getKeyForCoin(coin: coin) let address = CoinType.terra.deriveAddress(privateKey: key) XCTAssertEqual(address, "terra1jf9aaj9myrzsnmpdr7twecnaftzmku2mhs2hfe") } func testDeriveMonacoin() { let monacoin = CoinType.monacoin let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: monacoin) let address = monacoin.deriveAddress(privateKey: key) XCTAssertEqual("MHkScH5duuiaAkdQ22NkLWmXqWnjq3hThM", address) } func testDeriveFIO() { let fio = CoinType.fio let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: fio) let address = fio.deriveAddress(privateKey: key) XCTAssertEqual("FIO5J2xdfWygeNdHZNZRzRws8YGbVxjUXtp4eP8KoGkGKoLFQ7CaU", address) } func testDeriveAlgorand() { let algo = CoinType.algorand let wallet = HDWallet.test let key = wallet.getKeyForCoin(coin: algo) let address = algo.deriveAddress(privateKey: key) XCTAssertEqual("VEFQ2IIW7CVKDLFEY53BMVJYKURC7KJTCW6U6R2CMQLQXZI52SCFSYASEY", address) } }
43.660477
220
0.72497
673e50a03c08f10df2995e99bfedae7db25bf564
1,242
// // FirendsViewModel.swift // RxController_Example // // Created by Meng Li on 12/3/19. // Copyright © 2019 MuShare. All rights reserved. // import RxCocoa import RxDataSourcesSingleSection import RxSwift import Fakery class FriendsViewModel: BaseViewModel { private let nameRealy = BehaviorRelay<String?>(value: nil) private let firindsRelay = BehaviorRelay<[String]>(value: []) init(name: String) { super.init() nameRealy.accept(name) let faker = Faker(locale: "nb-NO") firindsRelay.accept((0...Int.random(in: 5...10)).map { _ in faker.name.name() }) } var title: Observable<String> { nameRealy.filter { $0 != nil }.map { "\($0!)'s friends" } } var friendSection: Observable<SingleSection<Selection>> { firindsRelay .map { $0.map { Selection(title: $0, accessory: .disclosureIndicator) } } .map { SingleSection.create($0) } } func pick(at index: Int) { guard 0..<firindsRelay.value.count ~= index else { return } steps.accept(FriendsStep.profile(firindsRelay.value[index])) } }
24.84
88
0.574074
f735b98f588a47b9e6f31d181f51fb73e685493a
1,642
// // AuthenticateThenExpandPayloadMiddleware.swift // Presentation // // Created by iq3AddLi on 2019/10/07. // import Domain import Vapor /// Middleware to processes that requires authentication and ask for JWT Payload Relay struct AuthenticateThenExpandPayloadMiddleware: Middleware { // MARK: Properties /// The use case for authentication. /// /// See `AuthenticateMiddlewareUseCase`. let useCase = AuthenticateMiddlewareUseCase() // MARK: Implementation as a Middleware /// Middleware processing. /// - Parameters: /// - request: See `Vapor.Request`. /// - next: A next responder. See `Responder`. /// - throws: /// Error is thrown in the following cases. /// * HTTPHeader has no Authorization. /// * JWT validation fails. /// - returns: /// The `Future` that returns `Response`. func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> { // Get Authentication: Token * guard let token = request.headers.tokenAuthorization?.token else { return request.eventLoop.makeFailedFuture(Error("failed")) } // Verify then expand payload let payload: SessionPayload do { payload = try useCase.payload(by: token) }catch{ return request.eventLoop.makeFailedFuture(Error("failed")) } // stored relay service value request.storage[VerifiedUserEntity.Key] = VerifiedUserEntity(id: payload.id, username: payload.username, token: token) return next.respond(to: request) } }
30.407407
126
0.6419
147e3d3f7a6692f0e68a014cb849c054cea8d238
2,559
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// /// A wrapper that transparently includes a parsable type. /// /// Use an option group to include a group of options, flags, or arguments /// declared in a parsable type. /// /// struct GlobalOptions: ParsableArguments { /// @Flag(name: .shortAndLong) /// var verbose: Bool /// /// @Argument() /// var values: [Int] /// } /// /// struct Options: ParsableArguments { /// @Option() /// var name: String /// /// @OptionGroup() /// var globals: GlobalOptions /// } /// /// The flag and positional arguments declared as part of `GlobalOptions` are /// included when parsing `Options`. @propertyWrapper public struct OptionGroup<Value: ParsableArguments>: Decodable, ParsedWrapper { internal var _parsedValue: Parsed<Value> internal init(_parsedValue: Parsed<Value>) { self._parsedValue = _parsedValue } public init(from decoder: Decoder) throws { if let d = decoder as? SingleValueDecoder, let value = try? d.previousValue(Value.self) { self.init(_parsedValue: .value(value)) } else { try self.init(_decoder: decoder) if let d = decoder as? SingleValueDecoder { d.saveValue(wrappedValue) } } do { try wrappedValue.validate() } catch { throw ParserError.userValidationError(error) } } /// The value presented by this property wrapper. public var wrappedValue: Value { get { switch _parsedValue { case .value(let v): return v case .definition: fatalError(directlyInitializedError) } } set { _parsedValue = .value(newValue) } } } extension OptionGroup: CustomStringConvertible { public var description: String { switch _parsedValue { case .value(let v): return String(describing: v) case .definition: return "OptionGroup(*definition*)" } } } extension OptionGroup { /// Creates a property that represents another parsable type. public init() { self.init(_parsedValue: .init { _ in ArgumentSet(Value.self) }) } }
26.381443
80
0.600625
11f6195c86e10bcb11c8b7c1183711c756ce87e0
225
import UIKit extension UIBezierPath { convenience init(lineIn rect: CGRect) { self.init() move(to: CGPoint(x: rect.minX, y: rect.midY)) addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) } }
17.307692
56
0.604444
4ae8df60a520cb8638b70f62d1ddf2d35296f61e
619
@testable import Kickstarter_Framework @testable import KsApi import Library import PlaygroundSupport import Prelude import Prelude_UIKit import UIKit // Instantiate the Settings view controller. initialize() let controller = Storyboard.DebugPushNotifications.instantiate(DebugPushNotificationsViewController.self) // Set the device type and orientation. let (parent, _) = playgroundControllers(device: .phone4_7inch, orientation: .portrait, child: controller) // Render the screen. let frame = parent.view.frame |> CGRect.lens.size.height .~ 1_400 PlaygroundPage.current.liveView = parent parent.view.frame = frame
30.95
105
0.817447
75ceca940f012ad78035473940c9dae814b195f9
746
// // LogoutFooterButton.swift // Tinder // // Created by Gin Imor on 11/2/21. // Copyright © 2021 Brevity. All rights reserved. // import UIKit class LogoutFooterButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { setTitle("Log out", for: .normal) setTitleColor(.systemRed, for: .normal) backgroundColor = .white titleLabel?.font = .systemFont(ofSize: 20) contentEdgeInsets = .init(16, 0) layer.masksToBounds = true } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = floor(bounds.height / 2) } }
20.722222
55
0.656836
89a25990072da78bb80559e5919ce3e9d953ea28
4,014
// // ViewController.swift // GithubDemo // // Created by Nhan Nguyen on 5/12/15. // Copyright (c) 2015 codepath. All rights reserved. // import UIKit import MBProgressHUD import AFNetworking // Main ViewController class RepoResultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableViewRepos: UITableView! var searchBar: UISearchBar! var searchSettings = GithubRepoSearchSettings() var repos: [GithubRepo]! = [] override func viewDidLoad() { super.viewDidLoad() tableViewRepos.estimatedRowHeight = 100 tableViewRepos.rowHeight = UITableViewAutomaticDimension // Initialize the UISearchBar searchBar = UISearchBar() searchBar.delegate = self // Add SearchBar to the NavigationBar searchBar.sizeToFit() navigationItem.titleView = searchBar // Perform the first search when the view controller first loads doSearch() } // Perform the search. fileprivate func doSearch() { MBProgressHUD.showAdded(to: self.view, animated: true) // Perform request to GitHub API to get the list of repositories GithubRepo.fetchRepos(searchSettings, successCallback: { (newRepos) -> Void in self.repos = [] // Print the returned repositories to the output window for repo in newRepos { print(repo) self.repos.append(repo) } self.tableViewRepos.reloadData() MBProgressHUD.hide(for: self.view, animated: true) }, error: { (error) -> Void in print(error) }) } // MARK: TableView Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } @objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "repoCell", for: indexPath) as! RepoTableViewCell cell.lblName.text = repos[indexPath.row].name cell.lblForks.text = "\(repos[indexPath.row].forks!)" cell.lblStars.text = "\(repos[indexPath.row].stars!)" cell.lblDescription.text = repos[indexPath.row].repoDescription cell.lblOwner.text = repos[indexPath.row].ownerHandle let imgUrl = URL(string: repos[indexPath.row].ownerAvatarURL!) cell.imgAvatar.setImageWith(imgUrl!) return cell } @objc(tableView:didSelectRowAtIndexPath:) func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) } @IBAction func onSettingsBtnTap(_ sender: AnyObject) { } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let settingsVC = segue.destination as! SettingsViewController settingsVC.doneHandler = {(minStars: Int) -> Void in self.searchSettings.minStars = minStars self.doSearch() self.dismiss(animated: true, completion: nil) } } } // SearchBar methods extension RepoResultsViewController: UISearchBarDelegate { func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { searchBar.setShowsCancelButton(true, animated: true) return true } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { searchBar.setShowsCancelButton(false, animated: true) return true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = "" searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchSettings.searchString = searchBar.text searchBar.resignFirstResponder() doSearch() } }
31.359375
140
0.653463
3af5af5e58cc04bf6065e67a2d92afbde4ae8e22
1,853
import ObjectiveC #if os(iOS) import UIKit #elseif os(macOS) import AppKit #endif extension ViewType { internal static func swizzle() { guard let from = class_getInstanceMethod(ViewType.classForCoder(), NSSelectorFromString("engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:")) else { fatalError("Could not get instance method for ViewType.engine:willBreakConstraint:dueToMutuallyExclusiveConstraints:") } guard let to = class_getInstanceMethod(ViewType.classForCoder(), #selector(ViewType._engine(engine:constraint:exclusiveConstraints:))) else { fatalError("Could not get instance method for ViewType.\(#selector(ViewType._engine(engine:constraint:exclusiveConstraints:)))") } method_exchangeImplementations(from, to) } @objc internal func _engine(engine: AnyObject, constraint: NSLayoutConstraint, exclusiveConstraints: [NSLayoutConstraint]) { gedatsuAssert(Thread.isMainThread) gedatsuAssert(NSClassFromString("NSISEngine") == engine.classForCoder, "Unexpected receive argument for NSEngine") defer { _engine(engine: engine, constraint: constraint, exclusiveConstraints: exclusiveConstraints) } #if os(iOS) guard let isLoggingSuspend = value(forKey: "_isUnsatisfiableConstraintsLoggingSuspended") as? Bool else { fatalError("Could not get value for _isUnsatisfiableConstraintsLoggingSuspended") } if isLoggingSuspend { return } #endif let context = Context(view: self, constraint: constraint, exclusiveConstraints: exclusiveConstraints) context.buildTree() shared?.interceptor.save { if var shared = shared { Swift.print(format(context: context), to: &shared) } } } }
45.195122
168
0.697787
e87f8f8e7bb27b4cbd3d99bbacc49172770ae67a
1,149
import UIKit open class BaseCoordinator: Coordinator { public private(set) var childCoordinators: [Coordinator] = [] public let router: Router init(router: Router) { self.router = router } open func start() {} public func dismiss(child coordinator: Coordinator?) { router.dismissModule() removeDependency(coordinator) } public func addDependency(_ coordinator: Coordinator) { guard !childCoordinators.contains(where: { $0 === coordinator }) else { return } childCoordinators.append(coordinator) } public func removeDependency(_ coordinator: Coordinator?) { guard !childCoordinators.isEmpty, let coordinator = coordinator else { return } if let coordinator = coordinator as? BaseCoordinator, !coordinator.childCoordinators.isEmpty { coordinator.childCoordinators.filter { $0 !== coordinator }.forEach { coordinator.removeDependency($0) } } childCoordinators.removeAll { $0 === coordinator } } public func clearChildCoordinators() { childCoordinators.forEach { removeDependency($0) } } }
31.916667
116
0.670148
79fb1e73307ec327714936f3a8f3db595baa3f40
6,074
// // UIHelperService.swift // Ana 57357 // // Created by Wissa Azmy on 7/22/19. // Copyright © 2019 Wissa Azmy. All rights reserved. // import Foundation import UIKit public class UIReactor { // MARK: - UI Components setup public class func fuseBtn(ofType btnType: UIButton.ButtonType, title: String, titleColor: UIColor, cornerRadius: CGFloat, fontSize: CGFloat = 15, backgroundColor: UIColor = .white) -> UIButton { let button = UIButton(type: btnType) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(title, for: .normal) button.setTitleColor(titleColor, for: .normal) button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) button.layer.cornerRadius = cornerRadius button.backgroundColor = backgroundColor return button } public class func fuseTxtField(withPlaceholder placeholder: String, fontSize: CGFloat = 14, iconName: String = "") -> UITextField { let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.layer.cornerRadius = 18 textField.layer.borderColor = #colorLiteral(red: 0.9128934145, green: 0.9176079035, blue: 0.930550158, alpha: 1) textField.layer.borderWidth = 1 textField.placeholder = placeholder textField.font = UIFont.systemFont(ofSize: fontSize) textField.textAlignment = .natural textField.clipsToBounds = true if let image = UIImage(named: iconName) { textField.addPaddingLeftIcon(image, padding: 20) } else { textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0)) textField.leftViewMode = .always } return textField } public class func fuseLabel(withText text: String = "", txtColor: UIColor = .black, font: UIFont = UIFont.systemFont(ofSize: 12)) -> UILabel { let label = UILabel() label.font = font label.textColor = txtColor label.text = text label.numberOfLines = 0 label.textAlignment = .natural label.translatesAutoresizingMaskIntoConstraints = false return label } public class func fuseImageView(withImageNamed imageName: String = "") -> UIImageView { let imageView = UIImageView() if let image = UIImage(named: imageName) { imageView.image = image } imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView } } // MARK: - Navigation Methods extension UIReactor { // REMOVE VIEW CONTROLLER FROM THE NAVIGATION STACK OF The Sender public static func popViewCotroller(sender: UIViewController) { sender.navigationController?.popViewController(animated: true) } @objc public static func segueToController( withName controllerName: String, from sender: UIViewController ) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let destinationVC = storyboard.instantiateViewController(withIdentifier: controllerName) as UIViewController sender.navigationController?.pushViewController(destinationVC, animated: true) } } // MARK: - Alerts, ActionSheets and ActivityIndicator extension UIReactor { public static func showActivityIndicator(on view: UIView, color: UIColor = .gray) -> UIActivityIndicatorView { let activityIndicator = UIActivityIndicatorView() activityIndicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0) activityIndicator.center = view.center activityIndicator.hidesWhenStopped = true activityIndicator.style = UIActivityIndicatorView.Style.whiteLarge activityIndicator.color = color view.addSubview(activityIndicator) return activityIndicator } public static func presentRequiredFieldAlert(on sender: UIViewController, localizedTitle: String, localizedMsg: String) { let alert = UIAlertController( title: NSLocalizedString(localizedTitle, comment: ""), message: NSLocalizedString(localizedMsg, comment: ""), preferredStyle: .alert ) let ok = UIAlertAction( title: NSLocalizedString("Ok", comment: ""), style: .cancel ) alert.addAction(ok) sender.present(alert, animated: true, completion: nil) } public static func presentRequiredAlert(on sender: UIViewController, localizedTitle: String, localizedMsg: String) { let alert = UIAlertController( title: NSLocalizedString(localizedTitle, comment: ""), message: NSLocalizedString(localizedMsg, comment: ""), preferredStyle: .alert ) let ok = UIAlertAction( title: NSLocalizedString("Ok", comment: ""), style: .cancel ) alert.addAction(ok) sender.present(alert, animated: true, completion: nil) } public static func presentInternetConnectionAlert(on sender: UIViewController, indicator: UIActivityIndicatorView? = nil) { let dataLoadingAlert = UIAlertController( title: NSLocalizedString("requiredInternetAlertTitle", comment: ""), message: NSLocalizedString("requiredInternetAlertMsg", comment: ""), preferredStyle: .alert ) let tryAgain = UIAlertAction( title: NSLocalizedString("tryAgainAlerAction", comment: ""), style: .default, handler: { (action) in sender.viewDidLoad() } ) let cancel = UIAlertAction( title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil ) dataLoadingAlert.addActions(tryAgain, cancel) sender.present(dataLoadingAlert, animated: true, completion: { indicator?.stopAnimating() }) } }
39.960526
198
0.656734
ac28e35632c36c802747882c7a327982619c96a7
1,329
// // EventCell.swift // SwiftHub // // Created by Sygnoos9 on 9/6/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import UIKit import RxSwift class EventCell: DetailedTableViewCell { override func makeUI() { super.makeUI() titleLabel.numberOfLines = 2 secondDetailLabel.numberOfLines = 0 leftImageView.cornerRadius = 25 } func bind(to viewModel: EventCellViewModel) { cellDisposeBag = DisposeBag() viewModel.title.drive(titleLabel.rx.text).disposed(by: rx.disposeBag) viewModel.detail.drive(detailLabel.rx.text).disposed(by: rx.disposeBag) viewModel.secondDetail.drive(secondDetailLabel.rx.text).disposed(by: rx.disposeBag) viewModel.imageUrl.drive(leftImageView.rx.imageURL).disposed(by: rx.disposeBag) viewModel.imageUrl.filterNil().drive(onNext: { [weak self] (url) in self?.leftImageView.hero.id = url.absoluteString }).disposed(by: rx.disposeBag) viewModel.badge.drive(badgeImageView.rx.image).disposed(by: rx.disposeBag) viewModel.badgeColor.drive(badgeImageView.rx.tintColor).disposed(by: rx.disposeBag) leftImageView.rx.tap().map { _ in viewModel.event.actor }.filterNil() .bind(to: viewModel.userSelected).disposed(by: cellDisposeBag) } }
34.973684
91
0.694507
21e1a94724e024f6f94676721b6c0b65100eb24c
9,038
/* * Copyright 2019 Google LLC. All Rights Reserved. * * 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 UIKit import MaterialComponents.MaterialShadowLayer /// Displays and triggers actions in a collection view. Selecting a cell will call the handler and /// dismiss the view controller. class PopUpMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { // MARK: - Properties /// The collection view's container view. let collectionViewContainer = ShadowedView() /// Pop up menu content insets. This is how close to each edge of the screen it is allowed to be. static let contentInsets = UIEdgeInsets(top: PopUpMenuCell.height, left: 10, bottom: PopUpMenuCell.height, right: 10) /// Additional top inset, used to account for presenting in views containing an app bar. Pass a /// value in to prevent the menu from positioning itself over the app bar. Only used when /// passing an anchor position in to `presentFrom` and not a source view. var additionalTopContentInset: CGFloat = 0 /// Dims the view behind the wrapper view. var isBackgroundDim: Bool = false { didSet { view.backgroundColor = isBackgroundDim ? UIColor(white: 0, alpha: 0.3) : .clear } } private var actions = [PopUpMenuAction]() private let popUpMenuCellIdentifier = "popUpMenuCellIdentifier" private let popUpMenuTransitionController = PopUpMenuTransitionController() private let popUpMenuMinimumWidth: CGFloat = 160 private let collectionView: UICollectionView // The pop up menu content size. private var contentSize: CGSize { // Width, calculated to fit the largest action title, plus text insets. Does not allow a width // narrower than `popUpMenuMinimumWidth` or wider than the view bounds minus `contentInsets`. var width = popUpMenuMinimumWidth for action in actions { var actionWidth = ceil(action.title.labelWidth(font: PopUpMenuCell.textLabelFont)) + PopUpMenuCell.margins.left + PopUpMenuCell.margins.right if action.icon != nil { actionWidth += PopUpMenuCell.imageViewSize.width + PopUpMenuCell.textToImageSpacing } if actionWidth > width { width = actionWidth } } width = min(view.bounds.size.width - PopUpMenuViewController.contentInsets.left - PopUpMenuViewController.contentInsets.right, width) // Height, calculated to fit the number of rows needed to show all actions. Does not allow a // height taller than the view bounds minus `contentInsets`. let maximumHeight = view.bounds.size.height - PopUpMenuViewController.contentInsets.top - PopUpMenuViewController.contentInsets.bottom let height = min(maximumHeight, actionsHeight) // Size. return CGSize(width: width, height: height) } // The height of the actions, if allowed infinite bounds. private var actionsHeight: CGFloat { return PopUpMenuCell.height * CGFloat(actions.count) } private var collectionViewLayout: UICollectionViewFlowLayout = { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.minimumLineSpacing = 0 return collectionViewLayout }() // MARK: Public init() { collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Always register collection view cells early to avoid a reload occurring first. collectionView.register(PopUpMenuCell.self, forCellWithReuseIdentifier: popUpMenuCellIdentifier) // Shadowed wrapper view. view.addSubview(collectionViewContainer) collectionViewContainer.setElevation(points: ShadowElevation.menu.rawValue) // Collection view. collectionView.alwaysBounceVertical = false collectionView.backgroundColor = .white collectionView.dataSource = self collectionView.delegate = self collectionView.frame = collectionViewContainer.bounds collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionViewContainer.addSubview(collectionView) // Gesture recognizer for canceling when touches occur outside the pop up menu view. let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) tapGestureRecognizer.cancelsTouchesInView = false view.addGestureRecognizer(tapGestureRecognizer) preferredContentSize = contentSize } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // If the preferred content size is too small to fit all actions on screen at a time, flash the // scroll indicator. if preferredContentSize.height < actionsHeight { collectionView.flashScrollIndicators() } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) dismiss(animated: true) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } /// Adds a pop up menu action to be displayed. /// /// - Parameter action: The action. func addAction(_ action: PopUpMenuAction) { addActions([action]) } /// Adds pop up menu actions to be displayed. /// /// - Parameter actions: The actions. func addActions(_ actions: [PopUpMenuAction]) { self.actions.append(contentsOf: actions) } /// Presents the pop up menu view controller. /// /// - Parameters: /// - viewController: The presenting view controller. /// - position: The position to display the pop up menu in. /// - Note: If a position is not passed in, the pop up menu view will be positioned in the center. func present(from viewController: UIViewController, position: PopUpMenuPosition? = nil) { modalPresentationStyle = .custom popUpMenuTransitionController.position = position transitioningDelegate = popUpMenuTransitionController viewController.present(self, animated: true) accessibilityViewIsModal = true } override func accessibilityPerformEscape() -> Bool { dismiss(animated: true) return true } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return actions.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: popUpMenuCellIdentifier, for: indexPath) if let popUpMenuCell = cell as? PopUpMenuCell { popUpMenuCell.icon = actions[indexPath.item].icon popUpMenuCell.textLabel.text = actions[indexPath.item].title popUpMenuCell.accessibilityLabel = actions[indexPath.item].accessibilityLabel popUpMenuCell.accessibilityHint = actions[indexPath.item].accessibilityHint popUpMenuCell.isEnabled = actions[indexPath.item].isEnabled } return cell } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let action = actions[indexPath.item] guard action.isEnabled else { return } dismiss(animated: true, completion: { guard let handler = action.handler else { return } handler(action) }) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width, height: PopUpMenuCell.height) } // MARK: - Gesture recognizers @objc func handleTapGesture(_ tapGestureRecognizer: UITapGestureRecognizer) { let point = tapGestureRecognizer.location(in: collectionView) if !collectionView.point(inside: point, with: nil) { dismiss(animated: true) } } }
37.658333
100
0.717083
76f335d62bf7863dbbf074a3319716147ac304db
2,240
// RUN: %empty-directory(%t.mcp) // RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -Xcc -w -typecheck %s -module-cache-path %t.mcp -disable-named-lazy-member-loading 2>&1 | %FileCheck %s // REQUIRES: objc_interop // CHECK-NOT: warning: import ObjCIRExtras func test(_ i: Int) { let t = SwiftNameTest() t.theMethod(number: i) _ = t.renamedSomeProp _ = type(of: t).renamedClassProp _ = circularFriends(_:_:) // We only see these five warnings because Clang can catch the other invalid // cases, and marks the attribute as invalid ahead of time. // CHECK: warning: too few parameters in swift_name attribute (expected 2; got 1) // CHECK: + (instancetype)g:(id)x outParam:(int *)foo SWIFT_NAME(init(g:)); // CHECK-NOT: warning: // CHECK: note: please report this issue to the owners of 'ObjCIRExtras' // CHECK-NOT: warning: // CHECK: warning: too few parameters in swift_name attribute (expected 2; got 1) // CHECK: + (instancetype)testW:(id)x out:(id *)outObject SWIFT_NAME(ww(_:)); // CHECK-NOT: warning: // CHECK: note: please report this issue to the owners of 'ObjCIRExtras' // CHECK-NOT: warning: // CHECK: warning: cycle detected while resolving 'CircularName' in swift_name attribute for 'CircularName' // CHECK: SWIFT_NAME(CircularName.Inner) @interface CircularName : NSObject @end // CHECK-NOT: {{warning|note}}: // CHECK: note: please report this issue to the owners of 'ObjCIRExtras' // CHECK-NOT: warning: // CHECK: warning: cycle detected while resolving 'MutuallyCircularNameB' in swift_name attribute for 'MutuallyCircularNameA' // CHECK: SWIFT_NAME(MutuallyCircularNameB.Inner) @interface MutuallyCircularNameA : NSObject @end // CHECK-NOT: {{warning|note}}: // CHECK: note: while resolving 'MutuallyCircularNameA' in swift_name attribute for 'MutuallyCircularNameB' // CHECK: SWIFT_NAME(MutuallyCircularNameA.Inner) @interface MutuallyCircularNameB : NSObject @end // CHECK-NOT: {{warning|note}}: // CHECK: note: please report this issue to the owners of 'ObjCIRExtras' // CHECK-NOT: {{warning|note}}: // CHECK: SWIFT_NAME(MutuallyCircularNameB.Inner) @interface MutuallyCircularNameA : NSObject @end }
43.921569
197
0.721875
ed5a19422d7a026170c014c23baec3f68e7481c1
3,159
// // ALKBaseViewController.swift // ApplozicSwift // // Created by Mukesh Thawani on 04/05/17. // Copyright © 2017 Applozic. All rights reserved. // import KommunicateCore_iOS_SDK import UIKit open class ALKBaseViewController: UIViewController, ALKConfigurable { public var configuration: ALKConfiguration! public required init(configuration: ALKConfiguration) { self.configuration = configuration super.init(nibName: nil, bundle: nil) addObserver() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) NSLog("🐸 \(#function) 🍀🍀 \(self) 🐥🐥🐥🐥") addObserver() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add the back button in case if first view controller is nil or is not same as current VC OR // Add the back button in case if first view controller is ALKConversationViewController and current VC is ALKConversationViewController if navigationController?.viewControllers.first != self { navigationItem.leftBarButtonItem = backBarButtonItem() } else if let vc = navigationController?.viewControllers.first, vc.isKind(of: ALKConversationViewController.self) { navigationItem.leftBarButtonItem = backBarButtonItem() } if configuration.hideNavigationBarBottomLine { navigationController?.navigationBar.hideBottomHairline() } } override open func viewDidLoad() { super.viewDidLoad() checkPricingPackage() checkForLanguageDirection() } func checkForLanguageDirection() { let language = NSLocale.preferredLanguages[0] let direction = NSLocale.characterDirection(forLanguage: language) if direction == NSLocale.LanguageDirection.rightToLeft { UIView.appearance().semanticContentAttribute = .forceRightToLeft } } @objc func backTapped() { _ = navigationController?.popViewController(animated: true) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NSLog("🐸 \(#function) 🍀🍀 \(self) 🐥🐥🐥🐥") addObserver() } open func addObserver() {} open func removeObserver() {} deinit { removeObserver() NSLog("💩 \(#function) ❌❌ \(self)‼️‼️‼️‼️") } func checkPricingPackage() { if ALApplicationInfo().isChatSuspended() { showAccountSuspensionView() } } open func showAccountSuspensionView() {} func backBarButtonItem() -> UIBarButtonItem { var backImage = UIImage(named: "icon_back", in: Bundle.applozic, compatibleWith: nil) backImage = backImage?.imageFlippedForRightToLeftLayoutDirection() let backButton = UIBarButtonItem( image: backImage, style: .plain, target: self, action: #selector(backTapped) ) backButton.accessibilityIdentifier = "conversationBackButton" return backButton } }
31.909091
145
0.655271
f53bb159da78d0aef9107dc43da21a470be93ce2
248
// // TreeExplorerApp.swift // TreeExplorer // // Created by Julian Arias Maetschl on 07-01-21. // import SwiftUI @main struct TreeExplorerApp: App { var body: some Scene { WindowGroup { ContentView() } } }
13.777778
49
0.592742
330d03d08c6751a1fb5445b8ffd42eac900e0f50
5,640
/* * Copyright 2019 Google * * 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 FirebaseFirestore #if swift(>=5.1) /// A type that can initialize itself from a Firestore Timestamp, which makes /// it suitable for use with the `@ServerTimestamp` property wrapper. /// /// Firestore includes extensions that make `Timestamp`, `Date`, and `NSDate` /// conform to `ServerTimestampWrappable`. public protocol ServerTimestampWrappable { /// Creates a new instance by converting from the given `Timestamp`. /// /// - Parameter timestamp: The timestamp from which to convert. init(from timestamp: Timestamp) /// Converts this value into a Firestore `Timestamp`. /// /// - Returns: A `Timestamp` representation of this value. func timestampValue() -> Timestamp } extension Date: ServerTimestampWrappable { init(from timestamp: Timestamp) { self = timestamp.dateValue() } func timestampValue() -> Timestamp { return Timestamp(date: self) } } extension NSDate: ServerTimestampWrappable { init(from timestamp: Timestamp) { let interval = timestamp.dateValue().timeIntervalSince1970 self = NSDate(timeIntervalSince1970: interval) } func timestampValue() -> Timestamp { return Timestamp(date: self) } } extension Timestamp: ServerTimestampWrappable { init(from timestamp: Timestamp) { self = timestamp } func timestampValue() -> Timestamp { return self } } /// A property wrapper that marks an `Optional<Timestamp>` field to be /// populated with a server timestamp. If a `Codable` object being written /// contains a `nil` for an `@ServerTimestamp`-annotated field, it will be /// replaced with `FieldValue.serverTimestamp()` as it is sent. /// /// Example: /// ``` /// struct CustomModel { /// @ServerTimestamp var ts: Timestamp? /// } /// ``` /// /// Then writing `CustomModel(ts: nil)` will tell server to fill `ts` with /// current timestamp. @propertyWrapper public struct ServerTimestamp<Value>: Codable, Equatable where Value: ServerTimestampWrappable & Codable & Equatable { var value: Value? public init(wrappedValue value: Value?) { self.value = value } public var wrappedValue: Value? { get { value } set { value = newValue } } // MARK: Codable public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { value = nil } else { value = Value(from: try container.decode(Timestamp.self)) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if let value = value { try container.encode(value.timestampValue()) } else { try container.encode(FieldValue.serverTimestamp()) } } } #endif // swift(>=5.1) /// A compatibility version of `ServerTimestamp` that does not use property /// wrappers, suitable for use in older versions of Swift. /// /// Wraps a `Timestamp` field to mark that it should be populated with a server /// timestamp. If a `Codable` object being written contains a `.pending` for an /// `Swift4ServerTimestamp` field, it will be replaced with /// `FieldValue.serverTimestamp()` as it is sent. /// /// Example: /// ``` /// struct CustomModel { /// var ts: Swift4ServerTimestamp /// } /// ``` /// /// Then `CustomModel(ts: .pending)` will tell server to fill `ts` with current /// timestamp. @available(swift, deprecated: 5.1) public enum Swift4ServerTimestamp: Codable, Equatable { /// When being read (decoded) from Firestore, NSNull values will be mapped to /// `pending`. When being written (encoded) to Firestore, `pending` means /// requesting server to set timestamp on the field (essentially setting value /// to FieldValue.serverTimestamp()). case pending /// When being read (decoded) from Firestore, non-nil Timestamp will be mapped /// to `resolved`. When being written (encoded) to Firestore, /// `resolved(stamp)` will set the field value to `stamp`. case resolved(Timestamp) /// Returns this value as an `Optional<Timestamp>`. /// /// If the server timestamp is still pending, the returned optional will be /// `.none`. Once resolved, the returned optional will be `.some` with the /// resolved timestamp. public var timestamp: Timestamp? { switch self { case .pending: return .none case let .resolved(timestamp): return .some(timestamp) } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .pending } else { let value = try container.decode(Timestamp.self) self = .resolved(value) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .pending: try container.encode(FieldValue.serverTimestamp()) case let .resolved(value: value): try container.encode(value) } } }
30.989011
80
0.673759
1eb21b3b8f71bfff81b84f90c0975f2608911407
1,267
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) /*: Create a bulleted list of animals ### Some Animals * Cat * Dog * Llama */ import Foundation class Regexp { let internalRegexp: NSRegularExpression let pattern: String init(_ pattern: String) { self.pattern = pattern self.internalRegexp = try! NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) } func isMatch(input: String) -> Bool { let matches = self.internalRegexp.matchesInString( input, options: [], range:NSMakeRange(0, input.characters.count) ) return matches.count > 0 } func matches(input: String) -> [String]? { if self.isMatch(input) { let matches = self.internalRegexp.matchesInString( input, options: [], range:NSMakeRange(0, input.characters.count) ) var results: [String] = [] for i in 0 ..< matches.count { results.append( (input as NSString).substringWithRange(matches[i].range) ) } return results } return nil } } var pattern = "bhoge$" var moji = "def hello(name)" Regexp(pattern).isMatch("hogefugahoge")
25.857143
129
0.632991
f95256a57c5a4e771586dd3f44bf4e66e874d09e
3,885
// // Created by Tom Baranes on 21/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public struct ActivityIndicatorFactory { public static func makeActivityIndicator(activityIndicatorType: ActivityIndicatorType) -> ActivityIndicatorAnimating { return activityIndicatorType.animator } } extension ActivityIndicatorType { func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { self.animator.configureAnimation(in: layer, size: size, color: color) } var animator: ActivityIndicatorAnimating { switch self { case .none: fatalError("Invalid ActivityIndicatorAnimating") case .audioEqualizer: return ActivityIndicatorAnimationAudioEqualizer() case .ballBeat: return ActivityIndicatorAnimationBallBeat() case .ballClipRotate: return ActivityIndicatorAnimationBallClipRotate() case .ballClipRotateMultiple: return ActivityIndicatorAnimationBallClipRotateMultiple() case .ballClipRotatePulse: return ActivityIndicatorAnimationBallClipRotatePulse() case .ballGridBeat: return ActivityIndicatorAnimationBallGridBeat() case .ballGridPulse: return ActivityIndicatorAnimationBallGridPulse() case .ballPulse: return ActivityIndicatorAnimationBallPulse() case .ballPulseRise: return ActivityIndicatorAnimationBallPulseRise() case .ballPulseSync: return ActivityIndicatorAnimationBallPulseSync() case .ballRotate: return ActivityIndicatorAnimationBallRotate() case .ballRotateChase: return ActivityIndicatorAnimationBallRotateChase() case .ballScale: return ActivityIndicatorAnimationBallScale() case .ballScaleMultiple: return ActivityIndicatorAnimationBallScaleMultiple() case .ballScaleRipple: return ActivityIndicatorAnimationBallScaleRipple() case .ballScaleRippleMultiple: return ActivityIndicatorAnimationBallScaleRippleMultiple() case .ballSpinFadeLoader: return ActivityIndicatorAnimationBallSpinFadeLoader() case .ballTrianglePath: return ActivityIndicatorAnimationBallTrianglePath() case .ballZigZag: return ActivityIndicatorAnimationBallZigZag() case .ballZigZagDeflect: return ActivityIndicatorAnimationBallZigZagDeflect() case .cubeTransition: return ActivityIndicatorAnimationCubeTransition() case .lineScale: return ActivityIndicatorAnimationLineScale() case .lineSpinFadeLoader: return ActivityIndicatorAnimationLineSpinFadeLoader() case .lineScaleParty: return ActivityIndicatorAnimationLineScaleParty() case .lineScalePulseOut: return ActivityIndicatorAnimationLineScalePulseOut() case .lineScalePulseOutRapid: return ActivityIndicatorAnimationLineScalePulseOutRapid() case .orbit: return ActivityIndicatorAnimationOrbit() case .pacman: return ActivityIndicatorAnimationPacman() case .semiCircleSpin: return ActivityIndicatorAnimationSemiCircleSpin() case .squareSpin: return ActivityIndicatorAnimationSquareSpin() case .triangleSkewSpin: return ActivityIndicatorAnimationTriangleSkewSpin() case .circleStrokeSpin: return ActivityIndicatorAnimationCircleStrokeSpin() case .circleDashStrokeSpin: return ActivityIndicatorAnimationCircleDashStrokeSpin() case .gear: return ActivityIndicatorAnimationGear() case .tripleGear: return ActivityIndicatorAnimationTripleGear() case .heartBeat: return ActivityIndicatorAnimationHeartBeat() case .triforce: return ActivityIndicatorAnimationTriforce() case .rupee: return ActivityIndicatorAnimationRupee() case .newtonCradle: return ActivityIndicatorAnimationNewtonCradle() case .circlePendulum: return ActivityIndicatorAnimationCirclePendulum() } } }
36.308411
120
0.771429
1143277602a9a60518cc9ae9fbe41eb8813af8ee
562
// // Copyright (c) 2019 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation public extension PaymentController { /// An error that occurred inside PaymentController. public enum Error: Swift.Error { /// Indicates the payment was cancelled by the user. case cancelled /// Indicates the payment could not be completed because the user returned from a redirect through an invalid URL. case invalidReturnURL } }
26.761905
122
0.674377
1cde1a0d8b25e287755c390b653fa5b930f11134
1,493
// // TodayWeather.swift // WeatherZone // // Created by Hardik on 18/02/18. // Copyright © 2018 Hardik Kothari. All rights reserved. // import UIKit import SwiftyJSON class TodayWeather: NSObject { var weather: Weather! var temp: Float = 0.0 var pressure: Float = 0 var humidity: Int = 0 var tempMin: Float = 0.0 var tempMax: Float = 0.0 var visibility: Float = 0.0 var windSpeed: Float = 0.0 var windDeg: Int = 0 var clouds: Int = 0 var date: Date! var sunrise: Date! var sunset: Date! var name: String! } extension TodayWeather { convenience init(json: JSON) { self.init() weather = Weather.init(json: json["weather"][0]) temp = json["main"]["temp"].floatValue pressure = json["main"]["pressure"].floatValue humidity = json["main"]["humidity"].intValue tempMin = json["main"]["temp_min"].floatValue tempMax = json["main"]["temp_max"].floatValue visibility = (Float(json["visibility"].intValue) / 1000.0) windSpeed = (json["wind"]["speed"].floatValue * 18.0) / 5.0 windDeg = json["wind"]["deg"].intValue clouds = json["clouds"]["all"].intValue date = Date.init(timeIntervalSince1970: json["dt"].doubleValue) sunrise = Date.init(timeIntervalSince1970: json["sys"]["sunrise"].doubleValue) sunset = Date.init(timeIntervalSince1970: json["sys"]["sunset"].doubleValue) name = json["name"].stringValue } }
31.104167
86
0.622237
096479d883b3b22fc8e7feac92c43d2d7007b81f
578
import Domain import Utils public final class GistsRepositorySpy: GistsRepository { public init() { } public private(set) var getPublicGistsCalled = false public private(set) var getPublicGistsPagePassed: Int? public var getPublicGistsResultToBeReturned: Result<[GistDigest]>? public func getPublicGists(page: Int, completion: @escaping (Result<[GistDigest]>) -> Void) { getPublicGistsCalled = true getPublicGistsPagePassed = page if let result = getPublicGistsResultToBeReturned { completion(result) } } }
30.421053
97
0.707612
e93720fa81ee7039ec6b72ca4ae62d22ea483c0b
133
extension Widget { public func with(classes: [String]) -> Self { self.classes.append(contentsOf: classes) return self } }
22.166667
47
0.676692
76c8ed0e14f0d911c82bbc74ccb119f87f220f29
966
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import Result import web3swift class GetNameCoordinator { private let server: RPCServer init(forServer server: RPCServer) { self.server = server } func getName( for contract: AlphaWallet.Address, completion: @escaping (Result<String, AnyError>) -> Void ) { let functionName = "name" callSmartContract(withServer: server, contract: contract, functionName: functionName, abiString: web3swift.Web3.Utils.erc20ABI, timeout: TokensDataStore.fetchContractDataTimeout).done { nameResult in if let name = nameResult["0"] as? String { completion(.success(name)) } else { completion(.failure(AnyError(Web3Error(description: "Error extracting result from \(contract.eip55String).\(functionName)()")))) } }.catch { completion(.failure(AnyError($0))) } } }
32.2
207
0.640787
289da4a27ba57417a39c87285d6ca4c3a9a1ad9d
672
// // QYVideoController.swift // QYVideoModule // // Created by cyd on 2020/8/20. // import UIKit import QYUtilCore open class QYVideoController: QYViewController { open override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
21
106
0.660714
f7094deda9e9a78768dc7aaabfc9633a98b1dae9
703
// // ProductDescriptionCoordinator.swift // eStore // // Created by Vladislav Kondrashkov on 3/5/19. // Copyright © 2019 Vladislav Kondrashkov. All rights reserved. // final class ProductDescriptionCoordinator { private let scene: ProductDescriptionScene private let show: ProductDescriptionShow init(scene: ProductDescriptionScene, show: ProductDescriptionShow) { self.scene = scene self.show = show } } // MARK: - Coordinator implementation extension ProductDescriptionCoordinator: Coordinator { func start() { scene.play(productDescriptionShow: show) } func stop(completion: (() -> Void)?) { completion?() } }
23.433333
64
0.677098
4b3399bd9dc5d8b556037f699541002ac0d082f4
3,039
// // Copyright © 2019 Gnosis Ltd. All rights reserved. // import UIKit class MainViewController: UIViewController { var handshakeController: HandshakeViewController! var actionsController: ActionsViewController! var walletConnect: WalletConnect! @IBAction func connect(_ sender: Any) { let connectionUrl = walletConnect.connect() let deepLinkUrl = connectionUrl.replacingOccurrences(of: "wc:", with: "wc://") if let url = URL(string: deepLinkUrl), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { handshakeController = HandshakeViewController.create(code: connectionUrl) present(handshakeController, animated: true) } } override func viewDidLoad() { super.viewDidLoad() walletConnect = WalletConnect(delegate: self) walletConnect.reconnectIfNeeded() } func onMainThread(_ closure: @escaping () -> Void) { if Thread.isMainThread { closure() } else { DispatchQueue.main.async { closure() } } } } extension MainViewController: WalletConnectDelegate { func failedToConnect() { onMainThread { [unowned self] in if let handshakeController = self.handshakeController { handshakeController.dismiss(animated: true) } UIAlertController.showFailedToConnect(from: self) } } func didConnect() { onMainThread { [unowned self] in self.actionsController = ActionsViewController.create(walletConnect: self.walletConnect) if let handshakeController = self.handshakeController { handshakeController.dismiss(animated: false) { [unowned self] in self.present(self.actionsController, animated: false) } } else if self.presentedViewController == nil { self.present(self.actionsController, animated: false) } } } func didDisconnect() { onMainThread { [unowned self] in if let presented = self.presentedViewController { presented.dismiss(animated: false) } UIAlertController.showDisconnected(from: self) } } } extension UIAlertController { func withCloseButton() -> UIAlertController { addAction(UIAlertAction(title: "Close", style: .cancel)) return self } static func showFailedToConnect(from controller: UIViewController) { let alert = UIAlertController(title: "Failed to connect", message: nil, preferredStyle: .alert) controller.present(alert.withCloseButton(), animated: true) } static func showDisconnected(from controller: UIViewController) { let alert = UIAlertController(title: "Did disconnect", message: nil, preferredStyle: .alert) controller.present(alert.withCloseButton(), animated: true) } }
34.146067
103
0.638039
f5f283c6f020e3581f57e79649c92d5c41185b79
264
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { func b { struct A { { } extension NSData { { } { } let h = [ { class A { class case ,
13.894737
87
0.689394
f5e61b5f1bb56a6eebbad2b8c346f47eb55b83e0
731
// // MineViewController.swift // Artoop // // Created by EROMANGA on 2021/2/2. // Copyright © 2021 Artoop. All rights reserved. // import UIKit class MineViewController: BestBaseViewController { override func viewDidLoad() { super.viewDidLoad() self.isHiddenNavigationBar = true // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
23.580645
106
0.670315
d966ad59e6193f346c18d47bcbaec95a3f852ad9
1,830
// // Utils.swift // OpenTokReactNative // // Created by Manik Sachdeva on 11/3/18. // Copyright © 2018 TokBox Inc. All rights reserved. // import Foundation class Utils { static func sanitizeCameraResolution(_ resolution: Any) -> OTCameraCaptureResolution { guard let cameraResolution = resolution as? String else { return .medium }; switch cameraResolution { case "HIGH": return .high; case "LOW": return .low; default: return .medium; } } static func sanitizeFrameRate(_ frameRate: Any) -> OTCameraCaptureFrameRate { guard let cameraFrameRate = frameRate as? Int else { return OTCameraCaptureFrameRate(rawValue: 30)!; } return OTCameraCaptureFrameRate(rawValue: cameraFrameRate)!; } static func sanitizeBooleanProperty(_ property: Any) -> Bool { guard let prop = property as? Bool else { return true; } return prop; } static func getPublisherId(_ publisher: OTPublisher) -> String { let publisherIds = OTRN.sharedState.publishers.filter {$0.value == publisher} guard let publisherId = publisherIds.first else { return ""; } return publisherId.key; } static func convertOTSubscriberVideoEventReasonToString(_ reason: OTSubscriberVideoEventReason) -> String { switch reason { case OTSubscriberVideoEventReason.publisherPropertyChanged: return "PublisherPropertyChanged" case OTSubscriberVideoEventReason.subscriberPropertyChanged: return "SubscriberPropertyChanged" case OTSubscriberVideoEventReason.qualityChanged: return "QualityChanged" case OTSubscriberVideoEventReason.codecNotSupported: return "CodecNotSupported" } } }
33.888889
111
0.667213
cc5c7042f1b4d309da757ac6f877cf0680caedbc
888
// // ConfigPathResolver.swift // App // // Created by Christoph Pageler on 25.01.19. // import Foundation public class ConfigPathResolver { public func resolveConfigPath() throws -> String { // ENV[CONFIG] if let configEnv = ProcessInfo.processInfo.environment["CONFIG"] { return configEnv } // working_directory/mock-config.yml let workingDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) let workingDirectoryConfigPath = workingDirectoryURL.appendingPathComponent("mock-config.yml").path if FileManager.default.fileExists(atPath: workingDirectoryConfigPath) { return workingDirectoryConfigPath } throw ConfigPathResolverError.couldNotResolveConfigPath } } public enum ConfigPathResolverError: Error { case couldNotResolveConfigPath }
23.368421
107
0.708333
6adf56bfabbd1f1849a73acf6fcc7dbb69610d27
430
// // GraphQLQueryWatching.swift // Adequate // // Created by Mathew Gacy on 2/6/21. // Copyright © 2021 Mathew Gacy. All rights reserved. // import AWSAppSync public protocol GraphQLQueryWatching: Cancellable { //associatedtype Query: GraphQLQuery /// Refetch a query from the server. func refetch() } // MARK: - GraphQLQueryWatcher+GraphQLQueryWatching extension GraphQLQueryWatcher: GraphQLQueryWatching {}
21.5
54
0.739535
d5a8faf3cb938967f506dcc94bde0a74c78dd244
339
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/airspeedswift (airspeedswift) // https://twitter.com/AirspeedSwift/status/535452613077401601 // rdar://19067567 enum E { case A } func f() -> (t: (Int,Int),e: E) { return ((0,0),.A) } func h() { let (t,e) = f() print(e) }
18.833333
85
0.651917
71f685001155aad8cf6d283cd850100973d8ac62
847
// // UInt16+Extension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 06/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // /** array of bytes */ extension UInt16 { @_specialize(ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Iterator.Element == UInt8, T.Index == Int { self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Iterator.Element == UInt8, T.Index == Int { let val0 = UInt16(bytes[index.advanced(by: 0)]) << 8 let val1 = UInt16(bytes[index.advanced(by: 1)]) self = val0 | val1 } func bytes(totalBytes: Int = MemoryLayout<UInt16>.size) -> Array<UInt8> { return arrayOfBytes(value: self, length: totalBytes) } }
29.206897
111
0.645809
14241c70c7fe69ee1e5b581acaf929062ed13764
597
import Cocoa class EventMonitor { private var monitor: Any? private let mask: NSEvent.EventTypeMask private let handler: (NSEvent?) -> Void public init(mask: NSEvent.EventTypeMask, handler: @escaping (NSEvent?) -> Void) { self.mask = mask self.handler = handler } deinit { stop() } public func start() { monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as! NSObject } public func stop() { if monitor != nil { NSEvent.removeMonitor(monitor!) monitor = nil } } }
21.321429
98
0.60804
01b2aaca22ba7758b8b1aa5e5fb54a8cfc30bac5
22,430
// // ParseUser+async.swift // ParseUser+async // // Created by Corey Baker on 8/6/21. // Copyright © 2021 Parse Community. All rights reserved. // #if swift(>=5.5) && canImport(_Concurrency) import Foundation public extension ParseUser { // MARK: Async/Await /** Signs up the user *asynchronously*. This will also enforce that the username isn't already taken. - warning: Make sure that password and username are set before calling this method. - parameter username: The username of the user. - parameter password: The password of the user. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the signed in `ParseUser`. - throws: An error of type `ParseError`. */ static func signup(username: String, password: String, options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in Self.signup(username: username, password: password, options: options, completion: continuation.resume) } } /** Signs up the user *asynchronously*. This will also enforce that the username isn't already taken. - warning: Make sure that password and username are set before calling this method. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the signed in `ParseUser`. - throws: An error of type `ParseError`. */ func signup(options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.signup(options: options, completion: continuation.resume) } } /** Makes an *asynchronous* request to log in a user with specified credentials. Returns an instance of the successfully logged in `ParseUser`. This also caches the user locally so that calls to *current* will use the latest logged in user. - parameter username: The username of the user. - parameter password: The password of the user. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the logged in `ParseUser`. - throws: An error of type `ParseError`. */ static func login(username: String, password: String, options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in Self.login(username: username, password: password, options: options, completion: continuation.resume) } } /** Logs in a `ParseUser` *asynchronously* with a session token. Returns an instance of the successfully logged in `ParseUser`. If successful, this saves the session to the keychain, so you can retrieve the currently logged in user using *current*. - parameter sessionToken: The sessionToken of the user to login. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the logged in `ParseUser`. - throws: An error of type `ParseError`. */ func become(sessionToken: String, options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.become(sessionToken: sessionToken, options: options, completion: continuation.resume) } } /** Logs out the currently logged in user *asynchronously*. This will also remove the session from the Keychain, log out of linked services and all future calls to `current` will return `nil`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. */ static func logout(options: API.Options = []) async throws { _ = try await withCheckedThrowingContinuation { continuation in Self.logout(options: options, completion: continuation.resume) } } /** Requests *asynchronously* a password reset email to be sent to the specified email address associated with the user account. This email allows the user to securely reset their password on the web. - parameter email: The email address associated with the user that forgot their password. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. */ static func passwordReset(email: String, options: API.Options = []) async throws { _ = try await withCheckedThrowingContinuation { continuation in Self.passwordReset(email: email, options: options, completion: continuation.resume) } } /** Requests *asynchronously* a verification email be sent to the specified email address associated with the user account. - parameter email: The email address associated with the user. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. */ static func verificationEmail(email: String, options: API.Options = []) async throws { _ = try await withCheckedThrowingContinuation { continuation in Self.verificationEmail(email: email, options: options, completion: continuation.resume) } } /** Fetches the `ParseUser` *aynchronously* with the current data from the server and sets an error if one occurs. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the fetched `ParseUser`. - throws: An error of type `ParseError`. - important: If an object fetched has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func fetch(includeKeys: [String]? = nil, options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.fetch(includeKeys: includeKeys, options: options, completion: continuation.resume) } } /** Saves the `ParseUser` *asynchronously*. - parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the saved `ParseUser`. - throws: An error of type `ParseError`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If you are using `ParseConfiguration.allowCustomObjectId = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `isIgnoreCustomObjectIdConfig = false`. Setting `ParseConfiguration.allowCustomObjectId = true` and `isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func save(isIgnoreCustomObjectIdConfig: Bool = false, options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.save(isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig, options: options, completion: continuation.resume) } } /** Creates the `ParseUser` *asynchronously*. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the saved `ParseUser`. - throws: An error of type `ParseError`. */ func create(options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.create(options: options, completion: continuation.resume) } } /** Replaces the `ParseUser` *asynchronously*. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the saved `ParseUser`. - throws: An error of type `ParseError`. - important: If an object replaced has the same objectId as current, it will automatically replace the current. */ func replace(options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.replace(options: options, completion: continuation.resume) } } /** Updates the `ParseUser` *asynchronously*. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns the saved `ParseUser`. - throws: An error of type `ParseError`. - important: If an object updated has the same objectId as current, it will automatically update the current. */ internal func update(options: API.Options = []) async throws -> Self { try await withCheckedThrowingContinuation { continuation in self.update(options: options, completion: continuation.resume) } } /** Deletes the `ParseUser` *asynchronously*. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. - important: If an object deleted has the same objectId as current, it will automatically update the current. */ func delete(options: API.Options = []) async throws { _ = try await withCheckedThrowingContinuation { continuation in self.delete(options: options, completion: continuation.resume) } } } public extension Sequence where Element: ParseUser { /** Fetches a collection of users *aynchronously* with the current data from the server and sets an error if one occurs. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns an array of Result enums with the object if a fetch was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object fetched has the same objectId as current, it will automatically update the current. */ func fetchAll(includeKeys: [String]? = nil, options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.fetchAll(includeKeys: includeKeys, options: options, completion: continuation.resume) } } /** Saves a collection of users *asynchronously*. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter isIgnoreCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.allowCustomObjectId = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns an array of Result enums with the object if a save was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - warning: If you are using `ParseConfiguration.allowCustomObjectId = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `isIgnoreCustomObjectIdConfig = false`. Setting `ParseConfiguration.allowCustomObjectId = true` and `isIgnoreCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliiding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func saveAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.useTransactions, isIgnoreCustomObjectIdConfig: Bool = false, options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.saveAll(batchLimit: limit, transaction: transaction, isIgnoreCustomObjectIdConfig: isIgnoreCustomObjectIdConfig, options: options, completion: continuation.resume) } } /** Creates a collection of users *asynchronously*. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns an array of Result enums with the object if a save was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func createAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.useTransactions, options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.createAll(batchLimit: limit, transaction: transaction, options: options, completion: continuation.resume) } } /** Replaces a collection of users *asynchronously*. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns an array of Result enums with the object if a save was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object replaced has the same objectId as current, it will automatically replace the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func replaceAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.useTransactions, options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.replaceAll(batchLimit: limit, transaction: transaction, options: options, completion: continuation.resume) } } /** Updates a collection of users *asynchronously*. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns an array of Result enums with the object if a save was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object updated has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ internal func updateAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.useTransactions, options: API.Options = []) async throws -> [(Result<Self.Element, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.updateAll(batchLimit: limit, transaction: transaction, options: options, completion: continuation.resume) } } /** Deletes a collection of users *asynchronously*. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Each element in the array is `nil` if the delete successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object deleted has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. */ func deleteAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.useTransactions, options: API.Options = []) async throws -> [(Result<Void, ParseError>)] { try await withCheckedThrowingContinuation { continuation in self.deleteAll(batchLimit: limit, transaction: transaction, options: options, completion: continuation.resume) } } } #endif
53.151659
120
0.672136
030bb5a2210867e0260aa67b7c95d6e8fab66626
152
// // SearchScreen.swift // gamesdb // // Created by Christoph Schwizer on 25.01.21. // import UIKit class SearchScreen: UIViewController { }
11.692308
46
0.671053
1c85f0bfae96dbbe0fe10c21f4d4551290d5f728
816
// // BuildBetaDetailBuildLinkageResponse.swift // AppStoreConnect-Swift-SDK // // Created by Pascal Edmond on 12/11/2018. // import Foundation #if os(Linux) import FoundationNetworking #endif /// A response containing the ID of the related resource. public struct BuildBetaDetailBuildLinkageResponse: Codable { public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public let `id`: String /// The resource type.Value: builds public let type: String = "builds" } /// The object types and IDs of the related resources. public let data: BuildBetaDetailBuildLinkageResponse.Data /// Navigational links including the self-link and links to the related data. public let links: DocumentLinks }
26.322581
81
0.70098
d7fea972d752c5429fdcaa12f72fd2069adb3550
370
// // Created by Jan Doornbos on 09-11-17. // Copyright © 2017 Move4Mobile. All rights reserved. // import UIKit extension UIView { /** Remove all the subviews from a UIView. - Author: Jeffrey Schonewille - Version: 0.1 */ public func removeAllSubviews() { self.subviews.forEach { $0.removeFromSuperview()} } }
17.619048
57
0.608108
62f6fd2b27f464eef1bc81e881d70e6e55fa6e32
22,882
import Foundation import TSCBasic import TuistCore import TuistGraph import TuistSupport import XcodeProj public struct GroupFileElement: Hashable { var path: AbsolutePath var group: ProjectGroup var isReference: Bool init(path: AbsolutePath, group: ProjectGroup, isReference: Bool = false) { self.path = path self.group = group self.isReference = isReference } } // swiftlint:disable:next type_body_length class ProjectFileElements { // MARK: - Static // swiftlint:disable:next force_try static let localizedRegex = try! NSRegularExpression(pattern: "(.+\\.lproj)/.+", options: []) // MARK: - Attributes var elements: [AbsolutePath: PBXFileElement] = [:] var products: [String: PBXFileReference] = [:] var sdks: [AbsolutePath: PBXFileReference] = [:] var knownRegions: Set<String> = Set([]) // MARK: - Init init(_ elements: [AbsolutePath: PBXFileElement] = [:]) { self.elements = elements } func generateProjectFiles(project: Project, graphTraverser: GraphTraversing, groups: ProjectGroups, pbxproj: PBXProj) throws { var files = Set<GroupFileElement>() try project.targets.forEach { target in try files.formUnion(targetFiles(target: target)) } let projectFileElements = projectFiles(project: project) files.formUnion(projectFileElements) let sortedFiles = files.sorted { (one, two) -> Bool in one.path < two.path } /// Files try generate(files: sortedFiles, groups: groups, pbxproj: pbxproj, sourceRootPath: project.sourceRootPath) // Products let directProducts = project.targets.map { GraphDependencyReference.product(target: $0.name, productName: $0.productNameWithExtension) } // Dependencies let dependencies = try graphTraverser.allProjectDependencies(path: project.path).sorted() try generate(dependencyReferences: Set(directProducts + dependencies), groups: groups, pbxproj: pbxproj, sourceRootPath: project.sourceRootPath, filesGroup: project.filesGroup) } func projectFiles(project: Project) -> Set<GroupFileElement> { var fileElements = Set<GroupFileElement>() /// Config files let configFiles = project.settings.configurations.values.compactMap { $0?.xcconfig } fileElements.formUnion(configFiles.map { GroupFileElement(path: $0, group: project.filesGroup) }) // Additional files fileElements.formUnion(project.additionalFiles.map { GroupFileElement(path: $0.path, group: project.filesGroup, isReference: $0.isReference) }) return fileElements } func targetFiles(target: Target) throws -> Set<GroupFileElement> { var files = Set<AbsolutePath>() files.formUnion(target.sources.map(\.path)) files.formUnion(target.playgrounds) files.formUnion(target.coreDataModels.map(\.path)) files.formUnion(target.coreDataModels.flatMap(\.versions)) if let headers = target.headers { files.formUnion(headers.public) files.formUnion(headers.private) files.formUnion(headers.project) } // Support files if let infoPlist = target.infoPlist, let path = infoPlist.path { files.insert(path) } if let entitlements = target.entitlements { files.insert(entitlements) } // Config files target.settings?.configurations.xcconfigs().forEach { configFilePath in files.insert(configFilePath) } // Elements var elements = Set<GroupFileElement>() elements.formUnion(files.map { GroupFileElement(path: $0, group: target.filesGroup) }) elements.formUnion(target.resources.map { GroupFileElement(path: $0.path, group: target.filesGroup, isReference: $0.isReference) }) target.copyFiles.forEach { elements.formUnion($0.files.map { GroupFileElement(path: $0.path, group: target.filesGroup, isReference: $0.isReference) }) } return elements } func generate(files: [GroupFileElement], groups: ProjectGroups, pbxproj: PBXProj, sourceRootPath: AbsolutePath) throws { try files.forEach { try generate(fileElement: $0, groups: groups, pbxproj: pbxproj, sourceRootPath: sourceRootPath) } } func generate(dependencyReferences: Set<GraphDependencyReference>, groups: ProjectGroups, pbxproj: PBXProj, sourceRootPath: AbsolutePath, filesGroup: ProjectGroup) throws { let sortedDependencies = dependencyReferences.sorted() func generatePrecompiled(_ path: AbsolutePath) throws { let fileElement = GroupFileElement(path: path, group: filesGroup) try generate(fileElement: fileElement, groups: groups, pbxproj: pbxproj, sourceRootPath: sourceRootPath) } try sortedDependencies.forEach { dependency in switch dependency { case let .xcframework(path, _, _, _): try generatePrecompiled(path) case let .framework(path, _, _, _, _, _, _, _): try generatePrecompiled(path) case let .library(path, _, _, _): try generatePrecompiled(path) case let .sdk(sdkNodePath, _, _): generateSDKFileElement(sdkNodePath: sdkNodePath, toGroup: groups.frameworks, pbxproj: pbxproj) case let .product(target: target, productName: productName): generateProduct(targetName: target, productName: productName, groups: groups, pbxproj: pbxproj) } } } private func generateProduct(targetName: String, productName: String, groups: ProjectGroups, pbxproj: PBXProj) { guard products[targetName] == nil else { return } let fileType = RelativePath(productName).extension.flatMap { Xcode.filetype(extension: $0) } let fileReference = PBXFileReference(sourceTree: .buildProductsDir, explicitFileType: fileType, path: productName, includeInIndex: false) pbxproj.add(object: fileReference) groups.products.children.append(fileReference) products[targetName] = fileReference } func generate(fileElement: GroupFileElement, groups: ProjectGroups, pbxproj: PBXProj, sourceRootPath: AbsolutePath) throws { // The file already exists if elements[fileElement.path] != nil { return } let closestRelativeRelativePath = closestRelativeElementPath(path: fileElement.path, sourceRootPath: sourceRootPath) let closestRelativeAbsolutePath = sourceRootPath.appending(closestRelativeRelativePath) let fileElementRelativeToSourceRoot = fileElement.path.relative(to: sourceRootPath) // Add the first relative element. let group: PBXGroup switch fileElement.group { case let .group(name: groupName): group = try groups.projectGroup(named: groupName) } guard let firstElement = addElement(relativePath: closestRelativeRelativePath, isLeaf: closestRelativeRelativePath == fileElementRelativeToSourceRoot, from: sourceRootPath, toGroup: group, pbxproj: pbxproj) else { return } // If it matches the file that we are adding or it's not a group we can exit. if (closestRelativeAbsolutePath == fileElement.path) || !(firstElement.element is PBXGroup) { return } var lastGroup: PBXGroup! = firstElement.element as? PBXGroup var lastPath: AbsolutePath = firstElement.path let components = fileElement.path.relative(to: lastPath).components for component in components.enumerated() { if lastGroup == nil { return } guard let element = addElement(relativePath: RelativePath(component.element), isLeaf: component.offset == components.count - 1, from: lastPath, toGroup: lastGroup!, pbxproj: pbxproj) else { return } lastGroup = element.element as? PBXGroup lastPath = element.path } } // MARK: - Internal @discardableResult func addElement(relativePath: RelativePath, isLeaf: Bool, from: AbsolutePath, toGroup: PBXGroup, pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath)? { let absolutePath = from.appending(relativePath) if elements[absolutePath] != nil { return (element: elements[absolutePath]!, path: from.appending(relativePath)) } // If the path is ../../xx we specify the name // to prevent Xcode from using that as a name. var name: String? let components = relativePath.components if components.count != 1 { name = components.last! } // Add the file element if isLocalized(path: absolutePath) { // Localized container (e.g. /path/to/en.lproj) we don't add it directly // an element will get added once the next path component is evaluated // // note: assumption here is a path to a nested resource is always provided return (element: toGroup, path: absolutePath) } else if isLocalized(path: from) { // Localized file (e.g. /path/to/en.lproj/foo.png) addLocalizedFile(localizedFile: absolutePath, toGroup: toGroup, pbxproj: pbxproj) return nil } else if isVersionGroup(path: absolutePath) { return addVersionGroupElement(from: from, folderAbsolutePath: absolutePath, folderRelativePath: relativePath, name: name, toGroup: toGroup, pbxproj: pbxproj) } else if !(isXcassets(path: absolutePath) || isScnassets(path: absolutePath) || isLeaf) { return addGroupElement(from: from, folderAbsolutePath: absolutePath, folderRelativePath: relativePath, name: name, toGroup: toGroup, pbxproj: pbxproj) } else if isPlayground(path: absolutePath) { addPlayground(from: from, fileAbsolutePath: absolutePath, fileRelativePath: relativePath, name: name, toGroup: toGroup, pbxproj: pbxproj) return nil } else { addFileElement(from: from, fileAbsolutePath: absolutePath, fileRelativePath: relativePath, name: name, toGroup: toGroup, pbxproj: pbxproj) return nil } } func addLocalizedFile(localizedFile: AbsolutePath, toGroup: PBXGroup, pbxproj: PBXProj) { // e.g. // from: resources/en.lproj/ // localizedFile: resources/en.lproj/App.strings // Variant Group let localizedName = localizedFile.basename // e.g. App.strings let localizedContainer = localizedFile.parentDirectory // e.g. resources/en.lproj let variantGroupPath = localizedContainer .parentDirectory .appending(component: localizedName) // e.g. resources/App.strings let variantGroup = addVariantGroup(variantGroupPath: variantGroupPath, localizedName: localizedName, toGroup: toGroup, pbxproj: pbxproj) // Localized element addLocalizedFileElement(localizedFile: localizedFile, variantGroup: variantGroup, localizedContainer: localizedContainer, pbxproj: pbxproj) } private func addVariantGroup(variantGroupPath: AbsolutePath, localizedName: String, toGroup: PBXGroup, pbxproj: PBXProj) -> PBXVariantGroup { if let variantGroup = elements[variantGroupPath] as? PBXVariantGroup { return variantGroup } let variantGroup = PBXVariantGroup(children: [], sourceTree: .group, name: localizedName) pbxproj.add(object: variantGroup) toGroup.children.append(variantGroup) elements[variantGroupPath] = variantGroup return variantGroup } private func addLocalizedFileElement(localizedFile: AbsolutePath, variantGroup: PBXVariantGroup, localizedContainer: AbsolutePath, pbxproj: PBXProj) { let localizedFilePath = localizedFile.relative(to: localizedContainer.parentDirectory) let lastKnownFileType = localizedFile.extension.flatMap { Xcode.filetype(extension: $0) } let language = localizedContainer.basenameWithoutExt let localizedFileReference = PBXFileReference(sourceTree: .group, name: language, lastKnownFileType: lastKnownFileType, path: localizedFilePath.pathString) pbxproj.add(object: localizedFileReference) variantGroup.children.append(localizedFileReference) knownRegions.insert(language) } func addVersionGroupElement(from: AbsolutePath, folderAbsolutePath: AbsolutePath, folderRelativePath: RelativePath, name: String?, toGroup: PBXGroup, pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) { let group = XCVersionGroup( currentVersion: nil, path: folderRelativePath.pathString, name: name, sourceTree: .group, versionGroupType: versionGroupType(for: folderRelativePath) ) pbxproj.add(object: group) toGroup.children.append(group) elements[folderAbsolutePath] = group return (element: group, path: from.appending(folderRelativePath)) } func addGroupElement(from: AbsolutePath, folderAbsolutePath: AbsolutePath, folderRelativePath: RelativePath, name: String?, toGroup: PBXGroup, pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) { let group = PBXGroup(children: [], sourceTree: .group, name: name, path: folderRelativePath.pathString) pbxproj.add(object: group) toGroup.children.append(group) elements[folderAbsolutePath] = group return (element: group, path: from.appending(folderRelativePath)) } func addFileElement(from _: AbsolutePath, fileAbsolutePath: AbsolutePath, fileRelativePath: RelativePath, name: String?, toGroup: PBXGroup, pbxproj: PBXProj) { let lastKnownFileType = fileAbsolutePath.extension.flatMap { Xcode.filetype(extension: $0) } let file = PBXFileReference(sourceTree: .group, name: name, lastKnownFileType: lastKnownFileType, path: fileRelativePath.pathString) pbxproj.add(object: file) toGroup.children.append(file) elements[fileAbsolutePath] = file } func addPlayground(from _: AbsolutePath, fileAbsolutePath: AbsolutePath, fileRelativePath: RelativePath, name: String?, toGroup: PBXGroup, pbxproj: PBXProj) { let lastKnownFileType = fileAbsolutePath.extension.flatMap { Xcode.filetype(extension: $0) } let file = PBXFileReference(sourceTree: .group, name: name, lastKnownFileType: lastKnownFileType, path: fileRelativePath.pathString, xcLanguageSpecificationIdentifier: "xcode.lang.swift") pbxproj.add(object: file) toGroup.children.append(file) elements[fileAbsolutePath] = file } private func generateSDKFileElement(sdkNodePath: AbsolutePath, toGroup: PBXGroup, pbxproj: PBXProj) { guard sdks[sdkNodePath] == nil else { return } addSDKElement(sdkNodePath: sdkNodePath, toGroup: toGroup, pbxproj: pbxproj) } private func addSDKElement(sdkNodePath: AbsolutePath, toGroup: PBXGroup, pbxproj: PBXProj) { let sdkPath = sdkNodePath.relative(to: AbsolutePath("/")) // SDK paths are relative let lastKnownFileType = sdkPath.extension.flatMap { Xcode.filetype(extension: $0) } let file = PBXFileReference(sourceTree: .developerDir, name: sdkPath.basename, lastKnownFileType: lastKnownFileType, path: sdkPath.pathString) pbxproj.add(object: file) toGroup.children.append(file) sdks[sdkNodePath] = file } func group(path: AbsolutePath) -> PBXGroup? { elements[path] as? PBXGroup } func product(target name: String) -> PBXFileReference? { products[name] } func sdk(path: AbsolutePath) -> PBXFileReference? { sdks[path] } func file(path: AbsolutePath) -> PBXFileReference? { elements[path] as? PBXFileReference } func isLocalized(path: AbsolutePath) -> Bool { path.extension == "lproj" } func isPlayground(path: AbsolutePath) -> Bool { path.extension == "playground" } func isVersionGroup(path: AbsolutePath) -> Bool { path.extension == "xcdatamodeld" } func isXcassets(path: AbsolutePath) -> Bool { path.extension == "xcassets" } func isScnassets(path: AbsolutePath) -> Bool { path.extension == "scnassets" } /// Normalizes a path. Some paths have no direct representation in Xcode, /// like localizable files. This method normalizes those and returns a project /// representable path. /// /// - Example: /// /test/es.lproj/Main.storyboard ~> /test/es.lproj func normalize(_ path: AbsolutePath) -> AbsolutePath { let pathString = path.pathString let range = NSRange(location: 0, length: pathString.count) if let localizedMatch = ProjectFileElements.localizedRegex.firstMatch(in: pathString, options: [], range: range) { let lprojPath = (pathString as NSString).substring(with: localizedMatch.range(at: 1)) return AbsolutePath(lprojPath) } else { return path } } /// Returns the relative path of the closest relative element to the source root path. /// If source root path is /a/b/c/project/ and file path is /a/d/myfile.swift /// this method will return ../../../d/ func closestRelativeElementPath(path: AbsolutePath, sourceRootPath: AbsolutePath) -> RelativePath { let relativePathComponents = path.relative(to: sourceRootPath).components let firstElementComponents = relativePathComponents.reduce(into: [String]()) { components, component in let isLastRelative = components.last == ".." || components.last == "." if components.last != nil, !isLastRelative { return } components.append(component) } if firstElementComponents.isEmpty, !relativePathComponents.isEmpty { return RelativePath(relativePathComponents.first!) } else { return RelativePath(firstElementComponents.joined(separator: "/")) } } private func versionGroupType(for filePath: RelativePath) -> String? { switch filePath.extension { case "xcdatamodeld": return "wrapper.xcdatamodel" case let fileExtension?: return Xcode.filetype(extension: fileExtension) default: return nil } } }
40.499115
140
0.548641
f77ac6fe1dd809be5dc26c17e3386f07bd3881f0
1,679
// // Copyright (c) 2017 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation /// Instances of conforming types provide additional logic for a payment method, such as an interface to enter payment details. internal protocol Plugin { /// The configuration of the plugin. var configuration: PluginConfiguration { get } /// Initializes the plugin. /// /// - Parameter configuration: The configuration of the plugin. init(configuration: PluginConfiguration) } internal protocol PluginRequiresFinalState: Plugin { /// Provides an opportunity for a plugin to execute asynchronous logic based on the result of a completed payment. /// /// - Parameters: /// - paymentStatus: The status of the completed payment. /// - completion: The completion handler to invoke when the plugin is done executing. func finish(with paymentStatus: PaymentStatus, completion: @escaping () -> Void) } internal protocol DeviceDependablePlugin: Plugin { /// Boolean value indicating whether the current device is supported. var isDeviceSupported: Bool { get } } internal protocol CardScanPlugin: Plugin { /// Handler for card scan button. var cardScanButtonHandler: ((@escaping CardScanCompletion) -> Void)? { get set } } /// Structure containing the configuration of a plugin. internal struct PluginConfiguration { /// The payment method for which the plugin is used. internal let paymentMethod: PaymentMethod /// The payment setup. internal let paymentSetup: PaymentSetup }
29.45614
127
0.702204
e98300dda24b0d075f3695f201df49fd1df6fb1d
8,111
// // EquationTests.swift // Stevia // // Created by Sacha Durand Saint Omer on 27/01/2017. // Copyright © 2017 Sacha Durand Saint Omer. All rights reserved. // import XCTest import Stevia class EquationTests: XCTestCase { var win: UIWindow! var ctrler: UIViewController! override func setUp() { super.setUp() win = UIWindow(frame: UIScreen.main.bounds) ctrler = UIViewController() win.rootViewController = ctrler } override func tearDown() { super.tearDown() } func testTop() { let v = UIView() ctrler.view.sv(v) v.Top == ctrler.view.Top + 10 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, 10) } func testTopReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Top + 10 == v.Top ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, 10) } func testBottom() { let v = UIView() ctrler.view.sv(v) v.Bottom == ctrler.view.Bottom - 23 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, ctrler.view.frame.height - 23) } func testBottomReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Bottom - 23 == v.Bottom ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, ctrler.view.frame.height - 23) } func testLeft() { let v = UIView() ctrler.view.sv(v) v.Left == ctrler.view.Left + 72 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, 72) } func testLeftReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Left + 72 == v.Left ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, 72) } func testRight() { let v = UIView() ctrler.view.sv(v) v.Right == ctrler.view.Right - 13 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - 13) } func testRightReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Right - 13 == v.Right ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - 13) } func testWidth() { let v = UIView() ctrler.view.sv(v) v.Width == ctrler.view.Width - 52 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.width, ctrler.view.frame.width - 52) } func testWidthReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Width - 52 == v.Width ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.width, ctrler.view.frame.width - 52) } func testHeight() { let v = UIView() ctrler.view.sv(v) v.Height == ctrler.view.Height + 34 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.height, ctrler.view.frame.height + 34) } func testHeightReflexive() { let v = UIView() ctrler.view.sv(v) ctrler.view.Height + 34 == v.Height ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.height, ctrler.view.frame.height + 34) } // Single Value func testSingleValueTop() { let v = UIView() ctrler.view.sv(v) v.Top == 10 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, 10) } func testSingleValueBottom() { let v = UIView() ctrler.view.sv(v) v.Bottom == 23 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.y, ctrler.view.frame.height - 23) } func testSingleValueLeft() { let v = UIView() ctrler.view.sv(v) v.Left == 72 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, 72) } func testSingleValueRight() { let v = UIView() ctrler.view.sv(v) v.Right == 13 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - 13) } func testSingleValueWidth() { let v = UIView() ctrler.view.sv(v) v.Width == 23 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.width, 23) } func testSingleValueHeight() { let v = UIView() ctrler.view.sv(v) v.Height == 94 ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(v.frame.height, 94) } func testScrollView() { let scrollView = UIScrollView() let contentView = UIView() ctrler.view.sv( scrollView.sv( contentView ) ) scrollView.fillContainer() contentView.Width == ctrler.view.Width ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(contentView.frame.width, ctrler.view.frame.width) } func testScrollViewReflexive() { let scrollView = UIScrollView() let contentView = UIView() ctrler.view.sv( scrollView.sv( contentView ) ) scrollView.fillContainer() ctrler.view.Width == contentView.Width ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in XCTAssertEqual(contentView.frame.width, ctrler.view.frame.width) } func testDifferentViewHierarchies() { // Classic example of a field with a dropdown. let box = UIView() let field = UIView() let dropdown = UIView() ctrler.view.sv( box.sv( field ), dropdown ) box.fillContainer(60) |-field-|.top(1).height(50)//centerVertically() |dropdown| dropdown.Bottom == ctrler.view.Bottom dropdown.Top == field.Bottom // This line is being tested test out reflexivity ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in let absoluteFieldBottom = field.frame.origin.y + field.frame.height + box.frame.origin.y XCTAssertEqual(absoluteFieldBottom, dropdown.frame.origin.y) } func testDifferentViewHierarchiesReflexivity() { // Classic example of a field with a dropdown. let box = UIView() let field = UIView() let dropdown = UIView() ctrler.view.sv( box.sv( field ), dropdown ) box.fillContainer(60) |-field-|.top(1).height(50)//centerVertically() |dropdown| dropdown.Bottom == ctrler.view.Bottom field.Bottom == dropdown.Top // This line is being tested test out reflexivity ctrler.view.layoutIfNeeded() // This is needed to force auto-layout to kick-in let absoluteFieldBottom = field.frame.origin.y + field.frame.height + box.frame.origin.y XCTAssertEqual(absoluteFieldBottom, dropdown.frame.origin.y) } }
31.560311
96
0.587104
d6fdef68373c95bff4a38866af33e297e3dfb0d1
303
// // Item.swift // FastMagnum // // Created by Beisenbek Yerbolat on 11/14/17. // Copyright © 2017 Beisenbek Yerbolat. All rights reserved. // import UIKit class Item: NSObject { var id: Int? var title: String? var descr: String? var price: String? var image: String? }
15.15
61
0.633663
48ca6a0938df77c1eb15326a2819af2d346ac581
462
// // AVCaptureDevice.FlashMode+descriptor.swift // mrousavy // // Created by Marc Rousavy on 15.12.20. // Copyright © 2020 mrousavy. All rights reserved. // import AVFoundation extension AVCaptureDevice.FlashMode { init?(withString string: String) { switch string { case "on": self = .on return case "off": self = .off return case "auto": self = .auto return default: return nil } } }
16.5
51
0.601732
3af8561fc29fb6bf8f1b17953cf37bb4efb723c4
2,819
import Foundation import XcodeKit import SwiftyKit import MockGenerator import AppKit open class BaseCommand: NSObject, XCSourceEditorCommand { open var templateName: String { fatalError("override me") } public func perform( with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> () ) { perform(with: invocation as SourceEditorCommandInvocation, completionHandler: completionHandler) } func perform( with invocation: SourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> () ) { invocation.cancellationHandler = { completionHandler(nil) } do { let projectURL = try getProjectURLOnMainThread() _ = projectURL.startAccessingSecurityScopedResource() setUpSwifty( projectURL: projectURL, useTabs: invocation.sourceTextBuffer.usesTabsForIndentation, indentationWidth: invocation.sourceTextBuffer.indentationWidth ) defer { projectURL.stopAccessingSecurityScopedResource() } let instructions = try InsertMockCommand(templateName: templateName) .execute(buffer: TextBufferImpl(invocation.sourceTextBuffer)) let selections = NSMutableArray() try instructions.forEach { instruction in try instruction.execute(lines: invocation.sourceTextBuffer.lines, selections: selections) } transformSelections(in: invocation.sourceTextBuffer.selections, selections) completionHandler(nil) } catch { completionHandler(error) } } private func transformSelections(in selections: NSMutableArray, _ toTransform: NSMutableArray) { selections.removeAllObjects() toTransform .compactMap { $0 as? SelectionRange } .map { $0.toXCSourceTextRange() } .forEach { selections.add($0) } } private func getProjectURLOnMainThread() throws -> URL { if Thread.isMainThread { return try getProjectURL() } return try DispatchQueue.main.sync { return try getProjectURL() } } private func getProjectURL() throws -> URL { let url = try ProjectFinder(projectFinder: XcodeProjectPathFinder(), preferences: Preferences()) .getProjectPath() return try BookmarkedURL.bookmarkedURL(url: url) } } extension SelectionRange { func toXCSourceTextRange() -> XCSourceTextRange { return XCSourceTextRange( start: XCSourceTextPosition(line: start.line, column: start.column), end: XCSourceTextPosition(line: end.line, column: end.column) ) } }
30.641304
105
0.6442
bb2173314d2ee468634959f127d2878ca60f2117
22,633
import Foundation public extension Zipper { private enum ModifyOperation: Int { case remove = -1 case add = 1 } /// Write files, directories or symlinks to the receiver. /// /// - Parameters: /// - path: The path that is used to identify an `Zipper.Entry` within the `Zipper` file. /// - baseURL: The base URL of the `Zipper.Entry` to add. /// The `baseURL` combined with `path` must form a fully qualified file URL. /// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Zipper.Entry`. /// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed). /// - Throws: An error if the source file cannot be read or the receiver is not writable. public func addEntry(with path: String, relativeTo baseURL: URL, compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize) throws { let fileManager = FileManager() let entryURL = baseURL.appendingPathComponent(path) guard fileManager.isReadableFile(atPath: entryURL.path) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoPermission.rawValue, userInfo: [NSFilePathErrorKey: url.path]) } let type = try FileManager.typeForItem(at: entryURL) let modDate = try FileManager.fileModificationDateTimeForItem(at: entryURL) let uncompressedSize = type == .directory ? 0 : try FileManager.fileSizeForItem(at: entryURL) let permissions = try FileManager.permissionsForItem(at: entryURL) var provider: ZipperProviderClosure switch type { case .file: let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: entryURL.path) let entryFile: UnsafeMutablePointer<FILE> = fopen(entryFileSystemRepresentation, "rb") defer { fclose(entryFile) } provider = { _, _ in return try Data.readChunk(from: entryFile, size: Int(bufferSize)) } try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, provider: provider) case .directory: provider = { _, _ in return Data() } try self.addEntry(with: path.hasSuffix("/") ? path : path + "/", type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, provider: provider) case .symlink: provider = { _, _ -> Data in let fileManager = FileManager() let path = entryURL.path let linkDestination = try fileManager.destinationOfSymbolicLink(atPath: path) let linkFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: linkDestination) let linkLength = Int(strlen(linkFileSystemRepresentation)) let linkBuffer = UnsafeBufferPointer(start: linkFileSystemRepresentation, count: linkLength) let linkData = Data.init(buffer: linkBuffer) return linkData } try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, provider: provider) } } /// Write files, directories or symlinks to the receiver. /// /// - Parameters: /// - path: The path that is used to identify an `Zipper.Entry` within the `Zipper` file. /// - type: Indicates the `Zipper.Entry.EntryType` of the added content. /// - uncompressedSize: The uncompressed size of the data that is going to be added with `provider`. /// - modificationDate: A `Date` describing the file modification date of the `Zipper.Entry`. /// Default is the current `Date`. /// - permissions: POSIX file permissions for the `Zipper.Entry`. /// Default is `0`o`755`. /// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Zipper.Entry`. /// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed). /// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk. /// - Throws: An error if the source data is invalid or the receiver is not writable. public func addEntry(with path: String, type: Zipper.Entry.EntryType, uncompressedSize: UInt32, modificationDate: Date = Date(), permissions: UInt16 = defaultPermissions, compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize, provider: ZipperProviderClosure) throws { guard self.accessMode != .read else { throw ArchiveError.unwritableArchive } var endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord var startOfCentralDirectory = Int(endOfCentralDirectoryRecord.offsetToStartOfCentralDirectory) var existingCentralDirectoryData = Data() fseek(self.archiveFile, startOfCentralDirectory, SEEK_SET) existingCentralDirectoryData = try Data.readChunk(from: self.archiveFile, size: Int(endOfCentralDirectoryRecord.sizeOfCentralDirectory)) fseek(self.archiveFile, startOfCentralDirectory, SEEK_SET) let localFileHeaderStart = ftell(self.archiveFile) let modDateTime = modificationDate.fileModificationDateTime var localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod, size: (uncompressedSize, 0), checksum: 0, modificationDateTime: modDateTime) let (sizeWritten, checksum) = try self.writeEntry(localFileHeader: localFileHeader, type: type, compressionMethod: compressionMethod, bufferSize: bufferSize, provider: provider) startOfCentralDirectory = ftell(self.archiveFile) fseek(self.archiveFile, localFileHeaderStart, SEEK_SET) // Write the local file header a second time. Now with compressedSize (if applicable) and a valid checksum. localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod, size: (uncompressedSize, sizeWritten), checksum: checksum, modificationDateTime: modDateTime) fseek(self.archiveFile, startOfCentralDirectory, SEEK_SET) _ = try Data.write(chunk: existingCentralDirectoryData, to: self.archiveFile) let externalFileAttributes = FileManager.externalFileAttributesForEntry(of: type, permissions: permissions) let offset = UInt32(localFileHeaderStart) let centralDirectory = try self.writeCentralDirectoryStructure(localFileHeader: localFileHeader, relativeOffset: offset, externalFileAttributes: externalFileAttributes) // FIXME: integer overflows when converted from UInt32 to Int: Int(UInt32.max) if UInt32(startOfCentralDirectory) > UInt32.max { throw ArchiveError.invalidStartOfCentralDirectoryOffset } let start = UInt32(startOfCentralDirectory) endOfCentralDirectoryRecord = try self.writeEndOfCentralDirectory(centralDirectoryStructure: centralDirectory, startOfCentralDirectory: start, operation: .add) fflush(self.archiveFile) self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord } /// Remove a ZIP `Zipper.Entry` from the receiver. /// /// - Parameters: /// - entry: The `Zipper.Entry` to remove. /// - bufferSize: The maximum size for the read and write buffers used during removal. /// - Throws: An error if the `Zipper.Entry` is malformed or the receiver is not writable. public func remove(_ entry: Zipper.Entry, bufferSize: UInt32 = defaultReadChunkSize) throws { let uniqueString = ProcessInfo.processInfo.globallyUniqueString let tempArchiveURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(uniqueString) guard let tempArchive = Zipper(url: tempArchiveURL, accessMode: .create) else { throw ArchiveError.unwritableArchive } var centralDirectoryData = Data() var offset = 0 for currentEntry in self { let localFileHeader = currentEntry.localFileHeader let centralDirectoryStructure = currentEntry.centralDirectoryStructure let dataDescriptor = currentEntry.dataDescriptor var extraDataLength = Int(localFileHeader.fileNameLength) extraDataLength += Int(localFileHeader.extraFieldLength) var entrySize = LocalFileHeader.size + extraDataLength let isCompressed = centralDirectoryStructure.compressionMethod != CompressionMethod.none.rawValue if let dataDescriptor = dataDescriptor { entrySize += Int(isCompressed ? dataDescriptor.compressedSize : dataDescriptor.uncompressedSize) entrySize += DataDescriptor.size } else { entrySize += Int(isCompressed ? localFileHeader.compressedSize : localFileHeader.uncompressedSize) } if currentEntry != entry { let entryStart = Int(currentEntry.centralDirectoryStructure.relativeOffsetOfLocalHeader) fseek(self.archiveFile, entryStart, SEEK_SET) let consumer = { _ = try Data.write(chunk: $0, to: tempArchive.archiveFile) } _ = try Data.consumePart(of: self.archiveFile, size: Int(entrySize), chunkSize: Int(bufferSize), skipCRC32: true, consumer: consumer) let centralDir = CentralDirectoryStructure(centralDirectoryStructure: centralDirectoryStructure, offset: UInt32(offset)) centralDirectoryData.append(centralDir.data) } else { offset = entrySize } } let startOfCentralDirectory = ftell(tempArchive.archiveFile) _ = try Data.write(chunk: centralDirectoryData, to: tempArchive.archiveFile) tempArchive.endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord let endOfCentralDirectoryRecord = try tempArchive.writeEndOfCentralDirectory(centralDirectoryStructure: entry.centralDirectoryStructure, startOfCentralDirectory: UInt32(startOfCentralDirectory), operation: .remove) tempArchive.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord fflush(tempArchive.archiveFile) try self.replaceCurrentArchiveWithArchive(at: tempArchive.url) } // MARK: - Helpers private func writeLocalFileHeader(path: String, compressionMethod: CompressionMethod, size: (uncompressed: UInt32, compressed: UInt32), checksum: ZipperCRC32, modificationDateTime: (UInt16, UInt16)) throws -> LocalFileHeader { let fileManager = FileManager() let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: path) let fileNameLength = Int(strlen(fileSystemRepresentation)) let fileNameBuffer = UnsafeBufferPointer(start: fileSystemRepresentation, count: fileNameLength) let fileNameData = Data.init(buffer: fileNameBuffer) let localFileHeader = LocalFileHeader(versionNeededToExtract: UInt16(20), generalPurposeBitFlag: UInt16(2048), compressionMethod: compressionMethod.rawValue, lastModFileTime: modificationDateTime.1, lastModFileDate: modificationDateTime.0, crc32: checksum, compressedSize: size.compressed, uncompressedSize: size.uncompressed, fileNameLength: UInt16(fileNameLength), extraFieldLength: UInt16(0), fileNameData: fileNameData, extraFieldData: Data()) _ = try Data.write(chunk: localFileHeader.data, to: self.archiveFile) return localFileHeader } private func writeEntry(localFileHeader: LocalFileHeader, type: Zipper.Entry.EntryType, compressionMethod: CompressionMethod, bufferSize: UInt32, provider: ZipperProviderClosure) throws -> (sizeWritten: UInt32, crc32: ZipperCRC32) { var checksum = ZipperCRC32(0) var sizeWritten = UInt32(0) switch type { case .file: switch compressionMethod { case .none: (sizeWritten, checksum) = try self.writeUncompressed(size: localFileHeader.uncompressedSize, bufferSize: bufferSize, provider: provider) case .deflate: (sizeWritten, checksum) = try self.writeCompressed(size: localFileHeader.uncompressedSize, bufferSize: bufferSize, provider: provider) } case .directory: _ = try provider(0, 0) case .symlink: (sizeWritten, checksum) = try self.writeSymbolicLink(size: localFileHeader.uncompressedSize, provider: provider) } return (sizeWritten, checksum) } private func writeUncompressed(size: UInt32, bufferSize: UInt32, provider: ZipperProviderClosure) throws -> (sizeWritten: UInt32, checksum: ZipperCRC32) { var position = 0 var sizeWritten = 0 var checksum = ZipperCRC32(0) while position < Int(size) { let readSize = (Int(size) - position) >= Int(bufferSize) ? Int(bufferSize) : (Int(size) - position) let entryChunk = try provider(Int(position), Int(readSize)) checksum = entryChunk.crc32(checksum: checksum) sizeWritten += try Data.write(chunk: entryChunk, to: self.archiveFile) position += Int(bufferSize) } return (UInt32(sizeWritten), checksum) } private func writeCompressed(size: UInt32, bufferSize: UInt32, provider: ZipperProviderClosure) throws -> (sizeWritten: UInt32, checksum: ZipperCRC32) { var sizeWritten = 0 let checksum = try Data.compress(size: Int(size), bufferSize: Int(bufferSize), provider: provider) { data in sizeWritten += try Data.write(chunk: data, to: self.archiveFile) } return(UInt32(sizeWritten), checksum) } private func writeSymbolicLink(size: UInt32, provider: ZipperProviderClosure) throws -> (sizeWritten: UInt32, checksum: ZipperCRC32) { let linkData = try provider(0, Int(size)) let checksum = linkData.crc32(checksum: 0) let sizeWritten = try Data.write(chunk: linkData, to: self.archiveFile) return (UInt32(sizeWritten), checksum) } private func writeCentralDirectoryStructure(localFileHeader: LocalFileHeader, relativeOffset: UInt32, externalFileAttributes: UInt32) throws -> CentralDirectoryStructure { let centralDirectory = CentralDirectoryStructure(localFileHeader: localFileHeader, fileAttributes: externalFileAttributes, relativeOffset: relativeOffset) _ = try Data.write(chunk: centralDirectory.data, to: self.archiveFile) return centralDirectory } private func writeEndOfCentralDirectory(centralDirectoryStructure: CentralDirectoryStructure, startOfCentralDirectory: UInt32, operation: ModifyOperation) throws -> EndOfCentralDirectoryRecord { var record = self.endOfCentralDirectoryRecord let countChange = operation.rawValue var dataLength = centralDirectoryStructure.extraFieldLength dataLength += centralDirectoryStructure.fileNameLength dataLength += centralDirectoryStructure.fileCommentLength let centralDirectoryDataLengthChange = operation.rawValue * (Int(dataLength) + CentralDirectoryStructure.size) var updatedSizeOfCentralDirectory = Int(record.sizeOfCentralDirectory) updatedSizeOfCentralDirectory += centralDirectoryDataLengthChange let numberOfEntriesOnDisk = UInt16(Int(record.totalNumberOfEntriesOnDisk) + countChange) let numberOfEntriesInCentralDirectory = UInt16(Int(record.totalNumberOfEntriesInCentralDirectory) + countChange) record = EndOfCentralDirectoryRecord(record: record, numberOfEntriesOnDisk: numberOfEntriesOnDisk, numberOfEntriesInCentralDirectory: numberOfEntriesInCentralDirectory, updatedSizeOfCentralDirectory: UInt32(updatedSizeOfCentralDirectory), startOfCentralDirectory: startOfCentralDirectory) _ = try Data.write(chunk: record.data, to: self.archiveFile) return record } private func replaceCurrentArchiveWithArchive(at URL: URL) throws { fclose(self.archiveFile) let fileManager = FileManager() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) _ = try fileManager.replaceItemAt(self.url, withItemAt: URL) #else _ = try fileManager.removeItem(at: self.url) _ = try fileManager.moveItem(at: URL, to: self.url) #endif let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: self.url.path) self.archiveFile = fopen(fileSystemRepresentation, "rb+") } } extension Zipper { /// Zips the file or direcory contents at the specified source URL to the destination URL. /// /// If the item at the source URL is a directory, the directory itself will be /// represented within the ZIP `Zipper`. Calling this method with a directory URL /// `file:///path/directory/` will create an archive with a `directory/` entry at the root level. /// You can override this behavior by passing `false` for `shouldKeepParent`. In that case, the contents /// of the source directory will be placed at the root of the archive. /// - Parameters: /// - sourceURL: The file URL pointing to an existing file or directory. /// - shouldKeepParent: Indicates that the directory name of a source item should be used as root element /// within the archive. Default is `true`. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. public func archive(item sourceURL: URL, shouldKeepParent: Bool = true) throws { guard FileManager.default.fileExists(atPath: sourceURL.path) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: sourceURL.path]) } let isDirectory = try FileManager.typeForItem(at: sourceURL) == .directory if isDirectory { // Use the path based enumerator because it returns String objects containing // relative paths instead of absolute URLs let dirEnumerator = FileManager.default.enumerator(atPath: sourceURL.path) // If the caller wants to keep the parent directory, we use the lastPathComponent of the source URL // as common base for all entries (similar to macOS' Archive Utility.app) let directoryPrefix = sourceURL.lastPathComponent while let entryPath = dirEnumerator?.nextObject() as? String { let finalEntryPath = shouldKeepParent ? directoryPrefix + "/" + entryPath : entryPath try self.addEntry(with: finalEntryPath, relativeTo: sourceURL.deletingLastPathComponent()) } } else { let baseURL = sourceURL.deletingLastPathComponent() try self.addEntry(with: sourceURL.lastPathComponent, relativeTo: baseURL) } } /// Zips the file or direcory contents at the specified source URL to the destination URL. /// /// If the item at the source URL is a directory, the directory itself will be /// represented within the ZIP `Zipper`. Calling this method with a directory URL /// `file:///path/directory/` will create an archive with a `directory/` entry at the root level. /// You can override this behavior by passing `false` for `shouldKeepParent`. In that case, the contents /// of the source directory will be placed at the root of the archive. /// - Parameters: /// - sourceURL: The file URL pointing to an existing file or directory. /// - shouldKeepParent: Indicates that the directory name of a source item should be used as root element /// within the archive. Default is `true`. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. public func zip(item sourceURL: URL, shouldKeepParent: Bool = true) throws { try archive(item: sourceURL, shouldKeepParent: shouldKeepParent) } }
65.037356
138
0.636858
f5fd699c77dedb0e1c88b6e9b13bb4327545f588
7,650
// // EmptyObjectDecoder.swift // JSONAPI // // Created by Mathew Polzin on 7/2/19. // /// `EmptyObjectDecoder` exists internally for the sole purpose of /// allowing certain fallback logic paths to attempt to create `Decodable` /// types from empty containers (specifically in a way that is agnostic /// of any given encoding). In other words, this serves the same purpose /// as `JSONDecoder().decode(Thing.self, from: "{}".data(using: .utf8)!)` /// without needing to use a third party or `Foundation` library decoder. struct EmptyObjectDecoder: Decoder { var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] = [:] func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { return KeyedDecodingContainer(EmptyKeyedContainer()) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { return EmptyUnkeyedContainer() } func singleValueContainer() throws -> SingleValueDecodingContainer { throw EmptyObjectDecodingError.emptyObjectCannotBeSingleValue } } enum EmptyObjectDecodingError: Swift.Error { case emptyObjectCannotBeSingleValue case emptyObjectCannotBeUnkeyedValues case emptyObjectCannotHaveKeyedValues case emptyObjectCannotHaveNestedContainers case emptyObjectCannotHaveSuper } struct EmptyUnkeyedContainer: UnkeyedDecodingContainer { var codingPath: [CodingKey] { return [] } var count: Int? { return 0 } var isAtEnd: Bool { return true } var currentIndex: Int { return 0 } mutating func decodeNil() throws -> Bool { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Bool.Type) throws -> Bool { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: String.Type) throws -> String { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Double.Type) throws -> Double { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Float.Type) throws -> Float { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Int.Type) throws -> Int { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Int8.Type) throws -> Int8 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Int16.Type) throws -> Int16 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Int32.Type) throws -> Int32 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: Int64.Type) throws -> Int64 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: UInt.Type) throws -> UInt { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: UInt8.Type) throws -> UInt8 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: UInt16.Type) throws -> UInt16 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: UInt32.Type) throws -> UInt32 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode(_ type: UInt64.Type) throws -> UInt64 { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable { throw EmptyObjectDecodingError.emptyObjectCannotBeUnkeyedValues } mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { throw EmptyObjectDecodingError.emptyObjectCannotHaveNestedContainers } mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { throw EmptyObjectDecodingError.emptyObjectCannotHaveNestedContainers } mutating func superDecoder() throws -> Decoder { throw EmptyObjectDecodingError.emptyObjectCannotHaveSuper } } struct EmptyKeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol { var codingPath: [CodingKey] { return [] } var allKeys: [Key] { return [] } func contains(_ key: Key) -> Bool { return false } func decodeNil(forKey key: Key) throws -> Bool { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: String.Type, forKey key: Key) throws -> String { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { throw EmptyObjectDecodingError.emptyObjectCannotHaveKeyedValues } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { throw EmptyObjectDecodingError.emptyObjectCannotHaveNestedContainers } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { throw EmptyObjectDecodingError.emptyObjectCannotHaveNestedContainers } func superDecoder() throws -> Decoder { throw EmptyObjectDecodingError.emptyObjectCannotHaveSuper } func superDecoder(forKey key: Key) throws -> Decoder { throw EmptyObjectDecodingError.emptyObjectCannotHaveSuper } }
35.416667
156
0.73098
1823dfddcc43f5ddb4ef72c617cee5bd1a644e84
2,189
// Copyright (c) 2021 Grigor Hakobyan <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public enum OAuthError: String, Error { /// The request is missing a required parameter, /// includes an invalid parameter value, or is otherwise malformed. case invalidRequest = "invalid_request" /// The client is not authorized to request an authorization /// code using this method. case unauthorizedClient = "unauthorized_client" /// The authorization server does not support obtaining an /// authorization code using this method. case unsupportedResponseType = "unsupported_response_type" /// The requested scope is invalid, unknown, or malformed. case invalidScope = "invalid_scope" /// The authorization server encountered an unexpected /// condition which prevented it from fulfilling the request. case serverError = "server_error" /// The authorization server is currently unable to handle /// the request due to a temporary overloading or maintenance of the server. case temporarilyUnavailable = "temporarily_unavailable" }
54.725
83
0.738693
0917d1428c70f6563161a10e8d86b8149399d774
1,244
// // RxKingfisherUITests.swift // RxKingfisherUITests // // Created by 郑军铎 on 2018/9/5. // Copyright © 2018年 ZJaDe. All rights reserved. // import XCTest class RxKingfisherUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.621622
182
0.663987
eb4403cb6c0c12cd5e5687a309f29afb95b3d195
832
///// //// AuxCameraPlayerView.swift /// Copyright © 2020 Dmitriy Borovikov. All rights reserved. // import UIKit class AuxCameraPlayerView: FloatingView { override func loadDefaults() -> CGPoint { assert(superview != nil) let cph = (superview!.frame.midX - bounds.midX) / superview!.frame.width let cpv = (superview!.frame.maxY - bounds.midY) / superview!.frame.height return CGPoint(x: cph, y: cpv) } override func savePosition(cp: CGPoint) { Preference.auxCameraPlayerViewCPH = cp.x Preference.auxCameraPlayerViewCPV = cp.y } override func loadPosition() -> CGPoint? { guard let cph = Preference.auxCameraPlayerViewCPH, let cpv = Preference.auxCameraPlayerViewCPV else { return nil } return CGPoint(x: cph, y: cpv) } }
29.714286
81
0.652644
ab25c800bc8249e5040b5a258c9853d674a6634b
9,196
// // PanelManager+Expose.swift // PanelKit // // Created by Louis D'hauwe on 24/02/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation import UIKit private var exposeOverlayViewKey: UInt8 = 0 private var exposeOverlayTapRecognizerKey: UInt8 = 0 private var exposeEnterTapRecognizerKey: UInt8 = 0 extension PanelManager { var exposeOverlayView: UIVisualEffectView { get { return associatedObject(self, key: &exposeOverlayViewKey) { return UIVisualEffectView(effect: nil) } } set { associateObject(self, key: &exposeOverlayViewKey, value: newValue) } } var exposeOverlayTapRecognizer: BlockGestureRecognizer { get { return associatedObject(self, key: &exposeOverlayTapRecognizerKey) { let gestureRecognizer = UITapGestureRecognizer() let blockRecognizer = BlockGestureRecognizer(view: exposeOverlayView, recognizer: gestureRecognizer, closure: { [weak self] in if self?.isInExpose == true { self?.exitExpose() } }) return blockRecognizer } } set { associateObject(self, key: &exposeOverlayTapRecognizerKey, value: newValue) } } var exposeEnterTapRecognizer: BlockGestureRecognizer { get { return associatedObject(self, key: &exposeEnterTapRecognizerKey) { let tapGestureRecognizer = UITapGestureRecognizer() tapGestureRecognizer.numberOfTapsRequired = 2 tapGestureRecognizer.numberOfTouchesRequired = 3 let blockRecognizer = BlockGestureRecognizer(view: panelContentWrapperView, recognizer: tapGestureRecognizer) { [weak self] in self?.toggleExpose() } return blockRecognizer } } set { associateObject(self, key: &exposeEnterTapRecognizerKey, value: newValue) } } } public extension PanelManager { func enableTripleTapExposeActivation() { _ = exposeEnterTapRecognizer } func toggleExpose() { if isInExpose { exitExpose() } else { enterExpose() } } var isInExpose: Bool { for panel in panels { if panel.isInExpose { return true } } return false } func enterExpose() { guard !isInExpose else { return } addExposeOverlayViewIfNeeded() let exposePanels = panels.filter { (p) -> Bool in return p.isPinned || p.isFloating } guard !exposePanels.isEmpty else { return } willEnterExpose() let (panelFrames, scale) = calculateExposeFrames(with: exposePanels) for panelFrame in panelFrames { panelFrame.panel.frameBeforeExpose = panelFrame.panel.view.frame updateFrame(for: panelFrame.panel, to: panelFrame.exposeFrame) } panelContentWrapperView.insertSubview(exposeOverlayView, aboveSubview: panelContentView) exposeOverlayView.isUserInteractionEnabled = true UIView.animate(withDuration: exposeEnterDuration, delay: 0.0, options: [], animations: { self.exposeOverlayView.effect = self.exposeOverlayBlurEffect self.panelContentWrapperView.layoutIfNeeded() for panelFrame in panelFrames { panelFrame.panel.view.transform = CGAffineTransform(scaleX: scale, y: scale) } }) for panel in panels { panel.hideResizeHandle() } } func exitExpose() { guard isInExpose else { return } let exposePanels = panels.filter { (p) -> Bool in return p.isInExpose } guard !exposePanels.isEmpty else { return } willExitExpose() for panel in exposePanels { if let frameBeforeExpose = panel.frameBeforeExpose { updateFrame(for: panel, to: frameBeforeExpose) panel.frameBeforeExpose = nil } } exposeOverlayView.isUserInteractionEnabled = false UIView.animate(withDuration: exposeExitDuration, delay: 0.0, options: [], animations: { self.exposeOverlayView.effect = nil self.panelContentWrapperView.layoutIfNeeded() for panel in exposePanels { panel.view.transform = .identity } }) for panel in panels { panel.showResizeHandleIfNeeded() } } } extension PanelManager { func addExposeOverlayViewIfNeeded() { if exposeOverlayView.superview == nil { exposeOverlayView.translatesAutoresizingMaskIntoConstraints = false panelContentWrapperView.addSubview(exposeOverlayView) panelContentWrapperView.insertSubview(exposeOverlayView, aboveSubview: panelContentView) exposeOverlayView.topAnchor.constraint(equalTo: panelContentView.topAnchor).isActive = true exposeOverlayView.bottomAnchor.constraint(equalTo: panelContentView.bottomAnchor).isActive = true exposeOverlayView.leadingAnchor.constraint(equalTo: panelContentWrapperView.leadingAnchor).isActive = true exposeOverlayView.trailingAnchor.constraint(equalTo: panelContentWrapperView.trailingAnchor).isActive = true exposeOverlayView.alpha = 1.0 exposeOverlayView.isUserInteractionEnabled = false panelContentWrapperView.layoutIfNeeded() _ = exposeOverlayTapRecognizer } } func calculateExposeFrames(with panels: [PanelViewController]) -> ([PanelExposeFrame], CGFloat) { let panelFrames: [PanelExposeFrame] = panels.map { (p) -> PanelExposeFrame in return PanelExposeFrame(panel: p) } distribute(panelFrames) guard let unionFrame = unionRect(with: panelFrames) else { return (panelFrames, 1.0) } if panelManagerLogLevel == .full { print("[Exposé] unionFrame: \(unionFrame)") } for r in panelFrames { r.exposeFrame.origin.x -= unionFrame.origin.x r.exposeFrame.origin.y -= unionFrame.origin.y } var normalizedUnionFrame = unionFrame normalizedUnionFrame.origin.x = 0.0 normalizedUnionFrame.origin.y = 0.0 if panelManagerLogLevel == .full { print("[Exposé] normalizedUnionFrame: \(normalizedUnionFrame)") } var exposeContainmentFrame = panelContentView.frame exposeContainmentFrame.size.width = panelContentWrapperView.frame.width exposeContainmentFrame.origin.x = 0 let padding: CGFloat = exposeOuterPadding let scale = min(1.0, min(((exposeContainmentFrame.width - padding) / unionFrame.width), ((exposeContainmentFrame.height - padding) / unionFrame.height))) if panelManagerLogLevel == .full { print("[Exposé] scale: \(scale)") } var scaledNormalizedUnionFrame = normalizedUnionFrame scaledNormalizedUnionFrame.size.width *= scale scaledNormalizedUnionFrame.size.height *= scale if panelManagerLogLevel == .full { print("[Exposé] scaledNormalizedUnionFrame: \(scaledNormalizedUnionFrame)") } for r in panelFrames { r.exposeFrame.origin.x *= scale r.exposeFrame.origin.y *= scale let width = r.exposeFrame.size.width let height = r.exposeFrame.size.height r.exposeFrame.origin.x -= width * (1.0 - scale) / 2 r.exposeFrame.origin.y -= height * (1.0 - scale) / 2 // Center r.exposeFrame.origin.x += (max(exposeContainmentFrame.width - scaledNormalizedUnionFrame.width, 0.0)) / 2.0 r.exposeFrame.origin.y += (max(exposeContainmentFrame.height - scaledNormalizedUnionFrame.height, 0.0)) / 2.0 r.exposeFrame.origin.y += exposeContainmentFrame.origin.y } return (panelFrames, scale) } func doFramesIntersect(_ frames: [PanelExposeFrame]) -> Bool { for r1 in frames { for r2 in frames { if r1 === r2 { continue } if numberOfIntersections(of: r1, with: [r2]) > 0 { return true } } } return false } func numberOfIntersections(of frame: PanelExposeFrame, with frames: [PanelExposeFrame]) -> Int { var intersections = 0 let r1 = frame for r2 in frames { if r1 === r2 { continue } let r1InsetFrame = r1.exposeFrame.insetBy(dx: -exposePanelHorizontalSpacing, dy: -exposePanelVerticalSpacing) if r1InsetFrame.intersects(r2.exposeFrame) { intersections += 1 } } return intersections } func unionRect(with frames: [PanelExposeFrame]) -> CGRect? { guard var rect = frames.first?.exposeFrame else { return nil } for r in frames { rect = rect.union(r.exposeFrame) } return rect } func distribute(_ frames: [PanelExposeFrame]) { var frames = frames var stack = [PanelExposeFrame]() while doFramesIntersect(frames) { let sortedFrames = frames.sorted(by: { (r1, r2) -> Bool in let n1 = numberOfIntersections(of: r1, with: frames) let n2 = numberOfIntersections(of: r2, with: frames) return n1 > n2 }) guard let mostIntersected = sortedFrames.first else { break } stack.append(mostIntersected) guard let index = frames.firstIndex(where: { (r) -> Bool in r === mostIntersected }) else { break } frames.remove(at: index) } while !stack.isEmpty { guard let last = stack.popLast() else { break } frames.append(last) guard let unionRect = self.unionRect(with: frames) else { break } let g = CGPoint(x: unionRect.midX, y: unionRect.midY) let deltaX = max(1.0, last.panel.view.center.x - g.x) let deltaY = max(1.0, last.panel.view.center.y - g.y) while numberOfIntersections(of: last, with: frames) > 0 { last.exposeFrame.origin.x += deltaX / 20.0 last.exposeFrame.origin.y += deltaY / 20.0 } } } } class PanelExposeFrame { let panel: PanelViewController var exposeFrame: CGRect init(panel: PanelViewController) { self.panel = panel self.exposeFrame = panel.view.frame } }
21.485981
155
0.715746
fcc8df83cfa9515a6a9202d5aa01e9094f9e0c57
18,256
// // SSPageViewController.swift // SSPageViewController // // Created by LawLincoln on 16/3/11. // Copyright © 2016年 Luoo. All rights reserved. // import UIKit #if !PACKING_FOR_APPSTORE import HMSegmentedControl_CodeEagle import SnapKit #endif //MARK:- SSPageViewController /// SSPageViewController public final class SSPageViewController < Template: SSPageViewContentProtocol, Delegate: SSPageViewDelegate>: UIViewController, UIScrollViewDelegate where Template == Delegate.Template { public typealias TemplateConfigurationClosure = (_ display: Template, _ backup: Template) -> Void // MARK:- Public public fileprivate(set) lazy var indicator: UIPageControl = UIPageControl() public fileprivate(set) lazy var scrollView = UIScrollView() public fileprivate(set) lazy var segment: HMSegmentedControl_CodeEagle = HMSegmentedControl_CodeEagle() public var itemLength: CGFloat { let size = view.bounds.size return _isHorizontal ? size.width : size.height } public weak var ss_delegate: Delegate? public var initializeTemplateConfiguration: TemplateConfigurationClosure? { didSet { initializeTemplateConfiguration?(_display, _backup) } } public var configurationBlock: TemplateConfigurationClosure? { didSet { configurationBlock?(_display, _backup) customConfigurationDone() } } public var indicatorAlignStyle: NSTextAlignment = .center { didSet { configureIndicator() } } public var loopInterval: TimeInterval = 0 { didSet { addDisplayNextTask() } } public var showsSegment = false { didSet { segment.snp.remakeConstraints { (make) -> Void in make.top.left.right.equalTo(view) make.height.equalTo(showsSegment ? 44 : 0) } } } public var showsIndicator: Bool = false { didSet { indicator.isHidden = !showsIndicator } } public var currentOffset: ((CGFloat) -> ())? // MARK:- Private fileprivate var _display: Template! fileprivate var _backup: Template! fileprivate var _direction: UIPageViewControllerNavigationOrientation! fileprivate var _task: SSCancelableTask? fileprivate var _isHorizontal: Bool { return _direction == .horizontal } fileprivate var _displayView: UIView! { return _display.ss_content } fileprivate var _backupView: UIView! { return _backup.ss_content } fileprivate var _boundsWidth: CGFloat { return view.bounds.width } fileprivate var _boundsHeight: CGFloat { return view.bounds.height } // MARK:- LifeCycle deinit { _display = nil _backup = nil scrollView.delegate = nil } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public convenience init(scrollDirection: UIPageViewControllerNavigationOrientation = .horizontal) { self.init(nibName: nil, bundle: nil) _direction = scrollDirection _display = Template() _backup = Template() automaticallyAdjustsScrollViewInsets = false setup() } fileprivate var _ignoreScroll = false public func scrollTo(_ template: (Template) -> Template, direction: UIPageViewControllerNavigationDirection) { _backup = template(_backup) _ignoreScroll = true let hasNextAfterBackup = _backup.ss_nextId != nil if direction == .forward { _displayView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(scrollView).offset(_displayView.frame.origin.x) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(scrollView).offset(_displayView.frame.origin.y) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) _backupView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(_displayView.snp.right) make.right.equalTo(scrollView).offset(hasNextAfterBackup ? -_boundsWidth : 0) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(_displayView.snp.bottom) make.bottom.equalTo(scrollView).offset(hasNextAfterBackup ? -_boundsHeight : 0) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) } else { let offset = _isHorizontal ? (_displayView.frame.origin.x - _boundsWidth) : (_displayView.frame.origin.y - _boundsHeight) _backupView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(scrollView).offset(offset) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(scrollView).offset(offset) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) _displayView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(_backupView.snp.right) make.right.equalTo(scrollView) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(_backupView.snp.bottom) make.bottom.equalTo(scrollView) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) } var point = scrollView.contentOffset if direction == .forward { if _isHorizontal { point.x += _boundsWidth } else { point.y += _boundsHeight } } else { if _isHorizontal { point.x -= _boundsWidth } else { point.y -= _boundsHeight } } scrollView.setNeedsLayout() scrollView.setContentOffset(point, animated: true) } // MARK:- UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { dealScroll(scrollView) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { dealEnd(scrollView) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { dealEnd(scrollView) } fileprivate func dealScroll(_ scrollView: UIScrollView) { SSCancelableTaskManager.cancel(_task) let offset = scrollView.contentOffset let standarValue = _isHorizontal ? offset.x : offset.y currentOffset?(standarValue) if _ignoreScroll { return } let backupPoint = _isHorizontal ? _backupView.frame.origin.x : _backupView.frame.origin.y let displayPoint = _isHorizontal ? _displayView.frame.origin.x : _displayView.frame.origin.y let displayLen = _isHorizontal ? _displayView.frame.size.width : _displayView.frame.size.height if displayPoint - standarValue > 0 { let targetBackupPoint = displayPoint - displayLen if let preId = _display.ss_previousId { if _backup.ss_identifer != preId || _backup.ss_identifer == "" { ss_delegate?.pageView(self, configureForView: _backup, beforeView: _display) } if backupPoint != targetBackupPoint { _backupView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(scrollView) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(scrollView) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) _displayView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.right.equalTo(scrollView).offset(-_boundsWidth) make.left.equalTo(_backupView.snp.right) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(_backupView.snp.bottom) make.left.right.equalTo(scrollView) make.bottom.equalTo(scrollView).offset(-_boundsHeight) } make.width.height.equalTo(scrollView) }) } } } else { let targetBackupPoint = displayPoint + displayLen if let nextId = _display.ss_nextId { if _backup.ss_identifer != nextId || _backup.ss_identifer == "" { ss_delegate?.pageView(self, configureForView: _backup, afterView: _display) } if backupPoint != targetBackupPoint { _displayView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.left.equalTo(scrollView).offset(_boundsWidth) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(scrollView).offset(_boundsHeight) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) _backupView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { make.right.equalTo(scrollView).offset(-_boundsWidth) make.left.equalTo(_displayView.snp.right) make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(_displayView.snp.bottom) make.left.right.equalTo(scrollView) make.bottom.equalTo(scrollView).offset(-_boundsHeight) } make.width.height.equalTo(scrollView) }) } } } scrollView.setNeedsLayout() } fileprivate func dealEnd(_ scrollView: UIScrollView) { _ignoreScroll = false let lastPoint = scrollView.contentOffset let displayPoint = _isHorizontal ? _displayView.frame.origin.x : _displayView.frame.origin.y let backupPoint = _isHorizontal ? _backupView.frame.origin.x : _backupView.frame.origin.y let standar = _isHorizontal ? lastPoint.x : lastPoint.y let b = abs(backupPoint - standar) let s = abs(displayPoint - standar) if b < s { swap(&_display, &_backup) } let reachHeader = _isHorizontal ? (lastPoint.x == 0) : (lastPoint.y == 0) let reachFooter = _isHorizontal ? (lastPoint.x == scrollView.bounds.size.width * 2) : (lastPoint.y == scrollView.bounds.size.height * 2) var target: CGFloat = 0 if reachHeader { if _display?.ss_previousId != nil { target = _isHorizontal ? _boundsWidth : _boundsHeight } let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target) scrollView.setContentOffset(point, animated: false) } else if reachFooter { target = _isHorizontal ? _boundsWidth * 2: _boundsHeight * 2 if _display?.ss_nextId != nil { target = _isHorizontal ? _boundsWidth : _boundsHeight } let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target) scrollView.setContentOffset(point, animated: false) } else { target = _isHorizontal ? _boundsWidth : _boundsHeight let point = CGPoint(x: _isHorizontal ? target : 0, y: _isHorizontal ? 0 : target) scrollView.setContentOffset(point, animated: false) } _displayView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { if target == _boundsWidth * 2 { make.right.equalTo(scrollView) } else { make.left.equalTo(scrollView).offset(target) } make.top.bottom.equalTo(scrollView) } else { if target == _boundsHeight * 2 { make.top.equalTo(scrollView).offset(_boundsHeight) } else { make.top.equalTo(scrollView).offset(target) } make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) }) _backupView.snp.remakeConstraints({ (make) -> Void in if _isHorizontal { if target == _boundsWidth * 2 { make.right.equalTo(_displayView.snp.left) make.left.equalTo(scrollView).offset(_boundsWidth) } else { make.left.equalTo(_displayView.snp.right) make.right.equalTo(scrollView) } make.top.bottom.equalTo(scrollView) } else { make.top.equalTo(_displayView.snp.bottom) make.left.right.equalTo(scrollView) make.bottom.equalTo(scrollView).offset(-target) } make.width.height.equalTo(scrollView) }) scrollView.setNeedsLayout() ss_delegate?.pageView(self, didScrollToView: _display) addDisplayNextTask() } } //MARK:- Private Function private extension SSPageViewController { func setup() { view.backgroundColor = UIColor.white initializeSegment() initializeScrollview() initializeIndicator() } func initializeScrollview() { view.addSubview(scrollView) scrollView.addSubview(_displayView) scrollView.addSubview(_backupView) _displayView.snp.makeConstraints { (make) -> Void in make.top.left.bottom.height.width.equalTo(scrollView) } _backupView.snp.makeConstraints { (make) -> Void in make.width.height.equalTo(scrollView) if _isHorizontal { make.top.bottom.equalTo(scrollView) make.left.equalTo(_displayView.snp.right) make.right.equalTo(scrollView).offset(-_boundsWidth) } else { make.left.right.equalTo(scrollView) make.top.equalTo(_displayView.snp.bottom) make.bottom.equalTo(scrollView).offset(-_boundsHeight) } } scrollView.snp.makeConstraints { (make) -> Void in make.top.equalTo(segment.snp.bottom) make.left.bottom.right.equalTo(view) } _isHorizontal ? (scrollView.alwaysBounceHorizontal = true) : (scrollView.alwaysBounceVertical = true) let factorX: CGFloat = _isHorizontal ? 3 : 1 let factorY: CGFloat = _isHorizontal ? 1 : 3 scrollView.contentSize = CGSize(width: _boundsWidth * factorX, height: _boundsHeight * factorY) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.backgroundColor = UIColor.white scrollView.isPagingEnabled = true scrollView.delegate = self } func initializeSegment() { view.addSubview(segment) segment.snp.makeConstraints { (make) -> Void in make.top.left.right.equalTo(view) make.height.equalTo(0) } } func initializeIndicator() { view.addSubview(indicator) indicator.isHidden = true configureIndicator() } func configureIndicator() { if !_isHorizontal { indicator.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI * 90 / 180.0)) } indicator.sizeToFit() var inset = UIEdgeInsets.zero switch indicatorAlignStyle { case .left: _isHorizontal ? (inset.left = 10) : (inset.top = 10) case .right: _isHorizontal ? (inset.right = 10) : (inset.bottom = 10) default: break } if _isHorizontal { inset.bottom = 10 } else { inset.right = 10 } indicator.snp.removeConstraints() indicator.snp.makeConstraints { (make) -> Void in if _isHorizontal { make.bottom.equalTo(inset.bottom) if inset.left != 0 { make.left.equalTo(inset.left) } if inset.right != 0 { make.right.equalTo(inset.right) } if indicatorAlignStyle == .center { make.right.left.equalTo(indicator.superview!) } } else { make.right.equalTo(inset.right) if inset.top != 0 { make.top.equalTo(inset.top) } if inset.bottom != 0 { make.bottom.equalTo(inset.bottom) } if indicatorAlignStyle == .center { make.top.bottom.equalTo(indicator.superview!) } } } UIView.animate(withDuration: 0.2, animations: { () -> Void in self.view.setNeedsLayout() }) } func customConfigurationDone() { let hideAndStall = !(_display.ss_nextId == nil && _display.ss_previousId == nil) if showsIndicator { indicator.isHidden = hideAndStall } scrollView.isScrollEnabled = hideAndStall _displayView.snp.removeConstraints() _backupView.snp.removeConstraints() let hasPrevious = _display.ss_previousId != nil _displayView.snp.remakeConstraints { (make) -> Void in if hasPrevious { if _isHorizontal { make.top.bottom.equalTo(scrollView) make.left.equalTo(scrollView).offset(_boundsWidth) } else { make.top.equalTo(scrollView).offset(_boundsHeight) make.left.right.equalTo(scrollView) } make.width.height.equalTo(scrollView) } else { make.top.left.bottom.height.width.equalTo(scrollView) } } _backupView.snp.remakeConstraints { (make) -> Void in make.width.height.equalTo(scrollView) if _isHorizontal { make.top.bottom.equalTo(scrollView) make.left.equalTo(_displayView.snp.right) make.right.equalTo(scrollView).offset(hasPrevious ? 0 : -_boundsWidth) } else { make.left.right.equalTo(scrollView) make.top.equalTo(_displayView.snp.bottom) make.bottom.equalTo(scrollView).offset(hasPrevious ? 0 : -_boundsHeight) } } let point = hasPrevious ? CGPoint(x: _isHorizontal ? _boundsWidth : 0, y: _isHorizontal ? 0 : _boundsHeight) : CGPoint.zero scrollView.setContentOffset(point, animated: false) view.setNeedsLayout() } func addDisplayNextTask() { SSCancelableTaskManager.cancel(_task) if loopInterval == 0 || (_display.ss_nextId == nil && _display.ss_previousId == nil) { return } _task = SSCancelableTaskManager.delay(loopInterval, work: { [weak self]() -> Void in guard let sself = self else { return } let x = sself._isHorizontal ? sself.scrollView.contentOffset.x + sself._boundsWidth: 0 let y = sself._isHorizontal ? 0 : sself.scrollView.contentOffset.y + sself._boundsHeight sself.scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true) }) } } //MARK:- //MARK:- SSPageViewContentProtocol /// SSPageViewContentProtocol public protocol SSPageViewContentProtocol { var ss_identifer: String { get } var ss_previousId: String? { get } var ss_nextId: String? { get } var ss_content: UIView { get } init() } private func == (lhs: SSPageViewContentProtocol, rhs: SSPageViewContentProtocol) -> Bool { return lhs.ss_identifer == rhs.ss_identifer } //MARK:- //MARK:- SSPageViewDelegateProtocol /// SSPageViewDelegateProtocol public protocol SSPageViewDelegate: class { associatedtype Template: SSPageViewContentProtocol func pageView(_ pageView: SSPageViewController<Template, Self>, configureForView view: Template, afterView: Template) func pageView(_ pageView: SSPageViewController<Template, Self>, configureForView view: Template, beforeView: Template) func pageView(_ pageView: SSPageViewController<Template, Self>, didScrollToView view: Template) } //MARK:- Help private extension NSRange { func contain(_ number: CGFloat) -> Bool { let target = Int(number) return location <= target && target <= length } } //MARK:- CancelableTaskManager typealias SSCancelableTask = (_ cancel: Bool) -> Void struct SSCancelableTaskManager { static func delay(_ time: TimeInterval, work: @escaping ()->()) -> SSCancelableTask? { var finalTask: SSCancelableTask? let cancelableTask: SSCancelableTask = { cancel in if cancel { finalTask = nil // key } else { DispatchQueue.main.async(execute: work) } } finalTask = cancelableTask DispatchQueue.main.asyncAfter(deadline: .now() + time ) { if let task = finalTask { task(false) } } return finalTask } static func cancel(_ cancelableTask: SSCancelableTask?) { cancelableTask?(true) } }
32.02807
187
0.71697
8a29bcc4fb8b7356a69be64b4fecd3f6501d8541
2,908
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import Foundation import KeychainAccess extension CompositePond { /// An enumeration representing the method requesting the pond for the key. public enum Method: Hashable { case get case set case contains case remove } } public struct CompositePond: Pond { private let pond: (Method, Key) -> Pond public init(_ pond: @escaping (Method, Key) -> Pond) { self.pond = pond } public func get<T>(_ type: T.Type, _ key: Key) -> T? { pond(.get, key).get(type, key) } public func set<T>(_ key: Key, value: T?) { pond(.set, key).set(key, value: value) } public func contains(_ key: Key) -> Bool { pond(.contains, key).contains(key) } public func remove(_ key: Key) { pond(.remove, key).remove(key) } } // MARK: - Dot Syntax Support extension Pond where Self == CompositePond { /// Returns composite variant of `Pond`. public static func composite(_ pond: @escaping (Self.Method, Key) -> Pond) -> Self { .init(pond) } /// Returns composite variant of `Pond` with Keychain `accessGroup` and optional /// ``UserDefaults`` `suiteName`. /// /// - Parameters: /// - accessGroup: A string indicating the access group for the Keychain /// items. /// - suiteName: Creates a user defaults object initialized with the defaults /// for the specified database name. The default value is `.standard` /// - Returns: Returns composite variant of `Pond`. public static func composite(accessGroup: String, suiteName: String? = nil) -> Self { composite(keychain: .default(accessGroup: accessGroup), suiteName: suiteName) } /// Returns composite variant of `Pond` with Keychain `accessGroup` and optional /// ``UserDefaults`` `suiteName`. /// /// - Parameters: /// - keychain: The Keychain to use for keys that are marked with `keychain` /// storage. Note, the policy is automatically applied to the given keychain /// to ensure key preference is preserved. /// - suiteName: Creates a user defaults object initialized with the defaults /// for the specified database name. The default value is `.standard` /// - Returns: Returns composite variant of `Pond`. public static func composite(keychain: Keychain, suiteName: String? = nil) -> Self { let defaults = suiteName.map { UserDefaults(suiteName: $0)! } ?? .standard let userDefaults = UserDefaultsPond(defaults) return composite { _, key in switch key.storage { case .userDefaults: return userDefaults case let .keychain(policy): return KeychainPond(keychain.policy(policy)) } } } }
32.674157
89
0.620014
bb285802c02fb213f5e937c2d1700b94f86891ed
2,170
// // AppDelegate.swift // TinderDemo // // Created by Yang Yang on 11/10/16. // Copyright © 2016 Yang Yang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.170213
285
0.754839
b9dd2dad4d71f1bc36638b59a8a2d35754f94f24
715
// // SearchBar.swift // iOSEngineerCodeCheck // // Created by 大塚周 on 2020/10/20. // Copyright © 2020 YUMEMI Inc. All rights reserved. // import UIKit import SVProgressHUD extension SearchViewController: UISearchBarDelegate { func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { // ↓こうすれば初期のテキストを消せる searchBar.text = "" return true } //Enterを押した時の動き func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { if let searchWord = searchBar.text { searchRepository(searchWord: searchWord) } else { SVProgressHUD.showError(withStatus: "リポジトリを名を入力してください。") } view.endEditing(true) } }
24.655172
72
0.654545
4b1f6be27fcaa4f205f43636b7822d5ac83091a7
4,593
// // AppDelegate.swift // CloudKitSyncPOC // // Created by Nick Harris on 12/12/15. // Copyright © 2015 Nick Harris. All rights reserved. // import UIKit import CloudKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var coreDataManager: CoreDataManager? var cloudKitManager: CloudKitManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { coreDataManager = CoreDataManager() { [unowned self] in self.setCoreDataManagerInViews() self.cloudKitManager = self.coreDataManager?.cloudKitManager } let notificationOptions = UIUserNotificationSettings(types: [.alert], categories: nil) application.registerUserNotificationSettings(notificationOptions) application.registerForRemoteNotifications() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: remote notifications func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print("application.didReceiveRemoteNotification") if let stringObjectUserInfo = userInfo as? [String : NSObject] { let cloudKitZoneNotificationUserInfo = CKRecordZoneNotification(fromRemoteNotificationDictionary: stringObjectUserInfo) if let recordZoneID = cloudKitZoneNotificationUserInfo.recordZoneID { let completionBlockOperation = BlockOperation { completionHandler(UIBackgroundFetchResult.newData) } cloudKitManager?.syncZone(recordZoneID.zoneName, completionBlockOperation: completionBlockOperation) } } else { completionHandler(UIBackgroundFetchResult.noData) } } // MARK: Core Data Helper Methods func setCoreDataManagerInViews() { guard let safeCoreDataManager = coreDataManager else { fatalError("CoreDataManager expected to be set") } let tabBarController = window?.rootViewController as! UITabBarController let tabBarViewControllers = tabBarController.viewControllers! for viewController in tabBarViewControllers { switch viewController { case let navigationController as UINavigationController: if var rootViewController: CoreDataManagerViewController = navigationController.viewControllers[0] as? CoreDataManagerViewController { rootViewController.coreDataManager = safeCoreDataManager } default: () } } } }
44.163462
285
0.696495
de7926f6eec35a3e4dc20194b1d7021ac9f9835b
1,206
// // XORCipherKeySearch.swift // Alien Adventure // // Created by Jarrod Parkes on 10/3/15. // Copyright © 2015 Udacity. All rights reserved. // import Foundation extension Hero { func xorCipherKeySearch(encryptedString: [UInt8]) -> UInt8 { // NOTE: This code doesn't exactly mimic what is in the Lesson. We've // added some print statements so that there are no warnings for // unused variables 😀. var key: UInt8 = 0b00000000 for x in UInt8.min..<UInt8.max { var decrypted:[UInt8] = [] for character in encryptedString { key = x decrypted.append(x ^ character) } if let decryptedString = String(bytes: decrypted, encoding: NSUTF8StringEncoding) where decryptedString == "udacity" { break } } return key } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 3"
31.736842
235
0.586235
ccea28174e0bce362e047579362562bfc0838bd6
1,452
// // ReactViewController.swift // qoswallet // // Created by Wanghao on 2018/10/12. // Copyright © 2018年 qos. All rights reserved. // import UIKit import React class ReactViewController: UIViewController { private var jsCodeLocation: NSURL? init(moduleName: String, bridge: RCTBridge) { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(disMissController), name: NSNotification.Name(rawValue:"backToViewController"), object: nil) let mockData:NSDictionary = ["scores": [ ["name":"Alex", "value":"42"], ["name":"Joel", "value":"10"] ] ] let rootView = RCTRootView(bridge: bridge, moduleName: moduleName, initialProperties: nil) rootView?.appProperties = mockData as? [AnyHashable : Any] view = rootView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @objc func disMissController(nofi: Notification) { self.dismiss(animated: true, completion: nil) } deinit { self.view = nil NotificationCenter.default.removeObserver(self) } }
26.4
165
0.589532
fe5fdbbdbb429222e3982183103fb6a67713b8fc
1,178
// // AppReducer.swift // Beside // // Created by wubaolai on 2018/12/4. // Copyright © 2018 wubaolai. All rights reserved. // import ReSwift func AppReducer(action: Action, state: AppState?) -> AppState { return AppState( isLoading: loadingReducer(state?.isLoading, action: action), errorMessage: errorMessageReducer(state?.errorMessage, action: action), property: propertyReducer(state?.property, action: action)) } func loadingReducer(_ state: Bool?, action: Action) -> Bool { var state = state ?? false switch action { case _ as StartLoading: state = true case _ as EndLoading: state = false default: break } return state } func errorMessageReducer(_ state: String?, action: Action) -> String { var state = state ?? "" switch action { case let action as SaveErrorMessage: state = action.errorMessage case _ as CleanErrorMessage: state = "" default: break } return state } func propertyReducer(_ state: PropertyState?, action: Action) -> PropertyState { var state = state ?? PropertyState() return state }
22.653846
80
0.63837
4ab8c69118c8aa58ff7d2f04d89a55243b057ca0
1,062
// // SHFullscreenPopGestureSwiftDemoTests.swift // SHFullscreenPopGestureSwiftDemoTests // // Created by qjsios on 2017/7/20. // Copyright © 2017年 ShowHandAce. All rights reserved. // import XCTest @testable import SHFullscreenPopGestureSwiftDemo class SHFullscreenPopGestureSwiftDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
28.702703
111
0.665725
23623f6770b6fad8ba141469ca7d2c3bf34568fb
22,706
import UIKit import CoreLocation import MapboxDirections public enum SimulationIntent: Int{ case manual, poorGPS } /** The simulation mode type. Used for setting the simulation mode of the navigation service. */ public enum SimulationMode: Int { /** A setting of `.onPoorGPS` will enable simulation when we do not recieve a location update after the `poorGPSPatience` threshold has elapsed. */ case onPoorGPS /** A setting of `.always` will simulate route progress at all times. */ case always /** A setting of `.never` will never enable the location simulator, regardless of circumstances. */ case never } /** A navigation service coordinates various nonvisual components that track the user as they navigate along a predetermined route. You use `MapboxNavigationService`, which conforms to this protocol, either as part of `NavigationViewController` or by itself as part of a custom user interface. A navigation service calls methods on its `delegate`, which conforms to the `NavigationServiceDelegate` protocol, whenever significant events or decision points occur along the route. A navigation service controls a `NavigationLocationManager` for determining the user’s location, a `Router` that tracks the user’s progress along the route, a `Directions` service for calculating new routes (only used when rerouting), and a `NavigationEventsManager` for sending telemetry events related to navigation or user feedback. `NavigationViewController` comes with a `MapboxNavigationService` by default. You may override it to customize the `Directions` service or simulation mode. After creating the navigation service, pass it into `NavigationOptions(styles:navigationService:voiceController:topBanner:bottomBanner:)`, then pass that object into `NavigationViewController(for:options:)`. If you use a navigation service by itself, outside of `NavigationViewController`, call `start()` when the user is ready to begin navigating along the route. */ public protocol NavigationService: CLLocationManagerDelegate, RouterDataSource, EventsManagerDataSource { /** The location manager for the service. This will be the object responsible for notifying the service of GPS updates. */ var locationManager: NavigationLocationManager { get } /** A reference to a MapboxDirections service. Used for rerouting. */ var directions: Directions { get } /** The router object that tracks the user’s progress as they travel along a predetermined route. */ var router: Router! { get } /** The events manager, responsible for all telemetry. */ var eventsManager: NavigationEventsManager! { get } /** The route along which the user is expected to travel. */ var route: Route { get set } /** The simulation mode of the service. */ var simulationMode: SimulationMode { get set } /** The simulation speed-multiplier. Modify this if you desire accelerated simulation. */ var simulationSpeedMultiplier: Double { get set } /** The Amount of time the service will wait until it begins simulation in a poor GPS scenerio. Defaults to 2.5 seconds. */ var poorGPSPatience: Double { get set } /** The navigation service’s delegate, which is informed of significant events and decision points along the route. To synchronize your application’s state with the turn-by-turn navigation experience, set this property before starting the navigation session. */ var delegate: NavigationServiceDelegate? { get set } /** Starts the navigation service. */ func start() /** Stops the navigation service. You may call `start()` after calling `stop()`. */ func stop() /** Ends the navigation session. Used when arriving at destination. */ func endNavigation(feedback: EndOfRouteFeedback?) /** Interrogates the navigationService as to whether or not the passed-in location is in a tunnel. */ func isInTunnel(at location: CLLocation, along progress: RouteProgress) -> Bool } /** A concrete implementation of the `NavigationService` protocol. `NavigationViewController` comes with a `MapboxNavigationService` by default. You may override it to customize the `Directions` service or simulation mode. After creating the navigation service, pass it into `NavigationOptions(styles:navigationService:voiceController:topBanner:bottomBanner:)`, then pass that object into `NavigationViewController(for:options:)`. If you use a navigation service by itself, outside of `NavigationViewController`, call `start()` when the user is ready to begin navigating along the route. */ public class MapboxNavigationService: NSObject, NavigationService { typealias DefaultRouter = RouteController /** The default time interval before beginning simulation when the `.onPoorGPS` simulation option is enabled. */ static let defaultPoorGPSPatience: Double = 2.5 //seconds /** The Amount of time the service will wait until it begins simulation in a poor GPS scenerio. Defaults to 2.5 seconds. */ public var poorGPSPatience: Double = defaultPoorGPSPatience { didSet { poorGPSTimer.countdownInterval = poorGPSPatience.dispatchInterval } } /** The active location manager. Returns the location simulator if we're actively simulating, otherwise it returns the native location manager. */ public var locationManager: NavigationLocationManager { return simulatedLocationSource ?? nativeLocationSource } /** A reference to a MapboxDirections service. Used for rerouting. */ public var directions: Directions /** The active router. By default, a `PortableRouteController`. */ public var router: Router! /** The events manager. Sends telemetry back to the Mapbox platform. */ public var eventsManager: NavigationEventsManager! /** The `NavigationService` delegate. Wraps `RouterDelegate` messages. */ public weak var delegate: NavigationServiceDelegate? /** The native location source. This is a `NavigationLocationManager` by default, but can be overridden with a custom location manager at initalization. */ private var nativeLocationSource: NavigationLocationManager /** The active location simulator. Only used during `SimulationOption.always` and `SimluatedLocationManager.onPoorGPS`. If there is no simulation active, this property is `nil`. */ private var simulatedLocationSource: SimulatedLocationManager? /** The simulation mode of the service. */ public var simulationMode: SimulationMode { didSet { switch simulationMode { case .always: simulate() case .onPoorGPS: poorGPSTimer.arm() case .never: poorGPSTimer.disarm() endSimulation(intent: .manual) } } } /** The simulation speed multiplier. If you desire the simulation to go faster than real-time, increase this value. */ public var simulationSpeedMultiplier: Double { get { guard simulationMode == .always else { return 1.0 } return simulatedLocationSource?.speedMultiplier ?? 1.0 } set { guard simulationMode == .always else { return } _simulationSpeedMultiplier = newValue simulatedLocationSource?.speedMultiplier = newValue } } var poorGPSTimer: DispatchTimer! private var isSimulating: Bool { return simulatedLocationSource != nil } private var _simulationSpeedMultiplier: Double = 1.0 /** Intializes a new `NavigationService`. Useful convienence initalizer for OBJ-C users, for when you just want to set up a service without customizing anything. - parameter route: The route to follow. */ convenience init(route: Route) { self.init(route: route, directions: nil, locationSource: nil, eventsManagerType: nil) } /** Intializes a new `NavigationService`. - parameter route: The route to follow. - parameter directions: The Directions object that created `route`. - parameter locationSource: An optional override for the default `NaviationLocationManager`. - parameter eventsManagerType: An optional events manager type to use while tracking the route. - parameter simulationMode: The simulation mode desired. - parameter routerType: An optional router type to use for traversing the route. */ required public init(route: Route, directions: Directions? = nil, locationSource: NavigationLocationManager? = nil, eventsManagerType: NavigationEventsManager.Type? = nil, simulating simulationMode: SimulationMode = .onPoorGPS, routerType: Router.Type? = nil) { nativeLocationSource = locationSource ?? NavigationLocationManager() self.directions = directions ?? Directions.shared self.simulationMode = simulationMode super.init() resumeNotifications() poorGPSTimer = DispatchTimer(countdown: poorGPSPatience.dispatchInterval) { [weak self] in guard let mode = self?.simulationMode, mode == .onPoorGPS else { return } self?.simulate(intent: .poorGPS) } let routerType = routerType ?? DefaultRouter.self router = routerType.init(along: route, directions: self.directions, dataSource: self) let eventType = eventsManagerType ?? NavigationEventsManager.self eventsManager = eventType.init(dataSource: self, accessToken: route.accessToken) locationManager.activityType = route.routeOptions.activityType bootstrapEvents() router.delegate = self nativeLocationSource.delegate = self checkForUpdates() checkForLocationUsageDescription() } deinit { suspendNotifications() endNavigation() nativeLocationSource.delegate = nil simulatedLocationSource?.delegate = nil } /** Determines if a location is within a tunnel. - parameter location: The location to test. - parameter progress: the RouteProgress model that contains the route geometry. */ public func isInTunnel(at location: CLLocation, along progress: RouteProgress) -> Bool { return TunnelAuthority.isInTunnel(at: location, along: progress) } private func simulate(intent: SimulationIntent = .manual) { guard !isSimulating else { return } let progress = router.routeProgress delegate?.navigationService(self, willBeginSimulating: progress, becauseOf: intent) simulatedLocationSource = SimulatedLocationManager(routeProgress: progress) simulatedLocationSource?.delegate = self simulatedLocationSource?.speedMultiplier = _simulationSpeedMultiplier simulatedLocationSource?.startUpdatingLocation() simulatedLocationSource?.startUpdatingHeading() delegate?.navigationService(self, didBeginSimulating: progress, becauseOf: intent) } private func endSimulation(intent: SimulationIntent = .manual) { guard isSimulating else { return } let progress = router.routeProgress delegate?.navigationService(self, willEndSimulating: progress, becauseOf: intent) simulatedLocationSource?.stopUpdatingLocation() simulatedLocationSource?.stopUpdatingHeading() simulatedLocationSource?.delegate = nil simulatedLocationSource = nil delegate?.navigationService(self, didEndSimulating: progress, becauseOf: intent) } public var route: Route { get { return router.route } set { router.route = newValue } } public func start() { // Jump to the first coordinate on the route if the location source does // not yet have a fixed location. if router.location == nil, let coordinate = route.coordinates?.first { let location = CLLocation(coordinate: coordinate, altitude: -1, horizontalAccuracy: -1, verticalAccuracy: -1, course: -1, speed: 0, timestamp: Date()) router.locationManager?(nativeLocationSource, didUpdateLocations: [location]) } nativeLocationSource.startUpdatingHeading() nativeLocationSource.startUpdatingLocation() if simulationMode == .always { simulate() } eventsManager.sendRouteRetrievalEvent() } public func stop() { nativeLocationSource.stopUpdatingHeading() nativeLocationSource.stopUpdatingLocation() if [.always, .onPoorGPS].contains(simulationMode) { endSimulation() } poorGPSTimer.disarm() } public func endNavigation(feedback: EndOfRouteFeedback? = nil) { eventsManager.sendCancelEvent(rating: feedback?.rating, comment: feedback?.comment) stop() } private func bootstrapEvents() { eventsManager.dataSource = self eventsManager.resetSession() } private func resetGPSCountdown() { //Sanity check: if we're not on this mode, we have no business here. guard simulationMode == .onPoorGPS else { return } // Immediately end simulation if it is occuring. if isSimulating { endSimulation(intent: .poorGPS) } // Reset the GPS countdown. poorGPSTimer.reset() } func resumeNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil) } func suspendNotifications() { NotificationCenter.default.removeObserver(self) } @objc private func applicationWillTerminate(_ notification: NSNotification) { endNavigation() } } extension MapboxNavigationService: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { router.locationManager?(manager, didUpdateHeading: newHeading) } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //If we're always simulating, make sure this is a simulated update. if simulationMode == .always, manager != simulatedLocationSource { return } //update the events manager with the received locations eventsManager.record(locations: locations) //sanity check: make sure the update actually contains a location guard let location = locations.last else { return } //If this is a good organic update, reset the timer. if simulationMode == .onPoorGPS, manager == nativeLocationSource, location.isQualified { //If the timer is disarmed, arm it. This is a good update. if poorGPSTimer.state == .disarmed, location.isQualifiedForStartingRoute { poorGPSTimer.arm() } //pass this good update onto the poor GPS timer mechanism. resetGPSCountdown() } //Finally, pass the update onto the router. router.locationManager?(manager, didUpdateLocations: locations) } } //MARK: - RouteControllerDelegate extension MapboxNavigationService: RouterDelegate { typealias Default = RouteController.DefaultBehavior public func router(_ router: Router, willRerouteFrom location: CLLocation) { //save any progress made by the router until now eventsManager.enqueueRerouteEvent() eventsManager.incrementDistanceTraveled(by: router.routeProgress.distanceTraveled) //notify our consumer delegate?.navigationService(self, willRerouteFrom: location) } public func router(_ router: Router, didRerouteAlong route: Route, at location: CLLocation?, proactive: Bool) { //notify the events manager that the route has changed eventsManager.reportReroute(progress: router.routeProgress, proactive: proactive) //update the route progress model of the simulated location manager, if applicable. simulatedLocationSource?.route = router.route //notify our consumer delegate?.navigationService(self, didRerouteAlong: route, at: location, proactive: proactive) } public func router(_ router: Router, didFailToRerouteWith error: Error) { delegate?.navigationService(self, didFailToRerouteWith: error) } public func router(_ router: Router, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { //notify the events manager of the progress update eventsManager.update(progress: progress) //pass the update on to consumers delegate?.navigationService(self, didUpdate: progress, with: location, rawLocation: rawLocation) } public func router(_ router: Router, didPassVisualInstructionPoint instruction: VisualInstructionBanner, routeProgress: RouteProgress) { delegate?.navigationService(self, didPassVisualInstructionPoint: instruction, routeProgress: routeProgress) } public func router(_ router: Router, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) { delegate?.navigationService(self, didPassSpokenInstructionPoint: instruction, routeProgress: routeProgress) } //MARK: Questions public func router(_ router: Router, shouldRerouteFrom location: CLLocation) -> Bool { return delegate?.navigationService(self, shouldRerouteFrom: location) ?? Default.shouldRerouteFromLocation } public func router(_ router: Router, shouldDiscard location: CLLocation) -> Bool { return delegate?.navigationService(self, shouldDiscard: location) ?? Default.shouldDiscardLocation } public func router(_ router: Router, willArriveAt waypoint: Waypoint, after remainingTimeInterval: TimeInterval, distance: CLLocationDistance) { delegate?.navigationService(self, willArriveAt: waypoint, after: remainingTimeInterval, distance: distance) } public func router(_ router: Router, didArriveAt waypoint: Waypoint) -> Bool { //Notify the events manager that we've arrived at a waypoint eventsManager.arriveAtWaypoint() let shouldAutomaticallyAdvance = delegate?.navigationService(self, didArriveAt: waypoint) ?? Default.didArriveAtWaypoint if !shouldAutomaticallyAdvance { stop() } return shouldAutomaticallyAdvance } public func router(_ router: Router, shouldPreventReroutesWhenArrivingAt waypoint: Waypoint) -> Bool { return delegate?.navigationService(self, shouldPreventReroutesWhenArrivingAt: waypoint) ?? Default.shouldPreventReroutesWhenArrivingAtWaypoint } public func routerShouldDisableBatteryMonitoring(_ router: Router) -> Bool { return delegate?.navigationServiceShouldDisableBatteryMonitoring(self) ?? Default.shouldDisableBatteryMonitoring } } //MARK: EventsManagerDataSource Logic extension MapboxNavigationService { public var routeProgress: RouteProgress { return self.router.routeProgress } public var desiredAccuracy: CLLocationAccuracy { return self.locationManager.desiredAccuracy } } //MARK: RouterDataSource extension MapboxNavigationService { public var locationProvider: NavigationLocationManager.Type { return type(of: locationManager) } } fileprivate extension NavigationEventsManager { func incrementDistanceTraveled(by distance: CLLocationDistance) { sessionState?.totalDistanceCompleted += distance } func arriveAtWaypoint() { sessionState?.departureTimestamp = nil sessionState?.arrivalTimestamp = nil } func record(locations: [CLLocation]) { guard let state = sessionState else { return } locations.forEach(state.pastLocations.push(_:)) } } private extension Double { var dispatchInterval: DispatchTimeInterval { let milliseconds = self * 1000.0 //milliseconds per second let intMilliseconds = Int(milliseconds) return .milliseconds(intMilliseconds) } } private func checkForUpdates() { #if TARGET_IPHONE_SIMULATOR guard (NSClassFromString("XCTestCase") == nil) else { return } // Short-circuit when running unit tests guard let version = Bundle(for: RouteController.self).object(forInfoDictionaryKey: "CFBundleShortVersionString") else { return } let latestVersion = String(describing: version) _ = URLSession.shared.dataTask(with: URL(string: "https://docs.mapbox.com/ios/navigation/latest_version.txt")!, completionHandler: { (data, response, error) in if let _ = error { return } guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { return } guard let data = data, let currentVersion = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .newlines) else { return } if latestVersion != currentVersion { let updateString = NSLocalizedString("UPDATE_AVAILABLE", bundle: .mapboxCoreNavigation, value: "Mapbox Navigation SDK for iOS version %@ is now available.", comment: "Inform developer an update is available") print(String.localizedStringWithFormat(updateString, latestVersion), "https://github.com/mapbox/mapbox-navigation-ios/releases/tag/v\(latestVersion)") } }).resume() #endif } private func checkForLocationUsageDescription() { guard let _ = Bundle.main.bundleIdentifier else { return } if Bundle.main.locationAlwaysUsageDescription == nil && Bundle.main.locationWhenInUseUsageDescription == nil && Bundle.main.locationAlwaysAndWhenInUseUsageDescription == nil { preconditionFailure("This application’s Info.plist file must include a NSLocationWhenInUseUsageDescription. See https://developer.apple.com/documentation/corelocation for more information.") } }
41.358834
474
0.692064
7ab55369b4955e093aa45a9ee54d2ae3740697de
9,158
// // MapViewController.swift // Tutorial // // Created by Cuong Doan M. on 12/13/17. // Copyright © 2017 Cuong Doan M. All rights reserved. // import UIKit import MapKit import CoreLocation import MVVM final class MapViewController: BaseController { // MARK: - IBOutlets @IBOutlet weak var mapView: MKMapView! @IBOutlet var sliderGroupView: [UIView]! @IBOutlet weak var sliderRadius: UISlider! // MARK: - Properties var viewModel = MapViewModel() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() configView() configData() mapView.delegate = self AppDelegate.shared.configLocationService() mapView.showsUserLocation = true mapView.removeOverlays(mapView.overlays) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = false } // MARK: - Private private func configView() { title = viewModel.title navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_list"), style: .plain, target: self, action: #selector(showSideMenu)) navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_refresh"), style: .plain, target: self, action: #selector(refreshLocation)) configBarColor() sliderRadius.maximumTrackTintColor = App.Color.extraColor sliderRadius.minimumTrackTintColor = App.Color.mainColor sliderRadius.thumbTintColor = App.Color.mainColor sliderGroupView.forEach { (view) in view.corner = UIView.cornerView(view: view) if view == sliderGroupView[0] { view.backgroundColor = App.Color.mainColor } else { view.backgroundColor = App.Color.extraColor } } } private func configData() { viewModel.getListPromotion { [weak self](result) in guard let this = self else { return } switch result { case .success: Hud.dismiss() case .failure(let msg): this.alert(msg: msg) } } } private func getAnnotation() { viewModel.getAnnotation() mapView.addAnnotations(viewModel.annotations) } private func updateLocation() { mapView.removeOverlays(mapView.overlays) mapView.removeAnnotations(mapView.annotations) guard let center = viewModel.center else { return } let region = MKCoordinateRegionMakeWithDistance(center, CLLocationDistance(2 * viewModel.radius + 200), CLLocationDistance(2 * viewModel.radius + 200)) let overlayCircle = MKCircle(center: center, radius: CLLocationDistance(viewModel.radius)) mapView.setRegion(region, animated: true) mapView.add(overlayCircle) getAnnotation() } private func pushToDetailView(id: Int) { let vc = DetailViewController() vc.viewModel.id = id sideMenuController?.leftViewController = nil navigationController?.pushViewController(vc, animated: true) } private func showTinderView() { let tinderView: MapBranchView = MapBranchView.loadNib() tinderView.frame = view.bounds tinderView.viewModel = viewModel.viewModelForItem() view.addSubview(tinderView) tinderView.delegate = self navigationItem.rightBarButtonItem?.isEnabled = false } // MARK: - IBActions @IBAction func sliderValueChanged(_ sender: UISlider) { let value = sliderRadius.value switch value { case 1_000..<2_000: sliderRadius.setValue(1_000, animated: true) sliderGroupView[1].backgroundColor = App.Color.extraColor sliderGroupView[2].backgroundColor = App.Color.extraColor sliderGroupView[3].backgroundColor = App.Color.extraColor sliderGroupView[4].backgroundColor = App.Color.extraColor case 2_000..<4_000: sliderRadius.setValue(3_000, animated: true) sliderGroupView[1].backgroundColor = App.Color.mainColor sliderGroupView[2].backgroundColor = App.Color.extraColor sliderGroupView[3].backgroundColor = App.Color.extraColor sliderGroupView[4].backgroundColor = App.Color.extraColor case 4_000..<6_000: sliderRadius.setValue(5_000, animated: true) sliderGroupView[1].backgroundColor = App.Color.mainColor sliderGroupView[2].backgroundColor = App.Color.mainColor sliderGroupView[3].backgroundColor = App.Color.extraColor sliderGroupView[4].backgroundColor = App.Color.extraColor case 6_000..<8_000: sliderRadius.setValue(7_000, animated: true) sliderGroupView[1].backgroundColor = App.Color.mainColor sliderGroupView[2].backgroundColor = App.Color.mainColor sliderGroupView[3].backgroundColor = App.Color.mainColor sliderGroupView[4].backgroundColor = App.Color.extraColor default: sliderRadius.setValue(9_000, animated: true) sliderGroupView[1].backgroundColor = App.Color.mainColor sliderGroupView[2].backgroundColor = App.Color.mainColor sliderGroupView[3].backgroundColor = App.Color.mainColor sliderGroupView[4].backgroundColor = App.Color.mainColor viewModel.radius = 15_000 updateLocation() return } viewModel.radius = sliderRadius.value updateLocation() } @IBAction func regionDidChange(_ sender: UIButton) { mapView(mapView, didUpdate: mapView.userLocation) updateLocation() } // MARK: - objc Private @objc func showSideMenu() { sideMenuController?.showLeftView(animated: true, completionHandler: nil) } @objc func refreshLocation() { viewModel.center = mapView.centerCoordinate updateLocation() } } // MARK: MKMapView Delegate extension MapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { viewModel.center = userLocation.coordinate if mapView.overlays.isEmpty { updateLocation() } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard let annotation = annotation as? PinAnnotation else { return nil } var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: App.String.Map) if pinView == nil { pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: App.String.Map) pinView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) pinView?.canShowCallout = true pinView?.calloutOffset = CGPoint(x: 0, y: 0) pinView?.contentMode = .scaleAspectFill pinView?.image = #imageLiteral(resourceName: "ic_pinSel") } else { pinView?.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { let drawRoute = RouteBetweenTwoAnnotations() if let annotation = view.annotation { drawRoute.drawRoute(mapView, annotation, mapView.userLocation) } } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard let annotation = view.annotation as? PinAnnotation else { return } let id = annotation.id viewModel.getListBranch(id: id) showTinderView() } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let polyline = overlay as? MKPolyline { let renderer = MKPolylineRenderer(polyline: polyline) renderer.strokeColor = #colorLiteral(red: 0.6263254285, green: 0.7929193377, blue: 0, alpha: 1) renderer.lineWidth = 5.0 return renderer } if let circle = overlay as? MKCircle { let circleRenderer = MKCircleRenderer(circle: circle) circleRenderer.fillColor = #colorLiteral(red: 0.5632263422, green: 0.7628647685, blue: 0, alpha: 0.2450235445) circleRenderer.strokeColor = #colorLiteral(red: 0.1150010899, green: 0.6517065763, blue: 0.3915095031, alpha: 0.5) circleRenderer.lineWidth = 3 circleRenderer.lineDashPhase = 10 return circleRenderer } return MKOverlayRenderer() } } // MARK: - MapBranchView Delegate extension MapViewController: MapBranchViewDelegate { func mapBranch(_ view: MapBranchView, needsPerformAction action: MapBranchView.Action) { switch action { case .remove: navigationItem.rightBarButtonItem?.isEnabled = true case .push(let id): pushToDetailView(id: id) } } }
39.304721
174
0.65036
dd002eccd958e8ba2064ccb88cf94491679f1a60
1,308
import Foundation // TODO: ⚠️ UnFinish! // TODO: 准确的知道一个 NSDate 应该转成多少天前,多少小时前,多少小时后,多少天后! private extension Date { static var parser : DateFormatter! = nil var isToday : Bool { return true } var isTomorrow : Bool { return true } var isYesterday : Bool { return true } var tian : String { return "今天" } static func chineseDate(_ dateString: String, dateFormat:String = "yyyy-MM-dd HH:mm:ss", timezone:TimeZone = TimeZone(secondsFromGMT: 8)!) -> Date? { if parser == nil { parser = DateFormatter() } parser.dateFormat = dateFormat parser.timeZone = timezone return parser.date(from: dateString) } } public extension DateFormatter { /// 直接使用 dateFormat 初始化一个 NSDateFormatter convenience init(dateFormat: String) { self.init() self.dateFormat = dateFormat } } public extension Int { /// 直接转化成 NSDate var date: Date { return Date(timeIntervalSince1970: TimeInterval(self)) } /// 除以 1000 后转化成 NSDate /// /// 从 Java 服务器获取的时间戳通常要除以1000 var dateDivideByAThousand: Date { return Date(timeIntervalSince1970: TimeInterval(self / 1000)) } }
20.123077
153
0.586391
691a164ada52e677d5de0fcfe8c93eb8706e0b3e
1,710
import UIKit class SettingsBreakVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { var data = [String]() var chosen = "none" @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var okButton: UIButton! override func viewDidLoad() { super.viewDidLoad() pickerView.dataSource = self pickerView.delegate = self UISetter().roundButtonCorners(buttons: [okButton]) for i in 1...10 { data.append("\(i)") } } @IBAction func okButtonTapped(_ sender: Any) { let defaults = UserDefaults.standard let row = pickerView.selectedRow(inComponent: 0) chosen = data[row] defaults.set(chosen, forKey: StringValues().breakLengthKey) print("Break Time: \(chosen)") } // Boilerplate func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // Boilerplate func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return data.count } // Delegate for when wheels stops func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { //chosen = data[row] } // Populate PickerView. Change font to white. func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let element = data[row] let text = NSAttributedString(string: element, attributes: [NSAttributedStringKey.font:UIFont(name: "Georgia", size: 20.0)!, NSAttributedStringKey.foregroundColor:UIColor.white]) return text } }
32.884615
186
0.652047
db79551e595c69afe7c4b7f29f61494a2869e36f
690
// // ObserverViewController.swift // DesignPatterns // // Created by Radyslav Krechet on 3/26/18. // Copyright © 2018 RubyGarage. All rights reserved. // import UIKit class ObserverViewController: UIViewController { @IBOutlet private weak var textEditorView: TextEditorView! @IBOutlet private weak var stringStatisticsView: StringStatisticsView! // MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() setupObservation() } // MARK: - Setup private func setupObservation() { // MARK: Uses observation textEditorView.addObserver(stringStatisticsView) } }
21.5625
74
0.666667
e8e34a62d92b2310f09f894f237e1bc5392351ba
6,232
// // ToDoListVC.swift // HSE // // Created by Сергей Мирошниченко on 30.10.2021. // import UIKit /* MVC - Model View Controller Clean Swift (VIPER) - View (View Controller)- отобржание ---> Interactor - взаимодействие ----> Presenter - отображение данных (ошибок) с севера ------> VIEW Router - навигация (передача данных в другие VC) <------ VIEW Model(Entity) - модель данных , контанты, запросы */ final class ToDoListVC: UIViewController { private let interactor: ToDoListBusinessLogic private let router: ToDoListRoutingLogic // MARK: - UI Components private lazy var tableView: UITableView = { let table = UITableView(frame: .zero, style: .plain) table.register(ToDoListCell.self, forCellReuseIdentifier: ToDoListCell.id) let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) table.refreshControl = refreshControl table.translatesAutoresizingMaskIntoConstraints = false table.rowHeight = 50 return table }() private lazy var flyButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(systemName: "plus"), for: .normal) button.backgroundColor = .systemBlue button.clipsToBounds = true button.layer.cornerRadius = 20 button.addTarget(self, action: #selector(plusButtonTapped), for: .touchUpInside) return button }() // MARK: - Variables private var items: [ToDoListItem] = [] // MARK: - Lifecycle init( _ interactor: ToDoListBusinessLogic, router: ToDoListRoutingLogic ) { self.interactor = interactor self.router = router super.init(nibName: nil, bundle: nil) } @available (*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() interactor.fetchItems(.init(nil, .all)) setupTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.rightBarButtonItems = setupNavButtons() navigationController?.navigationBar.prefersLargeTitles = true navigationItem.title = "To Do List Items" // if let window = UIWindow.key { // window.addSubview(flyButton) // setupFlyButton() // } } // // override func viewWillDisappear(_ animated: Bool) { // super.viewWillDisappear(animated) // if let window = UIApplication.shared.keyWindow, // flyButton.isDescendant(of: view) { // flyButton.removeFromSuperview() // } // } @objc private func refreshData() { interactor.fetchItems(.init(nil, .all)) } @objc private func goToSettings() { router.routeToSettings() } @objc private func plusButtonTapped() { router.routeToAddItem { [weak self] item in self?.interactor.fetchItems(.init(item, .add)) } } private func setupNavButtons() -> [UIBarButtonItem] { let plusButton = UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(plusButtonTapped)) let settings = UIBarButtonItem( image: UIImage(systemName: "gear"), style: .plain, target: self, action: #selector(goToSettings) ) return [settings, plusButton] } } // MARK: - Display Logic extension ToDoListVC: ToDoListDisplayLogic { func displayUpdateItem(_ viewModel: ToDoListModels.UpdateItems.ViewModel) { } func displayCells(_ viewModel: ToDoListModels.FetchItems.ViewModel) { tableView.refreshControl?.endRefreshing() items = viewModel.items tableView.reloadData() } func displayError(_ viewModel: ToDoListModels.Error.ViewModel) { } } // MARK: - UITableView Delegate&DataSource extension ToDoListVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: ToDoListCell.id, for: indexPath) as? ToDoListCell else { return UITableViewCell() } cell.model = items[indexPath.row] return cell } func numberOfSections(in tableView: UITableView) -> Int { 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { items.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Setup UI components private extension ToDoListVC { func setupTableView() { view.addSubview(tableView) tableView.backgroundColor = .systemBackground NSLayoutConstraint.activate([ tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) tableView.delegate = self tableView.dataSource = self } func setupFlyButton() { NSLayoutConstraint.activate([ flyButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -32), flyButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32), flyButton.widthAnchor.constraint(equalToConstant: 40), flyButton.heightAnchor.constraint(equalToConstant: 40) ]) } } extension UIWindow { static var key: UIWindow? { if #available(iOS 13, *) { return UIApplication.shared.windows.first { $0.isKeyWindow } } else { return UIApplication.shared.keyWindow } } }
29.961538
127
0.637516
26e672cc458b75869a4f742c460fa3061910ed71
1,328
// // AppDelegate.swift // RequestResponseDemo // // Created by Andrew Madsen on 3/14/15. // Copyright (c) 2015 Open Reel Software. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { }
39.058824
74
0.759789
d5d0ca9e98b10eb12a4c92502fb328eccd7ba611
837
// // KeyPathBuildable.swift // Swiftest // // Created by Brian Strobach on 1/14/19. // public protocol KeyPathBuildable: AnyObject { func with<T>(_ keyPath: WritableKeyPath<Self, T>, _ value: T) -> Self func with(_ keyPathValuePairs: KeyPathValuePairs<Self>) -> Self func with(_ keyPathValuePair: KeyPathValuePair<Self>...) -> Self } extension KeyPathBuildable { @discardableResult public func with<T>(_ keyPath: WritableKeyPath<Self, T>, _ value: T) -> Self { return with(keyPath.with(value: value)) } @discardableResult public func with(_ keyPathValuePair: KeyPathValuePair<Self>...) -> Self { return with(keyPathValuePair) } @discardableResult public func with(_ keyPathValuePairs: KeyPathValuePairs<Self>) -> Self { return self += keyPathValuePairs } }
27.9
82
0.682198
20be1606feb9a8d899b4c5be0077e244a6f7962c
931
// // StringExtension.swift // Words // // Created by Carlos Cáceres González on 17/03/2021. // import Foundation extension String { /// Allows the string localization code to be much more clean var localized: String { return NSLocalizedString(self, comment: "") } /// Array of substrings inside a string var words: [String] { var words: [String] = [] self.enumerateSubstrings(in: self.startIndex..., options: [.byWords]) { _, range, _, _ in words.append(String(self[range])) } return words } /// Delete all non-supported symbols and lowercase the string var sanitized: String { let nonSupportedSymbols = CharacterSet(arrayLiteral: ".", ",", "'", ";", "\"", ":", "`", "´", "(", ")", "-", "_", ":", "?", "!") return self.components(separatedBy: nonSupportedSymbols).joined(separator: "").lowercased() } } // String
25.162162
136
0.589689
d54772ec24b3287c04e714a90caadc9e8f9d4542
1,555
// // Copyright © 2018 Frollo. All rights reserved. // // 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 Foundation @testable import FrolloSDK extension InternationalContact { override func populateTestData() { super.populateTestData() internationalContactName = String.randomString(range: 5...20) internationalContactCountry = String.randomString(range: 5...20) internationalContactMessage = String.randomString(range: 5...20) internationalBankCountry = String.randomString(range: 5...20) internationalAccountNumber = String(Int.random(in: 1000000...Int.max)) internationalBankAddress = String.randomString(range: 5...20) bic = String.randomString(range: 5...20) fedwireNumber = String.randomString(range: 5...20) sortCode = String.randomString(range: 5...20) chipNumber = String.randomString(range: 5...20) routingNumber = String.randomString(range: 5...20) legalEntityId = String.randomString(range: 5...20) } }
38.875
78
0.705466
d9ac9e8018e2df5ed901bb1d04e932d530e7ee69
5,065
import Foundation import UIKit import Hodler class TransactionCell: UITableViewCell { static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale.current formatter.setLocalizedDateFormatFromTemplate("yyyy MMM d, HH:mm:ss") return formatter }() @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var valueLabel: UILabel? @IBOutlet weak var transactionTypeLabel: UILabel? private let coinRate: Decimal = pow(10, 8) func bind(transaction: TransactionRecord, coinCode: String, lastBlockHeight: Int?) { var confirmations = "n/a" if let lastBlockHeight = lastBlockHeight, let blockHeight = transaction.blockHeight { confirmations = "\(lastBlockHeight - blockHeight + 1)" } let from = transaction.from.map { from -> String in var string = from.address.flatMap { format(hash: $0) } ?? "Unknown address" if from.mine { string += "(mine)" } if let value = from.value { string += "(\((Decimal(value) / coinRate).formattedAmount))" } return string } let to = transaction.to.map { to -> String in var string = to.address.flatMap { format(hash: $0) } ?? "Unknown address" if to.mine { string += "(mine)" } if to.changeOutput { string += "(change)" } if let value = to.value { string += "(\((Decimal(value) / coinRate).formattedAmount))" } if let pluginId = to.pluginId, let pluginData = to.pluginData, pluginId == HodlerPlugin.id, let hodlerData = pluginData as? HodlerOutputData { string += "\nLocked Until: \(TransactionCell.dateFormatter.string(from: Date(timeIntervalSince1970: Double(hodlerData.approximateUnlockTime!)))) <-" string += "\nOriginal: \(format(hash: hodlerData.addressString)) <-" } return string } set(string: """ Tx Hash: Tx Status: Tx Index: Date: Type: Amount: Fee: Block: ConflictingHash: Confirmations: \(from.map { _ in "From:" }.joined(separator: "\n")) \(transaction.to.map { "To:\(String(repeating: "\n", count: TransactionCell.rowsCount(address: $0)))" }.joined(separator: "")) """, alignment: .left, label: titleLabel) set(string: """ \(format(hash: transaction.transactionHash)) \(transaction.status) \(transaction.transactionIndex) \(TransactionCell.dateFormatter.string(from: transaction.date)) \(transaction.type.rawValue) \(transaction.amount.formattedAmount) \(coinCode) \(transaction.fee?.formattedAmount ?? "") \(coinCode) \(transaction.blockHeight.map { "# \($0)" } ?? "n/a") \(format(hash: transaction.conflictingHash ?? "n/a")) \(confirmations) \(from.joined(separator: "\n")) \(to.joined(separator: "\n")) """, alignment: .right, label: valueLabel) transactionTypeLabel?.isHidden = transaction.transactionExtraType == nil transactionTypeLabel?.text = transaction.transactionExtraType } private func set(string: String, alignment: NSTextAlignment, label: UILabel?) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 paragraphStyle.alignment = alignment let attributedString = NSMutableAttributedString(string: string) attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length)) label?.attributedText = attributedString } private func format(hash: String) -> String { guard hash.count > 22 else { return hash } return "\(hash[..<hash.index(hash.startIndex, offsetBy: 8)])...\(hash[hash.index(hash.endIndex, offsetBy: -2)...])" } } extension TransactionCell { static func rowsCount(address: TransactionInputOutput) -> Int { var rowsCount = 1 if let pluginId = address.pluginId, pluginId == HodlerPlugin.id { rowsCount += 2 } return rowsCount } static func rowHeight(for transaction: TransactionRecord) -> Int { let addressRowsCount = transaction.to.reduce(0) { $0 + rowsCount(address: $1) } + transaction.from.count var height = (addressRowsCount + 10) * 18 + 30 if transaction.transactionExtraType != nil { height += 18 } return height } }
38.082707
165
0.561303
dee0f2859b9c7db25168c3a5c1fde34c849bdd13
4,319
// // RSDTextLabelCell.swift // ResearchUI (iOS) // // Copyright © 2017-2019 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import UIKit import Research /// `RSDTextLabelCell` can be used to display a text element such as a footnote in a table. @IBDesignable open class RSDTextLabelCell : RSDTableViewCell { private let kSideMargin = CGFloat(20.0).rsd_proportionalToScreenWidth() private let kVertMargin: CGFloat = 10.0 private let kMinHeight: CGFloat = 75.0 /// The label used to display text using this cell. @IBOutlet public var label: UILabel! /// Set the label text. override open var tableItem: RSDTableItem! { didSet { guard let item = tableItem as? RSDTextTableItem else { return } label.text = item.text } } public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } open override func awakeFromNib() { super.awakeFromNib() commonInit() } func commonInit() { self.selectionStyle = .none if label == nil { label = UILabel() contentView.addSubview(label) label.accessibilityTraits = UIAccessibilityTraits.summaryElement label.translatesAutoresizingMaskIntoConstraints = false label.preferredMaxLayoutWidth = UIScreen.main.bounds.size.width - (kSideMargin * 2) label.numberOfLines = 0 label.textAlignment = .left label.rsd_alignToSuperview([.leading, .trailing], padding: kSideMargin) label.rsd_alignToSuperview([.top], padding: kVertMargin) } contentView.rsd_makeHeight(.greaterThanOrEqual, kMinHeight) updateColorAndFont() setNeedsUpdateConstraints() } override open func setDesignSystem(_ designSystem: RSDDesignSystem, with background: RSDColorTile) { super.setDesignSystem(designSystem, with: background) updateColorAndFont() } func updateColorAndFont() { guard let colorTile = self.backgroundColorTile else { return } let designSystem = self.designSystem ?? RSDDesignSystem() label.font = designSystem.fontRules.font(for: .microDetail, compatibleWith: traitCollection) label.textColor = designSystem.colorRules.textColor(on: colorTile, for: .microDetail) } }
39.263636
104
0.692058
911ff8beb70c2e64122cbd80c31d174a3638a988
1,391
// Sources/SwiftProtobuf/ProtobufMap.swift - Map<> support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Generic type representing proto map<> fields. /// // ----------------------------------------------------------------------------- import Foundation /// SwiftProtobuf Internal: Support for Encoding/Decoding. public struct _ProtobufMap<KeyType: MapKeyType, ValueType: FieldType> { public typealias Key = KeyType.BaseType public typealias Value = ValueType.BaseType public typealias BaseType = Dictionary<Key, Value> } /// SwiftProtobuf Internal: Support for Encoding/Decoding. public struct _ProtobufMessageMap<KeyType: MapKeyType, ValueType: Message & Hashable> { public typealias Key = KeyType.BaseType public typealias Value = ValueType public typealias BaseType = Dictionary<Key, Value> } /// SwiftProtobuf Internal: Support for Encoding/Decoding. public struct _ProtobufEnumMap<KeyType: MapKeyType, ValueType: Enum> { public typealias Key = KeyType.BaseType public typealias Value = ValueType public typealias BaseType = Dictionary<Key, Value> }
34.775
85
0.671459
1c596cd6ed899263e39edba5af45db2f00806675
559
// // Result.swift // FlexNetworking // // Created by Dennis Lysenko on 6/27/18. // Copyright © 2018 Dennis Lysenko. All rights reserved. // import Foundation public enum Result<T>: CustomStringConvertible { case success(T) case failure(Error) public var description: String { switch self { case .success(let value): return "Success(\(value))" case .failure(let error): return "Failure(\(String(reflecting: error)))" } } } public typealias ResultBlock = (Result<Response>) -> ()
21.5
58
0.620751
3aabb16cfa1b8d3432df8c7ca93a7685ca8db828
1,557
// // TimeOut.swift // UltimatePegSolitaire // // Created by Maksim Khrapov on 4/11/20. // Copyright © 2020 Maksim Khrapov. All rights reserved. // // https://www.ultimatepegsolitaire.com/ // https://github.com/mkhrapov/ultimate-peg-solitaire // // 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 Foundation final class TimeOut { static let shared = TimeOut() let allowedTimeOuts = [ 10, 60, 2*60, 3*60, 5*60, 10*60, 15*60, 30*60, 60*60] let allowedTimeOutTitles = ["10 sec", "60 sec", "2 min", "3 min", "5 min", "10 min", "15 min", "30 min", "1 hour"] func row(_ n: Int) -> Int { for i in 0..<allowedTimeOuts.count { if allowedTimeOuts[i] == n { return i } } return 0 } func title(_ n: Int) -> String { for i in 0..<allowedTimeOuts.count { if allowedTimeOuts[i] == n { return allowedTimeOutTitles[i] } } return "Unknown" } }
29.377358
118
0.604367
338a96f2d2fda5ad3f3e6ea81507ae355dbc37c2
1,672
// // NetworkErrorPlugin.swift // F22Labs // // Created by Ranjith Kumar on 27/04/2017. // Copyright © 2017 F22Labs. All rights reserved. // enum HudPosition { case top,bottom } enum HudBgColor { case red,blue,gray } struct HudInfo { var bg_color:HudBgColor? var position:HudPosition? } public struct FLError<A> { var code:Int? var message:String? var status:Bool? var typeToShow:A? public init(code:Int,message:String,typeToShow:A,status:Bool) { self.code = code self.message = message self.typeToShow = typeToShow self.status = status } static func buildError<T>(input:T)->Any { var plugin:Any? = nil if input is FLMeta { let meta = input as! FLMeta let h_info = HudInfo.init(bg_color: (meta.status ? .red : .blue), position: .top) plugin = FLError<HudInfo>.init(code: 200, message: meta.message!, typeToShow: h_info,status:meta.status) }else { let error = input as! NSError if FLErrorJSON.list?.keys.contains(String(error.code)) == false { let h_info = HudInfo.init(bg_color: .red, position: .top) plugin = FLError<HudInfo>.init(code: error.code, message: error.localizedDescription, typeToShow: h_info,status: false) }else { let h_info = HudInfo.init(bg_color: .red, position: .top) let code = String(error.code) plugin = FLError<HudInfo>.init(code: error.code, message: (FLErrorJSON.list?[code])! as! String, typeToShow:h_info,status: false) } } return plugin! } }
30.4
145
0.605861
391eaa5a4020250d54470ab97e077c6b2c04ae55
198
import Foundation public class SquidCoders { private init() {} public static let shared = SquidCoders() public var decoder = JSONDecoder() public var encoder = JSONEncoder() }
19.8
44
0.681818
20dc133f4424d1ef9cffc90d16a04500a21e1ff8
332
// // WorldTVCell.swift // MultilevelExpandCollapse // // Created on 02/09/21. import Foundation import UIKit class WorldTVCell : UITableViewCell { @IBOutlet weak var titlel : UILabel! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setUpData() { } }
15.809524
45
0.626506
5b52c7049d0a50e3b146ca33d94783e9c747cb5c
18,202
import Foundation import CoreData import Time final class MedicationManager: ObservableObject { enum dateSection { case today case next } enum historicStatus { case onTime case late case missed } enum historicType { case all case all7Days case all30Days case medication7Days case medication30Days } private var notificationManager = NotificationManager() private var userSettings = UserSettings() let container: NSPersistentCloudKitContainer @Published var savedMedications: [Medication] = [] @Published var savedHistoric: [Historic] = [] init() { container = NSPersistentCloudKitContainer(name: "meuMedicamento") container.loadPersistentStores { description, error in if let error = error { print("ERROR LOADING CORE DATA. \(error)") } } //let options = NSPersistentCloudKitContainerSchemaInitializationOptions() //try? container.initializeCloudKitSchema(options: options) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy fetchMedications() } func fetchMedications() { let request = NSFetchRequest<Medication>(entityName: "Medication") let sortDescriptor = NSSortDescriptor(key: "date", ascending: true) request.sortDescriptors = [sortDescriptor] do { savedMedications = try container.viewContext.fetch(request) } catch { print("Error fetching \(error)") } } func fetchHistories() { let request = NSFetchRequest<Historic>(entityName: "Historic") do { savedHistoric = try container.viewContext.fetch(request) } catch { print("Error fetching \(error)") } } func deleteHistories() { let histories = savedHistoric for historic in histories { if historic.medication == nil { container.viewContext.delete(historic) } } _ = saveData() } func fetchHistoric (forStatus status: historicStatus, forType type: historicType, medication: Medication? = nil) -> Int { fetchHistories() let sevenDays = 7.days.inSeconds.value * -1 let thirtyDays = 30.days.inSeconds.value * -1 switch status { case .onTime: switch type { case .all: let onTime = savedHistoric.filter({$0.medicationStatus == "Sem Atraso"}).count return onTime case .all7Days: let onTime = savedHistoric.filter({$0.medicationStatus == "Sem Atraso" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays}).count return onTime case .all30Days: let onTime = savedHistoric.filter({$0.medicationStatus == "Sem Atraso" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays}).count return onTime case .medication7Days: guard let medication = medication else { return 0 } let onTime = savedHistoric.filter({$0.medicationStatus == "Sem Atraso" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays && $0.medication == medication}).count return onTime case .medication30Days: guard let medication = medication else { return 0 } let onTime = savedHistoric.filter({$0.medicationStatus == "Sem Atraso" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays && $0.medication == medication}).count return onTime } case .late: switch type { case .all: let late = savedHistoric.filter({$0.medicationStatus == "Atrasado"}).count return late case .all7Days: let late = savedHistoric.filter({$0.medicationStatus == "Atrasado" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays}).count return late case .all30Days: let late = savedHistoric.filter({$0.medicationStatus == "Atrasado" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays}).count return late case .medication7Days: guard let medication = medication else { return 0 } let late = savedHistoric.filter({$0.medicationStatus == "Atrasado" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays && $0.medication == medication}).count return late case .medication30Days: guard let medication = medication else { return 0 } let late = savedHistoric.filter({$0.medicationStatus == "Atrasado" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays && $0.medication == medication}).count return late } case .missed: switch type { case .all: let missed = savedHistoric.filter({$0.medicationStatus == "Não tomou"}).count return missed case .all7Days: let missed = savedHistoric.filter({$0.medicationStatus == "Não tomou" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays}).count return missed case .all30Days: let missed = savedHistoric.filter({$0.medicationStatus == "Não tomou" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays}).count return missed case .medication7Days: guard let medication = medication else { return 0 } let missed = savedHistoric.filter({$0.medicationStatus == "Não tomou" && $0.dates?.timeIntervalSinceNow ?? 0 >= sevenDays && $0.medication == medication}).count return missed case .medication30Days: guard let medication = medication else { return 0 } let missed = savedHistoric.filter({$0.medicationStatus == "Não tomou" && $0.dates?.timeIntervalSinceNow ?? 0 >= thirtyDays && $0.medication == medication}).count return missed } } } func fetchHistoric(forMedication medication: Medication) -> [Historic] { var aux = Array(medication.dates as? Set<Historic> ?? []) aux = aux.sorted(by: { $0.dates ?? .distantPast > $1.dates ?? .distantPast }) return aux } func checkMedicationDate(forMedication medication: Medication) -> dateSection { let calendar = Calendar.current let today = Date() let midnight = calendar.startOfDay(for: today) guard let tomorrow = calendar.date(byAdding: .day, value: 1, to: midnight) else {return .next} if medication.date ?? Date() < tomorrow { return .today } else { return .next } } func calculateLateMedications() -> Int { let lateMedications = savedMedications.filter({$0.date?.timeIntervalSinceNow ?? Date().timeIntervalSinceNow < 0}) return lateMedications.count } func saveData() -> medicationResult { var sucess: medicationResult = .sucess; if container.viewContext.hasChanges { do { try container.viewContext.save() fetchMedications() } catch let error { print("Error saving \(error)") sucess = .viewContextError } } return sucess } func addMedication(name: String, remainingQuantity: Int32, boxQuantity: Int32, date: Date, repeatPeriod: String, notes: String, notificationType: String) -> medicationResult { let newMedication = Medication(context: container.viewContext) newMedication.name = name newMedication.remainingQuantity = remainingQuantity newMedication.boxQuantity = boxQuantity newMedication.id = UUID().uuidString newMedication.date = date if repeatPeriod == "" { newMedication.repeatPeriod = "Nunca" } else { newMedication.repeatPeriod = repeatPeriod } newMedication.notes = notes newMedication.isSelected = false newMedication.repeatSeconds = convertToSeconds(newMedication.repeatPeriod ?? "") newMedication.notificationType = notificationType var situation: medicationResult = .sucess situation = saveData() if situation == .sucess { guard let timeInterval = newMedication.date?.timeIntervalSinceNow else { situation = .notificationTimeIntervalError return situation } guard let identifier = newMedication.id else { situation = .notificationTimeIntervalError return situation } if timeInterval > 0 { notificationManager.deleteLocalNotifications(identifiers: [identifier]) notificationManager.createLocalNotificationByTimeInterval(identifier: identifier, title: "Tomar \(newMedication.name ?? "Medicamento")", timeInterval: timeInterval) { error in if error == nil { print("Notificação criada com id: \(identifier)") situation = .sucess } } } } return situation } func editMedication(name: String, remainingQuantity: Int32, boxQuantity: Int32, date: Date, repeatPeriod: String, notes: String, notificationType: String, medication: Medication) -> medicationResult { medication.name = name medication.remainingQuantity = remainingQuantity medication.boxQuantity = boxQuantity medication.date = date if repeatPeriod == "" { medication.repeatPeriod = "Nunca" } else { medication.repeatPeriod = repeatPeriod } medication.notes = notes medication.isSelected = false medication.repeatSeconds = convertToSeconds(medication.repeatPeriod ?? "") medication.notificationType = notificationType var situation: medicationResult = .sucess situation = saveData() guard let timeInterval = medication.date?.timeIntervalSinceNow else { situation = .notificationTimeIntervalError return situation } let identifierRepeat = (medication.id ?? UUID().uuidString) + "-Repiting" guard let identifier = medication.id else { situation = .notificationTimeIntervalError return situation } if timeInterval > 0 { notificationManager.deleteLocalNotifications(identifiers: [identifier, identifierRepeat]) notificationManager.createLocalNotificationByTimeInterval(identifier: identifier, title: "Tomar \(medication.name ?? "Medicamento")", timeInterval: timeInterval) { error in if error == nil { print("Notificação criada com id: \(identifier)") situation = .sucess } } } return situation } func deleteMedication(medication: Medication) { guard let identifier = medication.id else {return} let identifierRepeat = identifier + "-Repiting" notificationManager.deleteLocalNotifications(identifiers: [identifier, identifierRepeat]) container.viewContext.delete(medication) let sucess = saveData() print(sucess) } func updateRemainingQuantity(medication: Medication) -> medicationResult { var situation: medicationResult = .sucess if medication.remainingQuantity > 1 { situation = scheduleQuantityNotification(forMedication: medication) medication.remainingQuantity -= 1 let historic = Historic(context: container.viewContext) historic.dates = Date() historic.medication = medication if !(medication.repeatPeriod == "Nunca") { rescheduleNotification(forMedication: medication, forHistoric: historic) } situation = saveData() } else { deleteMedication(medication: medication) } return situation } func scheduleQuantityNotification(forMedication medication: Medication) -> medicationResult { var situation: medicationResult = .sucess if medication.remainingQuantity > 1 { if Double(medication.remainingQuantity) <= Double(medication.boxQuantity) * (userSettings.limitMedication/100.0) { if userSettings.limitNotification { print("USERDEFAULTS-----------") print(userSettings.limitNotification) print(userSettings.limitMedication) print("---------------------------") let identifier = (medication.id ?? UUID().uuidString) + "-Repiting" let dateMatching = Calendar.current.dateComponents([.hour,.minute], from: userSettings.limitDate) let hour = dateMatching.hour let minute = dateMatching.minute notificationManager.deleteLocalNotifications(identifiers: [identifier]) notificationManager.createLocalNotificationByDateMatching(identifier: identifier, title: "Comprar \(medication.name ?? "Medicamento")", hour: hour ?? 12, minute: minute ?? 00) { error in if error == nil { situation = .sucess print("Notificação criada com id: \(identifier)") } else { situation = .notificationDateMatchingError } } } } } return situation } func nextDates(forMedication medication: Medication) -> [Date] { guard let date1 = medication.date else { return [] } var dates = [date1] if medication.repeatPeriod != "Nunca" { let date2 = Date(timeInterval: medication.repeatSeconds, since: date1) let date3 = Date(timeInterval: medication.repeatSeconds, since: date2) let date4 = Date(timeInterval: medication.repeatSeconds, since: date3) dates.append(date2) dates.append(date3) dates.append(date4) } return dates } func rescheduleNotification(forMedication medication: Medication, forHistoric historic: Historic) { medicationStatus(forMedication: medication, forHistoric: historic) if medication.notificationType == "Regularmente" { medication.date = Date(timeInterval: medication.repeatSeconds, since: medication.date ?? Date()) } else { medication.date = Date(timeIntervalSinceNow: medication.repeatSeconds) } guard let timeInterval = medication.date?.timeIntervalSinceNow else {return} guard let identifier = medication.id else {return} if timeInterval > 0 { notificationManager.deleteLocalNotifications(identifiers: [identifier]) notificationManager.createLocalNotificationByTimeInterval(identifier: identifier, title: "Tomar \(medication.name ?? "Medicamento")", timeInterval: timeInterval) { error in if error == nil {} } } else { rescheduleNotification(forMedication: medication, forHistoric: historic) historic.medicationStatus = "Não tomou" } } func reloadNotifications() { notificationManager.removeLocalNotifications() for medication in savedMedications { guard let date = medication.date else {return} if date.timeIntervalSinceNow > 0.0 { let timeInterval = date.timeIntervalSinceNow guard let identifier = medication.id else {return} print("Reagendando notificação para \(medication.name ?? "Medicamento")") notificationManager.createLocalNotificationByTimeInterval(identifier: identifier, title: "Tomar \(medication.name ?? "Medicamento")", timeInterval: timeInterval) { error in if error == nil {} } } _ = scheduleQuantityNotification(forMedication: medication) } } func medicationStatus(forMedication medication: Medication, forHistoric historic: Historic) { var timeIntervalComparation = 0.0 if let timeIntervalDate = medication.date?.timeIntervalSince(historic.dates ?? Date()) { timeIntervalComparation = timeIntervalDate } if timeIntervalComparation < -900.0 { historic.medicationStatus = "Atrasado" } else { historic.medicationStatus = "Sem Atraso" } } func refreshRemainingQuantity(medication: Medication) { medication.remainingQuantity += medication.boxQuantity let sucess = saveData() print(sucess) guard let id = medication.id else {return} let identifier = id + "-Repiting" notificationManager.deleteLocalNotifications(identifiers: [identifier]) } func convertToSeconds(_ time: String) -> Double { var seconds = 3.0 switch time { case "Nunca": seconds = 0.0 case "1 hora": seconds = 1.hours.inSeconds.value case "2 horas": seconds = 2.hours.inSeconds.value case "4 horas": seconds = 4.hours.inSeconds.value case "6 horas": seconds = 6.hours.inSeconds.value case "8 horas": seconds = 8.hours.inSeconds.value case "12 horas": seconds = 12.hours.inSeconds.value case "1 dia": seconds = 1.days.inSeconds.value case "2 dias": seconds = 2.days.inSeconds.value case "5 dias": seconds = 5.days.inSeconds.value case "1 semana": seconds = 7.days.inSeconds.value case "2 semanas": seconds = 14.days.inSeconds.value case "1 mês": seconds = 30.days.inSeconds.value case "3 meses": seconds = 90.days.inSeconds.value case "6 meses": seconds = 180.days.inSeconds.value default: break } return seconds } }
41.274376
204
0.610043