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
f585fcdb4c07b628ba5d4d0a59dd34512acdd742
2,164
// // AppDelegate.swift // infinite_scroll // // Created by Viktor on 3/6/19. // Copyright © 2019 vm. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.042553
285
0.754621
cc2afc978bdb0be7a3c3213a0237a2700a0ad7dd
927
// // UIApplication+Livetouch.swift // Pods // // Created by Guilherme Politta on 7/07/16. // // import UIKit public extension UIApplication { public static func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } if let menu = base as? SideMenuContainerViewController { return topViewController(menu.getCenterViewController()) } return base } }
27.264706
143
0.626753
e02703e21db4dbaf3baf4917656c599874c549d0
2,077
// // NotificationObject.swift // Picroup-iOS // // Created by luojie on 2018/5/14. // Copyright © 2018年 luojie. All rights reserved. // import RealmSwift import Apollo final class NotificationObject: PrimaryObject { @objc dynamic var userId: String? @objc dynamic var toUserId: String? @objc dynamic var mediumId: String? @objc dynamic var content: String? @objc dynamic var kind: String? let createdAt = RealmOptional<Double>() let viewed = RealmOptional<Bool>() @objc dynamic var user: UserObject? @objc dynamic var medium: MediumObject? } final class CursorNotificationsObject: PrimaryObject { let cursor = RealmOptional<Double>() let items = List<NotificationObject>() } extension CursorNotificationsObject: IsCursorItemsObject { typealias CursorItemsFragment = CursorNotoficationsFragment static func create(from fragment: CursorItemsFragment, id: String) -> (Realm) -> CursorNotificationsObject { return { realm in let itemSnapshots = fragment.items.map { $0.fragments.notificationFragment.rawSnapshot } // print("itemSnapshots", itemSnapshots) let value: Snapshot = fragment.snapshot.merging(["_id": id, "items": itemSnapshots]) { $1 } return realm.create(CursorNotificationsObject.self, value: value, update: true) } } func merge(from fragment: CursorItemsFragment) -> (Realm) -> Void { return { realm in let itemSnapshots = fragment.items.map { $0.fragments.notificationFragment.rawSnapshot } let items = itemSnapshots.map { realm.create(Item.self, value: $0, update: true) } self.cursor.value = fragment.cursor self.items.append(objectsIn: items) } } } extension CursorNotoficationsFragment: IsCursorFragment {} extension NotificationFragment { var rawSnapshot: Snapshot { return snapshot.merging([ "kind": kind.rawValue, "medium": medium?.fragments.mediumFragment.rawSnapshot ]) { $1 } } }
31.953846
112
0.672605
90193040b29c9a946b9515e457739e0e3c5950a7
2,259
/// Copyright (c) 2021 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 SwiftUI struct CardThumbnailView: View { var body: some View { RoundedRectangle(cornerRadius: 15) .foregroundColor(.random()) .frame( width: Settings.thumbnailSize.width, height: Settings.thumbnailSize.height) } } struct CardThumbnailView_Previews: PreviewProvider { static var previews: some View { CardThumbnailView() } }
45.18
83
0.748561
ebeb00955a1f0758e930aea7e5f5b776be0cdd0c
702
// // CompletePopUpViewController.swift // TikTok // // Created by IJ . on 2020/01/04. // Copyright © 2020 김준성. All rights reserved. // import UIKit class CompletePopUpViewController: UIViewController { 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. } */ }
22.645161
106
0.663818
20f9250aa575f0afabafeaa67161e289e9e931c0
478
// // TeamCityTestUITests.swift // TeamCityTestUITests // // Created by Кирилл Володин on 19.02.2018. // Copyright © 2018 Кирилл Володин. All rights reserved. // import XCTest class TeamCityTestUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testExample() { } }
17.071429
57
0.596234
bb9c222610fdf57fcaf8b475fa86248bcea09249
1,656
// // AdDialogViewController.swift // offers // // Created by Ravi Tamada on 18/07/17. // Copyright © 2017 Ravi Tamada. All rights reserved. // import UIKit protocol AdDialogDelegate { func onActivateCouponConfirmed(); func onAdDialogDismissed(); } public class AdDialogViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var viewBackground: UIView! @IBOutlet weak var adImage: UIImageView! public var imageUrl: String = "" var delegate: AdDialogDelegate! override public func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))) tap.delegate = self viewBackground.addGestureRecognizer(tap) } public override func viewDidAppear(_ animated: Bool) { self.view.superview?.backgroundColor = UIColor.clear self.view.superview?.isOpaque = false self.modalPresentationStyle = .overCurrentContext self.displayAdImage() } @objc func handleTap(sender: UITapGestureRecognizer? = nil) { dismiss(animated: true, completion: nil) self.delegate?.onAdDialogDismissed() } @IBAction func dismissClicked(_ sender: UIButton) { dismiss(animated: true, completion: nil) self.delegate?.onAdDialogDismissed() } @IBAction func onConfirmClicked(_ sender: UIButton) { dismiss(animated: true, completion: nil) self.delegate?.onActivateCouponConfirmed() } func displayAdImage(){ self.adImage.downloadedFrom(link: imageUrl) } }
27.147541
93
0.668478
7a75ed5187221c0c9810fccf6822839a2e04d4e3
2,155
// // Mastering SwiftUI // Copyright (c) KxCoding <[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. // import SwiftUI struct GestureList: View { var body: some View { List { Section { SupportNavigationLink("Tap") { Gesture_TapGesture() } SupportNavigationLink("Long Press") { Gesture_LongPressGesture() } SupportNavigationLink("Drag") { Gesture_DragGesture() } SupportNavigationLink("Magnification") { Gesture_MagnificationGesture() } SupportNavigationLink("Rotation") { Gesture_RotationGesture() } } Section { SupportNavigationLink("Sequence Gesture") { Gesture_SequenceGesture() } SupportNavigationLink("Simultaneous Gesture") { Gesture_SimultaneousGesture() } SupportNavigationLink("Exclusive Gesture") { Gesture_ExclusiveGesture() } } } .listStyle(GroupedListStyle()) .navigationBarTitle("Gestures") } } struct GestureList_Previews: PreviewProvider { static var previews: some View { GestureList() } }
40.660377
91
0.70116
e6cd803fdc2b31b6824e3838df953efec19d5507
3,917
// // ProfileViewController.swift // Instagram // // Created by Evan on 2/23/16. // Copyright © 2016 EvanTragesser. All rights reserved. // import UIKit import MBProgressHUD import Parse class ProfileViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. profileImageView.clipsToBounds = true profileImageView.layer.cornerRadius = 75 profileImageView.layer.borderColor = UIColor.blackColor().CGColor profileImageView.layer.borderWidth = 2 if let imageFile = PFUser.currentUser()!["profile_picture"] as? PFFile { do { try profileImageView.image = UIImage(data: imageFile.getData()) } catch { //what } } usernameLabel.text = PFUser.currentUser()!.username let pictureTapRecognizer = UITapGestureRecognizer(target: self, action: "didPressPicture:") profileImageView.userInteractionEnabled = true profileImageView.addGestureRecognizer(pictureTapRecognizer) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func didPressPicture(view: AnyObject) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.PhotoLibrary presentViewController(vc, animated: true, completion: nil) } @IBAction func didPressLogout(sender: AnyObject) { PFUser.logOutInBackgroundWithBlock { (error: NSError?) -> Void in print("logging out") NSNotificationCenter.defaultCenter().postNotificationName("userDidLogoutNotification", object: nil) } } func resize(image: UIImage, newSize: CGSize) -> UIImage { let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height)) resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill resizeImageView.image = image UIGraphicsBeginImageContext(resizeImageView.frame.size) resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { MBProgressHUD.showHUDAddedTo(self.view, animated: true) let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage let image = resize(editedImage, newSize: CGSize(width: 500, height: 500)) let imageFile = InstagramPost.getPFFileFromImage(image) let user = PFUser.currentUser() user?.setObject(imageFile!, forKey: "profile_picture") user?.saveInBackgroundWithBlock({ (successful: Bool, error: NSError?) -> Void in if successful { self.profileImageView.backgroundColor = UIColor.whiteColor() self.profileImageView.image = editedImage PFUser.currentUser()!.fetchInBackground() MBProgressHUD.hideHUDForView(self.view, animated: true) } else { MBProgressHUD.hideHUDForView(self.view, animated: true) print("Error: \(error!.localizedDescription)") } }) picker.dismissViewControllerAnimated(true, completion: nil) } }
32.641667
121
0.723002
2195c71b66aefd1f9074c58be7f09062c7f461d0
1,725
//// Copyright 2020 Esri // // 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 ArcGIS import Combine extension AGSPortalUser: PublishableBase { } extension Publishable where Base == AGSPortalUser { var fullName: AnyPublisher<String?, Never> { base.publisher(for: \.fullName).eraseToAnyPublisher() } var email: AnyPublisher<String?, Never> { base.publisher(for: \.email).eraseToAnyPublisher() } var thumbnail: AnyPublisher<AGSLoadableImage?, Never> { base.publisher(for: \.thumbnail).eraseToAnyPublisher() } func fetchContent() -> Future<(items: [AGSPortalItem], folders: [AGSPortalFolder]), Error> { Future<(items: [AGSPortalItem], folders: [AGSPortalFolder]), Error> { promise in self.base.fetchContent { (items, folders, error) in if let error = error { promise(.failure(error)) } else if let items = items, let folders = folders { promise(.success((items: items, folders: folders))) } else { promise(.failure(AppError.unknown)) } } } } }
34.5
96
0.626667
f711fbf240afcf33df1c9f55461f15984ddbf768
1,808
// // NSView+BorderBounder.swift // TreeView // // Created by Kelvin Wong on 2019/12/14. // Copyright © 2019 nonamecat. All rights reserved. // import Cocoa extension NSView { func boundToSuperView(superview:NSView) { self.translatesAutoresizingMaskIntoConstraints = false let attributes: [NSLayoutConstraint.Attribute] = [.top, .bottom, .right, .left] NSLayoutConstraint.activate(attributes.map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1, constant: 0) }) } func boundXToSuperView() { if let superview = self.superview { self.translatesAutoresizingMaskIntoConstraints = false let attributes: [NSLayoutConstraint.Attribute] = [.right, .left] NSLayoutConstraint.activate(attributes.map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1, constant: 0) }) } } func boundXToSuperView(superview:NSView) { self.translatesAutoresizingMaskIntoConstraints = false let attributes: [NSLayoutConstraint.Attribute] = [.right, .left] NSLayoutConstraint.activate(attributes.map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1, constant: 0) }) } func setHeight(_ height:CGFloat){ let f = self.frame self.frame = CGRect(x: f.origin.x, y: f.origin.y, width: f.width, height: height); } func setWidth(_ width:CGFloat){ let f = self.frame self.frame = CGRect(x: f.origin.x, y: f.origin.y, width: width, height: f.height); } }
33.481481
142
0.63219
21630e14632c473a2ae214ef01791afb01ab4522
559
// // Variable.swift // SimpleNN // // Created by taisuke fujita on 2017/08/17. // Copyright © 2017年 taisuke fujita. All rights reserved. // import Foundation public protocol Variable: Codable { func filled(value: Double) -> Self func transpose() -> Self func scale(_ scalar: Double) -> Self func add(_ x: Double) -> Self func add(_ x: Self) -> Self func difference(_ x: Double) -> Self func difference(_ x: Self) -> Self // Hadamard product func multiply(_ x: Self) -> Self }
18.633333
58
0.595707
eb982e0e994addc99b366c7376ba338b3707a93f
445
// // CalloutVerificationDetails.swift // Verification // // Created by Aleksander Wojcik on 03/08/2020. // Copyright © 2020 Sinch. All rights reserved. // import Foundation /// Class containing detailed information for the actual verification API request for callout verification. struct CalloutVerificationDetails: Codable { let code: String enum CodingKeys: String, CodingKey { case code = "code" } }
21.190476
107
0.701124
0e8b70bd773f67a13d54e2a0db63f42cb18e7a81
1,409
// // chatwootUITests.swift // chatwootUITests // // Created by shamzz on 21/09/21. // import XCTest class chatwootUITests: XCTestCase { override func setUpWithError() throws { // 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 // 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 tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
32.767442
182
0.655075
cce1af039d8307c607322824c3f30c8488537f4f
591
// // SAIToolboxItem.swift // SAC // // Created by SAGESSE on 9/15/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit @objc open class SAIToolboxItem: NSObject { open var name: String open var identifier: String open var image: UIImage? open var highlightedImage: UIImage? public init(_ identifier: String, _ name: String, _ image: UIImage?, _ highlightedImage: UIImage? = nil) { self.identifier = identifier self.name = name self.image = image self.highlightedImage = highlightedImage } }
22.730769
110
0.651438
87c7fe09ec6e2db478910fa346d4fdc134dec683
3,630
// // AutoLayour+Distribution.swift // AutoLayout // // Created by Stanislav Novacek on 02/10/2019. // import Foundation import UIKit public extension AutoLayout where Source: UIView { // MARK: Vertically /// Distributes given `UIView`s vertically inside receiver. /// - Parameter items: views to distribute func distributeVertically(_ items: [UIView]) -> [AutoLayout<UIView>] { return distributeVertically(items, spacing: 0) } /// Distributes given `UIView`s vertically inside receiver. /// - Parameter items: views to distribute /// - Parameter spacing: spacing between views func distributeVertically(_ items: [UIView], spacing: CGFloat) -> [AutoLayout<UIView>] { return distributeVertically(items, spacing: spacing, margin: .zero) } /// Distributes given `UIView`s vertically inside receiver. /// - Parameter items: views to distribute /// - Parameter spacing: spacing between views /// - Parameter margin: margin along the edges func distributeVertically(_ items: [UIView], spacing: CGFloat, margin: UIEdgeInsets) -> [AutoLayout<UIView>] { guard let source = source, items.isEmpty == false else { return [] } var layouts: [AutoLayout<UIView>] = [] for (index, item) in items.enumerated() { // Leading, trailing item.autoLayout(in: source).leading(margin.left).trailing(margin.right).activate() // Top if index == 0 { item.autoLayout.top(margin.top).activate() } else { item.autoLayout.below(spacing, to: items[index - 1]).activate() } // Bottom if index == items.count - 1 { item.autoLayout.bottom(margin.bottom).activate() } layouts.append(item.autoLayout) } return layouts } // MARK: Horizontally /// Distributes given `UIView`s horizontally inside receiver. /// - Parameter items: views to distribute func distributeHorizontally(_ items: [UIView]) -> [AutoLayout<UIView>] { return distributeHorizontally(items, spacing: 0) } /// Distributes given `UIView`s horizontally inside receiver. /// - Parameter items: views to distribute /// - Parameter spacing: spacing between views func distributeHorizontally(_ items: [UIView], spacing: CGFloat) -> [AutoLayout<UIView>] { return distributeHorizontally(items, spacing: spacing, margin: .zero) } /// Distributes given `UIView`s horizontally inside receiver. /// - Parameter items: views to distribute /// - Parameter spacing: spacing between views /// - Parameter margin: margin along the edges func distributeHorizontally(_ items: [UIView], spacing: CGFloat, margin: UIEdgeInsets) -> [AutoLayout<UIView>] { guard let source = source, items.isEmpty == false else { return [] } var layouts: [AutoLayout<UIView>] = [] for (index, item) in items.enumerated() { // Top, bottom item.autoLayout(in: source).top(margin.top).bottom(margin.bottom).activate() // Leading if index == 0 { item.autoLayout.leading(margin.left).activate() } else { item.autoLayout.after(spacing, to: items[index - 1]).activate() } // Trailing if index == items.count - 1 { item.autoLayout.trailing(margin.right).activate() } layouts.append(item.autoLayout) } return layouts } }
38.210526
116
0.611846
e25e86655e5a0ad8ac94b068bcb92d710cf47734
265
// // ErrorHandlingManager.swift // KynhongIOSBase // // Created by Kynhong on 2/2/21. // import Foundation class ErrorHandlingManager { public static let shared = ErrorHandlingManager() public func handle(_ error: CustomError) { } }
15.588235
53
0.664151
d64191ad6a9dce245e56b267d438fe12066f1915
484
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit class ___VARIABLE_sceneName___Worker { func doSomeWork() { } // // func doSomeOtherWork() { // // } }
20.166667
73
0.681818
01ba86be7405030c203c83e99215d5a4185d36ee
1,419
/* * Copyright (c) 2019 Elastos Foundation * * 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 Foundation public class PropertiesExecutable: FileExecutable { private let TYPE = "fileProperties" public init(name: String, path: String) { super.init(TYPE, name, path) } public init(name: String, path: String, output: Bool) { super.init(TYPE, name, path, output) } }
39.416667
80
0.749824
ccb1c0602f235d9278fe2952e038c70ee20e424b
1,890
// // ListViewController.swift // CompositionalLayout // // Created by Daniel Klein on 24.05.20. // Copyright © 2020 Daniel Klein. All rights reserved. // import UIKit class ListCell: UICollectionViewCell { @IBOutlet weak var textLabel: UILabel! } class ListViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() //collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) collectionView.collectionViewLayout = createLayout() } private func createLayout() -> UICollectionViewLayout { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0)) let item = NSCollectionLayoutItem(layoutSize: itemSize) item.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 2, trailing: 0) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(44)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section) return layout } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 100 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "List Cell", for: indexPath) as! ListCell cell.textLabel.text = String(indexPath.row) return cell } }
37.8
130
0.711111
696ee8c7e2657689b21ba91faa32bec978389c5d
4,392
// // MapsNavViewController.swift // BRIDGE-Driver // // Created by Bharat Kathi on 8/1/18. // Copyright © 2018 Bharat Kathi. All rights reserved. // import UIKit import MapKit import Firebase import UserNotifications class MapsNavViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() var userLocation:CLLocationCoordinate2D? var ref:DatabaseReference? var databaseHandle:DatabaseHandle? var geoFenceRegion:CLCircularRegion = CLCircularRegion(center: CLLocationCoordinate2DMake(0.0, 0.0), radius: 10, identifier: "Rider") override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = true let requestRef = ref?.child("acceptedRides").child(myRiderID) let values = ["riderName": myRiderName, "riderLat": 0.0, "riderLong": 0.0, "driverID": userID, "driverName": name, "driverLat": 0.0, "driverLong": 0.0, "driverArrived": false, "pickedUp": false, "dest": destination] as [String : Any] requestRef?.updateChildValues(values) let riderCoordinates = CLLocationCoordinate2D(latitude: myRiderLat, longitude: myRiderLong) let regionDistance:CLLocationDistance = 1000 let regionSpan = MKCoordinateRegionMakeWithDistance(riderCoordinates, regionDistance, regionDistance) self.geoFenceRegion = CLCircularRegion(center: riderCoordinates, radius: 10, identifier: "Rider") locationManager.startMonitoring(for: geoFenceRegion) let options = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)] let placemark = MKPlacemark(coordinate: riderCoordinates) let mapItem = MKMapItem(placemark: placemark) mapItem.name = "Rider Location" mapItem.openInMaps(launchOptions: options) } @IBAction func route(_ sender: Any) { let riderCoordinates = CLLocationCoordinate2D(latitude: myRiderLat, longitude: myRiderLong) let regionDistance:CLLocationDistance = 1000 let regionSpan = MKCoordinateRegionMakeWithDistance(riderCoordinates, regionDistance, regionDistance) let options = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)] let placemark = MKPlacemark(coordinate: riderCoordinates) let mapItem = MKMapItem(placemark: placemark) mapItem.name = "Rider Location" mapItem.openInMaps(launchOptions: options) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] let driverCoordinates = location.coordinate let requestRef = ref?.child("acceptedRides").child(myRiderID) let values = ["driverID": userID, "driverLat": driverCoordinates.latitude, "driverLong": driverCoordinates.longitude] as [String : Any] requestRef?.updateChildValues(values) } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { locationManager.stopMonitoring(for: geoFenceRegion) //Driver arrive at Rider Location let requestRef = ref?.child("acceptedRides").child(myRiderID) let values = ["driverArrived": true] as [String : Any] requestRef?.updateChildValues(values) locationManager.stopUpdatingLocation() //Driver Notification let content = UNMutableNotificationContent() content.title = "Arrived at Rider" content.body = "You have arrived at your rider's location!" content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) let request = UNNotificationRequest(identifier: "Arrival", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) self.performSegue(withIdentifier: "arrivedAtRider", sender: self) } }
46.231579
241
0.711066
4bbe1df4f89402c7d7c63b183415a939aed4b576
1,547
// RUN: %target-swift-frontend -typecheck -debug-generic-signatures -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s protocol P { associatedtype T } protocol Base { associatedtype A associatedtype B associatedtype C associatedtype D : P where B == D.T } // CHECK-LABEL: connected_components_concrete.(file).Derived1@ // CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int> protocol Derived1 : Base where A == B, A == C, A == Int {} // CHECK-LABEL: connected_components_concrete.(file).Derived2@ // CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int> protocol Derived2 : Base where A == D.T, A == C, B == Int {} // CHECK-LABEL: connected_components_concrete.(file).Derived3@ // CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int> protocol Derived3 : Base where A == B, B == C, A == Int {} // CHECK-LABEL: connected_components_concrete.(file).Derived4@ // CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int> protocol Derived4 : Base where A == Int, B == Int, C == Int {} // CHECK-LABEL: connected_components_concrete.(file).Derived5@ // CHECK-LABEL: Requirement signature: <Self where Self : Base, Self.[Base]A == Int, Self.[Base]B == Int, Self.[Base]C == Int> protocol Derived5 : Base where A == Int, D.T == Int, C == Int {}
46.878788
135
0.681319
f91398a9dcfaeb09e9ac4464f6ebbae88a6e2883
969
// // EnumArrays.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation <<<<<<< HEAD internal struct EnumArrays: Codable { ======= internal struct EnumArrays: Codable { >>>>>>> ooof internal enum JustSymbol: String, Codable, CaseIterable { case greaterThanOrEqualTo = ">=" case dollar = "$" } internal enum ArrayEnum: String, Codable, CaseIterable { case fish = "fish" case crab = "crab" } internal var justSymbol: JustSymbol? internal var arrayEnum: [ArrayEnum]? internal init(justSymbol: JustSymbol?, arrayEnum: [ArrayEnum]?) { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } <<<<<<< HEAD internal enum CodingKeys: String, CodingKey, CaseIterable { ======= internal enum CodingKeys: String, CodingKey, CaseIterable { >>>>>>> ooof case justSymbol = "just_symbol" case arrayEnum = "array_enum" } }
22.022727
69
0.633643
760c2818b08274cf69d562acd57dfbcede0b1761
4,554
import XCTest @testable import MapboxMaps final class GestureDecelerationCameraAnimatorTests: XCTestCase { var location: CGPoint! var velocity: CGPoint! var decelerationFactor: CGFloat! var locationChangeHandler: MockLocationChangeHandler! var dateProvider: MockDateProvider! // swiftlint:disable:next weak_delegate var delegate: MockCameraAnimatorDelegate! var animator: GestureDecelerationCameraAnimator! var completion: Stub<Void, Void>! override func setUp() { super.setUp() location = .zero velocity = CGPoint(x: 1000, y: -1000) decelerationFactor = 0.7 locationChangeHandler = MockLocationChangeHandler() dateProvider = MockDateProvider() delegate = MockCameraAnimatorDelegate() animator = GestureDecelerationCameraAnimator( location: location, velocity: velocity, decelerationFactor: decelerationFactor, locationChangeHandler: locationChangeHandler.call(withFromLocation:toLocation:), dateProvider: dateProvider, delegate: delegate) completion = Stub() animator.completion = completion.call } override func tearDown() { completion = nil animator = nil delegate = nil dateProvider = nil locationChangeHandler = nil decelerationFactor = nil velocity = nil location = nil super.tearDown() } func testStateIsInitiallyInactive() { XCTAssertEqual(animator.state, .inactive) } func testStartAnimation() { animator.startAnimation() XCTAssertEqual(animator.state, .active) XCTAssertEqual(delegate.cameraAnimatorDidStartRunningStub.invocations.count, 1) XCTAssertTrue(delegate.cameraAnimatorDidStartRunningStub.parameters.first === animator) } func testStopAnimation() { animator.startAnimation() animator.stopAnimation() XCTAssertEqual(animator.state, .inactive) XCTAssertEqual(completion.invocations.count, 1) XCTAssertEqual(delegate.cameraAnimatorDidStopRunningStub.invocations.count, 1) XCTAssertTrue(delegate.cameraAnimatorDidStopRunningStub.parameters.first === animator) } func testUpdate() { animator.startAnimation() // Simulate advancing by 10 ms dateProvider.nowStub.defaultReturnValue += 0.01 animator.update() // Expected value is duration * velocity; XCTAssertEqual(locationChangeHandler.parameters, [.init(fromLocation: location, toLocation: CGPoint(x: 10, y: -10))]) // The previous update() should also have reduced the velocity // by multiplying it by the decelerationFactor once for each elapsed // millisecond. In this simulateion, 10 ms have elapsed. let expectedVelocityAdjustmentFactor = pow(decelerationFactor, 10) locationChangeHandler.reset() // Make sure the animation didn't end yet XCTAssertEqual(animator.state, .active) XCTAssertEqual(completion.invocations.count, 0) // This time, advance by 20 ms to keep it distinct // from the first update() call. dateProvider.nowStub.defaultReturnValue += 0.02 animator.update() // The expected value this time is the previous location + the reduced // velocity (velocity * expectedVelocityAdjustmentFactor) times the elapsed duration XCTAssertEqual(locationChangeHandler.invocations.count, 1) XCTAssertEqual(locationChangeHandler.invocations[0].parameters.fromLocation, location) XCTAssertEqual(locationChangeHandler.invocations[0].parameters.toLocation.x, (velocity.x * expectedVelocityAdjustmentFactor) * 0.02, accuracy: 0.0000000001) XCTAssertEqual(locationChangeHandler.invocations[0].parameters.toLocation.y, (velocity.y * expectedVelocityAdjustmentFactor) * 0.02, accuracy: 0.0000000001) locationChangeHandler.reset() // After the previous update() call, the velocity should have also been reduced // to be sufficiently low (< 20 in both x and y) to end the animation. XCTAssertEqual(animator.state, .inactive) XCTAssertEqual(completion.invocations.count, 1) XCTAssertEqual(delegate.cameraAnimatorDidStopRunningStub.invocations.count, 1) XCTAssertTrue(delegate.cameraAnimatorDidStopRunningStub.parameters.first === animator) } }
40.660714
125
0.687088
0990ce08a52c54997b14ebfa4858afc0efe15632
787
// // DataGroup9.swift // MIDNFCReader // // Created by ivan.zagorulko on 07.09.2021. // import Foundation @available(iOS 13, macOS 10.15, *) public class DataGroup9: DataGroup { public private(set) var nrInstances : Int = 0 public private(set) var groupData : [UInt8] = [] required init( _ data : [UInt8] ) throws { try super.init(data) datagroupType = .DG9 } override func parse(_ data: [UInt8]) throws { var tag = try getNextTag() // Tag should be 0x02 if tag != 0x02 { throw NFCPassportReaderError.InvalidResponse } nrInstances = try Int(getNextValue()[0]) tag = try getNextTag() let value = try getNextValue() groupData = value } }
23.147059
56
0.579416
918865a399105bac184d3898589e8c9f81b0c154
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import CoreData (n protocol a { let i: Any typealias d: d
22.7
87
0.762115
7aea7636cf1de11421aef788bf532f9beeb5b69e
2,232
/* * Copyright (c) 2016 Razeware LLC * * 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. */ //https://www.raywenderlich.com/126365/ios-frameworks-tutorial import Foundation import AVFoundation public class Fanfare { public var ringSound = "coin07" public var allRingSound = "winning" public static let sharedInstance = Fanfare() fileprivate var player: AVAudioPlayer? public func playSoundsWhenReady() { NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: RingCompletedNotification), object: nil, queue: OperationQueue.main) { _ in self.playSound(self.ringSound) } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AllRingsCompletedNotification), object: nil, queue: OperationQueue.main) { _ in self.playSound(self.allRingSound) } } fileprivate func playSound(_ sound: String) { if let url = Bundle(for: type(of: self)).url(forResource: sound, withExtension: "mp3") { player = try? AVAudioPlayer(contentsOf: url) if player != nil { player!.numberOfLoops = 0 player!.prepareToPlay() player!.play() } } } deinit { NotificationCenter.default.removeObserver(self) } }
37.830508
161
0.745072
28553ba3c0ad581c779269f7d6d9bac32eb95002
373
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "CUtility", products: [ .library(name: "CUtility", targets: ["CUtility"]), ], targets: [ .target(name: "CUtility"), .target(name: "CTestCode"), .testTarget( name: "CUtilityTests", dependencies: [ "CUtility", "CTestCode", ]), ] )
17.761905
54
0.573727
f50d7e35f33770cd34657488e951d3a9d0aa8cf7
5,774
// // ObjectiveLuhn.swift // Example Project // // Created by Max Kramer on 29/03/2016. // Copyright © 2016 Max Kramer. All rights reserved. // import Foundation open class SwiftLuhn { public enum CardType: Int { case amex = 0 case visa case mastercard case rupay case dinersClub case jcb case maestro case discover case mir } public enum CardError: Error { case unsupported case invalid } fileprivate class func regularExpression(for cardType: CardType) -> String { switch cardType { case .amex: return "^3[47][0-9]{5,}$" case .dinersClub: return "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$" case .discover: return "^6(?:011|5[0-9]{2})[0-9]{3,}$" case .jcb: return "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$" case .mastercard: return "^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$" case .visa: return "^4[0-9]{6,}$" case .maestro: return "^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$" case .rupay: return "^508[5-9][0-9][0-9]{6,}|60698[5-9]{6,}|60699[0-9]{6,}|607[0-8][0-9][0-9]{6,}|6079[0-7][0-9]{6,}|60798[0-4]{6,}|608[0-4][0-9][0-9]{6,}|608500{6,}|6521[5-9][0-9]{6,}|652[2-9][0-9][0-9]{6,}|6530[0-9][0-9]{6,}|6531[0-4][0-9]{6,}$" case .mir: return "^220[0-9]{13}$" } } fileprivate class func suggestionRegularExpression(for cardType: CardType) -> String { switch cardType { case .amex: return "^3[47][0-9]+$" case .dinersClub: return "^3(?:0[0-5]|[68][0-9])[0-9]+$" case .discover: return "^6(?:011|5[0-9]{2})[0-9]+$" case .jcb: return "^(?:2131|1800|35[0-9]{3})[0-9]+$" case .mastercard: return "^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$" case .visa: return "^4[0-9]+$" case .maestro: return "^(5018|5020|5038|6304|6759|6761|6763)[0-9]+$" case .rupay: return "^508[5-9][0-9][0-9]{6,}|60698[5-9]{6,}|60699[0-9]{6,}|607[0-8][0-9][0-9]{6,}|6079[0-7][0-9]{6,}|60798[0-4]{6,}|608[0-4][0-9][0-9]{6,}|608500{6,}|6521[5-9][0-9]{6,}|652[2-9][0-9][0-9]{6,}|6530[0-9][0-9]{6,}|6531[0-4][0-9]{6,}+$" case .mir: return "^220[0-9]+$" } } class func performLuhnAlgorithm(with cardNumber: String) throws { let formattedCardNumber = cardNumber.formattedCardNumber() guard formattedCardNumber.count >= 9 else { throw CardError.invalid } let originalCheckDigit = formattedCardNumber.last! let characters = formattedCardNumber.dropLast().reversed() var digitSum = 0 for (idx, character) in characters.enumerated() { let value = Int(String(character)) ?? 0 if idx % 2 == 0 { var product = value * 2 if product > 9 { product = product - 9 } digitSum = digitSum + product } else { digitSum = digitSum + value } } digitSum = digitSum * 9 let computedCheckDigit = digitSum % 10 let originalCheckDigitInt = Int(String(originalCheckDigit)) let valid = originalCheckDigitInt == computedCheckDigit if valid == false { throw CardError.invalid } } class func cardType(for cardNumber: String, suggest: Bool = false) throws -> CardType { var foundCardType: CardType? for i in CardType.amex.rawValue...CardType.mir.rawValue { let cardType = CardType(rawValue: i)! let regex = suggest ? suggestionRegularExpression(for: cardType) : regularExpression(for: cardType) let predicate = NSPredicate(format: "SELF MATCHES %@", regex) if predicate.evaluate(with: cardNumber) == true { foundCardType = cardType break } } if foundCardType == nil { throw CardError.invalid } return foundCardType! } } public extension SwiftLuhn.CardType { func stringValue() -> String { switch self { case .amex: return "American Express" case .visa: return "Visa" case .mastercard: return "Mastercard" case .discover: return "Discover" case .dinersClub: return "Diner's Club" case .jcb: return "JCB" case .maestro: return "Maestro" case .rupay: return "Rupay" case .mir: return "Mir" } } init?(string: String) { switch string.lowercased() { case "american express": self.init(rawValue: 0) case "visa": self.init(rawValue: 1) case "mastercard": self.init(rawValue: 2) case "discover": self.init(rawValue: 4) case "diner's club": self.init(rawValue: 5) case "jcb": self.init(rawValue: 6) case "maestro": self.init(rawValue: 7) case "rupay": self.init(rawValue: 3) case "mir": self.init(rawValue: 8) default: return nil } } }
30.712766
247
0.485106
691bba252ae221b4ccbe2c07e2833bb5bfbdb3fa
280
// // HealthRecordConclusionStep.swift // SMARTMarkers // // Created by Raheel Sayeed on 2/24/21. // Copyright © 2021 Boston Children's Hospital. All rights reserved. // import Foundation import ResearchKit open class HealthRecordConclusionStep: ORKCompletionStep { }
17.5
69
0.746429
01d75ae9248f51e98165c94f8704e086dc46df63
256
import XCTest class Notes70UITests: XCTestCase { override func setUp() { super.setUp() XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testExample() { } }
19.692308
36
0.535156
26f427de707f9725e9d2e1ed5acf60d73a7bc1d9
382
// // ZPosition.swift // KJLunarLander // // Created by Kristopher Johnson on 12/25/16. // Copyright © 2016 Kristopher Johnson. All rights reserved. // import CoreGraphics /// Z-position constants for all sprites. enum ZPosition { static let thrust: CGFloat = 10 static let lander: CGFloat = 20 static let surface: CGFloat = 50 static let hud: CGFloat = 100 }
21.222222
61
0.693717
18f9e38157154c735246cc1d9267ee44b3aa3ca9
16,210
// // ImageSlideshow.swift // ImageSlideshow // // Created by Petr Zvoníček on 30.07.15. // import UIKit /** Used to represent position of the Page Control - hidden: Page Control is hidden - insideScrollView: Page Control is inside image slideshow - underScrollView: Page Control is under image slideshow - custom: Custom vertical padding, relative to "insideScrollView" position */ public enum PageControlPosition { case hidden case insideScrollView case underScrollView case custom(padding: CGFloat) var bottomPadding: CGFloat { switch self { case .hidden, .insideScrollView: return 0.0 case .underScrollView: return 30.0 case .custom(let padding): return padding } } } /// Used to represent image preload strategy /// /// - fixed: preload only fixed number of images before and after the current image /// - all: preload all images in the slideshow public enum ImagePreload { case fixed(offset: Int) case all } /// Main view containing the Image Slideshow @objcMembers open class ImageSlideshow: UIView { /// Scroll View to wrap the slideshow open let scrollView = UIScrollView() /// Page Control shown in the slideshow open let pageControl = UIPageControl() /// Activity indicator shown when loading image open var activityIndicator: ActivityIndicatorFactory? { didSet { self.reloadScrollView() } } // MARK: - State properties /// Page control position open var pageControlPosition = PageControlPosition.insideScrollView { didSet { setNeedsLayout() } } /// Current page open fileprivate(set) var currentPage: Int = 0 { didSet { if oldValue != currentPage { currentPageChanged?(currentPage) } } } /// Called on each currentPage change open var currentPageChanged: ((_ page: Int) -> ())? /// Called on scrollViewWillBeginDragging open var willBeginDragging: (() -> ())? /// Called on scrollViewDidEndDecelerating open var didEndDecelerating: (() -> ())? /// Currenlty displayed slideshow item open var currentSlideshowItem: ImageSlideshowItem? { if slideshowItems.count > scrollViewPage { return slideshowItems[scrollViewPage] } else { return nil } } /// Current scroll view page. This may differ from `currentPage` as circular slider has two more dummy pages at indexes 0 and n-1 to provide fluent scrolling between first and last item. open fileprivate(set) var scrollViewPage: Int = 0 /// Input Sources loaded to slideshow open fileprivate(set) var images = [InputSource]() /// Image Slideshow Items loaded to slideshow open fileprivate(set) var slideshowItems = [ImageSlideshowItem]() // MARK: - Preferences /// Enables/disables infinite scrolling between images open var circular = true { didSet { if self.images.count > 0 { self.setImageInputs(self.images) } } } /// Enables/disables user interactions open var draggingEnabled = true { didSet { self.scrollView.isUserInteractionEnabled = draggingEnabled } } /// Enables/disables zoom open var zoomEnabled = false { didSet { self.reloadScrollView() } } /// Maximum zoom scale open var maximumScale: CGFloat = 2.0 { didSet { self.reloadScrollView() } } /// Image change interval, zero stops the auto-scrolling open var slideshowInterval = 0.0 { didSet { self.slideshowTimer?.invalidate() self.slideshowTimer = nil setTimerIfNeeded() } } /// Image preload configuration, can be sed to .fixed to enable lazy load or .all open var preload = ImagePreload.all /// Content mode of each image in the slideshow open var contentScaleMode: UIViewContentMode = UIViewContentMode.scaleAspectFit { didSet { for view in slideshowItems { view.imageView.contentMode = contentScaleMode } } } fileprivate var slideshowTimer: Timer? fileprivate var scrollViewImages = [InputSource]() /// Transitioning delegate to manage the transition to full screen controller open fileprivate(set) var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate? var primaryVisiblePage: Int { return scrollView.frame.size.width > 0 ? Int(scrollView.contentOffset.x + scrollView.frame.size.width / 2) / Int(scrollView.frame.size.width) : 0 } // MARK: - Life cycle override public init(frame: CGRect) { super.init(frame: frame) initialize() } convenience init() { self.init(frame: CGRect.zero) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } fileprivate func initialize() { autoresizesSubviews = true clipsToBounds = true // scroll view configuration scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - 50.0) scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.bounces = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.autoresizingMask = self.autoresizingMask if #available(iOS 11.0, *) { scrollView.contentInsetAdjustmentBehavior = .never } addSubview(scrollView) addSubview(pageControl) pageControl.addTarget(self, action: #selector(pageControlValueChanged), for: .valueChanged) setTimerIfNeeded() layoutScrollView() } open override func removeFromSuperview() { super.removeFromSuperview() self.pauseTimer() } open override func layoutSubviews() { super.layoutSubviews() // fixes the case when automaticallyAdjustsScrollViewInsets on parenting view controller is set to true scrollView.contentInset = UIEdgeInsets.zero layoutPageControl() layoutScrollView() } open func layoutPageControl() { if case .hidden = self.pageControlPosition { pageControl.isHidden = true } else { pageControl.isHidden = self.images.count < 2 } var pageControlBottomInset: CGFloat = 12.0 if #available(iOS 11.0, *) { pageControlBottomInset += self.safeAreaInsets.bottom } pageControl.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: 10) pageControl.center = CGPoint(x: frame.size.width / 2, y: frame.size.height - pageControlBottomInset) } /// updates frame of the scroll view and its inner items func layoutScrollView() { let scrollViewBottomPadding: CGFloat = pageControlPosition.bottomPadding scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - scrollViewBottomPadding) scrollView.contentSize = CGSize(width: scrollView.frame.size.width * CGFloat(scrollViewImages.count), height: scrollView.frame.size.height) for (index, view) in self.slideshowItems.enumerated() { if !view.zoomInInitially { view.zoomOut() } view.frame = CGRect(x: scrollView.frame.size.width * CGFloat(index), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height) } setCurrentPage(currentPage, animated: false) } /// reloads scroll view with latest slideshow items func reloadScrollView() { // remove previous slideshow items for view in self.slideshowItems { view.removeFromSuperview() } self.slideshowItems = [] var i = 0 for image in scrollViewImages { let item = ImageSlideshowItem(image: image, zoomEnabled: self.zoomEnabled, activityIndicator: self.activityIndicator?.create(), maximumScale: maximumScale) item.imageView.contentMode = self.contentScaleMode slideshowItems.append(item) scrollView.addSubview(item) i += 1 } if circular && (scrollViewImages.count > 1) { scrollViewPage = 1 scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: false) } else { scrollViewPage = 0 } loadImages(for: scrollViewPage) } private func loadImages(for scrollViewPage: Int) { let totalCount = slideshowItems.count for i in 0..<totalCount { let item = slideshowItems[i] switch self.preload { case .all: item.loadImage() case .fixed(let offset): // if circular scrolling is enabled and image is on the edge, a helper ("dummy") image on the other side needs to be loaded too let circularEdgeLoad = circular && ((scrollViewPage == 0 && i == totalCount-3) || (scrollViewPage == 0 && i == totalCount-2) || (scrollViewPage == totalCount-2 && i == 1)) // load image if page is in range of loadOffset, else release image let shouldLoad = abs(scrollViewPage-i) <= offset || abs(scrollViewPage-i) > totalCount-offset || circularEdgeLoad shouldLoad ? item.loadImage() : item.releaseImage() } } } // MARK: - Image setting /** Set image inputs into the image slideshow - parameter inputs: Array of InputSource instances. */ open func setImageInputs(_ inputs: [InputSource]) { self.images = inputs self.pageControl.numberOfPages = inputs.count // in circular mode we add dummy first and last image to enable smooth scrolling if circular && images.count > 1 { var scImages = [InputSource]() if let last = images.last { scImages.append(last) } scImages += images if let first = images.first { scImages.append(first) } self.scrollViewImages = scImages } else { self.scrollViewImages = images } reloadScrollView() layoutScrollView() layoutPageControl() setTimerIfNeeded() } // MARK: paging methods /** Change the current page - parameter newPage: new page - parameter animated: true if animate the change */ open func setCurrentPage(_ newPage: Int, animated: Bool) { var pageOffset = newPage if circular && (scrollViewImages.count > 1) { pageOffset += 1 } self.setScrollViewPage(pageOffset, animated: animated) } /** Change the scroll view page. This may differ from `setCurrentPage` as circular slider has two more dummy pages at indexes 0 and n-1 to provide fluent scrolling between first and last item. - parameter newScrollViewPage: new scroll view page - parameter animated: true if animate the change */ open func setScrollViewPage(_ newScrollViewPage: Int, animated: Bool) { if scrollViewPage < scrollViewImages.count { self.scrollView.scrollRectToVisible(CGRect(x: scrollView.frame.size.width * CGFloat(newScrollViewPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: animated) self.setCurrentPageForScrollViewPage(newScrollViewPage) } } fileprivate func setTimerIfNeeded() { if slideshowInterval > 0 && scrollViewImages.count > 1 && slideshowTimer == nil { slideshowTimer = Timer.scheduledTimer(timeInterval: slideshowInterval, target: self, selector: #selector(ImageSlideshow.slideshowTick(_:)), userInfo: nil, repeats: true) } } @objc func slideshowTick(_ timer: Timer) { let page = scrollView.frame.size.width > 0 ? Int(scrollView.contentOffset.x / scrollView.frame.size.width) : 0 var nextPage = page + 1 if !circular && page == scrollViewImages.count - 1 { nextPage = 0 } self.setScrollViewPage(nextPage, animated: true) } fileprivate func setCurrentPageForScrollViewPage(_ page: Int) { if scrollViewPage != page { // current page has changed, zoom out this image if slideshowItems.count > scrollViewPage { slideshowItems[scrollViewPage].zoomOut() } } if page != scrollViewPage { loadImages(for: page) } scrollViewPage = page currentPage = currentPageForScrollViewPage(page) } fileprivate func currentPageForScrollViewPage(_ page: Int) -> Int { if circular { if page == 0 { // first page contains the last image return Int(images.count) - 1 } else if page == scrollViewImages.count - 1 { // last page contains the first image return 0 } else { return page - 1 } } else { return page } } /// Stops slideshow timer open func pauseTimer() { slideshowTimer?.invalidate() slideshowTimer = nil } /// Restarts slideshow timer open func unpauseTimer() { setTimerIfNeeded() } @available(*, deprecated, message: "use pauseTimer instead") open func pauseTimerIfNeeded() { self.pauseTimer() } @available(*, deprecated, message: "use unpauseTimer instead") open func unpauseTimerIfNeeded() { self.unpauseTimer() } /** Open full screen slideshow - parameter controller: Controller to present the full screen controller from - returns: FullScreenSlideshowViewController instance */ @discardableResult open func presentFullScreenController(from controller: UIViewController) -> FullScreenSlideshowViewController { let fullscreen = FullScreenSlideshowViewController() fullscreen.pageSelected = {[weak self] (page: Int) in self?.setCurrentPage(page, animated: false) } fullscreen.initialPage = self.currentPage fullscreen.inputs = self.images slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: self, slideshowController: fullscreen) fullscreen.transitioningDelegate = slideshowTransitioningDelegate controller.present(fullscreen, animated: true, completion: nil) return fullscreen } @objc private func pageControlValueChanged() { self.setCurrentPage(pageControl.currentPage, animated: true) } } extension ImageSlideshow: UIScrollViewDelegate { open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if slideshowTimer?.isValid != nil { slideshowTimer?.invalidate() slideshowTimer = nil } setTimerIfNeeded() willBeginDragging?() } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { setCurrentPageForScrollViewPage(primaryVisiblePage) didEndDecelerating?() } open func scrollViewDidScroll(_ scrollView: UIScrollView) { if circular { let regularContentOffset = scrollView.frame.size.width * CGFloat(images.count) if scrollView.contentOffset.x >= scrollView.frame.size.width * CGFloat(images.count + 1) { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x - regularContentOffset, y: 0) } else if scrollView.contentOffset.x < 0 { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x + regularContentOffset, y: 0) } } pageControl.currentPage = currentPageForScrollViewPage(primaryVisiblePage) } }
33.217213
216
0.634978
ccc509fb146f194425ace9c19c88f3e5b59afeb0
879
// // TitleCell.swift // 01_ChangeNext_Swift // // Created by Fengtf on 2016/11/23. // Copyright © 2016年 ftf. All rights reserved. // import UIKit class TitleCell: UICollectionViewCell { var titleStr:String?{ didSet{ titleL.text = titleStr titleL.sizeToFit() } } let titleL = UILabel() override init(frame: CGRect) { super.init(frame: frame) self .addSubview(titleL) titleL.textColor = UIColor.black titleL.font = UIFont.systemFont(ofSize: 12) titleL.numberOfLines = 2 titleL.textAlignment = .left titleL.sizeToFit() } override func layoutSubviews() { super.layoutSubviews() titleL.frame = self.bounds } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
18.702128
59
0.600683
38efaa3e8cf527104110326c31df305dc1128c8f
2,469
func getStandardTypeSubst(typeName: String) -> UnicodeScalar? { if (typeName == "AutoreleasingUnsafeMutablePointer") { return "A" } if (typeName == "Array") { return "a" } if (typeName == "Bool") { return "b" } if (typeName == "UnicodeScalar") { return "c" } if (typeName == "Dictionary") { return "D" } if (typeName == "Double") { return "d" } if (typeName == "Float") { return "f" } if (typeName == "Set") { return "h" } if (typeName == "DefaultIndices") { return "I" } if (typeName == "Int") { return "i" } if (typeName == "Character") { return "J" } if (typeName == "ClosedRange") { return "N" } if (typeName == "Range") { return "n" } if (typeName == "ObjectIdentifier") { return "O" } if (typeName == "UnsafePointer") { return "P" } if (typeName == "UnsafeMutablePointer") { return "p" } if (typeName == "UnsafeBufferPointer") { return "R" } if (typeName == "UnsafeMutableBufferPointer") { return "r" } if (typeName == "String") { return "S" } if (typeName == "Substring") { return "s" } if (typeName == "UInt") { return "u" } if (typeName == "UnsafeRawPointer") { return "V" } if (typeName == "UnsafeMutableRawPointer") { return "v" } if (typeName == "UnsafeRawBufferPointer") { return "W" } if (typeName == "UnsafeMutableRawBufferPointer") { return "w" } if (typeName == "Optional") { return "q" } if (typeName == "BinaryFloatingPoint") { return "B" } if (typeName == "Encodable") { return "E" } if (typeName == "Decodable") { return "e" } if (typeName == "FloatingPoint") { return "F" } if (typeName == "RandomNumberGenerator") { return "G" } if (typeName == "Hashable") { return "H" } if (typeName == "Numeric") { return "j" } if (typeName == "BidirectionalCollection") { return "K" } if (typeName == "RandomAccessCollection") { return "k" } if (typeName == "Comparable") { return "L" } if (typeName == "Collection") { return "l" } if (typeName == "MutableCollection") { return "M" } if (typeName == "RangeReplaceableCollection") { return "m" } if (typeName == "Equatable") { return "Q" } if (typeName == "Sequence") { return "T" } if (typeName == "IteratorProtocol") { return "t" } if (typeName == "UnsignedInteger") { return "U" } if (typeName == "RangeExpression") { return "X" } if (typeName == "Strideable") { return "x" } if (typeName == "RawRepresentable") { return "Y" } if (typeName == "StringProtocol") { return "y" } if (typeName == "SignedInteger") { return "Z" } if (typeName == "BinaryInteger") { return "z" } fatalError("Unknown typename") }
46.584906
67
0.633455
396c06d48ccf25e5f793fff0d195846dade3b393
1,606
// // LotusError.swift // Lotus // // Created by Jack on 14/08/2017. // Copyright © 2017 XWJACK. All rights reserved. // import Foundation /// Error for Lotus. public enum LotusError: Error { /// Send request error. public enum RequestError: Error { /// Invalid base url. case invalidBaseURL(urlString: String) } /// Receive response error. public enum ResponseError: Error { } /// Reading and saving cache error. public enum CacheError: Error { /// Reading cache from file error. case readingCacheError(cachePath: String) /// Saving cache to file error. case savingCacheError(data: Data, cachePath: String) } /// Log error. public enum LogError: Error { /// Recording log error. case recordError } /// System throw error. case systemError(Error) /// Custom error. case customError(Error) } // MARK: - LotusError.RequestError LocalizedError extension LotusError.RequestError: LocalizedError { public var errorDescription: String? { switch self { case .invalidBaseURL(let urlString): return "Base URL is not valid: " + urlString } } } // MARK: - LotusError.CacheError LocalizedError extension LotusError.CacheError: LocalizedError { public var errorDescription: String? { switch self { case .readingCacheError(let cachePath): return "Can't reading cache from: \(cachePath)" case .savingCacheError(let data, let cachePath): return "Can't saving cache to: \(cachePath) with data: \(data)" } } }
27.220339
120
0.646949
e2f7ff3476c0f82334539a5844b3c695d37532bd
5,576
// // AppDelegate.swift // Twitter // // Created by Kaushik on 9/26/17. // Copyright © 2017 Dev. All rights reserved. // import UIKit import BDBOAuth1Manager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let storyBoard = UIStoryboard(name: "Main", bundle: nil) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // window = UIWindow.init(frame: UIScreen.main.bounds) // NotificationCenter.default.addObserver(self, selector: #selector(userDidLogout), name: // NSNotification.Name(rawValue: userDidLogoutNotification), object: nil) // TwitterTheme.dark.apply() NotificationCenter.default.addObserver(self, selector: #selector(noLoggedInUser), name: NSNotification.Name(rawValue: accountManagerNoLoggedInUsersNotification), object: nil) let vc = storyBoard.instantiateViewController(withIdentifier: "tweetsViewController") let navController = UINavigationController(rootViewController: vc) navController.navigationBar.barTintColor = UIColor(red:0.00, green:0.67, blue:0.93, alpha:1.0) navController.navigationBar.tintColor = UIColor.white // navController.navigationItem.backBarButtonItem?.tintColor = UIColor.white // navController.navigationItem.leftBarButtonItem?.tintColor = UIColor.white // navController.navigationItem.rightBarButtonItem?.tintColor = UIColor.white // navController.navigationBar.isTranslucent = false // navController.navigationBar.setBackgroundImage(UIImage(), for: .default) // navController.navigationBar.shadowImage = UIImage() navController.navigationBar.isTranslucent = true // let tabBarController = UITabBarController.init() // tabBarController.viewControllers = [navController] let hamburgerViewController = self.window?.rootViewController as! HamburgerViewController let storyboard = UIStoryboard(name: "Main", bundle: nil) let menuViewController = storyboard.instantiateViewController(withIdentifier: "menuViewController") as! MenuViewController hamburgerViewController.menuViewController = menuViewController menuViewController.hamburgerViewController = hamburgerViewController hamburgerViewController.contentViewController = navController // window?.rootViewController = hamburgerViewController // window?.becomeKey() //print("\(self.window?.rootViewController)") // Override point for customization after application launch. if User.currentUser == nil { print("current user detected \(User.currentUser?.name)") showLoginViewController() }else{ AccountsManager.sharedInstance.addUserToAccounts(user: User.currentUser!) } return true } func userDidLogout() { // let vc = storyBoard.instantiateInitialViewController() // window?.rootViewController = vc showLoginViewController() } func noLoggedInUser() { showLoginViewController() } func showLoginViewController() -> Void { // let loginViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "loginViewController") as! ViewController // let vc = self.window?.rootViewController // // vc?.present(loginViewController, animated: true, completion: { // // }) } 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:. } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { TwitterClient.sharedInstance.openURL(url: url as NSURL) return true } }
45.704918
285
0.709648
e6056ecde310ab6aa567e96555156e0924a3d5c4
1,982
import SwiftRex import SwiftUI import UIKit import ReactiveSwift import ReactiveCocoa final class AuthViewController: BaseViewController { private let store: AnyStoreType<AuthAction, AuthState> private var viewStore: ViewStore<AuthAction, AuthState> init(store: AnyStoreType<AuthAction, AuthState>? = nil) { let unwrapStore = store ?? ReduxStoreBase( subject: .reactive(initialValue: AuthState()), reducer: AuthReducer, middleware: IdentityMiddleware<AuthAction, AuthAction, AuthState>() ) .eraseToAnyStoreType() self.store = unwrapStore self.viewStore = unwrapStore.asViewStore(initialState: AuthState()) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() viewStore.send(.viewDidLoad) // buttonLogin let buttonLogin = UIButton(type: .system) buttonLogin.setTitle("Login", for: .normal) buttonLogin.translatesAutoresizingMaskIntoConstraints = false view.addSubview(buttonLogin) // contraint NSLayoutConstraint.activate([ buttonLogin.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), buttonLogin.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), ]) //bind view to viewstore disposables += viewStore.action <~ buttonLogin.reactive.controlEvents(.touchUpInside).map{_ in AuthAction.login} } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewStore.send(.viewWillAppear) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewStore.send(.viewWillDisappear) } } struct AuthViewController_Previews: PreviewProvider { static var previews: some View { let vc = AuthViewController() UIViewRepresented(makeUIView: { _ in vc.view }) } }
30.96875
116
0.725025
03e0039136ff475a5074a7238f6409d652a3befa
9,591
// // MessageStreamImplTests.swift // WebimClientLibrary_Tests // // Created by Nikita Lazarev-Zubov on 22.02.18. // Copyright © 2018 Webim. 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 Foundation @testable import WebimClientLibrary import XCTest class MessageStreamImplTests: XCTestCase { // MARK: - Constants private static let userDefaultsKey = "userDefaultsKey" // MARK: - Properties var messageStream: MessageStreamImpl? var webimActions: WebimActions? // MARK: - Methods override func setUp() { super.setUp() let serverURLString = "https://demo.webim.ru" let sessionDestroyer = SessionDestroyer(userDefaultsKey: MessageStreamImplTests.userDefaultsKey) let accessChecker = AccessChecker(thread: Thread.current, sessionDestroyer: sessionDestroyer) let queue = DispatchQueue.main webimActions = WebimActionsImpl(baseURL: serverURLString, actionRequestLoop: ActionRequestLoopForTests(completionHandlerExecutor: ExecIfNotDestroyedHandlerExecutor(sessionDestroyer: sessionDestroyer, queue: queue), internalErrorListener: InternalErrorListenerForTests())) messageStream = MessageStreamImpl(serverURLString: serverURLString, currentChatMessageFactoriesMapper: CurrentChatMessageMapper(withServerURLString: serverURLString), sendingMessageFactory: SendingFactory(withServerURLString: serverURLString), operatorFactory: OperatorFactory(withServerURLString: serverURLString), surveyFactory: SurveyFactory(), accessChecker: accessChecker, webimActions: webimActions!, messageHolder: MessageHolder(accessChecker: accessChecker, remoteHistoryProvider: RemoteHistoryProvider(webimActions: webimActions!, historyMessageMapper: HistoryMessageMapper(withServerURLString: serverURLString), historyMetaInformationStorage: MemoryHistoryMetaInformationStorage()), historyStorage: MemoryHistoryStorage(), reachedEndOfRemoteHistory: true), messageComposingHandler: MessageComposingHandler(webimActions: webimActions!, queue: queue), locationSettingsHolder: LocationSettingsHolder(userDefaultsKey: "key")) } // MARK: - Tests func testSetVisitSessionState() { messageStream!.set(visitSessionState: .chat) XCTAssertEqual(messageStream!.getVisitSessionState(), VisitSessionState.chat) } func testSetUnreadByOperatorTimestamp() { let date = Date() messageStream!.set(unreadByOperatorTimestamp: date) XCTAssertEqual(messageStream!.getUnreadByOperatorTimestamp(), date) } func testSetUnreadByVisitorTimestamp() { let date = Date() messageStream!.set(unreadByVisitorTimestamp: date) XCTAssertEqual(messageStream!.getUnreadByVisitorTimestamp(), date) } func testOnReceivingDepartmentList() { let departmentItemDictionary = try! JSONSerialization.jsonObject(with: DEPARTMENT_ITEM_JSON_STRING.data(using: .utf8)!, options: []) as! [String : Any?] let departmentItem = DepartmentItem(jsonDictionary: departmentItemDictionary)! messageStream!.onReceiving(departmentItemList: [departmentItem]) XCTAssertEqual(messageStream!.getDepartmentList()![0].getKey(), "mobile_test_1") XCTAssertEqual(messageStream!.getDepartmentList()![0].getName(), "Mobile Test 1") XCTAssertEqual(messageStream!.getDepartmentList()![0].getDepartmentOnlineStatus(), DepartmentOnlineStatus.offline) XCTAssertEqual(messageStream!.getDepartmentList()![0].getOrder(), 100) XCTAssertEqual(messageStream!.getDepartmentList()![0].getLocalizedNames()!, ["ru" : "Mobile Test 1"]) XCTAssertEqual(messageStream!.getDepartmentList()![0].getLogoURL()!, URL(string: "https://demo.webim.ru/webim/images/department_logo/wmtest2_1.png")!) } func testGetChatState() { XCTAssertEqual(messageStream!.getChatState(), ChatState.unknown) } func testGetLocationSettings() { XCTAssertFalse(messageStream!.getLocationSettings().areHintsEnabled()) // Initial value must be false. } func testGetCurrentOperator() { XCTAssertNil(messageStream!.getCurrentOperator()) // Initially operator does not exist. } func testSetVisitSessionStateListener() { let visitSessionStateListener = VisitSessionStateListenerForTests() messageStream!.set(visitSessionStateListener: visitSessionStateListener) messageStream!.set(visitSessionState: .chat) XCTAssertTrue(visitSessionStateListener.called) XCTAssertEqual(visitSessionStateListener.state!, VisitSessionState.chat) } func testSetOnlineStatusChangeListener() { let onlineStatusChangeListener = OnlineStatusChangeListenerForTests() messageStream!.set(onlineStatusChangeListener: onlineStatusChangeListener) messageStream!.set(onlineStatus: .busyOnline) XCTAssertFalse(onlineStatusChangeListener.called) messageStream!.onOnlineStatusChanged(to: .busyOffline) XCTAssertTrue(onlineStatusChangeListener.called) XCTAssertEqual(onlineStatusChangeListener.status!, OnlineStatus.busyOffline) } func testChangingChatState() { let chatItemDictionary = try! JSONSerialization.jsonObject(with: ChatItemTests.CHAT_ITEM_JSON_STRING.data(using: .utf8)!, options: []) as! [String : Any?] let chatItem = ChatItem(jsonDictionary: chatItemDictionary) messageStream!.changingChatStateOf(chat: chatItem) XCTAssertEqual(messageStream!.getChatState(), ChatState.chatting) XCTAssertNil(messageStream!.getUnreadByOperatorTimestamp()) XCTAssertNil(messageStream!.getUnreadByVisitorTimestamp()) XCTAssertEqual(messageStream!.getCurrentOperator()!.getID(), "33201") } func testGetWebimActions() { XCTAssertTrue(webimActions! === messageStream!.getWebimActions()) } } // MARK: - fileprivate class VisitSessionStateListenerForTests: VisitSessionStateListener { // MARK: - Properties var called = false var state: VisitSessionState? // MARK: - Methods // MARK: VisitSessionStateListener protocol methods func changed(state previousState: VisitSessionState, to newState: VisitSessionState) { called = true state = newState } } // MARK: - fileprivate class OnlineStatusChangeListenerForTests: OnlineStatusChangeListener { // MARK: - Properties var called = false var status: OnlineStatus? // MARK: - Methods // MARK: OnlineStatusChangeListener protocol methods func changed(onlineStatus previousOnlineStatus: OnlineStatus, to newOnlineStatus: OnlineStatus) { called = true status = newOnlineStatus } }
46.333333
197
0.606506
ff4c5184dfa3d9c0b07f44d6472dce2d8c8219b0
67,124
// // MainWindowController.swift // Managed Software Center // // Created by Greg Neagle on 6/29/18. // Copyright © 2018-2020 The Munki Project. All rights reserved. // import Cocoa import WebKit class MainWindowController: NSWindowController, NSWindowDelegate, WKNavigationDelegate, WKScriptMessageHandler { var _alertedUserToOutstandingUpdates = false var _update_in_progress = false var managedsoftwareupdate_task = "" var cached_self_service = SelfService() var alert_controller = MSCAlertController() var htmlDir = "" var wkContentController = WKUserContentController() // let items = [["title": "Software", "icon": "AllItemsTemplate"], // ["title": "Categories", "icon": "toolbarCategoriesTemplate"], // ["title": "My Items", "icon": "MyStuffTemplate"], // ["title": "Updates", "icon": "updatesTemplate"]] let items = [["title": "Updates", "icon": "updatesTemplate"]] // status properties var _status_title = "" var stop_requested = false var user_warned_about_extra_updates = false var should_filter_apple_updates = false var forceFrontmost = false var backdropWindows: [NSWindow] = [] // Cocoa UI binding properties @IBOutlet weak var navigateBackButton: NSButton! @IBOutlet weak var progressSpinner: NSProgressIndicator! @IBOutlet weak var searchField: NSSearchField! @IBOutlet weak var sidebar: NSOutlineView! @IBOutlet weak var navigateBackMenuItem: NSMenuItem! @IBOutlet weak var findMenuItem: NSMenuItem! @IBOutlet weak var softwareMenuItem: NSMenuItem! @IBOutlet weak var categoriesMenuItem: NSMenuItem! @IBOutlet weak var myItemsMenuItem: NSMenuItem! @IBOutlet weak var updatesMenuItem: NSMenuItem! @IBOutlet weak var webViewPlaceholder: NSView! var webView: WKWebView! override func windowDidLoad() { super.windowDidLoad() } @objc private func onItemClicked() { if 0 ... items.count ~= sidebar.clickedRow { clearSearchField() switch sidebar.clickedRow { // case 0: // loadAllSoftwarePage(self) // case 1: // loadCategoriesPage(self) // case 2: // loadMyItemsPage(self) case 0: loadUpdatesPage(self) default: loadUpdatesPage(self) } } } func appShouldTerminate() -> NSApplication.TerminateReply { // called by app delegate // when it receives applicationShouldTerminate: if getUpdateCount() == 0 { // no pending updates return .terminateNow } if !should_filter_apple_updates && appleUpdatesRequireRestartOnMojaveAndUp() { if shouldAggressivelyNotifyAboutAppleUpdates(days: 2) { if !currentPageIsUpdatesPage() { loadUpdatesPage(self) } alert_controller.alertToAppleUpdates() should_filter_apple_updates = true return .terminateCancel } } if currentPageIsUpdatesPage() { if (!thereAreUpdatesToBeForcedSoon() && !shouldAggressivelyNotifyAboutMunkiUpdates()) { // We're already at the updates view, so user is aware of the // pending updates, so OK to just terminate // (unless there are some updates to be forced soon) return .terminateNow } if _alertedUserToOutstandingUpdates { if (thereAreUpdatesToBeForcedSoon() || shouldAggressivelyNotifyAboutMunkiUpdates()) { // user keeps avoiding; let's try at next logout or restart writeInstallAtStartupFlagFile(skipAppleUpdates: false) } return .terminateNow } } // we have pending updates and we have not yet warned the user // about them alert_controller.alertToPendingUpdates(self) return .terminateCancel } func currentPageIsUpdatesPage() -> Bool { // return true if current tab selected is Updates // return sidebar.selectedRow == 3 return sidebar.selectedRow == 0 } func newTranslucentWindow(screen: NSScreen) -> NSWindow { // makes a translucent masking window we use to prevent interaction with // other apps var windowRect = screen.frame windowRect.origin = NSMakePoint(0.0, 0.0) let thisWindow = NSWindow( contentRect: windowRect, styleMask: .borderless, backing: .buffered, defer: false, screen: screen ) thisWindow.level = .normal thisWindow.backgroundColor = NSColor.black.withAlphaComponent(0.50) thisWindow.isOpaque = false thisWindow.ignoresMouseEvents = false thisWindow.alphaValue = 0.0 thisWindow.orderFrontRegardless() thisWindow.animator().alphaValue = 1.0 return thisWindow } func displayBackdropWindows() { for screen in NSScreen.screens { let newWindow = newTranslucentWindow(screen: screen) // add to our backdropWindows array so a reference stays around backdropWindows.append(newWindow) } } func makeUsUnobnoxious() { // reverse all the obnoxious changes msc_log("msc", "end_obnoxious_mode") let options = NSApplication.PresentationOptions([]) NSApp.presentationOptions = options for window in self.backdropWindows { window.orderOut(self) } if let window = self.window { window.collectionBehavior = .fullScreenPrimary window.styleMask = [.titled, .fullSizeContentView, .closable, .miniaturizable, .resizable] window.level = .normal } self.forceFrontmost = false // enable/disable controls as needed enableOrDisableSoftwareViewControls() } func makeUsObnoxious() { // makes this app and window impossible(?)/difficult to ignore msc_log("msc", "start_obnoxious_mode") // make it very difficult to switch away from this app let options = NSApplication.PresentationOptions([.hideDock, .disableHideApplication, .disableProcessSwitching, .disableForceQuit]) NSApp.presentationOptions = options // alter some window properties to make the window harder to ignore if let window = self.window { window.center() window.collectionBehavior = .fullScreenNone window.styleMask = [.titled, .fullSizeContentView, .closable] window.level = .floating } // disable all of the other controls searchField.isEnabled = false // findMenuItem.isEnabled = false // softwareMenuItem.isEnabled = false // categoriesMenuItem.isEnabled = false // myItemsMenuItem.isEnabled = false self.sidebar.isEnabled = false // set flag to cause us to always be brought to front self.forceFrontmost = true // create translucent windows to mask all other apps displayBackdropWindows() } func weShouldBeObnoxious() -> Bool { // returns a Bool to let us know if we should enter obnoxiousMode if thereAreUpdatesToBeForcedSoon() { return true } if shouldAggressivelyNotifyAboutMunkiUpdates() { return true } if shouldAggressivelyNotifyAboutAppleUpdates() { if userIsAdmin() || !userMustBeAdminToInstallAppleUpdates() { // only be obnoxious if the user can actually _do_ something return true } } return false } func loadInitialView() { // Called by app delegate from applicationDidFinishLaunching: enableOrDisableSoftwareViewControls() let optional_items = getOptionalInstallItems() if optional_items.isEmpty || getUpdateCount() > 0 || !getProblemItems().isEmpty { loadUpdatesPage(self) } else { loadAllSoftwarePage(self) } displayUpdateCount() cached_self_service = SelfService() } func toolBarItemIsHighlighted(_ item: NSToolbarItem) -> Bool { if let button = item.view as? NSButton { return (button.state == .on) } return false } func setHighlightFor(item: NSToolbarItem, doHighlight: Bool) { if let button = item.view as? NSButton { button.state = (doHighlight ? .on : .off) } } func highlightToolbarButtons(_ nameToHighlight: String) { for (index, item) in items.enumerated() { if nameToHighlight == item["title"] { sidebar.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) } } } func clearSearchField() { self.searchField.stringValue = "" } func enableOrDisableSoftwareViewControls() { // Disable or enable the controls that let us view optional items let enabled_state = optionalInstallsExist() //enableOrDisableToolbarItems(enabled_state) searchField.isEnabled = enabled_state findMenuItem.isEnabled = enabled_state softwareMenuItem.isEnabled = enabled_state categoriesMenuItem.isEnabled = enabled_state myItemsMenuItem.isEnabled = enabled_state } func munkiStatusSessionEnded(withStatus sessionResult: Int, errorMessage: String) { // Called by StatusController when a Munki session ends msc_debug_log("MunkiStatus session ended: \(sessionResult)") if !errorMessage.isEmpty { msc_debug_log("MunkiStatus session error message: \(errorMessage)") } msc_debug_log("MunkiStatus session type: \(managedsoftwareupdate_task)") let tasktype = managedsoftwareupdate_task managedsoftwareupdate_task = "" _update_in_progress = false // The managedsoftwareupdate run will have changed state preferences // in ManagedInstalls.plist. Load the new values. reloadPrefs() if tasktype == "" { // probably a background session, but not one initiated by the user here resetAndReload() return } let lastCheckResult = pref("LastCheckResult") as? Int ?? 0 if sessionResult != 0 || lastCheckResult < 0 { var alertMessageText = NSLocalizedString( "Update check failed", comment: "Update Check Failed title") var detailText = "" if tasktype == "installwithnologout" { msc_log("MSC", "cant_update", msg: "Install session failed") alertMessageText = NSLocalizedString( "Install session failed", comment: "Install Session Failed title") } if sessionResult == -1 { // connection was dropped unexpectedly msc_log("MSC", "cant_update", msg: "unexpected process end") detailText = NSLocalizedString( ("There is a configuration problem with the managed " + "software installer. The process ended unexpectedly. " + "Contact your systems administrator."), comment: "Unexpected Session End message") } else if sessionResult == -2 { // session never started msc_log("MSC", "cant_update", msg: "process did not start") detailText = NSLocalizedString( ("There is a configuration problem with the managed " + "software installer. Could not start the process. " + "Contact your systems administrator."), comment: "Could Not Start Session message") } else if lastCheckResult == -1 { // server not reachable msc_log("MSC", "cant_update", msg: "cannot contact server") detailText = NSLocalizedString( ("Managed Software Center cannot contact the update " + "server at this time.\n" + "Try again later. If this situation continues, " + "contact your systems administrator."), comment: "Cannot Contact Server detail") } else if lastCheckResult == -2 { // preflight failed msc_log("MSC", "cant_update", msg: "failed preflight") detailText = NSLocalizedString( ("Managed Software Center cannot check for updates now.\n" + "Try again later. If this situation continues, " + "contact your systems administrator."), comment: "Failed Preflight Check detail") } if !errorMessage.isEmpty { detailText = "\(detailText)\n\n\(errorMessage)" } // show the alert sheet if let thisWindow = self.window { thisWindow.makeKeyAndOrderFront(self) if let attachedSheet = thisWindow.attachedSheet { // there's an existing sheet open; close it first thisWindow.endSheet(attachedSheet) } } let alert = NSAlert() alert.messageText = alertMessageText alert.informativeText = detailText alert.addButton(withTitle: NSLocalizedString("OK", comment:"OK button title")) alert.beginSheetModal(for: self.window!, completionHandler: { (modalResponse) -> Void in self.resetAndReload() }) return } if tasktype == "checktheninstall" { clearMunkiItemsCache() // possibly check again if choices have changed updateNow() return } // all done checking and/or installing: display results resetAndReload() if updateCheckNeeded() { // more stuff pending? Let's do it... updateNow() } } func resetAndReload() { // Clear cached values, reload from disk. Display any changes. // Typically called soon after a managedsoftwareupdate session completes msc_debug_log("resetAndReload method called") // need to clear out cached data clearMunkiItemsCache() // recache SelfService choices cached_self_service = SelfService() // copy any new custom client resources get_custom_resources() // pending updates may have changed _alertedUserToOutstandingUpdates = false // enable/disable controls as needed enableOrDisableSoftwareViewControls() // what page are we currently viewing? let page_url = webView.url let filename = page_url?.lastPathComponent ?? "" let name = (filename as NSString).deletingPathExtension let key = name.components(separatedBy: "-")[0] switch key { case "detail", "updatedetail": // item detail page; just rebuild and reload it load_page(filename) case "category", "filter", "developer": // optional item list page updateListPage() case "categories": // categories page updateCategoriesPage() case "myitems": // my items page updateMyItemsPage() case "updates": // updates page; just rebuild and reload it load_page("updates.html") if !shouldAggressivelyNotifyAboutMunkiUpdates() { _alertedUserToOutstandingUpdates = true } default: // should never get here msc_debug_log("Unexpected value for page name: \(filename)") } // update count might have changed displayUpdateCount() } // Begin NSWindowDelegate methods func windowShouldClose(_ sender: NSWindow) -> Bool { // NSWindowDelegate method called when user closes a window // for us, closing the main window should be the same as quitting NSApp.terminate(self) return false } func windowDidBecomeMain(_ notification: Notification) { // Our window was activated, make sure controls enabled as needed sidebar.action = #selector(onItemClicked) } func windowDidResignMain(_ notification: Notification) { // Our window was deactivated, make sure controls enabled as needed } // End NSWindowDelegate methods func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { // react to messages set to us by JavaScript print("Got message from JavaScript: \(message.name)") if message.name == "installButtonClicked" { installButtonClicked() } if message.name == "myItemsButtonClicked" { if let item_name = message.body as? String { myItemsActionButtonClicked(item_name) } } if message.name == "actionButtonClicked" { if let item_name = message.body as? String { actionButtonClicked(item_name) } } if message.name == "changeSelectedCategory" { if let category_name = message.body as? String { changeSelectedCategory(category_name) } } if message.name == "updateOptionalInstallButtonClicked" { if let item_name = message.body as? String { updateOptionalInstallButtonClicked(item_name) } } if message.name == "updateOptionalInstallButtonFinishAction" { if let item_name = message.body as? String { updateOptionalInstallButtonFinishAction(item_name) } } if message.name == "openExternalLink" { if let link = message.body as? String { openExternalLink(link) } } } func addJSmessageHandlers() { // define messages JavaScript can send us wkContentController.add(self, name: "openExternalLink") wkContentController.add(self, name: "installButtonClicked") wkContentController.add(self, name: "myItemsButtonClicked") wkContentController.add(self, name: "actionButtonClicked") wkContentController.add(self, name: "changeSelectedCategory") wkContentController.add(self, name: "updateOptionalInstallButtonClicked") wkContentController.add(self, name: "updateOptionalInstallButtonFinishAction") } func insertWebView() { // replace our webview placeholder with the real one if let superview = webViewPlaceholder?.superview { // define webview configuration let webConfiguration = WKWebViewConfiguration() addJSmessageHandlers() webConfiguration.userContentController = wkContentController webConfiguration.preferences.javaScriptEnabled = true webConfiguration.preferences.javaEnabled = false if UserDefaults.standard.bool(forKey: "developerExtrasEnabled") { webConfiguration.preferences.setValue(true, forKey: "developerExtrasEnabled") } // init our webview let replacementWebView = MSCWebView(frame: webViewPlaceholder.frame, configuration: webConfiguration) replacementWebView.autoresizingMask = webViewPlaceholder.autoresizingMask //replacementWebView.translatesAutoresizingMaskIntoConstraints = false // we'll add them later, by hand replacementWebView.allowsBackForwardNavigationGestures = false if #available(OSX 10.12, *) { replacementWebView.setValue(false, forKey: "drawsBackground") } // replace the placeholder in the window view with the real webview superview.replaceSubview(webViewPlaceholder, with: replacementWebView) webView = replacementWebView } } override func awakeFromNib() { // Stuff we need to initialize when we start super.awakeFromNib() insertWebView() webView.navigationDelegate = self setNoPageCache() alert_controller = MSCAlertController() alert_controller.window = self.window htmlDir = html_dir() registerForNotifications() } func registerForNotifications() { // register for notification messages let nc = DistributedNotificationCenter.default() // register for notification if user switches to/from Dark Mode nc.addObserver(self, selector: #selector(self.interfaceThemeChanged(_:)), name: NSNotification.Name( rawValue: "AppleInterfaceThemeChangedNotification"), object: nil, suspensionBehavior: .deliverImmediately) // register for notification if available updates change nc.addObserver(self, selector: #selector(self.updateAvailableUpdates(_:)), name: NSNotification.Name( rawValue: "com.googlecode.munki.managedsoftwareupdate.updateschanged"), object: nil, suspensionBehavior: .deliverImmediately) //register for notification to display a logout warning // from the logouthelper nc.addObserver(self, selector: #selector(self.forcedLogoutWarning(_:)), name: NSNotification.Name( rawValue: "com.googlecode.munki.ManagedSoftwareUpdate.logoutwarn"), object: nil, suspensionBehavior: .deliverImmediately) } @objc func interfaceThemeChanged(_ notification: Notification) { // Called when user switches to/from Dark Mode let interface_theme = interfaceTheme() // call JavaScript in the webview to update the appearance CSS webView.evaluateJavaScript("changeAppearanceModeTo('\(interface_theme)')") } @objc func updateAvailableUpdates(_ notification: Notification) { // If a Munki session is not in progress (that we know of) and // we get a updateschanged notification, resetAndReload msc_debug_log("Managed Software Center got update notification") if !_update_in_progress { resetAndReload() } } @objc func forcedLogoutWarning(_ notification: Notification) { // Received a logout warning from the logouthelper for an // upcoming forced install msc_debug_log("Managed Software Center got forced logout warning") // got a notification of an upcoming forced install // switch to updates view, then display alert loadUpdatesPage(self) alert_controller.forcedLogoutWarning(notification) } @objc func checkForUpdates(suppress_apple_update_check: Bool = false) { // start an update check session if _update_in_progress { return } do { try startUpdateCheck(suppress_apple_update_check) } catch { munkiStatusSessionEnded(withStatus: -2, errorMessage: "\(error)") return } _update_in_progress = true should_filter_apple_updates = false displayUpdateCount() managedsoftwareupdate_task = "manualcheck" if let status_controller = (NSApp.delegate as? AppDelegate)?.statusController { status_controller.startMunkiStatusSession() } markRequestedItemsAsProcessing() } @IBAction func reloadPage(_ sender: Any) { // User selected Reload page menu item. Reload the page and kick off an updatecheck msc_log("user", "reload_page_menu_item_selected") checkForUpdates() URLCache.shared.removeAllCachedResponses() webView.reload(sender) } func kickOffInstallSession() { // start an update install/removal session // check for need to logout, restart, firmware warnings // warn about blocking applications, etc... // then start an update session if updatesRequireRestart() || updatesRequireLogout() { if !currentPageIsUpdatesPage() { // switch to updates view loadUpdatesPage(self) } else { // we're already displaying the available updates _alertedUserToOutstandingUpdates = true } // warn about need to logout or restart alert_controller.confirmUpdatesAndInstall() } else { if alert_controller.alertedToBlockingAppsRunning() { loadUpdatesPage(self) return } if alert_controller.alertedToRunningOnBatteryAndCancelled() { loadUpdatesPage(self) return } managedsoftwareupdate_task = "" msc_log("user", "install_without_logout") _update_in_progress = true displayUpdateCount() if let status_controller = (NSApp.delegate as? AppDelegate)?.statusController { status_controller._status_message = NSLocalizedString( "Updating...", comment: "Updating message") } do { try justUpdate() } catch { msc_debug_log("Error starting install session: \(error)") munkiStatusSessionEnded(withStatus: -2, errorMessage: "\(error)") } managedsoftwareupdate_task = "installwithnologout" if let status_controller = (NSApp.delegate as? AppDelegate)?.statusController { status_controller.startMunkiStatusSession() } markPendingItemsAsInstalling() } } func markPendingItemsAsInstalling() { // While an install/removal session is happening, mark optional items // that are being installed/removed with the appropriate status msc_debug_log("marking pendingItems as installing") let install_info = getInstallInfo() let managed_installs = install_info["managed_installs"] as? [PlistDict] ?? [PlistDict]() let removals = install_info["removals"] as? [PlistDict] ?? [PlistDict]() let items_to_be_installed_names = managed_installs.filter( {$0["name"] != nil}).map({$0["name"] as! String}) let items_to_be_removed_names = removals.filter( {$0["name"] != nil}).map({$0["name"] as! String}) for name in items_to_be_installed_names { // remove names for user selections since we are installing user_install_selections.remove(name) } for name in items_to_be_removed_names { // remove names for user selections since we are removing user_removal_selections.remove(name) } for item in getOptionalInstallItems() { var new_status = "" if let name = item["name"] as? String { if items_to_be_installed_names.contains(name) { msc_debug_log("Setting status for \(name) to \"installing\"") new_status = "installing" } else if items_to_be_removed_names.contains(name) { msc_debug_log("Setting status for \(name) to \"removing\"") new_status = "removing" } } if !new_status.isEmpty { item["status"] = new_status updateDOMforOptionalItem(item) } } } func markRequestedItemsAsProcessing() { // When an update check session is happening, mark optional items // that have been requested as processing msc_debug_log("marking requested items as processing") for item in getOptionalInstallItems() { var new_status = "" let name = item["name"] as? String ?? "" if item["status"] as? String == "install-requested" { msc_debug_log("Setting status for \(name) to \"downloading\"") new_status = "downloading" } else if item["status"] as? String == "removal-requested" { msc_debug_log("Setting status for \(name) to \"preparing-removal\"") new_status = "preparing-removal" } if !new_status.isEmpty { item["status"] = new_status updateDOMforOptionalItem(item) } } } func updateNow() { /* If user has added to/removed from the list of things to be updated, run a check session. If there are no more changes, proceed to an update installation session if items to be installed/removed are exclusively those selected by the user in this session */ if stop_requested { // reset the flag stop_requested = false resetAndReload() return } if updateCheckNeeded() { // any item status changes that require an update check? msc_debug_log("updateCheck needed") msc_log("user", "check_then_install_without_logout") // since we are just checking for changed self-service items // we can suppress the Apple update check _update_in_progress = true displayUpdateCount() do { try startUpdateCheck(true) } catch { msc_debug_log("Error starting check-then-install session: \(error)") munkiStatusSessionEnded(withStatus: -2, errorMessage: "\(error)") return } managedsoftwareupdate_task = "checktheninstall" if let status_controller = (NSApp.delegate as? AppDelegate)?.statusController { status_controller.startMunkiStatusSession() } markRequestedItemsAsProcessing() } else if !_alertedUserToOutstandingUpdates && updatesContainNonUserSelectedItems() { // current list of updates contains some not explicitly chosen by // the user msc_debug_log("updateCheck not needed, items require user approval") _update_in_progress = false displayUpdateCount() loadUpdatesPage(self) alert_controller.alertToExtraUpdates() } else { msc_debug_log("updateCheck not needed") _alertedUserToOutstandingUpdates = false _status_title = NSLocalizedString( "Update in progress.", comment: "Update In Progress primary text") + ".." kickOffInstallSession() makeUsUnobnoxious() } } func getUpdateCount() -> Int { // Get the count of effective updates if _update_in_progress { return 0 } return getEffectiveUpdateList(should_filter_apple_updates).count } func displayUpdateCount() { // Display the update count as a badge in the window toolbar // and as an icon badge in the Dock let updateCount = getUpdateCount() var cellView:MSCTableCellView? // if let view = self.sidebar.rowView(atRow: 3, makeIfNecessary: false) { // cellView = view.view(atColumn: 0) as? MSCTableCellView // } if let view = self.sidebar.rowView(atRow: 0, makeIfNecessary: false) { cellView = view.view(atColumn: 0) as? MSCTableCellView } if updateCount > 0 { NSApp.dockTile.badgeLabel = String(updateCount) cellView?.badge.title = String(updateCount) cellView?.badge.isHidden = false } else { NSApp.dockTile.badgeLabel = nil cellView?.badge.isHidden = true } } func updateMyItemsPage() { // Update the "My Items" page with current data. // Modifies the DOM to avoid ugly browser refresh let myitems_rows = buildMyItemsRows() setInnerHTML(myitems_rows, elementID: "my_items_rows") } func updateCategoriesPage() { // Update the Categories page with current data. // Modifies the DOM to avoid ugly browser refresh let items_html = buildCategoryItemsHTML() setInnerHTML(items_html, elementID: "optional_installs_items") } func updateListPage() { // Update the optional items list page with current data. // Modifies the DOM to avoid ugly browser refresh let page_url = webView.url let filename = page_url?.lastPathComponent ?? "" let name = ((filename as NSString).deletingPathExtension) as String let components = name.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false) let key = String(components[0]) let value = String(components.count > 1 ? components[1] : "") var category = "" var our_filter = "" var developer = "" if key == "category" { if value != "all" { category = value } } else if key == "filter" { our_filter = value } else if key == "developer" { developer = value } else { msc_debug_log("updateListPage unexpected error: current page filename is \(filename)") return } msc_debug_log("updating software list page with " + "category: '\(category)', developer: '\(developer)', " + "filter: '\(our_filter)'") let items_html = buildListPageItemsHTML( category: category, developer: developer, filter: our_filter) setInnerHTML(items_html, elementID: "optional_installs_items") } func load_page(_ url_fragment: String) { // Tells the WebView to load the appropriate page msc_debug_log("load_page request for \(url_fragment)") let html_file = NSString.path(withComponents: [htmlDir, url_fragment]) let request = URLRequest(url: URL(fileURLWithPath: html_file), cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: TimeInterval(10.0)) webView.load(request) if url_fragment == "updates.html" { // clear all earlier update notifications NSUserNotificationCenter.default.removeAllDeliveredNotifications() // record that the user has been presented pending updates if !_update_in_progress && !shouldAggressivelyNotifyAboutMunkiUpdates() && !thereAreUpdatesToBeForcedSoon() { _alertedUserToOutstandingUpdates = true } } } func handleMunkiURL(_ url: URL) { // Display page associated with munki:// url NSLog("Handling URL: %@", url.absoluteString) guard url.scheme == "munki" else { msc_debug_log("URL \(url) has unsupported scheme") return } guard let host = url.host else { msc_debug_log("URL \(url) has invalid format") return } var filename = unquote(host) // append ".html" if absent if !(filename.hasSuffix(".html")) { filename += ".html" } // if the user has minimized the main window, deminiaturize it if let window = self.window { if window.isMiniaturized { window.deminiaturize(self) } } // try to build and load the page if filename == "notify.html" { //resetAndReload() load_page("updates.html") if !_update_in_progress && getUpdateCount() > 0 { // we're notifying about pending updates. We might need to be obnoxious about it if let window = self.window { // don't let people move the window mostly off-screen so // they can ignore it window.center() } if weShouldBeObnoxious() { NSLog("%@", "Entering obnoxious mode") makeUsObnoxious() } } } else { load_page(filename) } } func setNoPageCache() { /* We disable the back/forward page cache because we generate each page dynamically; we want things that are changed in one page view to be reflected immediately in all page views */ // TO-DO: figure this out for WKWebView /*let identifier = "com.googlecode.munki.ManagedSoftwareCenter" if let prefs = WebPreferences(identifier: identifier) { prefs.usesPageCache = false webView.preferencesIdentifier = identifier }*/ } func clearCache() { var osMinorVers = 9 if #available(OSX 10.10, *) { osMinorVers = ProcessInfo().operatingSystemVersion.minorVersion } if osMinorVers >= 11 { if #available(OSX 10.11, *) { let cacheDataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) let dateFrom = Date.init(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: cacheDataTypes, modifiedSince: dateFrom, completionHandler: {}) } } else { // Fallback on earlier versions URLCache.shared.removeAllCachedResponses() } } // WKNavigationDelegateMethods func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.url { msc_debug_log("Got load request for \(url)") if navigationAction.targetFrame == nil { // new window target // open link in default browser instead of in our app's WebView NSWorkspace.shared.open(url) decisionHandler(.cancel) return } } if let url = navigationAction.request.url, let scheme = url.scheme { msc_debug_log("Got URL scheme: \(scheme)") if scheme == "munki" { handleMunkiURL(url) decisionHandler(.cancel) return } if scheme == "mailto" || scheme == "http" || scheme == "https" { // open link in default mail client since WKWebView doesn't // forward these links natively NSWorkspace.shared.open(url) decisionHandler(.cancel) return } if url.scheme == "file" { // if this is a MSC page, generate it! if url.deletingLastPathComponent().path == htmlDir { let filename = url.lastPathComponent do { try buildPage(filename) } catch { msc_debug_log( "Could not build page for \(filename): \(error)") } } } } decisionHandler(.allow) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { if !(navigationResponse.canShowMIMEType) { if let url = navigationResponse.response.url { // open link in default browser instead of in our app's WebView NSWorkspace.shared.open(url) decisionHandler(.cancel) return } } decisionHandler(.allow) } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { // Animate progress spinner while we load a page and highlight the // proper toolbar button progressSpinner.startAnimation(self) if let main_url = webView.url { let pagename = main_url.lastPathComponent msc_debug_log("Requested pagename is \(pagename)") if (pagename == "category-all.html" || pagename.hasPrefix("detail-") || pagename.hasPrefix("filter-") || pagename.hasPrefix("developer-")) { highlightToolbarButtons("Software") } else if pagename == "categories.html" || pagename.hasPrefix("category-") { highlightToolbarButtons("Categories") } else if pagename == "myitems.html" { highlightToolbarButtons("My Items") } else if pagename == "updates.html" || pagename.hasPrefix("updatedetail-") { highlightToolbarButtons("Updates") } else { // no idea what type of item it is highlightToolbarButtons("") } } } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // react to end of displaying a new page progressSpinner.stopAnimation(self) clearCache() let allowNavigateBack = webView.canGoBack let page_url = webView.url let filename = page_url?.lastPathComponent ?? "" let onMainPage = ( ["category-all.html", "categories.html", "myitems.html", "updates.html"].contains(filename)) navigateBackButton.isHidden = !allowNavigateBack || onMainPage navigateBackMenuItem.isEnabled = (allowNavigateBack && !onMainPage) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { // Stop progress spinner and log error progressSpinner.stopAnimation(self) msc_debug_log("Committed load error: \(error)") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Stop progress spinner and log progressSpinner.stopAnimation(self) msc_debug_log("Provisional load error: \(error)") do { let files = try FileManager.default.contentsOfDirectory(atPath: htmlDir) msc_debug_log("Files in html_dir: \(files)") } catch { // ignore } } // JavaScript integration // handling DOM UI elements func setInnerHTML(_ htmlString: String, elementID: String) { if let rawData = htmlString.data(using: .utf8) { let encodedData = rawData.base64EncodedString() webView.evaluateJavaScript("setInnerHTMLforElementID('\(elementID)', '\(encodedData)')") } } func addToInnerHTML(_ htmlString: String, elementID: String) { if let rawData = htmlString.data(using: .utf8) { let encodedData = rawData.base64EncodedString() webView.evaluateJavaScript("addToInnerHTMLforElementID('\(elementID)', '\(encodedData)')") } } func setInnerText(_ textString: String, elementID: String) { if let rawData = textString.data(using: .utf8) { let encodedData = rawData.base64EncodedString() webView.evaluateJavaScript("setInnerTextforElementID('\(elementID)', '\(encodedData)')") } } func openExternalLink(_ url: String) { // open a link in the default browser msc_debug_log("External link request: \(url)") if let real_url = URL(string: url) { NSWorkspace.shared.open(real_url) } } func installButtonClicked() { // this method is called from JavaScript when the user // clicks the Install button in the Updates view if _update_in_progress { // this is now a stop/cancel button msc_log("user", "cancel_updates") if let status_controller = (NSApp.delegate as? AppDelegate)?.statusController { status_controller.disableStopButton() status_controller._status_stopBtnState = 1 } stop_requested = true // send a notification that stop button was clicked let stop_request_flag_file = "/private/tmp/com.googlecode.munki.managedsoftwareupdate.stop_requested" if !FileManager.default.fileExists(atPath: stop_request_flag_file) { FileManager.default.createFile(atPath: stop_request_flag_file, contents: nil, attributes: nil) } } else if getUpdateCount() == 0 { // no updates, the button must say "Check Again" msc_log("user", "refresh_clicked") checkForUpdates() } else { // button must say "Update" // we're on the Updates page, so users can see all the pending/ // outstanding updates _alertedUserToOutstandingUpdates = true if !should_filter_apple_updates && appleUpdatesRequireRestartOnMojaveAndUp() { // if there are pending Apple updates, alert the user to // install via System Preferences alert_controller.alertToAppleUpdates() should_filter_apple_updates = true } else { updateNow() } } } func updateOptionalInstallButtonClicked(_ item_name: String) { // this method is called from JavaScript when a user clicks // the cancel or add button in the updates list if let item = optionalItem(forName: item_name) { if (item["status"] as? String ?? "" == "update-available" && item["preupgrade_alert"] != nil) { displayPreInstallUninstallAlert(item["preupgrade_alert"] as? PlistDict ?? PlistDict(), action: updateOptionalInstallButtonBeginAction, item: item_name) } else { updateOptionalInstallButtonBeginAction(item_name) } } else { msc_debug_log("Unexpected error: Can't find item for \(item_name)") } } func updateOptionalInstallButtonBeginAction(_ item_name: String) { webView.evaluateJavaScript("fadeOutAndRemove('\(item_name)')") } func myItemsActionButtonClicked(_ item_name: String) { // this method is called from JavaScript when the user clicks // the Install/Remove/Cancel button in the My Items view if let item = optionalItem(forName: item_name) { if (item["status"] as? String ?? "" == "installed" && item["preuninstall_alert"] != nil) { displayPreInstallUninstallAlert(item["preuninstall_alert"] as? PlistDict ?? PlistDict(), action: myItemsActionButtonPerformAction, item: item_name) } else { myItemsActionButtonPerformAction(item_name) } } else { msc_debug_log("Unexpected error: Can't find item for \(item_name)") } } func myItemsActionButtonPerformAction(_ item_name: String) { // perform action needed when user clicks // the Install/Remove/Cancel button in the My Items view guard let item = optionalItem(forName: item_name) else { msc_debug_log( "User clicked MyItems action button for \(item_name)") msc_debug_log("Could not find item for \(item_name)") return } let prior_status = item["status"] as? String ?? "" if !update_status_for_item(item) { // there was a problem, can't continue return } displayUpdateCount() let current_status = item["status"] as? String ?? "" if current_status == "not-installed" { // we removed item from list of things to install // now remove from display webView.evaluateJavaScript("removeElementByID('\(item_name)_myitems_table_row')") } else { setInnerHTML(item["myitem_action_text"] as? String ?? "", elementID: "\(item_name)_action_button_text") setInnerHTML(item["myitem_status_text"] as? String ?? "", elementID: "\(item_name)_status_text") webView.evaluateJavaScript("document.getElementById('\(item_name)_status_text')).className = 'status \(current_status)'") } if ["install-requested", "removal-requested"].contains(current_status) { _alertedUserToOutstandingUpdates = false if !_update_in_progress { updateNow() } } else if ["will-be-installed", "update-will-be-installed", "will-be-removed"].contains(prior_status) { // cancelled a pending install or removal; should run an updatecheck checkForUpdates(suppress_apple_update_check: true) } } func actionButtonClicked(_ item_name: String) { // this method is called from JavaScript when the user clicks // the Install/Remove/Cancel button in the list or detail view if let item = optionalItem(forName: item_name) { var showAlert = true let status = item["status"] as? String ?? "" if status == "not-installed" && item["preinstall_alert"] != nil { displayPreInstallUninstallAlert(item["preinstall_alert"] as? PlistDict ?? PlistDict(), action: actionButtonPerformAction, item: item_name) } else if status == "installed" && item["preuninstall_alert"] != nil { displayPreInstallUninstallAlert(item["preuninstall_alert"] as? PlistDict ?? PlistDict(), action: actionButtonPerformAction, item: item_name) } else if status == "update-available" && item["preupgrade_alert"] != nil { displayPreInstallUninstallAlert(item["preupgrade_alert"] as? PlistDict ?? PlistDict(), action: actionButtonPerformAction, item: item_name) } else { actionButtonPerformAction(item_name) showAlert = false } if showAlert { msc_log("user", "show_alert") } } else { msc_debug_log( "User clicked Install/Remove/Upgrade/Cancel button in the list " + "or detail view") msc_debug_log("Unexpected error: Can't find item for \(item_name)") } } func displayPreInstallUninstallAlert(_ alert: PlistDict, action: @escaping (String)->Void, item: String) { // Display an alert sheet before processing item install/upgrade // or uninstall let defaultAlertTitle = NSLocalizedString( "Attention", comment:"Pre Install Uninstall Upgrade Alert Title") let defaultAlertDetail = NSLocalizedString( "Some conditions apply to this software. " + "Please contact your administrator for more details", comment: "Pre Install Uninstall Upgrade Alert Detail") let defaultOKLabel = NSLocalizedString( "OK", comment: "OK button title") let defaultCancelLabel = NSLocalizedString( "Cancel", comment: "Cancel button title/short action text") let alertTitle = alert["alert_title"] as? String ?? defaultAlertTitle let alertDetail = alert["alert_detail"] as? String ?? defaultAlertDetail let OKLabel = alert["ok_label"] as? String ?? defaultOKLabel let cancelLabel = alert["cancel_label"] as? String ?? defaultCancelLabel // show the alert sheet self.window?.makeKeyAndOrderFront(self) let alert = NSAlert() alert.messageText = alertTitle alert.informativeText = alertDetail alert.addButton(withTitle: cancelLabel) alert.addButton(withTitle: OKLabel) alert.beginSheetModal(for: self.window!, completionHandler: ({ (modalResponse) -> Void in if modalResponse == .alertFirstButtonReturn { // default is to cancel! msc_log("user", "alert_canceled") } else if modalResponse == .alertSecondButtonReturn { msc_log("user", "alert_accepted") // run our completion function action(item) } })) } func actionButtonPerformAction(_ item_name: String) { // Perform the action requested when clicking the action button // in the list or detail view if let item = optionalItem(forName: item_name) { let prior_status = item["status"] as? String ?? "" if !update_status_for_item(item) { // there was a problem, can't continue return } let current_status = item["status"] as? String ?? "" //msc_log("user", "action_button_\(current_status)", item_name) displayUpdateCount() updateDOMforOptionalItem(item) if ["install-requested", "removal-requested"].contains(current_status) { _alertedUserToOutstandingUpdates = false if !_update_in_progress { updateNow() } } else if ["will-be-installed", "update-will-be-installed", "will-be-removed"].contains(prior_status) { // cancelled a pending install or removal; should run an updatecheck checkForUpdates(suppress_apple_update_check: true) } } else { msc_debug_log( "User clicked Install/Upgrade/Removal/Cancel button " + "in the list or detail view") msc_debug_log("Can't find item: \(item_name)") return } } func update_status_for_item(_ item: OptionalItem) -> Bool { /* Attempts to update an item's status; displays an error dialog if SelfServeManifest is not writable. Returns a boolean to indicate success */ if item.update_status() { return true } else { let errMsg = "Could not update \(WRITEABLE_SELF_SERVICE_MANIFEST_PATH)" msc_debug_log(errMsg) let alertTitle = NSLocalizedString( "System configuration problem", comment: "System configuration problem alert title") let alertDetail = NSLocalizedString( "A systems configuration issue is preventing Managed Software " + "Center from operating correctly. The reported issue is: ", comment: "System configuration problem alert detail") + "\n" + errMsg let alert = NSAlert() alert.messageText = alertTitle alert.informativeText = alertDetail alert.addButton(withTitle: NSLocalizedString("OK", comment: "OK button title")) alert.runModal() return false } } func updateOptionalInstallButtonFinishAction(_ item_name: String) { // Perform the required action when a user clicks // the cancel or add button in the updates list msc_debug_log("Called updateOptionalInstallButtonFinishAction for \(item_name)") guard let item = optionalItem(forName: item_name) else { msc_debug_log( "Unexpected error: Can't find item for \(item_name)") return } // remove row for this item from its current table webView.evaluateJavaScript("removeElementByID('\(item_name)_update_item')") // update item status if !update_status_for_item(item) { // there was a problem, can't continue msc_debug_log( "Unexpected error: Can't update status of \(item_name)") return } let current_status = item["status"] as? String ?? "" msc_log("user", "optional_install_\(current_status)", msg: item_name) if pythonishBool(item["needs_update"]) { // make some new HTML for the updated item let item_template = getTemplate("update_item_template.html") item["added_class"] = "added" let item_html = item_template.substitute(item) if ["install-requested", "update-will-be-installed", "installed"].contains(current_status) { // add the node to the updates-to-install table addToInnerHTML(item_html, elementID: "updates-to-install-table") } if current_status == "update-available" { // add the node to the other-updates table addToInnerHTML(item_html, elementID: "other-updates-table") } } // might need to toggle visibility of other updates div // find any optional installs with status update available let other_updates = getOptionalInstallItems().filter( { ($0["status"] as? String ?? "") == "update-available" } ) if other_updates.isEmpty { webView.evaluateJavaScript("document.getElementById('other-updates').classList.add('hidden')") } else { webView.evaluateJavaScript("document.getElementById('other-updates').classList.remove('hidden')") } // update the updates-to-install header to reflect the new list of // updates to install setInnerText(updateCountMessage(getUpdateCount()), elementID: "update-count-string") setInnerText(getWarningText(should_filter_apple_updates), elementID: "update-warning-text") // update text of Install All button setInnerText(getInstallAllButtonTextForCount(getUpdateCount()), elementID: "install-all-button-text") // update count badges displayUpdateCount() if updateCheckNeeded() { // check for updates after a short delay so UI changes visually // complete first self.perform(#selector(self.checkForUpdates), with: true, afterDelay: 1.0) } } func updateDOMforOptionalItem(_ item: OptionalItem) { // Update displayed status of an item let item_name = item["name"] as? String ?? "" msc_debug_log("Called updateDOMforOptionalItem for \(item_name)") let btn_id = "\(item_name)_action_button_text" let status_line_id = "\(item_name)_status_text" webView.evaluateJavaScript("document.getElementById('\(btn_id)').className") { (result, error) in msc_debug_log("result: \(result ?? "<none>") error: \(String(describing: error))") if error == nil { var btn_classes = (result as? String ?? "").components(separatedBy: " ") // filter out status class btn_classes = btn_classes.filter( { ["msc-button-inner", "large", "small", "install-updates"].contains($0) } ) if let item_status = item["status"] as? String { btn_classes.append(item_status) let btnClassName = btn_classes.joined(separator: " ") self.webView.evaluateJavaScript("document.getElementById('\(btn_id)').className = '\(btnClassName)'") self.webView.evaluateJavaScript("document.getElementById('\(status_line_id)').className = '\(item_status)'") } if btn_classes.contains("install-updates") { //(btn as! DOMHTMLElement).innerText = item["myitem_action_text"] as? String ?? "" self.setInnerText(item["myitem_action_text"] as? String ?? "", elementID: btn_id) } else if btn_classes.contains("long_action_text") { //(btn as! DOMHTMLElement).innerText = item["long_action_text"] as? String ?? "" self.setInnerText(item["long_action_text"] as? String ?? "", elementID: btn_id) } else { //(btn as! DOMHTMLElement).innerText = item["short_action_text"] as? String ?? "" self.setInnerText(item["short_action_text"] as? String ?? "", elementID: btn_id) } // use innerHTML instead of innerText because sometimes the status // text contains html, like '<span class="warning">Some warning</span>' self.setInnerHTML(item["status_text"] as? String ?? "", elementID: "\(item_name)_status_text_span") } } } func changeSelectedCategory(_ category: String) { // this method is called from JavaScript when the user // changes the category selected in the sidebar popup let all_categories_label = NSLocalizedString( "All Categories", comment: "AllCategoriesLabel") let featured_label = NSLocalizedString("Featured", comment: "FeaturedLabel") if [all_categories_label, featured_label].contains(category) { load_page("category-all.html") } else { load_page("category-\(category).html") } } // some Cocoa UI bindings @IBAction func showHelp(_ sender: Any) { if let helpURL = pref("HelpURL") as? String { if let finalURL = URL(string: helpURL) { NSWorkspace.shared.open(finalURL) } } else { let alertTitle = NSLocalizedString("Help", comment: "No help alert title") let alertDetail = NSLocalizedString( "Help isn't available for Managed Software Center.", comment: "No help alert detail") let alert = NSAlert() alert.messageText = alertTitle alert.informativeText = alertDetail alert.addButton(withTitle: NSLocalizedString("OK", comment: "OK button title")) alert.runModal() } } @IBAction func navigateBackBtnClicked(_ sender: Any) { clearSearchField() // Handle WebView back button webView.goBack(self) /*let page_url = webView.url let filename = page_url?.lastPathComponent ?? "" navigateBackButton.isHidden = !filename.hasPrefix("detail-")*/ } @IBAction func navigateForwardBtnClicked(_ sender: Any) { // Handle WebView forward button clearSearchField() webView.goForward(self) } @IBAction func loadAllSoftwarePage(_ sender: Any) { // Called by Navigate menu item clearSearchField() load_page("category-all.html") } @IBAction func loadCategoriesPage(_ sender: Any) { // Called by Navigate menu item clearSearchField() load_page("categories.html") } @IBAction func loadMyItemsPage(_ sender: Any) { // Called by Navigate menu item''' clearSearchField() load_page("myitems.html") } @IBAction func loadUpdatesPage(_ sender: Any) { // Called by Navigate menu item''' clearSearchField() load_page("updates.html") } @IBAction func searchFilterChanged(_ sender: Any) { // User changed the search field let filterString = searchField.stringValue.lowercased() if !filterString.isEmpty { msc_debug_log("Search filter is: \(filterString)") load_page("filter-\(filterString).html") } } } extension MainWindowController: NSOutlineViewDataSource { // Number of items in the sidebar func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { return items.count } // Items to be added to sidebar func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { return items[index] } // Whether rows are expandable by an arrow func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { return false } func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? { return MSCTableRowView(frame: NSZeroRect); } func outlineView(_ outlineView: NSOutlineView, didAdd rowView: NSTableRowView, forRow row: Int) { rowView.selectionHighlightStyle = .regular } } extension MainWindowController: NSOutlineViewDelegate { func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { var view: MSCTableCellView? let itemDict = item as? [String: String] if let title = itemDict?["title"], let icon = itemDict?["icon"] { view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ItemCell"), owner: self) as? MSCTableCellView if let textField = view?.title { textField.stringValue = title.localized(withComment: "\(title) label") } if let imageView = view?.imgView { imageView.image = NSImage(named: NSImage.Name(icon))?.tint(color: .secondaryLabelColor) } } return view } } extension NSImage { func tint(color: NSColor) -> NSImage { guard !self.isTemplate else { return self } let image = self.copy() as! NSImage image.lockFocus() color.set() let imageRect = NSRect(origin: NSZeroPoint, size: image.size) imageRect.fill(using: .sourceAtop) image.unlockFocus() image.isTemplate = false return image } } extension String { func localized(withComment comment: String? = nil) -> String { return NSLocalizedString(self, comment: comment ?? "") } }
42.591371
157
0.593335
e0ca0490c3d89bd12b62127b0600abc5d2f3d0c2
2,355
import UIKit public typealias CustomMaskProvider = (CGSize) -> UIBezierPath /** Mask type for masking an IBAnimatable UI element. */ public enum MaskType: IBEnum { /// For circle shape with diameter equals to min(width, height). case circle /// For ellipse shape. case ellipse /// For polygon shape with `n` sides. (min: 3, the default: 6). case polygon(sides: Int) /// For star shape with n points (min: 3, default: 5) case star(points: Int) /// For isosceles triangle shape. The triangle's height is equal to the view's frame height. If the view is a square, the triangle is equilateral. case triangle /// For wave shape with `direction` (up or down, default: up), width (default: 40) and offset (default: 0) case wave(direction: WaveDirection, width: Double, offset: Double) /// For parallelogram shape with an angle (default: 60). If `angle == 90` then it is a rectangular mask. If `angle < 90` then is a left-oriented parallelogram\-\ case parallelogram(angle: Double) /// Custom shape case custom(pathProvider: CustomMaskProvider) case none /** Wave direction for `wave` shape. */ public enum WaveDirection: String { /// For the wave facing up. case up /// For the wave facing down. case down } } public extension MaskType { init(string: String?) { guard let string = string else { self = .none return } let (name, params) = MaskType.extractNameAndParams(from: string) switch name { case "circle": self = .circle case "ellipse": self = .ellipse case "polygon": self = .polygon(sides: params[safe: 0]?.toInt() ?? 6) case "star": self = .star(points: params[safe: 0]?.toInt() ?? 5) case "triangle": self = .triangle case "wave": self = .wave(direction: WaveDirection(raw: params[safe: 0], defaultValue: .up), width: params[safe: 1]?.toDouble() ?? 40, offset: params[safe: 2]?.toDouble() ?? 0) case "parallelogram": self = .parallelogram(angle: params[safe: 0]?.toDouble() ?? 60) default: self = .none } } }
32.708333
166
0.577919
1e5db2899940bdbe3a441afe954e07a2afe7b569
2,703
import UIKit /// Representation of a table section. public struct Section: Hashable, Equatable { // MARK: - Types /// Representation of a section header or footer. public enum Extremity { /// System defined style for the title of the header or footer. case title(String) /// Custom view for the header or footer. The height will be the view's `bounds.height`. case view(UIView) // View Sized with autolayout // If Pre iOS11: Requires tableview estimatedSectionHeader/FooterHeight to be > 0 case autoLayoutView(UIView) var _title: String? { switch self { case .title(let extremityTitle): return extremityTitle default: return nil } } var _view: UIView? { switch self { case .view(let extremityView): return extremityView case .autoLayoutView(let extremityView): return extremityView default: return nil } } var viewHeight: CGFloat { switch self { case .title(_), .autoLayoutView(_): return UITableViewAutomaticDimension case .view(let view): return view.bounds.height } } } // MARK: - Properties /// Unique identifier used to identify the section. public let uuid: String /// Title or view for the header of the section. public var header: Extremity? /// Array of rows for the section. public var rows: [Row] /// Title or view for the header of the section. public var footer: Extremity? /// Section index title public var indexTitle: String? public var hashValue: Int { return uuid.hashValue } // MARK: - Initiailizers public init(header: Extremity? = nil, rows: [Row] = [], footer: Extremity? = nil, indexTitle: String? = nil, uuid: String = UUID().uuidString) { self.uuid = uuid self.header = header self.rows = rows self.footer = footer self.indexTitle = indexTitle } } extension Section.Extremity: ExpressibleByStringLiteral { public typealias UnicodeScalarLiteralType = StringLiteralType public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self = .title(value) } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self = .title(value) } public init(stringLiteral value: StringLiteralType) { self = .title(value) } } public func ==(lhs: Section, rhs: Section) -> Bool { return lhs.uuid == rhs.uuid }
27.30303
148
0.630781
64fd000de874aaf1d01848a996a8a328e9a37bd1
1,540
public struct FreeNearSemiring<A>: NearSemiring { public let elements: [[A]] public init(_ elements: [[A]]) { self.elements = elements } public static func +(lhs: FreeNearSemiring<A>, rhs: FreeNearSemiring<A>) -> FreeNearSemiring<A> { return .init(lhs.elements <> rhs.elements) } public static func *(xss: FreeNearSemiring<A>, yss: FreeNearSemiring<A>) -> FreeNearSemiring<A> { return .init( xss.elements.flatMap { xs in yss.elements.map { ys in xs <> ys } } ) } public static var zero: FreeNearSemiring<A> { return .init([]) } public static var one: FreeNearSemiring<A> { return .init([[]]) } } // MARK: - Functor public func map<A, B>(_ f: @escaping (A) -> B) -> (FreeNearSemiring<A>) -> FreeNearSemiring<B> { return { s in .init(s.elements.map { $0.map(f) }) } } // MARK: - Apply public func apply<A, B>(_ fss: FreeNearSemiring<(A) -> B>) -> (FreeNearSemiring<A>) -> FreeNearSemiring<B> { return { (xss: FreeNearSemiring<A>) -> FreeNearSemiring<B> in .init( fss.elements.flatMap { fs in xss.elements.map { xs in fs <*> xs } } ) } } // MARK: - Applicative public func pure<A>(_ a: A) -> FreeNearSemiring<A> { return .init([[a]]) } // MARK: - Equatable public func ==<A: Equatable>(lhs: FreeNearSemiring<A>, rhs: FreeNearSemiring<A>) -> Bool { return lhs.elements.count == rhs.elements.count && zip(lhs.elements, rhs.elements).reduce(true) { accum, x in accum && x.0 == x.1 } }
23.692308
108
0.601948
cce1d2bc7c2a01dd09a0e1c7fc94dd05d9f3b75d
3,111
// // WisdomProtocolKit.swift // WisdomProtocolKit // // Created by jianfeng on 2019/10/8. // Copyright © 2019 All over the sky star. All rights reserved. // import UIKit // MARK: - Config Protocol @objc public protocol WisdomConfigProtocol { // register all module static func registerConfigModule() // register all class static func registerProtocolClass() } // MARK: - Router Controller Protocol Of UIViewController @objc public protocol WisdomControllerProtocol where Self: WisdomProtocolController { // - parameter : WisdomProtocolController @discardableResult static func wisdomProtocolController(rootVC: UIViewController) -> WisdomProtocolController // - parameter : WisdomProtocolController, Any @discardableResult static func wisdomProtocolController(rootVC: UIViewController, data: Any) -> WisdomProtocolController // - parameter : WisdomProtocolController, Any, WisdomRouterClosure @discardableResult static func wisdomProtocolController(rootVC: UIViewController, data: Any, closure: WisdomProtocolClosure) -> WisdomProtocolController // - parameter : WisdomProtocolController, Any, WisdomRouterReturnClosure @discardableResult static func wisdomProtocolController(rootVC: UIViewController, data: Any, returnClosure: WisdomProtocolReturnClosure) -> WisdomProtocolController } // MARK: - Router View Protocol Of UIView @objc public protocol WisdomViewProtocol where Self: WisdomProtocolView { // - parameter : UIView // - return : WisdomRouterView static func wisdomProtocolView(superview: UIView) -> WisdomProtocolView // - parameter : UIView, Any // - return : WisdomRouterView static func wisdomProtocolView(superview: UIView, data: Any) -> WisdomProtocolView // - parameter : UIView, Any, WisdomProtocolClosure // - return : WisdomRouterView static func wisdomProtocolView(superview: UIView, data: Any, closure: WisdomProtocolClosure) -> WisdomProtocolView // - parameter : UIView, Any, WisdomProtocolReturnClosure // - return : WisdomRouterView static func wisdomProtocolView(superview: UIView, data: Any, returnClosure: WisdomProtocolReturnClosure) -> WisdomProtocolView } // MARK: - Base Protocol @objc public protocol WisdomProtocol { // - parameter : Any func wisdomProtocol(data: Any) // - parameter : Any, WisdomProtocolClosure func wisdomProtocol(data: Any, closure: WisdomProtocolClosure) // - parameter : Any, WisdomProtocolReturnClosure func wisdomProtocol(data: Any, returnClosure: WisdomProtocolReturnClosure) } // MARK: - Class Protocol @objc public protocol WisdomClassProtocol { // - parameter : Any static func wisdomProtocolClass(data: Any) // - parameter : Any, WisdomProtocolClosure static func wisdomProtocolClass(data: Any, closure: WisdomProtocolClosure) // - parameter : Any, WisdomProtocolReturnClosure static func wisdomProtocolClass(data: Any, returnClosure: WisdomProtocolReturnClosure) }
32.40625
149
0.731598
504c67ccebab89d34973d1f2d02261b1b7b14ecd
368
// // TimeItem.swift // WallpapperLib // // Created by Marcin Czachurski on 01/07/2019. // Copyright © 2019 Marcin Czachurski. All rights reserved. // import Foundation public class TimeItem : Codable { enum CodingKeys: String, CodingKey { case time = "t" case imageIndex = "i" } var time: Double = 0.0 var imageIndex: Int = 0 }
18.4
60
0.63587
1ea501a6c6160f49bd280d40c80b653ead1063ed
690
// // NavigatorSwiftUI.swift // Task100 // // Created by Максим Ламанский on 15.09.2021. // import Foundation protocol NavigatorSwiftUI { var currentCoordinator: CoordinatorSwiftUI? { get set } var previousCoordinators: [CoordinatorSwiftUI] { get set } func push(_ coordinator: CoordinatorSwiftUI) func pop() func clear() func allCoordinators() -> [CoordinatorSwiftUI?] } protocol NavigatorGeneric { associatedtype Typ var current: Typ? { get set } var previous: [Typ] { get set } func push(_ coordinator: Typ) func pop() func clear() func allScenes() -> [Typ?] }
15.681818
62
0.608696
e61e1417a57334b5c11614e285678606f604434c
1,499
// // UISliderExtensionsTests.swift // SwifterSwift // // Created by Steven on 2/16/17. // Copyright © 2017 omaralbeik. All rights reserved. // #if os(iOS) import XCTest @testable import SwifterSwift final class UISliderExtensionsTests: XCTestCase { func testCompletionCalledAnimated() { let slider = UISlider() slider.minimumValue = 0 slider.maximumValue = 100 let exp = expectation(description: "calledCompletion") slider.setValue(90, animated: true, duration: 0.5) { XCTAssertEqual(slider.value, 90.0) exp.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testSetValue() { let slider = UISlider() slider.minimumValue = 0 slider.maximumValue = 100 var completionCalled = false slider.setValue(99) { completionCalled = true XCTAssert(completionCalled) } XCTAssertFalse(completionCalled) XCTAssertEqual(slider.value, 99) } func testCompletionCalled() { let slider = UISlider() slider.minimumValue = 0 slider.maximumValue = 100 let exp = expectation(description: "calledCompletion") slider.setValue(50, animated: false, duration: 2) { XCTAssert(true) exp.fulfill() } XCTAssertEqual(slider.value, 50.0) waitForExpectations(timeout: 3, handler: nil) } } #endif
25.40678
62
0.60507
8fda7fb02233a19e5336082303fc56cc3f88cfb1
1,793
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | FileCheck %s // REQUIRES: objc_interop import gizmo // Although we don't ever expose initializers and methods of generic classes // to ObjC yet, a generic subclass of an ObjC class must still use ObjC // deallocation. // CHECK-NOT: sil hidden @_TFCSo7Genericd // CHECK-NOT: sil hidden @_TFCSo8NSObjectd class Generic<T>: NSObject { var x: Int = 10 // CHECK-LABEL: sil hidden @_TFC18objc_generic_class7GenericD : $@convention(method) <T> (@owned Generic<T>) -> () { // CHECK: bb0({{%.*}} : $Generic<T>): // CHECK-LABEL: sil hidden [thunk] @_TToFC18objc_generic_class7GenericD : $@convention(objc_method) <T> (Generic<T>) -> () { // CHECK: bb0([[SELF:%.*]] : $Generic<T>): // CHECK: [[NATIVE:%.*]] = function_ref @_TFC18objc_generic_class7GenericD // CHECK: apply [[NATIVE]]<T>([[SELF]]) deinit { // Don't blow up when 'self' is referenced inside an @objc deinit method // of a generic class. <rdar://problem/16325525> self.x = 0 } } // CHECK-NOT: sil hidden @_TFC18objc_generic_class7Genericd // CHECK-NOT: sil hidden @_TFCSo8NSObjectd // CHECK-LABEL: sil hidden @_TFC18objc_generic_class11SubGeneric1D : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () { // CHECK: bb0([[SELF:%.*]] : $SubGeneric1<U, V>): // CHECK: [[SUPER_DEALLOC:%.*]] = super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.foreign : <T> (Generic<T>) -> () -> () , $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> () // CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int> // CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]]) class SubGeneric1<U, V>: Generic<Int> { }
43.731707
211
0.63971
466abd5255522ce30738e94d68771f325d8b1321
3,218
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you 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 import UIKit class AppNavigationController: UINavigationController { private var scrollViewObserver: NSKeyValueObservation? override func viewDidLoad() { super.viewDidLoad() navigationBar.isTranslucent = true navigationBar.prefersLargeTitles = true view.backgroundColor = .enaColor(for: .separator) delegate = self } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) scrollViewObserver?.invalidate() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let opacityDelegate = topViewController as? NavigationBarOpacityDelegate { navigationBar.backgroundAlpha = opacityDelegate.backgroundAlpha } } } extension AppNavigationController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { scrollViewObserver?.invalidate() var navigationBackgroundAlpha: CGFloat = 1.0 if let opacityDelegate = viewController as? NavigationBarOpacityDelegate { navigationBackgroundAlpha = opacityDelegate.backgroundAlpha if let scrollView = viewController.view as? UIScrollView ?? viewController.view.subviews.first(ofType: UIScrollView.self) { scrollViewObserver = scrollView.observe(\.contentOffset) { [weak self] _, _ in guard let self = self else { return } guard viewController == self.topViewController else { return } self.navigationBar.backgroundAlpha = opacityDelegate.backgroundAlpha } } } transitionCoordinator?.animate(alongsideTransition: { _ in self.navigationBar.backgroundAlpha = navigationBackgroundAlpha }) } } extension UINavigationBar { var backgroundView: UIView? { subviews.first } var shadowView: UIImageView? { backgroundView?.subviews.first(ofType: UIVisualEffectView.self)?.subviews.first(ofType: UIImageView.self) } var visualEffectView: UIVisualEffectView? { backgroundView?.subviews.last(ofType: UIVisualEffectView.self) } var backgroundAlpha: CGFloat { get { backgroundView?.alpha ?? 0 } set { backgroundView?.alpha = newValue } } } private extension Array { func first<T>(ofType _: T.Type) -> T? { first(where: { $0 is T }) as? T } func last<T>(ofType _: T.Type) -> T? { last(where: { $0 is T }) as? T } } protocol NavigationBarOpacityDelegate: class { var preferredNavigationBarOpacity: CGFloat { get } } private extension NavigationBarOpacityDelegate { var backgroundAlpha: CGFloat { max(0, min(preferredNavigationBarOpacity, 1)) } }
30.358491
139
0.76041
1ec5dbdc9a635d702a325ad3c2baf6fad5365faa
615
// // ViewController.swift // URandomInteger // // Created by Utsav2020 on 03/26/2020. // Copyright (c) 2020 Utsav2020. All rights reserved. // import UIKit import URandomInteger class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let randomInteger = RandomInteger.RadInteger() print(randomInteger) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.777778
80
0.684553
1199669f3bc5b2e3d47bf284bd2bb099ef79ad75
745
import XCTest import BT_Timer class Tests: 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. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.689655
111
0.6
28362db1493ddde896b8566d552790bcd422b327
3,571
// Copyright SIX DAY LLC. All rights reserved. import BigInt import Foundation import APIKit import JSONRPCKit import PromiseKit import Result class SendTransactionCoordinator { private let keystore: Keystore private let session: WalletSession private let formatter = EtherNumberFormatter.full private let confirmType: ConfirmType init( session: WalletSession, keystore: Keystore, confirmType: ConfirmType ) { self.session = session self.keystore = keystore self.confirmType = confirmType } func send( transaction: UnsignedTransaction, completion: @escaping (ResultResult<ConfirmResult, AnyError>.t) -> Void ) { if transaction.nonce >= 0 { signAndSend(transaction: transaction, completion: completion) } else { let request = EtherServiceRequest(server: session.server, batch: BatchFactory().create(GetTransactionCountRequest( address: session.account.address, state: "pending" ))) //TODO Verify we need a strong reference to self Session.send(request) { result in //guard let `self` = self else { return } switch result { case .success(let count): let transaction = self.appendNonce(to: transaction, currentNonce: count) self.signAndSend(transaction: transaction, completion: completion) case .failure(let error): completion(.failure(AnyError(error))) } } } } func send(transaction: UnsignedTransaction) -> Promise<ConfirmResult> { Promise { seal in send(transaction: transaction) { result in switch result { case .success(let result): seal.fulfill(result) case .failure(let error): seal.reject(error) } } } } private func appendNonce(to: UnsignedTransaction, currentNonce: Int) -> UnsignedTransaction { return UnsignedTransaction( value: to.value, account: to.account, to: to.to, nonce: currentNonce, data: to.data, gasPrice: to.gasPrice, gasLimit: to.gasLimit, server: to.server ) } func signAndSend( transaction: UnsignedTransaction, completion: @escaping (ResultResult<ConfirmResult, AnyError>.t) -> Void ) { let signedTransaction = keystore.signTransaction(transaction) switch signedTransaction { case .success(let data): switch confirmType { case .sign: completion(.success(.signedTransaction(data))) case .signThenSend: let request = EtherServiceRequest(server: session.server, batch: BatchFactory().create(SendRawTransactionRequest(signedTransaction: data.hexEncoded))) Session.send(request) { result in switch result { case .success(let transactionID): completion(.success(.sentTransaction(SentTransaction(id: transactionID, original: transaction)))) case .failure(let error): completion(.failure(AnyError(error))) } } } case .failure(let error): completion(.failure(AnyError(error))) } } }
34.669903
166
0.573229
bbea0a984874283b450783a477675032ee0e2311
827
// // AppraiserClient.swift // Uptick // // Created by StarryMedia 刘晓祥 on 2019/7/4. // Copyright © 2019 starrymedia. All rights reserved. // import Foundation open class AppraiserService : NSObject{ public func info(accessToken : String,pageNumber : Int ,pageSize : Int,did : String,tag : String,type: String,category : String,Success : @escaping ServerResultSuccessResult , Failed : @escaping ServerResultSuccessResult){ var dic : Dictionary<String,Any> = [:] dic["accessToken"] = accessToken dic["pageNumber"] = pageNumber dic["pageSize"] = pageSize dic["did"] = did dic["tag"] = tag dic["type"] = type dic["category"] = category DMAHttpUtil.getServerData(url: Config.Appraiser.ALL, param: dic, Success: Success, Failed: Failed) } }
31.807692
226
0.655381
bbe525d142e72b96a1a5d679e1d1bfb1aa242087
6,018
// // AttributeString.swift // SSUIKit // // Created by 吴頔 on 2019/11/30. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit import YYText import QMUIKit public extension NSMutableAttributedString { /// 改变颜色 /// /// - Parameters: /// - color: 颜色 /// - text: 要改变颜色的字符串 /// - Returns: NSMutableAttributedString @discardableResult func ss_color(color: UIColor?, with text: String? = nil) -> NSMutableAttributedString { guard let color = color else { return self } var str = text ?? "" if text == nil { str = self.string } if !string.contains(str) { return self } let range = string.ss_nsString.range(of: str) addAttribute(.foregroundColor, value: color, range: range) return self } /// 改变文字背景颜色 /// - Parameter color: 颜色 /// - Parameter text: 要改变颜色的字符串背景 @discardableResult func ss_backgroundColor(color: UIColor?, with text: String? = nil) -> NSMutableAttributedString { guard let color = color else { return self } var str = text.orEmpty if text == nil { str = self.string } if !string.contains(str) { return self } let range = string.ss_nsString.range(of: str) addAttribute(.backgroundColor, value: color, range: range) return self } /// 改变字体大小 /// /// - Parameters: /// - fontSize: 字体大小 /// - isBord: 是否加粗 /// - text: 要改变字体大小的字符串 /// - Returns: NSMutableAttributedString @discardableResult func ss_font( font: UIFont, with value: Any? = nil ) -> NSMutableAttributedString { var str = "" if value == nil { str = self.string }else{ str = "\(value!)" } if !string.contains(str) { return self } let range = string.ss_nsString.range(of: str) addAttribute(.font, value: font, range: range) return self } /// 改变字符串的对齐方式 /// /// - Parameters: /// - alignment: NSTextAlignment /// - text: 要改变对齐方式的字符串 /// - Returns: NSMutableAttributedString @discardableResult func ss_alignment(alignment: NSTextAlignment, with lineSpacing: CGFloat = 0, with text: String? = nil) -> NSMutableAttributedString { var str = text.orEmpty if text == nil { str = self.string } if !string.contains(str) { return self } let range = string.ss_nsString.range(of: str) let paragraph = NSMutableParagraphStyle() paragraph.alignment = alignment if lineSpacing > 0 { paragraph.lineSpacing = lineSpacing } addAttribute(.paragraphStyle, value: paragraph, range: range) return self } /// 添加字符串的样式 /// /// - Parameter text: 要添加样式的字符串 /// - Returns: NSMutableAttributedString @discardableResult func ss_addAttribute(key: NSAttributedString.Key, value: Any? = nil, with text:String? = nil) -> NSMutableAttributedString{ var str = text.orEmpty if text == nil { str = self.string } if !string.contains(str) { return self } let range = string.ss_nsString.range(of: str) let addValue = value == nil ? NSNumber(value: 1) : value! addAttribute(key, value: addValue, range: range) return self } /// 添加图片 /// /// - Parameters: /// - image: UIImage /// - bounds: CGRect /// - text: 在哪个文本的后面 /// - Returns: NSMutableAttributedString @discardableResult func ss_image(image: UIImage?, bounds: CGRect, behind text: String? = nil, insertAtFirst: Bool = false) -> NSMutableAttributedString { guard let image = image else { return self } var str = text.orEmpty if text == nil { str = self.string } let attachment = NSTextAttachment() attachment.image = image attachment.bounds = bounds let imageAttribute = NSAttributedString(attachment: attachment) if insertAtFirst { insert(imageAttribute, at: 0) }else{ insert(imageAttribute, at: str.count) } return self } /// 设置整体的对齐方式及行间距 /// /// - Parameters: /// - aligment: 对齐方式 /// - lineSpacing: 间距 /// - Returns: NSMutableAttributedString @discardableResult func ss_alignment(_ aligment: NSTextAlignment, lineSpacing: CGFloat? = nil) -> NSMutableAttributedString { let paragraph = NSMutableParagraphStyle() paragraph.alignment = aligment if let lineSpacing = lineSpacing { paragraph.lineSpacing = lineSpacing } addAttribute(.paragraphStyle, value: paragraph, range: NSMakeRange(0, string.count)) return self } /// 计算富文本尺寸 /// - Parameter maxWidth: 最大宽度 func ss_size(_ maxWidth: CGFloat) -> CGSize { if self.length > 0 { let rect = self.boundingRect( with: CGSize(width: maxWidth, height: CGFloat.infinity), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil ) return CGSize( width: rect.size.width+2, height: rect.size.height+2 ) }else{ return .zero } } } public extension NSMutableAttributedString { var ss_width: CGFloat { return size().width } var ss_height: CGFloat { return size().height } } public extension NSMutableAttributedString { var ss_layout: YYTextLayout? { let conteiner = YYTextContainer(size: CGSize(width: CGFloat.infinity, height: CGFloat.infinity)) let layout = YYTextLayout(container: conteiner, text: self) return layout } var ss_image: UIImage? { return UIImage.qmui_image(with: self) } }
29.356098
138
0.576437
08acf9cd2f74332d2ffe48d49a35ee74f23abde7
8,153
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Amplify import AWSMobileClient struct AuthErrorHelper { // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length static func toAuthError(awsMobileClientError: AWSMobileClientError) -> AuthError { switch awsMobileClientError { case .userNotFound(let message): return AuthError.service(message, AuthPluginErrorConstants.userNotFoundError, AWSCognitoAuthError.userNotFound) case .userNotConfirmed(let message): return AuthError.service(message, AuthPluginErrorConstants.userNotConfirmedError, AWSCognitoAuthError.userNotConfirmed) case .usernameExists(let message): return AuthError.service(message, AuthPluginErrorConstants.userNameExistsError, AWSCognitoAuthError.usernameExists) case .aliasExists(let message): return AuthError.service(message, AuthPluginErrorConstants.aliasExistsError, AWSCognitoAuthError.aliasExists) case .codeDeliveryFailure(let message): return AuthError.service(message, AuthPluginErrorConstants.codeDeliveryError, AWSCognitoAuthError.codeDelivery) case .codeMismatch(let message): return AuthError.service(message, AuthPluginErrorConstants.codeMismatchError, AWSCognitoAuthError.codeMismatch) case .expiredCode(let message): return AuthError.service(message, AuthPluginErrorConstants.codeExpiredError, AWSCognitoAuthError.codeExpired) case .invalidLambdaResponse(let message): return AuthError.service(message, AuthPluginErrorConstants.lambdaError, AWSCognitoAuthError.lambda) case .unexpectedLambda(let message): return AuthError.service(message, AuthPluginErrorConstants.lambdaError, AWSCognitoAuthError.lambda) case .userLambdaValidation(let message): return AuthError.service(message, AuthPluginErrorConstants.lambdaError, AWSCognitoAuthError.lambda) case .invalidParameter(let message): return AuthError.service(message, AuthPluginErrorConstants.invalidParameterError, AWSCognitoAuthError.invalidParameter) case .invalidPassword(let message): return AuthError.service(message, AuthPluginErrorConstants.invalidPasswordError, AWSCognitoAuthError.invalidPassword) case .mfaMethodNotFound(let message): return AuthError.service(message, AuthPluginErrorConstants.mfaMethodNotFoundError, AWSCognitoAuthError.mfaMethodNotFound) case .passwordResetRequired(let message): return AuthError.service(message, AuthPluginErrorConstants.passwordResetRequired, AWSCognitoAuthError.passwordResetRequired) case .resourceNotFound(let message): return AuthError.service(message, AuthPluginErrorConstants.resourceNotFoundError, AWSCognitoAuthError.resourceNotFound) case .softwareTokenMFANotFound(let message): return AuthError.service(message, AuthPluginErrorConstants.softwareTokenNotFoundError, AWSCognitoAuthError.softwareTokenMFANotEnabled) case .tooManyFailedAttempts(let message): return AuthError.service(message, AuthPluginErrorConstants.tooManyFailedError, AWSCognitoAuthError.failedAttemptsLimitExceeded) case .tooManyRequests(let message), .limitExceeded(let message): return AuthError.service(message, AuthPluginErrorConstants.tooManyRequestError, AWSCognitoAuthError.requestLimitExceeded) case .errorLoadingPage(let message): return AuthError.service(message, AuthPluginErrorConstants.errorLoadingPageError, AWSCognitoAuthError.errorLoadingUI) case .deviceNotRemembered(let message): return AuthError.service(message, AuthPluginErrorConstants.deviceNotRememberedError, AWSCognitoAuthError.deviceNotTracked) case .invalidState(let message): return AuthError.invalidState(message, AuthPluginErrorConstants.invalidStateError) case .invalidConfiguration(let message), .cognitoIdentityPoolNotConfigured(let message), .invalidUserPoolConfiguration(let message): return AuthError.configuration(message, AuthPluginErrorConstants.configurationError) case .notAuthorized(let message): // Not authorized is thrown from server when a user is not authorized. return AuthError.notAuthorized(message, AuthPluginErrorConstants.notAuthorizedError) // Below error should not happen, these will be handled inside the plugin. case .notSignedIn(let message), // Called in getTokens/getPassword when not signedin to CUP .identityIdUnavailable(let message), // From getIdentityId. Handled in plugin .guestAccessNotAllowed(let message), // Returned from getAWSCredentials. Handled in plugin .federationProviderExists(let message), // User is already signed in to user pool in federatedSignIn .unableToSignIn(let message), // Called in signout, releaseSignInWait. .idTokenNotIssued(let message), // Not used anywhere. .userPoolNotConfigured(let message): return AuthError.unknown(message) case .badRequest(let message), .securityFailed(let message), .userCancelledSignIn(let message), .idTokenAndAcceessTokenNotIssued(let message): // These errors are thrown from HostedUI signIn. // Handled in WebUISignIn inside plugin. return AuthError.unknown(message) case .expiredRefreshToken(let message): return AuthError.unknown(message) // These errors arise from the escape hatch methods. case .groupExists(let message), .invalidOAuthFlow(let message), .scopeDoesNotExist(let message): return AuthError.unknown(message) case .internalError(let message), .unknown(let message): return AuthError.unknown(message) } } static func toAuthError(_ error: Error) -> AuthError { if let awsMobileClientError = error as? AWSMobileClientError { return toAuthError(awsMobileClientError: awsMobileClientError) } return AuthError.unknown("An unknown error occurred", error) } }
48.242604
108
0.57672
217ba4256368b399a1ca4abc3108f37730c54ed3
5,234
// // Decrypter.swift // JOSESwift // // Created by Daniel Egger on 17/10/2017. // // --------------------------------------------------------------------------- // Copyright 2019 Airside Mobile Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // --------------------------------------------------------------------------- // import Foundation public struct Decrypter { private let keyManagementMode: DecryptionKeyManagementMode let keyManagementAlgorithm: KeyManagementAlgorithm let contentEncryptionAlgorithm: ContentEncryptionAlgorithm /// Constructs a decrypter that can be used to decrypt a JWE. /// /// - Parameters: /// - keyManagementAlgorithm: The algorithm that was used to encrypt the content encryption key. /// - contentEncryptionAlgorithm: The algorithm that was used to encrypt the JWE's payload. /// - decryptionKey: The key used to perform the decryption. The function of the key depends on the chosen key /// management algorithm. /// - For _key encryption_ it is the private key (`SecKey`) of the recipient to which the JWE was encrypted. /// - For _direct encryption_ it is the secret symmetric key (`Data`) shared between the sender and the /// recipient. public init?<KeyType>( keyManagementAlgorithm: KeyManagementAlgorithm, contentEncryptionAlgorithm: ContentEncryptionAlgorithm, decryptionKey: KeyType ) { self.keyManagementAlgorithm = keyManagementAlgorithm self.contentEncryptionAlgorithm = contentEncryptionAlgorithm let mode = keyManagementAlgorithm.makeDecryptionKeyManagementMode( contentEncryptionAlgorithm: contentEncryptionAlgorithm, decryptionKey: decryptionKey ) guard let keyManagementMode = mode else { return nil } self.keyManagementMode = keyManagementMode } internal func decrypt(_ context: DecryptionContext) throws -> Data { guard let alg = context.protectedHeader.keyManagementAlgorithm, alg == keyManagementAlgorithm else { throw JWEError.keyManagementAlgorithmMismatch } guard let enc = context.protectedHeader.contentEncryptionAlgorithm, enc == contentEncryptionAlgorithm else { throw JWEError.contentEncryptionAlgorithmMismatch } let contentEncryptionKey = try keyManagementMode.determineContentEncryptionKey(from: context.encryptedKey) let contentDecryptionContext = ContentDecryptionContext( ciphertext: context.ciphertext, initializationVector: context.initializationVector, additionalAuthenticatedData: context.protectedHeader.data().base64URLEncodedData(), authenticationTag: context.authenticationTag ) return try contentEncryptionAlgorithm .makeContentDecrypter(contentEncryptionKey: contentEncryptionKey) .decrypt(decryptionContext: contentDecryptionContext) } } extension Decrypter { struct DecryptionContext { let protectedHeader: JWEHeader let encryptedKey: Data let initializationVector: Data let ciphertext: Data let authenticationTag: Data } } // MARK: - Deprecated API extension Decrypter { @available(*, deprecated, message: "Use `init?(keyManagementAlgorithm:contentEncryptionAlgorithm:decryptionKey:)` instead") public init?<KeyType>(keyDecryptionAlgorithm: AsymmetricKeyAlgorithm, decryptionKey key: KeyType, contentDecryptionAlgorithm: SymmetricKeyAlgorithm) { self.init(keyManagementAlgorithm: keyDecryptionAlgorithm, contentEncryptionAlgorithm: contentDecryptionAlgorithm, decryptionKey: key) } @available(*, deprecated, message: "Use `init?(keyManagementAlgorithm:contentEncryptionAlgorithm:decryptionKey:)` instead") public init?<KeyType>(keyDecryptionAlgorithm: AsymmetricKeyAlgorithm, keyDecryptionKey kdk: KeyType, contentDecryptionAlgorithm: SymmetricKeyAlgorithm) { self.init(keyDecryptionAlgorithm: keyDecryptionAlgorithm, decryptionKey: kdk, contentDecryptionAlgorithm: contentDecryptionAlgorithm) } } @available(*, deprecated, message: "This type will be removed with the next major release.") public struct DecryptionContext { let header: JWEHeader let encryptedKey: Data let initializationVector: Data let ciphertext: Data let authenticationTag: Data } @available(*, deprecated, message: "This type will be removed with the next major release.") public struct SymmetricDecryptionContext { let ciphertext: Data let initializationVector: Data let additionalAuthenticatedData: Data let authenticationTag: Data }
42.901639
157
0.712648
14573ba746f0be4fae92e439b16f1d32c943029e
4,535
/*: To whom may be concerned: I offer professional support to all my open source projects. Contact: [[email protected]](http://krzyzanowskim.com) */ import CryptoSwift import Foundation /*: # Data types conversinn */ let data = Data([0x01, 0x02, 0x03]) let bytes = data.bytes let bytesHex = Array<UInt8>(hex: "0x010203") let hexString = bytesHex.toHexString() /*: # Digest */ data.md5() data.sha1() data.sha224() data.sha256() data.sha384() data.sha512() bytes.sha1() "123".sha1() Digest.sha1(bytes) //: Digest calculated incrementally do { var digest = MD5() _ = try digest.update(withBytes: [0x31, 0x32]) _ = try digest.update(withBytes: [0x33]) let result = try digest.finish() result.toBase64() } catch {} /*: # CRC */ bytes.crc16() bytes.crc32() bytes.crc32c() /*: # HMAC */ do { let key: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 23, 25, 26, 27, 28, 29, 30, 31, 32] try Poly1305(key: key).authenticate(bytes) try HMAC(key: key, variant: .sha256).authenticate(bytes) } catch {} /*: # PBKDF1, PBKDF2 */ do { let password: Array<UInt8> = Array("s33krit".utf8) let salt: Array<UInt8> = Array("nacllcan".utf8) try PKCS5.PBKDF1(password: password, salt: salt, variant: .sha1, iterations: 4096).calculate() let value = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, variant: .sha256).calculate() print(value) } catch {} /*: # Padding */ Padding.pkcs7.add(to: bytes, blockSize: AES.blockSize) /*: # ChaCha20 */ do { let key: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32] let iv: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8] let message = Array<UInt8>(repeating: 7, count: 10) let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message) let decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted) print(decrypted) } catch { print(error) } /*: # AES ### One-time shot. Encrypt all data at once. */ do { let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") // aes128 let ciphertext = try aes.encrypt(Array("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8)) print(ciphertext.toHexString()) } catch { print(error) } /*: ### Incremental encryption Instantiate Encryptor for AES encryption (or decryptor for decryption) and process input data partially. */ do { var encryptor = try AES(key: "passwordpassword", iv: "drowssapdrowssap").makeEncryptor() var ciphertext = Array<UInt8>() // aggregate partial results ciphertext += try encryptor.update(withBytes: Array("Nullam quis risus ".utf8)) ciphertext += try encryptor.update(withBytes: Array("eget urna mollis ".utf8)) ciphertext += try encryptor.update(withBytes: Array("ornare vel eu leo.".utf8)) // finish at the end ciphertext += try encryptor.finish() print(ciphertext.toHexString()) } catch { print(error) } /*: ### Encrypt stream */ do { // write until all is written func writeTo(stream: OutputStream, bytes: Array<UInt8>) { var writtenCount = 0 while stream.hasSpaceAvailable && writtenCount < bytes.count { writtenCount += stream.write(bytes, maxLength: bytes.count) } } let aes = try AES(key: "passwordpassword", iv: "drowssapdrowssap") var encryptor = try! aes.makeEncryptor() // prepare streams let data = Data( (0 ..< 100).map { $0 }) let inputStream = InputStream(data: data) let outputStream = OutputStream(toMemory: ()) inputStream.open() outputStream.open() var buffer = Array<UInt8>(repeating: 0, count: 2) // encrypt input stream data and write encrypted result to output stream while inputStream.hasBytesAvailable { let readCount = inputStream.read(&buffer, maxLength: buffer.count) if readCount > 0 { try encryptor.update(withBytes: buffer[0 ..< readCount]) { bytes in writeTo(stream: outputStream, bytes: bytes) } } } // finalize encryption try encryptor.finish { bytes in writeTo(stream: outputStream, bytes: bytes) } // print result if let ciphertext = outputStream.property(forKey: Stream.PropertyKey(rawValue: Stream.PropertyKey.dataWrittenToMemoryStreamKey.rawValue)) as? Data { print("Encrypted stream data: \(ciphertext.toHexString())") } } catch { print(error) }
26.366279
152
0.646748
48401c4010f1301412c01138750ecb942b6727f1
2,391
// // BloodyMary // // Copyright © TheInkedEngineer. All rights reserved. // import UIKit // MARK: - Navigation Functions internal extension Router { /// Shows a `UIViewController` inside the parent's `UINavigationController` if present, /// otherwise it creates a `UINavigationController`, sets the destination as a `rootViewController` /// and presents it as a full screen, unanimated over the parent view controller. /// - Parameters: /// - destination: The view controller to display. /// - navigationController: The navigation controller to push to. If the top view controller already has a navigation controller, the later's navigation controller will be leveraged. Defaults /// - animated: whether or not to animate the navigation. func push( _ destination: UIViewController, to navigationController: UINavigationController? = nil, animated: Bool = true, completion: Router.Completion? = nil ) { let topVC = Router.topViewController() guard topVC.hasNavigationController else { let navVC = navigationController ?? UINavigationController() navVC.viewControllers = [destination] navVC.modalPresentationStyle = destination.modalPresentationStyle topVC.present(navVC, animated: animated, completion: completion) return } topVC.navigationController?.pushViewController(destination, animated: animated, completion: completion) } /// Presents a `UIViewController` modally. /// - Parameters: /// - destination: The viewController to present. /// - viewController: The view controller presenting. /// - style: UIModalPresentationStyle to use when presenting. /// - animated: whether or not to animate the presentation of the viewController. Defaults to `true`. /// - completion: An optional completion to execute after presenting viewController. Defaults to `nil`. func present( _ destination: UIViewController, over viewController: UIViewController = Router.topViewController(), presentationStyle: UIModalPresentationStyle, transitionStyle: UIModalTransitionStyle, animated: Bool = true, completion: Router.Completion? = nil ) { destination.modalPresentationStyle = presentationStyle destination.modalTransitionStyle = transitionStyle viewController.present(destination, animated: animated, completion: completion) } }
41.224138
195
0.736512
396a77b7e6bbd03b893cde2ea1c9f4e54845a232
1,402
import Foundation /// The network client configuration. public final class NetworkConfiguration { /// The session used to perform the network requests. public let session: URLSession /// The default JSON decoder. It can be overwritten by /// individual requests, if necessary. public let defaultDecoder: JSONDecoder /// The default JSON encoder. It can be overwritten by /// individual requests, if necessary. public let defaultEncoder: JSONEncoder /// The base URL component. /// E.g., `https://hostname.com/api/v3` public let baseURL: URL /// The interceptor called right before performing the /// network request. Can be used to modify the `URLRequest` /// if necessary. public var interceptor: ((URLRequest) -> URLRequest)? /// Initializes the network client confirmation. /// - Parameters: /// - session: The session used to perform the network requests. /// - defaultDecoder: he default JSON decoder. /// - defaultEncoder: The default JSON encoder. /// - baseURL: The base URL component. public init( session: URLSession, defaultDecoder: JSONDecoder, defaultEncoder: JSONEncoder, baseURL: URL ) { self.session = session self.defaultDecoder = defaultDecoder self.defaultEncoder = defaultEncoder self.baseURL = baseURL } }
31.863636
70
0.666904
1d875d3e7e41a58779cdb23783c60ba45fae4bae
1,140
// // InitialState.swift // BroncoCast // // Created by Ken Schenke on 12/26/18. // Copyright © 2018 Ken Schenke. All rights reserved. // import Foundation import ReSwift struct AppState : StateType { var navigationState: NavigationState var signInState : SignInState var registrationState : RegistrationState var forgotPasswordState : ForgotPasswordState var profileOrgsState : ProfileOrgsState var profileNameState : ProfileNameState var profileContactsState : ProfileContactsState var profileContactsEditState : ProfileContactsEditState var userBroadcastsState : UserBroadcastsState var userBroadcastDetailState : UserBroadcastDetailState var adminUsersState : AdminUsersState var adminOrgState : AdminOrgState var adminUserDetailState : AdminUserDetailState var adminGroupsState : AdminGroupsState var adminGroupNameState : AdminGroupNameState var adminGroupDetailState : AdminGroupDetailState var adminBroadcastsState : AdminBroadcastsState var adminBroadcastDetailState : AdminBroadcastDetailState var adminNewBroadcastState : AdminNewBroadcastState }
34.545455
61
0.795614
ed1b0199826af11c2b266118c502f050652a9334
1,061
// // ViewController.swift // practiceScaleCGUI // // Created by Rim21 on 6/12/2015. // Copyright © 2015 Nathan Rima. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var displayElement: displayUI! @IBAction func menu(sender: rndBtnUI) { sender.selected = !sender.selected } @IBAction func Test3(sender: rndBtnUI) { sender.selected = !sender.selected } @IBAction func Test2(sender: rndBtnUI) { sender.selected = !sender.selected } @IBAction func Test1(sender: rndBtnUI) { sender.selected = !sender.selected } @IBAction func powerOn(sender: sqreBtnUI) { sender.selected = !sender.selected } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.104167
80
0.638077
e43fbb0a6f9faa6e438136d70d105f0c1715a9d5
3,948
// // PlayingZhiController.swift // ifanr // // Created by sys on 16/7/4. // Copyright © 2016年 ifanrOrg. All rights reserved. // import UIKit import Alamofire class PlayingZhiController: BasePageController { //MARK:-----life cycle----- override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self pullToRefresh.delegate = self tableView.sectionHeaderHeight = tableHeaderView.height tableView.tableHeaderView = tableHeaderView getData() } // 复写父类的方法 --- 获得获得 func getData(_ page: Int = 1) { isRefreshing = true let type: CommonModel? = CommonModel(dict: [:]) IFanrService.shareInstance.getData(APIConstant.newsFlash_latest(page), t: type, keys: ["data"], successHandle: { (modelArray) in if page == 1 { self.page = 1 self.playingZhiModelArray.removeAll() } // 添加数据 modelArray.forEach { self.playingZhiModelArray.append($0) } self.page += 1 self.isRefreshing = false self.tableView.reloadData() self.pullToRefresh.endRefresh() }) { (error) in print(error) } // IFanrService.shareInstance.getLatesModel(APIConstant.PlayingZhi_latest(page), successHandle: { (modelArray) in // if page == 1 { // self.page = 1 // self.playingZhiModelArray.removeAll() // } // // 添加数据 // modelArray.forEach { // self.playingZhiModelArray.append($0) // } // self.page += 1 // self.isRefreshing = false // self.tableView.reloadData() // self.pullToRefresh.endRefresh() // }) { (error) in // print(error) // } } //MARK: --------------------------- Getter and Setter -------------------------- /// 这个属性放到ScrollViewControllerReusable协议, 会初始化两次。所以放到这里好了 fileprivate lazy var tableHeaderView: UIView! = { return TableHeaderView(model: TableHeaderModelArray[1]) }() var playingZhiModelArray : Array<CommonModel> = Array() } // MARK: - 下拉刷新回调 extension PlayingZhiController: PullToRefreshDelegate { func pullToRefreshViewDidRefresh(_ pulllToRefreshView: PullToRefreshView) { getData() } } // MARK: - 上拉加载更多 extension PlayingZhiController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) if differY < happenY { if !isRefreshing { // 这里处理上拉加载更多 getData(page) } } } } // MARK: - tableView代理和数据源 extension PlayingZhiController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = PlayingZhiTableViewCell.cellWithTableView(tableView) cell.model = self.playingZhiModelArray[indexPath.row] cell.layoutMargins = UIEdgeInsetsMake(0, 32, 0, 0) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.playingZhiModelArray.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return PlayingZhiTableViewCell.estimateCellHeight(self.playingZhiModelArray[indexPath.row].title!) + 20 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model: CommonModel = self.playingZhiModelArray[indexPath.row] let ifDetailsController = IFDetailsController(model: model, naviTitle: "玩物志") self.navigationController?.pushViewController(ifDetailsController, animated: true) } }
32.360656
136
0.606636
28f4bc22791c508c3fd86a5ae3b444500db3ab75
2,178
// // AppDelegate.swift // FileStorage // // Created by Satyadev on 18/10/18. // Copyright © 2018 Satyadev Chauhan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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.340426
285
0.755739
1628bbdae2da9e703f78465a2f32faacb6b8d544
385
// // SettingsInfoViewTests.swift // Stampede-Tests // // Created by David House on 9/20/20. // Copyright © 2020 David House. All rights reserved. // import XCTest @testable import Stampede class SettingsInfoViewTests: XCTestCase { func testCapturePreviews() { capturedPreviews(SettingsInfoView_Previews.capturedPreviews(title: "SettingsInfoView_Previews")) } }
21.388889
104
0.74026
56167e3cf7a6d57ec6773e16b3e7a6424a5eb18c
992
// /* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 Beagle struct SizeSelector: Widget, AutoDecodable { var widgetProperties: WidgetProperties var sizes: [String] var height: Float func toView(renderer: BeagleRenderer) -> UIView { let view = ScrollSelector( selectorType: .size(sizes: sizes), height: height ) return view } }
28.342857
75
0.689516
5d6cd29ad996a181669019dbf4d516441b621b26
959
// // DateTests.swift // BrainKit // // Created by Ondřej Hanák on 30. 04. 2020. // Copyright © 2020 Userbrain. All rights reserved. // import XCTest final class DateTests: XCTestCase { private var calendar: Calendar! override func setUp() { super.setUp() self.calendar = Calendar.current } override func tearDown() { self.calendar = nil super.tearDown() } func test_DateString_CorrectInput() { let date = Date.from(dateString: "2019-02-03")! let components = self.calendar.dateComponents([.year, .month, .day], from: date) XCTAssertEqual(components.year, 2019) XCTAssertEqual(components.month, 2) XCTAssertEqual(components.day, 3) } func test_DateString_WrongInput() { let date = Date.from(dateString: "2019") // too short XCTAssertNil(date) } func test_ISODateString() { let input = "2019-02-03" let date = Date.from(dateString: input)! let output = date.isoDateString() XCTAssertEqual(input, output) } }
21.795455
82
0.704901
20c4eb33fb7b45c60fcad60fcefbdd98f1657c75
2,268
// // ViewController.swift // UITableExample // // Created by grade on 8.11.18. // Copyright © 2018 grade. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cc", for: indexPath) return cell } let cellIdentifier = "tableCell" let cellIdentifier2 = "rightAlignedCell" let sections = [["A", "B"], ["one", "two", "3"]] @IBOutlet weak var tableView: UITableView! @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.dataSource = self tableView.delegate = self collectionView.dataSource = self collectionView.delegate = self } //MARK: - data source func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Letters" : "Other" } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellId = indexPath.section == 0 ? cellIdentifier : cellIdentifier2 if let cell:MyCell = tableView.dequeueReusableCell(withIdentifier: cellId) as? MyCell{ let data = sections[indexPath.section][indexPath.row] cell.label.text = data print("create cell[\(indexPath)] = \(data)") return cell } print("DEFAULT") return UITableViewCell() } }
29.076923
121
0.643739
6ad16b529a6e89233c04019343427e3df4d3b13e
4,475
/* MIT License Copyright (c) 2020 Maik Müller (maikdrop) <[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. */ //source: https://stackoverflow.com/questions/56588332/align-two-swiftui-text-views-in-hstack-with-correct-alignment //Answer: 3 import SwiftUI struct HowToPlayView: View { @ObservedObject var titanicGameRules: TitanicGameRules @State private var width: CGFloat? // MARK: - Properties private var doneHandler: () -> Void // MARK: - Creates a game chooser view. init(titanicGameRules: TitanicGameRules, doneHandler: @escaping () -> Void) { self.titanicGameRules = titanicGameRules self.doneHandler = doneHandler } } // MARK: - View declaration extension HowToPlayView { var body: some View { NavigationView { List { Section { Toggle(isOn: $titanicGameRules.showAgainNextTime) { Text(AppStrings.HowToPlay.hideNxtTimeLblTxt) } } Section(header: Text(AppStrings.Rules.goalSectionTitle)) { Text(AppStrings.Rules.goalSectionContent) } Section(header: Text(AppStrings.HowToPlay.buttonSectionTitle)) { ForEach(titanicGameRules.btns.indices, id: \.self) { index in gameBtnDescriptions(for: index) } } Section(header: Text(AppStrings.HowToPlay.rulesSectionTitle), footer: Text(AppStrings.HowToPlay.rulesSectionFooter)) { ForEach(titanicGameRules.rules.indices, id: \.self) { index in ruleDescriptions(for: index) } } } .font(Font.system(.body)) .foregroundColor(Color(UIColor.label)) .onPreferenceChange(WidthPreferenceKey.self) { widths in if let width = widths.max() { self.width = width } } .listStyle(InsetGroupedListStyle()) .navigationTitle(AppStrings.HowToPlay.title) .navigationBarTitleDisplayMode(.inline) .navigationBarItems(trailing: doneButton) } } } // MARK: - Private view elements private extension HowToPlayView { private func gameBtnDescriptions(for index: Int) -> some View { Label { Text(titanicGameRules.btns[index]) } icon: { Image(systemName: titanicGameRules.btnImgNames[index]) .foregroundColor(Color(UIColor.oceanBlue)) } } private func ruleDescriptions(for index: Int) -> some View { HStack { Text(String(index + 1) + ".") .equalWidth() .frame(width: width, alignment: .leading) .foregroundColor(Color(UIColor.oceanBlue)) .font(Font.system(.largeTitle)) Text(titanicGameRules.rules[index]) .padding(edgeInsets) } } private var doneButton: some View { Button(action: doneHandler, label: { Text(AppStrings.ActionCommand.done) .font(.body) .fontWeight(.semibold) }) } } // MARK: - Constants extension HowToPlayView { private var edgeInsets: EdgeInsets { EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 0) } }
38.913043
460
0.616983
cc75e69c259ca52a1fa69e05e515551be92d0c1f
221
// // CocoaCaptureError.swift // CocoaCapture // // Created by v.a.jayachandran on 17/9/20. // Copyright © 2020 v.a.jayachandran. All rights reserved. // enum Error: Swift.Error { case failed(message: String) }
17
59
0.678733
8f8591c3cd23590582f38941bb65f484a197796e
12,782
// // BIP32HDwallet.swift // web3swift // // Created by Alexander Vlasov on 09.01.2018. // Copyright © 2018 Bankex Foundation. All rights reserved. // import Foundation import BigInt import CryptoSwift extension UInt32 { public func serialize32() -> Data { let uint32 = UInt32(self) var bigEndian = uint32.bigEndian let count = MemoryLayout<UInt32>.size let bytePtr = withUnsafePointer(to: &bigEndian) { $0.withMemoryRebound(to: UInt8.self, capacity: count) { UnsafeBufferPointer(start: $0, count: count) } } let byteArray = Array(bytePtr) return Data(byteArray) } } public class HDNode { public struct HDversion{ public var privatePrefix: Data = Data.fromHex("0x0488ADE4")! public var publicPrefix: Data = Data.fromHex("0x0488B21E")! public init() { } } public var path: String? = "m" public var privateKey: Data? = nil public var publicKey: Data public var chaincode: Data public var depth: UInt8 public var parentFingerprint: Data = Data(repeating: 0, count: 4) public var childNumber: UInt32 = UInt32(0) public var isHardened:Bool { get { return self.childNumber >= (UInt32(1) << 31) } } public var index: UInt32 { get { if self.isHardened { return self.childNumber - (UInt32(1) << 31) } else { return self.childNumber } } } public var hasPrivate:Bool { get { return privateKey != nil } } init() { publicKey = Data() chaincode = Data() depth = UInt8(0) } public convenience init?(_ serializedString: String) { let data = Data(Base58.bytesFromBase58(serializedString)) self.init(data) } public init?(_ data: Data) { guard data.count == 82 else {return nil} let header = data[0..<4] var serializePrivate = false if header == HDNode.HDversion().privatePrefix { serializePrivate = true } depth = data[4..<5].bytes[0] parentFingerprint = data[5..<9] let cNum = data[9..<13].bytes childNumber = UnsafePointer(cNum).withMemoryRebound(to: UInt32.self, capacity: 1) { $0.pointee } chaincode = data[13..<45] if serializePrivate { privateKey = data[46..<78] guard let pubKey = Web3.Utils.privateToPublic(privateKey!, compressed: true) else {return nil} if pubKey[0] != 0x02 && pubKey[0] != 0x03 {return nil} publicKey = pubKey } else { publicKey = data[45..<78] } let hashedData = data[0..<78].sha256().sha256() let checksum = hashedData[0..<4] if checksum != data[78..<82] {return nil} } public init?(seed: Data) { guard seed.count >= 16 else {return nil} let hmacKey = "Bitcoin seed".data(using: .ascii)! let hmac:Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha512) guard let entropy = try? hmac.authenticate(seed.bytes) else {return nil} guard entropy.count == 64 else { return nil} let I_L = entropy[0..<32] let I_R = entropy[32..<64] chaincode = Data(I_R) let privKeyCandidate = Data(I_L) guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else {return nil} guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else {return nil} guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} publicKey = pubKeyCandidate privateKey = privKeyCandidate depth = 0x00 childNumber = UInt32(0) } private static var curveOrder = BigUInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)! public static var defaultPath: String = "m/44'/60'/0'/0" public static var defaultPathPrefix: String = "m/44'/60'/0'" public static var defaultPathMetamask: String = "m/44'/60'/0'/0/0" public static var defaultPathMetamaskPrefix: String = "m/44'/60'/0'/0" public static var hardenedIndexPrefix: UInt32 = (UInt32(1) << 31) } extension HDNode { public func derive (index: UInt32, derivePrivateKey:Bool, hardened: Bool = false) -> HDNode? { if derivePrivateKey { if self.hasPrivate { // derive private key when is itself extended private key var entropy:Array<UInt8> var trueIndex: UInt32 if index >= (UInt32(1) << 31) || hardened { trueIndex = index; if trueIndex < (UInt32(1) << 31) { trueIndex = trueIndex + (UInt32(1) << 31) } let hmac:Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha512) var inputForHMAC = Data() inputForHMAC.append(Data([UInt8(0x00)])) inputForHMAC.append(self.privateKey!) inputForHMAC.append(trueIndex.serialize32()) guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } guard ent.count == 64 else { return nil } entropy = ent } else { trueIndex = index let hmac:Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha512) var inputForHMAC = Data() inputForHMAC.append(self.publicKey) inputForHMAC.append(trueIndex.serialize32()) guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } guard ent.count == 64 else { return nil } entropy = ent } let I_L = entropy[0..<32] let I_R = entropy[32..<64] let cc = Data(I_R) let bn = BigUInt(Data(I_L)) if bn > HDNode.curveOrder { if trueIndex < UInt32.max { return self.derive(index:index+1, derivePrivateKey: derivePrivateKey, hardened:hardened) } return nil } let newPK = (bn + BigUInt(self.privateKey!)) % HDNode.curveOrder if newPK == BigUInt(0) { if trueIndex < UInt32.max { return self.derive(index:index+1, derivePrivateKey: derivePrivateKey, hardened:hardened) } return nil } guard let privKeyCandidate = newPK.serialize().setLengthLeft(32) else {return nil} guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else {return nil } guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else {return nil} guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} guard self.depth < UInt8.max else {return nil} let newNode = HDNode() newNode.chaincode = cc newNode.depth = self.depth + 1 newNode.publicKey = pubKeyCandidate newNode.privateKey = privKeyCandidate newNode.childNumber = trueIndex let fprint = RIPEMD160.hash(message: self.publicKey.sha256())[0..<4] newNode.parentFingerprint = fprint var newPath = String() if newNode.isHardened { newPath = self.path! + "/" newPath += String(newNode.index % HDNode.hardenedIndexPrefix) + "'" } else { newPath = self.path! + "/" + String(newNode.index) } newNode.path = newPath return newNode } else { return nil // derive private key when is itself extended public key (impossible) } } else { // deriving only the public key var entropy:Array<UInt8> // derive public key when is itself public key if index >= (UInt32(1) << 31) || hardened { return nil // no derivation of hardened public key from extended public key } else { let hmac:Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha512) var inputForHMAC = Data() inputForHMAC.append(self.publicKey) inputForHMAC.append(index.serialize32()) guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } guard ent.count == 64 else { return nil } entropy = ent } let I_L = entropy[0..<32] let I_R = entropy[32..<64] let cc = Data(I_R) let bn = BigUInt(Data(I_L)) if bn > HDNode.curveOrder { if index < UInt32.max { return self.derive(index:index+1, derivePrivateKey: derivePrivateKey, hardened:hardened) } return nil } guard let tempKey = bn.serialize().setLengthLeft(32) else {return nil} guard SECP256K1.verifyPrivateKey(privateKey: tempKey) else {return nil } guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: tempKey, compressed: true) else {return nil} guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} guard let newPublicKey = SECP256K1.combineSerializedPublicKeys(keys: [self.publicKey, pubKeyCandidate], outputCompressed: true) else {return nil} guard newPublicKey.bytes[0] == 0x02 || newPublicKey.bytes[0] == 0x03 else {return nil} guard self.depth < UInt8.max else {return nil} let newNode = HDNode() newNode.chaincode = cc newNode.depth = self.depth + 1 newNode.publicKey = pubKeyCandidate newNode.childNumber = index let fprint = RIPEMD160.hash(message: self.publicKey.sha256())[0..<4] newNode.parentFingerprint = fprint var newPath = String() if newNode.isHardened { newPath = self.path! + "/" newPath += String(newNode.index % HDNode.hardenedIndexPrefix) + "'" } else { newPath = self.path! + "/" + String(newNode.index) } newNode.path = newPath return newNode } } public func derive (path: String, derivePrivateKey: Bool = true) -> HDNode? { let components = path.components(separatedBy: "/") var currentNode:HDNode = self var firstComponent = 0 if path.hasPrefix("m") { firstComponent = 1 } for component in components[firstComponent ..< components.count] { var hardened = false if component.hasSuffix("'") { hardened = true } guard let index = UInt32(component.trimmingCharacters(in: CharacterSet(charactersIn: "'"))) else {return nil} guard let newNode = currentNode.derive(index: index, derivePrivateKey: derivePrivateKey, hardened: hardened) else {return nil} currentNode = newNode } return currentNode } public func serializeToString(serializePublic: Bool = true, version: HDversion = HDversion()) -> String? { guard let data = self.serialize(serializePublic: serializePublic, version: version) else {return nil} let encoded = Base58.base58FromBytes(data.bytes) return encoded } public func serialize(serializePublic: Bool = true, version: HDversion = HDversion()) -> Data? { var data = Data() if (!serializePublic && !self.hasPrivate) {return nil} if serializePublic { data.append(version.publicPrefix) } else { data.append(version.privatePrefix) } data.append(contentsOf: [self.depth]) data.append(self.parentFingerprint) data.append(self.childNumber.serialize32()) data.append(self.chaincode) if serializePublic { data.append(self.publicKey) } else { data.append(contentsOf: [0x00]) data.append(self.privateKey!) } let hashedData = data.sha256().sha256() let checksum = hashedData[0..<4] data.append(checksum) return data } }
42.606667
157
0.566422
f56fb0044c6663e3513df6a0aaf845a2aff75cf1
420
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "Perspective-Vapor", dependencies: [ // Vapor .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0") ], targets: [ .target(name: "App", dependencies: ["Vapor"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]) ] )
24.705882
74
0.578571
87713e32a90db128efaaffe4eaeca86752a7ade8
2,369
import Foundation import PDFjet /** * Example_41.swift * */ public class Example_41 { public init() throws { if let stream = OutputStream(toFileAtPath: "Example_41.pdf", append: false) { let pdf = PDF(stream) let page = Page(pdf, Letter.PORTRAIT) let f1 = Font(pdf, CoreFont.HELVETICA) f1.setSize(10.0) let f2 = Font(pdf, CoreFont.HELVETICA_BOLD) f2.setSize(10.0) let f3 = Font(pdf, CoreFont.HELVETICA_OBLIQUE) f3.setSize(10.0) var paragraphs = [Paragraph]() var paragraph = Paragraph() .add(TextLine(f1, "The small business centres offer practical resources, from step-by-step info on setting up your business to sample business plans to a range of business-related articles and books in our resource libraries.") .setUnderline(true)) .add(TextLine(f2, "This text is bold!") .setColor(Color.blue)) paragraphs.append(paragraph) paragraph = Paragraph() .add(TextLine(f1, "The centres also offer free one-on-one consultations with business advisors who can review your business plan and make recommendations to improve it.") .setUnderline(true)) .add(TextLine(f3, "This text is using italic font.") .setColor(Color.green)) paragraphs.append(paragraph) let text = Text(paragraphs) text.setLocation(70.0, 90.0) text.setWidth(500.0) // text.setSpaceBetweenTextLines(0.0) text.drawOn(page) let beginParagraphPoints = text.getBeginParagraphPoints() var paragraphNumber: Int = 1 for i in 0..<beginParagraphPoints.count { let point = beginParagraphPoints[i] TextLine(f1, String(paragraphNumber) + ".") .setLocation(point[0] - 30.0, point[1]) .drawOn(page) paragraphNumber += 1 } pdf.complete() } } } // End of Example_41.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = try Example_41() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_41 => \(time1 - time0)")
33.366197
247
0.571971
d5d6f04b9db87f097c3ea7489936e1a7f7634176
609
// // RatingTests.swift // TVMazeAppTests // // Created by marcos.brito on 02/09/21. // import XCTest @testable import TVMazeApp class RatingTests: XCTestCase { func testRating_codable_ShouldEncodeAndDecodeRating() throws { // Arrange let sut = Rating(average: 10) let decoder = JSONDecoder() // Act guard let data = sut.toData() else { XCTFail("Should return a valid data.") return } let decodedValue = try decoder.decode(Rating.self, from: data) // Assert XCTAssertEqual(sut, decodedValue) } }
20.3
70
0.609195
8f9a9aeec3dc2a3d98fb39e2a93a345db821cbf6
4,997
import Model import SwiftUI import Styleguide public struct SmallCard: View { private let title: String private let imageURL: URL? private let tag: Media private let date: Date private let isFavorited: Bool private let tapAction: () -> Void private let tapFavoriteAction: () -> Void public init( title: String, imageURL: URL?, tag: Media, date: Date, isFavorited: Bool, tapAction: @escaping () -> Void, tapFavoriteAction: @escaping () -> Void ) { self.title = title self.imageURL = imageURL self.tag = tag self.date = date self.isFavorited = isFavorited self.tapAction = tapAction self.tapFavoriteAction = tapFavoriteAction } public var body: some View { VStack(alignment: .leading, spacing: 16) { ImageView( imageURL: imageURL, placeholder: .noImage, placeholderSize: .small ) .aspectRatio(163/114, contentMode: .fit) .scaledToFill() VStack(alignment: .leading, spacing: 12) { VStack(alignment: .leading, spacing: 4) { Text(title) .font(.subheadline) .foregroundColor(AssetColor.Base.primary.color) .lineLimit(3) .frame(maxHeight: .infinity, alignment: .top) Text(date.formatted) .font(.caption) .foregroundColor(AssetColor.Base.tertiary.color) } HStack(spacing: 8) { Tag(type: tag) { // do something if needed } Spacer() Button(action: tapFavoriteAction, label: { let image = isFavorited ? AssetImage.iconFavorite.image : AssetImage.iconFavoriteOff.image image .renderingMode(.template) .foregroundColor(AssetColor.primary.color) }) } } } .padding(8) .background(Color.clear) .onTapGesture(perform: tapAction) } } public struct SmallCard_Previews: PreviewProvider { public static var previews: some View { Group { SmallCard( title: "タイトルタイトルタイトルタイトルタイタイトルタイトルタイトルタイトルタイト...", imageURL: URL(string: ""), tag: .droidKaigiFm, date: Date(timeIntervalSince1970: 0), isFavorited: false, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .light) SmallCard( title: "タイトルタイトルタイトルタイトルタイタイトルタイトルタイトルタイトルタイト...", imageURL: URL(string: ""), tag: .medium, date: Date(timeIntervalSince1970: 0), isFavorited: true, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .light) SmallCard( title: "タイトル", imageURL: URL(string: ""), tag: .youtube, date: Date(timeIntervalSince1970: 0), isFavorited: true, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .light) SmallCard( title: "タイトルタイトルタイトルタイトルタイタイトルタイトルタイトルタイトルタイト...", imageURL: URL(string: ""), tag: .droidKaigiFm, date: Date(timeIntervalSince1970: 0), isFavorited: false, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .dark) SmallCard( title: "タイトルタイトルタイトルタイトルタイタイトルタイトルタイトルタイトルタイト...", imageURL: URL(string: ""), tag: .medium, date: Date(timeIntervalSince1970: 0), isFavorited: true, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .dark) SmallCard( title: "タイトル", imageURL: URL(string: ""), tag: .youtube, date: Date(timeIntervalSince1970: 0), isFavorited: true, tapAction: {}, tapFavoriteAction: {} ) .frame(width: 179, height: 278) .environment(\.colorScheme, .dark) } .previewLayout(.sizeThatFits) } }
32.23871
114
0.477887
239fc1bc15d2f971c97ca3beebb04a12473ba00e
350
// // ActionHeader.swift // Pods-TableDirector_Example // // Created by Aleksandr Lavrinenko on 01.05.2020. // import Foundation /// Header that can send actions to delegate public protocol ActionHeader: ConfigurableHeaderFooter, TableItemActionable { } /// Footer that can send actions to delegate public typealias ActionFooter = ActionHeader
23.333333
79
0.777143
184b22358ff0e87a23d61a2d2f6d3abf897b27dd
412
// // NSManageObject+Extension.swift // CoreDataExtensions // // Created by YZF on 5/7/17. // Copyright © 2017年 Xiaoye. All rights reserved. // import Foundation import CoreData extension NSManagedObject { open override func setValue(_ value: Any?, forUndefinedKey key: String) { print("the entity \(type(of: self)) is not key value coding-compliant for the key \"\(key)\".") } }
21.684211
103
0.669903
1ef9433122e52449a3090ad88d9e07608626fd2b
153
public class MultiplyBlend: BasicOperation { public init() { super.init(fragmentShader:MultiplyBlendFragmentShader, numberOfInputs:2) } }
30.6
80
0.738562
e420255aa7e79c2881577c54e09517d9b42a9f68
881
// 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. // // This is a GENERATED FILE, changes made here WILL BE LOST. // import Foundation public final class TezosSigner { public static func sign(input: TW_Tezos_Proto_SigningInput) -> TW_Tezos_Proto_SigningOutput { let inputData = TWDataCreateWithNSData(try! input.serializedData()) defer { TWDataDelete(inputData) } let resultData = TWDataNSData(TWTezosSignerSign(inputData)) return try! TW_Tezos_Proto_SigningOutput(serializedData: resultData) } let rawValue: OpaquePointer init(rawValue: OpaquePointer) { self.rawValue = rawValue } }
28.419355
97
0.713961
093b00935fc2b4ee880cb523821fc8a3f013efdb
1,122
// // ViewController.swift // tipi // // Created by Riya Agarwal on 1/20/20. // Copyright © 2020 RAgarwal. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { //get the bill amount let bill = Double(billField.text!) ?? 0 //calculate the tip and total let tipPercentages = [0.15, 0.18, 0.2] let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] let total = bill + tip //update the tip and total label tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } }
25.5
80
0.61943
fb44cf4b08db701945005fb66db151013f2a876c
4,340
// // OSCAddress.swift // CoreOSC // // Created by Sam Smallman on 26/07/2021. // Copyright © 2021 Sam Smallman. https://github.com/SammySmallman // // 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 Foundation /// An object that represents the full path to an OSC Method in an OSC Address Space. public struct OSCAddress: Hashable, Equatable { /// The full path to an OSC Method. public let fullPath: String /// The names of all the containers, in order, along the path from the root of the tree to the OSC Method. public let parts: [String] /// The name of the OSC Method the address is pointing to. public let methodName: String /// An OSC Address. /// /// An OSC Address begins with the character ‘/’ followed by the symbolic ASCII names of all the containers, /// in order, along the path from the root of the tree to the OSC Method, separated by forward slash characters, /// followed by the name of the OSC Method. /// /// Printable ASCII characters not allowed in names of OSC Methods or OSC Containers: /// - ' ' - Space /// - \# - Hash /// - \* - Asterisk /// - , - Comma /// - / - Forward Slash /// - ? - Question Mark /// - [ - Open Bracket /// - ] - Close Bracket /// - { - Open Curly Brace /// - } - Close Curly Brace /// /// - Parameter address: The full path to an OSC Method. /// - Throws: `OSCAddressError` if the format of the given address is invalid. public init(_ address: String) throws { let regex = "^\\/(?:(?![ #*,?\\[\\]\\{\\}])[\\x00-\\x7F])+$" if NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: address) { self.fullPath = address var addressParts = address.components(separatedBy: "/") addressParts.removeFirst() self.parts = addressParts self.methodName = addressParts.last ?? "" } else { throw OSCAddressError.invalidAddress } } /// Evaluate an OSC Address. /// - Parameter address: A `String` to be validated. /// - Returns: A `Result` that represents either the given string is valid, returning success, /// or that the given string is invalid returning a failure containing the `OSCAddressError`. public static func evaluate(with address: String) -> Result<String, OSCAddressError> { guard address.hasPrefix("/") else { return .failure(.forwardSlash) } for character in address { guard character.isASCII == true else { return .failure(.ascii) } guard character != " " else { return .failure(.space) } guard character != "#" else { return .failure(.hash) } guard character != "*" else { return .failure(.asterisk) } guard character != "," else { return .failure(.comma) } guard character != "?" else { return .failure(.questionMark) } guard character != "[" else { return .failure(.openBracket) } guard character != "]" else { return .failure(.closeBracket) } guard character != "{" else { return .failure(.openCurlyBrace) } guard character != "}" else { return .failure(.closeCurlyBrace) } } return .success(address) } }
45.208333
116
0.641244
46eb1186ff85261d2c3ab310f9a7abbc7040838f
677
// // ClimbState.swift // ClimbBar // // Created by Shichimitoucarashi on 5/10/19. // Copyright © 2019 Shichimitoucarashi. All rights reserved. // import UIKit public class State { public var origin: CGPoint? public var size: CGSize? public var conf: Configuration? public var pbState: CGFloat = 0 public var defaultContentOffset: CGPoint = .zero public var defaultInset: UIEdgeInsets = .zero var currentState: CGFloat = 0 init(configurations: Configuration, origin: CGPoint, size: CGSize) { conf = configurations self.origin = origin self.size = size pbState = conf!.compact } }
22.566667
61
0.651403
db58396b96e747c4bacf7627deff7ae8b883ffb3
1,168
// // EKEvent+Extensions.swift // Clendar // // Created by Vinh Nguyen on 10/23/20. // Copyright © 2020 Vinh Nguyen. All rights reserved. // import EventKit import Foundation extension EKEvent { func durationText(startDateOnly: Bool = false) -> String { if isAllDay { return NSLocalizedString("All day", comment: "") } else if startDateOnly { let startDateString = startDate.toHourAndMinuteString return startDateString } else { let startDateString = startDate.toHourAndMinuteString let endDateString = endDate.toHourAndMinuteString return startDate != endDate ? "\(startDateString) - \(endDateString)" : startDateString } } } extension EKEventStore { var selectableCalendarsFromSettings: [EKCalendar] { let savedCalendarIDs = UserDefaults.savedCalendarIDs return calendars(for: .event) .filter { calendar in if savedCalendarIDs.isEmpty { return true } return savedCalendarIDs.contains(calendar.calendarIdentifier) } } }
28.487805
77
0.619007
72cc39a062d91fcb7089d15b22786ba15ce203bd
3,231
// // PodcastViewModel.swift // WPRK-iOS // // Created by Mwai Banda on 2/26/22. // import Foundation import SwiftUI final class PodcastViewModel: ObservableObject { var contentService: ContentService var group: DispatchGroup? @Published var podcasts = [Podcast]() @Published var featured = [Episode]() @Published var episodes = [Episode]() @Published var selectedFeatured: Podcast? = nil init(contentService: ContentService, group: DispatchGroup? = nil){ self.contentService = contentService self.group = group getPodcasts { self.selectedFeatured = $0 } } private func fetchEpisodes(showID: String, onCompletion: @escaping ([Episode]) -> Void){ contentService.getEpisodes(showID: showID) { result in switch(result){ case .success(let episodes): onCompletion(episodes) case .failure(let err): print(err.localizedDescription) } } } private func fetchPodcasts(onCompletion: @escaping ([Podcast], Podcast) -> Void) { contentService.getPodcasts { result in switch(result) { case .success(let podcasts): guard let firstPodcast = podcasts.first else { return } onCompletion(podcasts, firstPodcast) case .failure(let error): print(error.localizedDescription ) } } } func getFeatured(showID: String) { if let group = group { group.enter() featured.removeAll() fetchEpisodes(showID: showID) { eps in DispatchQueue.main.async { eps.sorted( by: { return $0.attributes.number > $1.attributes.number } ).forEach { episode in if self.featured.count < 4 { self.featured.append(episode) } } } } group.leave() } else { fetchEpisodes(showID: showID) { eps in eps.forEach { episode in if self.featured.count < 4 { self.featured.append(episode) } } } } } func getPodcasts(onCompletion: @escaping (Podcast) -> Void){ if let group = group { group.enter() fetchPodcasts { podcasts, firstPodcast in DispatchQueue.main.async { self.podcasts = podcasts self.getFeatured(showID: firstPodcast.id) onCompletion(firstPodcast) } } group.leave() } else { fetchPodcasts { podcasts, firstPodcast in self.podcasts = podcasts self.getFeatured(showID: firstPodcast.id) onCompletion(firstPodcast) } } } func getEpisodes(showID: String) { self.episodes.removeAll() fetchEpisodes(showID: showID) { eps in self.episodes.append(contentsOf: eps) } } }
31.067308
92
0.518415
2203d3946a7cc3aad6ec0ec1f4423fef6fb18a51
4,742
// // ViewController.swift // my-test-chat // // Created by Shindarev Nikita on 20.10.2021. // import UIKit class ProfileViewController: UIViewController, UIAlertViewDelegate{ // MARK: UIFields @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var profileView: UIView! @IBOutlet weak var btnEdit: UIButton! @IBOutlet weak var btnSave: UIButton! @IBOutlet weak var lblInit: UILabel! @IBOutlet weak var lblFullName: UILabel! var imagePicker = UIImagePickerController() // MARK: ================== LIFECYCLE EVENTS ======================= override func viewDidLoad() { super.viewDidLoad() profileView.layer.cornerRadius = profileView.bounds.width / 2 imageView.layer.cornerRadius = profileView.bounds.width / 2 self.lblFullName.text = "Nikita Shindarev" self.lblInit.text = self.getInitials(fullName: lblFullName.text ?? "AA") self.lblInit.layer.zPosition = 1 self.profileView.bringSubviewToFront(lblInit) self.lblInit.isHidden = false btnSave.layer.cornerRadius = 14 imagePicker.delegate = self } // MARK: ================== UI EVENTS ======================= @IBAction func onEditTapped(_ sender: UIButton) { self.btnEdit.isUserInteractionEnabled = true let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.switchImagePicker(.camera) })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.switchImagePicker(.photoLibrary) })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } // MARK: ================== SUPPORT METHODS ======================= func switchImagePicker (_ type: UIImagePickerController.SourceType){ switch type{ case .camera: if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)) { self.imagePicker.sourceType = UIImagePickerController.SourceType.camera self.imagePicker.allowsEditing = true } else { let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } case .photoLibrary: if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary)) { self.imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary self.imagePicker.allowsEditing = true } else { let alert = UIAlertController(title: "Warning", message: "You don't have photo library access", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } default: return } self.present(self.imagePicker, animated: true, completion: nil) } func getInitials(fullName: String) -> String? { return fullName.components(separatedBy: " ") .reduce("") { ($0 == "" ? "" : $0.first) + $1.first} } } // MARK: ================== UIImagePickerController DELEGATE METHODS ======================= extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // The info dictionary may contain multiple representations of the image. You want to use the original. guard let selectedImage = info[.originalImage] as? UIImage else { fatalError("Expected a dictionary containing an image, but was provided the following: \(info)") } // Set photoImageView to display the selected image. imageView.image = selectedImage // Dismiss the picker. dismiss(animated: true, completion: nil) self.lblInit.isHidden = true } } // MARK: ================== FullName --> Initials ======================= extension String { public var first: String { return String(self[startIndex]) } }
36.476923
144
0.612822
11ac391244ab5d11ed4e74b0fdaa29d9b47abf27
864
// // DateTests.swift // VergeCore // // Created by muukii on 2020/01/13. // Copyright © 2020 muukii. All rights reserved. // import Foundation import XCTest import Verge final class CounterTests: XCTestCase { func testCounter() { var counter = NonAtomicVersionCounter() for _ in 0..<100 { counter.markAsUpdated() } XCTAssertEqual(counter.version, 100) } func testCounterPerformance() { var counter = NonAtomicVersionCounter() if #available(iOS 13.0, *) { measure(metrics: [XCTCPUMetric()]) { counter.markAsUpdated() } } else { // Fallback on earlier versions } } func testGenDatePerformance() { measure { _ = Date() } } func testGenCFDatePerformance() { measure { _ = CFAbsoluteTimeGetCurrent() } } }
16
49
0.59375
9cdb681e27e1baead4e6afd07eed094426008e52
6,287
// `XCTest` is not supported for watchOS Simulator. #if !os(watchOS) import Foundation import XCTest #if canImport(iOSDFULibrary) @testable import iOSDFULibrary #elseif canImport(NordicDFU) @testable import NordicDFU #endif class Hex2BinConverterTests: XCTestCase { // MARK: - Real HEX files func testSoftDevice() { performTest(for: "s110_nrf51822_6.2.1_softdevice", withMbrSize: 0x1000) } func testBlinky() { performTest(for: "blinky_s110_v7_0_0_sdk_v7_1") } func testHRM() { performTest(for: "ble_app_hrm_dfu_s110_v8_0_0_sdk_v8_0") } func testBootloader() { performTest(for: "sdk_15_2_bootloader") } func testOnlySoftDevice() { // This HEX file contains SD+BL, but they are separated by a blank region. // The second jump (0x04) is from 0001 to 0003 which is not supported. // Only the SD will then be converted to BIN. performTest(for: "nrf51422_sdk_5.2_sd_bl", withMbrSize: 0x1000) } // MARK: - Special cases func testSimpleHex() { let hex = """ :02000000010206 :02000200030480 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x01, 0x02, 0x03, 0x04])) } func testPrematureEndOfFile() { let hex = """ :02000000010206 :00000001FF :02000200030480 """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x01, 0x02])) } func testMbr() { let hex = """ :02000000010206 :02000200030480 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex, mbrSize: 2) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x03, 0x04])) } func testMbrInsideRecord() { let hex = """ :02000000010206 :02000200030480 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex, mbrSize: 1) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x02, 0x03, 0x04])) } func testShortRecordLength() { let hex = """ :020000040001F9 :02600000010206 :02600200030480 :0400000500016000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x01, 0x02, 0x03, 0x04])) } func testInvalidRecordLength() { let hex = """ :020000040001F9 :0460000008280020F56001000F6101001161010006 :106020000000000000000000000000000000000080 :0400000500016000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNil(bin) } func testGapInHex() { let hex = """ :020000040001F9 :1060000008280020F56001000F6101001161010006 :106020000000000000000000000000000000000080 :0400000500016000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x08, 0x28, 0x00, 0x20, 0xF5, 0x60, 0x01, 0x00, 0x0F, 0x61, 0x01, 0x00, 0x11, 0x61, 0x01, 0x00])) } func testBigJumpInHex() { let hex = """ :020000040001F9 :1060000008280020F56001000F6101001161010006 :020000040003F9 :100000000000000000000000000000000000000080 :0400000500016000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x08, 0x28, 0x00, 0x20, 0xF5, 0x60, 0x01, 0x00, 0x0F, 0x61, 0x01, 0x00, 0x11, 0x61, 0x01, 0x00])) } func testExtendedLinearAddressRecord() { let hex = """ :020000040000F9 :10FFF00008280020F56001000F6101001161010006 :020000040001F9 :100000000000000000000000000000000000000080 :0400000500016000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x08, 0x28, 0x00, 0x20, 0xF5, 0x60, 0x01, 0x00, 0x0F, 0x61, 0x01, 0x00, 0x11, 0x61, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) } func testExtendedSegmentAddressRecord() { let hex = """ :020000021000F9 :10FFF00008280020F56001000F6101001161010006 :020000022000F9 :100000000000000000000000000000000000000080 :020000031000D5 :00000001FF """.data(using: .ascii)! let bin = IntelHex2BinConverter.convert(hex) XCTAssertNotNil(bin) XCTAssertEqual(bin, Data([0x08, 0x28, 0x00, 0x20, 0xF5, 0x60, 0x01, 0x00, 0x0F, 0x61, 0x01, 0x00, 0x11, 0x61, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) } // MARK: - Helper methods private func performTest(for name: String, withMbrSize mbrSize: UInt32 = 0) { var baseURL = URL(fileURLWithPath: #file) baseURL.deleteLastPathComponent() baseURL.appendPathComponent("TestFirmwares") let url = baseURL.appendingPathComponent(name + ".hex") XCTAssertNotNil(url) let testUrl = baseURL.appendingPathComponent(name + ".bin") XCTAssertNotNil(testUrl) var data: Data! XCTAssertNoThrow(data = try Data(contentsOf: url)) XCTAssertNotNil(data) var testData: Data! XCTAssertNoThrow(testData = try Data(contentsOf: testUrl)) XCTAssertNotNil(testData) let bin = IntelHex2BinConverter.convert(data, mbrSize: mbrSize) XCTAssertNotNil(bin) XCTAssertEqual(bin, testData) } } #endif
30.818627
131
0.603149
90d0352b3e14a013697216618b968bae8046cb91
256
// // Logger.swift // PersonalDictionary // // Created by Maxim Ivanov on 07.10.2021. // public protocol Logger { func networkRequestStart(_ requestName: String) func networkRequestSuccess(_ requestName: String) func log(error: Error) }
16
53
0.703125
6a3b0a94d1daad17664d947aac23d8a12e3b8588
1,028
// // RegexExpressionMatcher.swift // Swifternalization // // Created by Tomasz Szulc on 27/06/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import Foundation /** Type that represents pattern with regular expression. */ internal typealias RegexPattern = String /** Matcher is responsible for matching expressions that contains regular expressions. */ struct RegexExpressionMatcher: ExpressionMatcher { /** Expression pattern with regular expression inside. */ let pattern: RegexPattern /** Initializes matcher. :param: pattern Expression pattern with regexp inside. */ init(pattern: RegexPattern) { self.pattern = pattern } /** Validates value by matching it to the pattern it contains. :param: val value that will be matched. :returns: `true` if value matches pattern, otherwise `false`. */ func validate(val: String) -> Bool { return (Regex.firstMatchInString(val, pattern: pattern) != nil) } }
23.363636
71
0.677043
8f6e3e63c3b08ec62772ad72c1998054ccfd5285
3,896
// // View.swift // RSSNews // // Created by Артём Горюнов on 28/05/2019. // Copyright © 2019 Артём Горюнов. All rights reserved. // import Foundation import UIKit import Kingfisher class NewsTableViewController : UITableViewController { let viewModel = NewsViewModel() let identifier = "RSSItemCell" override func viewWillAppear(_ animated: Bool) { self.refreshControl?.beginRefreshing() } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.prefersLargeTitles = true self.title = "RSS Feed" tableView.dataSource = nil tableView.delegate = nil tableView.separatorStyle = .none tableView.rowHeight = UITableView.automaticDimension tableView.register(UINib(nibName: "RSSItemCell", bundle: nil), forCellReuseIdentifier: identifier) self.refreshControl = UIRefreshControl() let refreshControl = self.refreshControl! refreshControl.backgroundColor = UIColor(white: 0.98, alpha: 1.0) refreshControl.tintColor = UIColor.darkGray refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged) self.refresh() viewModel.observableNews.bind(to: tableView.rx.items(cellIdentifier: identifier, cellType: RSSItemCell.self)) { ( ip, item, cell) in cell.news = item cell.contentView.backgroundColor = self.tableView.backgroundColor }.disposed(by: viewModel.disposeBag) tableView.rx.itemSelected.subscribe(onNext: { (ip) in self.viewModel.changeValue(ip: ip) self.tableView.scrollToRow(at: ip, at: .top, animated: false) }).disposed(by: viewModel.disposeBag) tableView.rx.setDelegate(self).disposed(by: viewModel.disposeBag) } @objc func refresh() { DispatchQueue.global(qos: .default).async { [weak self] in guard let self = self else { return } self.viewModel.bindData() DispatchQueue.main.async { self.refreshControl?.endRefreshing() } } } } extension NewsTableViewController { override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let item = viewModel.observableNews.value[indexPath.row] let descriptionText = item.description.replacingOccurrences(of: "<[^>]+>s", with: "", options: .regularExpression) let size = CGSize(width: view.frame.width - 32, height: 1000) let titleFrame = NSString(string: item.title).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], context: nil) let sourceFrame = NSString(string: item.author ?? "").boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], context: nil) let descFrame = NSString(string: descriptionText).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)], context: nil) let dateFrame = NSString(string: item.pubDate.toStr()).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)], context: nil) let imageViewHeight = ((self.view.frame.width / 3) * 2) + 48 let descHeight = item.isSelected ? descFrame.height : 0 let height = titleFrame.height + sourceFrame.height + dateFrame.height + descHeight + imageViewHeight return height } }
39.755102
196
0.664528
f7c46f8f5ee901228d5919ed7f8830ab2292f06f
43,555
import UIKit import WMF import CocoaLumberjackSwift @objc(WMFArticleViewController) class ArticleViewController: ViewController, HintPresenting { enum ViewState { case initial case loading case reloading case loaded case error } internal lazy var toolbarController: ArticleToolbarController = { return ArticleToolbarController(toolbar: toolbar, delegate: self) }() /// Article holds article metadata (displayTitle, description, etc) and user state (isSaved, viewedDate, viewedFragment, etc) internal var article: WMFArticle internal var mediaList: MediaList? /// Use separate properties for URL and language since they're optional on WMFArticle and to save having to re-calculate them @objc public var articleURL: URL let articleLanguage: String /// Set by the state restoration system /// Scroll to the last viewed scroll position in this case /// Also prioritize pulling data from cache (without revision/etag validation) so the user sees the article as quickly as possible var isRestoringState: Bool = false /// Set internally to wait for content size changes to chill before restoring the scroll offset var isRestoringStateOnNextContentSizeChange: Bool = false /// Called when initial load starts @objc public var loadCompletion: (() -> Void)? /// Called when initial JS setup is complete @objc public var initialSetupCompletion: (() -> Void)? internal let schemeHandler: SchemeHandler internal let dataStore: MWKDataStore private let cacheController: ArticleCacheController let surveyTimerController: ArticleSurveyTimerController var session: Session { return dataStore.session } var configuration: Configuration { return dataStore.configuration } private var authManager: WMFAuthenticationManager { return dataStore.authenticationManager } internal lazy var fetcher: ArticleFetcher = ArticleFetcher(session: session, configuration: configuration) @available(iOS 13.0, *) lazy var articleAsLivingDocController = ArticleAsLivingDocController(delegate: self, surveyController: SurveyAnnouncementsController.shared, abTestsController: dataStore.abTestsController) private var leadImageHeight: CGFloat = 210 private var contentSizeObservation: NSKeyValueObservation? = nil /// Current ETag of the web content response. Used to verify when content has changed on the server. var currentETag: String? /// Used to delay reloading the web view to prevent `UIScrollView` jitter fileprivate var shouldPerformWebRefreshAfterScrollViewDeceleration = false lazy var refreshControl: UIRefreshControl = { let rc = UIRefreshControl() rc.addTarget(self, action: #selector(refresh), for: .valueChanged) return rc }() lazy var referenceWebViewBackgroundTapGestureRecognizer: UITapGestureRecognizer = { let tapGR = UITapGestureRecognizer(target: self, action: #selector(tappedWebViewBackground)) tapGR.delegate = self webView.scrollView.addGestureRecognizer(tapGR) tapGR.isEnabled = false return tapGR }() @objc init?(articleURL: URL, dataStore: MWKDataStore, theme: Theme, schemeHandler: SchemeHandler? = nil) { guard let article = dataStore.fetchOrCreateArticle(with: articleURL) else { return nil } let cacheController = dataStore.cacheController.articleCache self.articleURL = articleURL self.articleLanguage = articleURL.wmf_language ?? Locale.current.languageCode ?? "en" self.article = article self.dataStore = dataStore self.schemeHandler = schemeHandler ?? SchemeHandler(scheme: "app", session: dataStore.session) self.cacheController = cacheController self.surveyTimerController = ArticleSurveyTimerController(articleURL: articleURL, surveyController: SurveyAnnouncementsController.shared) super.init(theme: theme) } deinit { NotificationCenter.default.removeObserver(self) contentSizeObservation?.invalidate() messagingController.removeScriptMessageHandler() } // MARK: WebView static let webProcessPool = WKProcessPool() private(set) var messagingController = ArticleWebMessagingController() lazy var webViewConfiguration: WKWebViewConfiguration = { let configuration = WKWebViewConfiguration() configuration.processPool = ArticleViewController.webProcessPool configuration.setURLSchemeHandler(schemeHandler, forURLScheme: schemeHandler.scheme) return configuration }() lazy var webView: WKWebView = { return WMFWebView(frame: view.bounds, configuration: webViewConfiguration) }() private var verticalOffsetPercentageToRestore: CGFloat? // MARK: HintPresenting var hintController: HintController? // MARK: Find In Page var findInPage = ArticleFindInPageState() // MARK: Responder chain override var canBecomeFirstResponder: Bool { return findInPage.view != nil } override var inputAccessoryView: UIView? { return findInPage.view } // MARK: Lead Image @objc func userDidTapLeadImage() { showLeadImage() } func loadLeadImage(with leadImageURL: URL) { leadImageHeightConstraint.constant = leadImageHeight leadImageView.wmf_setImage(with: leadImageURL, detectFaces: true, onGPU: true, failure: { (error) in DDLogError("Error loading lead image: \(error)") }) { self.updateLeadImageMargins() self.updateArticleMargins() if #available(iOS 13.0, *) { /// see implementation in `extension ArticleViewController: UIContextMenuInteractionDelegate` let interaction = UIContextMenuInteraction(delegate: self) self.leadImageView.addInteraction(interaction) } } } lazy var leadImageLeadingMarginConstraint: NSLayoutConstraint = { return leadImageView.leadingAnchor.constraint(equalTo: leadImageContainerView.leadingAnchor) }() lazy var leadImageTrailingMarginConstraint: NSLayoutConstraint = { return leadImageContainerView.trailingAnchor.constraint(equalTo: leadImageView.trailingAnchor) }() lazy var leadImageHeightConstraint: NSLayoutConstraint = { return leadImageContainerView.heightAnchor.constraint(equalToConstant: 0) }() lazy var leadImageView: UIImageView = { let imageView = NoIntrinsicContentSizeImageView(frame: .zero) imageView.isUserInteractionEnabled = true imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.accessibilityIgnoresInvertColors = true let tapGR = UITapGestureRecognizer(target: self, action: #selector(userDidTapLeadImage)) imageView.addGestureRecognizer(tapGR) return imageView }() lazy var leadImageBorderHeight: CGFloat = { let scale = UIScreen.main.scale return scale > 1 ? 0.5 : 1 }() lazy var leadImageContainerView: UIView = { let height: CGFloat = 10 let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: height)) containerView.clipsToBounds = true containerView.translatesAutoresizingMaskIntoConstraints = false let borderView = UIView(frame: CGRect(x: 0, y: height - leadImageBorderHeight, width: 1, height: leadImageBorderHeight)) borderView.backgroundColor = UIColor(white: 0, alpha: 0.2) borderView.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] leadImageView.frame = CGRect(x: 0, y: 0, width: 1, height: height - leadImageBorderHeight) containerView.addSubview(leadImageView) containerView.addSubview(borderView) return containerView }() lazy var refreshOverlay: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.alpha = 0 view.backgroundColor = .black view.isUserInteractionEnabled = true return view }() override func updateViewConstraints() { super.updateViewConstraints() updateLeadImageMargins() } func updateLeadImageMargins() { let doesArticleUseLargeMargin = (tableOfContentsController.viewController.displayMode == .inline && !tableOfContentsController.viewController.isVisible) var marginWidth: CGFloat = 0 if doesArticleUseLargeMargin { marginWidth = articleHorizontalMargin } leadImageLeadingMarginConstraint.constant = marginWidth leadImageTrailingMarginConstraint.constant = marginWidth } // MARK: Previewing public var articlePreviewingDelegate: ArticlePreviewingDelegate? // MARK: Layout override func scrollViewInsetsDidChange() { super.scrollViewInsetsDidChange() updateTableOfContentsInsets() } override func viewLayoutMarginsDidChange() { super.viewLayoutMarginsDidChange() updateArticleMargins() } internal func updateArticleMargins() { let defaultUpdateBlock = { self.messagingController.updateMargins(with: self.articleMargins, leadImageHeight: self.leadImageHeightConstraint.constant) } if #available(iOS 13.0, *) { if (articleAsLivingDocController.shouldAttemptToShowArticleAsLivingDoc) { messagingController.customUpdateMargins(with: articleMargins, leadImageHeight: self.leadImageHeightConstraint.constant) } else { defaultUpdateBlock() } } else { defaultUpdateBlock() } updateLeadImageMargins() } internal func stashOffsetPercentage() { let offset = webView.scrollView.verticalOffsetPercentage // negative and 0 offsets make small errors in scrolling, allow it to automatically handle those cases if offset > 0 { verticalOffsetPercentageToRestore = offset } } private func restoreOffsetPercentageIfNecessary() { guard let verticalOffsetPercentage = verticalOffsetPercentageToRestore else { return } verticalOffsetPercentageToRestore = nil webView.scrollView.verticalOffsetPercentage = verticalOffsetPercentage } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { stashOffsetPercentage() super.viewWillTransition(to: size, with: coordinator) let marginUpdater: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { _ in self.updateArticleMargins() } coordinator.animate(alongsideTransition: marginUpdater) } // MARK: Loading var state: ViewState = .initial { didSet { switch state { case .initial: break case .reloading: fallthrough case .loading: fakeProgressController.start() case .loaded: fakeProgressController.stop() case .error: fakeProgressController.stop() } } } lazy private var fakeProgressController: FakeProgressController = { let progressController = FakeProgressController(progress: navigationBar, delegate: navigationBar) progressController.delay = 0.0 return progressController }() required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { setup() super.viewDidLoad() setupToolbar() // setup toolbar needs to be after super.viewDidLoad because the superview owns the toolbar apply(theme: theme) setupForStateRestorationIfNecessary() surveyTimerController.timerFireBlock = { [weak self] result in self?.showSurveyAnnouncementPanel(surveyAnnouncementResult: result) } if #available(iOS 14.0, *) { self.navigationItem.backButtonTitle = articleURL.wmf_title self.navigationItem.backButtonDisplayMode = .generic } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableOfContentsController.setup(with: traitCollection) toolbarController.update() loadIfNecessary() startSignificantlyViewedTimer() surveyTimerController.viewWillAppear(withState: state) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) /// When jumping back to an article via long pressing back button (on iOS 14 or above), W button disappears. Couldn't find cause. It disappears between `viewWillAppear` and `viewDidAppear`, as setting this on the `viewWillAppear`doesn't fix the problem. If we can find source of this bad behavior, we can remove this next line. setupWButton() guard isFirstAppearance else { return } showAnnouncementIfNeeded() isFirstAppearance = false } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) tableOfContentsController.update(with: traitCollection) toolbarController.update() } override func wmf_removePeekableChildViewControllers() { super.wmf_removePeekableChildViewControllers() addToHistory() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cancelWIconPopoverDisplay() saveArticleScrollPosition() stopSignificantlyViewedTimer() surveyTimerController.viewWillDisappear(withState: state) } // MARK: Article load var articleLoadWaitGroup: DispatchGroup? func loadIfNecessary() { guard state == .initial else { return } load() } func load() { state = .loading setupPageContentServiceJavaScriptInterface { let cachePolicy: WMFCachePolicy? = self.isRestoringState ? .foundation(.returnCacheDataElseLoad) : nil self.loadPage(cachePolicy: cachePolicy) } } /// Waits for the article and article summary to finish loading (or re-loading) and performs post load actions func setupArticleLoadWaitGroup() { assert(Thread.isMainThread) guard articleLoadWaitGroup == nil else { return } articleLoadWaitGroup = DispatchGroup() articleLoadWaitGroup?.enter() // will leave on setup complete articleLoadWaitGroup?.notify(queue: DispatchQueue.main) { [weak self] in guard let self = self else { return } if #available(iOS 13.0, *) { self.articleAsLivingDocController.articleContentFinishedLoading() } self.setupFooter() self.shareIfNecessary() self.articleLoadWaitGroup = nil } guard let key = article.key else { return } articleLoadWaitGroup?.enter() // async to allow the page network requests some time to go through DispatchQueue.main.async { let cachePolicy: URLRequest.CachePolicy? = self.state == .reloading ? .reloadRevalidatingCacheData : nil self.dataStore.articleSummaryController.updateOrCreateArticleSummaryForArticle(withKey: key, cachePolicy: cachePolicy) { (article, error) in defer { self.articleLoadWaitGroup?.leave() self.updateMenuItems() } guard let article = article else { return } self.article = article // Handle redirects guard let newKey = article.key, newKey != key, let newURL = article.url else { return } self.articleURL = newURL self.addToHistory() } } } func loadPage(cachePolicy: WMFCachePolicy? = nil, revisionID: UInt64? = nil) { defer { callLoadCompletionIfNecessary() } guard let request = try? fetcher.mobileHTMLRequest(articleURL: articleURL, revisionID: revisionID, scheme: schemeHandler.scheme, cachePolicy: cachePolicy, isPageView: true) else { showGenericError() state = .error return } if #available(iOS 13.0, *) { articleAsLivingDocController.articleContentWillBeginLoading(traitCollection: traitCollection, theme: theme) } webView.load(request) } func syncCachedResourcesIfNeeded() { guard let groupKey = articleURL.wmf_databaseKey else { return } fetcher.isCached(articleURL: articleURL) { [weak self] (isCached) in guard let self = self, isCached else { return } self.cacheController.syncCachedResources(url: self.articleURL, groupKey: groupKey) { (result) in switch result { case .success(let itemKeys): DDLogDebug("successfully synced \(itemKeys.count) resources") case .failure(let error): DDLogDebug("failed to synced resources for \(groupKey): \(error)") } } } } // MARK: History func addToHistory() { // Don't add to history if we're in peek/pop guard self.wmf_PeekableChildViewController == nil else { return } try? article.addToReadHistory() } var significantlyViewedTimer: Timer? func startSignificantlyViewedTimer() { guard significantlyViewedTimer == nil, !article.wasSignificantlyViewed else { return } significantlyViewedTimer = Timer.scheduledTimer(withTimeInterval: 30, repeats: false, block: { [weak self] (timer) in self?.article.wasSignificantlyViewed = true self?.stopSignificantlyViewedTimer() }) } func stopSignificantlyViewedTimer() { significantlyViewedTimer?.invalidate() significantlyViewedTimer = nil } // MARK: State Restoration /// Save article scroll position for restoration later func saveArticleScrollPosition() { getVisibleSection { (sectionId, anchor) in assert(Thread.isMainThread) self.article.viewedScrollPosition = Double(self.webView.scrollView.contentOffset.y) self.article.viewedFragment = anchor try? self.article.managedObjectContext?.save() } } /// Perform any necessary initial configuration for state restoration func setupForStateRestorationIfNecessary() { guard isRestoringState else { return } setWebViewHidden(true, animated: false) } /// If state needs to be restored, listen for content size changes and restore the scroll position when those changes stop occurring func restoreStateIfNecessary() { guard isRestoringState else { return } isRestoringState = false isRestoringStateOnNextContentSizeChange = true perform(#selector(restoreState), with: nil, afterDelay: 0.5) // failsafe, attempt to restore state after half a second regardless } /// If state is supposed to be restored after the next content size change, restore that state /// This should be called in a debounced manner when article content size changes func restoreStateIfNecessaryOnContentSizeChange() { guard isRestoringStateOnNextContentSizeChange else { return } isRestoringStateOnNextContentSizeChange = false let scrollPosition = CGFloat(article.viewedScrollPosition) guard scrollPosition < webView.scrollView.bottomOffsetY else { return } restoreState() } /// Scroll to the state restoration scroll position now, canceling any previous attempts @objc func restoreState() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(restoreState), object: nil) let scrollPosition = CGFloat(article.viewedScrollPosition) if scrollPosition > 0 && scrollPosition < webView.scrollView.bottomOffsetY { scroll(to: CGPoint(x: 0, y: scrollPosition), animated: false) } else if let anchor = article.viewedFragment { scroll(to: anchor, animated: false) } setWebViewHidden(false, animated: true) } func setWebViewHidden(_ hidden: Bool, animated: Bool, completion: ((Bool) -> Void)? = nil) { let block = { self.webView.alpha = hidden ? 0 : 1 } guard animated else { block() completion?(true) return } UIView.animate(withDuration: 0.3, animations: block, completion: completion) } func callLoadCompletionIfNecessary() { loadCompletion?() loadCompletion = nil } // MARK: Theme lazy var themesPresenter: ReadingThemesControlsArticlePresenter = { return ReadingThemesControlsArticlePresenter(readingThemesControlsViewController: themesViewController, wkWebView: webView, readingThemesControlsToolbarItem: toolbarController.themeButton) }() private lazy var themesViewController: ReadingThemesControlsViewController = { return ReadingThemesControlsViewController(nibName: ReadingThemesControlsViewController.nibName, bundle: nil) }() override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground webView.scrollView.indicatorStyle = theme.scrollIndicatorStyle toolbarController.apply(theme: theme) tableOfContentsController.apply(theme: theme) findInPage.view?.apply(theme: theme) if state == .loaded { messagingController.updateTheme(theme) } } // MARK: Sharing private var isSharingWhenReady = false @objc public func shareArticleWhenReady() { isSharingWhenReady = true } func shareIfNecessary() { guard isSharingWhenReady else { return } isSharingWhenReady = false shareArticle() } // MARK: Navigation @objc(showAnchor:) func show(anchor: String) { dismiss(animated: false) scroll(to: anchor, animated: true) } // MARK: Refresh @objc public func refresh() { state = .reloading if !shouldPerformWebRefreshAfterScrollViewDeceleration { updateRefreshOverlay(visible: true) } shouldPerformWebRefreshAfterScrollViewDeceleration = true } /// Preserves the current scroll position, loads the provided revisionID or waits for a change in etag on the mobile-html response, then refreshes the page and restores the prior scroll position internal func waitForNewContentAndRefresh(_ revisionID: UInt64? = nil) { showNavigationBar() state = .reloading saveArticleScrollPosition() isRestoringState = true setupForStateRestorationIfNecessary() // If a revisionID was provided, just load that revision if let revisionID = revisionID { performWebViewRefresh(revisionID) return } // If no revisionID was provided, wait for the ETag to change guard let eTag = currentETag else { performWebViewRefresh() return } fetcher.waitForMobileHTMLChange(articleURL: articleURL, eTag: eTag, maxAttempts: 5) { (result) in DispatchQueue.main.async { switch result { case .failure(let error): self.showError(error, sticky: true) fallthrough default: self.performWebViewRefresh() } } } } internal func performWebViewRefresh(_ revisionID: UInt64? = nil) { if #available(iOS 13.0, *) { articleAsLivingDocController.articleDidTriggerPullToRefresh() } #if WMF_LOCAL_PAGE_CONTENT_SERVICE // on local PCS builds, reload everything including JS and CSS webView.reloadFromOrigin() #else // on release builds, just reload the page with a different cache policy loadPage(cachePolicy: .noPersistentCacheOnError, revisionID: revisionID) #endif } internal func updateRefreshOverlay(visible: Bool, animated: Bool = true) { let duration = animated ? (visible ? 0.15 : 0.1) : 0.0 let alpha: CGFloat = visible ? 0.3 : 0.0 UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration, delay: 0, options: [.curveEaseIn], animations: { self.refreshOverlay.alpha = alpha }) toolbarController.setToolbarButtons(enabled: !visible) } // MARK: Overrideable functionality internal func handleLink(with href: String) { guard let resolvedURL = articleURL.resolvingRelativeWikiHref(href) else { showGenericError() return } // Check if this is the same article by comparing database keys guard resolvedURL.wmf_databaseKey == articleURL.wmf_databaseKey else { navigate(to: resolvedURL) return } // Check for a fragment - if this is the same article and there's no fragment just do nothing? guard let anchor = resolvedURL.fragment?.removingPercentEncoding else { return } if #available(iOS 13.0, *) { articleAsLivingDocController.handleArticleAsLivingDocLinkForAnchor(anchor) } } // MARK: Table of contents lazy var tableOfContentsController: ArticleTableOfContentsDisplayController = ArticleTableOfContentsDisplayController(articleView: webView, delegate: self, theme: theme) var tableOfContentsItems: [TableOfContentsItem] = [] { didSet { tableOfContentsController.viewController.reload() } } var previousContentOffsetYForTOCUpdate: CGFloat = 0 func updateTableOfContentsHighlightIfNecessary() { guard tableOfContentsController.viewController.displayMode == .inline, tableOfContentsController.viewController.isVisible else { return } let scrollView = webView.scrollView guard abs(previousContentOffsetYForTOCUpdate - scrollView.contentOffset.y) > 15 else { return } guard scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating else { return } updateTableOfContentsHighlight() } func updateTableOfContentsHighlight() { previousContentOffsetYForTOCUpdate = webView.scrollView.contentOffset.y getVisibleSection { (sectionId, _) in self.tableOfContentsController.selectAndScroll(to: sectionId, animated: true) } } func updateTableOfContentsInsets() { let tocScrollView = tableOfContentsController.viewController.tableView let topOffsetY = 0 - tocScrollView.contentInset.top let wasAtTop = tocScrollView.contentOffset.y <= topOffsetY switch tableOfContentsController.viewController.displayMode { case .inline: tocScrollView.contentInset = webView.scrollView.contentInset tocScrollView.scrollIndicatorInsets = webView.scrollView.scrollIndicatorInsets case .modal: tocScrollView.contentInset = UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right: 0) tocScrollView.scrollIndicatorInsets = tocScrollView.contentInset } guard wasAtTop else { return } tocScrollView.contentOffset = CGPoint(x: 0, y: topOffsetY) } // MARK: Scroll var scrollToAnchorCompletions: [ScrollToAnchorCompletion] = [] var scrollViewAnimationCompletions: [() -> Void] = [] override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) updateTableOfContentsHighlightIfNecessary() } override func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { super.scrollViewDidScrollToTop(scrollView) updateTableOfContentsHighlight() } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { super.scrollViewWillBeginDragging(scrollView) dismissReferencesPopover() hintController?.dismissHintDueToUserInteraction() } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { super.scrollViewDidEndDecelerating(scrollView) if shouldPerformWebRefreshAfterScrollViewDeceleration { webView.scrollView.showsVerticalScrollIndicator = false DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { self.performWebViewRefresh() }) } } // MARK: Analytics internal lazy var editFunnel: EditFunnel = EditFunnel.shared internal lazy var shareFunnel: WMFShareFunnel? = WMFShareFunnel(article: article) internal lazy var savedPagesFunnel: SavedPagesFunnel = SavedPagesFunnel() internal lazy var readingListsFunnel = ReadingListsFunnel.shared } private extension ArticleViewController { func setup() { setupWButton() setupSearchButton() addNotificationHandlers() setupWebView() setupMessagingController() } // MARK: Notifications func addNotificationHandlers() { NotificationCenter.default.addObserver(self, selector: #selector(didReceiveArticleUpdatedNotification), name: NSNotification.Name.WMFArticleUpdated, object: article) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) contentSizeObservation = webView.scrollView.observe(\.contentSize) { [weak self] (scrollView, change) in self?.contentSizeDidChange() } } func contentSizeDidChange() { // debounce NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(debouncedContentSizeDidChange), object: nil) perform(#selector(debouncedContentSizeDidChange), with: nil, afterDelay: 0.1) } @objc func debouncedContentSizeDidChange() { restoreOffsetPercentageIfNecessary() restoreStateIfNecessaryOnContentSizeChange() } @objc func didReceiveArticleUpdatedNotification(_ notification: Notification) { toolbarController.setSavedState(isSaved: article.isSaved) } @objc func applicationWillResignActive(_ notification: Notification) { saveArticleScrollPosition() stopSignificantlyViewedTimer() surveyTimerController.willResignActive(withState: state) } @objc func applicationDidBecomeActive(_ notification: Notification) { startSignificantlyViewedTimer() surveyTimerController.didBecomeActive(withState: state) } func setupSearchButton() { navigationItem.rightBarButtonItem = AppSearchBarButtonItem.newAppSearchBarButtonItem } func setupMessagingController() { messagingController.delegate = self } func setupWebView() { // Add the stack view that contains the table of contents and the web view. // This stack view is owned by the tableOfContentsController to control presentation of the table of contents view.wmf_addSubviewWithConstraintsToEdges(tableOfContentsController.stackView) view.widthAnchor.constraint(equalTo: tableOfContentsController.inlineContainerView.widthAnchor, multiplier: 3).isActive = true // Prevent flash of white in dark mode webView.isOpaque = false webView.backgroundColor = .clear webView.scrollView.backgroundColor = .clear // Scroll view scrollView = webView.scrollView // so that content insets are inherited scrollView?.delegate = self webView.scrollView.keyboardDismissMode = .interactive webView.scrollView.refreshControl = refreshControl // Lead image setupLeadImageView() // Add overlay to prevent interaction while reloading webView.wmf_addSubviewWithConstraintsToEdges(refreshOverlay) // Delegates webView.uiDelegate = self webView.navigationDelegate = self // User Agent webView.customUserAgent = WikipediaAppUtils.versionedUserAgent() } /// Adds the lead image view to the web view's scroll view and configures the associated constraints func setupLeadImageView() { webView.scrollView.addSubview(leadImageContainerView) let leadingConstraint = leadImageContainerView.leadingAnchor.constraint(equalTo: webView.leadingAnchor) let trailingConstraint = webView.trailingAnchor.constraint(equalTo: leadImageContainerView.trailingAnchor) let topConstraint = webView.scrollView.topAnchor.constraint(equalTo: leadImageContainerView.topAnchor) let imageTopConstraint = leadImageView.topAnchor.constraint(equalTo: leadImageContainerView.topAnchor) imageTopConstraint.priority = UILayoutPriority(rawValue: 999) let imageBottomConstraint = leadImageContainerView.bottomAnchor.constraint(equalTo: leadImageView.bottomAnchor, constant: leadImageBorderHeight) NSLayoutConstraint.activate([topConstraint, leadingConstraint, trailingConstraint, leadImageHeightConstraint, imageTopConstraint, imageBottomConstraint, leadImageLeadingMarginConstraint, leadImageTrailingMarginConstraint]) if #available(iOS 13.0, *) { articleAsLivingDocController.setupLeadImageView() } } func setupPageContentServiceJavaScriptInterface(with completion: @escaping () -> Void) { guard let siteURL = articleURL.wmf_site else { DDLogError("Missing site for \(articleURL)") showGenericError() return } // Need user groups to let the Page Content Service know if the page is editable for this user authManager.getLoggedInUser(for: siteURL) { (result) in assert(Thread.isMainThread) switch result { case .success(let user): self.setupPageContentServiceJavaScriptInterface(with: user?.groups ?? []) case .failure: DDLogError("Error getting userinfo for \(siteURL)") self.setupPageContentServiceJavaScriptInterface(with: []) } completion() } } func setupPageContentServiceJavaScriptInterface(with userGroups: [String]) { let areTablesInitiallyExpanded = UserDefaults.standard.wmf_isAutomaticTableOpeningEnabled if #available(iOS 13.0, *) { messagingController.shouldAttemptToShowArticleAsLivingDoc = articleAsLivingDocController.shouldAttemptToShowArticleAsLivingDoc } messagingController.setup(with: webView, language: articleLanguage, theme: theme, layoutMargins: articleMargins, leadImageHeight: leadImageHeight, areTablesInitiallyExpanded: areTablesInitiallyExpanded, userGroups: userGroups) } func setupToolbar() { enableToolbar() toolbarController.apply(theme: theme) toolbarController.setSavedState(isSaved: article.isSaved) setToolbarHidden(false, animated: false) } } extension ArticleViewController { func presentEmbedded(_ viewController: UIViewController, style: WMFThemeableNavigationControllerStyle) { let nc = WMFThemeableNavigationController(rootViewController: viewController, theme: theme, style: style) present(nc, animated: true) } } extension ArticleViewController: ReadingThemesControlsResponding { func updateWebViewTextSize(textSize: Int) { messagingController.updateTextSizeAdjustmentPercentage(textSize) } func toggleSyntaxHighlighting(_ controller: ReadingThemesControlsViewController) { // no-op here, syntax highlighting shouldnt be displayed } } extension ArticleViewController: ImageScaleTransitionProviding { var imageScaleTransitionView: UIImageView? { return leadImageView } func prepareViewsForIncomingImageScaleTransition(with imageView: UIImageView?) { guard let imageView = imageView, let image = imageView.image else { return } leadImageHeightConstraint.constant = leadImageHeight leadImageView.image = image leadImageView.layer.contentsRect = imageView.layer.contentsRect view.layoutIfNeeded() } } // MARK: - Article Load Errors extension ArticleViewController { func handleArticleLoadFailure(with error: Error, showEmptyView: Bool) { fakeProgressController.finish() if showEmptyView { wmf_showEmptyView(of: .articleDidNotLoad, theme: theme, frame: view.bounds) } showError(error) refreshControl.endRefreshing() updateRefreshOverlay(visible: false) } func articleLoadDidFail(with error: Error) { // Convert from mobileview if necessary guard article.isConversionFromMobileViewNeeded else { handleArticleLoadFailure(with: error, showEmptyView: !article.isSaved) return } dataStore.migrateMobileviewToMobileHTMLIfNecessary(article: article) { [weak self] (migrationError) in DispatchQueue.main.async { self?.oneOffArticleMigrationDidFinish(with: migrationError) } } } func oneOffArticleMigrationDidFinish(with migrationError: Error?) { if let error = migrationError { handleArticleLoadFailure(with: error, showEmptyView: true) return } guard !article.isConversionFromMobileViewNeeded else { handleArticleLoadFailure(with: RequestError.unexpectedResponse, showEmptyView: true) return } loadPage() } } extension ArticleViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .reload: fallthrough case .other: setupArticleLoadWaitGroup() decisionHandler(.allow) default: decisionHandler(.cancel) } } @available(iOS 13.0, *) func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) { switch navigationAction.navigationType { case .reload: fallthrough case .other: setupArticleLoadWaitGroup() decisionHandler(.allow, preferences) default: decisionHandler(.cancel, preferences) } } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { defer { decisionHandler(.allow) } guard let response = navigationResponse.response as? HTTPURLResponse else { return } currentETag = response.allHeaderFields[HTTPURLResponse.etagHeaderKey] as? String } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { articleLoadDidFail(with: error) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { articleLoadDidFail(with: error) } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { // On process did terminate, the WKWebView goes blank // Re-load the content in this case to show it again webView.reload() } func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { if shouldPerformWebRefreshAfterScrollViewDeceleration { updateRefreshOverlay(visible: false) webView.scrollView.showsVerticalScrollIndicator = true shouldPerformWebRefreshAfterScrollViewDeceleration = false } } } extension ViewController { // Putting extension on ViewController rather than ArticleVC allows for re-use by EditPreviewVC var articleMargins: UIEdgeInsets { return UIEdgeInsets(top: 8, left: articleHorizontalMargin, bottom: 0, right: articleHorizontalMargin) } var articleHorizontalMargin: CGFloat { let viewForCalculation: UIView = navigationController?.view ?? view if let tableOfContentsVC = (self as? ArticleViewController)?.tableOfContentsController.viewController, tableOfContentsVC.isVisible { // full width return viewForCalculation.layoutMargins.left } else { // If (is EditPreviewVC) or (is TOC OffScreen) then use readableContentGuide to make text inset from screen edges. // Since readableContentGuide has no effect on compact width, both paths of this `if` statement result in an identical result for smaller screens. return viewForCalculation.readableContentGuide.layoutFrame.minX } } } @available(iOS 13.0, *) extension ArticleViewController: ArticleAsLivingDocViewControllerDelegate { var articleAsLivingDocViewModel: ArticleAsLivingDocViewModel? { return articleAsLivingDocController.articleAsLivingDocViewModel } func fetchNextPage(nextRvStartId: UInt, theme: Theme) { articleAsLivingDocController.fetchNextPage(nextRvStartId: nextRvStartId, traitCollection: traitCollection, theme: theme) } var isFetchingAdditionalPages: Bool { return articleAsLivingDocController.isFetchingAdditionalPages } } extension ArticleViewController: ArticleAsLivingDocControllerDelegate { }
38.273286
335
0.670348
6adfec6f391e881c64d3f54c2dedbc2106ffa3b1
7,734
// // CombinedChartView.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. open class CombinedChartView: BarLineChartViewBase, CombinedChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: IFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc(CombinedChartDrawOrder) public enum DrawOrder: Int { case bar case bubble case line case candle case scatter } open override func initialize() { super.initialize() self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) // Old default behaviour self.highlightFullBarEnabled = true _fillFormatter = DefaultFillFormatter() renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } open override var data: ChartData? { get { return super.data } set { super.data = newValue self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self) (renderer as? CombinedChartRenderer)?.createRenderers() renderer?.initBuffers() } } @objc open var fillFormatter: IFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if _fillFormatter == nil { _fillFormatter = DefaultFillFormatter() } } } /// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the CombinedChart. open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y) else { return nil } if !isHighlightFullBarEnabled { return h } // For isHighlightFullBarEnabled, remove stackIndex return Highlight( x: h.x, y: h.y, xPx: h.xPx, yPx: h.yPx, dataIndex: h.dataIndex, dataSetIndex: h.dataSetIndex, stackIndex: -1, axis: h.axis) } // MARK: - CombinedChartDataProvider open var combinedData: CombinedChartData? { get { return _data as? CombinedChartData } } // MARK: - LineChartDataProvider open var lineData: LineChartData? { get { return combinedData?.lineData } } // MARK: - BarChartDataProvider open var barData: BarChartData? { get { return combinedData?.barData } } // MARK: - ScatterChartDataProvider open var scatterData: ScatterChartData? { get { return combinedData?.scatterData } } // MARK: - CandleChartDataProvider open var candleData: CandleChartData? { get { return combinedData?.candleData } } // MARK: - BubbleChartDataProvider open var bubbleData: BubbleChartData? { get { return combinedData?.bubbleData } } // MARK: - Accessors /// if set to true, all values are drawn above their bars, instead of below their top @objc open var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value @objc open var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer).drawBarShadowEnabled = newValue } } /// - returns: `true` if drawing values above bars is enabled, `false` ifnot open var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled } /// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot open var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. @objc open var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer).drawOrder = newValue.map { DrawOrder(rawValue: $0)! } } } /// if set to true, a rounded rectangle with the corners is drawn on each bar @objc open var drawRoundedBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer).drawRoundedBarEnabled } set { (renderer as! CombinedChartRenderer).drawRoundedBarEnabled = newValue } } /// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values @objc open var highlightFullBarEnabled: Bool = false /// - returns: `true` the highlight is be full-bar oriented, `false` ifsingle-value open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled } /// - returns: `true` if drawing rounded bars is enabled, `false` ifnot open var isDrawRoundedBarEnabled: Bool { return drawRoundedBarEnabled } // MARK: - ChartViewBase /// draws all MarkerViews on the highlighted positions override func drawMarkers(context: CGContext) { guard let marker = marker, isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = combinedData?.getDataSetByHighlight(highlight), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } }
30.093385
149
0.591932
18e45c384c5eb173fd71c2fd2bb15becd5f6e102
943
// // KeyValueObserver.swift // Postgres // // Created by Chris on 19/08/2016. // Copyright © 2016 postgresapp. All rights reserved. // import Foundation class KeyValueObserver: NSObject { typealias KVOCallback = ([NSKeyValueChangeKey: Any]?) -> Void let keyPath: String private let callback: KVOCallback init(_ keyPath: String, _ callback: @escaping KVOCallback) { self.keyPath = keyPath self.callback = callback } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { callback(change) } } extension NSObject { func observe(_ keyPath: String, options: NSKeyValueObservingOptions = [], callback: @escaping KeyValueObserver.KVOCallback) -> KeyValueObserver { let observer = KeyValueObserver(keyPath, callback) self.addObserver(observer, forKeyPath: keyPath, options: options, context: nil) return observer } }
24.815789
148
0.740191
f84c74a0ec4b98055b2f493bf05a572fef4d90ec
924
// // Chap05_02AppTests.swift // Chap05-02AppTests // // Created by Hiroyuki Aoki on 2019/09/17. // Copyright © 2019 MyCompany. All rights reserved. // import XCTest @testable import Chap05_02App class Chap05_02AppTests: XCTestCase { override func 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. } 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. } } }
26.4
111
0.661255
209740df48792ec05d2265d6ba8f42faa4d3495a
2,507
// // NetworkRequestsIgnoredExtensionSettingsViewController.swift // QuickBrickXray // // Created by Alex Zchut on 02/25/21. // Copyright © 2021 Applicaster. All rights reserved. // import Foundation import XrayLogger class NetworkRequestsIgnoredExtensionSettingsViewController: UITableViewController, SettingsViewControllerDelegate { var delegate: SettingsViewController? var currentItems: [String] { get { delegate?.networkRequestsIgnoredExtensions ?? [] } set { delegate?.setNetworkRequestsIgnoredExtensions(extensions: newValue) } } let cellIdentifier = "IgnoredExtensionsCellIndentifier" required init?(coder: NSCoder) { super.init(coder: coder) } } extension NetworkRequestsIgnoredExtensionSettingsViewController { override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { currentItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.textLabel?.text = currentItems[indexPath.row] return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { currentItems.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } @IBAction func addItem(_: Any) { let alert = UIAlertController(title: "Add Extension", message: "", preferredStyle: .alert) alert.view.tintColor = .darkGray let saveAction = UIAlertAction(title: "Add", style: .default) { [unowned self] _ in guard let textField = alert.textFields?.first, let newItem = textField.text else { return } currentItems.append(newItem) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .default) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true) } }
32.558442
137
0.652573
2f6f7882ac82a3dd35b76ae1a0fd0b7621383024
1,210
// // AppDelegate.swift // LSRouterDemo_Swift // // Created by ArthurShuai on 2018/1/31. // Copyright © 2018年 ArthurShuai. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { LSRouter.application(application, didFinishLaunchingWithOptions: launchOptions) return true } func applicationWillResignActive(_ application: UIApplication) { LSRouter.applicationWillResignActive(application) } func applicationDidEnterBackground(_ application: UIApplication) { LSRouter.applicationDidEnterBackground(application) } func applicationWillEnterForeground(_ application: UIApplication) { LSRouter.applicationWillEnterForeground(application) } func applicationDidBecomeActive(_ application: UIApplication) { LSRouter.applicationDidBecomeActive(application) } func applicationWillTerminate(_ application: UIApplication) { LSRouter.applicationWillTerminate(application) } }
26.888889
144
0.752066
9c81a43193bd3a02f6efde9c5ecfe8f433adeaf4
1,170
// // pivotModifier.swift // Animations // // Created by Gokul Nair on 03/07/21. // import SwiftUI struct CornerRotateModifier: ViewModifier { let amount: Double let anchor: UnitPoint func body(content: Content) -> some View { content.rotationEffect(.degrees(amount), anchor: anchor) .clipped() } } extension AnyTransition { static var pivot: AnyTransition { .modifier(active: CornerRotateModifier(amount: 90, anchor: .topLeading), identity: CornerRotateModifier(amount: 0, anchor: .topLeading)) } } struct pivotModifier: View { @State private var isVisible = false var body: some View { VStack { Button("Tap") { withAnimation{ self.isVisible.toggle() } } if isVisible { Rectangle() .fill(Color.red) .frame(width: 200, height: 200) .transition(.pivot) } } } } struct pivotModifier_Previews: PreviewProvider { static var previews: some View { pivotModifier() } }
22.075472
144
0.549573
f94cc7845549f2b7c7cac6dba5a2d84a75a4f082
870
// // NibLoadable.swift // WordBuzzer // // Created by Onur Torna on 26/04/18. // Copyright © 2018 Onur Torna. All rights reserved. // import UIKit protocol NibLoadable { static var defaultNibName: String { get } static func loadFromNib() -> Self } extension NibLoadable where Self: UIView { static var defaultNibName: String { return String(describing: self) } static var defaultNib: UINib { return UINib(nibName: defaultNibName, bundle: nil) } static func loadFromNib() -> Self { guard let nib = Bundle.main.loadNibNamed(defaultNibName, owner: nil, options: nil)?.first as? Self else { fatalError("[NibLoadable] Cannot load view from nib.") } return nib } }
22.894737
78
0.562069
f5fc130a105a8abe769b79c7e59d4fddd6ac4816
480
// // CategoryTableViewCell.swift // ToDoApp // // Created by nalinis on 8/1/17. // Copyright © 2017 nalinis. All rights reserved. // import UIKit class CategoryTableViewCell: UITableViewCell { @IBOutlet weak var categoryLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
20.869565
65
0.679167
908d6556ff073e1cd1a9cb479e4dac2814d2de35
951
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "carttool", dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), .package(url: "https://github.com/apple/swift-package-manager.git", .exact("0.1.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "carttool", dependencies: ["CartToolCore"]), .target(name: "CartToolCore", dependencies: ["Utility"]), .testTarget( name: "CartToolTests", dependencies: ["CartToolCore"] ) ] )
35.222222
122
0.644585
56e9c0bbe0d12df7e1ff9777fa3b7602004dcc99
2,200
// // AppDelegate.swift // Reporte Responsable // // Created by Rodrigo on 20/09/17. // Copyright © 2017 Chilango Labs. All rights reserved. // import CoreLocation 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.808511
285
0.757727