repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Prosumma/CoreDataQueryInterface
Tests/CoreDataQueryInterfaceTests/Store.swift
1
1972
// // Store.swift // CoreDataQueryInterfaceTests // // Created by Gregory Higley on 2022-10-22. // import CoreData import CoreDataQueryInterface import PredicateQI enum Store { private static func initPersistentContainer() -> NSPersistentContainer { let mom = NSManagedObjectModel.mergedModel(from: [Bundle.module])! let container = NSPersistentContainer(name: "developers", managedObjectModel: mom) let store = NSPersistentStoreDescription(url: URL(fileURLWithPath: "/dev/null")) container.persistentStoreDescriptions = [store] container.loadPersistentStores { _, error in if let error = error { assertionFailure("\(error)") } } loadData(into: container) return container } private(set) static var container = Self.initPersistentContainer() private static func loadData(into container: NSPersistentContainer) { let moc = container.viewContext let languages = ["Swift", "Haskell", "Visual Basic", "Rust", "Ruby", "Kotlin", "Python"] for name in languages { let language = Language(context: moc) language.name = name } try! moc.save() let developers: [[String: Any]] = [ ["fn": "Iulius", "ln": "Caesar", "ls": ["Ruby", "Swift"]], ["fn": "Benjamin", "ln": "Disraeli", "ls": ["Swift", "Kotlin"]], ["fn": "Gregory", "ln": "Higley", "ls": ["Swift", "Rust", "Haskell"]] ] for info in developers { let firstName = info["fn"] as! String let lastName = info["ln"] as! String let languageNames = info["ls"] as! [String] var languages: Set<Language> = [] for name in languageNames { let language = try! moc.query(Language.self).filter { $0.name == name }.fetchFirst()! languages.insert(language) } let developer = Developer(context: moc) developer.firstName = firstName developer.lastName = lastName developer.languages = languages } try! moc.save() } }
mit
7bdcf909466a139ccdae67b822ceecd2
31.866667
93
0.640974
4.177966
false
false
false
false
shajrawi/swift
test/ParseableInterface/synthesized.swift
1
915
// RUN: %target-swift-frontend -typecheck -emit-parseable-module-interface-path - %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // CHECK-LABEL: public enum HasRawValue : Int { public enum HasRawValue: Int { // CHECK-NEXT: case a, b, c case a, b = 5, c // CHECK-DAG: public typealias RawValue = Swift.Int // CHECK-DAG: @inlinable public init?(rawValue: Swift.Int) // CHECK-DAG: public var rawValue: Swift.Int { // CHECK-DAG: @inlinable get{{$}} // CHECK-DAG: } } // CHECK: {{^}$}} @objc public enum ObjCEnum: Int32 { case a, b = 5, c } // CHECK-LABEL: @objc public enum ObjCEnum : Int32 { // CHECK-NEXT: case a, b = 5, c // CHECK-DAG: public typealias RawValue = Swift.Int32 // CHECK-DAG: @inlinable public init?(rawValue: Swift.Int32) // CHECK-DAG: public var rawValue: Swift.Int32 { // CHECK-DAG: @inlinable get{{$}} // CHECK-DAG: } // CHECK: {{^}$}}
apache-2.0
9141e424e0ae53143dac2fef56e814e3
35.6
167
0.659016
3.233216
false
false
false
false
apple/swift-syntax
Sources/SwiftParserDiagnostics/SyntaxExtensions.swift
1
5154
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension UnexpectedNodesSyntax { func tokens(satisfying isIncluded: (TokenSyntax) -> Bool) -> [TokenSyntax] { return self.children(viewMode: .sourceAccurate).compactMap({ $0.as(TokenSyntax.self) }).filter(isIncluded) } func tokens(withKind kind: TokenKind) -> [TokenSyntax] { return self.tokens(satisfying: { $0.tokenKind == kind }) } /// If this only contains a single item that is a token, return that token, otherwise return `nil`. var onlyToken: TokenSyntax? { return onlyToken(where: { _ in true }) } /// If this only contains a single item, which is a token satisfying `condition`, return that token, otherwise return `nil`. func onlyToken(where condition: (TokenSyntax) -> Bool) -> TokenSyntax? { if self.count == 1, let token = self.first?.as(TokenSyntax.self), condition(token) { return token } else { return nil } } /// If this only contains tokens satisfying `condition`, return an array containing those tokens, otherwise return `nil`. func onlyTokens(satisfying condition: (TokenSyntax) -> Bool) -> [TokenSyntax]? { let tokens = tokens(satisfying: condition) if tokens.count == self.count { return tokens } else { return nil } } } extension Syntax { func hasParent(_ expectedParent: Syntax) -> Bool { var walk = self.parent while walk != nil { if walk == expectedParent { return true } walk = walk?.parent } return false } } extension SyntaxProtocol { /// A name that can be used to describe this node's type in diagnostics or `nil` if there is no good name for this node. /// If `allowBlockNames` is `false`, `CodeBlockSyntax` and `MemberDeclBlockSyntax` are not considered to have a good name and will return `nil`. func nodeTypeNameForDiagnostics(allowBlockNames: Bool) -> String? { let syntax = Syntax(self) if !allowBlockNames && (syntax.is(CodeBlockSyntax.self) || syntax.is(MemberDeclBlockSyntax.self)) { return nil } return syntax.kind.nameForDiagnostics } /// A short description of this node that can be displayed inline in a single line. /// If the syntax node (excluding leading and trailing trivia) only spans a /// single line and has less than 100 characters (and thus fits into a /// diagnostic message), return that. /// Otherwise, return a generic message that describes the tokens in this node. var shortSingleLineContentDescription: String { let contentWithoutTrivia = self.withoutLeadingTrivia().withoutTrailingTrivia().description if self.children(viewMode: .sourceAccurate).allSatisfy({ $0.as(TokenSyntax.self)?.tokenKind == .rightBrace }) { if self.children(viewMode: .sourceAccurate).count == 1 { return "brace" } else { return "braces" } } else if let token = Syntax(self).as(UnexpectedNodesSyntax.self)?.onlyTokens(satisfying: { $0.tokenKind.isKeyword })?.only { return "'\(token.text)' keyword" } else if let token = Syntax(self).as(TokenSyntax.self) { return "'\(token.text)' keyword" } else if contentWithoutTrivia.contains("\n") || contentWithoutTrivia.count > 100 { return "code" } else { return "code '\(contentWithoutTrivia)'" } } /// Returns this node or the first ancestor that satisfies `condition`. func ancestorOrSelf(where condition: (Syntax) -> Bool) -> Syntax? { return ancestorOrSelf(mapping: { condition($0) ? $0 : nil }) } /// Returns this node or the first ancestor that satisfies `condition`. func ancestorOrSelf<T>(mapping map: (Syntax) -> T?) -> T? { var walk: Syntax? = Syntax(self) while let unwrappedParent = walk { if let mapped = map(unwrappedParent) { return mapped } walk = unwrappedParent.parent } return nil } /// Returns `true` if the next token's leading trivia should be made leading trivia /// of this mode, when it is switched from being missing to present. var shouldBeInsertedAfterNextTokenTrivia: Bool { if !self.raw.kind.isMissing, let memberDeclItem = self.ancestorOrSelf(mapping: { $0.as(MemberDeclListItemSyntax.self) }), memberDeclItem.firstToken(viewMode: .all) == self.firstToken(viewMode: .all) { return true } else { return false } } } extension TokenKind { var isIdentifier: Bool { switch self { case .identifier: return true default: return false } } var isDollarIdentifier: Bool { switch self { case .dollarIdentifier: return true default: return false } } }
apache-2.0
6325608f0a08029e934ccfbec7d363c7
34.544828
146
0.656189
4.298582
false
false
false
false
AlicJ/CPUSimulator
CPUSimulator/PathData.swift
1
1772
// // Coordinates.swift // CPUSimulator // // Created by Alic on 2017-06-19. // Copyright © 2017 4ZC3. All rights reserved. // import Foundation import UIKit struct PathData { static let lineWidth: CGFloat = 5.0 struct instructionBlock { static let toRegisterBlock: [CGPoint] = [ CGPoint(x: 480, y: 180), CGPoint(x: 500, y: 210), CGPoint(x: 690, y: 210), CGPoint(x: 700, y: 220), CGPoint(x: 700, y: 400), CGPoint(x: 690, y: 410), CGPoint(x: 677, y: 410) ] static let toALUBlock: [CGPoint] = [ CGPoint(x: 496, y: 188), CGPoint(x: 504, y: 200), CGPoint(x: 693, y: 200), CGPoint(x: 710, y: 216), CGPoint(x: 710, y: 806), CGPoint(x: 696, y: 820), CGPoint(x: 677, y: 820) ] } struct registerBlock { static let toALUBlock: [CGPoint] = [ CGPoint(x: 675, y: 420), CGPoint(x: 690, y: 420), CGPoint(x: 700, y: 430), CGPoint(x: 700, y: 800), CGPoint(x: 690, y: 810), CGPoint(x: 677, y: 810) ] static let toMemoryBlock: [CGPoint] = Array(memoryBlock.toRegisterBlock.reversed()) } struct ALUBlock { static let toRegisterBlock: [CGPoint] = Array(registerBlock.toALUBlock.reversed()) } struct memoryBlock { static let toRegisterBlock: [CGPoint] = [ CGPoint(x: 190, y: 100), CGPoint(x: 210, y: 100), CGPoint(x: 220, y: 110), CGPoint(x: 220, y: 290), CGPoint(x: 230, y: 300), CGPoint(x: 310, y: 300) ] } }
mit
27315c71c6d340b6d69b9c61b4156bd8
25.833333
91
0.48786
3.542
false
false
false
false
below/Math-O-Matic
Math-O-Matic/ViewController.swift
1
3182
// // ViewController.swift // Math-O-Matik // // Created by Alexander v. Below on 30.08.16. // Copyright © 2016 Alexander von Below. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var faktor1: UILabel! @IBOutlet weak var faktor2: UILabel! @IBOutlet weak var ergebnis: UITextField! @IBOutlet weak var anzeige: UILabel! @IBOutlet weak var operatorFeld: UILabel! @IBOutlet weak var rechenartenControl: UISegmentedControl! @IBOutlet weak var counterLabel: UILabel! var correct = 0 var wrong = 0 override func viewDidLoad() { super.viewDidLoad() setUpFields() } func setUpFields() { self.ergebnis.text = "" var f1 : Int! var f2 : Int! switch rechenartenControl.selectedSegmentIndex { case 1: operatorFeld.text = ":" f2 = Int(arc4random_uniform(9) + 2) let result = Int(arc4random_uniform(9) + 2) f1 = f2 * result default: operatorFeld.text = "⨯" f1 = Int(arc4random_uniform(10) + 1) f2 = Int(arc4random_uniform(10) + 1) } self.faktor2.text = String(f2) self.faktor1.text = String(f1) } @IBAction func andereRechenart(_ sender: UISegmentedControl) { setUpFields() } func currentOperation () -> ((_ x : Int, _ y : Int) -> Int) { switch rechenartenControl.selectedSegmentIndex { case 1: return { (x:Int, y:Int) -> Int in return x / y } default: return { (x:Int, y:Int) -> Int in return x * y } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let f1 = Int(self.faktor1.text ?? "") ?? 0 let f2 = Int(self.faktor2.text ?? "") ?? 0 let e = Int(self.ergebnis.text ?? "") ?? 0 let calc = currentOperation() if e == calc(f1, f2) { self.anzeige.text = "✔️" correct = correct + 1 } else { self.anzeige.text = "❌" wrong = wrong + 1 } let correctString = NSAttributedString(string: String(correct), attributes: [ NSForegroundColorAttributeName : UIColor.green ]) let wrongString = NSAttributedString(string: String(wrong), attributes: [ NSForegroundColorAttributeName : UIColor.red ]) setUpFields() let resultString = NSMutableAttributedString(attributedString: correctString) resultString.append(NSAttributedString(string: " / ")) resultString.append(wrongString) counterLabel.attributedText = resultString return true } @IBAction func clear(_ sender: AnyObject) { wrong = 0 correct = 0 counterLabel.text = "0 / 0" } @IBAction func neuesErgebnis(_ sender: AnyObject) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1383b36c2dc8bdc275dd8151d08b239e
27.845455
135
0.569177
4.247657
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/Attachment Keyboard/AttachmentKeyboard.swift
1
9986
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import Photos import PromiseKit @objc protocol AttachmentKeyboardDelegate { func didSelectRecentPhoto(asset: PHAsset, attachment: SignalAttachment) func didTapGalleryButton() func didTapCamera(withPhotoCapture: PhotoCapture?) func didTapGif() func didTapFile() func didTapContact() func didTapLocation() } class AttachmentKeyboard: CustomKeyboard { @objc weak var delegate: AttachmentKeyboardDelegate? private let mainStackView = UIStackView() private let recentPhotosCollectionView = RecentPhotosCollectionView() private let recentPhotosErrorView = RecentPhotosErrorView() private let galleryButton = UIButton() private let attachmentFormatPickerView = AttachmentFormatPickerView() private lazy var hasRecentsHeightConstraint = attachmentFormatPickerView.autoMatch( .height, to: .height, of: recentPhotosCollectionView, withMultiplier: 1, relation: .lessThanOrEqual ) private lazy var recentPhotosErrorHeightConstraint = attachmentFormatPickerView.autoMatch( .height, to: .height, of: recentPhotosErrorView, withMultiplier: 1, relation: .lessThanOrEqual ) private var mediaLibraryAuthorizationStatus: PHAuthorizationStatus { return PHPhotoLibrary.authorizationStatus() } // MARK: - override init() { super.init() backgroundColor = Theme.backgroundColor mainStackView.axis = .vertical mainStackView.spacing = 8 contentView.addSubview(mainStackView) mainStackView.autoPinWidthToSuperview() mainStackView.autoPinEdge(toSuperviewEdge: .top) mainStackView.autoPinEdge(toSuperviewSafeArea: .bottom, withInset: 8) setupRecentPhotos() setupGalleryButton() setupFormatPicker() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Recent Photos func setupRecentPhotos() { recentPhotosCollectionView.recentPhotosDelegate = self mainStackView.addArrangedSubview(recentPhotosCollectionView) mainStackView.addArrangedSubview(recentPhotosErrorView) recentPhotosErrorView.isHidden = true } func showRecentPhotos() { guard recentPhotosCollectionView.hasPhotos else { return showRecentPhotosError() } galleryButton.isHidden = false recentPhotosErrorHeightConstraint.isActive = false hasRecentsHeightConstraint.isActive = true recentPhotosErrorView.isHidden = true recentPhotosCollectionView.isHidden = false } func showRecentPhotosError() { recentPhotosErrorView.hasMediaLibraryAccess = isMediaLibraryAccessGranted galleryButton.isHidden = true hasRecentsHeightConstraint.isActive = false recentPhotosErrorHeightConstraint.isActive = true recentPhotosCollectionView.isHidden = true recentPhotosErrorView.isHidden = false } // MARK: Gallery Button func setupGalleryButton() { addSubview(galleryButton) galleryButton.setTemplateImage(#imageLiteral(resourceName: "photo-outline-28"), tintColor: .white) galleryButton.setBackgroundImage(UIImage(color: UIColor.black.withAlphaComponent(0.7)), for: .normal) galleryButton.autoSetDimensions(to: CGSize(width: 48, height: 48)) galleryButton.clipsToBounds = true galleryButton.layer.cornerRadius = 24 galleryButton.autoPinEdge(toSuperviewSafeArea: .leading, withInset: 16) galleryButton.autoPinEdge(.bottom, to: .bottom, of: recentPhotosCollectionView, withOffset: -8) galleryButton.addTarget(self, action: #selector(didTapGalleryButton), for: .touchUpInside) } @objc func didTapGalleryButton() { delegate?.didTapGalleryButton() } // MARK: Format Picker func setupFormatPicker() { attachmentFormatPickerView.attachmentFormatPickerDelegate = self mainStackView.addArrangedSubview(attachmentFormatPickerView) NSLayoutConstraint.autoSetPriority(.defaultLow) { attachmentFormatPickerView.autoSetDimension(.height, toSize: 80) } attachmentFormatPickerView.setCompressionResistanceLow() attachmentFormatPickerView.setContentHuggingLow() } // MARK: - override func willPresent() { super.willPresent() checkPermissions { [weak self] in self?.updateItemSizes() } } override func wasDismissed() { super.wasDismissed() attachmentFormatPickerView.stopCameraPreview() } override func orientationDidChange() { super.orientationDidChange() updateItemSizes() } func updateItemSizes() { // The items should always expand to fit the height of their collection view. // We'll always just have one row of items. recentPhotosCollectionView.itemSize = CGSize(square: recentPhotosCollectionView.height()) attachmentFormatPickerView.itemSize = CGSize(square: attachmentFormatPickerView.height()) } func checkPermissions(completion: @escaping () -> Void) { switch mediaLibraryAuthorizationStatus { case .authorized: showRecentPhotos() case .denied, .restricted: showRecentPhotosError() case .notDetermined: return PHPhotoLibrary.requestAuthorization { _ in DispatchQueue.main.async { self.checkPermissions(completion: completion) } } @unknown default: showRecentPhotosError() break } switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: attachmentFormatPickerView.startCameraPreview() case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { granted in if granted { DispatchQueue.main.async { self.attachmentFormatPickerView.startCameraPreview() } } } case .denied, .restricted: break @unknown default: break } completion() } } extension AttachmentKeyboard: RecentPhotosDelegate { var isMediaLibraryAccessGranted: Bool { return mediaLibraryAuthorizationStatus == .authorized } func didSelectRecentPhoto(asset: PHAsset, attachment: SignalAttachment) { delegate?.didSelectRecentPhoto(asset: asset, attachment: attachment) } } extension AttachmentKeyboard: AttachmentFormatPickerDelegate { func didTapCamera(withPhotoCapture photoCapture: PhotoCapture?) { delegate?.didTapCamera(withPhotoCapture: photoCapture) } func didTapGif() { delegate?.didTapGif() } func didTapFile() { delegate?.didTapFile() } func didTapContact() { delegate?.didTapContact() } func didTapLocation() { delegate?.didTapLocation() } } private class RecentPhotosErrorView: UIView { var hasMediaLibraryAccess = false { didSet { guard hasMediaLibraryAccess != oldValue else { return } updateMessaging() } } let label = UILabel() let buttonWrapper = UIView() override init(frame: CGRect) { super.init(frame: .zero) layoutMargins = UIEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8) let stackView = UIStackView() stackView.addBackgroundView(withBackgroundColor: Theme.attachmentKeyboardItemBackgroundColor, cornerRadius: 4) stackView.axis = .vertical stackView.spacing = 8 stackView.distribution = .fill stackView.isLayoutMarginsRelativeArrangement = true stackView.layoutMargins = UIEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16) addSubview(stackView) stackView.autoPinEdgesToSuperviewMargins() let topSpacer = UIView.vStretchingSpacer() stackView.addArrangedSubview(topSpacer) label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.textColor = Theme.primaryColor label.font = .ows_dynamicTypeSubheadlineClamped label.textAlignment = .center stackView.addArrangedSubview(label) let button = OWSFlatButton() button.setBackgroundColors(upColor: .ows_signalBlue) button.setTitle(title: CommonStrings.openSettingsButton, font: .ows_dynamicTypeBodyClamped, titleColor: .white) button.useDefaultCornerRadius() button.contentEdgeInsets = UIEdgeInsets(top: 3, leading: 8, bottom: 3, trailing: 8) button.setPressedBlock { UIApplication.shared.openSystemSettings() } buttonWrapper.addSubview(button) button.autoPinHeightToSuperview() button.autoHCenterInSuperview() stackView.addArrangedSubview(buttonWrapper) let bottomSpacer = UIView.vStretchingSpacer() stackView.addArrangedSubview(bottomSpacer) topSpacer.autoMatch(.height, to: .height, of: bottomSpacer) updateMessaging() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateMessaging() { buttonWrapper.isHidden = hasMediaLibraryAccess if hasMediaLibraryAccess { label.text = NSLocalizedString( "ATTACHMENT_KEYBOARD_NO_PHOTOS", comment: "A string indicating to the user that once they take photos, they'll be able to send them from this view." ) } else { label.text = NSLocalizedString( "ATTACHMENT_KEYBOARD_NO_PHOTO_ACCESS", comment: "A string indicating to the user that they'll be able to send photos from this view once they enable photo access." ) } } }
gpl-3.0
5a724ce924dd8de918ad93d3e3ba1013
30.601266
140
0.677849
5.357296
false
false
false
false
chrisbudro/ThisPic
ThisPic/Model/ParseService.swift
1
2958
// // ParseService.swift // ParseStarterProject // // Created by Chris Budro on 8/10/15. // Copyright (c) 2015 Parse. All rights reserved. // import UIKit import Parse class ParseService { class func getTimeline(completion: (posts: [PFObject]?, error: String?) -> Void) { if let user = PFUser.currentUser(), following = user["following"] as? [PFObject] { let query = PFQuery(className: "Post") query.whereKey("user", containedIn: following) query.orderByDescending("createdAt") query.findObjectsInBackgroundWithBlock { (posts, error) -> Void in if let error = error { completion(posts: nil, error: error.description) } if let posts = posts as? [PFObject] { completion(posts: posts, error: nil) } else { completion(posts: nil, error: "an unknown error occurred") } } } completion(posts: nil, error: "User is not set") } class func getUserList(completion: (users: [PFObject]?, error: String?) -> Void) { if let query = PFUser.query() { query.orderByAscending("username") query.findObjectsInBackgroundWithBlock { (users, error) -> Void in if let error = error { completion(users: nil, error: error.localizedDescription) } else if let users = users as? [PFObject] { completion(users: users, error: nil) } else { completion(users: nil, error: "An error has occurred") } } } } class func followUser(user: PFObject, completion: (Bool, error: String?) -> Void) { if let currentUser = PFUser.currentUser() { currentUser.addUniqueObject(user, forKey: "following") currentUser.saveInBackgroundWithBlock { (succeeded, error) -> Void in if let error = error { completion(false, error: error.localizedDescription) } else if succeeded == true { completion(succeeded, error: nil) println("followed") } } } } class func uploadPost(image: UIImage, caption: String?, completion: (Bool, error: String?) -> Void) { let post = PFObject(className: "Post") let aspectRatio = image.size.height / image.size.width let jpegData = UIImageJPEGRepresentation(image, 0.7) let imageFile = PFFile(name: "post", data: jpegData) post.setObject(imageFile, forKey: "image") post.setObject(aspectRatio, forKey: "imageAspectRatio") if let currentUser = PFUser.currentUser() { let user = PFUser.objectWithoutDataWithObjectId(currentUser.objectId) post.setObject(user, forKey: "user") } if let caption = caption { post.setObject(caption, forKey: "caption") } post.saveInBackgroundWithBlock { (success, error) -> Void in if let error = error { completion(false, error: error.localizedDescription) } else if success { completion(true, error: nil) } } } }
mit
fca28343ecf4db63641f1767f126c685
28.58
103
0.626437
4.305677
false
false
false
false
hoiberg/swiftMorse
MorseController.swift
1
9257
// // MorseController.swift // Morseboard // // Created by Alex on 03-02-15. // Copyright (c) 2015 Balancing Rock. All rights reserved. // MIT License applies // // // Features: // - Supports single button as well as dual button (one for . and one for -) applications // - Morse beep sounds with adjustable frequency (Low, Middle, High, Extra High, and you can supply your own if you want) // - Configurable WPM, Sound enable, Sound frequency, Auto space enable, error symbol // // Ideas for future updates: // - Iambic paddle support // - Option to use the ticking sound of a morse key instead of beeps // // Hope this saves someone time :) // import UIKit enum MorseSignal: String, Printable { case Short = "." case Long = "-" var description: String { get { return self.rawValue } } } protocol MorseControllerDelegate { func insertCharacter(var charToInsert: String) } private let _morseDictionary = [".-": "a", "-...": "b", "-.-.": "c", "-..": "d", ".": "e", "..-.": "f", "--.": "g", "....": "h", "..": "i", ".---": "j", "-.-": "k", ".-..": "l", "--": "m", "-.": "n", "---": "o", ".--.": "p", "--.-": "q", ".-.": "r", "...": "s", "-": "t", "..-": "u", "...-": "v", ".--": "w", "-..-": "x", "-.--": "y", "--..": "z", ".-.-": "ä", "---.": "ö", "..--": "ü", "...--..": "ß", "----": "CH", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", "-----": "0", "..--..": "?", "..--.": "!", ".--.-.": "@", ".-.-.-": ".", "--..--": ",", "-...-": "=", ".-.-.": "+"] class MorseController: NSObject { //MARK: - Class vars /// morse dictionary with dots and dashes being the keys and characters the values (singleton) class var morseDictionary: [String: String] { get { return _morseDictionary } } //MARK: - Instance vars /// Delegate the insertCharacter function will be called upon var delegate: MorseControllerDelegate? /// Speed (words per minute) var wpm: Int = 10 /// Whether a beep sound should be played var sounds: Bool = true /// Frequency of the beep sounds. Note: cannot be changed after initialization let soundFreq: ToneFrequency = .Middle /// Whether automaticly a space should be inserted after 7 time units var autoSpace: Bool = false /// The symbol that will be given if a nonextistend morse character has been generated var errorSymbol: String = "😕" /// Minimum duration of a morse sound, to prevent short dots to be unplayed/unheard private let minSoundDuration = 0.5 /// One time unit private var timeUnit: Double { get { return Double(1.2) / Double(self.wpm) } } /// Whether a space may be inserted /// not if A) there hasn't a character been inserted yet or B) if a space has been inserted private var mayInsertSpace = false // rest is self-explainatory private lazy var toneGen: ToneGenerator = ToneGenerator(freq: self.soundFreq) private var isBeingPressed: Bool = false private var lastBeginTime: NSDate? private var lastEndTime: NSDate? var morseToPresent: [String] = [] //MARK: - Functions override init() { super.init() // start update loop NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateMorse", userInfo: nil, repeats: true) } init(delegate: MorseControllerDelegate, wpm: Int, sounds: Bool, soundFreq: ToneFrequency, autoSpace: Bool, errorSymbol: String) { self.delegate = delegate self.wpm = wpm self.sounds = sounds self.soundFreq = soundFreq self.autoSpace = autoSpace self.errorSymbol = errorSymbol super.init() // start update loop NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateMorse", userInfo: nil, repeats: true) } /// Updates every 0.01 seconds to check whether /// a) A character should be inserted /// b) A space should be inserted (only if autoSpace is true) func updateMorse() { // check if it is needed to update if isBeingPressed == true || lastEndTime == nil { return } // is the time since previous tap long enough let timeSinceTap = NSDate().timeIntervalSinceDate(lastEndTime!) if timeSinceTap < timeUnit * 3 { return } // if there is some morse to insert if morseToPresent.count != 0 { // get the character to insert let charToInsert = characterForMorse(morseToPresent) morseToPresent = [] // call the delegate method delegate?.insertCharacter(charToInsert) // a space may be inserted from now on mayInsertSpace = true return } // maybe we have to insert a space if autoSpace && mayInsertSpace && timeSinceTap > timeUnit * 7 { // call the delegate method to insert a space delegate?.insertCharacter(" ") // no second spaces mayInsertSpace = false } } /// To be used by the delegate to notify that a tap as begun func beginMorse() { isBeingPressed = true lastBeginTime = NSDate() if sounds { toneGen.start() } } /// To be used by the delegate to notify that the tap has ended func endMorse() { isBeingPressed = false lastEndTime = NSDate() if sounds { // stop sounds, only if the minimum sound duration // has been exceeded to prevent too short blip's if lastEndTime!.timeIntervalSinceDate(lastBeginTime!) >= minSoundDuration { // alright, stop the sound gen toneGen.stop() } else { // shedule timer to stop the sound gen at the lastBeginTime + minSoundDuration let targetTime = lastBeginTime!.dateByAddingTimeInterval(minSoundDuration) NSTimer.scheduledTimerWithTimeInterval(lastEndTime!.timeIntervalSinceDate(targetTime), target: toneGen, selector: Selector("stop"), userInfo: nil, repeats: false) } } // add . or - let timePressed = lastEndTime!.timeIntervalSinceDate(lastBeginTime!) if timePressed >= timeUnit * Double(3) { morseToPresent += ["-"] } else { morseToPresent += ["."] } } /// To be used by the delegate to manually insert a . or - func manuallyInsertMorse(morse: MorseSignal) { if isBeingPressed { return } lastBeginTime = NSDate() lastEndTime = NSDate() morseToPresent.append(morse.description) } /// Returns the human readable character for the given morse sequence (or the error symbol if it is not valid morse) func characterForMorse(theArray:[String]) -> String { // join the objects let theString = "".join(theArray) // get the character let returnString = MorseController.morseDictionary[theString] // return errorsymbol if neccesary if returnString == nil || returnString?.isEmpty == true { return errorSymbol } return returnString! } }
mit
e04adc0b996f6f307e69cdee370df746
31.570423
178
0.460432
5.153203
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/PathNodes/ShapeNode.swift
1
1445
// // PathNode.swift // lottie-swift // // Created by Brandon Withrow on 1/16/19. // import Foundation import CoreGraphics final class ShapeNodeProperties: NodePropertyMap, KeypathSearchable { var keypathName: String init(shape: Shape) { self.keypathName = shape.name self.path = NodeProperty(provider: KeyframeInterpolator(keyframes: shape.path.keyframes)) self.keypathProperties = [ "Path" : path ] self.properties = Array(keypathProperties.values) } let path: NodeProperty<BezierPath> let keypathProperties: [String : AnyNodeProperty] let properties: [AnyNodeProperty] } final class ShapeNode: AnimatorNode, PathNode { let properties: ShapeNodeProperties let pathOutput: PathOutputNode init(parentNode: AnimatorNode?, shape: Shape) { self.pathOutput = PathOutputNode(parent: parentNode?.outputNode) self.properties = ShapeNodeProperties(shape: shape) self.parentNode = parentNode } // MARK: Animator Node var propertyMap: NodePropertyMap & KeypathSearchable { return properties } let parentNode: AnimatorNode? var hasLocalUpdates: Bool = false var hasUpstreamUpdates: Bool = false var lastUpdateFrame: CGFloat? = nil var isEnabled: Bool = true { didSet{ self.pathOutput.isEnabled = self.isEnabled } } func rebuildOutputs(frame: CGFloat) { pathOutput.setPath(properties.path.value, updateFrame: frame) } }
mit
e1612a4613b537f4a4559a597faae200
22.688525
93
0.718339
4.339339
false
false
false
false
HarukaMa/iina
iina/PlaybackInfo.swift
1
3025
// // PlaybackInfo.swift // iina // // Created by lhc on 21/7/16. // Copyright © 2016年 lhc. All rights reserved. // import Foundation class PlaybackInfo { var fileLoading: Bool = false var currentURL: URL? var isNetworkResource: Bool = false var videoWidth: Int? var videoHeight: Int? var displayWidth: Int? var displayHeight: Int? var rotation: Int = 0 var videoPosition: VideoTime? { didSet { guard let duration = videoDuration else { return } if videoPosition!.second < 0 { videoPosition!.second = 0 } if videoPosition!.second > duration.second { videoPosition!.second = duration.second } } } var videoDuration: VideoTime? var isSeeking: Bool = false var isPaused: Bool = false var justStartedFile: Bool = false var justOpenedFile: Bool = false var disableOSDForFileLoading: Bool = false /** The current applied aspect, used for find current aspect in menu, etc. Maybe not a good approach. */ var unsureAspect: String = "Default" var unsureCrop: String = "None" var cropFilter: MPVFilter? var flipFilter: MPVFilter? var mirrorFilter: MPVFilter? var audioEqFilter: MPVFilter? var deinterlace: Bool = false // video equalizer var brightness: Int = 0 var contrast: Int = 0 var saturation: Int = 0 var gamma: Int = 0 var hue: Int = 0 var volume: Double = 50 var isMuted: Bool = false var playSpeed: Double = 0 var audioDelay: Double = 0 var subDelay: Double = 0 // cache related var pausedForCache: Bool = false var cacheSize: Int = 0 var cacheUsed: Int = 0 var cacheSpeed: Int = 0 var cacheTime: Int = 0 var bufferingState: Int = 0 var audioTracks: [MPVTrack] = [] var videoTracks: [MPVTrack] = [] var subTracks: [MPVTrack] = [] var abLoopStatus: Int = 0 // 0: none, 1: A set, 2: B set (looping) /** Selected track IDs. Use these (instead of `isSelected` of a track) to check if selected */ var aid: Int? var sid: Int? var vid: Int? var secondSid: Int? var subEncoding: String? var haveDownloadedSub: Bool = false func trackList(_ type: MPVTrack.TrackType) -> [MPVTrack] { switch type { case .video: return videoTracks case .audio: return audioTracks case .sub, .secondSub: return subTracks } } func trackId(_ type: MPVTrack.TrackType) -> Int? { switch type { case .video: return vid case .audio: return aid case .sub: return sid case .secondSub: return secondSid } } func currentTrack(_ type: MPVTrack.TrackType) -> MPVTrack? { let id: Int?, list: [MPVTrack] switch type { case .video: id = vid list = videoTracks case .audio: id = aid list = audioTracks case .sub: id = sid list = subTracks case .secondSub: id = secondSid list = subTracks } if let id = id { return list.filter { $0.id == id }.at(0) } else { return nil } } var playlist: [MPVPlaylistItem] = [] var chapters: [MPVChapter] = [] }
gpl-3.0
f6ecc619ac48b5af64cc965fc9ef5439
21.220588
106
0.646261
3.703431
false
false
false
false
nathantannar4/InputBarAccessoryView
Example/Sources/Example ViewControllers/CommonTableViewController.swift
1
13546
// // CommonTableViewController.swift // Example // // Created by Nathan Tannar on 2018-07-10. // Copyright © 2018 Nathan Tannar. All rights reserved. // import UIKit import InputBarAccessoryView class CommonTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let inputBar: InputBarAccessoryView let tableView = UITableView() let conversation: SampleData.Conversation private let mentionTextAttributes: [NSAttributedString.Key : Any] = [ .font: UIFont.preferredFont(forTextStyle: .body), .foregroundColor: UIColor.systemBlue, .backgroundColor: UIColor.systemBlue.withAlphaComponent(0.1) ] /// The object that manages attachments open lazy var attachmentManager: AttachmentManager = { [unowned self] in let manager = AttachmentManager() manager.delegate = self return manager }() /// The object that manages autocomplete open lazy var autocompleteManager: AutocompleteManager = { [unowned self] in let manager = AutocompleteManager(for: self.inputBar.inputTextView) manager.delegate = self manager.dataSource = self return manager }() var hashtagAutocompletes: [AutocompleteCompletion] = { var array: [AutocompleteCompletion] = [] for _ in 1...100 { array.append(AutocompleteCompletion(text: Lorem.word(), context: nil)) } return array }() // Completions loaded async that get appeneded to local cached completions var asyncCompletions: [AutocompleteCompletion] = [] init(style: InputBarStyle, conversation: SampleData.Conversation) { self.conversation = conversation self.inputBar = style.generate() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13, *) { view.backgroundColor = .systemBackground } else { view.backgroundColor = .white } view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.keyboardDismissMode = .interactive tableView.register(ConversationCell.self, forCellReuseIdentifier: "\(ConversationCell.self)") tableView.tableFooterView = UIView() tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor), tableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor), ]) inputBar.delegate = self inputBar.inputTextView.keyboardType = .twitter // Configure AutocompleteManager autocompleteManager.register(prefix: "@", with: mentionTextAttributes) autocompleteManager.register(prefix: "#") autocompleteManager.maxSpaceCountDuringCompletion = 1 // Allow for autocompletes with a space // Set plugins inputBar.inputPlugins = [autocompleteManager, attachmentManager] // RTL Support // autocompleteManager.paragraphStyle.baseWritingDirection = .rightToLeft // inputBar.inputTextView.textAlignment = .right // inputBar.inputTextView.placeholderLabel.textAlignment = .right } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return conversation.messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConversationCell.self)", for: indexPath) cell.imageView?.image = conversation.messages[indexPath.row].user.image cell.imageView?.layer.cornerRadius = 5 cell.imageView?.clipsToBounds = true cell.textLabel?.text = conversation.messages[indexPath.row].user.name cell.textLabel?.font = .boldSystemFont(ofSize: 15) cell.textLabel?.numberOfLines = 0 if #available(iOS 13, *) { cell.detailTextLabel?.textColor = .secondaryLabel } else { cell.detailTextLabel?.textColor = .darkGray } cell.detailTextLabel?.font = .systemFont(ofSize: 14) cell.detailTextLabel?.text = conversation.messages[indexPath.row].text cell.detailTextLabel?.numberOfLines = 0 cell.selectionStyle = .none return cell } } extension CommonTableViewController: InputBarAccessoryViewDelegate { // MARK: - InputBarAccessoryViewDelegate func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) { // Here we can parse for which substrings were autocompleted let attributedText = inputBar.inputTextView.attributedText! let range = NSRange(location: 0, length: attributedText.length) attributedText.enumerateAttribute(.autocompleted, in: range, options: []) { (attributes, range, stop) in let substring = attributedText.attributedSubstring(from: range) let context = substring.attribute(.autocompletedContext, at: 0, effectiveRange: nil) print("Autocompleted: `", substring, "` with context: ", context ?? []) } inputBar.inputTextView.text = String() inputBar.invalidatePlugins() // Send button activity animation inputBar.sendButton.startAnimating() inputBar.inputTextView.placeholder = "Sending..." DispatchQueue.global(qos: .default).async { // fake send request task sleep(1) DispatchQueue.main.async { [weak self] in inputBar.sendButton.stopAnimating() inputBar.inputTextView.placeholder = "Aa" self?.conversation.messages.append(SampleData.Message(user: SampleData.shared.currentUser, text: text)) let indexPath = IndexPath(row: (self?.conversation.messages.count ?? 1) - 1, section: 0) self?.tableView.insertRows(at: [indexPath], with: .automatic) self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } } } func inputBar(_ inputBar: InputBarAccessoryView, didChangeIntrinsicContentTo size: CGSize) { // Adjust content insets print(size) tableView.contentInset.bottom = size.height + 300 // keyboard size estimate } @objc func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) { guard autocompleteManager.currentSession != nil, autocompleteManager.currentSession?.prefix == "#" else { return } // Load some data asyncronously for the given session.prefix DispatchQueue.global(qos: .default).async { // fake background loading task var array: [AutocompleteCompletion] = [] for _ in 1...10 { array.append(AutocompleteCompletion(text: Lorem.word())) } sleep(1) DispatchQueue.main.async { [weak self] in self?.asyncCompletions = array self?.autocompleteManager.reloadData() } } } } extension CommonTableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) dismiss(animated: true, completion: { if let pickedImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage { let handled = self.attachmentManager.handleInput(of: pickedImage) if !handled { // throw error } } }) } } extension CommonTableViewController: AttachmentManagerDelegate { // MARK: - AttachmentManagerDelegate func attachmentManager(_ manager: AttachmentManager, shouldBecomeVisible: Bool) { setAttachmentManager(active: shouldBecomeVisible) } func attachmentManager(_ manager: AttachmentManager, didReloadTo attachments: [AttachmentManager.Attachment]) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didInsert attachment: AttachmentManager.Attachment, at index: Int) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didRemove attachment: AttachmentManager.Attachment, at index: Int) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didSelectAddAttachmentAt index: Int) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } // MARK: - AttachmentManagerDelegate Helper func setAttachmentManager(active: Bool) { let topStackView = inputBar.topStackView if active && !topStackView.arrangedSubviews.contains(attachmentManager.attachmentView) { topStackView.insertArrangedSubview(attachmentManager.attachmentView, at: topStackView.arrangedSubviews.count) topStackView.layoutIfNeeded() } else if !active && topStackView.arrangedSubviews.contains(attachmentManager.attachmentView) { topStackView.removeArrangedSubview(attachmentManager.attachmentView) topStackView.layoutIfNeeded() } } } extension CommonTableViewController: AutocompleteManagerDelegate, AutocompleteManagerDataSource { // MARK: - AutocompleteManagerDataSource func autocompleteManager(_ manager: AutocompleteManager, autocompleteSourceFor prefix: String) -> [AutocompleteCompletion] { if prefix == "@" { return conversation.users .filter { $0.name != SampleData.shared.currentUser.name } .map { user in return AutocompleteCompletion(text: user.name, context: ["id": user.id]) } } else if prefix == "#" { return hashtagAutocompletes + asyncCompletions } return [] } func autocompleteManager(_ manager: AutocompleteManager, tableView: UITableView, cellForRowAt indexPath: IndexPath, for session: AutocompleteSession) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: AutocompleteCell.reuseIdentifier, for: indexPath) as? AutocompleteCell else { fatalError("Oops, some unknown error occurred") } let users = SampleData.shared.users let name = session.completion?.text ?? "" let user = users.filter { return $0.name == name }.first cell.imageView?.image = user?.image cell.textLabel?.attributedText = manager.attributedText(matching: session, fontSize: 15) return cell } // MARK: - AutocompleteManagerDelegate func autocompleteManager(_ manager: AutocompleteManager, shouldBecomeVisible: Bool) { setAutocompleteManager(active: shouldBecomeVisible) } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldRegister prefix: String, at range: NSRange) -> Bool { return true } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldUnregister prefix: String) -> Bool { return true } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldComplete prefix: String, with text: String) -> Bool { return true } // MARK: - AutocompleteManagerDelegate Helper func setAutocompleteManager(active: Bool) { let topStackView = inputBar.topStackView if active && !topStackView.arrangedSubviews.contains(autocompleteManager.tableView) { topStackView.insertArrangedSubview(autocompleteManager.tableView, at: topStackView.arrangedSubviews.count) topStackView.layoutIfNeeded() } else if !active && topStackView.arrangedSubviews.contains(autocompleteManager.tableView) { topStackView.removeArrangedSubview(autocompleteManager.tableView) topStackView.layoutIfNeeded() } inputBar.invalidateIntrinsicContentSize() } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
mit
4a937a6fb7159cf0e5d88b325c9d959f
40.676923
174
0.672425
5.533088
false
false
false
false
X-my/UIView-MYPop
UIView+MYPop/UIViewPopupExtension.swift
1
4212
// // UIViewPopupExtension.swift // 51offer // // Created by Origheart on 16/7/12. // Copyright © 2016年 51offer. All rights reserved. // import Foundation import UIKit enum OFFPopAnimationType: String { case Fade = "Fade" case Cover = "Cover" } fileprivate class PopupAssist { var preKeyWindow: UIWindow? = nil var newWindow: UIWindow? = nil } extension UIView { func show(animationType type: OFFPopAnimationType) { let screenSize = UIScreen.main.bounds.size let newWindow = UIWindow(frame: CGRect(x:0, y:0, width:screenSize.width, height:screenSize.height)) let viewController = UIViewController() viewController.view.frame = UIScreen.main.bounds newWindow.rootViewController = viewController let popupAssist = PopupAssist() popupAssist.preKeyWindow = UIApplication.shared.keyWindow popupAssist.newWindow = newWindow objc_setAssociatedObject(self, &AssociatedKeys.kMYPopUpAssist, popupAssist, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) let kWindow = newWindow kWindow.makeKeyAndVisible() let overlayView = UIControl(frame: UIScreen.main.bounds) overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.7) overlayView.addTarget(self, action: #selector(dismiss), for: .touchUpInside) kWindow.addSubview(overlayView) kWindow.addSubview(self) objc_setAssociatedObject(self, &AssociatedKeys.kMYPopAnimationTypeKey, type.rawValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) objc_setAssociatedObject(self, &AssociatedKeys.kMYPopOverlayViewKey, overlayView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) switch type { case .Fade: self.center = CGPoint(x: kWindow.bounds.size.width / 2.0, y: kWindow.bounds.size.height / 2.0) self.fadeIn() case .Cover: var frame = self.frame frame.origin.y = overlayView.frame.size.height frame.origin.x = (overlayView.frame.size.width-frame.size.width)/2.0 self.frame = frame; self.coverIn() } } func dismiss() { let animationType = objc_getAssociatedObject(self, &AssociatedKeys.kMYPopAnimationTypeKey) as! String let type = OFFPopAnimationType.init(rawValue: animationType) let overlayView = objc_getAssociatedObject(self, &AssociatedKeys.kMYPopOverlayViewKey) as! UIControl UIView.animate(withDuration: 0.35, animations: dismissAnimation(type!), completion: { (finished) in overlayView.removeFromSuperview() self.removeFromSuperview() let assist = objc_getAssociatedObject(self, &AssociatedKeys.kMYPopUpAssist) as! PopupAssist assist.preKeyWindow?.makeKey() assist.preKeyWindow = nil assist.newWindow = nil objc_setAssociatedObject(self, &AssociatedKeys.kMYPopUpAssist, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }) } fileprivate struct AssociatedKeys { static var kMYPopAnimationTypeKey = "kMYPopAnimationTypeKey" static var kMYPopOverlayViewKey = "kMYPopOverlayViewKey" static var kMYPopUpAssist = "kMYPopUpAssist" } fileprivate func fadeIn() { self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) self.alpha = 0; UIView.animate(withDuration: 0.35, animations: { self.alpha = 1.0 self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } fileprivate func coverIn() { UIView.animate(withDuration: 0.35, animations: { self.transform = CGAffineTransform(translationX: 0, y: -self.frame.size.height) }) } fileprivate func dismissAnimation(_ type:OFFPopAnimationType) -> (Void)->Void { var animation: ((Void)->Void)! switch type { case .Fade: animation = { self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) self.alpha = 0.0 } case .Cover: animation = { self.transform = CGAffineTransform.identity } } return animation } }
mit
def5c752f7a55fc22460c9c8e583e99a
36.247788
139
0.658114
4.47766
false
false
false
false
coach-plus/ios
Pods/YPImagePicker/Source/Pages/Gallery/YPAlbumVC.swift
1
3124
// // YPAlbumVC.swift // YPImagePicker // // Created by Sacha Durand Saint Omer on 20/07/2017. // Copyright © 2017 Yummypets. All rights reserved. // import UIKit import Stevia import Photos class YPAlbumVC: UIViewController { override var prefersStatusBarHidden: Bool { return YPConfig.hidesStatusBar } var didSelectAlbum: ((YPAlbum) -> Void)? var albums = [YPAlbum]() let albumsManager: YPAlbumsManager let v = YPAlbumView() override func loadView() { view = v } required init(albumsManager: YPAlbumsManager) { self.albumsManager = albumsManager super.init(nibName: nil, bundle: nil) title = YPConfig.wordings.albumsTitle } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: YPConfig.wordings.cancel, style: .plain, target: self, action: #selector(close)) setUpTableView() fetchAlbumsInBackground() } func fetchAlbumsInBackground() { v.spinner.startAnimating() DispatchQueue.global(qos: .userInitiated).async { [weak self] in self?.albums = self?.albumsManager.fetchAlbums() ?? [] DispatchQueue.main.async { self?.v.spinner.stopAnimating() self?.v.tableView.isHidden = false self?.v.tableView.reloadData() } } } @objc func close() { dismiss(animated: true, completion: nil) } func setUpTableView() { v.tableView.isHidden = true v.tableView.dataSource = self v.tableView.delegate = self v.tableView.rowHeight = UITableView.automaticDimension v.tableView.estimatedRowHeight = 80 v.tableView.separatorStyle = .none v.tableView.register(YPAlbumCell.self, forCellReuseIdentifier: "AlbumCell") } } extension YPAlbumVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let album = albums[indexPath.row] if let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumCell", for: indexPath) as? YPAlbumCell { cell.thumbnail.backgroundColor = .ypSystemGray cell.thumbnail.image = album.thumbnail cell.title.text = album.title cell.numberOfItems.text = "\(album.numberOfItems)" return cell } return UITableViewCell() } } extension YPAlbumVC: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { didSelectAlbum?(albums[indexPath.row]) } }
mit
d5db349362a462569bb3d4cb56070f59
30.867347
114
0.606148
5.004808
false
false
false
false
taiwancek/KNLayout
Source/Classes/KNLayoutHelper.swift
1
1772
// // KNLayoutHelper.swift // KNLayout // // Created by cek on 2017/6/29. // Copyright © 2017年 . All rights reserved. // import UIKit @discardableResult public func += ( left: inout [KNRestraint], right: KNRestraint) -> [KNRestraint] { left.append(right) return left } @objc open class KNLayoutHelper:NSObject { public weak var rootView:UIView? public weak var delegate:KNLayoutDelegate? var addEdConstraints = [NSLayoutConstraint]() public func addConstraints(block:((inout [KNRestraint])->Void)) { if let view = rootView{ var constraints = [KNRestraint]() block(&constraints) for constraint in constraints{ addEdConstraints.append(constraint.add(toView:view)) } } } @objc public func updateConstraint() { guard let view = rootView else{ return } view.removeConstraints(addEdConstraints) addEdConstraints.removeAll() if UIDevice().kn.isPhone && UIDevice().kn.isLandscape && delegate?.constraintForLandscapeWithPhone != nil //phone landscape { delegate?.constraintForLandscapeWithPhone?() } else if UIDevice().kn.isPad && UIDevice().kn.isLandscape && delegate?.constraintForLandscapeWithPad != nil//pad landscape { delegate?.constraintForLandscapeWithPad?() } else if UIDevice().kn.isPad && delegate?.constraintForPortraitWithPad != nil //pad portrait { delegate?.constraintForPortraitWithPad?() } else //phone portrait(default) { delegate?.constraintForPortraitWithPhone() } } }
mit
5197a09967cde2ca8136688746563ccc
23.569444
81
0.599209
4.606771
false
false
false
false
yichizhang/Swift_Useful_Extensions
SwiftUsefulExtensions-Source/DialogBox.swift
1
2778
/* Copyright (c) 2014 Yichi Zhang https://github.com/yichizhang [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 Foundation extension UIView { func drawDialogBoxInViewFrame(viewFrame:CGRect, triangleSize:CGSize, boxInsetX:CGFloat, boxInsetY:CGFloat){ let bgColor = UIColor.whiteColor() let strokeColor = UIColor.blackColor() drawDialogBoxInViewFrame(viewFrame, triangleSize:triangleSize, trianglePosition:0.5, boxInsetX:boxInsetX, boxInsetY:boxInsetY, bgColor:bgColor, strokeColor:strokeColor) } func drawDialogBoxInViewFrame(viewFrame:CGRect, triangleSize:CGSize, trianglePosition:CGFloat, boxInsetX:CGFloat, boxInsetY:CGFloat, bgColor:UIColor, strokeColor:UIColor){ let viewFrameWithInset = CGRectInset(viewFrame, boxInsetX, boxInsetY) var boxFrame = viewFrameWithInset boxFrame = CGRectMake( boxFrame.minX, boxFrame.minY, boxFrame.width, boxFrame.height - triangleSize.height ) let start:CGPoint = CGPointMake( boxFrame.minX + boxFrame.width * trianglePosition - triangleSize.width * 0.5, boxFrame.minY + boxFrame.height ) var bezierPath = UIBezierPath() bezierPath.moveToPoint( boxFrame.origin ) bezierPath.addLineToPoint( CGPointMake(boxFrame.minX, boxFrame.maxY) ) bezierPath.addLineToPoint( start ) bezierPath.addLineToPoint( CGPointMake(start.x + triangleSize.width * 0.5, start.y + triangleSize.height) ) bezierPath.addLineToPoint( CGPointMake(start.x + triangleSize.width, start.y) ) bezierPath.addLineToPoint( CGPointMake(boxFrame.maxX, boxFrame.maxY) ) bezierPath.addLineToPoint( CGPointMake(boxFrame.maxX, boxFrame.minY) ) bezierPath.addLineToPoint( boxFrame.origin ) bgColor.setFill() bezierPath.fill() strokeColor.setStroke() bezierPath.stroke() } }
mit
0f6a3139ee43437c9f6af226fbc00e92
43.822581
460
0.782577
4.115556
false
false
false
false
tamadon/nassi
ios/nassi/ViewControllers/MilkListViewController.swift
1
1576
// // MilkListViewController.swift // nassi // // Created by Hideaki Tamai on 2017/08/12. // Copyright © 2017年 tamadon. All rights reserved. // import UIKit class MilkListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet var headerView: UIView! let milkAmounts = ["60", "80", "100", "120", "140", "160", "180", "200"] override func viewDidLoad() { tableView.tableHeaderView = headerView } @IBAction func onTapCloseButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } } extension MilkListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") cell.textLabel?.text = "\(milkAmounts[indexPath.row]) ml" return cell } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return milkAmounts.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let params = ["username": "ミルク", "text": "bot: \(milkAmounts[indexPath.row]) ml :tanonda:", "icon_emoji": ":baby_bottle:"] let api = API(parameters: params) api.request(success: { _ in }, fail: { _ in }) self.dismiss(animated: true, completion: nil) } } extension MilkListViewController: UITableViewDataSource { }
mit
11d8a55753f4d511d3f951105293e0d5
28.018519
130
0.66305
4.246612
false
false
false
false
jorgevila/ioscreator
SpriteKitSwiftScenesTutorial/SpriteKitSwiftScenesTutorial/GameViewController.swift
36
2173
// // GameViewController.swift // SpriteKitSwiftScenesTutorial // // Created by Arthur Knopper on 25/01/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
76ab5d445ef77381e2d63760f73f6a21
30.492754
104
0.628164
5.614987
false
false
false
false
cherrywoods/swift-meta-serialization
Examples/Example2Translator.swift
1
3085
// // Dynamic.swift // MetaSerialization // // Copyright 2018 cherrywoods // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation @testable import MetaSerialization struct Example2Translator: MetaSupplier, Unwrapper { // MARK: - MetaSupplier func wrap<T: Encodable>(_ value: T, for encoder: MetaEncoder) throws -> Meta? { // supply metas for Strings, Doubles, Int, all LosslessStringConvertible types if value is LosslessStringConvertible { return Example2Meta.string( (value as! LosslessStringConvertible).description ) } return nil } func keyedContainerMeta() -> EncodingKeyedContainerMeta { return Example2EncodingKeyedContainerMeta() } func unkeyedContainerMeta() -> EncodingUnkeyedContainerMeta { return Example2EncodingUnkeyedContainerMeta() } // MARK: - Unwrapper func unwrap<T>(meta: Meta, toType type: T.Type, for decoder: MetaDecoder) throws -> T? where T : Decodable { guard let example2Meta = meta as? Example2Meta, case Example2Meta.string(let string) = example2Meta, type is LosslessStringConvertible.Type else { return nil } return (type as! LosslessStringConvertible.Type).init(string) as! T? } // MARK: dynamic unwrapping func unwrap(meta: Meta, toType: NilMeta.Protocol, for decoder: MetaDecoder) -> NilMeta? { guard let example2Meta = meta as? Example2Meta, case Example2Meta.string(let string) = example2Meta, string == "nil" else { return nil } return NilMarker.instance } func unwrap(meta: Meta, toType: DecodingKeyedContainerMeta.Protocol, for decoder: MetaDecoder) throws -> DecodingKeyedContainerMeta? { guard let example2Meta = meta as? Example2Meta, case Example2Meta.array(let array) = example2Meta else { return nil } return Example2DecodingKeyedContainerMeta(array: array) } func unwrap(meta: Meta, toType: DecodingUnkeyedContainerMeta.Protocol, for decoder: MetaDecoder) throws -> DecodingUnkeyedContainerMeta? { guard let example2Meta = meta as? Example2Meta, case Example2Meta.array(let array) = example2Meta else { return nil } return Example2DecodingUnkeyedContainerMeta(array: array) } }
apache-2.0
a05da374039f11dbc17cbbd12d4cb30c
31.135417
154
0.644084
4.805296
false
false
false
false
Daij-Djan/DDCalendarView
Demos/EventKitDemo_swift/EventView.swift
1
831
// // EventView.swift // Demos // // Created by Dominik Pich on 13/10/15. // Copyright © 2015 Dominik Pich. All rights reserved. // import UIKit import EventKit class EventView: DDCalendarEventView { override var active : Bool { didSet { var c = UIColor.red if let ek = self.event.userInfo["event"] as? EKEvent { c = UIColor(cgColor: ek.calendar.cgColor) } if(active) { self.backgroundColor = c.withAlphaComponent(0.8) self.layer.borderColor = c.cgColor self.layer.borderWidth = 1 } else { self.backgroundColor = c.withAlphaComponent(0.5) self.layer.borderColor = nil self.layer.borderWidth = 0 } } } }
bsd-2-clause
753963f64570808796758a0f59185167
24.9375
66
0.53253
4.278351
false
false
false
false
thanhcuong1990/swift-sample-code
SampleCode/Modules/Main/MainViewController.swift
1
1855
// // MainViewController.swift // SampleCode // // Created by Cuong Lam on 11/9/15. // Copyright © 2015 Cuong Lam. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() let vcFeatured = StoryboardManager.sharedInstance.getInitialViewController(Storyboard.Featured) as! UINavigationController vcFeatured.tabBarItem.image = UIImage(named: "star") vcFeatured.tabBarItem.title = "Featured" let vcCategories = StoryboardManager.sharedInstance.getInitialViewController(Storyboard.Categories) as! UINavigationController vcCategories.tabBarItem.image = UIImage(named: "menu") vcCategories.tabBarItem.title = "Categories" let vcSearch = StoryboardManager.sharedInstance.getInitialViewController(Storyboard.Search) as! UINavigationController vcSearch.tabBarItem.image = UIImage(named: "search") vcSearch.tabBarItem.title = "Search" let vcWishlist = StoryboardManager.sharedInstance.getInitialViewController(Storyboard.Wishlist) as! UINavigationController vcWishlist.tabBarItem.image = UIImage(named: "heart") vcWishlist.tabBarItem.title = "Wishlist" let vcAccount = StoryboardManager.sharedInstance.getInitialViewController(Storyboard.Account) as! UINavigationController vcAccount.tabBarItem.image = UIImage(named: "account") vcAccount.tabBarItem.title = "Account" self.tabBar.tintColor = UIColor.hexColor("#4dd2cb", alpha: 1.0) self.viewControllers = [vcFeatured, vcCategories, vcSearch, vcWishlist, vcAccount]; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
unlicense
259a3d1edf4db51c316750c7f50e84e8
39.304348
134
0.714132
4.983871
false
false
false
false
qianyu09/AppLove
App Love/WHC_Lib/Swift_Lib/WHC_MenuView.swift
1
58408
// // WHC_MenuView.swift // CRM // // Created by 吴海超 on 15/9/29. // Copyright © 2015年 吴海超. All rights reserved. // /* * qq:712641411 * gitHub:https://github.com/netyouli * csdn:http://blog.csdn.net/windwhc/article/category/3117381 */ import UIKit extension Array { /// 交换下标对象 mutating func exchangeObject(index1: Int , _ index2:Int){ if index1 != index2 { let object = self[index1]; self[index1] = self[index2]; self[index2] = object; } } } enum WHC_MenuViewOrientation { /// 垂直布局 case Vertical /// 横向布局 case Horizontal } enum WHC_DragOrientation { /// 向上 case Up /// 向下 case Down /// 向左 case Left /// 向右 case Right } @objc protocol WHC_MenuViewDelegate{ optional func WHCMenuView(menuView: WHC_MenuView ,item: WHC_MenuItem, title: String); optional func WHCMenuViewClickDelete(item: WHC_MenuItem); optional func WHCMenuViewClickInsertItem(); } class WHC_MenuViewParam{ /// 缓存菜单key var cacheWHCMenuKey: String!; /// 分段标题集合 var segmentPartTitles: [String]!; /// 分段图片集合 var segmentPartImageNames: [String]!; var imageDatas:NSMutableArray! /// 分段文字颜色 var txtColor = UIColor.grayColor(); /// 选择背景色 var selectedBackgroundColor: UIColor!; /// 网格线的颜色 var lineColor: UIColor = UIColor.lineColor(); /// 分割视图集合 var segmentViews: [UIView]!; // 这个属性这个版本废除不可使用 /// 菜单视图布局方向 var menuOrientation: WHC_MenuViewOrientation!; /// 每行个数 var column = 4; /// 间隙 var pading: CGFloat = 5.0; /// 字体大小 var txtSize: CGFloat = 12.0; /// 是否能够排序 var canSort = true; /// 是否能够删除 var canDelete = true; /// 是否能够添加 var canAdd = true; /// 是否显示页标签 var canShowPageCtl = true; /// 线宽 var lineWidth: CGFloat = 0.5; /// 顶部是否有线 var isShowTopLine = true; /// 是否网格显示 var isGridShow = true; /// 是否动态插入菜单项 var isDynamicInsertMenuItem = false; /// 动态插入背景图片名称 var insertMenuItemImageName: String!; /// 是否自动拉伸菜单高度 var autoStretchHeight = false; /// 是否是更多界面 var isMoreMenuItem = false; //to do /// 获取默认视图菜单配置参数 class func getWHCMenuViewDefaultParam(titles titles: [String]! , imageNames: [String]! , cacheWHCMenuKey: String)->WHC_MenuViewParam{ let param = WHC_MenuViewParam(); param.segmentPartTitles = titles; param.segmentPartImageNames = imageNames; param.selectedBackgroundColor = UIColor.themeBackgroundColor(); param.menuOrientation = .Vertical; param.cacheWHCMenuKey = cacheWHCMenuKey; return param; } } class WHC_MenuView: UIView ,WHC_MenuItemDelegate , WHC_MoreMenuItemVCDelegate , UIScrollViewDelegate{ /// 缓存标题集合key private let kWHCTitlesKey = "WHC-TitlesKey"; private let kWHCDeleteTitlesKey = "WHC-DeleteTitlesKey"; private let kWHCImageNamesKey = "WHC-ImageNamesKey"; private let kWHCAppsKey = "WHC-AppsKey"; private let kWHCDeleteAppsKey = "WHC-DeleteAppsKey"; private let kWHCDeleteImageNamesKey = "WHC-DeleteImageNamesKey"; /// 页控件高度 private let kPageCtlHeight: CGFloat = 20.0; /// 更多按钮标题 private let kMoreTxt = "●●●"; /// 动画周期 private let kWHCAnimationTime = 0.5; /// 菜单项视图集合 private var menuItems: [WHC_MenuItem]!; /// 菜单项坐标集合 private var menuItemPoints: [CGPoint]!; /// 被删除菜单项标题集合 private var deletedMenuItemTitles = [String](); /// 被删除菜单项图片名称集合 private var deletedMenuItemImageNames = [String](); /// 初始菜单项标题集合 private var menuItemTitles: [String]!; /// 初始菜单项图片名称集合 private var menuItemImageNames: [String]!; /// 开始按下点 private var startPoint = CGPointZero; /// 当前移动点 private var currentMovePoint = CGPointZero; /// 移动的菜单项 private var moveMenuItem: WHC_MenuItem!; /// 移动菜单条件是否满足 private var canMoveMenuItem = false; /// 移动菜单下标 private var moveMenuItemIndex = 0; /// 是否正在进行动画移动 private var isAnimationMoving = false; /// 是否触摸结束 private var isTouchEnd = false; /// 菜单项尺寸 private var menuItemSize: CGFloat = 0.0; /// 线宽 private var lineWidth: CGFloat = 0.5; /// 当前删除菜单项 private var currentDeleteMenuItem: WHC_MenuItem!; /// 初始偏移 private var initEdge: UIEdgeInsets!; /// 屏幕刷新时钟 private var displayLink: CADisplayLink!; /// 移动增量 private var moveIncrement = 0; /// 插入菜单图片集合 private var insertMenuImages: [UIImage]!; /// 页控件 private var pageCtl: UIPageControl!; /// 滚动控件 private var scrollView: UIScrollView!; /// 拖拽方向 private var dragOri: WHC_DragOrientation!; /// 是否继续执行偏移动画 private var canMoveAnimation = false; /// 是否进行了排序 private var isSorted = false; /// 菜单代理 var delegate: WHC_MenuViewDelegate?; /// 构建视图菜单配置参数 private var menuViewParam: WHC_MenuViewParam!{ willSet{ if self.menuViewParam == nil { self.initData(); self.layoutUI(); } } }; //MARK: - 初始化方法 convenience init(frame: CGRect , menuViewParam: WHC_MenuViewParam){ self.init(frame: frame); self.menuViewParam = menuViewParam; self.initData(); self.layoutUI(); } override init(frame: CGRect) { super.init(frame: frame); self.backgroundColor = UIColor.whiteColor(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } private func initData(){ if !self.menuViewParam.isDynamicInsertMenuItem { if self.menuViewParam.cacheWHCMenuKey != nil { if self.menuViewParam.canSort || self.menuViewParam.canDelete { let us = NSUserDefaults.standardUserDefaults(); let object = us.objectForKey(self.menuViewParam.cacheWHCMenuKey); if object != nil { let cacheInfoDict: NSDictionary = object as! NSDictionary; var titles: [String]!; var imageNames: [String]!; var deleteTitles: [String]!; var deleteImageNames: [String]!; if self.menuViewParam.isMoreMenuItem { titles = cacheInfoDict[kWHCDeleteTitlesKey] as? [String]; imageNames = cacheInfoDict[kWHCDeleteImageNamesKey] as? [String]; }else { titles = cacheInfoDict[kWHCTitlesKey] as? [String]; imageNames = cacheInfoDict[kWHCImageNamesKey] as? [String]; deleteTitles = cacheInfoDict[kWHCDeleteTitlesKey] as? [String]; deleteImageNames = cacheInfoDict[kWHCDeleteImageNamesKey] as? [String]; } var reset = false; if deleteTitles == nil || deleteImageNames == nil { deleteTitles = [String](); deleteImageNames = [String](); } if titles != nil && (titles.count + deleteTitles.count == self.menuViewParam.segmentPartTitles.count) { for (_ , title) in self.menuViewParam.segmentPartTitles.enumerate() { if !titles.contains(title) && !deleteTitles.contains(title) { //to do reset = true; break; } } }else { //to do reset = true; } if reset { us.setObject([kWHCTitlesKey: self.menuViewParam.segmentPartTitles , kWHCImageNamesKey: self.menuViewParam.segmentPartImageNames, kWHCDeleteImageNamesKey: [String](), kWHCDeleteTitlesKey: [String]()], forKey: self.menuViewParam.cacheWHCMenuKey); self.menuItemTitles = self.menuViewParam.segmentPartTitles; self.menuItemImageNames = self.menuViewParam.segmentPartImageNames; }else { self.menuItemTitles = titles; self.menuItemImageNames = imageNames; self.deletedMenuItemTitles = deleteTitles; self.deletedMenuItemImageNames = deleteImageNames; // print(titles, deleteTitles) } }else { us.setObject([kWHCTitlesKey: self.menuViewParam.segmentPartTitles , kWHCImageNamesKey: self.menuViewParam.segmentPartImageNames, kWHCDeleteImageNamesKey: [String](), kWHCDeleteTitlesKey: [String]()], forKey: self.menuViewParam.cacheWHCMenuKey); self.menuItemTitles = self.menuViewParam.segmentPartTitles; self.menuItemImageNames = self.menuViewParam.segmentPartImageNames; } us.synchronize(); }else { self.cleanMenuItemCache(); self.menuItemTitles = self.menuViewParam.segmentPartTitles; self.menuItemImageNames = self.menuViewParam.segmentPartImageNames; } }else{ self.menuItemTitles = self.menuViewParam.segmentPartTitles; self.menuItemImageNames = self.menuViewParam.segmentPartImageNames; } }else { self.menuViewParam.canAdd = false; self.menuViewParam.canSort = false; } self.menuItems = [WHC_MenuItem](); self.menuItemPoints = [CGPoint](); } private func layoutUI(){ self.scrollView = UIScrollView(frame: self.bounds); self.addSubview(self.scrollView); self.scrollView.showsHorizontalScrollIndicator = false; self.scrollView.showsVerticalScrollIndicator = false; if self.menuViewParam != nil { if !self.menuViewParam.isDynamicInsertMenuItem { if self.menuViewParam.canAdd { self.menuItemTitles.append(kMoreTxt); self.menuItemImageNames.append(""); } self.createGridViewLayout(); }else { self.insertMenuItemsImage([UIImage]()); } } if self.menuViewParam.canSort || self.menuViewParam.canDelete || self.menuViewParam.isDynamicInsertMenuItem { self.scrollView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: Selector("handleSortGesture:"))); } } //MARK: - 私有方法 /// 创建动态插入菜单 private func createDynamicInsertLayout(){ for (_ , view) in self.scrollView.subviews.enumerate() { if view is WHC_MenuItem { view.removeFromSuperview(); } } self.menuItems.removeAll(); self.menuItemPoints.removeAll(); self.menuItemSize = self.width() / CGFloat(self.menuViewParam.column); let rowCount = self.insertMenuImages.count / self.menuViewParam.column + (self.insertMenuImages.count % self.menuViewParam.column == 0 ? 0 : 1); for row in 0...rowCount - 1 { for index in 0...self.menuViewParam.column - 1 { let currentIndex = row * self.menuViewParam.column + index; if currentIndex < self.insertMenuImages.count { let menuItem = WHC_MenuItem(frame: CGRectMake(CGFloat(index) * (menuItemSize), CGFloat(row) * (menuItemSize), menuItemSize , menuItemSize), pading: self.menuViewParam.pading); menuItem.delegate = self; menuItem.index = currentIndex; menuItem.fontSize = 0; menuItem.setImage(self.insertMenuImages[currentIndex]); menuItem.selectedBackgroundColor = UIColor.clearColor(); if currentIndex == self.insertMenuImages.count - 1 { menuItem.insertMark = true; } self.menuItems.append(menuItem); self.scrollView.addSubview(menuItem); self.menuItemPoints.append(menuItem.center); } } } } /// 创建网格菜单 private func createGridViewLayout(){ for (_ , view) in self.scrollView.subviews.enumerate() { if view is WHC_MenuItem { view.removeFromSuperview(); } } self.menuItems.removeAll(); self.menuItemPoints.removeAll(); var sumCount = 0; if self.menuItemImageNames != nil || self.menuItemTitles != nil { sumCount = self.menuItemTitles == nil ? self.menuItemImageNames.count : self.menuItemTitles.count; } switch self.menuViewParam.menuOrientation! { case .Vertical: self.menuViewParam.isGridShow = false; self.menuViewParam.isShowTopLine = false; // self.lineWidth = self.menuViewParam.isGridShow ? self.menuViewParam.lineWidth : 0; self.menuItemSize = (self.width() - (self.menuViewParam.isGridShow ? CGFloat(self.menuViewParam.column - 1) * self.lineWidth : 0)) / CGFloat(self.menuViewParam.column); let rowCount = sumCount / self.menuViewParam.column + (sumCount % self.menuViewParam.column == 0 ? 0 : 1); if rowCount < 1 { return; } self.createGridViewModel(rowCount, sumCount: sumCount, page: 0, pageCount: 0); self.createGridLineLayout(); case .Horizontal: self.scrollView.delegate = self; self.menuViewParam.isShowTopLine = false; self.menuViewParam.isGridShow = false; // self.lineWidth = self.menuViewParam.isGridShow ? self.menuViewParam.lineWidth : 0; self.menuItemSize = (self.width() - (self.menuViewParam.isGridShow ? CGFloat(self.menuViewParam.column - 1) * self.lineWidth : 0)) / CGFloat(self.menuViewParam.column); let rowCount = Int(self.height() / self.menuItemSize); let pageCount = rowCount * self.menuViewParam.column; let sumPageCount = sumCount / pageCount + (sumCount % pageCount != 0 ? 1 : 0); if self.menuViewParam.canShowPageCtl && self.pageCtl == nil { self.scrollView.setHeight(CGFloat(rowCount) * self.menuItemSize); self.setHeight(CGFloat(rowCount) * self.menuItemSize + kPageCtlHeight); self.pageCtl = UIPageControl(frame: CGRectMake(0, CGFloat(rowCount) * self.menuItemSize, self.width(), kPageCtlHeight)); self.pageCtl.currentPageIndicatorTintColor = UIColor.greenColor(); self.pageCtl.pageIndicatorTintColor = UIColor(white: 0.9, alpha: 1.0); self.pageCtl.numberOfPages = sumPageCount; self.addSubview(self.pageCtl); }else if self.menuViewParam.autoStretchHeight { self.setHeight(CGFloat(rowCount) * self.menuItemSize); self.scrollView.setHeight(self.height()); } for page in 0...sumPageCount - 1 { self.createGridViewModel(rowCount, sumCount: sumCount, page: page, pageCount: pageCount); } self.scrollView.pagingEnabled = true; self.scrollView.contentSize = CGSizeMake(CGFloat(sumPageCount) * self.width(), 0); } } /// 创建网格公共模块 private func createGridViewModel(rowCount: Int , sumCount: Int, page: Int, pageCount: Int){ self.createGridViewModel(rowCount, sumCount: sumCount, page: page, pageCount: pageCount, currentRow: 0, currentColumn: 0); } /// 创建网格公共模块 private func createGridViewModel(rowCount: Int , sumCount: Int, page: Int, pageCount: Int , currentRow: Int , var currentColumn: Int){ for row in currentRow...rowCount - 1 { for index in currentColumn...self.menuViewParam.column - 1 { let currentIndex = row * self.menuViewParam.column + index + page * pageCount; if currentIndex < sumCount { var imageName = ""; if currentIndex < self.menuItemImageNames.count { imageName = self.menuItemImageNames[currentIndex]; } let title = self.menuItemTitles != nil && (currentIndex < self.menuItemTitles .count) ? self.menuItemTitles[currentIndex] : ""; let menuItem = WHC_MenuItem(frame: CGRectMake(CGFloat(index) * (menuItemSize + lineWidth) + CGFloat(page) * self.width(), CGFloat(row) * (menuItemSize + lineWidth) + (self.menuViewParam.isShowTopLine ? lineWidth : 0), menuItemSize , menuItemSize), pading: self.menuViewParam.pading); menuItem.delegate = self; menuItem.title = title; menuItem.titleColor = self.menuViewParam.txtColor; menuItem.imageName = imageName; menuItem.index = currentIndex; menuItem.fontSize = self.menuViewParam.txtSize; menuItem.selectedBackgroundColor = self.menuViewParam.selectedBackgroundColor; self.menuItems.append(menuItem); self.scrollView.addSubview(menuItem); self.menuItemPoints.append(menuItem.center); } currentColumn = 0; } } } /// 创建网格线布局 private func createGridLineLayout(){ if self.menuViewParam.isGridShow { for (_ , view) in self.scrollView.subviews.enumerate() { if view is UILabel { view.removeFromSuperview(); } } } switch self.menuViewParam.menuOrientation! { case .Vertical: let sumCount = self.menuItemTitles == nil ? self.menuItemImageNames.count : self.menuItemTitles.count; let rowCount = sumCount / self.menuViewParam.column + (sumCount % self.menuViewParam.column == 0 ? 0 : 1); if rowCount < 1 { return; } if self.menuViewParam.isGridShow && self.menuViewParam.isShowTopLine { let line = UILabel(frame: CGRectMake(0, 0, self.width(), lineWidth)); line.backgroundColor = self.menuViewParam.lineColor; self.scrollView.addSubview(line); } for row in 0...rowCount - 1 { if self.menuViewParam.isGridShow { let rowLine = UILabel(frame: CGRectMake(0, CGFloat(row + 1) * menuItemSize + CGFloat(row) * lineWidth + (self.menuViewParam.isShowTopLine ? lineWidth : 0), self.width(), lineWidth)); rowLine.backgroundColor = self.menuViewParam.lineColor; self.scrollView.addSubview(rowLine); } } if self.menuViewParam.isGridShow { for i in 1...self.menuViewParam.column { let columnLine = UILabel(frame: CGRectMake(menuItemSize * CGFloat(i) + CGFloat(i - 1) * lineWidth, lineWidth, lineWidth, CGFloat(rowCount) * menuItemSize + CGFloat(rowCount) * lineWidth)); columnLine.backgroundColor = self.menuViewParam.lineColor; self.scrollView.addSubview(columnLine); } } self.dynamicCalcSelfHeight(); break; case .Horizontal: break; } } /// 通过长按点获取对应的菜单下标 private func getMenuItemIndex(point: CGPoint) -> Int{ var index = -1; for menuItem in self.scrollView.subviews { if menuItem is WHC_MenuItem && self.moveMenuItem !== menuItem && CGRectContainsPoint(menuItem.frame, point) && (menuItem as! WHC_MenuItem).title != kMoreTxt{ index = (menuItem as! WHC_MenuItem).index; break; } } return index; } /// 通过菜单项标题获取相应的菜单项对象 private func getMenuItem(title: String) -> WHC_MenuItem!{ var menuItem: WHC_MenuItem! = nil; for (index, item) in self.menuItems.enumerate() { if item.title == title { menuItem = self.menuItems[index]; break; } } return menuItem; } /// 动态计算高度 private func dynamicCalcSelfHeight() { let sumCount = self.menuItems.count; let rowCount = sumCount / self.menuViewParam.column + (sumCount % self.menuViewParam.column == 0 ? 0 : 1); var contentHeight = CGFloat(rowCount) * menuItemSize; if self.menuViewParam.isGridShow { contentHeight += CGFloat(rowCount) * lineWidth + (self.menuViewParam.isShowTopLine ? self.lineWidth : 0); } if self.menuViewParam.autoStretchHeight { self.setHeight(contentHeight); self.scrollView.setHeight(contentHeight); }else { self.scrollView.contentSize = CGSizeMake(self.width(), contentHeight + 10); // print("scrollView-contentHeight:\(self.scrollView.contentSize)") } } //MARK: - 类方法 /// 创建删除/插入图标 class func createImage(isDelete: Bool , size: CGSize) -> UIImage! { let pading:CGFloat = 2; UIGraphicsBeginImageContext(size); let context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2); if isDelete { CGContextSetFillColorWithColor(context, UIColor.redColor().CGColor); }else { CGContextSetFillColorWithColor(context, UIColor(red: 63.0 / 255.0, green: 145.0 / 255.0, blue: 49.0 / 255.0, alpha: 1.0).CGColor); } CGContextSetStrokeColorWithColor(context, UIColor.whiteColor().CGColor); CGContextAddRect(context, CGRectMake(0, 0, size.width, size.height)); CGContextDrawPath(context, .Fill); CGContextMoveToPoint(context, pading, size.height / 2); CGContextAddLineToPoint(context, size.width - pading, size.height / 2); if !isDelete { CGContextMoveToPoint(context, size.width / 2, pading); CGContextAddLineToPoint(context, size.width / 2, size.height - pading); } CGContextDrawPath(context, .Stroke); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } //MARK: - 公共方法 /// 获取菜单项图片集合 func getImages() -> [UIImage] { var images = [UIImage](); for (_ , item) in self.menuItems.enumerate() { let imageObject = item.imageObject(); if imageObject != nil { images.append(imageObject!); } } return images; } /// 更新图片集合 func update(imagesName imagesName: [String] , titles: [String]! , deleteImages:[String]!, deleteTitles:[String]!){ if deleteImages != nil { self.deletedMenuItemImageNames = deleteImages } if deleteTitles != nil { self.deletedMenuItemTitles = deleteTitles } if imagesName.count == self.menuItems.count { for (i , menuItem) in self.menuItems.enumerate() { menuItem.imageName = imagesName[i]; } // self.dynamicCalcSelfHeight(); self.createGridViewLayout(); }else if imagesName.count > self.menuItems.count { if self.menuItemImageNames != nil { self.menuItemImageNames.removeAll(); } if self.menuItemTitles != nil { self.menuItemTitles.removeAll(); } if titles != nil { self.menuItemTitles = titles; } self.menuItemImageNames = imagesName; if self.menuItems.count > 0 { for (i , menuItem) in self.menuItems.enumerate() { menuItem.imageName = imagesName[i]; } let sumCount = imagesName.count; let rowCount = sumCount / self.menuViewParam.column + (sumCount % self.menuViewParam.column == 0 ? 0 : 1); let currentIndex = self.menuItems.count; let currentRow = currentIndex / self.menuViewParam.column + (currentIndex % self.menuViewParam.column == 0 ? 0 : 1) - 1; let currentColumn = currentIndex % self.menuViewParam.column; self.createGridViewModel(rowCount, sumCount: sumCount, page: 0, pageCount: 0, currentRow: currentRow, currentColumn: currentColumn); self.dynamicCalcSelfHeight(); }else{ self.createGridViewLayout(); } }else { if self.menuItems.count > 0 { let count = self.menuItems.count; for i in imagesName.count ... count - 1 { self.menuItems[i].removeFromSuperview(); } self.menuItems.removeRange(Range(start: imagesName.count , end: count)); for (i , menuItem) in self.menuItems.enumerate() { menuItem.imageName = imagesName[i]; } // self.dynamicCalcSelfHeight(); self.createGridViewLayout(); }else{ self.createGridViewLayout(); } } } /// 插入图片菜单集合 func insertMenuItemsImage(images: [UIImage]){ self.insertMenuImages = images; if self.menuViewParam.insertMenuItemImageName == nil { self.insertMenuImages.append(WHC_MenuView.createImage(false, size: CGSizeMake(80, 80))); }else { self.insertMenuImages.append(UIImage(named: self.menuViewParam.insertMenuItemImageName)!); } self.createDynamicInsertLayout(); } /// 处理屏幕时钟 func handleDisplayLink(){ if self.scrollView.contentOffset.y >= -self.initEdge.top { self.scrollView.setContentOffset(CGPointMake(self.scrollView.contentOffset.x, self.scrollView.contentOffset.y - CGFloat(self.moveIncrement)), animated: false); self.moveMenuItem.center = CGPointMake(self.moveMenuItem.centerX(), self.moveMenuItem.centerY() - CGFloat(self.moveIncrement)); switch self.dragOri! { case .Up: if self.scrollView.contentOffset.y < -self.initEdge.top { self.moveIncrement = 0; self.scrollView.contentOffset.y = -self.initEdge.top; self.removeDisplayerLink(); } case .Down: if self.scrollView.contentSize.height - self.height() + self.initEdge.bottom <= self.scrollView.contentOffset.y{ self.scrollView.contentOffset.y = self.scrollView.contentSize.height - self.height() + self.initEdge.bottom; self.moveIncrement = 0; self.removeDisplayerLink(); } case .Left: break; case .Right: break; } self.sortWHCMenuView(self.moveMenuItem.center , isSorted: nil); } } /// 获取添加菜单项标题集合 func getInsertTitles() -> [String]! { return self.deletedMenuItemTitles; } /// 获取添加菜单项图片名称集合 func getInsertImageNames() -> [String]! { return self.deletedMenuItemImageNames; } /// 保存删除后菜单项的状态 func saveInsertedMenuItemState(){ let us = NSUserDefaults.standardUserDefaults(); let object = us.objectForKey(self.menuViewParam.cacheWHCMenuKey); if object != nil { var titles = self.menuItemTitles; var imageNames = self.menuItemImageNames; if titles.contains(kMoreTxt) && self.menuViewParam.canAdd { titles.removeAtIndex(titles.indexOf(kMoreTxt)!); imageNames.removeAtIndex(imageNames.indexOf("")!); } us.setObject([ kWHCTitlesKey: titles , kWHCImageNamesKey: imageNames, kWHCDeleteImageNamesKey: self.deletedMenuItemImageNames, kWHCDeleteTitlesKey: self.deletedMenuItemTitles], forKey: self.menuViewParam.cacheWHCMenuKey) us.synchronize(); } } /// 保存编辑后菜单项的状态 func saveEditedMenuItemState(){ self.menuItemImageNames.removeAll(); self.menuItemTitles.removeAll(); for (_ , item) in self.menuItems.enumerate() { self.menuItemTitles.append(item.title); self.menuItemImageNames.append(item.imageName); } let us = NSUserDefaults.standardUserDefaults(); let object = us.objectForKey(self.menuViewParam.cacheWHCMenuKey); if object != nil { if self.menuViewParam.isMoreMenuItem { let cacheMenuDict: NSDictionary = object as! NSDictionary; let cacheMenuMutableDict: NSMutableDictionary = cacheMenuDict.mutableCopy() as! NSMutableDictionary; cacheMenuMutableDict.setObject(self.menuItemTitles, forKey: kWHCDeleteTitlesKey) cacheMenuMutableDict.setObject(self.menuItemImageNames, forKey: kWHCDeleteImageNamesKey); us.setObject(cacheMenuMutableDict, forKey: self.menuViewParam.cacheWHCMenuKey) us.synchronize(); }else { self.saveInsertedMenuItemState(); } } } /// 清除缓存 func cleanMenuItemCache() { let us = NSUserDefaults.standardUserDefaults(); if self.menuViewParam.cacheWHCMenuKey != nil { us.setObject([String : String](), forKey: self.menuViewParam.cacheWHCMenuKey); us.synchronize(); } } /// 通过菜单项标题设置消息红色气泡 func setMenuItemRedMark(title: String){ let menuItem = self.getMenuItem(title); if menuItem != nil { menuItem.showMark(); } } /// 通过菜单项标题移除消息红色气泡 func removeMenuItemRedMark(title: String){ let menuItem = self.getMenuItem(title); if menuItem != nil { menuItem.hideMark(); } } /// 获取菜单项标题集合 func getMenuItemTitles()->[String]{ var menuItemTitles: [String] = [String](); for (index , _) in self.menuItemTitles.enumerate() { menuItemTitles.append(self.menuItemTitles[index]); } return menuItemTitles; } //MARK: - 手势排序 private func addDisplayerLink(){ if self.displayLink == nil { self.displayLink = CADisplayLink(target: self, selector: Selector("handleDisplayLink")); self.displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode); }else{ self.displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode); } } private func stopDisplayerLink(){ if self.displayLink != nil { self.displayLink.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode); } } private func removeDisplayerLink(){ if self.displayLink != nil { self.displayLink.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode); self.displayLink.paused = true; self.displayLink.invalidate(); self.displayLink = nil; } } func handleSortGesture(sender: UILongPressGestureRecognizer){ switch sender.state { case .Began: if self.initEdge == nil { self.initEdge = self.scrollView.contentInset; } self.isSorted = false; self.currentMovePoint = CGPointZero; self.canMoveMenuItem = false; self.moveMenuItem = nil; self.isTouchEnd = false; let point = sender.locationInView(sender.view); self.moveMenuItemIndex = self.getMenuItemIndex(point); if self.moveMenuItemIndex > -1 { if self.menuViewParam.canSort { self.canMoveMenuItem = true; self.canMoveAnimation = true; } self.moveMenuItem = self.menuItems[self.moveMenuItemIndex]; if !self.moveMenuItem.insertMark { self.scrollView.bringSubviewToFront(self.moveMenuItem); self.moveMenuItem.setLongPressBackgroundColor(); for menuItem in self.menuItems { if menuItem != self.moveMenuItem { menuItem.resetBackgroundColor(); } } if self.menuViewParam.canAdd && !self.menuViewParam.canDelete { self.moveMenuItem.addInsertButton(); }else if self.menuViewParam.canDelete || self.menuViewParam.isDynamicInsertMenuItem { self.moveMenuItem.addDeleteButton(); } } self.startPoint = self.moveMenuItem.center; } case .Changed: if self.canMoveMenuItem && self.menuViewParam.canSort { self.currentMovePoint = sender.locationInView(sender.view); var moveUp = false; if self.menuViewParam.menuOrientation == .Vertical { if self.currentMovePoint.y < self.moveMenuItem.centerY() { moveUp = true; } }else { self.dragOri = .Right; if self.currentMovePoint.x < self.moveMenuItem.centerX() { self.dragOri = .Left; } } self.moveMenuItem.center = self.currentMovePoint; if !self.isAnimationMoving { self.removeDisplayerLink(); if self.menuViewParam.menuOrientation == .Vertical { if self.moveMenuItem.y() > 0 { if moveUp { self.dragOri = .Up; let diff = self.moveMenuItem.y() - self.initEdge.top - self.scrollView.contentOffset.y; if diff < -1 { self.moveIncrement = Int(-diff); self.addDisplayerLink(); } }else{ self.dragOri = .Down; let diff = self.moveMenuItem.maxY() - self.height() - self.scrollView.contentOffset.y + self.initEdge.bottom; if diff > 1 && (self.scrollView.contentOffset.y + 1) < (self.scrollView.contentSize.height - self.height()){ self.moveIncrement = Int(-diff); self.addDisplayerLink(); } } } }else { if self.moveMenuItem.x() > 0 && self.canMoveAnimation{ if self.pageCtl.currentPage < self.pageCtl.numberOfPages - 1 && self.dragOri == .Right { if moveMenuItem.maxX() > (CGFloat(self.pageCtl.currentPage + 1) * self.width() + 10) && moveMenuItem.maxX() < CGFloat(self.pageCtl.currentPage + 1) * self.width() + self.menuItemSize { self.canMoveAnimation = false; UIView.animateWithDuration(kWHCAnimationTime, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.scrollView.contentOffset = CGPointMake(CGFloat(self.pageCtl.currentPage + 1) * self.width(), 0); }, completion: { (finish) -> Void in self.pageCtl.currentPage += 1; self.moveMenuItem.center = CGPointMake(CGFloat(self.pageCtl.currentPage + 1) * self.width() - self.moveMenuItem.width() / 2.0, self.moveMenuItem.centerY()); self.setMoveAnimation(); }); } }else if self.pageCtl.currentPage > 0 { if moveMenuItem.x() < (CGFloat(self.pageCtl.currentPage) * self.width() - 10) { self.canMoveAnimation = false; UIView.animateWithDuration(kWHCAnimationTime, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.scrollView.contentOffset = CGPointMake(CGFloat(self.pageCtl.currentPage - 1) * self.width(), 0); }, completion: { (finish) -> Void in self.pageCtl.currentPage -= 1; self.moveMenuItem.center = CGPointMake(CGFloat(self.pageCtl.currentPage) * self.width() + self.moveMenuItem.width() / 2.0, self.moveMenuItem.centerY()); self.setMoveAnimation(); }); } } } } self.sortWHCMenuView(self.currentMovePoint , isSorted: nil); } } case .Cancelled , .Ended: self.canMoveAnimation = false; self.removeDisplayerLink(); self.isTouchEnd = true; self.moveMenuItem?.resetRect(self.startPoint); if self.menuViewParam.canSort && self.isSorted { self.saveEditedMenuItemState(); } default: break; } } private func sortWHCMenuView(movePoint: CGPoint , isSorted: ((Bool) -> Void)?){ let currentIndex = self.getMenuItemIndex(movePoint); if currentIndex > -1 { self.isSorted = true; self.isAnimationMoving = true; UIView.animateWithDuration(kWHCAnimationTime / 2.0, animations: { () -> Void in if currentIndex > self.moveMenuItemIndex { for var i = currentIndex ; i > self.moveMenuItemIndex ; i-- { let menuItem = self.menuItems[i]; menuItem.sendSubviewToBack(self.moveMenuItem); var menuItemPoint = self.menuItemPoints[i - 1]; if i == self.moveMenuItemIndex + 1 { let movingMenuItemCenter = self.menuItemPoints[self.moveMenuItemIndex]; menuItemPoint.x = movingMenuItemCenter.x; menuItemPoint.y = movingMenuItemCenter.y; } menuItem.center = menuItemPoint; } } else if currentIndex < self.moveMenuItemIndex { for var i = currentIndex ; i < self.moveMenuItemIndex ; i++ { let menuItem = self.menuItems[i]; menuItem.sendSubviewToBack(self.moveMenuItem); var menuItemPoint = self.menuItemPoints[i + 1]; if i == self.moveMenuItemIndex - 1 { let movingMenuItemCenter = self.menuItemPoints[self.moveMenuItemIndex]; menuItemPoint.x = movingMenuItemCenter.x; menuItemPoint.y = movingMenuItemCenter.y; } menuItem.center = menuItemPoint; } } }, completion: { (finish: Bool) -> Void in self.menuItems.exchangeObject(self.moveMenuItemIndex, currentIndex); if currentIndex > self.moveMenuItemIndex { for var i = self.moveMenuItemIndex ; i < currentIndex - 1 ; i++ { self.menuItems.exchangeObject(i, i + 1); } }else if currentIndex < self.moveMenuItemIndex { for var i = self.moveMenuItemIndex ; i > currentIndex + 1; i-- { self.menuItems.exchangeObject(i, (i - 1 < 0 ? 0 : i - 1)); } } for i in 0...(self.menuItems.count - 1){ self.menuItems[i].index = i; } self.startPoint = self.menuItemPoints[currentIndex]; if self.isTouchEnd && self.startPoint != self.moveMenuItem.center { self.moveMenuItem.center = self.startPoint; self.saveEditedMenuItemState(); } self.moveMenuItemIndex = currentIndex; self.isAnimationMoving = false; isSorted?(true); }) }else { isSorted?(false); } } //MARK: - WHC_MoreMenuItemVCDelegate func WHCMoreMenuItemVC(moreVC: WHC_MoreMenuItemVC, addTitles: [String]!, addImageNames: [String]!) { if addTitles != nil { for (_ , value) in addTitles.enumerate() { self.menuItemTitles.insert(value, atIndex: self.menuItemTitles.count - 1); if self.deletedMenuItemTitles.contains(value) { self.deletedMenuItemTitles.removeAtIndex(self.deletedMenuItemTitles.indexOf(value)!); } } } if addImageNames != nil { for (_ , value) in addImageNames.enumerate() { self.menuItemImageNames.insert(value, atIndex: self.menuItemImageNames.count - 1); if self.deletedMenuItemImageNames.contains(value) { self.deletedMenuItemImageNames.removeAtIndex(self.deletedMenuItemImageNames.indexOf(value)!); } } } let us = NSUserDefaults.standardUserDefaults(); let object = us.objectForKey(self.menuViewParam.cacheWHCMenuKey); if object != nil { let cacheMenuDict: NSMutableDictionary = (object as! NSDictionary).mutableCopy() as! NSMutableDictionary; self.deletedMenuItemTitles = cacheMenuDict[self.kWHCDeleteTitlesKey] as! [String]; self.deletedMenuItemImageNames = cacheMenuDict[self.kWHCDeleteImageNamesKey] as! [String]; } self.saveInsertedMenuItemState(); self.createGridViewLayout(); } //MARK: - WHC_MenuItemDelegate func WHCMenuItemClick(item: WHC_MenuItem , title: String , index: Int){ if self.canMoveAnimation { return; } for menuItem in self.menuItems { if menuItem !== item && menuItem.pressState { return; } } if self.menuViewParam.isDynamicInsertMenuItem { if item.insertMark { self.delegate?.WHCMenuViewClickInsertItem?(); } }else { if title == kMoreTxt { var currentVC: UIViewController!; let rootVC = UIApplication.sharedApplication().delegate?.window??.rootViewController; if rootVC is UINavigationController { currentVC = (rootVC as! UINavigationController).topViewController; }else if rootVC is UITabBarController { let tabBarVC: UIViewController = (rootVC as! UITabBarController).selectedViewController!; if tabBarVC is UINavigationController { currentVC = (tabBarVC as! UINavigationController).topViewController; }else{ currentVC = tabBarVC; } }else{ currentVC = rootVC; } let vc = WHC_MoreMenuItemVC(); vc.delegate = self; vc.menuItemTitles = self.deletedMenuItemTitles; vc.menuItemImageNames = self.deletedMenuItemImageNames; vc.cacheWHCMenuKey = self.menuViewParam.cacheWHCMenuKey; vc.pading = self.menuViewParam.pading; currentVC?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: nil); }else { self.delegate?.WHCMenuView?(self , item: item , title: title); } } } func WHCMenuItemClickInsert(item: WHC_MenuItem) { let itemIndex = item.index; self.deletedMenuItemTitles.append(item.title); self.deletedMenuItemImageNames.append(item.imageName); UIView.animateWithDuration(self.kWHCAnimationTime, animations: { () -> Void in item.transform = CGAffineTransformMakeScale(0.1, 0.1); }) { (finish) -> Void in let isDeleteRow = ((self.menuItems.count % self.menuViewParam.column != 1) ? false : true); item.removeFromSuperview(); UIView.animateWithDuration(self.kWHCAnimationTime, animations: { () -> Void in if itemIndex < self.menuItems.count - 1 { for index in itemIndex + 1 ... self.menuItems.count - 1 { let nextMenuItem = self.menuItems[index]; let newNextMenuItemCenter = self.menuItemPoints[index - 1]; nextMenuItem.center = newNextMenuItemCenter; } } }, completion: { (finish) -> Void in self.menuItems.removeAtIndex(itemIndex); self.menuItemTitles.removeAtIndex(itemIndex); self.menuItemImageNames.removeAtIndex(itemIndex); self.menuItemPoints.removeAll(); if self.menuItems.count > 0 { for index in 0...self.menuItems.count - 1 { let menuItem = self.menuItems[index]; self.scrollView.bringSubviewToFront(menuItem); menuItem.index = index; self.menuItemPoints.append(menuItem.center); } } self.isAnimationMoving = false; if isDeleteRow { self.createGridLineLayout(); } let us = NSUserDefaults.standardUserDefaults(); let object = us.objectForKey(self.menuViewParam.cacheWHCMenuKey); if object != nil { let cacheMenuDict: NSMutableDictionary = (object as! NSDictionary).mutableCopy() as! NSMutableDictionary; var deleteTitles: [String] = cacheMenuDict[self.kWHCDeleteTitlesKey] as! [String]; var deleteImageNames: [String] = cacheMenuDict[self.kWHCDeleteImageNamesKey] as! [String]; if deleteImageNames.contains(item.imageName) { deleteImageNames.removeAtIndex(deleteImageNames.indexOf(item.imageName)!); } if deleteTitles.contains(item.title) { deleteTitles.removeAtIndex(deleteTitles.indexOf(item.title)!); } cacheMenuDict.setObject(deleteTitles, forKey: self.kWHCDeleteTitlesKey) cacheMenuDict.setObject(deleteImageNames, forKey: self.kWHCDeleteImageNamesKey); us.setObject(cacheMenuDict, forKey: self.menuViewParam.cacheWHCMenuKey) us.synchronize(); } }) } } func WHCMenuItemClickDelete(item: WHC_MenuItem) { self.currentDeleteMenuItem = item; self.scrollView.bringSubviewToFront(item); let itemCenterPoint = item.center; if self.menuViewParam.isDynamicInsertMenuItem { let itemIndex = item.index; UIView.animateWithDuration(self.kWHCAnimationTime, animations: { () -> Void in item.transform = CGAffineTransformMakeScale(0.1, 0.1); }) { (finish) -> Void in item.removeFromSuperview(); UIView.animateWithDuration(self.kWHCAnimationTime, animations: { () -> Void in if itemIndex < self.menuItems.count - 1 { for index in itemIndex + 1 ... self.menuItems.count - 1 { let nextMenuItem = self.menuItems[index]; self.scrollView.bringSubviewToFront(nextMenuItem); let newNextMenuItemCenter = self.menuItemPoints[index - 1]; nextMenuItem.center = newNextMenuItemCenter; } } }, completion: { (finish) -> Void in self.insertMenuImages.removeAtIndex(itemIndex); self.menuItems.removeAtIndex(itemIndex); self.menuItemPoints.removeAll(); if self.menuItems.count > 0 { for index in 0...self.menuItems.count - 1 { let menuItem = self.menuItems[index]; menuItem.index = index; self.menuItemPoints.append(menuItem.center); } } self.isAnimationMoving = false; self.delegate?.WHCMenuViewClickDelete?(item); }) } }else { if self.menuViewParam.canAdd { let moreItemCenterPoint = self.getMenuItem(kMoreTxt).center; let transform = CGAffineTransformMakeTranslation(moreItemCenterPoint.x - itemCenterPoint.x, moreItemCenterPoint.y - itemCenterPoint.y); UIView.animateWithDuration(kWHCAnimationTime, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in item.transform = CGAffineTransformScale(transform, 0.1, 0.1); }, completion: { (finish) -> Void in self.currentDeleteMenuItem.hidden = true; let itemIndex = self.currentDeleteMenuItem.index; self.deletedMenuItemTitles.append(self.currentDeleteMenuItem.title); self.deletedMenuItemImageNames.append(self.currentDeleteMenuItem.imageName); self.currentDeleteMenuItem.removeFromSuperview(); let isDeleteRow = ((self.menuItems.count % self.menuViewParam.column != 1) ? false : true); self.menuItemImageNames.removeAtIndex(itemIndex); self.menuItemTitles.removeAtIndex(itemIndex); self.isAnimationMoving = true; UIView.animateWithDuration(self.kWHCAnimationTime, animations: { () -> Void in for index in itemIndex + 1 ... self.menuItems.count - 1 { let nextMenuItem = self.menuItems[index]; let newNextMenuItemCenter = self.menuItemPoints[index - 1]; nextMenuItem.center = newNextMenuItemCenter; } }) { (finish) -> Void in self.menuItems.removeAtIndex(itemIndex); self.menuItemPoints.removeAll(); for index in 0...self.menuItems.count - 1 { let menuItem = self.menuItems[index]; self.scrollView.bringSubviewToFront(menuItem); menuItem.index = index; self.menuItemPoints.append(menuItem.center); } self.isAnimationMoving = false; self.saveEditedMenuItemState(); if isDeleteRow { self.createGridLineLayout(); } } }) }else { UIAlertView(title: "无法删除请设置canAdd = true", message: nil, delegate: nil, cancelButtonTitle: "确定").show(); } } } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.currentDeleteMenuItem.hidden = true; let itemIndex = self.currentDeleteMenuItem.index; self.deletedMenuItemTitles.append(self.currentDeleteMenuItem.title); self.deletedMenuItemImageNames.append(self.currentDeleteMenuItem.imageName); self.currentDeleteMenuItem.removeFromSuperview(); let isDeleteRow = ((self.menuItems.count % self.menuViewParam.column != 1) ? false : true); self.menuItemImageNames.removeAtIndex(itemIndex); self.menuItemTitles.removeAtIndex(itemIndex); self.isAnimationMoving = true; UIView.animateWithDuration(kWHCAnimationTime, animations: { () -> Void in for index in itemIndex + 1 ... self.menuItems.count - 1 { let nextMenuItem = self.menuItems[index]; let newNextMenuItemCenter = self.menuItemPoints[index - 1]; nextMenuItem.center = newNextMenuItemCenter; } }) { (finish) -> Void in self.menuItems.removeAtIndex(itemIndex); self.menuItemPoints.removeAll(); for index in 0...self.menuItems.count - 1 { let menuItem = self.menuItems[index]; menuItem.index = index; self.menuItemPoints.append(menuItem.center); } self.isAnimationMoving = false; self.saveEditedMenuItemState(); if isDeleteRow { self.createGridLineLayout(); } } } //MARK: - UIScrollViewDelegate func setMoveAnimation(){ self.canMoveAnimation = true; } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.pageCtl?.currentPage = Int(floor((scrollView.contentOffset.x - self.pageCtl.width() / 2.0) / self.pageCtl.width())) + 1; } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { self.performSelector(Selector("setMoveAnimation"), withObject: nil, afterDelay: 0.5); } }
mit
291b9e24bbc7fa7e8fb99f6d10fc50b0
44.548207
200
0.534856
5.127646
false
false
false
false
qasim/CDFLabs
CDFLabs/PopupView.swift
1
4617
// // PopupView.swift // CDFLabs // // Created by Qasim Iqbal on 1/6/16. // Copyright © 2016 Qasim Iqbal. All rights reserved. // import UIKit import KLCPopup class PopupView: UIView { private typealias `this` = PopupView static var popupView: PopupView? static var popup: KLCPopup? var titleLabel: UILabel? var infoLabel: UILabel? var button: UIButton? init() { super.init(frame: CGRect( x: 0, y: 0, width: 320, height: 208)) self.backgroundColor = UIColor.whiteColor() self.layer.cornerRadius = 12 self.titleLabel = UILabel() self.titleLabel!.translatesAutoresizingMaskIntoConstraints = false self.titleLabel!.textColor = UIColor.blackColor() self.titleLabel!.font = UIFont.systemFontOfSize(22.0, weight: UIFontWeightSemibold) self.titleLabel!.textAlignment = .Center self.addSubview(self.titleLabel!) self.infoLabel = UILabel() self.infoLabel!.translatesAutoresizingMaskIntoConstraints = false self.infoLabel!.textColor = UIColor.blackColor() self.infoLabel!.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightLight) self.infoLabel!.textAlignment = .Center self.infoLabel!.lineBreakMode = .ByWordWrapping self.infoLabel!.numberOfLines = 0 self.addSubview(self.infoLabel!) self.button = UIButton(type: UIButtonType.RoundedRect) self.button!.translatesAutoresizingMaskIntoConstraints = false self.button!.setTitle("Continue", forState: UIControlState.Normal) self.button!.backgroundColor = UIColor.cdfBlueColor() self.button!.layer.cornerRadius = 6 self.button!.tintColor = UIColor.whiteColor() self.button!.titleLabel!.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightSemibold) self.button!.addTarget(self, action: #selector(self.hide), forControlEvents: .TouchUpInside) self.addSubview(self.button!) let paddingView = UIView() paddingView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(paddingView) let viewsDict: [String: AnyObject] = [ "titleLabel": self.titleLabel!, "infoLabel": self.infoLabel!, "button": self.button!, "paddingView": paddingView ] let metricsDict: [String: AnyObject] = [:] let options = NSLayoutFormatOptions(rawValue: 0) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "|-16-[titleLabel]-16-|", options: options, metrics: metricsDict, views: viewsDict)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "|-20-[infoLabel]-20-|", options: options, metrics: metricsDict, views: viewsDict)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "|-20-[button]-20-|", options: options, metrics: metricsDict, views: viewsDict)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat( "V:|-20-[titleLabel]-12-[infoLabel][paddingView(>=1)]-12-[button(40)]-16-|", options: options, metrics: metricsDict, views: viewsDict)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func hide() { this.popup!.dismiss(true) } static func ensureInstance() { if this.popup == nil { this.popupView = PopupView() this.popup = KLCPopup(contentView: this.popupView!) this.popup!.showType = .BounceInFromTop this.popup!.dismissType = .FadeOut } } static func showFirstLaunchPopup() { this.ensureInstance() this.popupView!.titleLabel!.text = "Welcome to CDF Labs!" this.popupView!.infoLabel!.text = "Use this app to check the availability of CDF computers and printer queues at the University of Toronto." this.popupView!.button!.setTitle("Continue", forState: UIControlState.Normal) this.popupView!.infoLabel!.setLineHeight(1.1) this.popup!.show() } static func showFirstPrintersLaunchPopup() { this.ensureInstance() this.popupView!.titleLabel!.text = "See who's printing..." this.popupView!.infoLabel!.text = "Tap on a printer to view detailed queue information." this.popupView!.button!.setTitle("I'll try it out", forState: UIControlState.Normal) var frame = this.popupView!.frame frame.size.height = 176 this.popupView!.frame = frame this.popup!.show() } }
mit
2a4ad272b4482fd56b803a003c7a9515
35.928
148
0.658362
4.798337
false
false
false
false
VirrageS/TDL
TDL/TodayNoTaskCell.swift
1
1720
import UIKit let todayNoTaskCellHeight: CGFloat = 300 let todayNoTaskCellTextFontSize: CGFloat = 18 class TodayNoTaskCell: UITableViewCell { let nameTextLabel: UILabel override init(style: UITableViewCellStyle, reuseIdentifier: String?) { nameTextLabel = UILabel(frame: CGRectZero) nameTextLabel.backgroundColor = UIColor.whiteColor() nameTextLabel.font = UIFont.systemFontOfSize(noTaskCellTextFontSize) nameTextLabel.numberOfLines = 2 nameTextLabel.text = "No tasks for today.\nHave a nice day :)" nameTextLabel.textAlignment = NSTextAlignment.Center nameTextLabel.textColor = UIColor.blackColor() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameTextLabel) nameTextLabel.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 50)) contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: nameTextLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
1d9f3a63d74c17af6c181af8751e6b5a
52.78125
182
0.735465
5.014577
false
false
false
false
iCodesign/ICSTable
ICSTableDemo/InputViewController.swift
1
953
// // InputViewController.swift // ICSTable // // Created by LEI on 4/11/15. // Copyright (c) 2015 TouchingApp. All rights reserved. // import Foundation import ICSTable class InputViewController: WTFTable { override func viewDidLoad() { super.viewDidLoad() var tableManager = Manager() var section = Section(identifier: "section0") tableManager.addSection(section) var row = Row(identifier: "LeftTextField", type: .TextField(.Left, .Default), title: "Left") section.addRow(row) row = Row(identifier: "RightTextField", type: RowType.TextField(RowTextFieldStyle.Right, UIKeyboardType.Default), title: "Right") section.addRow(row) row = Row(identifier: "NumberTextField", type: RowType.TextField(RowTextFieldStyle.Left, UIKeyboardType.NumberPad), title: "Number") section.addRow(row) self.manager = tableManager } }
mit
978d84fe529e4a458c94487f87d8d793
28.8125
140
0.655824
4.235556
false
false
false
false
andreipitis/ASPCircleChart
Sources/ASPCircleChartSliceLayer.swift
1
2730
// // CircleChartSliceLayer.swift // ASPCircleChart // // Created by Andrei-Sergiu Pițiș on 15/06/16. // Copyright © 2016 Andrei-Sergiu Pițiș. All rights reserved. // import UIKit /** Custom layer that draws a slice of a circle. */ open class ASPCircleChartSliceLayer: CALayer { /** The start angle in radians of the slice. */ @NSManaged open var startAngle: CGFloat /** The end angle in radians of the slice. */ @NSManaged open var endAngle: CGFloat /** The color of the slice. */ open var strokeColor: UIColor = UIColor.black /** The width of the slice. Default value is 10.0. */ open var strokeWidth: CGFloat = 10.0 /** The duration of the slice animation. Default value is 0.35. */ open var animationDuration: Double = 0.35 /** The value that will be subtracted from the slice radius. */ open var radiusOffset: CGFloat = 0.0 /** The cap style of the slice. */ open var lineCapStyle: CGLineCap = .butt public override init() { super.init() contentsScale = UIScreen.main.scale } public override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale if let layer = layer as? ASPCircleChartSliceLayer { startAngle = layer.startAngle endAngle = layer.endAngle strokeColor = layer.strokeColor strokeWidth = layer.strokeWidth lineCapStyle = layer.lineCapStyle animationDuration = layer.animationDuration radiusOffset = layer.radiusOffset } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func draw(in ctx: CGContext) { super.draw(in: ctx) UIGraphicsPushContext(ctx) let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY) let radius = min(centerPoint.x, centerPoint.y) - (strokeWidth / 2.0) - radiusOffset let bezierPath = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) strokeColor.setStroke() bezierPath.lineWidth = strokeWidth bezierPath.lineCapStyle = lineCapStyle bezierPath.stroke() UIGraphicsPopContext() } open override func action(forKey event: String) -> CAAction? { if event == "startAngle" || event == "endAngle" { let basicAnimation = CABasicAnimation(keyPath: event) basicAnimation.fromValue = presentation()?.value(forKey: event) basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut) basicAnimation.duration = animationDuration return basicAnimation } return super.action(forKey: event) } open override class func needsDisplay(forKey key: String) -> Bool { if key == "startAngle" || key == "endAngle" { return true } return super.needsDisplay(forKey: key) } }
mit
4e11acfe7b9bb5ea0c3360228469317d
23.115044
132
0.708257
3.702446
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/Order/CustomView/SkillLayoutView.swift
2
4810
// // SkillLayoutView.swift // TestLayoutView // // Created by J-bb on 16/12/1. // Copyright © 2016年 J-BB. All rights reserved. // import UIKit /** * layout 结束后回调高度 修改容器高度 */ @objc protocol LayoutStopDelegate:NSObjectProtocol { func layoutStopWithHeight(layoutView:SkillLayoutView,height:CGFloat) optional func selectedAtIndexPath(layoutView:SkillLayoutView, indexPath:NSIndexPath) } class SkillLayoutView: UIView, UICollectionViewDataSource,UICollectionViewDelegate, SkillWidthLayoutDelegate { var collectionView: UICollectionView? var showDelete = false var layout: SkillWidthLayout? weak var delegate:LayoutStopDelegate? var dataSouce:Array<SkillsModel>? { didSet { if dataSouce?.count == 0 { let skillsModel = SkillsModel() skillsModel.skill_name = "无" skillsModel.labelWidth = 30 showDelete = false dataSouce?.append(skillsModel) } collectionView!.reloadData() } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override init(frame: CGRect) { super.init(frame: frame) layout = SkillWidthLayout.init() layout?.itemHeight = 30 collectionView = UICollectionView(frame: CGRectMake(0, 0, frame.size.width, 100), collectionViewLayout: layout!) layout!.delegate = self collectionView?.delegate = self collectionView?.dataSource = self collectionView?.backgroundColor = UIColor.whiteColor() collectionView!.registerClass(SingleSkillCell.classForCoder(), forCellWithReuseIdentifier: "singleCell") addSubview(collectionView!) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SkillLayoutView.layoutStop), name: "LayoutStop", object: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layout = SkillWidthLayout.init() collectionView = UICollectionView(frame: CGRectMake(0, 0, frame.size.width, 100), collectionViewLayout: layout!) layout!.delegate = self collectionView?.delegate = self collectionView?.dataSource = self collectionView?.backgroundColor = UIColor.whiteColor() collectionView!.registerClass(SingleSkillCell.classForCoder(), forCellWithReuseIdentifier: "singleCell") addSubview(collectionView!) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SkillLayoutView.layoutStop), name: "LayoutStop", object: nil) } /** layout结束回调。传出最终高度,修改collectionView高度 */ func layoutStop() { if delegate != nil { delegate?.layoutStopWithHeight(self, height: CGFloat((layout?.finalHeight)!)) collectionView!.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, CGFloat(layout!.finalHeight)) } } /** SkillWidthLayoutDelegate 宽度自适应回调 - parameter layout: - parameter atIndexPath: item所在的indexPath - returns: item 所占宽度 */ func autoLayout(layout:SkillWidthLayout, atIndexPath:NSIndexPath)->Float { let skill = dataSouce![atIndexPath.row] let size = skill.skill_name!.boundingRectWithSize(CGSizeMake(0, 21), font: UIFont.systemFontOfSize(15), lineSpacing: 0) return Float(size.width + 30) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("singleCell", forIndexPath: indexPath) as! SingleSkillCell let skill = dataSouce![indexPath.row] cell.setupTitle(skill.skill_name!, labelWidth:skill.labelWidth,showDeleteButton: showDelete) return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSouce == nil ? 0 : (dataSouce?.count)! } /** - parameter collectionView: - parameter indexPath: */ func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { guard delegate != nil else {return} /** * 判断delegate 是否实现了 点击回调 如果实现了 则调用 selectedAtIndexPath * */ if delegate!.respondsToSelector(#selector(delegate?.selectedAtIndexPath(_:indexPath:))) { delegate?.selectedAtIndexPath!(self, indexPath: indexPath) } } }
apache-2.0
7af1dc2b21b4923e35e5b7fc759f972c
32.92029
144
0.65862
5.172376
false
false
false
false
brentdax/swift
test/ParseableInterface/inlinable-function.swift
2
7699
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/Test.swiftmodule -emit-parseable-module-interface-path %t/Test.swiftinterface -module-name Test %s // RUN: %FileCheck %s < %t/Test.swiftinterface // RUN: %target-swift-frontend -emit-module -o /dev/null -merge-modules %t/Test.swiftmodule -disable-objc-attr-requires-foundation-module -emit-parseable-module-interface-path - -module-name Test | %FileCheck %s // CHECK: public struct Foo : Hashable { public struct Foo: Hashable { // CHECK: public var inlinableGetPublicSet: [[INT:(Swift.)?Int]] { public var inlinableGetPublicSet: Int { // CHECK: @inlinable get { // CHECK-NEXT: return 3 // CHECK-NEXT: } @inlinable get { return 3 } // CHECK-NEXT: set[[NEWVALUE:(\(newValue\))?]]{{$}} set { print("I am set to \(newValue)") } // CHECK-NEXT: {{^}} } } // CHECK: public var noAccessors: [[INT]]{{$}} public var noAccessors: Int // CHECK: public var hasDidSet: [[INT]] { public var hasDidSet: Int { // CHECK-NEXT: @_transparent get{{$}} // CHECK-NEXT: set[[NEWVALUE]]{{$}} // CHECK-NOT: didSet didSet { print("b set to \(hasDidSet)") } // CHECK-NEXT: {{^}} } } // CHECK: @_transparent public var transparent: [[INT]] { // CHECK-NEXT: get { // CHECK-NEXT: return 34 // CHECK-NEXT: } // CHECK-NEXT: } @_transparent public var transparent: Int { return 34 } // CHECK: public var transparentSet: [[INT]] { public var transparentSet: Int { // CHECK-NEXT: get{{$}} get { return 34 } // CHECK-NEXT: @_transparent set[[NEWVALUE]] { // CHECK-NOT: #if false // CHECK-NOT: print("I should not appear") // CHECK-NOT: #else // CHECK-NOT: #if false // CHECK-NOT: print("I also should not") // CHECK-NOT: #else // CHECK: print("I am set to \(newValue)") // CHECK-NOT: #endif // CHECK-NOT: #endif // CHECK-NEXT: } @_transparent set { #if false print("I should not appear") #else #if false print("I also should not") #else print("I am set to \(newValue)") #endif #endif } } // CHECK: @inlinable public var inlinableProperty: [[INT]] { @inlinable public var inlinableProperty: Int { // CHECK: get { // CHECK: return 32 // CHECK: } get { return 32 } // CHECK: set[[NEWVALUE]] { // CHECK-NOT: #if true // CHECK: print("I am set to \(newValue)") // CHECK-NOT: #else // CHECK-NOT: print("I should not appear") // CHECK-NOT #endif // CHECK: } set { #if true print("I am set to \(newValue)") #else print("I should not appear") #endif } // CHECK-NEXT: } } // CHECK: @inlinable public var inlinableReadAndModify: [[INT]] { @inlinable public var inlinableReadAndModify: Int { // CHECK: _read { // CHECK-NEXT: yield 0 // CHECK-NEXT: } _read { yield 0 } // CHECK: _modify { // CHECK-NEXT: var x = 0 // CHECK-NEXT: yield &x // CHECK-NEXT: } _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var inlinableReadNormalModify: [[INT]] { public var inlinableReadNormalModify: Int { // CHECK: @inlinable _read { // CHECK-NEXT: yield 0 // CHECK-NEXT: } @inlinable _read { yield 0 } // CHECK: _modify{{$}} // CHECK-NOT: var x = 0 // CHECK-NOT: yield &x // CHECK-NOT: } _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var normalReadInlinableModify: [[INT]] { public var normalReadInlinableModify: Int { // CHECK: _read{{$}} // CHECK-NOT: yield 0 // CHECK-NOT: } _read { yield 0 } // CHECK: @inlinable _modify { // CHECK-NEXT: var x = 0 // CHECK-NEXT: yield &x // CHECK-NEXT: } @inlinable _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: public var normalReadAndModify: [[INT]] { public var normalReadAndModify: Int { // CHECK-NEXT: _read{{$}} _read { yield 0 } // CHECK-NEXT: _modify{{$}} _modify { var x = 0 yield &x } // CHECK-NEXT: } } // CHECK: @inlinable public func inlinableMethod() { // CHECK-NOT: #if NO // CHECK-NOT: print("Hello, world!") // CHECK-NOT: #endif // CHECK: print("Goodbye, world!") // CHECK-NEXT: } @inlinable public func inlinableMethod() { #if NO print("Hello, world!") #endif print("Goodbye, world!") } // CHECK: @_transparent [[ATTRS:(mutating public|public mutating)]] func transparentMethod() { // CHECK-NEXT: inlinableProperty = 4 // CHECK-NEXT: } @_transparent mutating public func transparentMethod() { inlinableProperty = 4 } // CHECK: @inline(__always) [[ATTRS]] func inlineAlwaysMethod() { // CHECK-NEXT: inlinableProperty = 4 // CHECK-NEXT: } @inline(__always) mutating public func inlineAlwaysMethod() { inlinableProperty = 4 } // CHECK: public func nonInlinableMethod(){{$}} // CHECK-NOT: print("Not inlinable") public func nonInlinableMethod() { print("Not inlinable") } // CHECK: public subscript(i: [[INT]]) -> [[INT]] { // CHECK-NEXT: get{{$}} // CHECK-NEXT: @inlinable set[[NEWVALUE]] { print("set") } // CHECK-NEXT: } public subscript(i: Int) -> Int { get { return 0 } @inlinable set { print("set") } } // CHECK: public subscript(j: [[INT]], k: [[INT]]) -> [[INT]] { // CHECK-NEXT: @inlinable get { return 0 } // CHECK-NEXT: set[[NEWVALUE]]{{$}} // CHECK-NEXT: } public subscript(j: Int, k: Int) -> Int { @inlinable get { return 0 } set { print("set") } } // CHECK: @inlinable public subscript(l: [[INT]], m: [[INT]], n: [[INT]]) -> [[INT]] { // CHECK-NEXT: get { return 0 } // CHECK-NEXT: set[[NEWVALUE]] { print("set") } // CHECK-NEXT: } @inlinable public subscript(l: Int, m: Int, n: Int) -> Int { get { return 0 } set { print("set") } } // CHECK: public init(value: [[INT]]) { // CHECK-NEXT: topLevelUsableFromInline() // CHECK-NEXT: noAccessors = value // CHECK-NEXT: hasDidSet = value // CHECK-NEXT: } @inlinable public init(value: Int) { topLevelUsableFromInline() noAccessors = value hasDidSet = value } // CHECK: public init(){{$}} // CHECK-NOT: noAccessors = 0 // CHECK-NOT: hasDidSet = 0 public init() { noAccessors = 0 hasDidSet = 0 } // CHECK: {{^}}} } // CHECK-NOT: private func topLevelPrivate() private func topLevelPrivate() { print("Ssshhhhh") } // CHECK: internal func topLevelUsableFromInline(){{$}} @usableFromInline internal func topLevelUsableFromInline() { topLevelPrivate() } // CHECK: @inlinable public func topLevelInlinable() { // CHECK-NEXT: topLevelUsableFromInline() // CHECK-NEXT: } @inlinable public func topLevelInlinable() { topLevelUsableFromInline() } // CHECK: public class HasInlinableDeinit { public class HasInlinableDeinit { // CHECK: public init(){{$}} public init() {} // CHECK: [[OBJC:(@objc )?]]@inlinable deinit { // CHECK-NEXT: print("goodbye") // CHECK-NEXT: } @inlinable deinit { print("goodbye") } // CHECK-NEXT: } } // CHECK: public class HasStandardDeinit { public class HasStandardDeinit { // CHECK: public init(){{$}} public init() {} // CHECK: [[OBJC]]deinit{{$}} deinit { print("goodbye") } // CHECK-NEXT: } } // CHECK: public class HasDefaultDeinit { public class HasDefaultDeinit { // CHECK: public init(){{$}} public init() {} // CHECK: [[OBJC]]deinit{{$}} // CHECK-NEXT: } }
apache-2.0
b37dfdfc2005ed4d8231028855887535
23.134796
211
0.575789
3.590951
false
false
false
false
jonatascb/Smashtag
Smashtag/TweetTableViewController.swift
1
6517
// // TweetTableViewController.swift // Smashtag // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit class TweetTableViewController: UITableViewController, UITextFieldDelegate { // MARK: - Public API var tweets = [[Tweet]]() var searchText: String? = "#stanford" { didSet { lastSuccessfulRequest = nil searchTextField?.text = searchText tweets.removeAll() tableView.reloadData() // clear out the table view refresh() } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension refresh() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // MARK: - Refreshing private var lastSuccessfulRequest: TwitterRequest? private var nextRequestToAttempt: TwitterRequest? { if lastSuccessfulRequest == nil { if searchText != nil { return TwitterRequest(search: searchText!, count: 100) } else { return nil } } else { return lastSuccessfulRequest!.requestForNewer } } @IBAction private func refresh(sender: UIRefreshControl?) { if let request = nextRequestToAttempt { request.fetchTweets { (newTweets) -> Void in dispatch_async(dispatch_get_main_queue()) { () -> Void in if newTweets.count > 0 { self.lastSuccessfulRequest = request // oops, forgot this line in lecture self.tweets.insert(newTweets, atIndex: 0) self.tableView.reloadData() self.title = self.searchText } sender?.endRefreshing() } } } else { sender?.endRefreshing() } } func refresh() { refreshControl?.beginRefreshing() refresh(refreshControl) } // MARK: - Storyboard Connectivity @IBOutlet private weak var searchTextField: UITextField! { didSet { searchTextField.delegate = self searchTextField.text = searchText } } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == searchTextField { textField.resignFirstResponder() searchText = textField.text } return true } private struct Storyboard { static let CellReuseIdentifier = "Tweet" } override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { if identifier == "Mostrar Mencoes" { if let tweetCell = sender as? TweetTableViewCell { if tweetCell.tweet!.userMentions.count + tweetCell.tweet!.hashtags.count + tweetCell.tweet!.media.count + tweetCell.tweet!.urls.count == 0 { return false } } } return true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "Mostrar Mencoes" { if let mencoesTweetViewController = segue.destinationViewController as? MencoesTweetTableViewController { if let celulaOrigem = sender as? TweetTableViewCell { mencoesTweetViewController.tweet = celulaOrigem.tweet } } } } } // MARK: - UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return tweets.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets[section].count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as! TweetTableViewCell cell.tweet = tweets[indexPath.section][indexPath.row] return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .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 } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // 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. } */ }
mit
a0e60678d9cfd74d1e9d0e3c2f6e6b2f
32.25
157
0.613012
5.691703
false
false
false
false
xmartlabs/Bender
Example/Example/Luminance.swift
1
2521
// // LuminanceLayer.swift // Bender // // Created by Mathias Claassen on 4/25/17. // Copyright © 2017 Xmartlabs. All rights reserved. // import MetalPerformanceShaders import MetalPerformanceShadersProxy import MetalBender /// Receives two input images. The first is used to take the luminance and the second is used to take the color for the output image. Used for color preservation class Luminance: NetworkLayer { var enabled: Bool // Custom kernels let pipelineLuminance: MTLComputePipelineState init(enabled: Bool, id: String? = nil) { self.enabled = enabled pipelineLuminance = MetalShaderManager.shared.getFunction(name: "luminance_transfer") super.init(id: id) } override func validate() { let incoming = getIncoming() precondition(incoming.count == 2, "Luminance layer must have two inputs") precondition(incoming[1].outputSize == incoming[0].outputSize, "Luminance layer must have two inputs with same size") } override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) { super.initialize(network: network, device: device, temporaryImage: temporaryImage) let incoming = getIncoming() outputSize = incoming[0].outputSize createOutputs(size: outputSize, temporary: temporaryImage) } override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) { let incoming = getIncoming() let input1 = incoming[0].getOutput(index: index) let input2 = incoming[1].getOutput(index: index) let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index) if !enabled { rewireIdentity(at: index, image: input1) return } let encoder = commandBuffer.makeComputeCommandEncoder()! encoder.label = "Luminance encoder" encoder.setComputePipelineState(pipelineLuminance) encoder.setTexture(input1.texture, index: 0) encoder.setTexture(input2.texture, index: 1) encoder.setTexture(output.texture, index: 2) let threadsPerGroups = MTLSizeMake(32, 8, 1) let threadGroups = MTLSizeMake(output.texture.width / threadsPerGroups.width, output.texture.height / threadsPerGroups.height, 1) encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups) encoder.endEncoding() input1.setRead() input2.setRead() } }
mit
44fb8529952493133995e7f09451a4e2
38.375
161
0.686905
4.632353
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Value Import Processors/ValueImportProcessorPrivacyPolicy.swift
1
3035
// // ValueImportProcessorPrivacyPolicy.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa class ValueImportProcessorPrivacyPolicy: ValueImportProcessor { init() { super.init(identifier: "com.apple.TCC.configuration-profile-policy.services") } override func addValue(toCurrentValue: [Any]?, cellView: PayloadCellView, completionHandler: @escaping (_ value: Any?) -> Void) throws { guard let fileURL = self.fileURL else { completionHandler(nil) return } var value = [String: Any]() // whiteList.whiteListItem.appStore value["StaticCode"] = false // whiteList.whiteListItem.disabled value["Allowed"] = true if let fileUTI = self.fileUTI, NSWorkspace.shared.type(fileUTI, conformsToType: kUTTypeApplicationBundle as String) { guard let applicationBundle = Bundle(url: fileURL), let bundleIdentifier = applicationBundle.bundleIdentifier else { throw ValueImportError("The file: \"\(self.fileURL?.lastPathComponent ?? "Unknown File")\" does not seem to be a valid application bundle.") } // Check if this bundle identifier is already added if let currentValue = toCurrentValue as? [[String: Any]], currentValue.contains(where: { $0["Identifier"] as? String == bundleIdentifier }) { completionHandler(nil) return } guard let designatedCodeRequirement = applicationBundle.designatedCodeRequirementString else { throw ValueImportError("The file: \"\(self.fileURL?.lastPathComponent ?? "Unknown File")\" did not have a designated code requirement for it's code signature, and cannot be used.") } value["IdentifierType"] = "bundleID" value["Identifier"] = bundleIdentifier value["CodeRequirement"] = designatedCodeRequirement } else { // Check if this path is already added if let currentValue = toCurrentValue as? [[String: Any]], currentValue.contains(where: { $0["Identifier"] as? String == fileURL.path }) { completionHandler(nil) return } guard let designatedCodeRequirement = SecRequirementCopyString(forURL: fileURL) else { throw ValueImportError("The file: \"\(self.fileURL?.lastPathComponent ?? "Unknown File")\" did not have a designated code requirement for it's code signature, and cannot be used.") } value["IdentifierType"] = "path" value["Identifier"] = fileURL.path value["CodeRequirement"] = designatedCodeRequirement } if var currentValue = toCurrentValue as? [[String: Any]] { currentValue.append(value) completionHandler(currentValue) } else { completionHandler([value]) } } }
mit
2d277c202d642343b8e5f6ea0a4fa620
37.897436
196
0.625577
5.204117
false
false
false
false
mansoor92/MaksabComponents
Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Segmented Control/DarkBorderSegmentedControl.swift
1
2576
import UIKit public class DarkBorderSegmentedControl: UISegmentedControl { @IBInspectable public var isLightBackground: Bool = false @IBInspectable public var cornerRadius: CGFloat = 5 override public init(frame: CGRect) { super.init(frame: frame) setup() } override public init(items: [Any]?) { super.init(items: items) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override func awakeFromNib() { setup() } //setup func setup() { var normalTextColor: UIColor! if isLightBackground{ normalTextColor = UIColor.appColor(color: .DarkText) }else{ normalTextColor = UIColor.appColor(color: .DarkText) } sharpCornersStyle(normalBackgroudColor: UIColor.clear, selectedBackggroundColor: UIColor.appColor(color: .Primary), tintColor: UIColor.appColor(color: .Primary), normalTextColor: normalTextColor, selectedTextColor: UIColor.appColor(color: .Light)) } func sharpCornersStyle(normalBackgroudColor:UIColor,selectedBackggroundColor:UIColor,tintColor:UIColor,normalTextColor: UIColor, selectedTextColor:UIColor) { // let img = UIImage.getImageFromColor(color: normalBackgroudColor, size: CGSize(width: 200, height: 200)) // self.setBackgroundImage(img, for: UIControlState.normal, barMetrics: .default) // self.setBackgroundImage(UIImage.getImageFromColor(color: selectedBackggroundColor, size: CGSize(width: 200, height: 200)), for: UIControlState.selected, barMetrics: .default) self.tintColor = tintColor let img = UIImage.getImageFromColor(color: UIColor.init(netHex: 0x979797), size: CGSize(width: 1, height: self.frame.size.height)) self.setDividerImage(img, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default) let titleTextAttributes = [NSForegroundColorAttributeName: selectedTextColor] let normalTitleTextAttributes = [NSForegroundColorAttributeName: normalTextColor] self.setTitleTextAttributes(titleTextAttributes, for: .selected) self.setTitleTextAttributes(normalTitleTextAttributes, for: .normal) self.backgroundColor = normalBackgroudColor self.layer.borderWidth = 1 self.layer.cornerRadius = 5 self.layer.borderColor = UIColor.init(netHex: 0x979797).cgColor } }
mit
2742b26f9592a4595165b52d01331393
39.888889
255
0.67896
4.982592
false
false
false
false
NorgannasAddOns/ColorDial
ColorDial/ColorCircle.swift
1
4531
// // ColorCircle.swift // ColorDial // // Created by Kenneth Allan on 1/12/2015. // Copyright © 2015 Kenneth Allan. All rights reserved. // import Cocoa class ColorCircle: NSView { var fill: NSColor = NSColor.black var bg: NSBezierPath? var downInView: Bool = false var delegate: ColorSupplyDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! var rect = self.bounds.offsetBy(dx: 1, dy: 1) rect.size.width -= 2 rect.size.height -= 2 bg = NSBezierPath(roundedRect: rect, xRadius: rect.width / 2, yRadius: rect.height / 2) self.setNeedsDisplay(self.bounds) } func changeShapeToSquare() { bg = NSBezierPath(roundedRect: NSRect(x: self.bounds.origin.x + 1, y: self.bounds.origin.y + 1, width: self.bounds.size.width - 2, height: self.bounds.size.height - 2), xRadius: 3, yRadius: 3) setNeedsDisplay(self.bounds) } override func mouseDown(with theEvent: NSEvent) { downInView = false let click = self.convert(theEvent.locationInWindow, from: nil) if let bg = self.bg { if (bg.contains(click)) { downInView = true } } } override func mouseUp(with theEvent: NSEvent) { if (downInView) { downInView = false let click = self.convert(theEvent.locationInWindow, from: nil) if let bg = self.bg { if (bg.contains(click)) { if let delegate = self.delegate { delegate.colorSupplied(fill, sender: self) } } } } } override func mouseDragged(with theEvent: NSEvent) { NSColorPanel.dragColor(fill, with: theEvent, from: self) } func setColor(_ c: NSColor) { fill = c self.setNeedsDisplay(self.bounds) } func lighten(_ color: NSColor, n: CGFloat) { var h: CGFloat = 0 var s: CGFloat = 0 var l: CGFloat = 0 var a: CGFloat = 0 color.get(&h, saturation: &s, lightness: &l, alpha: &a) fill = NSColor.colorWith(h, saturation: s, lightness: clamp(l + n), alpha: a) self.setNeedsDisplay(self.bounds) } func saturate(_ color: NSColor, n: CGFloat) { var h: CGFloat = 0 var s: CGFloat = 0 var l: CGFloat = 0 var a: CGFloat = 0 color.get(&h, saturation: &s, lightness: &l, alpha: &a) fill = NSColor.colorWith(h, saturation: clamp(s + n), lightness: l, alpha: a) self.setNeedsDisplay(self.bounds) } func setHSV(_ h: CGFloat, s: CGFloat, v: CGFloat) { fill = NSColor(hue: clamp((h/360).truncatingRemainder(dividingBy: 360)), saturation: clamp(s/100), brightness: clamp(v/100), alpha: 1) self.setNeedsDisplay(self.bounds) } func clamp(_ value: CGFloat) -> CGFloat { if (value >= 1) { return 0.99999 } if (value <= 0) { return 0.00001 } return value } func mix(_ value: CGFloat, with: CGFloat, factor: CGFloat) -> CGFloat { return value*(1-factor) + with*factor } func adjustColor(_ brightness: CGFloat, contrast: CGFloat, saturation: CGFloat) { let r = fill.redComponent let g = fill.greenComponent let b = fill.blueComponent let br = r * brightness let bg = g * brightness let bb = b * brightness let ir = br * 0.2125 let ig = bg * 0.7154 let ib = bb * 0.0721 let sr = mix(ir, with: br, factor: saturation) let sg = mix(ig, with: bg, factor: saturation) let sb = mix(ib, with: bb, factor: saturation) let cr = mix(0.5, with: sr, factor: contrast) let cg = mix(0.5, with: sg, factor: contrast) let cb = mix(0.5, with: sb, factor: contrast) fill = NSColor(red: clamp(cr), green: clamp(cg), blue: clamp(cb), alpha: 1) } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if let bg = self.bg { NSColor.black.setStroke() fill.setFill() bg.fill() NSColor.black.setStroke() bg.lineWidth = 2 bg.stroke() NSColor.white.setStroke() bg.lineWidth = 1.25 bg.stroke() } } }
agpl-3.0
5f2381c9ab924904af01af521788fbc7
29.816327
200
0.543046
4.070081
false
false
false
false
nguyenantinhbk77/practice-swift
iCloud/Tinypix/Tinypix/TinyPixDocument.swift
2
1872
// // TinyPixDocument.swift // Tinypix // // Created by Domenico on 27.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class TinyPixDocument: UIDocument { // 8x8 bitmap data private var bitmap: [UInt8] = [] override init(fileURL url: NSURL) { bitmap = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80] super.init(fileURL: url) } /// It grabs relevant byte from our array of bytes, and then does a bit shift and /// an AND operation to determine whether the specified bit was set, /// returning true or false accordingly. func stateAt(#row: Int, column: Int) -> Bool { let rowByte = bitmap[row] let result = UInt8(1 << column) & rowByte return result != 0 } func setState(state: Bool, atRow row: Int, column: Int) { var rowByte = bitmap[row] if state { rowByte |= UInt8(1 << column) } else { rowByte &= ~UInt8(1 << column) } bitmap[row] = rowByte } func toggleStateAt(#row: Int, column: Int) { let state = stateAt(row: row, column: column) setState(!state, atRow: row, column: column) } //- MARK: UIDocument override func contentsForType(typeName: String, error outError: NSErrorPointer) -> AnyObject? { println("Saving document to URL \(fileURL)") let bitmapData = NSData(bytes: bitmap, length: bitmap.count) return bitmapData } override func loadFromContents(contents: AnyObject, ofType typeName: String, error outError: NSErrorPointer) -> Bool { println("Loading document from URL \(fileURL)") let bitmapData = contents as! NSData bitmapData.getBytes(UnsafeMutablePointer<UInt8>(bitmap), length: bitmap.count) return true } }
mit
4b899f758fbc260404bd69dd09c9cfee
31.275862
99
0.60844
4.043197
false
false
false
false
xmartlabs/XLPagerTabStrip
Example/Example/ReloadExampleViewController.swift
1
3180
// ReloadExampleViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XLPagerTabStrip class ReloadExampleViewController: UIViewController { @IBOutlet lazy var titleLabel: UILabel! = { let label = UILabel() return label }() lazy var bigLabel: UILabel = { let bigLabel = UILabel() bigLabel.backgroundColor = .clear bigLabel.textColor = .white bigLabel.font = UIFont.boldSystemFont(ofSize: 20) bigLabel.adjustsFontSizeToFitWidth = true return bigLabel }() override func viewDidLoad() { super.viewDidLoad() if navigationController != nil { navigationItem.titleView = bigLabel bigLabel.sizeToFit() } if let pagerViewController = children.first as? PagerTabStripViewController { updateTitle(of: pagerViewController) } } @IBAction func reloadTapped(_ sender: UIBarButtonItem) { for childViewController in children { guard let child = childViewController as? PagerTabStripViewController else { continue } child.reloadPagerTabStripView() updateTitle(of: child) break } } @IBAction func closeTapped(_ sender: UIButton) { dismiss(animated: true, completion: nil) } func updateTitle(of pagerTabStripViewController: PagerTabStripViewController) { func stringFromBool(_ bool: Bool) -> String { return bool ? "YES" : "NO" } titleLabel.text = "Progressive = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isProgressiveIndicator)) ElasticLimit = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isElasticIndicatorLimit))" (navigationItem.titleView as? UILabel)?.text = titleLabel.text navigationItem.titleView?.sizeToFit() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
407a67696bb688d7baf12afaa42e51f1
35.976744
228
0.694654
5.221675
false
false
false
false
MomentaBV/CwlUtils
Sources/CwlUtils/CwlRandom.swift
1
16176
// // CwlRandom.swift // CwlUtils // // Created by Matt Gallagher on 2016/05/17. // Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation public protocol RandomGenerator { init() /// Initializes the provided buffer with randomness mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) // Generates 64 bits of randomness mutating func random64() -> UInt64 // Generates 32 bits of randomness mutating func random32() -> UInt32 // Generates a uniform distribution with a maximum value no more than `max` mutating func random64(max: UInt64) -> UInt64 // Generates a uniform distribution with a maximum value no more than `max` mutating func random32(max: UInt32) -> UInt32 /// Generates a double with a random 52 bit significand on the half open range [0, 1) mutating func randomHalfOpen() -> Double /// Generates a double with a random 52 bit significand on the closed range [0, 1] mutating func randomClosed() -> Double /// Generates a double with a random 51 bit significand on the open range (0, 1) mutating func randomOpen() -> Double } public extension RandomGenerator { mutating func random64() -> UInt64 { var bits: UInt64 = 0 randomize(buffer: &bits, size: MemoryLayout<UInt64>.size) return bits } mutating func random32() -> UInt32 { var bits: UInt32 = 0 randomize(buffer: &bits, size: MemoryLayout<UInt32>.size) return bits } mutating func random64(max: UInt64) -> UInt64 { switch max { case UInt64.max: return random64() case 0: return 0 default: var result: UInt64 repeat { result = random64() } while result < UInt64.max % (max + 1) return result % (max + 1) } } mutating func random32(max: UInt32) -> UInt32 { switch max { case UInt32.max: return random32() case 0: return 0 default: var result: UInt32 repeat { result = random32() } while result < UInt32.max % (max + 1) return result % (max + 1) } } mutating func randomHalfOpen() -> Double { return halfOpenDoubleFrom64(bits: random64()) } mutating func randomClosed() -> Double { return closedDoubleFrom64(bits: random64()) } mutating func randomOpen() -> Double { return openDoubleFrom64(bits: random64()) } } public func halfOpenDoubleFrom64(bits: UInt64) -> Double { return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740992.0) } public func closedDoubleFrom64(bits: UInt64) -> Double { return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740991.0) } public func openDoubleFrom64(bits: UInt64) -> Double { return (Double(bits & 0x000f_ffff_ffff_ffff) + 0.5) * (1.0 / 9007199254740991.0) } public protocol RandomWordGenerator: RandomGenerator { associatedtype WordType mutating func randomWord() -> WordType } extension RandomWordGenerator { public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) { let b = buffer.assumingMemoryBound(to: WordType.self) for i in 0..<(size / MemoryLayout<WordType>.size) { b[i] = randomWord() } let remainder = size % MemoryLayout<WordType>.size if remainder > 0 { var final = randomWord() let b2 = buffer.assumingMemoryBound(to: UInt8.self) withUnsafePointer(to: &final) { (fin: UnsafePointer<WordType>) in fin.withMemoryRebound(to: UInt8.self, capacity: remainder) { f in for i in 0..<remainder { b2[size - i - 1] = f[i] } } } } } } public struct DevRandom: RandomGenerator { class FileDescriptor { let value: CInt init() { value = open("/dev/urandom", O_RDONLY) precondition(value >= 0) } deinit { close(value) } } let fd: FileDescriptor public init() { fd = FileDescriptor() } public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) { let result = read(fd.value, buffer, size) precondition(result == size) } public static func random64() -> UInt64 { var r = DevRandom() return r.random64() } public static func randomize(buffer: UnsafeMutableRawPointer, size: Int) { var r = DevRandom() r.randomize(buffer: buffer, size: size) } } public struct Arc4Random: RandomGenerator { public init() { } public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) { arc4random_buf(buffer, size) } public mutating func random64() -> UInt64 { // Generating 2x32-bit appears to be faster than using arc4random_buf on a 64-bit value var value: UInt64 = 0 arc4random_buf(&value, MemoryLayout<UInt64>.size) return value } public mutating func random32() -> UInt32 { return arc4random() } } public struct Lfsr258: RandomWordGenerator { public typealias WordType = UInt64 public typealias StateType = (UInt64, UInt64, UInt64, UInt64, UInt64) static let k: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 9, 12, 17, 23) static let q: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 24, 3, 5, 3) static let s: (UInt64, UInt64, UInt64, UInt64, UInt64) = (10, 5, 29, 23, 8) var state: StateType = (0, 0, 0, 0, 0) public init() { var r = DevRandom() repeat { r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size) } while state.0 < Lfsr258.k.0 repeat { r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size) } while state.1 < Lfsr258.k.1 repeat { r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size) } while state.2 < Lfsr258.k.2 repeat { r.randomize(buffer: &state.3, size: MemoryLayout<UInt64>.size) } while state.3 < Lfsr258.k.3 repeat { r.randomize(buffer: &state.4, size: MemoryLayout<UInt64>.size) } while state.4 < Lfsr258.k.4 } public init(seed: StateType) { self.state = seed } public mutating func randomWord() -> UInt64 { return random64() } public mutating func random64() -> UInt64 { // Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer: // http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps let l: UInt64 = 64 let x0 = (((state.0 << Lfsr258.q.0) ^ state.0) >> (l - Lfsr258.k.0 - Lfsr258.s.0)) state.0 = ((state.0 & (UInt64.max << Lfsr258.k.0)) << Lfsr258.s.0) | x0 let x1 = (((state.1 << Lfsr258.q.1) ^ state.1) >> (l - Lfsr258.k.1 - Lfsr258.s.1)) state.1 = ((state.1 & (UInt64.max << Lfsr258.k.1)) << Lfsr258.s.1) | x1 let x2 = (((state.2 << Lfsr258.q.2) ^ state.2) >> (l - Lfsr258.k.2 - Lfsr258.s.2)) state.2 = ((state.2 & (UInt64.max << Lfsr258.k.2)) << Lfsr258.s.2) | x2 let x3 = (((state.3 << Lfsr258.q.3) ^ state.3) >> (l - Lfsr258.k.3 - Lfsr258.s.3)) state.3 = ((state.3 & (UInt64.max << Lfsr258.k.3)) << Lfsr258.s.3) | x3 let x4 = (((state.4 << Lfsr258.q.4) ^ state.4) >> (l - Lfsr258.k.4 - Lfsr258.s.4)) state.4 = ((state.4 & (UInt64.max << Lfsr258.k.4)) << Lfsr258.s.4) | x4 return (state.0 ^ state.1 ^ state.2 ^ state.3 ^ state.4) } } public struct Lfsr176: RandomWordGenerator { public typealias WordType = UInt64 public typealias StateType = (UInt64, UInt64, UInt64) static let k: (UInt64, UInt64, UInt64) = (1, 6, 9) static let q: (UInt64, UInt64, UInt64) = (5, 19, 24) static let s: (UInt64, UInt64, UInt64) = (24, 13, 17) var state: StateType = (0, 0, 0) public init() { var r = DevRandom() repeat { r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size) } while state.0 < Lfsr176.k.0 repeat { r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size) } while state.1 < Lfsr176.k.1 repeat { r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size) } while state.2 < Lfsr176.k.2 } public init(seed: StateType) { self.state = seed } public mutating func random64() -> UInt64 { return randomWord() } public mutating func randomWord() -> UInt64 { // Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer: // http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps let l: UInt64 = 64 let x0 = (((state.0 << Lfsr176.q.0) ^ state.0) >> (l - Lfsr176.k.0 - Lfsr176.s.0)) state.0 = ((state.0 & (UInt64.max << Lfsr176.k.0)) << Lfsr176.s.0) | x0 let x1 = (((state.1 << Lfsr176.q.1) ^ state.1) >> (l - Lfsr176.k.1 - Lfsr176.s.1)) state.1 = ((state.1 & (UInt64.max << Lfsr176.k.1)) << Lfsr176.s.1) | x1 let x2 = (((state.2 << Lfsr176.q.2) ^ state.2) >> (l - Lfsr176.k.2 - Lfsr176.s.2)) state.2 = ((state.2 & (UInt64.max << Lfsr176.k.2)) << Lfsr176.s.2) | x2 return (state.0 ^ state.1 ^ state.2) } } public struct Xoroshiro: RandomWordGenerator { public typealias WordType = UInt64 public typealias StateType = (UInt64, UInt64) var state: StateType = (0, 0) public init() { DevRandom.randomize(buffer: &state, size: MemoryLayout<StateType>.size) } public init(seed: StateType) { self.state = seed } public mutating func random64() -> UInt64 { return randomWord() } public mutating func randomWord() -> UInt64 { // Directly inspired by public domain implementation here: // http://xoroshiro.di.unimi.it // by David Blackman and Sebastiano Vigna let (l, k0, k1, k2): (UInt64, UInt64, UInt64, UInt64) = (64, 55, 14, 36) let result = state.0 &+ state.1 let x = state.0 ^ state.1 state.0 = ((state.0 << k0) | (state.0 >> (l - k0))) ^ x ^ (x << k1) state.1 = (x << k2) | (x >> (l - k2)) return result } } public struct ConstantNonRandom: RandomWordGenerator { public typealias WordType = UInt64 var state: UInt64 = DevRandom.random64() public init() { } public init(seed: UInt64) { self.state = seed } public mutating func random64() -> UInt64 { return randomWord() } public mutating func randomWord() -> UInt64 { return state } } public struct MersenneTwister: RandomWordGenerator { public typealias WordType = UInt64 // 312 is 13 x 6 x 4 private var state_internal: ( UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64 ) = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) private var index: Int private static let stateCount: Int = 312 public init() { self.init(seed: DevRandom.random64()) } public init(seed: UInt64) { index = MersenneTwister.stateCount withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { state in state[0] = seed for i in 1..<MersenneTwister.stateCount { state[i] = 6364136223846793005 &* (state[i &- 1] ^ (state[i &- 1] >> 62)) &+ UInt64(i) } } } } public mutating func randomWord() -> UInt64 { return random64() } public mutating func random64() -> UInt64 { if index == MersenneTwister.stateCount { // Really dirty leaking of unsafe pointer outside its closure to ensure inlining in Swift 3 preview 1 let state = withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { $0 } } let n = MersenneTwister.stateCount let m = n / 2 let a: UInt64 = 0xB5026F5AA96619E9 let lowerMask: UInt64 = (1 << 31) - 1 let upperMask: UInt64 = ~lowerMask var (i, j, stateM) = (0, m, state[m]) repeat { let x1 = (state[i] & upperMask) | (state[i &+ 1] & lowerMask) state[i] = state[i &+ m] ^ (x1 >> 1) ^ ((state[i &+ 1] & 1) &* a) let x2 = (state[j] & upperMask) | (state[j &+ 1] & lowerMask) state[j] = state[j &- m] ^ (x2 >> 1) ^ ((state[j &+ 1] & 1) &* a) (i, j) = (i &+ 1, j &+ 1) } while i != m &- 1 let x3 = (state[m &- 1] & upperMask) | (stateM & lowerMask) state[m &- 1] = state[n &- 1] ^ (x3 >> 1) ^ ((stateM & 1) &* a) let x4 = (state[n &- 1] & upperMask) | (state[0] & lowerMask) state[n &- 1] = state[m &- 1] ^ (x4 >> 1) ^ ((state[0] & 1) &* a) index = 0 } var result = withUnsafePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { ptr in return ptr[index] } } index = index &+ 1 result ^= (result >> 29) & 0x5555555555555555 result ^= (result << 17) & 0x71D67FFFEDA60000 result ^= (result << 37) & 0xFFF7EEE000000000 result ^= result >> 43 return result } }
isc
2afc0674b48eb88603742dd9f0b3ef0e
33.635974
147
0.652736
2.76354
false
false
false
false
mshhmzh/firefox-ios
ClientTelemetry.swift
4
2597
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared private let PrefKeySearches = "Telemetry.Searches" private let PrefKeyUsageTime = "Telemetry.UsageTime" private let PrefKeyUsageCount = "Telemetry.UsageCount" class SearchTelemetry { // For data consistency, the strings used here are identical to the ones reported in Android. enum Source: String { case URLBar = "actionbar" case QuickSearch = "listitem" case Suggestion = "suggestion" } private init() {} class func makeEvent(engine engine: OpenSearchEngine, source: Source) -> TelemetryEvent { let engineID = engine.engineID ?? "other" return SearchTelemetryEvent(engineWithSource: "\(engineID).\(source.rawValue)") } class func getData(prefs: Prefs) -> [String: Int]? { return prefs.dictionaryForKey(PrefKeySearches) as? [String: Int] } class func resetCount(prefs: Prefs) { prefs.removeObjectForKey(PrefKeySearches) } } private class SearchTelemetryEvent: TelemetryEvent { private let engineWithSource: String init(engineWithSource: String) { self.engineWithSource = engineWithSource } func record(prefs: Prefs) { var searches = SearchTelemetry.getData(prefs) ?? [:] searches[engineWithSource] = (searches[engineWithSource] ?? 0) + 1 prefs.setObject(searches, forKey: PrefKeySearches) } } class UsageTelemetry { private init() {} class func makeEvent(usageInterval: Int) -> TelemetryEvent { return UsageTelemetryEvent(usageInterval: usageInterval) } class func getCount(prefs: Prefs) -> Int { return Int(prefs.intForKey(PrefKeyUsageCount) ?? 0) } class func getTime(prefs: Prefs) -> Int { return Int(prefs.intForKey(PrefKeyUsageTime) ?? 0) } class func reset(prefs: Prefs) { prefs.setInt(0, forKey: PrefKeyUsageCount) prefs.setInt(0, forKey: PrefKeyUsageTime) } } private class UsageTelemetryEvent: TelemetryEvent { private let usageInterval: Int init(usageInterval: Int) { self.usageInterval = usageInterval } func record(prefs: Prefs) { let count = Int32(UsageTelemetry.getCount(prefs) + 1) prefs.setInt(count, forKey: PrefKeyUsageCount) let time = Int32(UsageTelemetry.getTime(prefs) + usageInterval) prefs.setInt(time, forKey: PrefKeyUsageTime) } }
mpl-2.0
fa535d25e7c4386227a96df242b6ae33
29.209302
97
0.683481
4.306799
false
false
false
false
serbomjack/Firefox-for-windows-10-mobile
Providers/Profile.swift
1
39347
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import ReadingList import Shared import Storage import Sync import XCGLogger private let log = Logger.syncLogger public let NotificationProfileDidStartSyncing = "NotificationProfileDidStartSyncing" public let NotificationProfileDidFinishSyncing = "NotificationProfileDidFinishSyncing" public let ProfileRemoteTabsSyncDelay: NSTimeInterval = 0.1 public protocol SyncManager { var isSyncing: Bool { get } var lastSyncFinishTime: Timestamp? { get set } func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult func syncEverything() -> Success // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func applicationDidEnterBackground() func applicationDidBecomeActive() func onNewProfile() func onRemovedAccount(account: FirefoxAccount?) -> Success func onAddedAccount() -> Success } typealias EngineIdentifier = String typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult class ProfileFileAccessor: FileAccessor { convenience init(profile: Profile) { self.init(localName: profile.localName()) } init(localName: String) { let profileDirName = "profile.\(localName)" // Bug 1147262: First option is for device, second is for simulator. var rootPath: NSString if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path { rootPath = path as NSString } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString } super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName)) } } class CommandStoringSyncDelegate: SyncDelegate { let profile: Profile init() { profile = BrowserProfile(localName: "profile", app: nil) } func displaySentTabForURL(URL: NSURL, title: String) { let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil) self.profile.queue.addToQueue(item) } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } class BrowserProfileSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } // SyncDelegate func displaySentTabForURL(URL: NSURL, title: String) { // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them if let currentSettings = app.currentUserNotificationSettings() { if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 { if Logger.logPII { log.info("Displaying notification for URL \(URL.absoluteString)") } let notification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString) notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title] notification.alertAction = nil notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> { get } func shutdown() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } // Do we have an account at all? func hasAccount() -> Bool // Do we have an account that (as far as we know) is in a syncable state? func hasSyncableAccount() -> Bool func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(account: FirefoxAccount) func getClients() -> Deferred<Maybe<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) var syncManager: SyncManager { get } } public class BrowserProfile: Profile { private let name: String internal let files: FileAccessor weak private var app: UIApplication? /** * N.B., BrowserProfile is used from our extensions, often via a pattern like * * BrowserProfile(…).foo.saveSomething(…) * * This can break if BrowserProfile's initializer does async work that * subsequently — and asynchronously — expects the profile to stick around: * see Bug 1218833. Be sure to only perform synchronous actions here. */ init(localName: String, app: UIApplication?) { log.debug("Initing profile \(localName) on thread \(NSThread.currentThread()).") self.name = localName self.files = ProfileFileAccessor(localName: localName) self.app = app let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil) notificationCenter.addObserver(self, selector: Selector("onProfileDidFinishSyncing:"), name: NotificationProfileDidFinishSyncing, object: nil) notificationCenter.addObserver(self, selector: Selector("onPrivateDataClearedHistory:"), name: NotificationPrivateDataClearedHistory, object: nil) if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() { KeychainWrapper.serviceName = baseBundleIdentifier } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") } // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account metadata.") self.removeAccountMetadata() self.syncManager.onNewProfile() prefs.clearAll() } // Always start by needing invalidation. // This is the same as self.history.setTopSitesNeedsInvalidation, but without the // side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread. prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func shutdown() { log.debug("Shutting down profile.") if self.dbCreated { db.forceClose() } if self.loginsDBCreated { loginsDB.forceClose() } } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url), let title = notification.userInfo!["title"] as? NSString { // Only record local vists if the change notification originated from a non-private tab if !(notification.userInfo!["isPrivate"] as? Bool ?? false) { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString, title: title as String) let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType) history.addLocalVisit(visit) } history.setTopSitesNeedsInvalidation() } else { log.debug("Ignoring navigation.") } } // These selectors run on which ever thread sent the notifications (not the main thread) @objc func onProfileDidFinishSyncing(notification: NSNotification) { history.setTopSitesNeedsInvalidation() } @objc func onPrivateDataClearedHistory(notification: NSNotification) { // Immediately invalidate the top sites cache history.refreshTopSitesCache() } deinit { log.debug("Deiniting profile \(self.localName).") self.syncManager.endTimedSyncs() NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationOnLocationChange, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil) } func localName() -> String { return name } lazy var queue: TabQueue = { withExtendedLifetime(self.history) { return SQLiteQueue(db: self.db) } }() private var dbCreated = false var db: BrowserDB { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "browser.db", files: self.files) self.dbCreated = true } return Singleton.instance } /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. * * Any other class that needs to access any one of these should ensure * that this is initialized first. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = { return SQLiteHistory(db: self.db, prefs: self.prefs)! }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { return self.places } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. withExtendedLifetime(self.places) { return MergedSQLiteBookmarks(db: self.db) } }() lazy var mirrorBookmarks: BookmarkMirrorStorage = { // Yeah, this is lazy. Sorry. return self.bookmarks as! MergedSQLiteBookmarks }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() lazy var remoteClientsAndTabs: protocol<RemoteClientsAndTabs, ResettableSyncStorage, AccountRemovalDelegate> = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var syncManager: SyncManager = { return BrowserSyncManager(profile: self) }() private func getSyncDelegate() -> SyncDelegate { if let app = self.app { return BrowserProfileSyncDelegate(app: app) } return CommandStoringSyncDelegate() } public func getClients() -> Deferred<Maybe<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { let commands = items.map { item in SyncCommand.fromShareItem(item, withAction: "displayURI") } self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() } } lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = { return SQLiteLogins(db: self.loginsDB) }() // This is currently only used within the dispatch_once block in loginsDB, so we don't // have to worry about races giving us two keys. But if this were ever to be used // elsewhere, it'd be unsafe, so we wrap this in a dispatch_once, too. private var loginsKey: String? { let key = "sqlcipher.key.logins.db" struct Singleton { static var token: dispatch_once_t = 0 static var instance: String! } dispatch_once(&Singleton.token) { if KeychainWrapper.hasValueForKey(key) { let value = KeychainWrapper.stringForKey(key) Singleton.instance = value } else { let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString KeychainWrapper.setString(secret, forKey: key) Singleton.instance = secret } } return Singleton.instance } private var loginsDBCreated = false private lazy var loginsDB: BrowserDB = { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) self.loginsDBCreated = true } return Singleton.instance }() var accountConfiguration: FirefoxAccountConfiguration { let syncService: Bool = self.prefs.boolForKey("useChinaSyncService") ?? false if syncService { return ChinaEditionFirefoxAccountConfiguration() } return ProductionFirefoxAccountConfiguration() } private lazy var account: FirefoxAccount? = { if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] { return FirefoxAccount.fromDictionary(dictionary) } return nil }() func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.None } func getAccount() -> FirefoxAccount? { return account } func removeAccountMetadata() { self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) KeychainWrapper.removeObjectForKey(self.name + ".account") } func removeAccount() { let old = self.account removeAccountMetadata() self.account = nil // Tell any observers that our account has changed. NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) // Deregister for remote notifications. app?.unregisterForRemoteNotifications() } func setAccount(account: FirefoxAccount) { KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account") self.account = account // register for notifications for the account registerForNotifications() // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) self.syncManager.onAddedAccount() } func registerForNotifications() { let viewAction = UIMutableUserNotificationAction() viewAction.identifier = SentTabAction.View.rawValue viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") viewAction.activationMode = UIUserNotificationActivationMode.Foreground viewAction.destructive = false viewAction.authenticationRequired = false let bookmarkAction = UIMutableUserNotificationAction() bookmarkAction.identifier = SentTabAction.Bookmark.rawValue bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground bookmarkAction.destructive = false bookmarkAction.authenticationRequired = false let readingListAction = UIMutableUserNotificationAction() readingListAction.identifier = SentTabAction.ReadingList.rawValue readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") readingListAction.activationMode = UIUserNotificationActivationMode.Foreground readingListAction.destructive = false readingListAction.authenticationRequired = false let sentTabsCategory = UIMutableUserNotificationCategory() sentTabsCategory.identifier = TabSendCategory sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default) sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal) app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory])) app?.registerForRemoteNotifications() } // Extends NSObject so we can use timers. class BrowserSyncManager: NSObject, SyncManager { // We shouldn't live beyond our containing BrowserProfile, either in the main app or in // an extension. // But it's possible that we'll finish a side-effect sync after we've ditched the profile // as a whole, so we hold on to our Prefs, potentially for a little while longer. This is // safe as a strong reference, because there's no cycle. unowned private let profile: BrowserProfile private let prefs: Prefs let FifteenMinutes = NSTimeInterval(60 * 15) let OneMinute = NSTimeInterval(60) private var syncTimer: NSTimer? = nil private var backgrounded: Bool = true func applicationDidEnterBackground() { self.backgrounded = true self.endTimedSyncs() } func applicationDidBecomeActive() { self.backgrounded = false guard self.profile.hasAccount() else { return } self.beginTimedSyncs() // Sync now if it's been more than our threshold. let now = NSDate.now() let then = self.lastSyncFinishTime ?? 0 let since = now - then log.debug("\(since)msec since last sync.") if since > SyncConstants.SyncOnForegroundMinimumDelayMillis { self.syncEverythingSoon() } } /** * Locking is managed by withSyncInputs. Make sure you take and release these * whenever you do anything Sync-ey. */ var syncLock = OSSpinLock() { didSet { let notification = syncLock == 0 ? NotificationProfileDidFinishSyncing : NotificationProfileDidStartSyncing NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil)) } } // According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value // and a locked lock is a non-zero value var isSyncing: Bool { return syncLock != 0 } private func beginSyncing() -> Bool { return OSSpinLockTry(&syncLock) } private func endSyncing() { OSSpinLockUnlock(&syncLock) } init(profile: BrowserProfile) { self.profile = profile self.prefs = profile.prefs super.init() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "onDatabaseWasRecreated:", name: NotificationDatabaseWasRecreated, object: nil) center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil) center.addObserver(self, selector: "onFinishSyncing:", name: NotificationProfileDidFinishSyncing, object: nil) } deinit { // Remove 'em all. let center = NSNotificationCenter.defaultCenter() center.removeObserver(self, name: NotificationDatabaseWasRecreated, object: nil) center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil) center.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) } private func handleRecreationOfDatabaseNamed(name: String?) -> Success { let loginsCollections = ["passwords"] let browserCollections = ["bookmarks", "history", "tabs"] switch name ?? "<all>" { case "<all>": return self.locallyResetCollections(loginsCollections + browserCollections) case "logins.db": return self.locallyResetCollections(loginsCollections) case "browser.db": return self.locallyResetCollections(browserCollections) default: log.debug("Unknown database \(name).") return succeed() } } func doInBackgroundAfter(millis millis: Int64, _ block: dispatch_block_t) { let delay = millis * Int64(NSEC_PER_MSEC) let when = dispatch_time(DISPATCH_TIME_NOW, delay) let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_after(when, queue, block) } @objc func onDatabaseWasRecreated(notification: NSNotification) { log.debug("Database was recreated.") let name = notification.object as? String log.debug("Database was \(name).") // We run this in the background after a few hundred milliseconds; // it doesn't really matter when it runs, so long as it doesn't // happen in the middle of a sync. We take the lock to prevent that. self.doInBackgroundAfter(millis: 300) { OSSpinLockLock(&self.syncLock) self.handleRecreationOfDatabaseNamed(name).upon { res in log.debug("Reset of \(name) done: \(res.isSuccess)") OSSpinLockUnlock(&self.syncLock) } } } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(notification: NSNotification) { log.debug("Login did change.") if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = NSDate.now() // Give it a few seconds. let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered) // Trigger on the main queue. The bulk of the sync work runs in the background. let greenLight = self.greenLight() dispatch_after(when, dispatch_get_main_queue()) { if greenLight() { self.syncLogins() } } } } var lastSyncFinishTime: Timestamp? { get { return self.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime) } set(value) { if let value = value { self.prefs.setTimestamp(value, forKey: PrefsKeys.KeyLastSyncFinishTime) } else { self.prefs.removeObjectForKey(PrefsKeys.KeyLastSyncFinishTime) } } } @objc func onFinishSyncing(notification: NSNotification) { self.lastSyncFinishTime = NSDate.now() } var prefsForSync: Prefs { return self.prefs.branch("sync") } func onAddedAccount() -> Success { self.beginTimedSyncs(); return self.syncEverything() } func locallyResetCollections(collections: [String]) -> Success { return walk(collections, f: self.locallyResetCollection) } func locallyResetCollection(collection: String) -> Success { switch collection { case "bookmarks": return MirroringBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks") case "clients": fallthrough case "tabs": // Because clients and tabs share storage, and thus we wipe data for both if we reset either, // we reset the prefs for both at the same time. return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync) case "history": return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history") case "passwords": return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords") case "forms": log.debug("Requested reset for forms, but this client doesn't sync them yet.") return succeed() case "addons": log.debug("Requested reset for addons, but this client doesn't sync them.") return succeed() case "prefs": log.debug("Requested reset for prefs, but this client doesn't sync them.") return succeed() default: log.warning("Asked to reset collection \(collection), which we don't know about.") return succeed() } } func onNewProfile() { SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } func onRemovedAccount(account: FirefoxAccount?) -> Success { let profile = self.profile // Run these in order, because they might write to the same DB! let remove = [ profile.history.onRemovedAccount, profile.remoteClientsAndTabs.onRemovedAccount, profile.logins.onRemovedAccount, profile.bookmarks.onRemovedAccount, ] let clearPrefs: () -> Success = { withExtendedLifetime(self) { // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } return succeed() } return accumulate(remove) >>> clearPrefs } private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true) } func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = Selector("syncOnTimer") log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping sync timer.") self.syncTimer = nil t.invalidate() } } private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info) } private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) } private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Mirroring server bookmarks to storage.") let bookmarksMirrorer = ready.synchronizer(MirroringBookmarksSynchronizer.self, delegate: delegate, prefs: prefs) return bookmarksMirrorer.mirrorBookmarksToStorage(self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) } func takeActionsOnEngineStateChanges<T: EngineStateChanges>(changes: T) -> Deferred<Maybe<T>> { var needReset = Set<String>(changes.collectionsThatNeedLocalReset()) needReset.unionInPlace(changes.enginesDisabled()) needReset.unionInPlace(changes.enginesEnabled()) if needReset.isEmpty { log.debug("No collections need reset. Moving on.") return deferMaybe(changes) } // needReset needs at most one of clients and tabs, because we reset them // both if either needs reset. This is strictly an optimization to avoid // doing duplicate work. if needReset.contains("clients") { if needReset.remove("tabs") != nil { log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.") } } return walk(Array(needReset), f: self.locallyResetCollection) >>> effect(changes.clearLocalCommands) >>> always(changes) } /** * Returns nil if there's no account. */ private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? { if let account = profile.account { if !beginSyncing() { log.info("Not syncing \(label); already syncing something.") return deferMaybe(AlreadySyncingError()) } if let label = label { log.info("Syncing \(label).") } let authState = account.syncAuthState let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState) let delegate = profile.getSyncDelegate() let go = readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in function(delegate, self.prefsForSync, ready) } // Always unlock when we're done. go.upon({ res in self.endSyncing() }) return go } log.warning("No account; can't sync.") return nil } /** * Runs the single provided synchronization function and returns its status. */ private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult { return self.withSyncInputs(label, function: function) ?? deferMaybe(.NotStarted(.NoAccount)) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses the same length as the input. */ private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { typealias Pair = (EngineIdentifier, SyncStatus) let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Maybe<Pair>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) } } } return accumulate(thunks) } return self.withSyncInputs(nil, function: combined) ?? deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) }) } func syncEverything() -> Success { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("logins", self.syncLoginsWithDelegate), ("bookmarks", self.mirrorBookmarksWithDelegate), ("history", self.syncHistoryWithDelegate) ) >>> succeed } func syncEverythingSoon() { self.doInBackgroundAfter(millis: SyncConstants.SyncOnForegroundAfterMillis) { log.debug("Running delayed startup sync.") self.syncEverything() } } @objc func syncOnTimer() { self.syncEverything() } func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate) ) >>== { statuses in let tabsStatus = statuses[1].1 return deferMaybe(tabsStatus) } } func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } func mirrorBookmarks() -> SyncResult { return self.sync("bookmarks", function: mirrorBookmarksWithDelegate) } /** * Return a thunk that continues to return true so long as an ongoing sync * should continue. */ func greenLight() -> () -> Bool { let start = NSDate.now() // Give it one minute to run before we stop. let stopBy = start + OneMinuteInMilliseconds log.debug("Checking green light. Backgrounded: \(self.backgrounded).") return { !self.backgrounded && NSDate.now() < stopBy && self.profile.hasSyncableAccount() } } } } class AlreadySyncingError: MaybeErrorType { var description: String { return "Already syncing." } }
mpl-2.0
270ea5429ca8a0a05e273ad917968972
39.387064
238
0.637593
5.387892
false
false
false
false
ZhengShouDong/CloudPacker
Sources/CloudPacker/Service/AssetsManager.swift
1
3098
// // AssetsManager.swift // CloudPacker // // Created by ZHENGSHOUDONG on 2018/3/12. // import Foundation import PerfectLib import SwiftyJSON struct AssetsManager { fileprivate init() {} /// 替换appIcon内的图片 传入文件路径数组 public static func appIconContentsHandler(iconsFilePathArray: Array<JSON>) { let appIconDir = String(format: "%@/%@/%@/Assets.xcassets/AppIcon.appiconset", packInfoObj.currentWorkspaceDir, packInfoObj.projectName, packInfoObj.projectName) if !Dir(appIconDir).exists { printLog(message: "总工程中的[appIconDir]没找到!", type: .error) return } for iconPath in iconsFilePathArray { let path = iconPath.string ?? emptyString if path.isEmpty { printLog(message: "icon数组中有路径为空!\(iconsFilePathArray)", type: .error) continue } let file = File(path) if !file.exists { printLog(message: "icon数组中指定的路径文件不存在!\(iconsFilePathArray)", type: .error) continue } do { let fileName = String(path.split(separator: "/").last ?? Substring()) printLog(message: "icon文件名为:\(fileName), 传入的原始路径为:\(iconPath)", type: .info) try file.copyTo(path: String(format: "%@/%@", appIconDir, fileName), overWrite: true) }catch { printLog(message: "\(error)", type: .error) } } } /// 将启动图片替换 传入文件路径数组 public static func launchImageContentsHandler(imagesFilePathArray: Array<JSON>) { let launchImageDir = String(format: "%@/%@/%@/Assets.xcassets/LaunchImage.launchimage", packInfoObj.currentWorkspaceDir, packInfoObj.projectName, packInfoObj.projectName) if !Dir(launchImageDir).exists { printLog(message: "总工程中的[launchImageDir]没找到!", type: .error) return } for imagePath in imagesFilePathArray { let path = imagePath.string ?? emptyString if path.isEmpty { printLog(message: "LaunchImages数组中有路径为空!\(imagesFilePathArray)", type: .error) continue } let file = File(path) if !file.exists { printLog(message: "LaunchImages数组中指定的路径文件不存在!\(imagesFilePathArray)", type: .error) continue } do { let fileName = String(path.split(separator: "/").last ?? Substring()) printLog(message: "启动图文件名为:\(fileName), 传入的原始路径为:\(imagePath)", type: .info) try file.copyTo(path: String(format: "%@/%@", launchImageDir, fileName), overWrite: true) }catch { printLog(message: "\(error)", type: .error) } } } }
apache-2.0
6ca77775826fe9ad8af90720008740e5
36.272727
178
0.562718
4.484375
false
false
false
false
jspahrsummers/Clairvoyant
Clairvoyant/ArchiveStore.swift
1
11136
// // ArchiveStore.swift // Clairvoyant // // Created by Justin Spahr-Summers on 2015-07-25. // Copyright © 2015 Justin Spahr-Summers. All rights reserved. // import Foundation /// Represents anything which can be encoded into an archive. /// /// This is very much like the built-in <NSCoding> protocol, but is stateless /// and supports native Swift types. public protocol Archivable { /// Attempts to initialize a value of this type using an object which was /// read from an NSCoder. init?(coderRepresentation: NSCoding) /// Serializes this value into an object that can be written using an /// NSCoder. var coderRepresentation: NSCoding { get } } /// Errors that can occur when using an ArchiveStore or ArchiveTransaction. public enum ArchiveStoreError<Value: Archivable where Value: Hashable>: ErrorType { /// No entity with the specified identifier exists. case NoSuchEntity(identifier: ArchiveEntity<Value>.Identifier) /// Creating an entity failed because another entity already exists with the /// same identifier. case EntityAlreadyExists(existingEntity: ArchiveEntity<Value>) /// The given fact could not be asserted or retracted because the necessary /// preconditions were not met. case FactValidationError(fact: ArchiveFact<Value>, onEntity: ArchiveEntity<Value>) /// The specified transaction cannot be committed, because another /// transaction was successfully committed after the former was opened. case TransactionCommitConflict(attemptedTransaction: ArchiveTransaction<Value>) /// There was an error unarchiving the store from a file at the given URL. case ReadError(storeURL: NSURL) /// There was an error archiving the store to a file at the given URL. case WriteError(storeURL: NSURL) } public struct ArchiveFact<Value: Archivable where Value: Hashable>: FactType { public typealias Key = String public let key: Key public let value: Value public init(key: Key, value: Value) { self.key = key self.value = value } public var hashValue: Int { return key.hashValue ^ value.hashValue } } public func == <Value>(lhs: ArchiveFact<Value>, rhs: ArchiveFact<Value>) -> Bool { return lhs.key == rhs.key && lhs.value == rhs.value } extension ArchiveFact: Archivable { public init?(coderRepresentation: NSCoding) { guard let dictionary = coderRepresentation as? NSDictionary else { return nil } guard let key = dictionary["key"] as? Key else { return nil } guard let archivedValue = dictionary["value"] else { return nil } guard let value = Value(coderRepresentation: archivedValue as! NSCoding) else { return nil } self.init(key: key, value: value) } public var coderRepresentation: NSCoding { return [ "key": self.key, "value": self.value.coderRepresentation ] } } extension String: Archivable { public init?(coderRepresentation: NSCoding) { guard let string = coderRepresentation as? String else { return nil } self.init(string) } public var coderRepresentation: NSCoding { return self } } extension UInt: Archivable { public init?(coderRepresentation: NSCoding) { guard let number = coderRepresentation as? NSNumber else { return nil } self.init(number) } public var coderRepresentation: NSCoding { return self } } /// Attempts to unarchive an Event from the given object. private func eventWithCoderRepresentation<Value: Archivable>(coderRepresentation: NSCoding) -> Event<ArchiveFact<Value>, ArchiveEntity<Value>.Time>? { guard let dictionary = coderRepresentation as? NSDictionary else { return nil } guard let type = dictionary["type"] as? String else { return nil } guard let archivedFact = dictionary["fact"] else { return nil } guard let fact = ArchiveFact<Value>(coderRepresentation: archivedFact as! NSCoding) else { return nil } guard let archivedTime = dictionary["time"] else { return nil } guard let time = ArchiveEntity<Value>.Time(coderRepresentation: archivedTime as! NSCoding) else { return nil } switch type { case "assertion": return .Assertion(fact, time) case "retraction": return .Retraction(fact, time) default: return nil } } /// Archives an event into an object that can be encoded. private func coderRepresentationOfEvent<Value: Archivable>(event: Event<ArchiveFact<Value>, ArchiveEntity<Value>.Time>) -> NSCoding { let type: String switch event { case .Assertion: type = "assertion" case .Retraction: type = "retraction" } return [ "type": type, "fact": event.fact.coderRepresentation, "time": event.timestamp.coderRepresentation ] } public struct ArchiveEntity<Value: Archivable where Value: Hashable>: EntityType { public typealias Identifier = String public typealias Fact = ArchiveFact<Value> public typealias Time = UInt private var events: [Event<Fact, Time>] public let identifier: Identifier public let creationTimestamp: Time private init(identifier: Identifier, creationTimestamp: Time) { self.identifier = identifier self.creationTimestamp = creationTimestamp events = [] } public var history: AnyForwardCollection<Event<Fact, Time>> { return AnyForwardCollection(events) } } extension ArchiveEntity: Archivable { public init?(coderRepresentation: NSCoding) { guard let dictionary = coderRepresentation as? NSDictionary else { return nil } guard let identifier = dictionary["identifier"] as? String else { return nil } guard let archivedTime = dictionary["time"] else { return nil } guard let time = Time(coderRepresentation: archivedTime as! NSCoding) else { return nil } guard let archivedEvents = dictionary["events"] as? NSArray else { return nil } self.identifier = identifier self.creationTimestamp = time events = [] for archivedEvent in archivedEvents { guard let event: Event<Fact, Time> = eventWithCoderRepresentation(archivedEvent as! NSCoding) else { return nil } events.append(event) } } public var coderRepresentation: NSCoding { let archivedEvents = events.map(coderRepresentationOfEvent) as NSArray return [ "identifier": identifier, "events": archivedEvents, "time": creationTimestamp.coderRepresentation, ] } } public struct ArchiveTransaction<Value: Archivable where Value: Hashable>: TransactionType { public typealias Entity = ArchiveEntity<Value> private var entitiesByIdentifier: [Entity.Identifier: Entity] public let openedTimestamp: Entity.Time private init?(openedTimestamp: Entity.Time, archivedEntities: NSArray) { self.openedTimestamp = openedTimestamp entitiesByIdentifier = [:] for archivedEntity in archivedEntities { guard let entity = Entity(coderRepresentation: archivedEntity as! NSCoding) else { return nil } entitiesByIdentifier[entity.identifier] = entity } } public var entities: AnyForwardCollection<Entity> { return AnyForwardCollection(entitiesByIdentifier.values) } public mutating func createEntity(identifier: Entity.Identifier, facts: [Entity.Fact]) throws -> Entity { if let existingEntity = entitiesByIdentifier[identifier] { throw ArchiveStoreError<Value>.EntityAlreadyExists(existingEntity: existingEntity) } var entity = Entity(identifier: identifier, creationTimestamp: openedTimestamp) try assertFacts(facts, forEntity: &entity) return entity } public mutating func assertFacts(facts: [Entity.Fact], forEntityWithIdentifier identifier: Entity.Identifier) throws { guard var entity = entitiesByIdentifier[identifier] else { throw ArchiveStoreError<Value>.NoSuchEntity(identifier: identifier) } try assertFacts(facts, forEntity: &entity) } private mutating func assertFacts(facts: [Entity.Fact], inout forEntity entity: Entity) throws { for fact in facts { guard !entity.facts.contains(fact) else { throw ArchiveStoreError<Value>.FactValidationError(fact: fact, onEntity: entity) } entity.events.append(.Assertion(fact, openedTimestamp)) } entitiesByIdentifier[entity.identifier] = entity } public mutating func retractFacts(facts: [Entity.Fact], forEntityWithIdentifier identifier: Entity.Identifier) throws { guard var entity = entitiesByIdentifier[identifier] else { throw ArchiveStoreError<Value>.NoSuchEntity(identifier: identifier) } for fact in facts { guard entity.facts.contains(fact) else { throw ArchiveStoreError<Value>.FactValidationError(fact: fact, onEntity: entity) } entity.events.append(.Retraction(fact, openedTimestamp)) } entitiesByIdentifier[identifier] = entity } public subscript(identifier: Entity.Identifier) -> Entity? { return entitiesByIdentifier[identifier] } } /// A database store backed by NSKeyedArchiver, and written into a property list /// on disk. /// /// ArchiveStores do not support conflict resolution. Any transaction making /// changes should be committed before opening another transaction to make /// changes, or else a conflict could result in the second transaction being /// rejected at commit time. Any number of read-only transactions can be open /// while making changes, without issue. public final class ArchiveStore<Value: Archivable where Value: Hashable>: StoreType { public typealias Transaction = ArchiveTransaction<Value> public let storeURL: NSURL private var transactionTimestamp: Transaction.Entity.Time private var archivedEntities: NSArray /// Opens a database store that will read from and write to a property list /// at the given file URL. /// /// If the file does not exist yet, it will be created the first time /// a transaction is committed. public init?(storeURL: NSURL) { precondition(storeURL.fileURL) self.storeURL = storeURL guard let unarchivedObject = NSKeyedUnarchiver.unarchiveObjectWithFile(storeURL.path!) else { archivedEntities = [] transactionTimestamp = 0 return } guard let dictionary = unarchivedObject as? NSDictionary, let entities = dictionary["entities"] as? NSArray, let archivedTimestamp = dictionary["timestamp"], let timestamp = Transaction.Entity.Time(coderRepresentation: archivedTimestamp as! NSCoding) else { archivedEntities = [] transactionTimestamp = 0 return nil } archivedEntities = entities transactionTimestamp = timestamp } public func newTransaction() throws -> Transaction { guard let transaction = Transaction(openedTimestamp: transactionTimestamp, archivedEntities: archivedEntities) else { throw ArchiveStoreError<Value>.ReadError(storeURL: storeURL) } return transaction } public func commitTransaction(transaction: Transaction) throws { guard transaction.openedTimestamp == transactionTimestamp else { throw ArchiveStoreError<Value>.TransactionCommitConflict(attemptedTransaction: transaction) } archivedEntities = transaction.entities.map { $0.coderRepresentation } transactionTimestamp++ let dictionary: NSDictionary = [ "entities": archivedEntities, "timestamp": transactionTimestamp.coderRepresentation, ] if !NSKeyedArchiver.archiveRootObject(dictionary, toFile: storeURL.path!) { throw ArchiveStoreError<Value>.WriteError(storeURL: storeURL) } } }
mit
b807e1fb7576b161074762cb1eb0f9ff
26.8375
150
0.750516
3.991039
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Components/UIShared/DynamicActionSheet.swift
1
3717
// // DynamicActionSheet.swift // FuzFuz // // Created by Cenker Ozkurt on 10/7/19. // Copyright © 2019 FuzFuz. All rights reserved. // import UIKit open class DynamicActionSheet: AppTableBase { @IBOutlet public weak var blurView: UIView! private static var dismissing = false private var animation: Bool = true public var tableViewBottomGap: CGFloat = 0 /// set this flag to true to to use tableview as notification style /// it wil adjust tableView y position to snap to bottom with animation var defaultTableView = false open override func viewDidLoad() { super.viewDidLoad() self.tableView?.addEmptyFooter() self.tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView?.reloadData() self.resetTableHeightPosition() runOnMainQueue(after: 0.3) { self.updateTableHeight(self.tableViewBottomGap, self.animation) } } public func resetTableHeightPosition() { if defaultTableView { return } self.tableView?.frame = CGRect(x: self.tableView.frame.origin.x, y: self.view.frame.height, width: self.tableView.frame.width, height: self.tableView.frame.height) } public func updateTableHeight(_ tableViewBottomGap: CGFloat = 0, _ animation: Bool = true) { if defaultTableView { return } self.animation = animation self.tableViewBottomGap = tableViewBottomGap self.tableView?.layoutIfNeeded() UIView.animate(withDuration: animation ? 0.5 : 0, delay: 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: .curveEaseIn, animations: { let gap:CGFloat = self.tableViewBottomGap let viewHeight = self.view.frame.height let halfScreen = viewHeight / 5 let tableHeight = self.tableView?.contentSize.height ?? 0 let adjustedHeight = max(viewHeight - tableHeight, halfScreen + gap) self.tableView?.frame = CGRect(x: self.tableView.frame.origin.x, y: adjustedHeight - gap, width: self.tableView.frame.width, height: viewHeight - adjustedHeight) self.tableView?.layoutIfNeeded() }, completion: nil) if !animation { self.tableView?.alpha = 0 UIView.animate(withDuration: 0.5) { self.tableView?.alpha = 1 } } } public func animateDismiss(_ completed: @escaping () -> Void = {}) { UIView.animate(withDuration: 0.5, delay: 0.3, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: { let gap:CGFloat = (UIDevice().isIPhoneX() ? 20 : 10) + self.tableViewBottomGap self.tableView?.frame.origin.y = self.view.frame.height + gap }, completion: {(Bool) -> Void in completed() }) } public func dismiss() { if DynamicActionSheet.dismissing { return } DynamicActionSheet.dismissing = true self.animateDismiss { DynamicActionSheet.dismissing = false NotificationsCenterManager.sharedInstance.post("DISMISS") } } @IBAction public func dismissButton() { if defaultTableView { NotificationsCenterManager.sharedInstance.post("DISMISS") } else { dismiss() } } }
gpl-3.0
ff52428c47fc4b60a9d09647af8c0b54
31.884956
173
0.601722
4.895916
false
false
false
false
IBM-Swift/Swift-cfenv
Sources/CloudFoundryEnv/Service.swift
1
2239
/** * Copyright IBM Corporation 2016,2017 * * 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. **/ /** * See https://docs.run.pivotal.io/devguide/deploy-apps/environment-variable.html#VCAP-SERVICES. */ open class Service { public class Builder { var name: String? var label: String? var plan: String? var tags: [String]? var credentials: [String:Any]? init() {} func setName(name: String?) -> Builder { self.name = name return self } func setLabel(label: String?) -> Builder { self.label = label return self } func setPlan(plan: String?) -> Builder { self.plan = plan return self } func setTags(tags: [String]?) -> Builder { self.tags = tags return self } func setCredentials(credentials: [String:Any]?) -> Builder { self.credentials = credentials return self } func build() -> Service? { guard let name = name, let label = label, let tags = tags else { return nil } return Service(name: name, label: label, plan: plan, tags: tags, credentials: credentials) } } public let name: String public let label: String public let plan: String public let tags: [String] public let credentials: [String:Any]? public init(name: String, label: String, plan: String?, tags: [String], credentials: [String:Any]?) { self.name = name self.label = label self.plan = plan ?? "N/A" self.tags = tags self.credentials = credentials } public init(service: Service) { self.name = service.name self.label = service.label self.plan = service.plan self.tags = service.tags self.credentials = service.credentials } }
apache-2.0
999d7dccd1fcdbf081bf0c09a083066e
24.157303
95
0.648057
3.991087
false
false
false
false
kosicki123/Design-Patterns-In-Swift
source/behavioral/memento.swift
13
2039
/*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = Dictionary<NSObject, AnyObject> let DPMementoKeyChapter = "com.valve.halflife.chapter" let DPMementoKeyWeapon = "com.valve.halflife.weapon" let DPMementoGameState = "com.valve.halflife.state" /*: Originator */ class GameState { var chapter: String = "" var weapon: String = "" func toMemento() -> Memento { return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ] } func restoreFromMemento(memento: Memento) { chapter = memento[DPMementoKeyChapter] as? String ?? "n/a" weapon = memento[DPMementoKeyWeapon] as? String ?? "n/a" } } /*: Caretaker */ class CheckPoint { class func saveState(memento: Memento, keyName: String = DPMementoGameState) { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(memento, forKey: keyName) defaults.synchronize() } class func restorePreviousState(keyName: String = DPMementoGameState) -> Memento { let defaults = NSUserDefaults.standardUserDefaults() return defaults.objectForKey(keyName) as? Memento ?? Memento() } } /*: ### Usage */ var gameState = GameState() gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Black Mesa Inbound" gameState.weapon = "Crowbar" CheckPoint.saveState(gameState.toMemento()) gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" gameState.restoreFromMemento(CheckPoint.restorePreviousState()) gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.saveState(gameState.toMemento()) gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2"))
gpl-3.0
d6717b856af6fb52df38905d68a32762
28.507246
184
0.734774
3.976563
false
false
false
false
freshking/BKFilterView
FilterLayer/BKFilter/BKFilterType.swift
1
7077
// // BKFilterList.swift // FilterLayer // // Created by Bastian Kohlbauer on 07.03.16. // Copyright © 2016 Bastian Kohlbauer. All rights reserved. // import Foundation enum BKFilterType: String { //TODO: complete from list: https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW166 static let collection: [String: [BKFilterType]] = [ "Color Effect": colorEffecFilters, "Distortion Effect": distortionEffectFilters, "Halfton eEffect": halftoneEffectFilters, "Tile Effect": tileEffectFilters, "Stylize": stylizeFilters] case ColorControls = "CIColorControls" case ColorCrossPolynomial = "CIColorCrossPolynomial" case ColorCube = "CIColorCube" case ColorCubeWithColorSpace = "CIColorCubeWithColorSpace" case ColorInvert = "CIColorInvert" case ColorMap = "CIColorMap" case ColorMonochrome = "CIColorMonochrome" case ColorPosterize = "CIColorPosterize" case FalseColor = "CIFalseColor" case MaskToAlpha = "CIMaskToAlpha" case MaximumComponent = "CIMaximumComponent" case MinimumComponent = "CIMinimumComponent" case PhotoEffectChrome = "CIPhotoEffectChrome" case PhotoEffectFade = "CIPhotoEffectFade" case PhotoEffectInstant = "CIPhotoEffectInstant" case PhotoEffectMono = "CIPhotoEffectMono" case PhotoEffectNoir = "CIPhotoEffectNoir" case PhotoEffectProcess = "CIPhotoEffectProcess" case PhotoEffectTonal = "CIPhotoEffectTonal" case PhotoEffectTransfer = "CIPhotoEffectTransfer" case SepiaTone = "CISepiaTone" case Vignette = "CIVignette" static private let colorEffecFilters: [BKFilterType] = [ ColorControls, ColorCrossPolynomial, ColorCube, ColorCubeWithColorSpace, ColorInvert, ColorMap, ColorMonochrome, ColorPosterize, FalseColor, MaskToAlpha, MaximumComponent, MinimumComponent, PhotoEffectChrome, PhotoEffectFade, PhotoEffectInstant, PhotoEffectMono, PhotoEffectNoir, PhotoEffectProcess, PhotoEffectTonal, PhotoEffectTransfer, SepiaTone, Vignette] //MARK:- CICategoryDistortionEffect //TODO: Some distorion effets require additional input to th CIFilter. Implement this. case BumpDistortion = "CIBumpDistortion" case BumpDistortionLinear = "CIBumpDistortionLinear" case CircleSplashDistortion = "CICircleSplashDistortion" case CircularWrap = "CICircularWrap" case Droste = "CIDroste" case DisplacementDistortion = "CIDisplacementDistortion" case GlassDistortion = "CIGlassDistortion" case GlassLozenge = "CIGlassLozenge" case HoleDistortion = "CIHoleDistortion" case LightTunnel = "CILightTunnel" case PinchDistortion = "CIPinchDistortion" case StretchCrop = "CIStretchCrop" case TorusLensDistortion = "CITorusLensDistortion" case TwirlDistortion = "CITwirlDistortion" static private let distortionEffectFilters: [BKFilterType] = [ BumpDistortion, BumpDistortionLinear, CircleSplashDistortion, CircularWrap, Droste, DisplacementDistortion, GlassDistortion, GlassLozenge, HoleDistortion, LightTunnel, PinchDistortion, StretchCrop, TorusLensDistortion, TwirlDistortion] //MARK:- CICategoryHalftoneEffect case CircularScreen = "CICircularScreen" case CMYKHalftone = "CICMYKHalftone" case DotScreen = "CIDotScreen" case HatchedScreen = "CIHatchedScreen" case LineScreen = "CILineScreen" static private let halftoneEffectFilters: [BKFilterType] = [ CircularScreen, CMYKHalftone, DotScreen, HatchedScreen, LineScreen] //MARK:- CICategoryTileEffect //TODO: Some distorion effets require additional input to th CIFilter. Implement this. case AffineClamp = "CIAffineClamp" case AffineTile = "CIAffineTile" case EightfoldReflectedTile = "CIEightfoldReflectedTile" case FourfoldReflectedTile = "CIFourfoldReflectedTile" case FourfoldRotatedTile = "CIFourfoldRotatedTile" case FourfoldTranslatedTile = "CIFourfoldTranslatedTile" case GlideReflectedTile = "CIGlideReflectedTile" case Kaleidoscope = "CIKaleidoscope" case OpTile = "CIOpTile" case ParallelogramTile = "CIParallelogramTile" case PerspectiveTile = "CIPerspectiveTile" case SixfoldReflectedTile = "CISixfoldReflectedTile" case SixfoldRotatedTile = "CISixfoldRotatedTile" case TriangleKaleidoscope = "CITriangleKaleidoscope" case TriangleTile = "CITriangleTile" case TwelvefoldReflectedTile = "CITwelvefoldReflectedTile" static private let tileEffectFilters: [BKFilterType] = [ AffineClamp, AffineTile, EightfoldReflectedTile, FourfoldReflectedTile, FourfoldRotatedTile, FourfoldTranslatedTile, GlideReflectedTile, Kaleidoscope, OpTile, ParallelogramTile, PerspectiveTile, SixfoldReflectedTile, SixfoldRotatedTile, TriangleKaleidoscope, TriangleTile, TwelvefoldReflectedTile] //MARK:- CICategoryStylize //TODO: Some distorion effets require additional input to th CIFilter. Implement this. case BlendWithAlphaMask = "CIBlendWithAlphaMask" case BlendWithMask = "CIBlendWithMask" case Bloom = "CIBloom" case ComicEffect = "CIComicEffect" case Convolution3X3 = "CIConvolution3X3" case Convolution5X5 = "CIConvolution5X5" case Convolution7X7 = "CIConvolution7X7" case Convolution9Horizontal = "CIConvolution9Horizontal" case Convolution9Vertical = "CIConvolution9Vertical" case Crystallize = "CICrystallize" case DepthOfField = "CIDepthOfField" case Edges = "CIEdges" case EdgeWork = "CIEdgeWork" case Gloom = "CIGloom" case HeightFieldFromMask = "CIHeightFieldFromMask" case HexagonalPixellate = "CIHexagonalPixellate" case HighlightShadowAdjust = "CIHighlightShadowAdjust" case LineOverlay = "CILineOverlay" case Pixellate = "CIPixellate" case Pointillize = "CIPointillize" case ShadedMaterial = "CIShadedMaterial" case SpotColor = "CISpotColor" case SpotLight = "CISpotLight" static private let stylizeFilters: [BKFilterType] = [ BlendWithAlphaMask, BlendWithMask, Bloom, ComicEffect, Convolution3X3, Convolution5X5, Convolution7X7, Convolution9Horizontal, Convolution9Vertical, Crystallize, DepthOfField, Edges, EdgeWork, Gloom, HeightFieldFromMask, HexagonalPixellate, HighlightShadowAdjust, LineOverlay, Pixellate, Pointillize, ShadedMaterial, SpotColor, SpotLight] }
mit
6828f60423faf710cc5ae8c2780633cc
32.695238
184
0.696863
4.247299
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/VerifyCoInfoController.swift
1
2159
// // VerifyCoInfoController.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/8. // Copyright © 2017年 伯驹 黄. All rights reserved. // class VerifyCoInfoNotNeededCell: UITableViewCell, Updatable { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none backgroundColor = .groupTableViewBackground let button = HZUIHelper.generateNormalButton(title: "搞错了,不需要", target: self, action: #selector(notNeededAction)) button.setTitleColor(UIColor(hex: 0x4A4A4A), for: .normal) button.setTitleColor(.lightGray, for: .highlighted) button.titleLabel?.font = UIFontMake(12) contentView.addSubview(button) button.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.bottom.equalTo(-10) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func notNeededAction() { } } class VerifyCoInfoController: GroupTableController, CoVerifyActionable { override func initSubviews() { tableView.tableHeaderView = VerifyCoInfoHeaderView() tableView.separatorStyle = .none rows = [ [ Row<CompanyInfoCell>(viewData: NoneItem()), Row<VerifyCoInfoFieldCell>(viewData: VerifyCoInfoFieldItem(placeholder: "请输入您的企业邮箱", title: "工作邮箱")), Row<VerifyCoInfoFieldCell>(viewData: VerifyCoInfoFieldItem(placeholder: "请输入公司名称", title: "公司名称")), Row<CoInfoVerifyCell>(viewData: NoneItem()), Row<VerifyCoInfoNotNeededCell>(viewData: NoneItem()) ] ] let headerView: VerifyCoInfoHeaderView? = tableHeaderView() headerView?.model = "华住金会员权益" } @objc func verifyAction() { } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } }
mit
5a7a9373844a1694e519b4972628149f
29.865672
120
0.639749
4.466523
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatModule/Chat/View/Message/JCMessageTextContent.swift
1
1444
// // JCMessageTextContent.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit open class JCMessageTextContent: NSObject, JCMessageContentType { public weak var delegate: JCMessageDelegate? public override init() { let text = "this is a test text" self.text = NSAttributedString(string: text) super.init() } public init(text: String) { self.text = NSAttributedString(string: text) super.init() } public init(attributedText: NSAttributedString) { self.text = attributedText super.init() } open class var viewType: JCMessageContentViewType.Type { return JCMessageTextContentView.self } open var layoutMargins: UIEdgeInsets = .init(top: 9, left: 10, bottom: 9, right: 10) open var text: NSAttributedString open func sizeThatFits(_ size: CGSize) -> CGSize { let mattr = NSMutableAttributedString(attributedString: text) mattr.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, mattr.length)) let mattrSize = mattr.boundingRect(with: CGSize(width: 220.0, height: Double(MAXFLOAT)), options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil) self.text = mattr return .init(width: max(mattrSize.width, 15), height: max(mattrSize.height, 15)) } }
mit
fcbde1f8a410faee0d0c6d6a0ee3e5e5
33.309524
163
0.674532
4.176812
false
false
false
false
SheffieldKevin/CustomControlDemo
CustomControlDemo/CustomControlLayer.swift
1
1380
// CustomControlLayer.swift // CustomControlDemo // // Copyright (c) 2015 Zukini Ltd. import UIKit import MovingImagesiOS class CustomControlLayer: CALayer { weak var numericDial: CustomDial? let simpleRenderer: MISimpleRenderer = MISimpleRenderer() let drawDict: [String:AnyObject]! init(drawDictionary: [String : AnyObject]) { self.drawDict = drawDictionary super.init() } required init(coder aDecoder: NSCoder) { self.drawDict = aDecoder.decodeObjectForKey("draw_dictionary") as! [String : AnyObject] super.init(coder: aDecoder) } override func drawInContext(ctx: CGContext!) { if let theDial = numericDial { CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, 0.0, theDial.bounds.size.height) CGContextScaleCTM(ctx, 1.0, -1.0); let currentVal:NSNumber = NSNumber( double: Double(theDial.currentValue)) let controlText = NSString(format: "%1.3f", currentVal.floatValue) let variables = [ "controlvalue" : currentVal, "controltext" : controlText ] self.simpleRenderer.variables = variables self.simpleRenderer.drawDictionary(self.drawDict, intoCGContext: ctx) CGContextRestoreGState(ctx) } } }
mit
7d9fe0723da279a75846a20da694bb5c
31.857143
81
0.624638
4.495114
false
false
false
false
Friend-LGA/LGSideMenuController
LGSideMenuController/LGSideMenuHelper.swift
1
5124
// // LGSideMenuHelper.swift // LGSideMenuController // // // The MIT License (MIT) // // Copyright © 2015 Grigorii Lutkov <[email protected]> // (https://github.com/Friend-LGA/LGSideMenuController) // // 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 import ObjectiveC import QuartzCore import UIKit internal struct LGSideMenuHelper { private struct Keys { static var sideMenuController = "sideMenuController" } static func animate(duration: TimeInterval, timingFunction: CAMediaTimingFunction, animations: @escaping () -> Void, completion: @escaping () -> Void) { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(duration) CATransaction.begin() CATransaction.setCompletionBlock(completion) CATransaction.setAnimationTimingFunction(timingFunction) animations() CATransaction.commit() UIView.commitAnimations() } static func statusBarAppearanceUpdate(viewController: UIViewController, duration: TimeInterval, animations: (() -> Void)?) { if viewController.preferredStatusBarUpdateAnimation == .none || duration == .zero { if let animations = animations { animations() } viewController.setNeedsStatusBarAppearanceUpdate() } else { UIView.animate(withDuration: duration, animations: { if let animations = animations { animations() } viewController.setNeedsStatusBarAppearanceUpdate() }) } } static func isPhone() -> Bool { return UIDevice.current.userInterfaceIdiom == .phone } static func isPad() -> Bool { return UIDevice.current.userInterfaceIdiom == .pad } static func getKeyWindow() -> UIWindow? { if #available(iOS 13.0, *) { return UIApplication.shared.windows.first(where: { $0.isKeyWindow }) } else { return UIApplication.shared.keyWindow } } static func getStatusBarFrame() -> CGRect { if #available(iOS 13.0, *) { return getKeyWindow()?.windowScene?.statusBarManager?.statusBarFrame ?? .zero } else { return UIApplication.shared.statusBarFrame } } static func getInterfaceOrientation() -> UIInterfaceOrientation? { if #available(iOS 13.0, *) { return getKeyWindow()?.windowScene?.interfaceOrientation } else { return UIApplication.shared.statusBarOrientation } } static func getOppositeInterfaceOrientation() -> UIInterfaceOrientation? { guard let orientation = getInterfaceOrientation() else { return nil } if (orientation.isLandscape) { return .portrait } else { return .landscapeLeft } } static func isPortrait() -> Bool { return getInterfaceOrientation()?.isPortrait ?? true } static func isLandscape() -> Bool { return getInterfaceOrientation()?.isLandscape ?? false } static func setSideMenuController(_ sideMenuController: LGSideMenuController?, to viewController: UIViewController) { objc_setAssociatedObject(viewController, &Keys.sideMenuController, sideMenuController, .OBJC_ASSOCIATION_ASSIGN) } static func getSideMenuController(from viewController: UIViewController) -> LGSideMenuController? { return objc_getAssociatedObject(viewController, &Keys.sideMenuController) as? LGSideMenuController } static func canPerformSegue(_ viewController: UIViewController, withIdentifier identifier: String) -> Bool { guard let identifiers = viewController.value(forKey: "storyboardSegueTemplates") as? [NSObject] else { return false } return identifiers.contains { (object: NSObject) -> Bool in if let id = object.value(forKey: "_identifier") as? String { return id == identifier } else { return false } } } }
mit
153feaf9cc61ccd6119cab8255de5696
36.394161
156
0.668163
5.227551
false
false
false
false
jeffh/Tailor
TailorTests/TailorRunnerComponentsTest.swift
1
4861
import XCTest import Tailor import Kick class TailorBootstrap : TSSpec { override class func defineBehaviors() { describe("closure execution") { it("should call beforeEachs, then then the it, followed by afterEaches") { var callHistory = String[]() TSSpecContext.behaviors { beforeEach { callHistory.append("beforeEach1") } afterEach { callHistory.append("afterEach1") } beforeEach { callHistory.append("beforeEach2") } afterEach { callHistory.append("afterEach2") } describe("Cake") { beforeEach { callHistory.append("beforeEach3") } afterEach { callHistory.append("afterEach3") } it("is yummy") { callHistory.append("it1") } it("is tasty") { callHistory.append("it2") } } }.verifyBehaviors() let expectedCallOrder = [ "beforeEach1", "beforeEach2", "beforeEach3", "it1", "afterEach3", "afterEach2", "afterEach1", "beforeEach1", "beforeEach2", "beforeEach3", "it2", "afterEach3", "afterEach2", "afterEach1", ] expect(callHistory).to(equal(expectedCallOrder)) } it("call nested blocks immediately") { var describeWasCalled = false var contextWasCalled = false var nestedWasCalled = false var leafWasCalled = false TSSpecContext.behaviors { beforeEach { leafWasCalled = true } afterEach { leafWasCalled = true } it("should not invoke") { leafWasCalled = true } describe("stuff") { describeWasCalled = true beforeEach { leafWasCalled = true } afterEach { leafWasCalled = true } it("should not invoke") { leafWasCalled = true } context("sub context") { nestedWasCalled = true beforeEach { leafWasCalled = true } afterEach { leafWasCalled = true } it("should not invoke") { leafWasCalled = true } } } context("context") { contextWasCalled = true beforeEach { leafWasCalled = true } afterEach { leafWasCalled = true } it("should not invoke") { leafWasCalled = true } } } expect(describeWasCalled).to(beTruthy()) expect(contextWasCalled).to(beTruthy()) expect(nestedWasCalled).to(beTruthy()) expect(leafWasCalled).to(beFalsy()) } } context("when inside a beforeEach") { it("should throw errors") { var beforeEachWasCalled = false var afterEachWasCalled = false TSSpecContext.behaviors { beforeEach { failsWithErrorMessage("describe() is not allowed here") { describe("") {} } failsWithErrorMessage("context() is not allowed here") { context("") {} } failsWithErrorMessage("it() is not allowed here") { it("") {} } beforeEachWasCalled = true } afterEach { failsWithErrorMessage("describe() is not allowed here") { describe("") {} } failsWithErrorMessage("context() is not allowed here") { context("") {} } failsWithErrorMessage("it() is not allowed here") { it("") {} } afterEachWasCalled = true } }.verifyBehaviors() expect(beforeEachWasCalled).to(beTruthy()) expect(afterEachWasCalled).to(beTruthy()) } } } }
apache-2.0
ead7c50e0bdfeb15783896c60b2269cc
36.392308
86
0.410409
6.760779
false
false
false
false
Daniesy/UIPrimitives
UIPrimitives.swift
1
2831
public class UIPrimitives{ public class func drawOval(#width: CGFloat, height: CGFloat, fillColor: UIColor = UIColor.redColor(), strokeSize: CGFloat = 0, strokeColor: UIColor = UIColor.clearColor(), rotation: CGFloat = 0) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Oval Drawing CGContextSaveGState(context) if rotation != 0{ CGContextRotateCTM(context, -rotation * CGFloat(M_PI) / 180) } var ovalPath = UIBezierPath(ovalInRect: CGRectMake(-width/2, -height/2, width, height)) fillColor.setFill() ovalPath.fill() if strokeSize != 0 { strokeColor.setStroke() ovalPath.lineWidth = strokeSize ovalPath.stroke() } CGContextRestoreGState(context) } public class func drawRectangle(#width: CGFloat, height: CGFloat, cornerRadius:CGFloat = 0, fillColor: UIColor = UIColor.redColor(), strokeSize: CGFloat = 0, strokeColor: UIColor = UIColor.clearColor(), rotation: CGFloat = 0) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Rectangle 2 Drawing CGContextSaveGState(context) if rotation != 0{ CGContextRotateCTM(context, -rotation * CGFloat(M_PI) / 180) } let rectangle2Path = UIBezierPath(roundedRect: CGRectMake(-width/2, -height/2, width, height), cornerRadius: cornerRadius) fillColor.setFill() rectangle2Path.fill() if strokeSize != 0 { strokeColor.setStroke() rectangle2Path.lineWidth = strokeSize rectangle2Path.stroke() } CGContextRestoreGState(context) } public class func drawTriangle(#width: CGFloat, height: CGFloat, fillColor: UIColor = UIColor.redColor(), strokeSize: CGFloat = 0, strokeColor: UIColor = UIColor.clearColor(), rotation: CGFloat = 0) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Polygon Drawing CGContextSaveGState(context) if rotation != 0{ CGContextRotateCTM(context, -rotation * CGFloat(M_PI) / 180) } var trianglePath = UIBezierPath() trianglePath.moveToPoint(CGPointMake(-width/2, 0)) trianglePath.addLineToPoint(CGPointMake(-width, -height)) trianglePath.addLineToPoint(CGPointMake(0, -height)) trianglePath.closePath() fillColor.setFill() trianglePath.fill() if strokeSize != 0 { strokeColor.setStroke() trianglePath.lineWidth = strokeSize trianglePath.stroke() } CGContextRestoreGState(context) } }
mit
9e814e46d0fd534e2bc264fed04f72cb
35.766234
231
0.608972
5.475822
false
false
false
false
nikHowlett/Attend-O
attendo1/ProfessorPanel.swift
1
5030
// // ProfessorPanel.swift // attendo1 // // Created by Nik Howlett on 11/7/15. // Copyright (c) 2015 NikHowlett. All rights reserved. // import Foundation import UIKit import CoreData import QuartzCore class ProfessorPanel: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var editClassesButton: UIButton! @IBOutlet weak var addClassesButton: UIButton! @IBOutlet weak var classPicker: UIPickerView! var pickerSelectedClassName: String = String() var curRow: Int = Int() var pickerSelectedClassDate: NSDate = NSDate() //var pickerSelectedClassObj: NSManagedObject = NSManagedObject() var backupData: [String] = [String]() var classes : [Class2] = [Class2]() @IBOutlet weak var string: UILabel! lazy var managedObjectContext : NSManagedObjectContext? = { let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if let managedContext : NSManagedObjectContext? = appDelegate.managedObjectContext { return managedContext } else { return nil } }() override func viewDidLoad() { super.viewDidLoad() let fetchRequest : NSFetchRequest = NSFetchRequest(entityName: "Class2") let error: NSError? = nil do { classes = try managedObjectContext?.executeFetchRequest(fetchRequest) as! [Class2] } catch _ as NSError { print("An error occurred loading the data") } if error != nil { print("An error occurred loading the data") } if classes.isEmpty { backupData = ["CS 2340", "CS 3750"]; } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if classes.count > 0 { return classes.count } else { return backupData.count } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func SelectThisClass(sender: AnyObject) { performSegueWithIdentifier("selectClass", sender: self) } @IBAction func addClassButt(sender: AnyObject) { somehowAddClass() } func somehowAddClass() { performSegueWithIdentifier("addClass", sender: self) } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if classes.count > 0 { pickerSelectedClassName = classes[row].courseName pickerSelectedClassDate = classes[row].startTime curRow = row //pickerSelectedClassObj = classes[row] return classes[row].courseName } else { return backupData[row] } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if classes.count > 0 { string.text = classes[row].courseName } else { string.text = backupData[row] } } @IBAction func editClassButtPress(sender: AnyObject) { performSegueWithIdentifier("editClass", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "editClass") { let svc = segue.destinationViewController as! EditViewController svc.classNameSent = pickerSelectedClassName svc.dateTimeSent = pickerSelectedClassDate //svc.classObjSent = pickerSelectedClassObj //svc.classObjSent = (classes[curRow] as? NSManagedObject)! } if (segue.identifier == "selectClass") { let svc = segue.destinationViewController as! SelectClassViewController svc.classNameSent = pickerSelectedClassName svc.dateTimeSent = pickerSelectedClassDate //svc.classObjSent = classes[curRow] } } @IBAction func Logout9(sender: AnyObject) { /*if #available(iOS 9.0, *) { //self.navigationController?.popToViewController((ViewController.self as? UIViewController)!, animated: true) self.navigationController?.popToRootViewControllerAnimated(true) self.navigationController?.popToViewController(viewControllerForUnwindSegueAction("logout9", fromViewController: ProfessorPanel, withSender: self), animated: true) }*/ } /*@IBAction func unwindToVC(segue: UIStoryboardSegue) { /*let alert = UIAlertView() alert.title = "Signing Out" alert.message = "You have successfully signed out." alert.addButtonWithTitle("Ok") alert.show() print("test")*/ if let redViewController = segue.sourceViewController as? ProfessorPanel { print("Coming from RED") } }*/ }
mit
3be6d38c0083ad661f5ea1afc7b5f013
33.22449
175
0.632604
5.245047
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Managers/Shots State Handlers/ShotsInitialAnimationsStateHandler.swift
1
4334
// // Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import DZNEmptyDataSet class ShotsInitialAnimationsStateHandler: NSObject, ShotsStateHandler { let animationManager = ShotsAnimator() weak var shotsCollectionViewController: ShotsCollectionViewController? { didSet { shotsCollectionViewController?.collectionView?.emptyDataSetSource = self } } weak var delegate: ShotsStateHandlerDelegate? var state: ShotsCollectionViewController.State { return .initialAnimations } var nextState: ShotsCollectionViewController.State? { return .normal } var tabBarInteractionEnabled: Bool { return false } var tabBarAlpha: CGFloat { return 0.3 } var collectionViewLayout: UICollectionViewLayout { return InitialShotsCollectionViewLayout() } var collectionViewInteractionEnabled: Bool { return false } var collectionViewScrollEnabled: Bool { return false } var shouldShowNoShotsView: Bool { return Settings.areAllStreamSourcesOff() } fileprivate let emptyDataSetLoadingView = EmptyDataSetLoadingView.newAutoLayout() override init () { super.init() animationManager.delegate = self } func prepareForPresentingData() { // Do nothing, all set. } func presentData() { hideEmptyDataSetLoadingView() self.animationManager.startAnimationWithCompletion() { self.shotsCollectionViewController?.collectionView?.emptyDataSetSource = nil self.delegate?.shotsStateHandlerDidInvalidate(self) } } } // MARK: UICollecitonViewDataSource extension ShotsInitialAnimationsStateHandler { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.animationManager.visibleItems.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let shotsCollectionViewController = shotsCollectionViewController else { return UICollectionViewCell() } let cell = collectionView.dequeueReusableClass(ShotCollectionViewCell.self, forIndexPath: indexPath, type: .cell) cell.configureForDisplayingAuthorView = Settings.Customization.ShowAuthor let shot = shotsCollectionViewController.shots[indexPath.item] let shouldBlurShotImage = indexPath.row != 0 let blur = shouldBlurShotImage ? CGFloat(1) : CGFloat(0) cell.shotImageView.loadShotImageFromURL(shot.shotImage.normalURL, blur: blur) cell.shotImageView.applyBlur(blur) cell.gifLabel.isHidden = !shot.animated let imageCompletion: (UIImage) -> Void = { image in cell.shotImageView.image = image cell.shotImageView.applyBlur(blur) } LazyImageProvider.lazyLoadImageFromURLs( (shot.shotImage.teaserURL, shot.shotImage.normalURL, nil), teaserImageCompletion: imageCompletion, normalImageCompletion: imageCompletion ) return cell } } extension ShotsInitialAnimationsStateHandler: ShotsAnimatorDelegate { func collectionViewForShotsAnimator(_ animator: ShotsAnimator) -> UICollectionView? { return shotsCollectionViewController?.collectionView } func itemsForShotsAnimator(_ animator: ShotsAnimator) -> [ShotType] { guard let shotsCollectionViewController = shotsCollectionViewController else { return [] } return Array(shotsCollectionViewController.shots.prefix(3)) } } extension ShotsInitialAnimationsStateHandler: DZNEmptyDataSetSource { func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! { emptyDataSetLoadingView.startAnimating() return emptyDataSetLoadingView } } // MARK: Private methods private extension ShotsInitialAnimationsStateHandler { // DZNEmptyDataSet does not react on `insertItemsAtIndexPaths` so we need to manually hide loading view func hideEmptyDataSetLoadingView() { emptyDataSetLoadingView.isHidden = true emptyDataSetLoadingView.stopAnimating() } }
gpl-3.0
12076ffe62cfd0da7432f0e6bdcd0256
29.521127
107
0.701892
5.585052
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Managers/Language.swift
1
664
// // Language.swift // Inbbbox // // Copyright © 2017 Netguru Sp. z o.o. All rights reserved. // import Foundation enum Language: String { case deviceDefault = "default" case english = "en" case polish = "pl" case german = "de" case portuguese = "pt-PT" case spanish = "es" case french = "fr" /// Returns localized name for language. var localizedName: String { return Localized("Language.\(rawValue)", comment: "Language name.") } /// Returns all cases of enum. static var allOptions: [Language] { return [.deviceDefault, .english, .polish, .german, .portuguese, .spanish, .french] } }
gpl-3.0
64b78303744e1c5bc578cba3c94ccf2e
22.678571
91
0.621418
3.724719
false
false
false
false
AgeProducts/WatchRealmSync
Share module/LapShare.swift
1
1257
// // LapShare.swift // WatchRealmSync // // Created by Takuji Hori on 2017/02/03. // Copyright © 2017 AgePro. All rights reserved. // import Foundation import RealmSwift /* Compare item digest. */ func lapItemDigestComp(first:Lap, second:Lap) -> Bool { return lapItemDigest(lap:first) == lapItemDigest(lap:second) } /* Compare item hash. */ func lapItemHashNumberComp(first:Lap, second:Lap) -> Bool { return lapItemHashNumber(lap:first) == lapItemHashNumber(lap:second) } /* Make item digest. */ @objc(LapDigest) class LapDigest: NSObject, NSCoding { var identifier:String = "" var modifyDate = Date() var digestString = "" override init() { super.init() } required init(coder aDecoder: NSCoder) { self.identifier = aDecoder.decodeObject(forKey: "identifier") as? String ?? "" self.modifyDate = aDecoder.decodeObject(forKey: "modifyDate") as? Date ?? Date() self.digestString = aDecoder.decodeObject(forKey: "digestString") as? String ?? "" } func encode(with aCoder: NSCoder) { aCoder.encode(self.identifier, forKey:"identifier") aCoder.encode(self.modifyDate, forKey:"modifyDate") aCoder.encode(self.digestString, forKey:"digestString") } }
mit
1058f854823dba7a6e715936a4fa230e
28.209302
90
0.675159
3.683284
false
false
false
false
mikezone/EffectiveSwift
EffectiveSwift/Extension/UIKit/UIGestureRecognizer+SE.swift
1
2083
// // UIGestureRecognizer+MKAdd.swift // SwiftExtension // // Created by Mike on 17/1/23. // Copyright © 2017年 Mike. All rights reserved. // import UIKit fileprivate var block_key: Int8 = 0 public extension UIGestureRecognizer { public convenience init(actionBlock: @escaping (UIGestureRecognizer) -> Swift.Void) { self.init() self.addActionBlock(actionBlock) } public func addActionBlock(_ actionBlock: @escaping (UIGestureRecognizer) -> Swift.Void) { let target = _UIGestureRecognizerBlockTarget(block: actionBlock) self.addTarget(target, action: #selector(_UIGestureRecognizerBlockTarget.invoke(sender:))) self._allUIGestureRecognizerBlockTargets.append(target) } public func removeAllActionBlocks() { for target in self._allUIGestureRecognizerBlockTargets { self.removeTarget(target, action: #selector(_UIGestureRecognizerBlockTarget.invoke(sender:))) } self._allUIGestureRecognizerBlockTargets.removeAll() } private var _allUIGestureRecognizerBlockTargets: [_UIGestureRecognizerBlockTarget] { get { var targets = objc_getAssociatedObject(self, &block_key) as? [_UIGestureRecognizerBlockTarget] if targets == nil { targets = [_UIGestureRecognizerBlockTarget]() objc_setAssociatedObject(self, &block_key, targets, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return targets! } set { objc_setAssociatedObject(self, &block_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } fileprivate class _UIGestureRecognizerBlockTarget: NSObject { internal var block: ((UIGestureRecognizer) -> Swift.Void)! private override init() {super.init()} public convenience init(block: @escaping (UIGestureRecognizer) -> Swift.Void) { self.init() self.block = block } @objc public func invoke(sender: UIGestureRecognizer) { if block != nil { block(sender) } } }
gpl-3.0
e52e182e62d4ac5f15a4eca4111a553f
32.548387
106
0.659135
4.792627
false
false
false
false
jquave/SwiftNetworking
SwiftNetworking/Classes/JSON.swift
1
7510
// // QJSON.swift // AccessControl // // Created by Jameson Quave on 7/25/14. // Copyright (c) 2014 JQ Software. All rights reserved. // import Foundation func parseJSON(data: NSData) -> JSONVal { return JSON(data).parse() } func parseJSON(str: String) -> JSONVal { return JSON(str).parse() } public enum JSONVal : Printable { // Generator protocol, use for `for x in y` // typealias Element /*public func next() -> JSONVal? { return self } typealias GeneratorType = JSONVal */ /* protocol Sequence { typealias GeneratorType : Generator func generate() -> GeneratorType } */ /*typealias GeneratorType = JSONVal func generate() -> GeneratorType { return GeneratorType(0) } func next() -> JSONVal { return JSONVal("hi") } */ public func val() -> Any { switch self { case .Dictionary(let dict): return dict case .JSONDouble(let d): return d case .JSONInt(let i): return i case .JSONArray(let arr): return arr case .JSONStr(let str): return str case .JSONBool(let jbool): return jbool case .Null: return "Null" } } case Dictionary([String : JSONVal]) case JSONDouble(Double) case JSONInt(Int) case JSONArray([JSONVal]) case JSONStr(String) case JSONBool(Bool) case Null // Pretty prints for Dictionary and Array func pp(data : [String : JSONVal]) -> String { return "DICT" } func pp(data : [JSONVal]) -> String { var str = "[\n" var indentation = " " for x : JSONVal in data { str += "\(indentation)\(x)\n" } return str } public var description: String { switch self { case .Dictionary(let dict): var str = "{\n" var indent = " " for (key,val) in dict { str += "\(indent)\(key): \(val)\n" } return "JSONDictionary \(str)" case .JSONDouble(let d): return "\(d)" case .JSONInt(let i): return "\(i)" case .JSONArray(let arr): var str = "[\n" var num = 0 var indent = " " for object in arr { str += "[\(num)]\(indent)\(object.description)\n" num++ } str += "]" return "JSONArray [\(arr.count)]: \(str)" case .JSONStr(let str): return str case .JSONBool(let jbool): return "\(jbool)" case .Null: return "Null" } } subscript(index: String) -> JSONVal { switch self { case .Dictionary(let dict): if dict[index]? { return dict[index]! } return JSONVal("JSON Fault") default: println("Element is not a dictionary") return JSONVal("JSON Fault") } } subscript(index: Int) -> JSONVal { switch self { case .JSONArray(let arr): return arr[index] default: println("Element is not an array") return JSONVal("JSON Fault") } } init(_ json: Int) { self = .JSONInt(json) } init(_ json: AnyObject) { if let jsonDict = json as? NSDictionary { var kvDict = [String : JSONVal]() for (key: AnyObject, value: AnyObject) in jsonDict { if let keyStr = key as? String { kvDict[keyStr] = JSONVal(value) } else { println("Error: key in dictionary is not of type String") } } self = .Dictionary(kvDict) } else if let jsonDouble = json as? Double { self = .JSONDouble(jsonDouble) } else if let jsonInt = json as? Int { self = .JSONInt(jsonInt) } else if let jsonBool = json as? Bool { self = .JSONBool(jsonBool) } else if let jsonStr = json as? String { self = .JSONStr(jsonStr) } else if let jsonArr = json as? NSArray { var arr = [JSONVal]() for val in jsonArr { arr += JSONVal(val) } self = .JSONArray( arr ) } else { println("ERROR: Couldn't convert element \(json)") self = .Null } } } public class JSON { public var json = "" public var data: NSData init(_ json: String) { self.json = json self.data = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! } init(_ data: NSData) { self.json = "" self.data = data //self.data = self.json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } public func parse() -> JSONVal { var err: NSError? = nil var val = JSONVal(NSJSONSerialization.JSONObjectWithData(self.data, options: nil, error: &err)) return val } public class func encodeAsJSON(data: AnyObject!) -> String? { var json = "" if let rootObjectArr = data as? [AnyObject] { // Array json = "\(json)[" for embeddedObject: AnyObject in rootObjectArr { var encodedEmbeddedObject = encodeAsJSON(embeddedObject) if encodedEmbeddedObject? { json = "\(json)\(encodedEmbeddedObject!)," } else { println("Error creating JSON") return nil } } json = "\(json)]" } else if let rootObjectStr = data as? String { // This is a string, just return it return escape(rootObjectStr) } else if let rootObjectDictStrStr = data as? Dictionary<String, String> { json = "\(json){" var numKeys = rootObjectDictStrStr.count var keyIndex = 0 for (key,value) in rootObjectDictStrStr { // This could be a number if(keyIndex==(numKeys-1)) { json = json.stringByAppendingString("\(escape(key)):\(escape(value))") } else { json = json.stringByAppendingString("\(escape(key)):\(escape(value)),") } keyIndex = keyIndex + 1 } json = "\(json)}" } else { println("Failed to write JSON object") return nil } return json } class func escape(str: String) -> String { var newStr = str.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) // Replace already escaped quotes with non-escaped quotes newStr = newStr.stringByReplacingOccurrencesOfString("\\\"", withString: "\"") // Escape all non-escaped quotes newStr = newStr.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") return "\"\(newStr)\"" } }
mit
a35d5e627b6970d6ea221458ea25197a
26.613971
103
0.486285
4.829582
false
false
false
false
SergeMaslyakov/audio-player
app/src/controllers/music/popover/MusicPickerViewController.swift
1
3495
// // MusicPickerViewController.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import TableKit import Dip import DipUI import SwiftyBeaver import Reusable class MusicPickerViewController: UIViewController, StoryboardSceneBased, Loggable { static let sceneStoryboard = UIStoryboard(name: StoryboardScenes.musicPopoverPicker.rawValue, bundle: nil) var currentMusicState: MusicLibraryState? weak var delegate: MusicPickerViewControllerDelegate? var tableDirector: TableDirector! lazy var animator: MusicPickerAnimator = MusicPickerAnimator() @IBOutlet weak var containerView: UIView! @IBOutlet weak var tableView: UITableView! { didSet { tableDirector = TableDirector(tableView: tableView) installTable() } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.modalPresentationStyle = UIModalPresentationStyle.custom self.transitioningDelegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.modalPresentationStyle = UIModalPresentationStyle.custom self.transitioningDelegate = self } override func viewDidLoad() { super.viewDidLoad() } func installTable() { let cellOrder = [ MusicLibraryState.artists, MusicLibraryState.albums, MusicLibraryState.songs, MusicLibraryState.genres, MusicLibraryState.playLists ] let section = TableSection() for state in cellOrder { let row = TableRow<MusicPickerTableViewCell>(item: (state, currentMusicState!)) .on(.click) { [weak self] (options) in guard let strongSelf = self else { return } guard let uDelegate = strongSelf.delegate else { strongSelf.tableDirector.tableView?.deselectRow(at: options.indexPath, animated: true) return } uDelegate.userDidPickMusicController(withState: state, from: self!) } section += row } section.footerHeight = ThemeHeightHelper.MusicPicker.sectionFooterHeight section.headerHeight = ThemeHeightHelper.MusicPicker.sectionHeaderHeight tableDirector += section } } extension MusicPickerViewController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = true return animator } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.presenting = false return animator } } extension MusicPickerViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view == view; } @IBAction func handleTapGestureOnDimmingView(recognizer: UITapGestureRecognizer) { dismiss(animated: true) } }
apache-2.0
70d3c4e5946ad768a996dd241ad6d84e
29.920354
177
0.667716
5.803987
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Extensions/UIImageViewExtensions.swift
1
4110
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import SDWebImage import Shared extension UIColor { var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { return UIGraphicsImageRenderer(size: size).image { rendererContext in self.setFill() rendererContext.fill(CGRect(origin: .zero, size: size)) } } } public extension UIImageView { func setImageAndBackground(forIcon icon: Favicon?, website: URL?, completion: @escaping () -> Void) { func finish(bgColor: UIColor?) { if let bgColor = bgColor { // If the background color is clear, we may decide to set our own background based on the theme. let color = bgColor.components.alpha < 0.01 ? UIColor.theme.general.faviconBackground : bgColor self.backgroundColor = color } completion() } backgroundColor = nil sd_setImage(with: nil) // cancels any pending SDWebImage operations. if let url = website, let bundledIcon = FaviconFetcher.getBundledIcon(forUrl: url) { self.image = UIImage(contentsOfFile: bundledIcon.filePath) finish(bgColor: bundledIcon.bgcolor) } else { let imageURL = URL(string: icon?.url ?? "") let defaults = fallbackFavicon(forUrl: website) self.sd_setImage(with: imageURL, placeholderImage: defaults.image, options: []) {(img, err, _, _) in guard err == nil else { finish(bgColor: defaults.color) return } finish(bgColor: nil) } } } func setFavicon(forSite site: Site, completion: @escaping () -> Void ) { setImageAndBackground(forIcon: site.icon, website: site.tileURL, completion: completion) } /* * If the webpage has low-res favicon, use defaultFavIcon */ func setFaviconOrDefaultIcon(forSite site: Site, completion: @escaping () -> Void ) { setImageAndBackground(forIcon: site.icon, website: site.tileURL) { [weak self] in if let image = self?.image, image.size.width < 32 || image.size.height < 32 { let defaults = self?.fallbackFavicon(forUrl: site.tileURL) self?.image = defaults?.image self?.backgroundColor = defaults?.color } completion() } } private func fallbackFavicon(forUrl url: URL?) -> (image: UIImage, color: UIColor) { if let url = url { return (FaviconFetcher.letter(forUrl: url), FaviconFetcher.color(forUrl: url)) } else { return (FaviconFetcher.defaultFavicon, .white) } } func setImageColor(color: UIColor) { let templateImage = self.image?.withRenderingMode(.alwaysTemplate) self.image = templateImage self.tintColor = color } } open class ImageOperation: NSObject, SDWebImageOperation { open var cacheOperation: Operation? var cancelled: Bool { return cacheOperation?.isCancelled ?? false } @objc open func cancel() { cacheOperation?.cancel() } } extension UIImage { func overlayWith(image: UILabel) -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: size.width, height: size.height), false, 0.0) draw(in: CGRect(origin: CGPoint.zero, size: size)) image.draw(CGRect(origin: CGPoint.zero, size: image.frame.size)) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } }
mpl-2.0
1e3c6bd97ddc004cdf45c000ff65bc5a
35.052632
112
0.609246
4.511526
false
false
false
false
hxx0215/VPNOn
VPNOn/LTVPNTableViewController+Geo.swift
1
782
// // LTVPNTableViewController+Geo.swift // VPNOn // // Created by Lex on 3/3/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit import VPNOnKit extension LTVPNTableViewController { func geoDidUpdate(notification: NSNotification) { if let vpn = notification.object as! VPN? { VPNManager.sharedManager.geoInfoOfHost(vpn.server) { geoInfo in vpn.countryCode = geoInfo.countryCode vpn.isp = geoInfo.isp vpn.latitude = geoInfo.latitude vpn.longitude = geoInfo.longitude vpn.managedObjectContext!.save(nil) self.tableView.reloadData() } } } }
mit
2b0b80d11b256c30396615c6da8cf481
23.4375
64
0.557545
4.6
false
false
false
false
drahot/DHQueryString
Sources/DHQueryString.swift
1
3167
import Foundation /// DHQueryString public struct DHQueryString { private init() {} public static func toDictionary(_ queryString: String, removePercentEncoding: Bool = true) -> [String:String] { return queryString.toDictionary(removePercentEncoding) } public static func toString(_ dictionary: [String:String], addingPercentEncoding: Bool = true) -> String { return dictionary.toQueryString(addingPercentEncoding) } public static func toString<Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral>( _ dictionary: DictionaryLiteral<Key, Value>, addingPercentEncoding: Bool = true) -> String { return dictionary.toQueryString(addingPercentEncoding) } } extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral { fileprivate func toQueryString(_ addingPercentEncoding: Bool = true) -> String { return queryString(self.map {($0.key as! String, $0.value as! String)}, addingPercentEncoding: addingPercentEncoding) } } extension KeyValuePairs where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral { fileprivate func toQueryString(_ addingPercentEncoding: Bool = true) -> String { return queryString(self.map {($0.key as! String, $0.value as! String)}, addingPercentEncoding: addingPercentEncoding) } } fileprivate func queryString<T: Sequence, V: ExpressibleByStringLiteral>(_ seq: T, addingPercentEncoding: Bool) -> String where T.Iterator.Element == (V, V) { let array = seq.map { (k, v) -> String in var key = k as! String var value = v as! String if addingPercentEncoding { key = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? key value = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? value } return "\(key)=\(value)" } return array.joined(separator: "&") } extension Sequence { fileprivate func toDictionary<K: Hashable, V>() -> [K:V] where Iterator.Element == (K, V) { var dictionary = [K:V]() for (key, value) in self { dictionary[key] = value } return dictionary } } extension String { fileprivate func toDictionary(_ removePercentEncoding: Bool = true) -> [String:String] { guard self.contains("=") else { return [:] } var query = self if query.hasPrefix("?") { query.remove(at: query.startIndex) } let seq = query.components(separatedBy: "&").map { s -> (String, String) in let data = s.components(separatedBy: "=") var key = data.first! var value = data.last! if removePercentEncoding { key = key.removingPercentEncoding ?? key value = value.removingPercentEncoding ?? value } return (key, value) } return seq.toDictionary() } }
mit
b9d96ac61358954fce0efc657d3afdc7
32.336842
125
0.613199
5.269551
false
false
false
false
naturaln0va/Doodler_iOS
Doodler/UIView+Additions.swift
1
1304
import UIKit extension UIView { /** Captures the screen and returns a UIImage with its contents. */ var imageByCapturing: UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0) drawHierarchy(in: CGRect(x: 0.0, y: 0.0, width: bounds.size.width, height: bounds.size.height), afterScreenUpdates: false) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } /** Shows a rectangle around the view's frame. - Parameter color: The border color. */ @objc(showBoundingRectWithColor:) func showBoundingRect(with color: UIColor = .red) { layer.borderColor = color.cgColor layer.borderWidth = 1 } /** Creates a new spring animation with predefined values. */ class func springAnimate(with duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil) { UIView.animate( withDuration: duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.4, options: [], animations: animations, completion: completion ) } }
mit
12fa9f35f286075ac598bb3a1130b90c
26.744681
130
0.597393
5.09375
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/TwitterAccountSelectionViewController.swift
2
1839
// // TwitterAccountSelectionViewController.swift // WSDOT // // Created by Logan Sims on 9/8/16. // Copyright © 2016 WSDOT. All rights reserved. // import UIKit class TwitterAccountSelectionViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "accountCell" var my_parent: TwitterViewController? = nil var menu_options: [String] = ["All Accounts", "Ferries", "Snoqualmie Pass", "WSDOT", "WSDOT East", "WSDOT North Traffic", "WSDOT Southwest", "WSDOT Tacoma", "WSDOT Traffic"] var selectedIndex = 8 @IBAction func cancelAction(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: {()->Void in}); } override func viewDidLoad() { self.view.backgroundColor = ThemeManager.currentTheme().mainColor } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu_options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) // Configure Cell cell.textLabel?.text = menu_options[indexPath.row] if (indexPath.row == selectedIndex){ cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { my_parent!.accountSelected(indexPath.row) self.dismiss(animated: true, completion: {()->Void in}); } }
gpl-3.0
a6a39d25f155bd0411d2e81dd8ac0b43
30.689655
177
0.658324
4.798956
false
false
false
false
shridharmalimca/iOSDev
iOS/Swift 3.0/MapView/MapView/ViewController.swift
2
5409
// // ViewController.swift // MapView // // Created by Shridhar Mali on 12/9/16. // Copyright © 2016 TIS. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! let objLocationManager = LocationManagerHelper.sharedInstance override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(self.refreshMap)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Draw", style: .plain, target: self, action: #selector(self.drawOnMap)) objLocationManager.updateUserLocation() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addAnnotation() } func refreshMap() { let overlays = self.mapView.overlays self.mapView.removeOverlays(overlays) addAnnotation() } func addAnnotation() { print(objLocationManager.userLocation.coordinate.latitude) print(objLocationManager.userLocation.coordinate.longitude) // 2 Create span var span = MKCoordinateSpanMake(0.05, 0.05) span.latitudeDelta = 0.02 span.longitudeDelta = 0.02 let region = MKCoordinateRegion(center: objLocationManager.userLocation.coordinate, span: span) mapView.setRegion(region, animated: true) // 3 Add Annotation on map let annotations = mapView.annotations mapView.removeAnnotations(annotations) let annotation = MKPointAnnotation() annotation.coordinate = objLocationManager.userLocation.coordinate annotation.title = "Title" annotation.subtitle = "SubTitle" mapView.addAnnotation(annotation) } // drawOnMap func drawOnMap() { let alertController = UIAlertController(title: "Draw On Map", message: "", preferredStyle: .actionSheet) let circle = UIAlertAction(title: "Circle", style: .default) { (action: UIAlertAction) in self.drawCircle() } let polygoan = UIAlertAction(title: "Polygoan", style: .default) { (action: UIAlertAction) in self.drawPolygon() } let polyline = UIAlertAction(title: "Polyline", style: .default) { (action: UIAlertAction) in self.drawPolyline() } let route = UIAlertAction(title: "Route (BOM to PNR)", style: .default) { (action: UIAlertAction) in self.drawRoute() } let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) { (action: UIAlertAction) in self.dismiss(animated: true, completion: nil) } alertController.addAction(circle) alertController.addAction(polygoan) alertController.addAction(polyline) alertController.addAction(route) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } func drawCircle() { let circle = MKCircle(center: objLocationManager.userLocation.coordinate, radius: 300) self.mapView.add(circle) } func drawPolygon() { let locations = [CLLocationCoordinate2D(latitude: 19.0176147, longitude: 72.8561644), CLLocationCoordinate2D(latitude: 18.5204303,longitude: 73.8567437), CLLocationCoordinate2D(latitude: 19.0945700, longitude: 74.7384300), CLLocationCoordinate2D(latitude: 19.0176147, longitude: 72.8561644)] let polygon = MKPolygon(coordinates: locations, count: locations.count) self.mapView.add(polygon) } func drawPolyline() { let locations = [CLLocationCoordinate2D(latitude: 19.0176147, longitude: 72.8561644), CLLocationCoordinate2D(latitude: 18.5204303,longitude: 73.8567437)] let polyline = MKPolyline(coordinates: locations, count: locations.count) self.mapView.add(polyline) } func drawRoute() { // Draw Routes using MKPolyline } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKCircle { let circle = MKCircleRenderer(overlay: overlay) circle.strokeColor = UIColor.red circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1) circle.lineWidth = 1 return circle } if overlay is MKPolygon { let polygoan = MKPolygonRenderer(overlay: overlay) polygoan.fillColor = UIColor.red polygoan.strokeColor = UIColor.black polygoan.lineWidth = 1 return polygoan } if overlay is MKPolyline { let line = MKPolylineRenderer(overlay: overlay) line.fillColor = UIColor.blue line.strokeColor = UIColor.red line.lineWidth = 2 return line } return overlay as! MKOverlayRenderer } }
apache-2.0
76600b8bc9d2a1a402949ce8aa164333
35.789116
299
0.64645
4.902992
false
false
false
false
thebrankoo/CryptoLab
CryptoLab/Message Auth/CoreHMAC.swift
1
3958
// // CoreHMAC.swift // CryptoLab // // Created by Branko Popovic on 4/26/17. // Copyright © 2017 Branko Popovic. All rights reserved. // import Foundation import OpenSSL class HMACCoreAuth: NSObject { let key: Data let hashFunction: AuthHashFunction var context: UnsafeMutablePointer<HMAC_CTX>? init(key: Data, hashFunction: AuthHashFunction) { self.key = key self.hashFunction = hashFunction super.init() } //MARK: Auth Code func authenticationCode(forData data: Data) -> (result: UnsafeMutablePointer<UInt8>?, resultSize: UnsafeMutablePointer<UInt32>) { let dataPointer = data.makeUInt8DataPointer() let dataLen = Int(data.count) let keyPointer = key.makeUInt8DataPointer() let keyLen = Int32(key.count) let resultSize = UnsafeMutablePointer<UInt32>.allocate(capacity: MemoryLayout<UInt32.Stride>.size) let result = HMAC(hashFunction.value(), keyPointer, keyLen, dataPointer, dataLen, nil, resultSize) return (result, resultSize) } func authCodeInit() { self.context = UnsafeMutablePointer<HMAC_CTX>.allocate(capacity: MemoryLayout<HMAC_CTX>.size) HMAC_CTX_init(self.context) let keyPointer = key.makeUInt8DataPointer() let keyLen = Int32(key.count) HMAC_Init(self.context, keyPointer, keyLen, hashFunction.value()) } func authCodeUpdate(withData data: Data) { let dataPointer = data.makeUInt8DataPointer() let dataLen = Int(data.count) HMAC_Update(self.context, dataPointer, dataLen) } func authCodeFinish() -> (result: Array<UInt8>?, resultSize: UnsafeMutablePointer<UInt32>) { var resultData = Data.makeUInt8EmptyArray(ofSize: Int(hashFunction.digestLength())) let resultSize = UnsafeMutablePointer<UInt32>.allocate(capacity: MemoryLayout<UInt32.Stride>.size) HMAC_Final(self.context, &resultData, resultSize) HMAC_CTX_cleanup(self.context) self.context?.deallocate(capacity: MemoryLayout<HMAC_CTX>.size) self.context = nil return (resultData, resultSize) } } class HMACSignVerifyUnit: NSObject { var context: UnsafeMutablePointer<EVP_MD_CTX> let hashFunction: AuthHashFunction let key: Data init(key: Data, hashFunction: AuthHashFunction) { context = EVP_MD_CTX_create() self.hashFunction = hashFunction self.key = key super.init() } func initSignUnit(){ let digestInitError = EVP_DigestInit_ex(context, hashFunction.value(), nil) if digestInitError != 1 { //init error } if let pkey = generateEVPPkey(fromData: key) { let digestSignInitError = EVP_DigestSignInit(context, nil, hashFunction.value(), nil, pkey) if digestSignInitError != 1 { //init error } } else { //init error } } func updateSignUnit(withData data: Data) { //let updateError = EVP_Update // EVP_DigestSignUpdate(context, data.makeUInt8DataPointer(), data.count) // if updateError != 1 { // //update error // } } func finalSignUnit() -> UnsafeMutablePointer<UInt8> { let result = UnsafeMutablePointer<UInt8>.allocate(capacity: MemoryLayout<UInt8.Stride>.size) let resultSize = UnsafeMutablePointer<Int>.allocate(capacity: MemoryLayout<Int.Stride>.size) let finalError = EVP_DigestSignFinal(context, result, resultSize) if finalError != 1 { //final error } return result } func initVerifyUnit() { context = EVP_MD_CTX_create() let digestInitError = EVP_DigestInit_ex(context, hashFunction.value(), nil) if digestInitError != 1 { //init error } if let pkey = generateEVPPkey(fromData: key) { let digestSignInitError = EVP_DigestSignInit(context, nil, hashFunction.value(), nil, pkey) if digestSignInitError != 1 { //init error } } else { //init error } } func generateEVPPkey(fromData data: Data) -> UnsafeMutablePointer<EVP_PKEY>? { let bioStruct : UnsafeMutablePointer<BIO> = BIO_new(BIO_s_mem()) BIO_write(bioStruct, ((data as NSData?)?.bytes)!, Int32(data.count)) let pkey = PEM_read_bio_PUBKEY(bioStruct, nil, nil, nil) return pkey } }
mit
888e2354e01fdc01cd2aa98b97459535
28.311111
130
0.720243
3.359083
false
false
false
false
gfx/Swift-JsonSerializer
SwiftFeed/ApiClient.swift
2
1200
// // ApiClient.swift // JsonSerializer // // Created by Fuji Goro on 2014/09/19. // Copyright (c) 2014年 Fuji Goro. All rights reserved. // import Foundation import JsonSerializer class ApiClient { enum Result { case Success(Json) case Error(ErrorType) } func get(url: NSURL, completion: (Result) -> Void) { let request = NSMutableURLRequest(URL: url); request.HTTPMethod = "GET" let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { (data, request, error) -> Void in if let err = error { completion(.Error(err)) return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { guard let data = data else { return } do { let result = try Json.deserialize(data); dispatch_async(dispatch_get_main_queue()) { completion(.Success(result)) } } catch { completion(.Error(error)) } } } task.resume() } }
apache-2.0
3c9cc9bcdee1015b589dce6ac108129c
25.644444
91
0.522538
4.625483
false
false
false
false
Kalvin126/BatteryNotifier
iOS Battery Notifier/StatusItemController.swift
1
2609
// // StatusItemController.swift // iOS Battery Notifier // // Created by Kalvin Loc on 3/15/16. // Copyright © 2016 Red Panda. All rights reserved. // import Cocoa final class StatusItemController: NSObject { private var statusItem: NSStatusItem private let itemView = NSView() private let menu = NotifierMenu(title: "notifierMenu") private var batteryViewController: BatteryViewController private var isUpdating = false // MARK: Init override init() { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) guard let controller = MainStoryBoard.instantiateController(with: .batteryViewController), let batteryController = controller as? BatteryViewController else { fatalError(#function + " - Could not instantiate BatteryViewController") } self.batteryViewController = batteryController super.init() statusItem.length = 30.0 batteryViewController.view.frame = statusItem.button!.frame // This force loads view as well statusItem.button?.addSubview(batteryViewController.view, positioned: .above, relativeTo: nil) statusItem.highlightMode = true statusItem.menu = menu } } // MARK: - Actions extension StatusItemController { } // MARK: - DeviceManagerDelegate extension StatusItemController: DeviceObserver { func deviceManager(_ manager: DeviceManager, didFetch devices: Set<Device>) { guard let lowestCapacityDevice = devices.lowestCapacityDevice else { return } let displayedDevice = self.batteryViewController.displayedDevice var updateDisplayDevice = false if let displayedDevice = displayedDevice, displayedDevice.currentBatteryCapacity > lowestCapacityDevice.currentBatteryCapacity || displayedDevice == lowestCapacityDevice || devices.contains(displayedDevice) { updateDisplayDevice = true } if updateDisplayDevice { self.batteryViewController.displayedDevice = lowestCapacityDevice } self.menu.updateBatteryLabels(devices: devices) } func deviceManager(_ manager: DeviceManager, didExpire device: Device) { if batteryViewController.displayedDevice?.serialNumber == device.serialNumber { let newLowestCapacityDevice = manager.devices.values.lowestCapacityDevice batteryViewController.displayedDevice = newLowestCapacityDevice } menu.invalidateDeviceItem(serial: device.serialNumber) } }
gpl-3.0
7054db683bcefa25004f9635c722f8d8
29.682353
102
0.70092
5.333333
false
false
false
false
ilyapuchka/VIPER-SWIFT
VIPER-SWIFT/Classes/Common/Store/CoreDataStore.swift
1
3079
// // CoreDataStore.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import CoreData protocol DataStore { func fetchEntriesWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor], completionBlock: (([TodoItem]) -> Void)!) func newTodoItem(entiry: TodoItem) func save() } class CoreDataStore : NSObject, DataStore { var persistentStoreCoordinator : NSPersistentStoreCoordinator! var managedObjectModel : NSManagedObjectModel! var managedObjectContext : NSManagedObjectContext! override init() { print("creating \(self.dynamicType)") managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil) persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let domains = NSSearchPathDomainMask.UserDomainMask let directory = NSSearchPathDirectory.DocumentDirectory let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domains).first! let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true] let storeURL = applicationDocumentsDirectory.URLByAppendingPathComponent("VIPER-SWIFT.sqlite") try! persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: "", URL: storeURL, options: options) managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator managedObjectContext.undoManager = nil super.init() } deinit { print("deinit \(self.dynamicType)") } func fetchEntriesWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor], completionBlock: (([TodoItem]) -> Void)!) { let fetchRequest = NSFetchRequest(entityName: "TodoItem") fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sortDescriptors managedObjectContext.performBlock { let queryResults = try? self.managedObjectContext.executeFetchRequest(fetchRequest) let managedResults = queryResults! as! [ManagedTodoItem] completionBlock(managedResults.map(self.todoItemFromDataStoreEntry)) } } func newTodoItem(entry: TodoItem) { let newEntry = NSEntityDescription.insertNewObjectForEntityForName("TodoItem", inManagedObjectContext: managedObjectContext) as! ManagedTodoItem newEntry.name = entry.name newEntry.date = entry.dueDate } func save() { do { try managedObjectContext.save() } catch _ { } } func todoItemFromDataStoreEntry(entry: ManagedTodoItem) -> TodoItem { return TodoItem(dueDate: entry.date, name: entry.name as String) } }
mit
b12e9fed922cb31489983dd658ab8408
37.974684
152
0.717441
6.296524
false
false
false
false
carabina/Tactile
Source/UIControl+Tactile.swift
2
15027
// // Tactile // // The MIT License (MIT) // // Copyright (c) 2015 Damien D. // // 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 UIKit // MARK: Hashable extension UIControlEvents: Hashable { public var hashValue: Int { return Int(rawValue) } } // MARK: UIControl private extension UIControl { /** Attaches an event handler function for an event. :param: control An object whose class descends from the UIControl class :param: event A UIControlEvents event :param: callback The event handler function :returns: The control */ func on<T: UIControl>(control: T, event: UIControlEvents, callback: T -> Void) -> T { let actor = Actor(control: control, event: event, callback: callback) addTarget(actor.proxy, action: "recognized:", forControlEvents: event) return control } /** Attaches an event handler function for multiple events. :param: control An object whose class descends from the UIControl class :param: events An array of UIControlEvents :param: callback The event handler function :returns: The control */ func on<T: UIControl>(control: T, events: [UIControlEvents], callback: T -> Void) -> T { for event in events { on(control, event: event, callback: callback) } return control } /** Attaches event handler functions for different events. :param: control An object whose class descends from the UIControl class :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The control */ func on<T: UIControl>(control: T, callbacks: [UIControlEvents: T -> Void]) -> T { for (event, callback) in callbacks { on(control, event: event, callback: callback) } return control } } // MARK: UIButton public extension UIButton { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The button */ func on(event: UIControlEvents, _ callback: UIButton -> Void) -> UIButton { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The button */ func on(events: [UIControlEvents], _ callback: UIButton -> Void) -> UIButton { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UIButton -> Void]) -> UIButton { return super.on(self, callbacks: callbacks) } } // MARK: UIDatePicker public extension UIDatePicker { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The datepicker */ func on(event: UIControlEvents, _ callback: UIDatePicker -> Void) -> UIDatePicker { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The datepicker */ func on(events: [UIControlEvents], _ callback: UIDatePicker -> Void) -> UIDatePicker { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UIDatePicker -> Void]) -> UIDatePicker { return super.on(self, callbacks: callbacks) } } // MARK: UIPageControl public extension UIPageControl { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The page control */ func on(event: UIControlEvents, _ callback: UIPageControl -> Void) -> UIPageControl { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The page control */ func on(events: [UIControlEvents], _ callback: UIPageControl -> Void) -> UIPageControl { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UIPageControl -> Void]) -> UIPageControl { return super.on(self, callbacks: callbacks) } } // MARK: UIRefreshControl public extension UIRefreshControl { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The refresh control */ func on(event: UIControlEvents, _ callback: UIRefreshControl -> Void) -> UIRefreshControl { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The refresh control */ func on(events: [UIControlEvents], _ callback: UIRefreshControl -> Void) -> UIRefreshControl { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UIRefreshControl -> Void]) -> UIRefreshControl { return super.on(self, callbacks: callbacks) } } // MARK: UISegmentedControl public extension UISegmentedControl { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The segmented control */ func on(event: UIControlEvents, _ callback: UISegmentedControl -> Void) -> UISegmentedControl { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The segmented control */ func on(events: [UIControlEvents], _ callback: UISegmentedControl -> Void) -> UISegmentedControl { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UISegmentedControl -> Void]) -> UISegmentedControl { return super.on(self, callbacks: callbacks) } } // MARK: UISlider public extension UISlider { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The slider */ func on(event: UIControlEvents, _ callback: UISlider -> Void) -> UISlider { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The slider */ func on(events: [UIControlEvents], _ callback: UISlider -> Void) -> UISlider { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UISlider -> Void]) -> UISlider { return super.on(self, callbacks: callbacks) } } // MARK: UIStepper public extension UIStepper { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The stepper */ func on(event: UIControlEvents, _ callback: UIStepper -> Void) -> UIStepper { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The stepper */ func on(events: [UIControlEvents], _ callback: UIStepper -> Void) -> UIStepper { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UIStepper -> Void]) -> UIStepper { return super.on(self, callbacks: callbacks) } } // MARK: UISwitch public extension UISwitch { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The switch */ func on(event: UIControlEvents, _ callback: UISwitch -> Void) -> UISwitch { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The switch */ func on(events: [UIControlEvents], _ callback: UISwitch -> Void) -> UISwitch { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UISwitch -> Void]) -> UISwitch { return super.on(self, callbacks: callbacks) } } // MARK: UITextField public extension UITextField { /** Attaches an event handler function for an event. :param: event A UIControlEvents event :param: callback The event handler function :returns: The text field */ func on(event: UIControlEvents, _ callback: UITextField -> Void) -> UITextField { return super.on(self, event: event, callback: callback) } /** Attaches an event handler function for multiple events. :param: events An array of UIControlEvents :param: callback The event handler function :returns: The text field */ func on(events: [UIControlEvents], _ callback: UITextField -> Void) -> UITextField { return super.on(self, events: events, callback: callback) } /** Attaches event handler functions for different events. :param: callbacks A dictionary with a UIControlEvents event as the key and an event handler function as the value :returns: The button */ func on(callbacks: [UIControlEvents: UITextField -> Void]) -> UITextField { return super.on(self, callbacks: callbacks) } } // MARK: Actor private protocol Triggerable { func trigger(control: UIControl) } private struct Actor<T: UIControl>: Triggerable { let callback: T -> Void var proxy: Proxy! init(control: T, event: UIControlEvents, callback: T -> Void) { self.callback = callback self.proxy = Proxy(actor: self, control: control, event: event) } func trigger(control: UIControl) { if let control = control as? T { callback(control) } } } // MARK: Proxy private let proxies = NSMapTable.weakToStrongObjectsMapTable() private class Proxy: NSObject { var actor: Triggerable! init(actor: Triggerable, control: UIControl, event: UIControlEvents) { super.init() self.actor = actor proxies.setObject(self, forKey: "\(control, event.rawValue)") } @objc func recognized(control: UIControl) { actor.trigger(control) } }
mit
12f5727442d7417062ae6852d4abd9a5
28.874751
121
0.631996
5.009
false
false
false
false
MakeAWishFoundation/SwiftyMocky
SwiftyMocky-Example/Shared/AssociatedTypes/SuggestionRepository.swift
1
1052
// // SuggestionRepository.swift // SwiftyMocky // // Created by Andrzej Michnia on 11/11/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation //sourcery: AutoMockable //sourcery: typealias = "Entity = Suggestion" protocol SuggestionRepository: Repository where Entity == Suggestion {} //sourcery: AutoMockable //sourcery: associatedtype = "Entity: SuggestionProtocol" protocol SuggestionRepositoryConstrainedToProtocol: Repository where Entity: SuggestionProtocol {} protocol Repository { associatedtype Entity: EntityType func save(entity: Entity) -> Bool func save(entities: [Entity]) -> Bool func find( where predicate: NSPredicate, sortedBy sortDescriptors: [NSSortDescriptor] ) -> [Entity] func findOne(where predicate: NSPredicate) -> Entity func delete(entity: Entity) -> Bool func delete(entities: [Entity]) -> Bool } protocol EntityType {} protocol SuggestionProtocol: EntityType, AutoMockable { } class Suggestion: SuggestionProtocol { init() {} }
mit
1a59a1b8a833768f7a949291816963f1
24.634146
98
0.727878
4.51073
false
false
false
false
carabina/FunkySwift
Source/Int.swift
1
2665
// // Int.swift // FunkySwift // // Created by Donnacha Oisín Kidney on 27/05/2015. // Copyright (c) 2015 Donnacha Oisín Kidney. All rights reserved. // import Foundation extension Int { func isEven() -> Bool { return self % 2 == 0 } func isOdd() -> Bool { return self % 2 != 0 } /** returns the greatest common divisor of self and a */ func gcd(var a: Int) -> Int { var b = self while a != 0 { (b, a) = (a, b % a) } return b } /** returns the lowest common multiple of self and a */ func lcm(a: Int) -> Int { return self * a / self.gcd(a) } /** concatenates self with x, as in: 54.concat(21) = 5421 :param: the number to be concatenated onto the end of self */ func concat(x: Int) -> Int { return self * Int(pow(10,(ceil(log10(Double(x)))))) + x } /** returns an array of the digits of self */ func digits() -> [Int] { var left = self return Array( GeneratorOf<Int> { let ret = left % 10 left /= 10 return ret > 1 ? ret : nil } ).reverse() } /** repeats a function n times, where n is self */ func times<T>(call: () -> T) { for _ in 0..<self { call() } } func primesBelow() -> GeneratorOf<Int> { let max = Int(ceil(sqrt(Double(self)))) var (nums, i) = ([Int](0..<self), 1) return GeneratorOf { for (++i; i < self; ++i) { if nums[i] != 0 { if i < max {for nP in stride(from: i*i, to: self, by: i){nums[nP] = 0}} return i }} return nil } } func primeFactors() -> GeneratorOf<Int> { var g = self.primesBelow() var accu = 1 return GeneratorOf{ while let next = g.next() where accu != self { if self % next == 0{ for(var tot = accu; self % tot == 0; tot *= next) {accu = tot} return next } } return nil } } func isPrime() -> Bool { switch self { case let n where n < 2: return false case 2, 3: return true default: let max = Int(sqrt(Double(self))) var nums = [Int](0...self) for (var i = 2; i <= max; ++i) { if nums[i] != 0 { if self % i == 0 { return false } else { for nP in stride(from: i*i, through: max, by: i){ nums[nP] = 0 } } }} return true } } func isDivBy(n: Int) -> Bool { return self % n == 0 } } infix operator |+ {associativity left precedence 160} func |+(lhs: Int, rhs: Int) -> Int { return lhs.concat(rhs) } func remquo(x: Int, y: Int) -> (Int, Int) { let ans = div(Int32(x), Int32(y)) return (Int(ans.rem), Int(ans.quot)) }
mit
571053f513c5f9ff98c0b1f42783f043
19.976378
79
0.519715
3.255501
false
false
false
false
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/PaymentDetailsViewController.swift
1
5124
// // PaymentDetailsViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 10/31/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit import LocalAuthentication class PaymentDetailsViewController: UIViewController, UITextFieldDelegate { //Variables var ticket: Ticket? var currentTip: Double? //IBOutlets @IBOutlet weak var payTitle: UILabel! @IBOutlet weak var ticketTitle: UILabel! @IBOutlet weak var priceTitle: UILabel! @IBOutlet weak var tipTitle: UILabel! @IBOutlet weak var dollarTitle: UILabel! @IBOutlet var ticketLabel: UILabel! @IBOutlet var priceLabel: UILabel! @IBOutlet var confirmButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var tipField: UITextField! @IBOutlet var paymentLine: UIView! @IBOutlet var tipLine: UIView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true ticketLabel.text = ticket!.desc! priceLabel.text = "$" + String(format: "%.2f", ticket!.total!) tipField.delegate = self tipField.keyboardType = .numbersAndPunctuation loadTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldDidEndEditing(_ textField: UITextField) { currentTip = Double(textField.text!) } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PaymentSummarySegue" { let paySumVC = segue.destination as! PaymentSummaryViewController TicketManager.UpdatePayTicket(ticket: ticket!, isPaid: true) ticket!.paid = true paySumVC.ticket = ticket } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 let nextResponder = textField.superview?.viewWithTag(nextTag) if nextResponder != nil { nextResponder?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } @IBAction func confirmButtonPressed(_ sender: AnyObject) { let confirmPopup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PaymentPopup") as! PaymentPopupViewController self.addChildViewController(confirmPopup) self.view.addSubview(confirmPopup.view) confirmPopup.didMove(toParentViewController: self) if currentTip != nil { ticket!.tip! = currentTip! } else { ticket!.tip! = 0.0 } } @IBAction func cancelButtonPressed(_ sender: AnyObject) { performSegue(withIdentifier: "UnwindToSummarySegue", sender: self) } //Get Touch ID func ConfirmWithTouchID(laContext: LAContext)->(Bool, NSError?){ var error: NSError? var didSucceed = false guard laContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else { return (didSucceed, error) } laContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Only device owner is allowed", reply: { (success, error) -> Void in if( success ) { didSucceed = success } else{ // Check if there is an error if error != nil { didSucceed = false } } }) return (didSucceed, error) } //yup this is exactly what I hand in mind. Nice job. func loadTheme() { //Background and Tint self.view.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Labels payTitle.textColor = currentTheme!.highlight! ticketTitle.textColor = currentTheme!.highlight! priceTitle.textColor = currentTheme!.highlight! tipTitle.textColor = currentTheme!.highlight! ticketLabel.textColor = currentTheme!.highlight! priceLabel.textColor = currentTheme!.highlight! tipField.textColor = currentTheme!.highlight! tipLine.backgroundColor = currentTheme!.highlight! dollarTitle.textColor = currentTheme!.highlight! paymentLine.backgroundColor = currentTheme!.highlight! //Buttons confirmButton.backgroundColor = currentTheme!.highlight! confirmButton.setTitleColor(currentTheme!.primary!, for: .normal) cancelButton.backgroundColor = currentTheme!.highlight! cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) } }
mit
eab80d32f07aa2204a1615973c7baca6
30.819876
168
0.62034
5.485011
false
false
false
false
davepagurek/raytracer
Sources/Geometry/SubsurfaceScatterer.swift
1
2114
import VectorMath import RaytracerLib import Foundation public struct SubsurfaceMaterial { let density: Scalar let color: Color let bounceFn: (Vector4, Vector4) -> Vector4 public init(density: Scalar, color: Color, bounceFn: @escaping (Vector4, Vector4) -> Vector4) { self.density = density self.color = color self.bounceFn = bounceFn } } public struct SubsurfaceScatterer : ContainedSurface { let object: ContainedSurface let density: Scalar let color: Color public init(object: ContainedSurface, density: Scalar, color: Color) { self.object = object self.density = density self.color = color } public func boundingBox() -> BoundingBox { return object.boundingBox() } public func containsPoint(_ point: Vector4) -> Bool { return object.containsPoint(point) } public func normalAt(_ point: Vector4) -> Vector4 { return object.normalAt(point) } public func intersectsRay(_ ray: Ray, min minimum: Scalar, max maximum: Scalar) -> Intersection? { if let start = object.intersectsRay(ray, min: minimum, max: maximum) { var nextRay: Ray = Ray( point: start.point + ray.direction.normalized() * minimum, direction: ray.direction, color: ray.color, time: ray.time ) var prevIntersection: Intersection = start while true { if let end = object.intersectsRay(nextRay, min: minimum, max: maximum) { let path = end.point - nextRay.point let distanceTravelled = -log(rand(0,1))/density if distanceTravelled < path.length { let nextPoint = nextRay.point + path.normalized()*distanceTravelled nextRay = Ray( point: nextPoint, direction: randomVector(), color: nextRay.color.multiply(color), time: nextRay.time ) prevIntersection = end } else { return end } } else { // Basically on the edge return prevIntersection } } } else { return nil } } }
mit
bb0842c167ff2a6ff51600d655122335
27.186667
100
0.618732
4.305499
false
false
false
false
zvonler/PasswordElephant
external/github.com/CryptoSwift/Sources/CryptoSwift/HKDF.swift
5
3218
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // https://www.ietf.org/rfc/rfc5869.txt // #if canImport(Darwin) import Darwin #else import Glibc #endif /// A key derivation function. /// /// HKDF - HMAC-based Extract-and-Expand Key Derivation Function. public struct HKDF { public enum Error: Swift.Error { case invalidInput case derivedKeyTooLong } private let numBlocks: Int // l private let dkLen: Int private let info: Array<UInt8> fileprivate let prk: Array<UInt8> fileprivate let variant: HMAC.Variant /// - parameters: /// - variant: hash variant /// - salt: optional salt (if not provided, it is set to a sequence of variant.digestLength zeros) /// - info: optional context and application specific information /// - keyLength: intended length of derived key public init(password: Array<UInt8>, salt: Array<UInt8>? = nil, info: Array<UInt8>? = nil, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha256) throws { guard !password.isEmpty else { throw Error.invalidInput } let dkLen = keyLength ?? variant.digestLength let keyLengthFinal = Double(dkLen) let hLen = Double(variant.digestLength) let numBlocks = Int(ceil(keyLengthFinal / hLen)) // l = ceil(keyLength / hLen) guard numBlocks <= 255 else { throw Error.derivedKeyTooLong } /// HKDF-Extract(salt, password) -> PRK /// - PRK - a pseudo-random key; it is used by calculate() prk = try HMAC(key: salt ?? [], variant: variant).authenticate(password) self.info = info ?? [] self.variant = variant self.dkLen = dkLen self.numBlocks = numBlocks } public func calculate() throws -> Array<UInt8> { let hmac = HMAC(key: prk, variant: variant) var ret = Array<UInt8>() ret.reserveCapacity(numBlocks * variant.digestLength) var value = Array<UInt8>() for i in 1...numBlocks { value.append(contentsOf: info) value.append(UInt8(i)) let bytes = try hmac.authenticate(value) ret.append(contentsOf: bytes) /// update value to use it as input for next iteration value = bytes } return Array(ret.prefix(dkLen)) } }
gpl-3.0
d896869abd7d943ad182896a05353d26
37.297619
217
0.657445
4.199739
false
false
false
false
HongliYu/DPSlideMenuKit-Swift
DPSlideMenuKitDemo/SideContent/DPMessageListViewController.swift
1
6680
// // DPMessageListViewController.swift // DPSlideMenuKitDemo // // Created by Hongli Yu on 04/07/2017. // Copyright © 2017 Hongli Yu. All rights reserved. // import UIKit let kDPMessageListCellReuseID: String = "kDPMessageListCellReuseID" class DPMessageListViewController: DPBaseEmbedViewController { @IBOutlet weak var mainTableView: UITableView! @IBOutlet weak var editButton: UIButton! { didSet { editButton.titleLabel!.font = UIFont(name: "fontawesome", size: 24)! editButton.setTitle("\u{f044}", for: .normal) editButton.setTitleColor(UIColor.white, for: .normal) } } private(set) var messageViewModels: [DPMessageViewModel] = [] @IBOutlet weak var titleContentViewTopConstraints: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() basicUI() basicData() } func basicUI() { mainTableView.register(UITableViewCell.self, forCellReuseIdentifier: kDPMessageListCellReuseID) mainTableView.separatorStyle = .none mainTableView.backgroundColor = UIColor.clear mainTableView.delegate = self mainTableView.dataSource = self if UIScreen().iPhoneBangsScreen { titleContentViewTopConstraints.constant = 20 } } func basicData() { let messageCellViewModel0 = DPMessageCellViewModel(color: UIColor.random(), title: "@Alina", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } if let viewController = UIViewController.viewController(DPChatViewController.self, storyboard: "Pages") as? DPChatViewController { DPSlideMenuManager.shared.replaceCenter(viewController, position: strongSelf.positionState) viewController.bindData(title: "@Alina", message: "Hi Alina, Wie geht es dir~") } } let messageCellViewModel1 = DPMessageCellViewModel(color: UIColor.random(), title: "@Dana", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } if let viewController = UIViewController.viewController(DPChatViewController.self, storyboard: "Pages") as? DPChatViewController { DPSlideMenuManager.shared.replaceCenter(viewController, position: strongSelf.positionState) viewController.bindData(title: "@Dana", message: "Hi Dana, Wie geht es dir~") } } let messageCellViewModel2 = DPMessageCellViewModel(color: UIColor.random(), title: "@Ivana", cellHeight: kDefaultCellHeight) { [weak self] in guard let strongSelf = self else { return } if let viewController = UIViewController.viewController(DPChatViewController.self, storyboard: "Pages") as? DPChatViewController { DPSlideMenuManager.shared.replaceCenter(viewController, position: strongSelf.positionState) viewController.bindData(title: "@Ivana", message: "Hi Ivana, Wie geht es dir~") } } let messageSectionViewModel = DPMessageSectionViewModel(title: "RECENT", height: kDefaultSectionHeight, actionBlock: nil) let messageViewModel0: DPMessageViewModel = DPMessageViewModel( messageCellViewModels: [messageCellViewModel0, messageCellViewModel1, messageCellViewModel2], messageSectionViewModel: messageSectionViewModel) messageViewModels.append(messageViewModel0) } } extension DPMessageListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return messageViewModels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { for (index, messageViewModel) in messageViewModels.enumerated() { if section == index { return messageViewModel.messageCellViewModels?.count ?? 0 } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kDPMessageListCellReuseID, for: indexPath) let messageViewModel: DPMessageViewModel? = messageViewModels[indexPath.section] let messageCellViewModel: DPMessageCellViewModel? = messageViewModel?.messageCellViewModels?[indexPath.row] cell.textLabel?.text = messageCellViewModel?.title?.localized cell.textLabel?.textColor = UIColor.white cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20.0) cell.backgroundColor = messageCellViewModel?.color return cell } } extension DPMessageListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 1 ? kDefaultSectionHeight : 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section == 0 else { return nil } let messageViewModel: DPMessageViewModel? = messageViewModels[section] let view = UIView(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height:20)) view.backgroundColor = UIColor.clear let label = UILabel(frame: CGRect(x:16, y:0, width:200, height:kDefaultSectionHeight)) label.font = UIFont.systemFont(ofSize: 16) label.text = messageViewModel?.messageSectionViewModel?.title label.textColor = UIColor.white label.backgroundColor = UIColor.clear view.addSubview(label) return view } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let messageViewModel: DPMessageViewModel? = messageViewModels[indexPath.section] let messageCellViewModel: DPMessageCellViewModel? = messageViewModel?.messageCellViewModels?[indexPath.row] return messageCellViewModel?.cellHeight ?? kDefaultCellHeight } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let messageViewModel: DPMessageViewModel? = messageViewModels[indexPath.section] let messageCellViewModel: DPMessageCellViewModel? = messageViewModel?.messageCellViewModels?[indexPath.row] messageCellViewModel?.actionBlock?() } }
mit
8effa9567490a1b5c7121dcee5ffc670
41.814103
111
0.674502
5.263199
false
false
false
false
lioonline/v2ex-lio
V2ex/V2ex/FeedReplyCell.swift
1
3080
// // FeedReplyCell.swift // V2ex // // Created by Lee on 16/4/12. // Copyright © 2016年 lio. All rights reserved. // import UIKit class FeedReplyCell: UITableViewCell,UITextViewDelegate { override func awakeFromNib() { super.awakeFromNib() // Initialization code } let avatar = UIButton() let nameAndTime = UILabel() let conten = UITextView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initView(){ self.contentView.addSubview(avatar) avatar.layer.cornerRadius = 4 avatar.clipsToBounds = true // self.avatar.backgroundColor = UIColor.redColor() self.avatar.snp_makeConstraints { (make) in make.top.equalTo(self.contentView.snp_top).offset(10) make.left.equalTo(self.contentView.snp_left).offset(10) make.height.width.equalTo(44) } self.contentView.addSubview(nameAndTime) nameAndTime.textColor = RGBA(128, g: 128, b: 128, a: 1) nameAndTime.font = UIFont.systemFontOfSize(12) self.nameAndTime.snp_makeConstraints { (make) in make.left.equalTo(self.avatar.snp_right).offset(10) make.top.equalTo(avatar.snp_top) make.height.equalTo(20) make.right.equalTo(self.contentView.snp_right).offset(-60) } self.contentView.addSubview(self.conten) conten.font = UIFont.systemFontOfSize(17) conten.scrollEnabled = false conten.editable = false conten.selectable = true conten.textContainer.lineFragmentPadding = 0 conten.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0) conten.delegate = self self.conten.snp_makeConstraints { (make) in make.top.equalTo(nameAndTime.snp_bottom).offset(5) make.left.equalTo(nameAndTime.snp_left) make.right.equalTo(self.contentView.snp_right).offset(-10) make.bottom.equalTo(self.contentView.snp_bottom).offset(-10) } } func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool{ // 验证是邮箱 电话 还是URL NSLog("链接地址:\(URL.description)") let str = textView.attributedText.attributedSubstringFromRange(characterRange) let alert = UIAlertView.init(title: str.string, message: "", delegate: nil, cancelButtonTitle: "OK") alert.show() return false } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
48914ca4877c846a1e134d18a4f0f28a
28.621359
115
0.609636
4.533432
false
false
false
false
ekurutepe/Motif
Examples/SwiftButtonsExample/UIView+Theming.swift
3
2076
// // UIView+Theming.swift // SwiftButtonsExample // // Created by Eric Horacek on 3/14/15. // Copyright (c) 2015 Eric Horacek. All rights reserved. // import UIKit import Motif extension UIView { public override class func initialize() { if self !== UIView.self { return } self.mtf_registerThemeProperty( ThemeProperties.backgroundColor.rawValue, requiringValueOfClass: UIColor.self, applierBlock: { (color, view) -> Void in if let view = view as? UIView, let color = color as? UIColor { view.backgroundColor = color } } ) self.mtf_registerThemeProperty( ThemeProperties.borderColor.rawValue, requiringValueOfClass: UIColor.self, applierBlock: { (color, view) -> Void in if let view = view as? UIView, let color = color as? UIColor { view.layer.borderColor = color.CGColor } } ) self.mtf_registerThemeProperty( ThemeProperties.cornerRadius.rawValue, requiringValueOfClass: NSNumber.self, applierBlock: { (cornerRadius, view) -> Void in if let view = view as? UIView, let cornerRadius = cornerRadius as? NSNumber { view.layer.cornerRadius = CGFloat(cornerRadius.floatValue) } } ) self.mtf_registerThemeProperty( ThemeProperties.borderWidth.rawValue, requiringValueOfClass: NSNumber.self, applierBlock: { (borderWidth, view) -> Void in if let view = view as? UIView, let borderWidth = borderWidth as? NSNumber { view.layer.borderWidth = CGFloat(borderWidth.floatValue) } } ) } }
mit
05571b5e298c160874cf0e79ec035d8d
31.4375
82
0.508671
5.269036
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/TabContentsScripts/SessionRestoreHelper.swift
2
1215
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import WebKit protocol SessionRestoreHelperDelegate: AnyObject { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) } class SessionRestoreHelper: TabContentScript { weak var delegate: SessionRestoreHelperDelegate? fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab } func scriptMessageHandlerName() -> String? { return "sessionRestoreHelper" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let tab = tab, let params = message.body as? [String: AnyObject] { if params["name"] as! String == "didRestoreSession" { DispatchQueue.main.async { self.delegate?.sessionRestoreHelper(self, didRestoreSessionForTab: tab) } } } } class func name() -> String { return "SessionRestoreHelper" } }
mpl-2.0
b35ef2312de774e17d59a398446e52dc
31.837838
132
0.67572
5
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/ViewModel/HearViewModel.swift
1
980
// // HearViewModel.swift // MGDYZB // // Created by i-Techsys.com on 17/4/10. // Copyright © 2017年 ming. All rights reserved. // import UIKit class HearViewModel: BaseViewModel { lazy var tag_id: Int = 0 lazy var offset: Int = 0 /* http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=20&client_sys=ios&offset=0 // 颜值 http://capi.douyucdn.cn/api/v1/live/1?limit=20&client_sys=ios&offset=0 // 英雄联盟 http://capi.douyucdn.cn/api/v1/live/124?limit=20&client_sys=ios&offset=0 // 户外 http://capi.douyucdn.cn/api/v1/live/148?limit=20&client_sys=ios&offset=0 // 守望先锋 */ func loadHearderData(_ finishCallback: @escaping () -> ()) { let urlStr = "http://capi.douyucdn.cn/api/v1/live/\(tag_id)" let parameters: [String: Any] = ["limit": 20,"client_sys": "ios","offset": offset] loadAnchorData(isGroup: false, urlString: urlStr, parameters: parameters, finishedCallback: finishCallback) } }
mit
08e1096ef3ab03b42a3abe234031b89f
34.296296
115
0.660021
3.035032
false
false
false
false
felipesantolim/MemeMeProject_V2_SOLVED
MemeMe/ViewController/MemeMeViewController.swift
1
6784
// // MemeMeViewController.swift // MemeMe // // Created by Felipe Henrique Santolim on 12/18/16. // Copyright © 2016 Felipe Henrique Santolim. All rights reserved. // import UIKit private typealias SaveResult = () -> () class MemeMeViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var isCancel: Bool = false var isEditMemeMe: Bool = false var meme: Meme? //MARK: private properties private enum SourceType: Int { case Camera = 0, Album } private var mainView: MemeMeView { return self.view as! MemeMeView } //MARK: lifecycle override func viewDidLoad() { super.viewDidLoad() mainView.shareButton.isEnabled = false mainView.cancelButton.isEnabled = isCancel if isEditMemeMe { changeMemeMe() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) subscribeToKeyboardDelegates() subscribeToKeyboardNotifications() mainView.cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unsubscribeFromKeyboardNotifications() } override var prefersStatusBarHidden: Bool { return true } //MARK: actions @IBAction func openCameraOrAlbum (_ sender: UIButton) { let pickerController = UIImagePickerController() pickerController.delegate = self switch (SourceType(rawValue: sender.tag)!) { case .Camera: pickerController.sourceType = .camera break case .Album: pickerController.sourceType = .photoLibrary break } present(pickerController, animated: true, completion: nil) } @IBAction func openShareController (_ sender: UIButton) { guard let image = mainView.memeImage.image else { return } save(image) { let shareController = UIActivityViewController(activityItems: [meme!.shareImage], applicationActivities: nil) present(shareController, animated: true, completion: nil) shareController.completionWithItemsHandler = { activity, success, items, error in if success { guard let me = self.meme else { return } (UIApplication.shared.delegate as! AppDelegate).memes.append(me) self.dismiss(animated: true, completion: nil) } } } } @IBAction func cancelMemeMe (_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } //MARK: UIImagePickerController delegates func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { mainView.memeImage.image = image mainView.shareButton.isEnabled = true } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } //MARK: UITextField delegates private func subscribeToKeyboardDelegates () { mainView.memeDescriptionTopText.delegate = self mainView.memeDescriptionBotText.delegate = self } func textFieldShouldReturn(_ textField: UITextField) -> Bool { mainView.memeDescriptionTopText.resignFirstResponder() mainView.memeDescriptionBotText.resignFirstResponder() return true } //MARK: Notification observers private func subscribeToKeyboardNotifications () { NotificationCenter.default.addObserver(self, selector: #selector(MemeMeViewController.keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MemeMeViewController.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) } private func unsubscribeFromKeyboardNotifications () { NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil) } @objc private func keyboardWillShow (_ notification: Notification) { if mainView.memeDescriptionBotText.isEditing { view.frame.origin.y -= getKeyboardHeight(notification) } } @objc private func keyboardWillHide (_ notification: Notification) { if mainView.memeDescriptionBotText.resignFirstResponder() { view.frame.origin.y += getKeyboardHeight(notification) } } private func getKeyboardHeight (_ notification: Notification) -> CGFloat { let info = notification.userInfo let keyboardSize = info?[UIKeyboardFrameEndUserInfoKey] as! NSValue return keyboardSize.cgRectValue.height } //MARK: Private functions private func save(_ image: UIImage, _ completion: SaveResult) { meme = Meme( bottomDescription: mainView.memeDescriptionBotText.text!, topDescription: mainView.memeDescriptionTopText.text!, originalImage: image, shareImage: generateMemedImage() ) completion() } private func generateMemedImage () -> UIImage { navigationAndToolbarNonAvailable(true) UIGraphicsBeginImageContext(self.view.frame.size) view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true) let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() navigationAndToolbarNonAvailable(false) return memedImage } private func navigationAndToolbarNonAvailable (_ isAvailable: Bool) { mainView.memeTolbarControl.isHidden = isAvailable mainView.memeNavigationBar.isHidden = isAvailable } private func changeMemeMe () { mainView.shareButton.isEnabled = true guard let meme = meme else { return } mainView.memeDescriptionTopText.text = meme.topDescription mainView.memeDescriptionBotText.text = meme.bottomDescription mainView.memeImage.image = meme.originalImage } }
mit
59eefdbf0327e1e648404d480828daef
32.25
156
0.640572
5.898261
false
false
false
false
Trevi-Swift/Trevi-sys
Sources/Tcp.swift
1
4898
// // Tcp.swift // Trevi // // Created by JangTaehwan on 2016. 2. 17.. // Copyright © 2016 Trevi Community. All rights reserved. // import Libuv /** Libuv Tcp bindings and allow the user to use a closure on event. */ public class Tcp : Stream { public let tcpHandle : uv_tcp_ptr public init () { self.tcpHandle = uv_tcp_ptr.alloc(1) uv_tcp_init(uv_default_loop(), self.tcpHandle) super.init(streamHandle : uv_stream_ptr(self.tcpHandle)) } deinit { if isAlive { Handle.close(self.handle) self.tcpHandle.dealloc(1) isAlive = false } } } // Tcp static functions. extension Tcp { public static func open (handle : uv_tcp_ptr, fd : uv_os_fd_t) { // Sets socket fd to non-block. uv_tcp_open(handle, fd) } public static func bind(handle : uv_tcp_ptr, address: String, port: Int32) -> Int32? { var sockaddr = sockaddr_in() let status = withUnsafeMutablePointer(&sockaddr) { (ptr) -> Int32 in var error = uv_ip4_addr(address, port, ptr) if error == 0 { error = uv_tcp_bind(handle , UnsafePointer(ptr), 0) } return error } if status != 0 { LibuvError.printState("Tcp.bind", error : status) return nil } return status } public static func bind6(handle : uv_tcp_ptr, address: String, port: Int32) -> Int32? { var sockaddr = sockaddr_in6() let status = withUnsafeMutablePointer(&sockaddr) { (ptr) -> Int32 in var error = uv_ip6_addr(address, port, ptr) if error == 0{ error = uv_tcp_bind(handle , UnsafePointer(ptr), 0) } return error } if status != 0 { LibuvError.printState("Tcp.bind6", error : status) return nil } return status } public static func listen(handle : uv_tcp_ptr, backlog : Int32 = 50) -> Int32? { // Set onConnection event from other thread in thread pool. Not stable yet. // let error = uv_listen(uv_stream_ptr(handle), backlog, Work.onConnection) let error = uv_listen(uv_stream_ptr(handle), backlog, Tcp.onConnection) if error != 0 { LibuvError.printState("Tcp.listen", error : error) return nil } Loop.run(mode: UV_RUN_DEFAULT) return error } public static func connect(handle : uv_tcp_ptr) -> Int32? { let request = uv_connect_ptr.alloc(1) let address = Tcp.getSocketName(handle) let error = uv_tcp_connect(request, handle, address, Tcp.afterConnect) if error != 0 { LibuvError.printState("Tcp.connect", error : error) return nil } return error } // Enable / disable Nagle’s algorithm. public static func setNoDelay (handle : uv_tcp_ptr, enable : Int32) { uv_tcp_nodelay(handle, enable) } public static func setKeepAlive (handle : uv_tcp_ptr, enable : Int32, delay : UInt32) { uv_tcp_keepalive(handle, enable, delay) } public static func setSimultaneousAccepts (handle : uv_tcp_ptr, enable : Int32) { uv_tcp_simultaneous_accepts(handle, enable) } // Should add dealloc module on return value sockaddr_ptr. // Temporary it is dealloced public static func getSocketName(handle : uv_tcp_ptr) -> sockaddr_ptr { var len = Int32(sizeof(sockaddr)) let name = sockaddr_ptr.alloc(Int(len)) uv_tcp_getsockname(handle, name, &len) return name } public static func getPeerName(handle : uv_tcp_ptr) -> sockaddr_ptr { var len = Int32(sizeof(sockaddr)) let name = sockaddr_ptr.alloc(Int(len)) uv_tcp_getpeername(handle, name, &len) return name } } // Tcp static callbacks. extension Tcp { public static var onConnection : uv_connection_cb = { (handle, status) in var client = Tcp() if uv_accept(handle, client.streamHandle) != 0 { return } if let wrap = Handle.dictionary[uv_handle_ptr(handle)] { if let callback = wrap.event.onConnection { callback(client.streamHandle) } } client.readStart() } public static var afterConnect : uv_connect_cb = { (request, status) in } }
apache-2.0
c0718c1bfeb36deb75c139d80e571f12
23.722222
91
0.526251
4.173061
false
false
false
false
NirvanAcN/2017DayDayUp
Day3-CustomTimer/Day3-CustomTimer/TimerDisplayViewController.swift
1
1454
// // TimerDisplayViewController.swift // Day3-CustomTimer // // Created by NirvanAcN on 2017/1/5. // Copyright © 2017年 HOME Ma. All rights reserved. // import UIKit enum TimerType: String { case DefaultCustomTimer, EveryTimer, DelayTimer } class TimerDisplayViewController: UIViewController { var timer: Timer! var type = TimerType.DefaultCustomTimer override func viewDidLoad() { super.viewDidLoad() switch type { case .DefaultCustomTimer: timer = Timer.scheduledTimer(timeInterval: 1.0.seconds, repeats: true, event: { _ = $0 print("DefaultCustomTimer") }) timer.start() case .EveryTimer: timer = Timer.every(1.0.seconds, { _ = $0 print("EveryTimer") }) case .DelayTimer: Timer.after(2.0.seconds, { print("DelayTimer") }) } } deinit { timer?.invalidate() print(type(of: self), #function) } /* // 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.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
8cd9694e47ae330539e8a1d6ebf4dcf2
24.017241
106
0.577533
4.520249
false
false
false
false
oneWarcraft/PictureBrowser-Swift
PictureBrowser/PictureBrowser/Classes/PictureBrowser/PictureBrowserAnimator.swift
1
4954
// // PictureBrowserAnimator.swift // PictureBrowser // // Created by 王继伟 on 16/7/14. // Copyright © 2016年 WangJiwei. All rights reserved. // import UIKit protocol PresentedProtocol : class { func getImageView(indexPath : NSIndexPath) -> UIImageView func getStartRect(indexPath : NSIndexPath) -> CGRect func getEndRect(indexPath : NSIndexPath) -> CGRect } protocol DismissProtocol : class { func getImageView() -> UIImageView func getIndexPath() -> NSIndexPath } class PictureBrowserAnimator: NSObject { var isPresented : Bool = false var indexPath : NSIndexPath? weak var presentedDelegate : PresentedProtocol? weak var dismissDelegate : DismissProtocol? } // MARK: 实现pictureBrowser的转场代理方法 extension PictureBrowserAnimator : UIViewControllerTransitioningDelegate { // 告诉弹出的动画交给谁去处理 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true return self } // 告诉消失的动画交给谁去处理 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false return self } } extension PictureBrowserAnimator : UIViewControllerAnimatedTransitioning { // 1.决定动画执行的时间 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 2.0 } // 2.决定动画如何实现 // transitionContext : 可以通过转场上下文去获取弹出的View和即将消失的View func animateTransition(transitionContext: UIViewControllerContextTransitioning) { if isPresented { // 0. nil值校验 guard let indexPath = indexPath, presentedDelegate = presentedDelegate else { return } // 1.获取弹出的View let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)! // // 2.将弹出的View添加到containerView中 // transitionContext.containerView()?.addSubview(presentedView) // 3.执行动画 // 3.1 获取执行动画的imageView let imageView = presentedDelegate.getImageView(indexPath) transitionContext.containerView()?.addSubview(imageView) // 3.2 设置ImageViw的起始位置 imageView.frame = presentedDelegate.getStartRect(indexPath) // 3.3 执行动画 transitionContext.containerView()?.backgroundColor = UIColor.blackColor() UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in imageView.frame = presentedDelegate.getEndRect(indexPath) }) { (_) -> Void in // 2. 将弹出的View添加到containerView中 transitionContext.containerView()?.addSubview(presentedView) transitionContext.containerView()?.backgroundColor = UIColor.clearColor() imageView.removeFromSuperview() transitionContext.completeTransition(true) } }else { guard let dismissDelegate = dismissDelegate, presentedDelegate = presentedDelegate else { return } // 1.取出消失的View let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey) // 2.执行动画 // 2.1 获取执行动画的 ImageView let imageView = dismissDelegate.getImageView() transitionContext.containerView()?.addSubview(imageView) // 2.2 取出indexPath let indexPath = dismissDelegate.getIndexPath() // 2.3 获取结束位置 let endRect = presentedDelegate.getStartRect(indexPath) dismissView?.alpha = endRect == CGRectZero ? 1.0 : 0.0 // 2.4 执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in if endRect == CGRectZero { imageView.removeFromSuperview() dismissView?.alpha = 0.0 }else { imageView.frame = endRect } }, completion: { (_) -> Void in dismissView?.removeFromSuperview() transitionContext.completeTransition(true) }) } } }
apache-2.0
37f50a3f6048a83636e7efa33810d854
31.524476
217
0.605031
6.160265
false
false
false
false
TurfDb/Turf
Turf/Extensions/SecondaryIndex/Internals/SecondaryIndexWriteTransaction.swift
1
3877
internal class SecondaryIndexWriteTransaction<IndexedCollection: TurfCollection, Properties: IndexedProperties>: ExtensionWriteTransaction { // MARK: Private properties private unowned let connection: SecondaryIndexConnection<IndexedCollection, Properties> // MARK: Object lifecycle internal init(connection: SecondaryIndexConnection<IndexedCollection, Properties>) { self.connection = connection } // MARK: Internal methods func handleValueInsertion<TCollection : TurfCollection>(value: TCollection.Value, forKey primaryKey: String, inCollection collection: TCollection) throws { //Exensions are allowed to take values from any collection //We must force cast the value (to ensure it will crash otherwise) to the same type as the indexed collection's value let indexedCollectionValue = value as! Properties.IndexedCollection.Value defer { sqlite3_reset(connection.insertStmt) } let stmt = connection.insertStmt let primaryKeyIndex = SQLITE_FIRST_BIND_COLUMN sqlite3_bind_text(stmt, primaryKeyIndex, primaryKey, -1, SQLITE_TRANSIENT) let properties = connection.index.properties for (index, property) in properties.allProperties.enumerated() { property.bindPropertyValue(indexedCollectionValue, toSQLiteStmt: stmt!, atIndex: Int32(index) + primaryKeyIndex + 1) } if sqlite3_step(stmt).isNotDone { Logger.log(warning: "SQLite error") let db = sqlite3_db_handle(stmt) throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } func handleValueUpdate<TCollection : TurfCollection>(value: TCollection.Value, forKey primaryKey: String, inCollection collection: TCollection) throws { let indexedCollectionValue = value as! Properties.IndexedCollection.Value defer { sqlite3_reset(connection.updateStmt) } let stmt = connection.updateStmt let properties = connection.index.properties let primaryKeyIndex = SQLITE_FIRST_BIND_COLUMN + Int32(properties.allProperties.count) sqlite3_bind_text(stmt, primaryKeyIndex, primaryKey, -1, SQLITE_TRANSIENT) for (index, property) in properties.allProperties.enumerated() { property.bindPropertyValue(indexedCollectionValue, toSQLiteStmt: stmt!, atIndex: Int32(index) + SQLITE_FIRST_BIND_COLUMN) } if sqlite3_step(stmt).isNotDone { Logger.log(warning: "SQLite error") let db = sqlite3_db_handle(stmt) throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } func handleRemovalOfAllRows<TCollection : TurfCollection>(collection: TCollection) throws { defer { sqlite3_reset(connection.removeAllStmt) } if sqlite3_step(connection.removeAllStmt).isNotDone { Logger.log(warning: "SQLite error") let db = sqlite3_db_handle(connection.removeAllStmt) throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } } func handleRemovalOfRows<TCollection : TurfCollection>(withKeys primaryKeys: [String], inCollection collection: TCollection) throws { let primaryKeyIndex = SQLITE_FIRST_BIND_COLUMN for primaryKey in primaryKeys { sqlite3_bind_text(connection.removeStmt, primaryKeyIndex, primaryKey, -1, SQLITE_TRANSIENT) if sqlite3_step(connection.removeStmt).isNotDone { Logger.log(warning: "SQLite error") let db = sqlite3_db_handle(connection.removeStmt) throw SQLiteError.error(code: sqlite3_errcode(db), reason: String(cString: sqlite3_errmsg(db))) } sqlite3_reset(connection.removeStmt) } } }
mit
3330517b7ee50888e2dc35324099075d
45.154762
159
0.696931
4.518648
false
false
false
false
xuzhou524/Convenient-Swift
Convenient-Swift/AppDelegate.swift
1
7583
// // AppDelegate.swift // Convenient-Swift // // Created by gozap on 16/3/1. // Copyright © 2016年 xuzhou. All rights reserved. // import UIKit import CoreLocation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate { var window: UIWindow? var currLocation : CLLocation! var centerNav : XZSwiftNavigationController? //用于定位服务管理类,它能够给我们提供位置信息和高度信息,也可以监控设备进入或离开某个区域,还可以获得设备的运行方向 var locationManager : CLLocationManager = CLLocationManager() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { locationManager.delegate = self //设备使用电池供电时最高的精度 locationManager.desiredAccuracy = kCLLocationAccuracyBest //精确到1000米,距离过滤器,定义了设备移动后获得位置信息的最小距离 locationManager.distanceFilter = kCLLocationAccuracyKilometer locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() self.window = UIWindow(); self.window?.frame=UIScreen.main.bounds; self.window?.backgroundColor = XZSwiftColor.convenientBackgroundColor; self.window?.makeKeyAndVisible(); centerNav = XZSwiftNavigationController(rootViewController: RootWeatherViewController()); self.window?.rootViewController = centerNav; WXApi.registerApp("wx88234dc1246eb81b", withDescription: "用易") //self.shareSetup() return true } // func shareSetup(){ // ShareSDK.registerApp("10ceb4d796c88", activePlatforms: [SSDKPlatformType.typeSinaWeibo.rawValue, // SSDKPlatformType.typeQQ.rawValue, // SSDKPlatformType.typeWechat.rawValue,], onImport: { (platform : SSDKPlatformType) in // switch platform{ // case SSDKPlatformType.typeWechat: // ShareSDKConnector.connectWeChat(WXApi.classForCoder()) // case SSDKPlatformType.typeSinaWeibo: // ShareSDKConnector.connectWeibo(WeiboSDK.classForCoder()) // case SSDKPlatformType.typeQQ: // ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder()) // default: // break // } // }, // onConfiguration: {(platform : SSDKPlatformType,appInfo : NSMutableDictionary!) -> Void in // switch platform { // case SSDKPlatformType.typeSinaWeibo: // //设置新浪微博应用信息,其中authType设置为使用SSO+Web形式授权 // appInfo.ssdkSetupSinaWeibo(byAppKey: "3112753426", // appSecret : "8d827d8c5849b1d763f2d077d20e109e", // redirectUri : "http://www.xzzai.com", // authType : SSDKAuthTypeBoth) // break // case SSDKPlatformType.typeWechat: // //设置微信应用信息 // appInfo.ssdkSetupWeChat(byAppId: "wx88234dc1246eb81b", appSecret: "1c4d416db0008c17e01d616cb3866db7") // break // case SSDKPlatformType.typeQQ: // appInfo.ssdkSetupQQ(byAppId: "1105277654", appKey: "bQcT8M8lTt9MATbY", authType: SSDKAuthTypeBoth) // break // default: // break // } // }) // } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currLocation = locations.last! as CLLocation let geocder = CLGeocoder() var p:CLPlacemark? geocder.reverseGeocodeLocation(currLocation) { (placemarks, error) -> Void in if error != nil { return } let pm = placemarks! as [CLPlacemark] if pm.count > 0{ p = placemarks![0] as CLPlacemark let lenght :Int = ((p?.locality)! as String).Lenght - 1 if p?.locality?.Lenght > 0 { XZSetting.sharedInstance[KplacemarkName] = ((p?.locality)! as NSString).substring(to: lenght) if XZClient.sharedInstance.username != XZSetting.sharedInstance[KplacemarkName]{ XZClient.sharedInstance.username = XZSetting.sharedInstance[KplacemarkName] } } } } locationManager.stopUpdatingLocation() } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
9526675d014cc880a83cf2c6f71e5393
47.450331
285
0.581329
5.45563
false
false
false
false
sfurlani/addsumfun
Add Sum Fun/Add Sum Fun/PlayViewController.swift
1
5706
// // PlayViewController.swift // Add Sum Fun // // Created by SFurlani on 8/26/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import UIKit class PlayViewController: UIViewController { enum SegueIdentifiers: String { case EmbedNumbers = "embedNumbers" case EmbedEquation = "embedEquation" case ShowVerticalEquation = "showVertical" case ShowHorizontalEquation = "showHorizontal" case ShowResults = "showResults" } @IBOutlet var equationContainer: UIView! @IBOutlet var numberContainer: UIView! @IBOutlet var panGesture: UIPanGestureRecognizer! @IBOutlet var correctView: UIImageView! @IBOutlet var incorrectView: UIImageView! // MARK: - Properties var numbersViewController: NumbersViewController! var equationViewController: EquationViewController? { let filtered = childViewControllers.filter { ($0 as? EquationViewController) != nil ? true : false } return filtered.first as? EquationViewController } var gameData: GameType! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - IBActions @IBAction func panUpdate(sender: UIPanGestureRecognizer) { gestureSwitch: switch sender.state { case .Began: numbersViewController.beginDraggingView(sender) case .Changed: numbersViewController.updateDraggingView(sender) case .Ended: guard let panView = numbersViewController.panView, let number = panView.number else { break gestureSwitch } let switchValue = equationViewController?.switchNumber(number, gesture: sender) numbersViewController.endDraggingView(switchValue ?? false, gesture: sender) default: break gestureSwitch } } @IBAction func unwindForNewGame(segue: UIStoryboardSegue) { gameData.addNewRound() equationViewController?.view.hidden = true performSegueWithIdentifier(SegueIdentifiers.ShowVerticalEquation.rawValue, sender: nil) navigationController?.popViewControllerAnimated(true) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { switch segue.destinationViewController { case let vc as NumbersViewController: self.numbersViewController = vc case let vc as EquationViewController: vc.equation = gameData?.currentEquation vc.delegate = self case let vc as ResultsViewController: vc.gameData = gameData default: break } } private func answerEquation(entered: UInt) { guard let answer = gameData.addNewAnswer(entered) else { print("Could not generate answer: \(entered)") return } if answer.isCorrect() { showSuccess(advanceToNextScreen) } else { showFailure(advanceToNextScreen) } } private func advanceToNextScreen() { if let _ = gameData?.currentEquation { let segue = gameData.answers.count % 2 == 0 ? SegueIdentifiers.ShowVerticalEquation.rawValue : SegueIdentifiers.ShowHorizontalEquation.rawValue performSegueWithIdentifier(segue, sender: nil) } else { performSegueWithIdentifier(SegueIdentifiers.ShowResults.rawValue, sender: nil) } } // MARK: Navigation Animations typealias Callback = () -> () private func showSuccess(callback: Callback? ) { showResult(correctView, callback: callback) } private func showFailure(callback: Callback? ) { showResult(incorrectView, callback: callback) } private func showResult(imageView: UIImageView, callback: Callback?) { let diameter = min(view.frame.width, view.frame.height) * 0.8 let radius = diameter / 2 view.addSubview(imageView) imageView.alpha = 0.0 imageView.frame = CGRect(x: view.frame.midX - radius, y: view.frame.midY - radius, width: diameter, height: diameter) imageView.tintColor = UIColor.whiteColor() imageView.layer.cornerRadius = radius imageView.transform = CGAffineTransformMakeScale(0.1, 0.1) UIView.animateWithDuration( 0.3, delay: 0.1, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [UIViewAnimationOptions.CurveEaseOut], animations: { imageView.alpha = 1.0 imageView.transform = CGAffineTransformIdentity }, completion: { (_) in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(200 * NSEC_PER_MSEC)), dispatch_get_main_queue()) { self.hideResult(imageView, callback: callback) } } ) } private func hideResult(imageView: UIImageView, callback: Callback?) { UIView.animateWithDuration( 0.2, animations: { imageView.alpha = 0.0 }, completion: { (_) in imageView.removeFromSuperview() callback?() } ) } } extension PlayViewController: EquationViewControllerDelegate { func didEnterResult(result: UInt) { print("Recieved: \(result)") answerEquation(UInt(result)) } }
mit
05521c2fdc01c0d64bc5c89eccd4c2eb
30.174863
155
0.60631
5.277521
false
false
false
false
imryan/swifty-tinder
Example/Tests/Tests.swift
1
1179
// https://github.com/Quick/Quick import Quick import Nimble import SwiftyTinder class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
0a65cdf17544162de6ac33b63aa53708
22.46
63
0.364876
5.455814
false
false
false
false
WEzou/weiXIn
swift-zw/BaseNavigationController.swift
1
1419
// // BaseNavigationController.swift // swift-zw // // Created by ymt on 2017/12/12. // Copyright © 2017年 ymt. All rights reserved. // import UIKit import WeexSDK class BaseNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() configuration() } func configuration(){ let color = UIColor(0x181d23) let navImage = UIImage.imageWithColor(color) self.navigationBar.setBackgroundImage(navImage, for: .default) self.navigationBar.tintColor = UIColor.white self.navigationBar.tintAdjustmentMode = .automatic self.navigationBar.barTintColor = UIColor.white self.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white] } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count>0 { viewController.hidesBottomBarWhenPushed = true } let tabBarFrame = self.tabBarController?.tabBar.frame super.pushViewController(viewController, animated: animated) self.tabBarController?.tabBar.frame = tabBarFrame! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
7e38083322a0157ac358d17c02b9668d
27.897959
102
0.680085
5.186813
false
false
false
false
adolfrank/Swift_practise
21-day/21-day/RefreshItem.swift
1
834
// // RefreshItem.swift // 21-day // // Created by Hongbo Yu on 16/4/28. // Copyright © 2016年 Frank. All rights reserved. // import UIKit class RefreshItem { private var centerStart: CGPoint private var centerEnd: CGPoint unowned var view: UIView init(view: UIView, centerEnd: CGPoint, parallaxRatio: CGFloat, screenHeight: CGFloat) { self.view = view self.centerEnd = centerEnd centerStart = CGPoint(x: centerEnd.x , y: centerEnd.y + (parallaxRatio * screenHeight)) self.view.center = centerStart } func updateViewPositionForPercentage(percentage: CGFloat) { view.center = CGPoint( x: centerStart.x + (centerEnd.x - centerStart.x) * percentage, y: centerStart.y + (centerEnd.y - centerStart.y) * percentage) } }
mit
8fbdbb5d1847e59a405dd205b57b99b1
26.7
95
0.642599
4.053659
false
false
false
false
ahoppen/swift
test/SILGen/fixed_layout_attribute.swift
29
2729
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s --check-prefix=FRAGILE --check-prefix=CHECK // RUN: %target-swift-emit-silgen -enable-library-evolution -parse-as-library %s | %FileCheck %s --check-prefix=RESILIENT --check-prefix=CHECK // RUN: %target-swift-emit-silgen -parse-as-library -enable-testing %s // RUN: %target-swift-emit-silgen -parse-as-library -enable-testing -enable-library-evolution %s public let global = 0 struct InternalStruct { var storedProperty = global } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s22fixed_layout_attribute14InternalStructV14storedPropertySivpfi : $@convention(thin) () -> Int // // ... okay to directly reference the addressor here: // CHECK: function_ref @$s22fixed_layout_attribute6globalSivau // CHECK: return public struct NonFixedStruct { public var storedProperty = global } // FRAGILE-LABEL: sil [transparent] [ossa] @$s22fixed_layout_attribute14NonFixedStructV14storedPropertySivpfi : $@convention(thin) () -> Int // RESILIENT-LABEL: sil hidden [transparent] [ossa] @$s22fixed_layout_attribute14NonFixedStructV14storedPropertySivpfi : $@convention(thin) () -> Int // // ... okay to directly reference the addressor here: // CHECK: function_ref @$s22fixed_layout_attribute6globalSivau // CHECK: return @frozen public struct FixedStruct { public var storedProperty = global } // CHECK-LABEL: sil non_abi [transparent] [serialized] [ossa] @$s22fixed_layout_attribute11FixedStructV14storedPropertySivpfi : $@convention(thin) () -> Int // // ... a fragile build can still reference the addressor: // FRAGILE: function_ref @$s22fixed_layout_attribute6globalSivau // ... a resilient build has to use the getter because the addressor // is not public, and the initializer is serialized: // RESILIENT: function_ref @$s22fixed_layout_attribute6globalSivg // CHECK: return // This would crash with -enable-testing private let privateGlobal = 0 struct AnotherInternalStruct { var storedProperty = privateGlobal } // Static properties in fixed-layout type is still resilient @frozen public struct HasStaticProperty { public static var staticProperty: Int = 0 } // CHECK-LABEL: sil [ossa] @$s22fixed_layout_attribute18usesStaticPropertyyyF : $@convention(thin) () -> () // CHECK: function_ref @$s22fixed_layout_attribute17HasStaticPropertyV06staticF0Sivau : $@convention(thin) () -> Builtin.RawPointer // CHECK: return public func usesStaticProperty() { _ = HasStaticProperty.staticProperty } // CHECK-LABEL: sil [serialized] [ossa] @$s22fixed_layout_attribute27usesStaticPropertyInlinableyyF : $@convention(thin) () -> () @inlinable public func usesStaticPropertyInlinable() { _ = HasStaticProperty.staticProperty }
apache-2.0
11b5703a5fc64e16ea0c7e6b79b81fba
36.902778
156
0.752657
3.733242
false
false
false
false
halo/LinkLiar
LinkTools/Vendor.swift
1
1634
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 struct Vendor: Comparable, Equatable { init(id: String, name: String, prefixes: [MACPrefix]) { self.id = id self.name = name self.prefixes = prefixes } var name: String var id: String var prefixes: [MACPrefix] var title: String { [name, " ・ ", String(prefixes.count)].joined() } static func <(lhs: Vendor, rhs: Vendor) -> Bool { return lhs.name < rhs.name } } func ==(lhs: Vendor, rhs: Vendor) -> Bool { return lhs.name == rhs.name }
mit
85054a58fee8af2cfe1454761dc54527
36.953488
133
0.727328
4.152672
false
false
false
false
vanyaland/Californication
Californication/PlaceImage.swift
1
2208
/** * Copyright (c) 2016 Ivan Magda * * 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 // MARK: Types private enum Key: String { case thumbnail, medium, large } // MARK: PlaceImage: NSObject, NSCoding final class PlaceImage: NSObject, NSCoding { // MARK: Properties let thumbnailURL: String let mediumURL: String let largeURL: String // MARK: Init init(thumbnail: String, medium: String, large: String) { thumbnailURL = thumbnail mediumURL = medium largeURL = large super.init() } // MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(thumbnailURL, forKey: Key.thumbnail.rawValue) aCoder.encode(mediumURL, forKey: Key.medium.rawValue) aCoder.encode(largeURL, forKey: Key.large.rawValue) } required convenience init?(coder aDecoder: NSCoder) { let thumbnail = aDecoder.decodeObject(forKey: Key.thumbnail.rawValue) as! String let medium = aDecoder.decodeObject(forKey: Key.medium.rawValue) as! String let large = aDecoder.decodeObject(forKey: Key.large.rawValue) as! String self.init(thumbnail: thumbnail, medium: medium, large: large) } }
mit
dd0b7cb9d12291f5f40742572ab4af60
31.955224
84
0.730072
4.337917
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/Browser/SearchViewController.swift
4
31218
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import Glean import Telemetry private enum SearchListSection: Int { case searchSuggestions case bookmarksAndHistory static let Count = 2 } private struct SearchViewControllerUX { static var SearchEngineScrollViewBackgroundColor: CGColor { return UIColor.theme.homePanel.toolbarBackground.withAlphaComponent(0.8).cgColor } static let SearchEngineScrollViewBorderColor = UIColor.black.withAlphaComponent(0.2).cgColor // TODO: This should use ToolbarHeight in BVC. Fix this when we create a shared theming file. static let EngineButtonHeight: Float = 44 static let EngineButtonWidth = EngineButtonHeight * 1.4 static let EngineButtonBackgroundColor = UIColor.clear.cgColor static let SearchImage = "search" static let SearchEngineTopBorderWidth = 0.5 static let SearchPillIconSize = 12 static var SuggestionBackgroundColor: UIColor { return UIColor.theme.homePanel.searchSuggestionPillBackground } static var SuggestionBorderColor: UIColor { return UIColor.theme.homePanel.searchSuggestionPillForeground } static let SuggestionBorderWidth: CGFloat = 1 static let SuggestionCornerRadius: CGFloat = 4 static let SuggestionInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) static let SuggestionMargin: CGFloat = 8 static let SuggestionCellVerticalPadding: CGFloat = 10 static let SuggestionCellMaxRows = 2 static let IconSize: CGFloat = 23 static let FaviconSize: CGFloat = 29 static let IconBorderColor = UIColor(white: 0, alpha: 0.1) static let IconBorderWidth: CGFloat = 0.5 } protocol SearchViewControllerDelegate: AnyObject { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) func presentSearchSettingsController() func searchViewController(_ searchViewController: SearchViewController, didHighlightText text: String, search: Bool) } class SearchViewController: SiteTableViewController, KeyboardHelperDelegate, LoaderListener { var searchDelegate: SearchViewControllerDelegate? fileprivate let isPrivate: Bool fileprivate var suggestClient: SearchSuggestClient? // Views for displaying the bottom scrollable search engine list. searchEngineScrollView is the // scrollable container; searchEngineScrollViewContent contains the actual set of search engine buttons. fileprivate let searchEngineContainerView = UIView() fileprivate let searchEngineScrollView = ButtonScrollView() fileprivate let searchEngineScrollViewContent = UIView() fileprivate lazy var bookmarkedBadge: UIImage = { return UIImage.templateImageNamed("bookmarked_passive")!.tinted(withColor: .lightGray).createScaled(CGSize(width: 16, height: 16)) }() // Cell for the suggestion flow layout. Since heightForHeaderInSection is called *before* // cellForRowAtIndexPath, we create the cell to find its height before it's added to the table. fileprivate let suggestionCell = SuggestionCell(style: .default, reuseIdentifier: nil) static var userAgent: String? init(profile: Profile, isPrivate: Bool) { self.isPrivate = isPrivate super.init(profile: profile) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.backgroundColor = UIColor.theme.homePanel.panelBackground let blur = UIVisualEffectView(effect: UIBlurEffect(style: .light)) view.addSubview(blur) super.viewDidLoad() KeyboardHelper.defaultHelper.addDelegate(self) searchEngineContainerView.layer.backgroundColor = SearchViewControllerUX.SearchEngineScrollViewBackgroundColor searchEngineContainerView.layer.shadowRadius = 0 searchEngineContainerView.layer.shadowOpacity = 100 searchEngineContainerView.layer.shadowOffset = CGSize(width: 0, height: -SearchViewControllerUX.SearchEngineTopBorderWidth) searchEngineContainerView.layer.shadowColor = SearchViewControllerUX.SearchEngineScrollViewBorderColor searchEngineContainerView.clipsToBounds = false searchEngineScrollView.decelerationRate = UIScrollView.DecelerationRate.fast searchEngineContainerView.addSubview(searchEngineScrollView) view.addSubview(searchEngineContainerView) searchEngineScrollViewContent.layer.backgroundColor = UIColor.clear.cgColor searchEngineScrollView.addSubview(searchEngineScrollViewContent) layoutTable() layoutSearchEngineScrollView() searchEngineScrollViewContent.snp.makeConstraints { make in make.center.equalTo(self.searchEngineScrollView).priority(10) //left-align the engines on iphones, center on ipad if UIScreen.main.traitCollection.horizontalSizeClass == .compact { make.left.equalTo(self.searchEngineScrollView).priority(1000) } else { make.left.greaterThanOrEqualTo(self.searchEngineScrollView).priority(1000) } make.right.lessThanOrEqualTo(self.searchEngineScrollView).priority(1000) make.top.equalTo(self.searchEngineScrollView) make.bottom.equalTo(self.searchEngineScrollView) } blur.snp.makeConstraints { make in make.edges.equalTo(self.view) } searchEngineContainerView.snp.makeConstraints { make in make.left.right.bottom.equalToSuperview() } suggestionCell.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } @objc func dynamicFontChanged(_ notification: Notification) { guard notification.name == .DynamicFontChanged else { return } reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadSearchEngines() reloadData() } fileprivate func layoutSearchEngineScrollView() { let keyboardHeight = KeyboardHelper.defaultHelper.currentState?.intersectionHeightForView(self.view) ?? 0 searchEngineScrollView.snp.remakeConstraints { make in make.left.right.top.equalToSuperview() if keyboardHeight == 0 { make.bottom.equalTo(view.safeArea.bottom) } else { make.bottom.equalTo(view).offset(-keyboardHeight) } } } var searchEngines: SearchEngines! { didSet { suggestClient?.cancelPendingRequest() // Query and reload the table with new search suggestions. querySuggestClient() // Show the default search engine first. if !isPrivate { let ua = SearchViewController.userAgent ?? "FxSearch" suggestClient = SearchSuggestClient(searchEngine: searchEngines.defaultEngine, userAgent: ua) } // Reload the footer list of search engines. reloadSearchEngines() } } fileprivate var quickSearchEngines: [OpenSearchEngine] { var engines = searchEngines.quickSearchEngines // If we're not showing search suggestions, the default search engine won't be visible // at the top of the table. Show it with the others in the bottom search bar. if isPrivate || !searchEngines.shouldShowSearchSuggestions { engines?.insert(searchEngines.defaultEngine, at: 0) } return engines! } var searchQuery: String = "" { didSet { // Reload the tableView to show the updated text in each engine. reloadData() } } override func reloadData() { querySuggestClient() } fileprivate func layoutTable() { tableView.snp.remakeConstraints { make in make.top.equalTo(self.view.snp.top) make.leading.trailing.equalTo(self.view) make.bottom.equalTo(self.searchEngineScrollView.snp.top) } } fileprivate func reloadSearchEngines() { searchEngineScrollViewContent.subviews.forEach { $0.removeFromSuperview() } var leftEdge = searchEngineScrollViewContent.snp.left //search settings icon let searchButton = UIButton() searchButton.setImage(UIImage(named: "quickSearch"), for: []) searchButton.imageView?.contentMode = .center searchButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor searchButton.addTarget(self, action: #selector(didClickSearchButton), for: .touchUpInside) searchButton.accessibilityLabel = String(format: NSLocalizedString("Search Settings", tableName: "Search", comment: "Label for search settings button.")) searchEngineScrollViewContent.addSubview(searchButton) searchButton.snp.makeConstraints { make in make.size.equalTo(SearchViewControllerUX.FaviconSize) //offset the left edge to align with search results make.left.equalTo(leftEdge).offset(SearchViewControllerUX.SuggestionMargin * 2) make.top.equalTo(self.searchEngineScrollViewContent).offset(SearchViewControllerUX.SuggestionMargin) make.bottom.equalTo(self.searchEngineScrollViewContent).offset(-SearchViewControllerUX.SuggestionMargin) } //search engines leftEdge = searchButton.snp.right for engine in quickSearchEngines { let engineButton = UIButton() engineButton.setImage(engine.image, for: []) engineButton.imageView?.contentMode = .scaleAspectFit engineButton.imageView?.layer.cornerRadius = 4 engineButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor engineButton.addTarget(self, action: #selector(didSelectEngine), for: .touchUpInside) engineButton.accessibilityLabel = String(format: NSLocalizedString("%@ search", tableName: "Search", comment: "Label for search engine buttons. The argument corresponds to the name of the search engine."), engine.shortName) engineButton.imageView?.snp.makeConstraints { make in make.width.height.equalTo(SearchViewControllerUX.FaviconSize) return } searchEngineScrollViewContent.addSubview(engineButton) engineButton.snp.makeConstraints { make in make.width.equalTo(SearchViewControllerUX.EngineButtonWidth) make.height.equalTo(SearchViewControllerUX.EngineButtonHeight) make.left.equalTo(leftEdge) make.top.equalTo(self.searchEngineScrollViewContent) make.bottom.equalTo(self.searchEngineScrollViewContent) if engine === self.searchEngines.quickSearchEngines.last { make.right.equalTo(self.searchEngineScrollViewContent) } } leftEdge = engineButton.snp.right } } @objc func didSelectEngine(_ sender: UIButton) { // The UIButtons are the same cardinality and order as the array of quick search engines. // Subtract 1 from index to account for magnifying glass accessory. guard let index = searchEngineScrollViewContent.subviews.firstIndex(of: sender) else { assertionFailure() return } let engine = quickSearchEngines[index - 1] guard let url = engine.searchURLForQuery(searchQuery) else { assertionFailure() return } Telemetry.default.recordSearch(location: .quickSearch, searchEngine: engine.engineID ?? "other") GleanMetrics.Search.counts["\(engine.engineID ?? "custom").\(SearchesMeasurement.SearchLocation.quickSearch.rawValue)"].add() searchDelegate?.searchViewController(self, didSelectURL: url) } @objc func didClickSearchButton() { self.searchDelegate?.presentSearchSettingsController() } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { animateSearchEnginesWithKeyboard(state) } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { animateSearchEnginesWithKeyboard(state) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // The height of the suggestions row may change, so call reloadData() to recalculate cell heights. coordinator.animate(alongsideTransition: { _ in self.tableView.reloadData() }, completion: nil) } fileprivate func animateSearchEnginesWithKeyboard(_ keyboardState: KeyboardState) { layoutSearchEngineScrollView() UIView.animate(withDuration: keyboardState.animationDuration, animations: { UIView.setAnimationCurve(keyboardState.animationCurve) self.view.layoutIfNeeded() }) } fileprivate func querySuggestClient() { suggestClient?.cancelPendingRequest() if searchQuery.isEmpty || !searchEngines.shouldShowSearchSuggestions || searchQuery.looksLikeAURL() { suggestionCell.suggestions = [] tableView.reloadData() return } suggestClient?.query(searchQuery, callback: { suggestions, error in if let error = error { let isSuggestClientError = error.domain == SearchSuggestClientErrorDomain switch error.code { case NSURLErrorCancelled where error.domain == NSURLErrorDomain: // Request was cancelled. Do nothing. break case SearchSuggestClientErrorInvalidEngine where isSuggestClientError: // Engine does not support search suggestions. Do nothing. break case SearchSuggestClientErrorInvalidResponse where isSuggestClientError: print("Error: Invalid search suggestion data") default: print("Error: \(error.description)") } } else { self.suggestionCell.suggestions = suggestions! } // If there are no suggestions, just use whatever the user typed. if suggestions?.isEmpty ?? true { self.suggestionCell.suggestions = [self.searchQuery] } // Reload the tableView to show the new list of search suggestions. self.tableView.reloadData() }) } func loader(dataLoaded data: Cursor<Site>) { self.data = data tableView.reloadData() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = SearchListSection(rawValue: indexPath.section)! if section == SearchListSection.bookmarksAndHistory { if let site = data[indexPath.row] { if let url = URL(string: site.url) { searchDelegate?.searchViewController(self, didSelectURL: url) TelemetryWrapper.recordEvent(category: .action, method: .open, object: .bookmark, value: .awesomebarResults) } } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let currentSection = SearchListSection(rawValue: indexPath.section) { switch currentSection { case .searchSuggestions: // heightForRowAtIndexPath is called *before* the cell is created, so to get the height, // force a layout pass first. suggestionCell.layoutIfNeeded() return suggestionCell.frame.height default: return super.tableView(tableView, heightForRowAt: indexPath) } } return 0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch SearchListSection(rawValue: indexPath.section)! { case .searchSuggestions: suggestionCell.imageView?.image = searchEngines.defaultEngine.image suggestionCell.imageView?.isAccessibilityElement = true suggestionCell.imageView?.accessibilityLabel = String(format: NSLocalizedString("Search suggestions from %@", tableName: "Search", comment: "Accessibility label for image of default search engine displayed left to the actual search suggestions from the engine. The parameter substituted for \"%@\" is the name of the search engine. E.g.: Search suggestions from Google"), searchEngines.defaultEngine.shortName) return suggestionCell case .bookmarksAndHistory: let cell = super.tableView(tableView, cellForRowAt: indexPath) if let site = data[indexPath.row] { if let cell = cell as? TwoLineTableViewCell { let isBookmark = site.bookmarked ?? false cell.setLines(site.title, detailText: site.url) cell.setRightBadge(isBookmark ? self.bookmarkedBadge : nil) cell.imageView?.layer.borderColor = SearchViewControllerUX.IconBorderColor.cgColor cell.imageView?.layer.borderWidth = SearchViewControllerUX.IconBorderWidth cell.imageView?.contentMode = .center cell.imageView?.setImageAndBackground(forIcon: site.icon, website: site.tileURL) { [weak cell] in cell?.imageView?.image = cell?.imageView?.image?.createScaled(CGSize(width: SearchViewControllerUX.IconSize, height: SearchViewControllerUX.IconSize)) } } } return cell } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch SearchListSection(rawValue: section)! { case .searchSuggestions: return searchEngines.shouldShowSearchSuggestions && !searchQuery.looksLikeAURL() && !isPrivate ? 1 : 0 case .bookmarksAndHistory: return data.count } } func numberOfSections(in tableView: UITableView) -> Int { return SearchListSection.Count } func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { guard let section = SearchListSection(rawValue: indexPath.section) else { return } if section == .bookmarksAndHistory, let suggestion = data[indexPath.item] { searchDelegate?.searchViewController(self, didHighlightText: suggestion.url, search: false) } } override func applyTheme() { super.applyTheme() reloadData() } } extension SearchViewController { func handleKeyCommands(sender: UIKeyCommand) { let initialSection = SearchListSection.bookmarksAndHistory.rawValue guard let current = tableView.indexPathForSelectedRow else { let count = tableView(tableView, numberOfRowsInSection: initialSection) if sender.input == UIKeyCommand.inputDownArrow, count > 0 { let next = IndexPath(item: 0, section: initialSection) self.tableView(tableView, didHighlightRowAt: next) tableView.selectRow(at: next, animated: false, scrollPosition: .top) } return } let nextSection: Int let nextItem: Int guard let input = sender.input else { return } switch input { case UIKeyCommand.inputUpArrow: // we're going down, we should check if we've reached the first item in this section. if current.item == 0 { // We have, so check if we can decrement the section. if current.section == initialSection { // We've reached the first item in the first section. searchDelegate?.searchViewController(self, didHighlightText: searchQuery, search: false) return } else { nextSection = current.section - 1 nextItem = tableView(tableView, numberOfRowsInSection: nextSection) - 1 } } else { nextSection = current.section nextItem = current.item - 1 } case UIKeyCommand.inputDownArrow: let currentSectionItemsCount = tableView(tableView, numberOfRowsInSection: current.section) if current.item == currentSectionItemsCount - 1 { if current.section == tableView.numberOfSections - 1 { // We've reached the last item in the last section return } else { // We can go to the next section. nextSection = current.section + 1 nextItem = 0 } } else { nextSection = current.section nextItem = current.item + 1 } default: return } guard nextItem >= 0 else { return } let next = IndexPath(item: nextItem, section: nextSection) self.tableView(tableView, didHighlightRowAt: next) tableView.selectRow(at: next, animated: false, scrollPosition: .middle) } } extension SearchViewController: SuggestionCellDelegate { fileprivate func suggestionCell(_ suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) { // Assume that only the default search engine can provide search suggestions. let engine = searchEngines.defaultEngine if let url = engine.searchURLForQuery(suggestion) { Telemetry.default.recordSearch(location: .suggestion, searchEngine: engine.engineID ?? "other") GleanMetrics.Search.counts["\(engine.engineID ?? "custom").\(SearchesMeasurement.SearchLocation.suggestion.rawValue)"].add() searchDelegate?.searchViewController(self, didSelectURL: url) } } fileprivate func suggestionCell(_ suggestionCell: SuggestionCell, didLongPressSuggestion suggestion: String) { searchDelegate?.searchViewController(self, didLongPressSuggestion: suggestion) } } /** * Private extension containing string operations specific to this view controller */ fileprivate extension String { func looksLikeAURL() -> Bool { // The assumption here is that if the user is typing in a forward slash and there are no spaces // involved, it's going to be a URL. If we type a space, any url would be invalid. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1192155 for additional details. return self.contains("/") && !self.contains(" ") } } /** * UIScrollView that prevents buttons from interfering with scroll. */ fileprivate class ButtonScrollView: UIScrollView { fileprivate override func touchesShouldCancel(in view: UIView) -> Bool { return true } } fileprivate protocol SuggestionCellDelegate: AnyObject { func suggestionCell(_ suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) func suggestionCell(_ suggestionCell: SuggestionCell, didLongPressSuggestion suggestion: String) } /** * Cell that wraps a list of search suggestion buttons. */ fileprivate class SuggestionCell: UITableViewCell { weak var delegate: SuggestionCellDelegate? let container = UIView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) isAccessibilityElement = false accessibilityLabel = nil layoutMargins = .zero separatorInset = .zero selectionStyle = .none container.backgroundColor = UIColor.clear contentView.backgroundColor = UIColor.clear backgroundColor = UIColor.clear contentView.addSubview(container) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var suggestions: [String] = [] { didSet { for view in container.subviews { view.removeFromSuperview() } for suggestion in suggestions { let button = SuggestionButton() button.setTitle(suggestion, for: []) button.addTarget(self, action: #selector(didSelectSuggestion), for: .touchUpInside) button.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(didLongPressSuggestion))) // If this is the first image, add the search icon. if container.subviews.isEmpty { let size = SearchViewControllerUX.SearchPillIconSize let image = UIImage.templateImageNamed(SearchViewControllerUX.SearchImage)?.createScaled(CGSize(width: size, height: size)).tinted(withColor: UIColor.theme.homePanel.searchSuggestionPillForeground) button.setImage(image, for: []) if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) } else { button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8) } } container.addSubview(button) } setNeedsLayout() } } @objc func didSelectSuggestion(_ sender: UIButton) { delegate?.suggestionCell(self, didSelectSuggestion: sender.titleLabel!.text!) } @objc func didLongPressSuggestion(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { if let button = recognizer.view as! UIButton? { delegate?.suggestionCell(self, didLongPressSuggestion: button.titleLabel!.text!) } } } fileprivate override func layoutSubviews() { super.layoutSubviews() // The left bounds of the suggestions, aligned with where text would be displayed. let textLeft: CGFloat = 61 // The maximum width of the container, after which suggestions will wrap to the next line. let maxWidth = contentView.frame.width let imageSize = CGFloat(SearchViewControllerUX.FaviconSize) // The height of the suggestions container (minus margins), used to determine the frame. // We set it to imageSize.height as a minimum since we don't want the cell to be shorter than the icon var height: CGFloat = imageSize var currentLeft = textLeft var currentTop = SearchViewControllerUX.SuggestionCellVerticalPadding var currentRow = 0 for view in container.subviews { let button = view as! UIButton var buttonSize = button.intrinsicContentSize // Update our base frame height by the max size of either the image or the button so we never // make the cell smaller than any of the two if height == imageSize { height = max(buttonSize.height, imageSize) } var width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin if width > maxWidth { // Only move to the next row if there's already a suggestion on this row. // Otherwise, the suggestion is too big to fit and will be resized below. if currentLeft > textLeft { currentRow += 1 if currentRow >= SearchViewControllerUX.SuggestionCellMaxRows { // Don't draw this button if it doesn't fit on the row. button.frame = .zero continue } currentLeft = textLeft currentTop += buttonSize.height + SearchViewControllerUX.SuggestionMargin height += buttonSize.height + SearchViewControllerUX.SuggestionMargin width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin } // If the suggestion is too wide to fit on its own row, shrink it. if width > maxWidth { buttonSize.width = maxWidth - currentLeft - SearchViewControllerUX.SuggestionMargin } } button.frame = CGRect(x: currentLeft, y: currentTop, width: buttonSize.width, height: buttonSize.height) currentLeft += buttonSize.width + SearchViewControllerUX.SuggestionMargin } frame.size.height = height + 2 * SearchViewControllerUX.SuggestionCellVerticalPadding contentView.frame = bounds container.frame = bounds let imageX = (textLeft - imageSize) / 2 let imageY = (frame.size.height - imageSize) / 2 imageView!.frame = CGRect(x: imageX, y: imageY, width: imageSize, height: imageSize) } } /** * Rounded search suggestion button that highlights when selected. */ fileprivate class SuggestionButton: InsetButton { override init(frame: CGRect) { super.init(frame: frame) setTitleColor(UIColor.theme.homePanel.searchSuggestionPillForeground, for: []) setTitleColor(UIColor.Photon.White100, for: .highlighted) titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont backgroundColor = SearchViewControllerUX.SuggestionBackgroundColor layer.borderColor = SearchViewControllerUX.SuggestionBorderColor.cgColor layer.borderWidth = SearchViewControllerUX.SuggestionBorderWidth layer.cornerRadius = SearchViewControllerUX.SuggestionCornerRadius contentEdgeInsets = SearchViewControllerUX.SuggestionInsets accessibilityHint = NSLocalizedString("Searches for the suggestion", comment: "Accessibility hint describing the action performed when a search suggestion is clicked") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc override var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? UIColor.theme.general.highlightBlue : SearchViewControllerUX.SuggestionBackgroundColor } } }
mpl-2.0
943787ea1b7df8a67ea2e537983b49c1
42.479109
422
0.665546
5.593621
false
false
false
false
ntian2/NTDownload
NTDownload/download/NTDownload/NTCommonHelper.swift
1
1141
// // NTCommonHelper.swift // // Created by ntian on 2017/7/12. // Copyright © 2017年 ntian. All rights reserved. // import UIKit public let NTDocumentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] open class NTCommonHelper { open class func calculateFileSize(_ contentLength: Int64) -> Float { let dataLength: Float64 = Float64(contentLength) if dataLength >= (1024.0 * 1024.0 * 1024.0) { return Float(dataLength / (1024.0 * 1024.0 * 1024.0)) } else if dataLength >= 1024.0 * 1024.0 { return Float(dataLength / (1024.0 * 1024.0)) } else if dataLength >= 1024.0 { return Float(dataLength / 1024.0) } else { return Float(dataLength) } } open class func calculateUnit(_ contentLength: Int64) -> String { if (contentLength >= (1024 * 1024 * 1024)) { return "GB" } else if contentLength >= (1024 * 1024) { return "MB" } else if contentLength >= 1024 { return "KB" } else { return "Bytes" } } }
mit
16c52dd37a5f72550fcc8153da293cda
29.756757
109
0.577329
4.093525
false
false
false
false
authme-org/authme
authme-iphone/AuthMe/AuthMeAppDelegate.swift
1
8301
/* * * Copyright 2015 Berin Lautenbach * * 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. * */ // // AppDelegate.swift // AuthMe // // Created by Berin Lautenbach on 23/02/2015. // Copyright (c) 2015 Berin Lautenbach. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AuthMeAppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Default logging Log.setLogLevel(.finest) // Setup the master password let masterPassword = MasterPassword.getInstance() // Kick off the initialisation process masterPassword.managedObjectContext = managedObjectContext return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. self.saveContext() } //MARK: Core Data lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.xxxx.ProjectName" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "AuthMe", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("AuthMe") var failureReason = "There was an error creating or loading the application's saved data." do { let options = [ NSInferMappingModelAutomaticallyOption : true, NSMigratePersistentStoresAutomaticallyOption : true] try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let b64 = Base64() let logger = Log() if let apnToken = b64.base64encode(deviceToken, length: Int32(deviceToken.count)) { logger.log(.debug, message: "Recieved token " + (apnToken as String)) let appConfiguration = AppConfiguration.getInstance() appConfiguration.setConfigItem("apnToken", value: apnToken) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { let logger = Log() logger.log(.warn, message: "Error retreiving device notification: " + error.localizedDescription) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { let logger = Log() logger.log(.debug, message: "Got a remote notification") let masterPassword = MasterPassword.getInstance() if let authController = masterPassword.authController { authController.reloadAuths() } } }
apache-2.0
74e4735961f163498804cae126e91380
48.118343
291
0.699193
5.673958
false
false
false
false
cikelengfeng/Jude
Jude/Antlr4/atn/ATNConfig.swift
2
8131
/// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// A tuple: (ATN state, predicted alt, syntactic, semantic context). /// The syntactic context is a graph-structured stack node whose /// path(s) to the root is the rule invocation(s) /// chain used to arrive at the state. The semantic context is /// the tree of semantic predicates encountered before reaching /// an ATN state. public class ATNConfig: Hashable, CustomStringConvertible { /// This field stores the bit mask for implementing the /// {@link #isPrecedenceFilterSuppressed} property as a bit within the /// existing {@link #reachesIntoOuterContext} field. private final let SUPPRESS_PRECEDENCE_FILTER: Int = 0x40000000 /// The ATN state associated with this configuration public final let state: ATNState /// What alt (or lexer rule) is predicted by this configuration public final let alt: Int /// The stack of invoking states leading to the rule/states associated /// with this config. We track only those contexts pushed during /// execution of the ATN simulator. public final var context: PredictionContext? /// We cannot execute predicates dependent upon local context unless /// we know for sure we are in the correct context. Because there is /// no way to do this efficiently, we simply cannot evaluate /// dependent predicates unless we are in the rule that initially /// invokes the ATN simulator. /// /// <p> /// closure() tracks the depth of how far we dip into the outer context: /// depth &gt; 0. Note that it may not be totally accurate depth since I /// don't ever decrement. TODO: make it a boolean then</p> /// /// <p> /// For memory efficiency, the {@link #isPrecedenceFilterSuppressed} method /// is also backed by this field. Since the field is publicly accessible, the /// highest bit which would not cause the value to become negative is used to /// store this field. This choice minimizes the risk that code which only /// compares this value to 0 would be affected by the new purpose of the /// flag. It also ensures the performance of the existing {@link org.antlr.v4.runtime.atn.ATNConfig} /// constructors as well as certain operations like /// {@link org.antlr.v4.runtime.atn.ATNConfigSet#add(org.antlr.v4.runtime.atn.ATNConfig, DoubleKeyMap)} method are /// <em>completely</em> unaffected by the change.</p> public final var reachesIntoOuterContext: Int = 0 //=0 intital by janyou public final let semanticContext: SemanticContext public init(_ old: ATNConfig) { // dup self.state = old.state self.alt = old.alt self.context = old.context self.semanticContext = old.semanticContext self.reachesIntoOuterContext = old.reachesIntoOuterContext } public convenience init(_ state: ATNState, _ alt: Int, _ context: PredictionContext?) { self.init(state, alt, context, SemanticContext.NONE) } public init(_ state: ATNState, _ alt: Int, _ context: PredictionContext?, _ semanticContext: SemanticContext) { self.state = state self.alt = alt self.context = context self.semanticContext = semanticContext } public convenience init(_ c: ATNConfig, _ state: ATNState) { self.init(c, state, c.context, c.semanticContext) } public convenience init(_ c: ATNConfig, _ state: ATNState, _ semanticContext: SemanticContext) { self.init(c, state, c.context, semanticContext) } public convenience init(_ c: ATNConfig, _ semanticContext: SemanticContext) { self.init(c, c.state, c.context, semanticContext) } public convenience init(_ c: ATNConfig, _ state: ATNState, _ context: PredictionContext?) { self.init(c, state, context, c.semanticContext) } public init(_ c: ATNConfig, _ state: ATNState, _ context: PredictionContext?, _ semanticContext: SemanticContext) { self.state = state self.alt = c.alt self.context = context self.semanticContext = semanticContext self.reachesIntoOuterContext = c.reachesIntoOuterContext } /// This method gets the value of the {@link #reachesIntoOuterContext} field /// as it existed prior to the introduction of the /// {@link #isPrecedenceFilterSuppressed} method. public final func getOuterContextDepth() -> Int { return reachesIntoOuterContext & ~SUPPRESS_PRECEDENCE_FILTER } public final func isPrecedenceFilterSuppressed() -> Bool { return (reachesIntoOuterContext & SUPPRESS_PRECEDENCE_FILTER) != 0 } public final func setPrecedenceFilterSuppressed(_ value: Bool) { if value { self.reachesIntoOuterContext |= 0x40000000 } else { self.reachesIntoOuterContext &= ~SUPPRESS_PRECEDENCE_FILTER } } /// An ATN configuration is equal to another if both have /// the same state, they predict the same alternative, and /// syntactic/semantic contexts are the same. public var hashValue: Int { var hashCode: Int = MurmurHash.initialize(7) hashCode = MurmurHash.update(hashCode, state.stateNumber) hashCode = MurmurHash.update(hashCode, alt) hashCode = MurmurHash.update(hashCode, context) hashCode = MurmurHash.update(hashCode, semanticContext) hashCode = MurmurHash.finish(hashCode, 4) return hashCode } public func toString() -> String { return description } public var description: String { //return "MyClass \(string)" return toString(nil, true) } public func toString<T:ATNSimulator>(_ recog: Recognizer<T>?, _ showAlt: Bool) -> String { let buf: StringBuilder = StringBuilder() // if ( state.ruleIndex>=0 ) { // if ( recog!=null ) buf.append(recog.getRuleNames()[state.ruleIndex]+":"); // else buf.append(state.ruleIndex+":"); // } buf.append("(") buf.append(state) if showAlt { buf.append(",") buf.append(alt) } //TODO: context can be nil ? if context != nil { buf.append(",[") buf.append(context!) buf.append("]") } //TODO: semanticContext can be nil ? //if ( semanticContext != nil && semanticContext != SemanticContext.NONE ) { if semanticContext != SemanticContext.NONE { buf.append(",") buf.append(semanticContext) } if getOuterContextDepth() > 0 { buf.append(",up=").append(getOuterContextDepth()) } buf.append(")") return buf.toString() } } public func ==(lhs: ATNConfig, rhs: ATNConfig) -> Bool { if lhs === rhs { return true } //TODO : rhs nil? /// else { if (other == nil) { /// return false; /// } if (lhs is LexerATNConfig) && (rhs is LexerATNConfig) { return (lhs as! LexerATNConfig) == (rhs as! LexerATNConfig) } if lhs.state.stateNumber != rhs.state.stateNumber { return false } if lhs.alt != rhs.alt { return false } if lhs.isPrecedenceFilterSuppressed() != rhs.isPrecedenceFilterSuppressed() { return false } var contextCompare = false if lhs.context == nil && rhs.context == nil { contextCompare = true } else if lhs.context == nil && rhs.context != nil { contextCompare = false } else if lhs.context != nil && rhs.context == nil { contextCompare = false } else { contextCompare = (lhs.context! == rhs.context!) } if !contextCompare { return false } return lhs.semanticContext == rhs.semanticContext }
mit
b997f92cc35a1d679758704768f81c96
34.662281
118
0.62932
4.542458
false
true
false
false
juanm95/Soundwich
Quaggify/Alert.swift
2
777
// // Alert.swift // Quaggify // // Created by Jonathan Bijos on 02/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import Foundation import UIKit class Alert: NSObject { static let shared = Alert() private override init () {} var isShown = false func show(title: String, message: String, completion: (() -> Void)? = nil) { if isShown == true { return } isShown = true let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in self?.isShown = false completion?() }) UIApplication.topViewController()?.present(alertController, animated: true, completion: nil) } }
mit
33f949d61bf05e4bca94b933af5d7280
23.25
99
0.657216
4.194595
false
false
false
false
cuappdev/podcast-ios
Recast/iTunesPodcasts/Models/RSS/mapAttributes.swift
1
6264
// // RSSFeed + mapAttributes.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length extension Podcast { /// Maps the attributes of the specified dictionary for a given `RSSPath` /// to the `Podcast` model, /// /// - Parameters: /// - attributes: The attribute dictionary to map to the model. /// - path: The path of feed's element. func map(_ attributes: [String: String], for path: RSSPath) { switch path { case .rssChannelItem: let episode = Episode(context: AppDelegate.appDelegate.dataController.managedObjectContext) var items = self.items?.array items?.append(episode) setValue(NSOrderedSet(array: items ?? []), for: .items) case .rssChannelImage: break case .rssChannelSkipDays: if self.rawSkipDays == nil { setValue([String](), for: .rawSkipDays) } case .rssChannelSkipHours: if self.skipHours == nil { setValue([Int64](), for: .skipHours) } case .rssChannelTextInput: if self.textInput == nil { let textInput = TextInput(context: AppDelegate.appDelegate.dataController.managedObjectContext) setValue(textInput, for: .textInput) } case .rssChannelCategory: if self.categories == nil { setValue([String](), for: .categories) } case .rssChannelItemCategory: let items = self.items?.array as? [Episode] if items?.last?.categories == nil { items?.last?.setValue([String](), for: .categories) } case .rssChannelItemEnclosure: let items = self.items?.array as? [Episode] if items?.last?.enclosure == nil { let enclosure = Enclosure(from: attributes) items?.last?.setValue(enclosure, for: .enclosure) } case .rssChannelItemGUID: break case .rssChannelItemSource: let items = self.items?.array as? [Episode] if items?.last?.source == nil { let itemSource = ItemSource(attributes: attributes) items?.last?.setValue(itemSource, for: .source) } case .rssChannelItemContentEncoded: break case .rssChannelItunesAuthor, .rssChannelItunesBlock, .rssChannelItunesCategory, .rssChannelItunesSubcategory, .rssChannelItunesImage, .rssChannelItunesExplicit, .rssChannelItunesComplete, .rssChannelItunesNewFeedURL, .rssChannelItunesOwner, .rssChannelItunesOwnerName, .rssChannelItunesOwnerEmail, .rssChannelItunesSubtitle, .rssChannelItunesSummary, .rssChannelItunesKeywords, .rssChannelItunesType: if self.iTunes == nil { self.iTunes = ITunesNamespace(context: AppDelegate.appDelegate.dataController.managedObjectContext) } switch path { case .rssChannelItunesCategory: if self.iTunes?.categories == nil { self.iTunes?.setValue([ITunesCategory](), for: .categories) } var categories = self.iTunes?.categories categories?.append(ITunesCategory(attributes: attributes)) self.iTunes?.setValue(categories, for: .categories) case .rssChannelItunesSubcategory: self.iTunes?.categories?.last?.setValue(attributes["text"], for: .subcategory) case .rssChannelItunesImage: self.iTunes?.setValue(NSURL(string: attributes["href"] ?? ""), for: .image) case .rssChannelItunesOwner: if self.iTunes?.owner == nil { self.iTunes?.owner = ITunesOwner(context: AppDelegate.appDelegate.dataController.managedObjectContext) } default: break } case .rssChannelItemItunesAuthor, .rssChannelItemItunesBlock, .rssChannelItemItunesDuration, .rssChannelItemItunesImage, .rssChannelItemItunesExplicit, .rssChannelItemItunesIsClosedCaptioned, .rssChannelItemItunesOrder, .rssChannelItemItunesSubtitle, .rssChannelItemItunesSummary, .rssChannelItemItunesKeywords: let items = self.items?.array as? [Episode] if items?.last?.iTunes == nil { items?.last?.iTunes = ITunesNamespace(context: AppDelegate.appDelegate.dataController.managedObjectContext) } switch path { case .rssChannelItemItunesImage: let items = self.items?.array as? [Episode] items?.last?.iTunes?.setValue(NSURL(string: attributes["href"] ?? ""), for: .image) default: break } default: break } } }
mit
7e6f2eed8dfd9c1e33fda8482bd1506a
33.229508
123
0.609834
4.829607
false
false
false
false
Molbie/Outlaw-SpriteKit
Sources/OutlawSpriteKit/Nodes/Display/SKCropNode+Outlaw.swift
1
1285
// // SKCropNode+Outlaw.swift // OutlawSpriteKit // // Created by Brian Mullen on 12/16/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import SpriteKit import Outlaw import OutlawCoreGraphics import OutlawAppKit import OutlawUIKit // NOTE: Swift doesn't allow methods to be overriden // within extensions, so we are defining // explicit methods for each SKNode subclass public extension SKCropNode { struct CropNodeExtractableKeys { public static let maskNode = "maskNode" } private typealias keys = SKCropNode.CropNodeExtractableKeys } public extension SKCropNode { /* Serializable */ func serializedCropNode(withChildren: Bool) -> [String: Any] { var result = self.serializedNode(withChildren: withChildren) if let maskNode = self.maskNode { result[keys.maskNode] = maskNode.serialized() } return result } } public extension SKCropNode { /* Updatable */ func updateCropNode(with object: Extractable) throws { try self.updateNode(with: object) if let maskNode: [String: Any] = object.optional(for: keys.maskNode) { // TODO: create one if it doesn't already exist try self.maskNode?.update(with: maskNode) } } }
mit
a6712c2c72722c73217d71615c7a0c4c
26.913043
78
0.675234
4.07619
false
false
false
false
gifsy/Gifsy
Frameworks/Bond/Bond/Extensions/iOS/UICollectionView+Bond.swift
10
9030
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 UIKit @objc public protocol BNDCollectionViewProxyDataSource { optional func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView optional func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool optional func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) } private class BNDCollectionViewDataSource<T>: NSObject, UICollectionViewDataSource { private let array: ObservableArray<ObservableArray<T>> private weak var collectionView: UICollectionView! private let createCell: (NSIndexPath, ObservableArray<ObservableArray<T>>, UICollectionView) -> UICollectionViewCell private weak var proxyDataSource: BNDCollectionViewProxyDataSource? private let sectionObservingDisposeBag = DisposeBag() private init(array: ObservableArray<ObservableArray<T>>, collectionView: UICollectionView, proxyDataSource: BNDCollectionViewProxyDataSource?, createCell: (NSIndexPath, ObservableArray<ObservableArray<T>>, UICollectionView) -> UICollectionViewCell) { self.collectionView = collectionView self.createCell = createCell self.proxyDataSource = proxyDataSource self.array = array super.init() collectionView.dataSource = self collectionView.reloadData() setupPerSectionObservers() array.observeNew { [weak self] arrayEvent in guard let unwrappedSelf = self, let collectionView = unwrappedSelf.collectionView else { return } switch arrayEvent.operation { case .Batch(let operations): collectionView.performBatchUpdates({ for operation in changeSetsFromBatchOperations(operations) { BNDCollectionViewDataSource.applySectionUnitChangeSet(operation, collectionView: collectionView) } }, completion: nil) case .Reset: collectionView.reloadData() default: BNDCollectionViewDataSource.applySectionUnitChangeSet(arrayEvent.operation.changeSet(), collectionView: collectionView) } unwrappedSelf.setupPerSectionObservers() }.disposeIn(bnd_bag) } private func setupPerSectionObservers() { sectionObservingDisposeBag.dispose() for (sectionIndex, sectionObservableArray) in array.enumerate() { sectionObservableArray.observeNew { [weak collectionView] arrayEvent in guard let collectionView = collectionView else { return } switch arrayEvent.operation { case .Batch(let operations): collectionView.performBatchUpdates({ for operation in changeSetsFromBatchOperations(operations) { BNDCollectionViewDataSource.applyRowUnitChangeSet(operation, collectionView: collectionView, sectionIndex: sectionIndex) } }, completion: nil) case .Reset: collectionView.reloadSections(NSIndexSet(index: sectionIndex)) default: BNDCollectionViewDataSource.applyRowUnitChangeSet(arrayEvent.operation.changeSet(), collectionView: collectionView, sectionIndex: sectionIndex) } }.disposeIn(sectionObservingDisposeBag) } } private class func applySectionUnitChangeSet(changeSet: ObservableArrayEventChangeSet, collectionView: UICollectionView) { switch changeSet { case .Inserts(let indices): collectionView.insertSections(NSIndexSet(set: indices)) case .Updates(let indices): collectionView.reloadSections(NSIndexSet(set: indices)) case .Deletes(let indices): collectionView.deleteSections(NSIndexSet(set: indices)) } } private class func applyRowUnitChangeSet(changeSet: ObservableArrayEventChangeSet, collectionView: UICollectionView, sectionIndex: Int) { switch changeSet { case .Inserts(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } collectionView.insertItemsAtIndexPaths(indexPaths) case .Updates(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } collectionView.reloadItemsAtIndexPaths(indexPaths) case .Deletes(let indices): let indexPaths = indices.map { NSIndexPath(forItem: $0, inSection: sectionIndex) } collectionView.deleteItemsAtIndexPaths(indexPaths) } } /// MARK - UICollectionViewDataSource @objc func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return array.count } @objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return array[section].count } @objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return createCell(indexPath, array, collectionView) } @objc func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if let view = proxyDataSource?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) { return view } else { fatalError("Dear Sir/Madam, your collection view has asked for a supplementary view of a \(kind) kind. Please provide a proxy data source object in bindTo() method that implements `collectionView(collectionView:viewForSupplementaryElementOfKind:atIndexPath)` method!") } } @objc func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool { return proxyDataSource?.collectionView?(collectionView, canMoveItemAtIndexPath: indexPath) ?? false } @objc func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { proxyDataSource?.collectionView?(collectionView, moveItemAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } extension UICollectionView { private struct AssociatedKeys { static var BondDataSourceKey = "bnd_BondDataSourceKey" } } public extension EventProducerType where EventType: ObservableArrayEventType, EventType.ObservableArrayEventSequenceType.Generator.Element: EventProducerType, EventType.ObservableArrayEventSequenceType.Generator.Element.EventType: ObservableArrayEventType { private typealias ElementType = EventType.ObservableArrayEventSequenceType.Generator.Element.EventType.ObservableArrayEventSequenceType.Generator.Element public func bindTo(collectionView: UICollectionView, proxyDataSource: BNDCollectionViewProxyDataSource? = nil, createCell: (NSIndexPath, ObservableArray<ObservableArray<ElementType>>, UICollectionView) -> UICollectionViewCell) -> DisposableType { let array: ObservableArray<ObservableArray<ElementType>> if let downcastedObservableArray = self as? ObservableArray<ObservableArray<ElementType>> { array = downcastedObservableArray } else { array = self.map { $0.crystallize() }.crystallize() } let dataSource = BNDCollectionViewDataSource(array: array, collectionView: collectionView, proxyDataSource: proxyDataSource, createCell: createCell) collectionView.dataSource = dataSource objc_setAssociatedObject(collectionView, UICollectionView.AssociatedKeys.BondDataSourceKey, dataSource, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return BlockDisposable { [weak collectionView] in if let collectionView = collectionView { objc_setAssociatedObject(collectionView, UICollectionView.AssociatedKeys.BondDataSourceKey, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
apache-2.0
1ece8fd1b3c962e52f103c7b5a16c458
48.615385
274
0.768328
5.657895
false
false
false
false
soundq/SoundQ-iOS
SoundQ/Queue.swift
1
1142
// // Queue.swift // SoundQ // // Created by Nishil Shah on 5/22/16. // Copyright © 2016 Nishil Shah. All rights reserved. // import Foundation import Soundcloud import Alamofire import AlamofireImage struct Queue { var title: String var identifier: String var owner: Int var tracks: [Track] = [] var coverArt: UIImage? init(title: String, identifier: String) { self.init(title: title, identifier: identifier, owner: 0) } init(title: String, identifier: String, owner: Int) { self.title = title self.identifier = identifier self.owner = owner } mutating func setCoverArtWithPath(path: String) { if path.characters.count < 1 { setUnknownCoverArt() } Alamofire.request(.GET, path).responseImage { response in if let image = response.result.value { self.coverArt = image } else { self.setUnknownCoverArt() } } } mutating func setUnknownCoverArt() { self.coverArt = UIImage(named: "unknown_cover_art") } }
apache-2.0
825084518b8c91949611282b50c71223
22.306122
65
0.587204
4.134058
false
false
false
false
spire-inc/Bond
Sources/UIKit/UICollectionView.swift
6
5887
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 UIKit import ReactiveKit public protocol CollectionViewBond { associatedtype DataSource: DataSourceProtocol func cellForRow(at indexPath: IndexPath, collectionView: UICollectionView, dataSource: DataSource) -> UICollectionViewCell } private struct SimpleCollectionViewBond<DataSource: DataSourceProtocol>: CollectionViewBond { let createCell: (DataSource, IndexPath, UICollectionView) -> UICollectionViewCell func cellForRow(at indexPath: IndexPath, collectionView: UICollectionView, dataSource: DataSource) -> UICollectionViewCell { return createCell(dataSource, indexPath, collectionView) } } public extension UICollectionView { public var bnd_delegate: ProtocolProxy { return protocolProxy(for: UICollectionViewDelegate.self, setter: NSSelectorFromString("setDelegate:")) } public var bnd_dataSource: ProtocolProxy { return protocolProxy(for: UICollectionViewDataSource.self, setter: NSSelectorFromString("setDataSource:")) } } public extension SignalProtocol where Element: DataSourceEventProtocol, Error == NoError { @discardableResult public func bind(to collectionView: UICollectionView, createCell: @escaping (DataSource, IndexPath, UICollectionView) -> UICollectionViewCell) -> Disposable { return bind(to: collectionView, using: SimpleCollectionViewBond<DataSource>(createCell: createCell)) } @discardableResult public func bind<B: CollectionViewBond>(to collectionView: UICollectionView, using bond: B) -> Disposable where B.DataSource == DataSource { let dataSource = Property<DataSource?>(nil) collectionView.bnd_dataSource.feed( property: dataSource, to: #selector(UICollectionViewDataSource.collectionView(_:cellForItemAt:)), map: { (dataSource: DataSource?, collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell in return bond.cellForRow(at: indexPath as IndexPath, collectionView: collectionView, dataSource: dataSource!) }) collectionView.bnd_dataSource.feed( property: dataSource, to: #selector(UICollectionViewDataSource.collectionView(_:numberOfItemsInSection:)), map: { (dataSource: DataSource?, _: UICollectionView, section: Int) -> Int in dataSource?.numberOfItems(inSection: section) ?? 0 } ) collectionView.bnd_dataSource.feed( property: dataSource, to: #selector(UICollectionViewDataSource.numberOfSections(in:)), map: { (dataSource: DataSource?, _: UICollectionView) -> Int in dataSource?.numberOfSections ?? 0 } ) let serialDisposable = SerialDisposable(otherDisposable: nil) var bufferedEvents: [DataSourceEventKind]? = nil serialDisposable.otherDisposable = observeIn(ImmediateOnMainExecutionContext).observeNext { [weak collectionView] event in guard let collectionView = collectionView else { serialDisposable.dispose() return } dataSource.value = event.dataSource let applyEventOfKind: (DataSourceEventKind) -> () = { kind in switch kind { case .reload: collectionView.reloadData() case .insertItems(let indexPaths): collectionView.insertItems(at: indexPaths) case .deleteItems(let indexPaths): collectionView.deleteItems(at: indexPaths) case .reloadItems(let indexPaths): collectionView.reloadItems(at: indexPaths) case .moveItem(let indexPath, let newIndexPath): collectionView.moveItem(at: indexPath, to: newIndexPath) case .insertSections(let indexSet): collectionView.insertSections(indexSet) case .deleteSections(let indexSet): collectionView.deleteSections(indexSet) case .reloadSections(let indexSet): collectionView.reloadSections(indexSet) case .moveSection(let index, let newIndex): collectionView.moveSection(index, toSection: newIndex) case .beginUpdates: fatalError() case .endUpdates: fatalError() } } switch event.kind { case .reload: collectionView.reloadData() case .beginUpdates: bufferedEvents = [] case .endUpdates: if let bufferedEvents = bufferedEvents { collectionView.performBatchUpdates({ bufferedEvents.forEach(applyEventOfKind) }, completion: nil) } else { fatalError("Bond: Unexpected event .endUpdates. Should have been preceded by a .beginUpdates event.") } bufferedEvents = nil default: if bufferedEvents != nil { bufferedEvents!.append(event.kind) } else { applyEventOfKind(event.kind) } } } return serialDisposable } }
mit
094ae6eaa12d4def4a52185f45f934e0
39.6
160
0.718193
5.260947
false
false
false
false