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
benlangmuir/swift
test/expr/primary/selector/property.swift
22
10482
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -typecheck -primary-file %s %S/Inputs/property_helper.swift -verify -swift-version 4 import ObjectiveC // REQUIRES: objc_interop @objc class HelperClass: NSObject {} struct Wrapper { var objcInstance = ObjCClass() } class ObjCClass { @objc var myProperty = HelperClass() @objc let myConstant = HelperClass() // expected-note 4{{'myConstant' declared here}} @objc var myComputedReadOnlyProperty: HelperClass { // expected-note 2{{'myComputedReadOnlyProperty' declared here}} get { return HelperClass() } } @objc var myComputedReadWriteProperty: HelperClass { get { return HelperClass() } set { } } @objc func myFunc() {} @objc class func myClassFunc() {} func instanceMethod() { let _ = #selector(myFunc) let _ = #selector(getter: myProperty) let _ = #selector(setter: myProperty) let _ = #selector(setter: myComputedReadWriteProperty) let _ = #selector(setter: myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myConstant'}} let _ = #selector(setter: myComputedReadOnlyProperty) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myComputedReadOnlyProperty'}} let _ = #selector(myClassFunc) // expected-error{{static member 'myClassFunc' cannot be used on instance of type 'ObjCClass'}} } class func classMethod() { let _ = #selector(myFunc) let _ = #selector(getter: myProperty) let _ = #selector(setter: myProperty) let _ = #selector(setter: myComputedReadWriteProperty) let _ = #selector(setter: myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myConstant'}} let _ = #selector(setter: myComputedReadOnlyProperty) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myComputedReadOnlyProperty'}} let _ = #selector(myClassFunc) } } let myObjcInstance = ObjCClass() let myWrapperInstance = Wrapper() func testSimple(myObjcInstance: ObjCClass, myWrapperInstance: Wrapper) { // Check cases that should work let _ = #selector(ObjCClass.myFunc) let _ = #selector(getter: ObjCClass.myProperty) let _ = #selector(setter: ObjCClass.myProperty) let _ = #selector(myObjcInstance.myFunc) let _ = #selector(getter: myObjcInstance.myProperty) let _ = #selector(setter: myObjcInstance.myProperty) let _ = #selector(myWrapperInstance.objcInstance.myFunc) let _ = #selector(getter: myWrapperInstance.objcInstance.myProperty) let _ = #selector(setter: myWrapperInstance.objcInstance.myProperty) } func testWrongKind(myObjcInstance: ObjCClass, myWrapperInstance: Wrapper) { // Referring to a property with a method selector or a method with a // property selector let _ = #selector(myObjcInstance.myProperty) // expected-error{{use 'getter:' or 'setter:' to refer to the Objective-C getter or setter of property 'myProperty', respectively}} // expected-note@-1{{add 'getter:' to reference the Objective-C getter for 'myProperty'}}{{21-21=getter: }} // expected-note@-2{{add 'setter:' to reference the Objective-C setter for 'myProperty'}}{{21-21=setter: }} let _ = #selector(myObjcInstance.myComputedReadOnlyProperty) // expected-error{{use 'getter:' to refer to the Objective-C getter of property 'myComputedReadOnlyProperty'}}{{21-21=getter: }} let _ = #selector(ObjCClass.myProperty) // expected-error{{use 'getter:' or 'setter:' to refer to the Objective-C getter or setter of property 'myProperty', respectively}} // expected-note@-1{{add 'setter:' to reference the Objective-C setter for 'myProperty'}}{{21-21=setter: }} // expected-note@-2{{add 'getter:' to reference the Objective-C getter for 'myProperty'}}{{21-21=getter: }} // Referring to a method with a property selector let _ = #selector(getter: myObjcInstance.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'getter:'}} {{21-29=}} let _ = #selector(setter: myObjcInstance.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'setter:'}} {{21-29=}} let _ = #selector(getter: ObjCClass.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'getter:'}} {{21-29=}} let _ = #selector(setter: ObjCClass.myFunc) // expected-error{{cannot reference instance method 'myFunc()' as a property; remove 'setter:'}} {{21-29=}} // Referring to a let property with a setter let _ = #selector(setter: myObjcInstance.myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myConstant'}} let _ = #selector(setter: ObjCClass.myConstant) // expected-error {{argument of '#selector(setter:)' refers to non-settable property 'myConstant'}} } // Referring to non ObjC members class NonObjCClass { var nonObjCPropertyForGetter = HelperClass() // expected-note{{add '@objc' to expose this property to Objective-C}} {{3-3=@objc }} var nonObjCPropertyForSetter = HelperClass() // expected-note{{add '@objc' to expose this property to Objective-C}} {{3-3=@objc }} } func testNonObjCMembers(nonObjCInstance: NonObjCClass) { let _ = #selector(getter: nonObjCInstance.nonObjCPropertyForGetter) // expected-error{{argument of '#selector' refers to property 'nonObjCPropertyForGetter' that is not exposed to Objective-C}} let _ = #selector(setter: nonObjCInstance.nonObjCPropertyForSetter) // expected-error{{argument of '#selector' refers to property 'nonObjCPropertyForSetter' that is not exposed to Objective-C}} // Referencing undefined symbols let _ = #selector(getter: UndefinedClass.myVariable) // expected-error{{cannot find 'UndefinedClass' in scope}} let _ = #selector(getter: ObjCClass.undefinedProperty) // expected-error{{type 'ObjCClass' has no member 'undefinedProperty'}} let _ = #selector(getter: myObjcInstance.undefinedProperty) // expected-error{{value of type 'ObjCClass' has no member 'undefinedProperty'}} } // Ambiguous expressions func testAmbiguous(myObjcInstance: ObjCClass) { // expected-note{{'myObjcInstance' declared here}} // Referring to a properties not within a type. let myOtherObjcInstance = ObjCClass(); // expected-note{{'myOtherObjcInstance' declared here}} let _ = #selector(getter: myObjcInstance) // expected-error{{argument of '#selector' cannot refer to parameter 'myObjcInstance'}} let _ = #selector(getter: myOtherObjcInstance) // expected-error{{argument of '#selector' cannot refer to variable 'myOtherObjcInstance'}} } // Getter/setter is no keyword let getter = HelperClass() let setter = HelperClass() // Referencing methods named getter and setter class ObjCClassWithGetterSetter: NSObject { @objc func getter() { } @objc func setter() { } func referenceGetterSetter() { let _ = #selector(getter) let _ = #selector(setter) } } // Looking up inherited members class BaseClass: NSObject { @objc var myVar = 1 @objc func myFunc() { } } class SubClass: BaseClass { } func testInherited() { let _ = #selector(getter: SubClass.myVar) let _ = #selector(SubClass.myFunc) let subInstance = SubClass() let _ = #selector(getter: subInstance.myVar) let _ = #selector(subInstance.myFunc) } // Looking up instance/static methods on instance/static contexts class InstanceStaticTestClass { @objc static let staticProperty = HelperClass() @objc let instanceProperty = HelperClass() @objc class func classMethod() {} @objc static func staticMethod() {} @objc func instanceMethod() {} @objc func instanceAndStaticMethod() {} @objc class func instanceAndStaticMethod() {} class func testClass() { let _ = #selector(getter: instanceProperty) let _ = #selector(instanceMethod) let _ = #selector(classMethod) let _ = #selector(staticMethod) let _ = #selector(getter: staticProperty) let _ = #selector(instanceAndStaticMethod) } static func testStatic() { let _ = #selector(getter: instanceProperty) let _ = #selector(getter: staticProperty) let _ = #selector(instanceMethod) let _ = #selector(classMethod) let _ = #selector(staticMethod) let _ = #selector(instanceAndStaticMethod) } func testInstance() { let _ = #selector(getter: instanceProperty) let _ = #selector(instanceMethod) let _ = #selector(getter: staticProperty) // expected-error{{static member 'staticProperty' cannot be used on instance of type 'InstanceStaticTestClass'}} let _ = #selector(classMethod) // expected-error{{static member 'classMethod' cannot be used on instance of type 'InstanceStaticTestClass'}} let _ = #selector(staticMethod) // expected-error{{static member 'staticMethod' cannot be used on instance of type 'InstanceStaticTestClass'}} let _ = #selector(instanceAndStaticMethod) } } // Accessibility let otherObjCInstance = OtherObjCClass() let v11 = #selector(getter: OtherObjCClass.privateVar) // expected-error{{'privateVar' is inaccessible due to 'private' protection level}} let v12 = #selector(setter: OtherObjCClass.privateVar) // expected-error{{'privateVar' is inaccessible due to 'private' protection level}} let v13 = #selector(getter: otherObjCInstance.privateVar) // expected-error{{}} let v14 = #selector(setter: otherObjCInstance.privateVar) // expected-error{{privateVar' is inaccessible due to 'private' protection level}} let v21 = #selector(getter: OtherObjCClass.privateSetVar) let v22 = #selector(setter: OtherObjCClass.privateSetVar) // expected-error{{setter of property 'privateSetVar' is inaccessible}} let v23 = #selector(getter: otherObjCInstance.privateSetVar) let v24 = #selector(setter: otherObjCInstance.privateSetVar) // expected-error{{setter of property 'privateSetVar' is inaccessible}} let v31 = #selector(getter: OtherObjCClass.internalVar) let v32 = #selector(setter: OtherObjCClass.internalVar) let v33 = #selector(getter: otherObjCInstance.internalVar) let v34 = #selector(setter: otherObjCInstance.internalVar) let v41 = #selector(OtherObjCClass.internalFunc) let v42 = #selector(otherObjCInstance.internalFunc) let v51 = #selector(OtherObjCClass.privateFunc) // expected-error{{'privateFunc' is inaccessible due to 'private' protection level}} let v52 = #selector(otherObjCInstance.privateFunc) // expected-error{{'privateFunc' is inaccessible due to 'private' protection level}}
apache-2.0
fa131596ceaa217e54de6526928f6537
43.227848
195
0.729632
4.025346
false
true
false
false
Luissoo/Transporter
Transporter/TPExtensions.swift
6
1314
// // TPExtensions.swift // Example // // Created by Le VanNghia on 3/26/15. // Copyright (c) 2015 Le VanNghia. All rights reserved. // import UIKit extension UIDevice { private class var osVersion: String { return UIDevice.currentDevice().systemVersion } class func systemVersionEqualTo(version: String) -> Bool { return osVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedSame } class func systemVersionGreaterThan(version: String) -> Bool { return osVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedDescending } class func systemVersionGreaterThanOrEqualTo(version: String) -> Bool { return osVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending } class func systemVersionLessThan(version: String) -> Bool { return osVersion.compare(version, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending } class func systemVersionLessThanOrEqualTo(version: String) -> Bool { return osVersion.compare(version, options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedDescending } }
mit
8d8190b623a837d74ca2005f24ddec4b
36.571429
128
0.737443
5.363265
false
false
false
false
malaonline/iOS
mala-ios/View/Profile/ProfileItemCollectionView.swift
1
2429
// // ProfileItemCollectionView.swift // mala-ios // // Created by 王新宇 on 16/6/13. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit private let ProfileItemCollectionViewCellReuseId = "ProfileItemCollectionViewCellReuseId" class ProfileItemCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource { // MARK: - Property var model: [ProfileElementModel]? { didSet { self.reloadData() } } // MARK: - Instance Method override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) configure() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func configure() { delegate = self dataSource = self backgroundColor = UIColor.white bounces = false isScrollEnabled = false register(ProfileItemCollectionViewCell.self, forCellWithReuseIdentifier: ProfileItemCollectionViewCellReuseId) } // MARK: - DataSource func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 所有操作结束弹栈时,取消选中项 defer { collectionView.deselectItem(at: indexPath, animated: true) } if let model = model?[indexPath.row] { NotificationCenter.default.post(name: MalaNotification_PushProfileItemController, object: model) } } func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } // MARK: - DataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return model?.count ?? 3 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileItemCollectionViewCellReuseId, for: indexPath) as! ProfileItemCollectionViewCell cell.model = model?[indexPath.row] return cell } }
mit
75c1a793fa094edc53a991d18028860c
30.447368
162
0.67364
5.506912
false
false
false
false
bitjammer/swift
test/ClangImporter/objc_bridging.swift
24
1746
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -verify %s // REQUIRES: objc_interop import Foundation import objc_structs extension String { func onlyOnString() -> String { return self } } extension Bool { func onlyOnBool() -> Bool { return self } } extension Array { func onlyOnArray() { } } extension Dictionary { func onlyOnDictionary() { } } extension Set { func onlyOnSet() { } } func foo() { _ = NSStringToNSString as (String!) -> String? _ = DummyClass().nsstringProperty.onlyOnString() as String _ = BOOLtoBOOL as (Bool) -> Bool _ = DummyClass().boolProperty.onlyOnBool() as Bool _ = arrayToArray as (Array<Any>!) -> (Array<Any>!) DummyClass().arrayProperty.onlyOnArray() _ = dictToDict as (Dictionary<AnyHashable, Any>!) -> Dictionary<AnyHashable, Any>! DummyClass().dictProperty.onlyOnDictionary() _ = setToSet as (Set<AnyHashable>!) -> Set<AnyHashable>! DummyClass().setProperty.onlyOnSet() } func allocateMagic(_ zone: NSZone) -> UnsafeMutableRawPointer { return allocate(zone) } func constPointerToObjC(_ objects: [AnyObject]) -> NSArray { return NSArray(objects: objects, count: objects.count) } func mutablePointerToObjC(_ path: String) throws -> NSString { return try NSString(contentsOfFile: path) } func objcStructs(_ s: StructOfNSStrings, sb: StructOfBlocks) { // Struct fields must not be bridged. _ = s.nsstr! as Bool // expected-error {{cannot convert value of type 'Unmanaged<NSString>' to type 'Bool' in coercion}} // FIXME: Blocks should also be Unmanaged. _ = sb.block as Bool // expected-error {{cannot convert value of type '@convention(block) () -> Void' to type 'Bool' in coercion}} sb.block() // okay }
apache-2.0
77b6ccefabc0226fb6ac054d0ad3d76a
25.861538
132
0.696449
3.707006
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Settings/SettingsCell.swift
1
15915
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireCommonComponents enum SettingsCellPreview { case none case text(String) case badge(Int) case image(UIImage) case color(UIColor) } protocol SettingsCellType: AnyObject { var titleText: String {get set} var preview: SettingsCellPreview {get set} var descriptor: SettingsCellDescriptorType? {get set} var icon: StyleKitIcon? {get set} } typealias SettingsTableCellProtocol = UITableViewCell & SettingsCellType class SettingsTableCell: SettingsTableCellProtocol { private let iconImageView: UIImageView = { let iconImageView = UIImageView() iconImageView.contentMode = .center iconImageView.tintColor = SemanticColors.Label.textDefault return iconImageView }() let cellNameLabel: UILabel = { let label = DynamicFontLabel( fontSpec: .normalSemiboldFont, color: .textForeground) label.textColor = SemanticColors.Label.textDefault label.numberOfLines = 0 label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) label.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) label.adjustsFontSizeToFitWidth = true return label }() let valueLabel: UILabel = { let valueLabel = UILabel() valueLabel.textColor = SemanticColors.Label.textDefault valueLabel.font = UIFont.systemFont(ofSize: 17) valueLabel.textAlignment = .right return valueLabel }() let badge: RoundedBadge = { let badge = RoundedBadge(view: UIView()) badge.backgroundColor = SemanticColors.View.backgroundBadgeCell badge.isHidden = true return badge }() private let badgeLabel: UILabel = { let badgeLabel = DynamicFontLabel(fontSpec: .smallMediumFont, color: .textInBadge) badgeLabel.textAlignment = .center badgeLabel.textColor = SemanticColors.Label.textSettingsCellBadge return badgeLabel }() private let imagePreview: UIImageView = { let imagePreview = UIImageView() imagePreview.clipsToBounds = true imagePreview.layer.cornerRadius = 12 imagePreview.contentMode = .scaleAspectFill imagePreview.accessibilityIdentifier = "imagePreview" return imagePreview }() private lazy var cellNameLabelToIconInset: NSLayoutConstraint = cellNameLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 24) var titleText: String = "" { didSet { cellNameLabel.text = titleText } } var preview: SettingsCellPreview = .none { didSet { switch preview { case .text(let string): valueLabel.text = string badgeLabel.text = "" badge.isHidden = true imagePreview.image = .none imagePreview.backgroundColor = UIColor.clear imagePreview.accessibilityValue = nil imagePreview.isAccessibilityElement = false case .badge(let value): valueLabel.text = "" badgeLabel.text = "\(value)" badge.isHidden = false imagePreview.image = .none imagePreview.backgroundColor = UIColor.clear imagePreview.accessibilityValue = nil imagePreview.isAccessibilityElement = false case .image(let image): valueLabel.text = "" badgeLabel.text = "" badge.isHidden = true imagePreview.image = image imagePreview.backgroundColor = UIColor.clear imagePreview.accessibilityValue = "image" imagePreview.isAccessibilityElement = true case .color(let color): valueLabel.text = "" badgeLabel.text = "" badge.isHidden = true imagePreview.image = .none imagePreview.backgroundColor = color imagePreview.accessibilityValue = "color" imagePreview.isAccessibilityElement = true case .none: valueLabel.text = "" badgeLabel.text = "" badge.isHidden = true imagePreview.image = .none imagePreview.backgroundColor = UIColor.clear imagePreview.accessibilityValue = nil imagePreview.isAccessibilityElement = false } setupAccessibility() } } var icon: StyleKitIcon? { didSet { if let icon = icon { iconImageView.setTemplateIcon(icon, size: .tiny) cellNameLabelToIconInset.isActive = true } else { iconImageView.image = nil cellNameLabelToIconInset.isActive = false } } } override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) updateBackgroundColor() } var descriptor: SettingsCellDescriptorType? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not implemented") } override func prepareForReuse() { super.prepareForReuse() preview = .none } func setup() { backgroundView = UIView() selectedBackgroundView = UIView() badge.containedView.addSubview(badgeLabel) [iconImageView, cellNameLabel, valueLabel, badge, imagePreview].forEach { contentView.addSubview($0) } createConstraints() addBorder(for: .bottom) setupAccessibility() } private func createConstraints() { let leadingConstraint = cellNameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16) leadingConstraint.priority = .defaultHigh let trailingBoundaryView = accessoryView ?? contentView if trailingBoundaryView != contentView { trailingBoundaryView.translatesAutoresizingMaskIntoConstraints = false } [iconImageView, valueLabel, badge, badgeLabel, imagePreview, cellNameLabel].prepareForLayout() NSLayoutConstraint.activate([ iconImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24), iconImageView.widthAnchor.constraint(equalToConstant: 16), iconImageView.heightAnchor.constraint(equalTo: iconImageView.heightAnchor), iconImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), leadingConstraint, cellNameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12), cellNameLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12), valueLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: -8), valueLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 8), valueLabel.leadingAnchor.constraint(greaterThanOrEqualTo: cellNameLabel.trailingAnchor, constant: 8), valueLabel.trailingAnchor.constraint(equalTo: trailingBoundaryView.trailingAnchor, constant: -16), badge.centerXAnchor.constraint(equalTo: valueLabel.centerXAnchor), badge.centerYAnchor.constraint(equalTo: valueLabel.centerYAnchor), badge.heightAnchor.constraint(equalToConstant: 20), badge.widthAnchor.constraint(greaterThanOrEqualToConstant: 28), badgeLabel.leadingAnchor.constraint(equalTo: badge.leadingAnchor, constant: 6), badgeLabel.trailingAnchor.constraint(equalTo: badge.trailingAnchor, constant: -6), badgeLabel.topAnchor.constraint(equalTo: badge.topAnchor), badgeLabel.bottomAnchor.constraint(equalTo: badge.bottomAnchor), imagePreview.widthAnchor.constraint(equalTo: imagePreview.heightAnchor), imagePreview.heightAnchor.constraint(equalToConstant: 24), imagePreview.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16), imagePreview.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 56) ]) } func setupAccessibility() { isAccessibilityElement = true accessibilityTraits = .button let badgeValue = badgeLabel.text ?? "" accessibilityHint = badgeValue.isEmpty ? "" : L10n.Accessibility.Settings.DeviceCount.hint("\(badgeValue)") } func updateBackgroundColor() { backgroundColor = SemanticColors.View.backgroundUserCell if isHighlighted && selectionStyle != .none { backgroundColor = SemanticColors.View.backgroundUserCellHightLighted badge.backgroundColor = SemanticColors.View.backgroundBadgeCell badgeLabel.textColor = SemanticColors.Label.textSettingsCellBadge } } } final class SettingsButtonCell: SettingsTableCell { override func setup() { super.setup() cellNameLabel.textColor = SemanticColors.Label.textDefault } } final class SettingsToggleCell: SettingsTableCell { var switchView: UISwitch! override func setup() { super.setup() selectionStyle = .none shouldGroupAccessibilityChildren = false let switchView = Switch(style: .default) switchView.addTarget(self, action: #selector(SettingsToggleCell.onSwitchChanged(_:)), for: .valueChanged) accessoryView = switchView switchView.isAccessibilityElement = true accessibilityElements = [cellNameLabel, switchView] accessibilityTraits = .button self.switchView = switchView backgroundColor = SemanticColors.View.backgroundUserCell } @objc func onSwitchChanged(_ sender: UIResponder) { descriptor?.select(SettingsPropertyValue(switchView.isOn)) } } final class SettingsValueCell: SettingsTableCell { override var descriptor: SettingsCellDescriptorType? { willSet { if let propertyDescriptor = descriptor as? SettingsPropertyCellDescriptorType { NotificationCenter.default.removeObserver(self, name: propertyDescriptor.settingsProperty.propertyName.notificationName, object: nil) } } didSet { if let propertyDescriptor = descriptor as? SettingsPropertyCellDescriptorType { NotificationCenter.default.addObserver(self, selector: #selector(SettingsValueCell.onPropertyChanged(_:)), name: propertyDescriptor.settingsProperty.propertyName.notificationName, object: nil) } } } // MARK: - Properties observing @objc func onPropertyChanged(_ notification: Notification) { descriptor?.featureCell(self) } } final class SettingsTextCell: SettingsTableCell, UITextFieldDelegate { var textInput: UITextField! override func setup() { super.setup() selectionStyle = .none textInput = TailEditingTextField(frame: CGRect.zero) textInput.delegate = self textInput.textAlignment = .right textInput.textColor = SemanticColors.Label.textDefault textInput.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) textInput.isAccessibilityElement = true contentView.addSubview(textInput) createConstraints() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(onCellSelected(_:))) contentView.addGestureRecognizer(tapGestureRecognizer) } private func createConstraints() { let textInputSpacing: CGFloat = 16 let trailingBoundaryView = accessoryView ?? contentView textInput.translatesAutoresizingMaskIntoConstraints = false if trailingBoundaryView != contentView { trailingBoundaryView.translatesAutoresizingMaskIntoConstraints = false } NSLayoutConstraint.activate([ textInput.topAnchor.constraint(equalTo: contentView.topAnchor, constant: -8), textInput.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 8), textInput.trailingAnchor.constraint(equalTo: trailingBoundaryView.trailingAnchor, constant: -textInputSpacing), cellNameLabel.trailingAnchor.constraint(equalTo: textInput.leadingAnchor, constant: -textInputSpacing) ]) } override func setupAccessibility() { super.setupAccessibility() var currentElements = accessibilityElements ?? [] if let textInput = textInput { currentElements.append(textInput) } accessibilityElements = currentElements } @objc func onCellSelected(_ sender: AnyObject!) { if !textInput.isFirstResponder { textInput.becomeFirstResponder() } } // MARK: - UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string.rangeOfCharacter(from: CharacterSet.newlines) != .none { textField.resignFirstResponder() return false } else { return true } } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } func textFieldDidEndEditing(_ textField: UITextField) { if let text = textInput.text { descriptor?.select(SettingsPropertyValue.string(value: text)) } } } final class SettingsStaticTextTableCell: SettingsTableCell { override func setup() { super.setup() cellNameLabel.numberOfLines = 0 cellNameLabel.textAlignment = .justified accessibilityTraits = .staticText } } final class SettingsProfileLinkCell: SettingsTableCell { // MARK: - Properties var label = CopyableLabel() override func setup() { super.setup() setupViews() createConstraints() } // MARK: - Helpers private func setupViews() { contentView.addSubview(label) label.textColor = SemanticColors.Label.textDefault label.font = FontSpec(.normal, .light).font label.lineBreakMode = .byClipping label.numberOfLines = 0 accessibilityTraits = .staticText } private func createConstraints() { [label].prepareForLayout() label.fitIn(view: contentView, insets: UIEdgeInsets(top: 4, left: 16, bottom: 4, right: 16)) } }
gpl-3.0
2aae1665ca1aa1ac82bf319c82c5e33a
34.604027
159
0.654163
5.780966
false
false
false
false
mattgallagher/CwlSignal
Sources/CwlSignal/CwlSignal.swift
1
171413
// // CwlSignal.swift // CwlSignal // // Created by Matt Gallagher on 2016/06/05. // Copyright © 2016 Matt Gallagher ( https://www.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 CwlUtils import Foundation /// This protocol allows transformations that apply to `Signal` types to be applied to a type that exposes a signal. public protocol SignalInterface { associatedtype OutputValue var signal: Signal<OutputValue> { get } } /// This protocol allows transformations that apply to `Signal` types to be applied to a type that exposes a signal. public protocol SignalInputInterface { associatedtype InputValue var input: SignalInput<InputValue> { get } } #if DEBUG_LOGGING // NOTE: This is thread unsafe. There should really be a lock around access and logging. var globalCount: Int = 0 #endif /// A composable, one-way, potentially asynchronous, FIFO communication channel that delivers a sequence of `Result<OutputValue, SignalEnd>`. /// /// In conjunction with various transformation functions, this class forms the core of a reactive programming system. Try the playgrounds for a better walkthrough of concepts and usage. /// /// # Terminology /// /// The word "signal" may be used in a number of ways, so keep in mind: /// - `Signal`: refers to this class /// - signal graph: one or more `Signal` instances, connected together, from `SignalInput` to `SignalOutput` /// - signal: the sequence of `Result` instances, from activation to close, that pass through a signal graph public class Signal<OutputValue>: SignalInterface { public typealias Result = Swift.Result<OutputValue, SignalEnd> public enum Next { case none case single(Result) case array(Array<Result>) } // # GOALS // // The primary design goals for this implementation are: // 1. All possible actions on `Signal` itself are threadsafe (no possible action results in undefined or corrupt memory behavior for internal data) // 2. Deadlocks on internally created mutexes will never occur. // 3. Values will never be delivered out-of-order. // 4. After a disconnection and reconnection, only values from the latest connection will be delivered. // 5. Loopback (sending to an antecedent input from a subsequent signal handler) and attempts at re-entrancy to any closure in the graph are permitted. Attempted re-entrancy delivery is simply queued to be delivered after any in-flight behavior completes. // // That's quite a list of goals but it's largely covered by two ideas: // 1. No user code is ever invoked inside a `Signal` internal mutex // 2. Delivery to a `Signal` includes the "predecessor" and the "activationCount". If either fail to match the internal state of the `Signal`, then the delivery is out-of-date and can be discarded. // // The first of these points is ensured through the use of `itemProcessing`, `holdCount` and `DeferredWork`. The `itemProcessing` and `holdCount` block a queue while out-of-mutex work is performed. The `DeferredWork` defers work to be performed later, once the stack has unwound and no mutexes are held. // This ensures that no problematic work is performed inside a mutex but it means that we often have "in-flight" work occurring outside a mutex that might no longer be valid. So we need to combine this work identifiers that allow us to reject out-of-date work. That's where the second point becomes important. // The "activationCount" for an `Signal` changes any time a manual input control is generated (`SignalInput`/`SignalMergedInput`), any time a first predecessor is added or any time there are predecessors connected and the `delivery` state changes to or from `.disabled`. Combined with the fact that it is not possible to disconnect and re-add the same predecessor to a multi-input Signal (SignalMergedInput or SignalCombiner) this guarantees any messages from out-of-date but still in-flight deliveries are ignored. // // # LIMITS TO THREADSAFETY // // While all actions on `Signal` are threadsafe, there are some points to keep in mind: // 1. Threadsafe means that the internal members of the `Signal` class will remain threadsafe and your own closures will always be serially and non-reentrantly invoked on the provided `Exec` context. However, this doesn't mean that work you perform in processing closures is always threadsafe; shared references or mutable captures in your closures will still require mutual exclusion. // 2. Delivery of signal values is guaranteed to be in-order and within appropriate mutexes but is not guaranteed to be executed on the sending thread. If subsequent results are sent to a `Signal` from a second thread while the `Signal` is processing a previous result from a first thread the subsequent result will be *queued* and handled on the *first* thread once it completes processing the earlier values. // 3. Handlers, captured values and state values will be released *outside* all contexts or mutexes. If you capture an object with `deinit` behavior in a processing closure, you must apply any synchronization context yourself. // MARK: - Signal static construction functions /// Create a manual input/output pair where values sent to the `SignalInput` are passed through the `Signal` output. /// /// - returns: a (`SignalInput`, `Signal`) tuple being the input and output for this stage in the signal pipeline. public static func create() -> (input: SignalInput<OutputValue>, signal: Signal<OutputValue>) { let s = Signal<OutputValue>() s.activationCount = 1 return (SignalInput(signal: s, activationCount: s.activationCount), s) } /// A version of created that creates a `SignalMultiInput` instead of a `SignalInput`. /// /// - Returns: the (input, signal) public static func createMultiInput() -> (input: SignalMultiInput<OutputValue>, signal: Signal<OutputValue>) { let s = Signal<OutputValue>() var dw = DeferredWork() s.sync { s.updateActivationInternal(andInvalidateAllPrevious: true, dw: &dw) } dw.runWork() return (SignalMultiInput(signal: s), s) } /// A version of created that creates a `SignalMergedInput` instead of a `SignalInput`. /// /// - Returns: the (input, signal) public static func createMergedInput(onLastInputClosed: SignalEnd? = nil, onDeinit: SignalEnd = .cancelled) -> (input: SignalMergedInput<OutputValue>, signal: Signal<OutputValue>) { let s = Signal<OutputValue>() var dw = DeferredWork() s.sync { s.updateActivationInternal(andInvalidateAllPrevious: true, dw: &dw) } dw.runWork() return (SignalMergedInput(signal: s, onLastInputClosed: onLastInputClosed, onDeinit: onDeinit), s) } /// Similar to `create`, in that it creates a "head" for the graph but rather than immediately providing a `SignalInput`, this function calls the `activationChange` function when the signal graph is activated and provides the newly created `SignalInput` at that time. When the graph deactivates, `nil` is sent to the `activationChange` function. If a subsequent reactivation occurs, the new `SignalInput` for the re-activation is provided. /// /// - Parameters: /// - context: the `activationChange` will be invoked in this context /// - activationChange: receives inputs on activation and nil on each deactivation /// - Returns: the constructed `Signal` public static func generate(context: Exec = .direct, _ activationChange: @escaping (_ input: SignalInput<OutputValue>?) -> Void) -> Signal<OutputValue> { let s = Signal<OutputValue>() let nis = Signal<Any?>() s.newInputSignal = (nis, nis.subscribe(context: context) { r in if case .success(let v) = r { activationChange(v as? SignalInput<OutputValue>) } }) return s } /// Constructs a `SignalMulti` with an array of "activation" values and a closing error. /// /// - Parameters: /// - values: an array of values /// - end: the closing condition for the `Signal` /// - Returns: a `SignalMulti` public static func preclosed<S: Sequence>(sequence: S, end: SignalEnd = .complete) -> SignalMulti<OutputValue> where S.Iterator.Element == OutputValue { return SignalMulti<OutputValue>(processor: Signal<OutputValue>().attach { (s, dw) in SignalMultiProcessor(source: s, values: (Array(sequence), end), userUpdated: false, activeWithoutOutputs: .always, dw: &dw, context: .direct, updater: { a, p, r in ([], nil) }) }) } /// Constructs a `SignalMulti` with a single activation value and a closing error. /// /// - Parameters: /// - value: a single value /// - end: the closing condition for the `Signal` /// - Returns: a `SignalMulti` public static func preclosed(_ values: OutputValue..., end: SignalEnd = .complete) -> SignalMulti<OutputValue> { return preclosed(sequence: values, end: end) } /// Constructs a `SignalMulti` that is already closed with an error. /// /// - Parameter end: the closing condition for the `Signal` /// - Returns: a `SignalMulti` public static func preclosed(end: SignalEnd = .complete) -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: Signal<OutputValue>().attach { (s, dw) in SignalMultiProcessor(source: s, values: ([], end), userUpdated: false, activeWithoutOutputs: .always, dw: &dw, context: .direct, updater: { a, p, r in ([], nil) }) }) } // MARK: - Signal public transformation functions public var signal: Signal<OutputValue> { return self } /// Appends a `SignalOutput` listener to the value emitted from this `Signal`. The output will "activate" this `Signal` and all direct antecedents in the graph (which may start lazy operations deferred until activation). /// /// - Parameters: /// - context: context: the `Exec` context used to invoke the `handler` /// - handler: the function invoked for each received `Result` /// - Returns: the created `SignalOutput` (if released, the subscription will be cancelled). public final func subscribe(context: Exec = .direct, _ handler: @escaping (Result) -> Void) -> SignalOutput<OutputValue> { return attach { (s, dw) in SignalOutput<OutputValue>(source: s, dw: &dw, context: context, handler: handler) } } /// A version of `subscribe` that retains the `SignalOutput` internally, keeping the signal graph alive. The `SignalOutput` is cancelled and released if the signal closes or if the handler returns `false` after any signal. /// /// NOTE: this subscriber deliberately creates a reference counted loop. If the signal is never closed and the handler never returns false, it will result in a memory leak. This function should be used only when `self` is guaranteed to close or the handler `false` condition is guaranteed. /// /// - Parameters: /// - context: the execution context where the `processor` will be invoked /// - handler: will be invoked with each value received and if returns `false`, the output will be cancelled and released public final func subscribeWhile(context: Exec = .direct, _ handler: @escaping (Result) -> Bool) { _ = attach { (s, dw) in var handlerRetainedOutput: SignalOutput<OutputValue>? = nil let output = SignalOutput<OutputValue>(source: s, dw: &dw, context: context, handler: { r in withExtendedLifetime(handlerRetainedOutput) {} if !handler(r) || r.isFailure { handlerRetainedOutput?.cancel() handlerRetainedOutput = nil } }) handlerRetainedOutput = output return output } } /// Appends a disconnected `SignalJunction` to this `Signal` so outputs can be repeatedly joined and disconnected from this graph in the future. /// /// - Returns: the `SignalJunction<OutputValue>` public final func junction() -> SignalJunction<OutputValue> { return attach { (s, dw) -> SignalJunction<OutputValue> in return SignalJunction<OutputValue>(source: s, dw: &dw) } } /// Appends an immediately activated handler that captures any activation values from this `Signal`. The captured values can be accessed from the `SignalCapture<OutputValue>` using the `activation()` function. The `SignalCapture<OutputValue>` can then be joined to further `Signal`s using the `bind(to:)` function on the `SignalCapture<OutputValue>`. /// /// - Returns: the handler than can be used to obtain activation values and bind to subsequent nodes. public final func capture() -> SignalCapture<OutputValue> { return attach { (s, dw) -> SignalCapture<OutputValue> in SignalCapture<OutputValue>(source: s, dw: &dw) } } /// Appends a handler function that transforms the value emitted from this `Signal` into a new `Signal`. /// /// - Parameters: /// - context: the `Exec` context used to invoke the `handler` /// - processor: the function invoked for each received `Result` /// - Returns: the created `Signal` public final func transform<U>(context: Exec = .direct, _ processor: @escaping (Result) -> Signal<U>.Next) -> Signal<U> { return Signal<U>(processor: attach { (s, dw) in SignalTransformer<OutputValue, U>(source: s, dw: &dw, context: context, processor) }).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that transforms the value emitted from this `Signal` into a new `Signal`. /// /// - Parameters: /// - context: the `Exec` context used to invoke the `handler` /// - processor: the function invoked for each received `Result` /// - Returns: the created `Signal` public final func transformActivation<U>(context: Exec = .direct, activation: @escaping (Result) -> Signal<U>.Next, _ processor: @escaping (Result) -> Signal<U>.Next) -> Signal<U> { return Signal<U>(processor: attach { (s, dw) in SignalActivationTransformer<OutputValue, U>(source: s, dw: &dw, context: context, activationProcessor: activation, processor) }).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that transforms the value emitted from this `Signal` into a new `Signal`. /// /// - Parameters: /// - initialState: the initial value for a state value associated with the handler. This value is retained and if the signal graph is deactivated, the state value is reset to this value. /// - context: the `Exec` context used to invoke the `handler` /// - processor: the function invoked for each received `Result` /// - Returns: the transformed output `Signal` public final func transform<S, U>(initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, Result) -> Signal<U>.Next) -> Signal<U> { return Signal<U>(processor: attach { (s, dw) in SignalTransformerWithState<OutputValue, U, S>(source: s, initialState: initialState, dw: &dw, context: context, processor) }).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that receives inputs from this and another `Signal<U>`. The `handler` function applies any transformation it wishes an emits a (potentially) third `Signal` type. /// /// - Parameters: /// - second: the other `Signal` that is, along with `self` used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self` or `second` as `EitherResult2<OutputValue, U>` (an enum which may contain either `.result1` or `.result2` corresponding to `self` or `second`) and sends results to an `SignalNext<V>`. /// - Returns: an `Signal<V>` which is the result stream from the `SignalNext<V>` passed to the `handler`. public final func combine<U: SignalInterface, V>(_ second: U, context: Exec = .direct, _ processor: @escaping (EitherResult2<OutputValue, U.OutputValue>) -> Signal<V>.Next) -> Signal<V> { return Signal<EitherResult2<OutputValue, U.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult2<OutputValue, U.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult2<OutputValue, U.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult2<OutputValue, U.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult2<OutputValue, U.OutputValue>.result2) }).transform(context: context, Signal.successProcessor(processor)).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that receives inputs from this and two other `Signal`s. The `handler` function applies any transformation it wishes an emits a (potentially) fourth `Signal` type. /// /// - Parameters: /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second` or `third` as `EitherResult3<OutputValue, U, V>` (an enum which may contain either `.result1`, `.result2` or `.result3` corresponding to `self`, `second` or `third`) and sends results to an `SignalNext<W>`. /// - Returns: an `Signal<W>` which is the result stream from the `SignalNext<W>` passed to the `handler`. public final func combine<U: SignalInterface, V: SignalInterface, W>(_ second: U, _ third: V, context: Exec = .direct, _ processor: @escaping (EitherResult3<OutputValue, U.OutputValue, V.OutputValue>) -> Signal<W>.Next) -> Signal<W> { return Signal<EitherResult3<OutputValue, U.OutputValue, V.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result3) }).transform(context: context, Signal.successProcessor(processor)).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that receives inputs from this and three other `Signal`s. The `handler` function applies any transformation it wishes an emits a (potentially) fifth `Signal` type. /// /// - Parameters: /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - fourth: the fourth `Signal`, after `self`, `second` and `third`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second`, `third` or `fourth` as `EitherResult4<OutputValue, U, V, W>` (an enum which may contain either `.result1`, `.result2`, `.result3` or `.result4` corresponding to `self`, `second`, `third` or `fourth`) and sends results to an `SignalNext<X>`. /// - Returns: an `Signal<X>` which is the result stream from the `SignalNext<X>` passed to the `handler`. public final func combine<U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(_ second: U, _ third: V, _ fourth: W, context: Exec = .direct, _ processor: @escaping (EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>) -> Signal<X>.Next) -> Signal<X> { return Signal<EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result3) }).addPreceeding(processor: fourth.signal.attach { (s4, dw) -> SignalCombiner<W.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s4, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result4) }).transform(context: context, Signal.successProcessor(processor)).returnToGlobalIfNeeded(context: context) } /// Appends a handler function that receives inputs from this and four other `Signal`s. The `handler` function applies any transformation it wishes an emits a (potentially) sixth `Signal` type. /// /// - Parameters: /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - fourth: the fourth `Signal`, after `self`, `second` and `third`, used as input to the `handler` /// - fifth: the fifth `Signal`, after `self`, `second`, `third` and `fourth`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second`, `third`, `fourth` or `fifth` as `EitherResult5<OutputValue, U, V, W, X>` (an enum which may contain either `.result1`, `.result2`, `.result3`, `.result4` or `.result5` corresponding to `self`, `second`, `third`, `fourth` or `fifth`) and sends results to an `SignalNext<Y>`. /// - Returns: an `Signal<Y>` which is the result stream from the `SignalNext<Y>` passed to the `handler`. public final func combine<U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface, Y>(_ second: U, _ third: V, _ fourth: W, _ fifth: X, context: Exec = .direct, _ processor: @escaping (EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>) -> Signal<Y>.Next) -> Signal<Y> { return Signal<EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result3) }).addPreceeding(processor: fourth.signal.attach { (s4, dw) -> SignalCombiner<W.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s4, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result4) }).addPreceeding(processor: fifth.signal.attach { (s5, dw) -> SignalCombiner<X.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s5, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result5) }).transform(context: context, Signal.successProcessor(processor)).returnToGlobalIfNeeded(context: context) } /// Similar to `combine(second:context:handler:)` with an additional "state" value. /// /// - Parameters: /// - initialState: the initial value of a "state" value passed into the closure on each invocation. The "state" will be reset to this value if the `Signal` deactivates. /// - second: the other `Signal` that is, along with `self` used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self` or `second` as `EitherResult2<OutputValue, U>` (an enum which may contain either `.result1` or `.result2` corresponding to `self` or `second`) and sends results to an `SignalNext<V>`. /// - Returns: an `Signal<V>` which is the result stream from the `SignalNext<V>` passed to the `handler`. public final func combine<S, U: SignalInterface, V>(_ second: U, initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, EitherResult2<OutputValue, U.OutputValue>) -> Signal<V>.Next) -> Signal<V> { return Signal<EitherResult2<OutputValue, U.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult2<OutputValue, U.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult2<OutputValue, U.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult2<OutputValue, U.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult2<OutputValue, U.OutputValue>.result2) }).transform(initialState: initialState, context: context, Signal.successProcessorWithState(processor)).returnToGlobalIfNeeded(context: context) } /// Similar to `combine(second:third:context:handler:)` with an additional "state" value. /// /// - Parameters: /// - initialState: the initial value of a "state" value passed into the closure on each invocation. The "state" will be reset to this value if the `Signal` deactivates. /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second` or `third` as `EitherResult3<OutputValue, U, V>` (an enum which may contain either `.result1`, `.result2` or `.result3` corresponding to `self`, `second` or `third`) and sends results to an `SignalNext<W>`. /// - Returns: an `Signal<W>` which is the result stream from the `SignalNext<W>` passed to the `handler`. public final func combine<S, U: SignalInterface, V: SignalInterface, W>(_ second: U, _ third: V, initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>) -> Signal<W>.Next) -> Signal<W> { return Signal<EitherResult3<OutputValue, U.OutputValue, V.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult3<OutputValue, U.OutputValue, V.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult3<OutputValue, U.OutputValue, V.OutputValue>.result3) }).transform(initialState: initialState, context: context, Signal.successProcessorWithState(processor)).returnToGlobalIfNeeded(context: context) } /// Similar to `combine(second:third:fourth:context:handler:)` with an additional "state" value. /// /// - Parameters: /// - initialState: the initial value of a "state" value passed into the closure on each invocation. The "state" will be reset to this value if the `Signal` deactivates. /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - fourth: the fourth `Signal`, after `self`, `second` and `third`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second`, `third` or `fourth` as `EitherResult4<OutputValue, U, V, W>` (an enum which may contain either `.result1`, `.result2`, `.result3` or `.result4` corresponding to `self`, `second`, `third` or `fourth`) and sends results to an `SignalNext<X>`. /// - Returns: an `Signal<X>` which is the result stream from the `SignalNext<X>` passed to the `handler`. public final func combine<S, U: SignalInterface, V: SignalInterface, W: SignalInterface, X>(_ second: U, _ third: V, _ fourth: W, initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>) -> Signal<X>.Next) -> Signal<X> { return Signal<EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result3) }).addPreceeding(processor: fourth.signal.attach { (s4, dw) -> SignalCombiner<W.OutputValue, EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>> in SignalCombiner(source: s4, dw: &dw, context: .direct, processor: EitherResult4<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue>.result4) }).transform(initialState: initialState, context: context, Signal.successProcessorWithState(processor)).returnToGlobalIfNeeded(context: context) } /// Similar to `combine(second:third:fourth:fifthcontext:handler:)` with an additional "state" value. /// /// - Parameters: /// - initialState: the initial value of a "state" value passed into the closure on each invocation. The "state" will be reset to this value if the `Signal` deactivates. /// - second: the second `Signal`, after `self` used as input to the `handler` /// - third: the third `Signal`, after `self` and `second`, used as input to the `handler` /// - fourth: the fourth `Signal`, after `self`, `second` and `third`, used as input to the `handler` /// - fifth: the fifth `Signal`, after `self`, `second`, `third` and `fourth`, used as input to the `handler` /// - context: the `Exec` context used to invoke the `handler` /// - processor: processes inputs from either `self`, `second`, `third`, `fourth` or `fifth` as `EitherResult5<OutputValue, U, V, W, X>` (an enum which may contain either `.result1`, `.result2`, `.result3`, `.result4` or `.result5` corresponding to `self`, `second`, `third`, `fourth` or `fifth`) and sends results to an `SignalNext<Y>`. /// - Returns: an `Signal<Y>` which is the result stream from the `SignalNext<Y>` passed to the `handler`. public final func combine<S, U: SignalInterface, V: SignalInterface, W: SignalInterface, X: SignalInterface, Y>(_ second: U, _ third: V, _ fourth: W, _ fifth: X, initialState: S, context: Exec = .direct, _ processor: @escaping (inout S, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>) -> Signal<Y>.Next) -> Signal<Y> { return Signal<EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>>(processor: self.attach { (s1, dw) -> SignalCombiner<OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s1, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result1) }).addPreceeding(processor: second.signal.attach { (s2, dw) -> SignalCombiner<U.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s2, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result2) }).addPreceeding(processor: third.signal.attach { (s3, dw) -> SignalCombiner<V.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s3, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result3) }).addPreceeding(processor: fourth.signal.attach { (s4, dw) -> SignalCombiner<W.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s4, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result4) }).addPreceeding(processor: fifth.signal.attach { (s5, dw) -> SignalCombiner<X.OutputValue, EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>> in SignalCombiner(source: s5, dw: &dw, context: .direct, processor: EitherResult5<OutputValue, U.OutputValue, V.OutputValue, W.OutputValue, X.OutputValue>.result5) }).transform(initialState: initialState, context: context, Signal.successProcessorWithState(processor)).returnToGlobalIfNeeded(context: context) } /// Appends a new `SignalMulti` to this `Signal`. The new `SignalMulti` immediately activates its antecedents and is "continuous" (multiple listeners can be attached to the `SignalMulti` and each new listener immediately receives the most recently sent value on "activation"). /// /// NOTE: this is the canonical "shared value" signal /// /// - parameter initialValues: the immediate value sent to any listeners that connect *before* the first value is sent through this `Signal` /// - returns: a continuous `SignalMulti` public final func continuous(initialValue: OutputValue) -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: ([initialValue], nil), userUpdated: false, activeWithoutOutputs: .always, dw: &dw, context: .direct, updater: { a, p, r -> (Array<OutputValue>, SignalEnd?) in let previous: (Array<OutputValue>, SignalEnd?) = (a, p) switch r { case .success(let v): a = [v] case .failure(let e): a = []; p = e } return previous }) }) } /// Appends a new `SignalMulti` to this `Signal`. The new `SignalMulti` immediately activates its antecedents and is "continuous" (multiple listeners can be attached to the `SignalMulti` and each new listener immediately receives the most recently sent value on "activation"). Any listeners that connect before the first signal is received will receive no value on "activation". /// /// NOTE: this is the canonical "shared results" signal /// /// - returns: a continuous `SignalMulti` public final func continuous() -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: ([], nil), userUpdated: false, activeWithoutOutputs: .always, dw: &dw, context: .direct, updater: { a, p, r -> (Array<OutputValue>, SignalEnd?) in let previous: (Array<OutputValue>, SignalEnd?) = (a, p) switch r { case .success(let v): a = [v]; p = nil case .failure(let e): a = []; p = e } return previous }) }) } /// Appends a new `SignalMulti` to this `Signal`. The new `SignalMulti` does not immediately activate (it waits until an output activates it normally). The first activator receives no cached values but does start the signal. If a value is received, subsequent activators will receive the most recent value. Depending on the `discardOnDeactivate` behavior, the cached value may be discarded (resetting the entire signal to its deactivated state) or the cached value might be retained for delivery to any future listeners. /// /// NOTE: this signal is intended for lazily loaded, shared resources. /// /// - returns: a continuous `SignalMulti` public final func continuousWhileActive(discardOnDeactivate: Bool = true) -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: ([], nil), userUpdated: false, activeWithoutOutputs: discardOnDeactivate ? .never : .ifNonEmpty, dw: &dw, context: .direct, updater: { a, p, r -> (Array<OutputValue>, SignalEnd?) in let previous: (Array<OutputValue>, SignalEnd?) = (a, p) switch r { case .success(let v): a = [v]; p = nil case .failure(let e): a = []; p = e } return previous }) }) } /// Appends a new `SignalMulti` to this `Signal`. The new `SignalMulti` immediately activates its antecedents and offers full "playback" (multiple listeners can be attached to the `SignalMulti` and each new listener receives the entire history of values previously sent through this `Signal` upon "activation"). /// /// - returns: a playback `SignalMulti` public final func playback() -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: ([], nil), userUpdated: false, activeWithoutOutputs: .always, dw: &dw, context: .direct, updater: { a, p, r -> (Array<OutputValue>, SignalEnd?) in switch r { case .success(let v): a.append(v) case .failure(let e): p = e } return ([], nil) }) }) } /// Appends a new `Signal` to this `Signal`. The new `Signal` immediately activates its antecedents and caches any values it receives until this the new `Signal` itself is activated – at which point it sends all prior values upon "activation" and subsequently reverts to passthough. /// /// NOTE: this is intended for greedily started signals that might start emitting before the listeners connect. /// /// - Parameter precached: start the cache with some initial values to which subsequent values will be added (default: nil) /// - Returns: a "cache until active" `Signal`. public final func cacheUntilActive(precached: [OutputValue]? = nil) -> Signal<OutputValue> { return Signal<OutputValue>(processor: attach { (s, dw) in SignalCacheUntilActive(source: s, precached: precached, dw: &dw) }) } /// Appends a new `SignalMulti` to this `Signal`. While multiple listeners are permitted, there is no caching, activation signal or other changes inherent in this new `Signal` – newly connected listeners will receive only those values sent after they connect. /// /// NOTE: this is intended for shared signals where new values are important but previous values are not /// /// - returns: a "multicast" `SignalMulti`. public final func multicast() -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: ([], nil), userUpdated: false, activeWithoutOutputs: .never, dw: &dw, context: .direct, updater: nil) }) } /// Appends a new `SignalMulti` to this `Signal`. The new `SignalMulti` immediately activates its antecedents. Every time a value is received, it is passed to an "updater" which creates an array of activation values and an error that will be used for any new listeners. /// Consider this as an operator that allows the creation of a custom "bring-up-to-speed" value for new listeners. /// /// - Parameters: /// - initialValues: activation values used when *before* any incoming value is received (if you wan't to specify closed as well, use `preclosed` instead) /// - context: the execution context where the `updater` will run /// - updater: run for each incoming `Result` to update the buffered activation values /// - Returns: a `SignalMulti` with custom activation public final func customActivation(initialValues: Array<OutputValue> = [], context: Exec = .direct, _ updater: @escaping (_ cachedValues: inout Array<OutputValue>, _ cachedError: inout SignalEnd?, _ incoming: Result) -> Void) -> SignalMulti<OutputValue> { return SignalMulti<OutputValue>(processor: attach { (s, dw) in SignalMultiProcessor(source: s, values: (initialValues, nil), userUpdated: true, activeWithoutOutputs: .always, dw: &dw, context: context) { (bufferedValues: inout Array<OutputValue>, bufferedError: inout SignalEnd?, incoming: Result) -> (Array<OutputValue>, SignalEnd?) in let oldActivationValues = bufferedValues let oldError = bufferedError updater(&bufferedValues, &bufferedError, incoming) return (oldActivationValues, oldError) } }) } /// This operator applies a reducing function to the stream of incoming values, reducing down to a single, internal `State` value. /// /// A value of the same `State` type is emitted on each iteration, although it is not required to be the same value. Having the return value be potentially different to the internal state isn't standard "reduction semantics" but it enables differential notifications, rather than whole state notifications. /// /// This operator combines aspects of `transform` and `customActivation` into a single operation, transforming the incoming message into state values by combining with a cached state value (that also serves as the activation value). /// /// - Parameters: /// - initialState: initial activation value for the stream and internal state for the reducer /// - context: execution context where `reducer` will run /// - reducer: the function that combines the state with incoming values and emits differential updates /// - Returns: a `SignalMulti<State>` public final func reduce<State>(initialState: State, context: Exec = .direct, _ reducer: @escaping (_ state: State, _ message: OutputValue) throws -> State) -> SignalMulti<State> { return SignalMulti<State>(processor: attach { (s, dw) in return SignalReducer<OutputValue, State>(source: s, state: initialState, end: nil, dw: &dw, context: context) { (state: State, message: Signal<OutputValue>.Result) -> Signal<State>.Result in switch message { case .success(let m): return Swift.Result { try reducer(state, m) }.mapError(SignalEnd.other) case .failure(let e): return .failure(e) } } }) } /// This operator applies a reducing function to the stream of incoming values, reducing down to a single, internal `State` value. /// /// A value of the same `State` type is emitted on each iteration, although it is not required to be the same value. Having the return value be potentially different to the internal state isn't standard "reduction semantics" but it enables differential notifications, rather than whole state notifications. /// /// This operator combines aspects of `transform` and `customActivation` into a single operation, transforming the incoming message into state values by combining with a cached state value (that also serves as the activation value). /// /// - Parameters: /// - initialState: initial activation value for the stream and internal state for the reducer /// - context: execution context where `reducer` will run /// - reducer: the function that combines the state with incoming values and emits differential updates /// - Returns: a `SignalMulti<State>` public final func reduce<State>(context: Exec = .direct, initializer: @escaping (_ message: OutputValue) throws -> State?, _ reducer: @escaping (_ state: State, _ message: OutputValue) throws -> State) -> SignalMulti<State> { return SignalMulti<State>(processor: attach { (s, dw) in let ini: SignalReducer<OutputValue, State>.Initializer = { message in switch message { case .success(let m): return Swift.Result { try initializer(m) }.mapError(SignalEnd.other) case .failure(let e): return .failure(e) } } return SignalReducer<OutputValue, State>(source: s, initializer: ini, end: nil, dw: &dw, context: context) { (state: State, message: Signal<OutputValue>.Result) -> Signal<State>.Result in switch message { case .success(let m): return Swift.Result { try reducer(state, m) }.mapError(SignalEnd.other) case .failure(let e): return .failure(e) } } }) } // MARK: - Signal private properties // A struct that stores data associated with the current handler. Under the `Signal` mutex, if the `itemProcessing` flag is acquired, the fields of this struct are filled in using `Signal` and `SignalHandler` data and the contents of the struct can be used by the current thread *outside* the private struct ItemContext<OutputValue> { let context: Exec let direct: Bool let synchronous: Bool let handler: (Result) -> Void let activationCount: Int init(context: Exec, synchronous: Bool, handler: @escaping (Result) -> Void, activationCount: Int) { self.activationCount = activationCount self.context = context if case .direct = context { self.direct = true } else { self.direct = false } self.synchronous = synchronous self.handler = handler } } #if DEBUG_LOGGING var count: Int = { globalCount += 1 return globalCount }() #endif // Protection for all mutable members on this class and any attached `signalHandler`. // NOTE 1: This mutex may be shared between synchronous serially connected `Signal`s (for memory and performance efficiency). // NOTE 2: It is noted that a `DispatchQueue` mutex would be preferrable since it respects libdispatch's QoS, however, it is not possible (as of Swift 4) to use `DispatchQueue` as a mutex without incurring a heap allocated closure capture so `PThreadMutex` is used instead to avoid a factor of 10 performance loss. private final var mutex = os_unfair_lock() fileprivate final func unbalancedLock() { os_unfair_lock_lock(&mutex) } fileprivate final func unbalancedTryLock() -> Bool { return os_unfair_lock_trylock(&mutex) } fileprivate final func unbalancedUnlock() { os_unfair_lock_unlock(&mutex) } fileprivate func sync<R>(execute work: () throws -> R) rethrows -> R { unbalancedLock() defer { unbalancedUnlock() } return try work() } // The graph can be disconnected and reconnected and various actions may occur outside locks, it's helpful to determine which actions are no longer relevant. The `Signal` controls this through `delivery` and `activationCount`. The `delivery` controls the basic lifecycle of a simple connected graph through 4 phases: `.disabled` (pre-connection) -> `.sychronous` (connecting) -> `.normal` (connected) -> `.disabled` (disconnected). fileprivate final var delivery = SignalDelivery.disabled { didSet { handlerContextNeedsRefresh = true } } // The graph can be disconnected and reconnected and various actions may occur outside locks, it's helpful to determine which actions are no longer relevant because they are associated with a phase of a previous connection. // When connected to a preceeding `SignalPredecessor`, `activationCount` is incremented on each connection and disconnection to ensure that actions associated with a previous phase of a previous connection are rejected. // When connected to a preceeding `SignalInput`, `activationCount` is incremented solely when a new `SignalInput` is attached or the current input is invalidated (joined using an `SignalJunction`). fileprivate final var activationCount: Int = 0 { didSet { handlerContextNeedsRefresh = true } } // If there is a preceeding `Signal` in the graph, its `SignalProcessor` is stored in this variable. Note that `SignalPredecessor` is always an instance of `SignalProcessor`. /// If Swift gains an `OrderedSet` type, it should be used here in place of this `Set` and the `sortedPreceeding` accessor, below. fileprivate final var preceeding: Set<OrderedSignalPredecessor> // The destination of this `Signal`. This value is `nil` on construction. fileprivate final weak var signalHandler: SignalHandler<OutputValue>? = nil { didSet { handlerContextNeedsRefresh = true } } fileprivate final var handlerContextNeedsRefresh = true // Queue of values pending dispatch (NOTE: the current `item` is not stored in the queue) // Normally the queue is FIFO but when an `Signal` has multiple inputs, the "activation" from each input will be considered before any post-activation inputs. private final var queue = Deque<Result>() // A `holdCount` may indefinitely block the queue for one of two reasons: // 1. a `SignalNext` is retained outside its handler function for asynchronous processing of an item // 2. a `SignalCapture` handler has captured the activation but a `Signal` to receive the remainder is not currently connected // Accordingly, the `holdCount` should only have a value in the range [0, 2] private final var holdCount: UInt8 = 0 // When a `Result` is popped from the queue and the handler is being invoked, the `itemProcessing` is set to `true`. The effect is equivalent to `holdCount`. private final var itemProcessing: Bool = false // Notifications for the inverse of `delivery == .disabled`, accessed exclusively through the `generate` constructor. Can be used for lazy construction/commencement, resetting to initial state on graph disconnect and reconnect or cleanup after graph deletion. // A signal is used here instead of a simple function callback since re-entrancy-safe queueing and context delivery are needed. // WARNING: this is actually a (Signal<SignalInput<OutputValue>?>, SignalEndpont<SignalInput<OutputValue>?>)? but we use `Any` to avoid huge optimization overheads. private final var newInputSignal: (Signal<Any?>, SignalOutput<Any?>)? = nil // A monotonically increasing counter that is incremented every time the set of connected, preceeding handlers changes. This value is used to reject predecessors that are not up-to-date with the latest graph structure (i.e. have been asynchronously removed or invalidated). private final var preceedingCount: Int = 0 // This is a cache of values that can be read outside the lock by the current owner of the `itemProcessing` flag. private final var handlerContext = ItemContext<OutputValue>(context: .direct, synchronous: false, handler: { _ in }, activationCount: 0) // MARK: - Signal private functions // Invokes `removeAllPreceedingInternal` if and only if the `forDisconnector` matches the current `preceeding.first` // // - Parameter forDisconnector: the disconnector requesting this change // - Returns: if the predecessor matched, then a new `SignalInput<OutputValue>` for this `Signal`, otherwise `nil`. fileprivate final func newInput(forDisconnector: SignalProcessor<OutputValue, OutputValue>) -> SignalInput<OutputValue>? { var dw = DeferredWork() let result = sync { () -> SignalInput<OutputValue>? in if preceeding.count == 1, let p = preceeding.first?.base, p === forDisconnector { removeAllPreceedingInternal(dw: &dw) return SignalInput(signal: self, activationCount: activationCount) } else { return nil } } dw.runWork() return result } /// If this `Signal` can attach a new handler, this function runs the provided closure (which is expected to construct and set the new handler) and returns the handler. If this `Signal` can't attach a new handler, returns the result of running the closure inside the mutex of a separate preclosed `Signal`. /// /// This method serves three purposes: /// 1) It enforces the idea that the `signalHandler` should be constructed under this `Signal`'s mutex, providing the `DeferredWork` required by the `signalHandler` constructor interface. /// 2) It enforces the rule that multiple listen attempts should be immediately closed with a `.duplicate` error /// 3) It allows abstraction over the actual `Signal` used for attachment (self for single listener and a newly created `Signal` for multi listener). /// /// - Parameter constructor: the handler constructor function /// - Returns: the result from the constructor (typically an SignalHandler) fileprivate func attach<R>(constructor: (Signal<OutputValue>, inout DeferredWork) -> R) -> R where R: SignalHandler<OutputValue> { var dw = DeferredWork() let result: R? = sync { self.signalHandler == nil ? constructor(self, &dw) : nil } dw.runWork() if let r = result { return r } else { preconditionFailure("Multiple outputs added to single listener Signal.") } } /// Avoids complications with non-reentrant /// /// - Parameter context: the context upon which `asyncRelativeContext` will be called /// - Returns: possibly `self`, possibly `self` a transform that shifts to the `asyncRelativeContext`. fileprivate func returnToGlobalIfNeeded(context: Exec) -> Signal<OutputValue> { if context.type.isImmediateAlways || context.type.isReentrant { return self } else { return self.transform(context: context.relativeAsync(), { .single($0) }) } } /// Constructor for a `Signal` that is the output for a `SignalProcessor`. /// /// - Parameter processor: input source for this `Signal` fileprivate init<U>(processor: SignalProcessor<U, OutputValue>) { preceedingCount += 1 preceeding = [processor.wrappedWithOrder(preceedingCount)] #if DEBUG_LOGGING print("\(type(of: self)): \(self.count) created") #endif if !(self is SignalMulti<OutputValue>) { var dw = DeferredWork() sync { // Since this function must be used only in cases where the processor is *also* new, this can't be `duplicate` or `loop` try! processor.outputAddedSuccessorInternal(self, param: nil, activationCount: nil, dw: &dw) } dw.runWork() } } // Connects this `Signal` to a preceeding SignalPredecessor. Other connection functions must go through this. // // - Parameters: // - newPreceeding: the preceeding SignalPredecessor to add // - param: this function may invoke `outputAddedSuccessorInternal` internally. If it does this `param` will be passed as the `param` for that function. // - dw: required // - Throws: any error from `outputAddedSuccessorInternal` invoked on `newPreceeding` fileprivate final func addPreceedingInternal(_ newPreceeding: SignalPredecessor, param: Any?, dw: inout DeferredWork) throws { preceedingCount += 1 let wrapped = newPreceeding.wrappedWithOrder(preceedingCount) preceeding.insert(wrapped) do { try newPreceeding.outputAddedSuccessorInternal(self, param: param, activationCount: (delivery.isDisabled || preceeding.count == 1) ? Optional<Int>.none : Optional<Int>(activationCount), dw: &dw) if !delivery.isDisabled, preceeding.count == 1 { updateActivationInternal(andInvalidateAllPrevious: true, dw: &dw) if !delivery.isSynchronous { let ac = activationCount dw.append { var dw = DeferredWork() self.sync { if ac == self.activationCount { newPreceeding.outputCompletedActivationSuccessorInternal(self, dw: &dw) } } dw.runWork() } } } } catch { preceeding.remove(wrapped) throw error } } // Removes a (potentially) non-unique predecessor. Used only from `SignalMergeSet` and `SignalMergeProcessor`. This is one of two, independent, functions for removing preceeding. The other being `removeAllPreceedingInternal`. // // - Parameters: // - oldPreceeding: the predecessor to remove // - dw: required fileprivate final func removePreceedingWithoutInterruptionInternal(_ oldPreceeding: SignalPredecessor, dw: inout DeferredWork) -> Bool { if preceeding.remove(oldPreceeding.wrappedWithOrder(0)) != nil { oldPreceeding.outputRemovedSuccessorInternal(self, dw: &dw) return true } return false } // Removes all predecessors and invalidate all previous inputs. This is one of two, independent, functions for removing preceeding. The other being `removePreceedingWithoutInterruptionInternal`. // // - Parameters: // - oldPreceeding: the predecessor to remove // - dw: required fileprivate final func removeAllPreceedingInternal(dw: inout DeferredWork) { if preceeding.count > 0 { dw.append { [preceeding] in withExtendedLifetime(preceeding) {} } // Careful to use *sorted* preceeding to propagate graph changes deterministically sortedPreceedingInternal.forEach { $0.base.outputRemovedSuccessorInternal(self, dw: &dw) } preceeding = [] } updateActivationInternal(andInvalidateAllPrevious: true, dw: &dw) } // The primary `send` function (although the `push` functions do also send). // Sends `result`, assuming `fromInput` matches the current `self.input` and `self.delivery` is enabled // // - Parameters: // - result: the value or error to pass to any attached handler // - predecessor: the `SignalInput` or `SignalNext` delivering the handler // - activationCount: the activation count from the predecessor to match against internal value // - activated: whether the predecessor is already in `normal` delivery mode // - Returns: `nil` on success. Non-`nil` values include `SignalSendError.disconnected` if the `predecessor` or `activationCount` fail to match, `SignalSendError.inactive` if the current `delivery` state is `.disabled`. @discardableResult @usableFromInline final func send(result: Result, predecessor: Unmanaged<AnyObject>?, activationCount: Int, activated: Bool) -> SignalSendError? { unbalancedLock() guard isCurrent(predecessor, activationCount) else { unbalancedUnlock() // Retain the result past the end of the lock withExtendedLifetime(result) {} return SignalSendError.disconnected } switch delivery { case .normal: if holdCount == 0 && itemProcessing == false { assert(queue.isEmpty) break } else { queue.append(result) unbalancedUnlock() return nil } case .synchronous(let count): if activated { queue.append(result) unbalancedUnlock() return nil } else if count == 0, holdCount == 0, itemProcessing == false { break } else { queue.insert(result, at: count) delivery = .synchronous(count + 1) unbalancedUnlock() return nil } case .disabled: unbalancedUnlock() // Retain the result past the end of the lock withExtendedLifetime(result) {} return SignalSendError.inactive } assert(holdCount == 0 && itemProcessing == false) if handlerContextNeedsRefresh { var dw = DeferredWork() let hasHandler = refreshItemContextInternal(&dw) if hasHandler { itemProcessing = true } unbalancedUnlock() // We need to be extremely careful that any previous handlers, replaced in the `refreshItemContextInternal` function are released *here* if we're going to re-enter the lock and that we've *already* acquired the `itemProcessing` Bool. There's a little bit of dancing around in this `if handlerContextNeedsRefresh` block to ensure these two things are true. dw.runWork() if !hasHandler { return SignalSendError.inactive } } else { itemProcessing = true unbalancedUnlock() } #if DEBUG_LOGGING print("\(type(of: self)): \(self.count) emitted \(result))") #endif if handlerContext.direct, case .success = result { handlerContext.handler(result) unbalancedLock() if handlerContextNeedsRefresh || !queue.isEmpty { unbalancedUnlock() specializedSyncPop() } else { itemProcessing = false unbalancedUnlock() } } else { dispatch(result) } return nil } // A secondary send function used to push values and possibly and end-of-stream error onto the `newInputSignal`. The push is not handled immediately but is deferred until the `DeferredWork` runs. Since values are *always* queued, this is less efficient than `send` but it avoids re-entrancy into self if the `newInputSignal` immediately tries to send values back to us. // // - Parameters: // - values: pushed onto this `Signal`'s queue // - end: pushed onto this `Signal`'s queue // - activationCount: activationCount of the sender (must match the internal value) // - dw: used to dispatch the signal safely outside the parent's mutex fileprivate final func push(values: Array<OutputValue>, end: SignalEnd?, activationCount: Int, activated: Bool, dw: inout DeferredWork) { sync { guard self.activationCount == activationCount else { return } pushInternal(values: values, end: end, activated: activated, dw: &dw) } } // A secondary send function used to push activation values and activation errors. Since values are *always* queued, this is less efficient than `send` but it can safely be invoked inside mutexes. // // - Parameters: // - values: pushed onto this `Signal`'s queue // - end: pushed onto this `Signal`'s queue // - dw: used to dispatch the signal safely outside the parent's mutex fileprivate final func pushInternal(values: Array<OutputValue>, end: SignalEnd?, activated: Bool, dw: inout DeferredWork) { assert(unbalancedTryLock() == false) guard values.count > 0 || end != nil else { dw.append { withExtendedLifetime(values) {} withExtendedLifetime(end) {} } return } if !activated, case .synchronous(let count) = delivery { assert(count == 0) delivery = .synchronous(values.count + (end != nil ? 1 : 0)) } for v in values { queue.append(.success(v)) } if let e = end { queue.append(.failure(e)) } resumeIfPossibleInternal(dw: &dw) } // Used in SignalCapture.handleSynchronousToNormalInternal to handle a situation where a deactivation and reactivation occurs *while* `itemProcessing` so the next capture is in the queue instead of being captured. This function extracts the queued value for capture before transition to normal. // // - Returns: the queued items under the synchronous count. fileprivate final func pullQueuedSynchronousInternal() -> (values: Array<OutputValue>, end: SignalEnd?) { if case .synchronous(let count) = delivery, count > 0 { var values = Array<OutputValue>() var end: SignalEnd? = nil for _ in 0..<count { switch queue.removeFirst() { case .success(let v): values.append(v) case .failure(let e): end = e } } delivery = .synchronous(0) return (values, end) } return ([], nil) } // Increment the `holdCount` fileprivate final func blockInternal() { assert(unbalancedTryLock() == false) assert(holdCount <= 1) holdCount += 1 } // Decrement the `holdCount`, if the `activationCountAtBlock` provided matches `self.activationCount` // // NOTE: the caller must resume processing if holdCount reaches zero and there are queued items. /// /// - Parameter activationCountAtBlock: must match the internal value or the block request will be ignored fileprivate final func unblockInternal(activationCountAtBlock: Int) { guard self.activationCount == activationCountAtBlock else { return } assert(unbalancedTryLock() == false) assert(holdCount >= 1 && holdCount <= 2) holdCount -= 1 } // If the holdCount is zero and there are queued items, increments the hold count immediately and starts processing in the deferred work. /// /// - Parameter dw: required fileprivate final func resumeIfPossibleInternal(dw: inout DeferredWork) { if holdCount == 0, itemProcessing == false, !queue.isEmpty { if !refreshItemContextInternal(&dw) { // The weakly held handler has asynchronously released. return } itemProcessing = true dw.append { if let r = self.pop() { self.dispatch(r) } } } } // Decrement the `holdCount`, if the `activationCount` provided matches `self.activationCount` and resume processing if the `holdCount` reaches zero and there are items in the queue. /// /// - Parameter activationCount: must match the internal value or the block request will be ignored fileprivate final func unblock(activationCountAtBlock: Int) { var dw = DeferredWork() sync { unblockInternal(activationCountAtBlock: activationCountAtBlock) resumeIfPossibleInternal(dw: &dw) } dw.runWork() } // Changes the value of the `self.delivery` instance variable and handles associated lifecycle updates (like incrementing the activation count). // /// - Parameters: /// - newDelivery: new value for `self.delivery` /// - dw: required fileprivate final func changeDeliveryInternal(newDelivery: SignalDelivery, dw: inout DeferredWork) { assert(unbalancedTryLock() == false) assert(newDelivery.isDisabled != delivery.isDisabled || newDelivery.isSynchronous != delivery.isSynchronous) #if DEBUG_LOGGING print("\(type(of: self)): \(self.count) delivery changed from \(delivery) to \(newDelivery)") #endif let oldDelivery = delivery delivery = newDelivery switch delivery { case .normal: if oldDelivery.isSynchronous { // Careful to use *sorted* preceeding to propagate graph changes deterministically for p in sortedPreceedingInternal { p.base.outputCompletedActivationSuccessorInternal(self, dw: &dw) } } resumeIfPossibleInternal(dw: &dw) newInputSignal?.0.push(values: [SignalInput(signal: self, activationCount: activationCount)], end: nil, activationCount: 0, activated: true, dw: &dw) case .synchronous: if preceeding.count > 0 { updateActivationInternal(andInvalidateAllPrevious: false, dw: &dw) } case .disabled: updateActivationInternal(andInvalidateAllPrevious: true, dw: &dw) _ = newInputSignal?.0.push(values: [Optional<SignalInput<OutputValue>>.none], end: nil, activationCount: 0, activated: true, dw: &dw) } } /// Constructor for signal graph head. Called from `create`. private init() { preceeding = [] #if DEBUG_LOGGING print("\(type(of: self)): \(self.count) created") #endif } // Need to close the `newInputSignal` and detach from all predecessors on deinit. deinit { newInputSignal?.0.send(result: .failure(.cancelled), predecessor: nil, activationCount: 0, activated: true) var dw = DeferredWork() sync { removeAllPreceedingInternal(dw: &dw) } dw.runWork() } // Internal wrapper used by the `combine` functions to ignore error `Results` (which would only be due to graph changes between internal nodes) and process the values with the user handler. // // - Parameter handler: the user handler @discardableResult private static func successProcessor<U, V>(_ processor: @escaping (U) -> Signal<V>.Next) -> (Signal<U>.Result) -> Signal<V>.Next { return { (r: Signal<U>.Result) in switch r { case .success(let v): return processor(v) case .failure(let e): return .single(.failure(e)) } } } // Internal wrapper used by the `combine(initialState:...)` functions to ignore error `Results` (which would only be due to graph changes between internal nodes) and process the values with the user handler. // // - Parameter handler: the user handler @discardableResult private static func successProcessorWithState<S, U, V>(_ processor: @escaping (inout S, U) -> Signal<V>.Next) -> (inout S, Signal<U>.Result) -> Signal<V>.Next { return { (s: inout S, r: Signal<U>.Result) in switch r { case .success(let v): return processor(&s, v) case .failure(let e): return .single(.failure(e)) } } } /// Returns a copy of the preceeding set, sorted by "order". This allows deterministic sending of results through the graph – older connections are prioritized over newer. private var sortedPreceedingInternal: Array<OrderedSignalPredecessor> { return preceeding.sorted(by: { (a, b) -> Bool in return a.order < b.order }) } // A wrapper around addPreceedingInternal for use outside the Only used by the `combine` functions (which is why it returns `self` – it's a syntactic convenience in those methods). // // - Parameter processor: the preceeding SignalPredecessor to add // - Returns: self (for syntactic convenience in the `combine` methods) private final func addPreceeding(processor: SignalPredecessor) -> Signal<OutputValue> { var dw = DeferredWork() sync { // Since this is for use only by the `combine` functions, it cann't be `duplicate` or `loop` try! addPreceedingInternal(processor, param: nil, dw: &dw) } dw.runWork() return self } // Increment the activation count. // // - Parameters: // - andInvalidateAllPrevious: if true, removes all items from the queue (should be false only when transitioning from synchronous to normal). // - dw: required private final func updateActivationInternal(andInvalidateAllPrevious: Bool, dw: inout DeferredWork) { assert(unbalancedTryLock() == false) activationCount = activationCount &+ 1 if andInvalidateAllPrevious { let oldItems = Array<Result>(queue) dw.append { withExtendedLifetime(oldItems) {} } queue.removeAll() holdCount = 0 } else { assert(holdCount == 0) } switch delivery { case .synchronous: if andInvalidateAllPrevious, let h = signalHandler { // Any outstanding end activation won't resolve now so we need to apply it directly. h.endActivationInternal(dw: &dw) return } fallthrough case .normal: // Careful to use *sorted* preceeding to propagate graph changes deterministically for p in sortedPreceedingInternal { p.base.outputActivatedSuccessorInternal(self, activationCount: activationCount, dw: &dw) } case .disabled: // Careful to use *sorted* preceeding to propagate graph changes deterministically for p in sortedPreceedingInternal { p.base.outputDeactivatedSuccessorInternal(self, dw: &dw) } } } // Tests whether a `Result` from a `predecessor` with `activationCount` should be accepted or rejected. // // - Parameters: // - predecessor: the source of the `Result` // - activationCount: the `activationCount` when the source was connected // - Returns: true if `preceeding` contains `predecessor` and `self.activationCount` matches `activationCount` private final func isCurrent(_ predecessor: Unmanaged<AnyObject>?, _ activationCount: Int) -> Bool { if activationCount != self.activationCount { return false } if preceeding.count == 1, let expected = preceeding.first?.base { return predecessor?.takeUnretainedValue() === expected } else if preceeding.count == 0 { return predecessor == nil } guard let p = predecessor?.takeUnretainedValue() as? SignalPredecessor else { return false } return preceeding.contains(p.wrappedWithOrder(0)) } // The `handlerContext` holds information uniquely used by the currently processing item so it can be read outside the This may only be called immediately before calling `blockInternal` to start a processing item (e.g. from `send` or `resume`. // // - Parameter dw: required // - Returns: false if the `signalHandler` was `nil`, true otherwise. private final func refreshItemContextInternal(_ dw: inout DeferredWork) -> Bool { assert(unbalancedTryLock() == false) assert(holdCount == 0 && itemProcessing == false) if handlerContextNeedsRefresh { if let h = signalHandler { dw.append { [handlerContext] in withExtendedLifetime(handlerContext) {} } handlerContext = ItemContext(context: h.context, synchronous: delivery.isSynchronous, handler: h.handler, activationCount: activationCount) handlerContextNeedsRefresh = false } else { return false } } return true } // Sets the `handlerContext` back to an "idle" state (releasing any handler closure and setting `activationCount` to zero. // This function may be called only from `specializedSyncPop` or `pop`. /// /// - Returns: an empty/idle `ItemContext` private final func clearItemContextInternalToExternal(itemOnly: Bool) { assert(unbalancedTryLock() == false) itemProcessing = false if itemOnly { unbalancedUnlock() } else { var dw = DeferredWork() let oldContext = handlerContext handlerContext = ItemContext<OutputValue>(context: .direct, synchronous: false, handler: { _ in }, activationCount: 0) resumeIfPossibleInternal(dw: &dw) unbalancedUnlock() withExtendedLifetime(oldContext) {} dw.runWork() } } // Invoke the user handler and deactivates the `Signal` if `result` is a `failure`. // // - Parameter result: passed to the `handlerContext.handler` private final func invokeHandler(_ result: Result) { handlerContext.handler(result) if case .failure = result { var dw = DeferredWork() sync { if handlerContext.activationCount == activationCount, !delivery.isDisabled { signalHandler?.deactivateInternal(dueToLackOfOutputs: false, dw: &dw) } } dw.runWork() } } // Dispatches the `result` to the current handler in the appropriate context then pops the next `result` and attempts to invoke the handler with the next result (if any) // // - Parameter result: for sending to the handler private final func dispatch(_ result: Result) { if case .direct = handlerContext.context { invokeHandler(result) specializedSyncPop() } else if handlerContext.context.type.isImmediateInCurrentContext { for r in sequence(first: result, next: { _ in self.pop() }) { invokeHandler(r) } } else if handlerContext.synchronous { for r in sequence(first: result, next: { _ in self.pop() }) { handlerContext.context.invokeSync{ invokeHandler(r) } } } else { // Perform asynchronous transition to the appropriate context let ac = activationCount handlerContext.context.invoke { // Ensure that the signal hasn't been cancelled while we were transitioning to this context self.unbalancedLock() guard ac == self.activationCount else { self.clearItemContextInternalToExternal(itemOnly: false) return } self.unbalancedUnlock() for r in sequence(first: result, next: { _ in self.pop() }) { self.invokeHandler(r) } } } } /// Gets the next item from the queue for processing and updates the `ItemContext`. /// /// - Returns: the next result for processing, if any private final func pop() -> Result? { unbalancedLock() assert(itemProcessing == true) guard !handlerContextNeedsRefresh else { clearItemContextInternalToExternal(itemOnly: false) return nil } if !queue.isEmpty, holdCount == 0 { switch delivery { case .synchronous(let count) where count == 0: break case .synchronous(let count): delivery = .synchronous(count - 1) fallthrough default: let result = queue.removeFirst() unbalancedUnlock() return result } } clearItemContextInternalToExternal(itemOnly: true) return nil } /// An optimized version of `pop(_:)` used when context is .direct. The semantics are slightly different: this doesn't pop a result off the queue... rather, it looks to see if there's anything in the queue and handles it internally if there is. This allows optimization for the expected case where there's nothing in the queue. private final func specializedSyncPop() { unbalancedLock() assert(itemProcessing == true) if handlerContextNeedsRefresh { clearItemContextInternalToExternal(itemOnly: false) } else if !queue.isEmpty { unbalancedUnlock() while let r = pop() { invokeHandler(r) } } else { itemProcessing = false unbalancedUnlock() } } } /// `SignalMulti<OutputValue>` is the only subclass of `Signal<OutputValue>`. It represents a `Signal<OutputValue>` that allows attaching multiple listeners (a normal `Signal<OutputValue>` is "single owner" and will immediately close any subsequent listeners after the first with a `SignalBindError.duplicate` error). /// This class is not constructed directly but is instead created from one of the `SignalMulti<OutputValue>` returning functions on `Signal<OutputValue>`, including `playback()`, `multicast()` and `continuous()`. public final class SignalMulti<OutputValue>: Signal<OutputValue> { private let spawnSingle: (SignalPredecessor) -> Signal<OutputValue> fileprivate override init<U>(processor: SignalProcessor<U, OutputValue>) { assert(processor.multipleOutputsPermitted, "Construction of SignalMulti from a single output processor is illegal.") spawnSingle = { proc in let p = proc as! SignalProcessor<U, OutputValue> return Signal<OutputValue>(processor: p).returnToGlobalIfNeeded(context: p.context) } super.init(processor: processor) } fileprivate override func attach<R>(constructor: (Signal<OutputValue>, inout DeferredWork) -> R) -> R where R: SignalHandler<OutputValue> { return spawnSingle(preceeding.first!.base).attach(constructor: constructor) } } /// An `SignalInput` is used to send values to the "head" `Signal`s in a signal graph. It is created using the `Signal<T>.create()` function. public class SignalInput<InputValue>: Lifetime, SignalInputInterface { @usableFromInline final var signal: Signal<InputValue>? @usableFromInline final let activationCount: Int public var input: SignalInput<InputValue> { return self } // Create a new `SignalInput` (usually created by the `Signal<T>.create` function) // // - Parameters: // - signal: the destination signal // - activationCount: to be sent with each send to the signal fileprivate init(signal: Signal<InputValue>, activationCount: Int) { self.signal = signal self.activationCount = activationCount } /// The primary signal sending function /// /// - Parameter result: the value or error to send, composed as a `Result` /// - Returns: `nil` on success. Non-`nil` values include `SignalSendError.disconnected` if the `predecessor` or `activationCount` fail to match, `SignalSendError.inactive` if the current `delivery` state is `.disabled`. @discardableResult @inlinable public func send(result: Result<InputValue, SignalEnd>) -> SignalSendError? { guard let s = signal else { return SignalSendError.disconnected } return s.send(result: result, predecessor: nil, activationCount: activationCount, activated: true) } /// The purpose for this method is to obtain a true `SignalInput` (instead of a `SignalMultiInput` or `SignalMergedInput`. A true `SignalInput` is faster for multiple send operations and is needed internally by the `bind` methods. /// The base `SignalInput` implementation returns `self`. public func singleInput() -> SignalInput<InputValue> { return self } /// Implementation of `Lifetime` that sends a `SignalComplete.cancelled`. You wouldn't generally invoke this yourself; it's intended to be invoked if the `SignalInput` owner is released and the `SignalInput` is no longer retained. public func cancel() { send(result: .failure(.cancelled)) } fileprivate func cancelOnDeinit() { cancel() } deinit { cancelOnDeinit() } } // If `Signal<OutputValue>` is a delivery channel, then `SignalHandler` is the destination to which it delivers. // While the base `SignalHandler<OutputValue>` is not "abstract" in any technical sense, it doesn't do anything by default and offers no public members. Subclasses include `SignalOutput` (the user "exit" point for signal results), `SignalProcessor` (used for transforming signals between instances of `Signal<OutputValue>`), `SignalJunction` (for enabling dynamic graph connection and disconnections). // `SignalHandler<OutputValue>` is never directly created or held by users of the CwlSignal library. It is implicitly created when one of the listening or transformation methods on `Signal<OutputValue>` are invoked. public class SignalHandler<OutputValue> { fileprivate final let source: Signal<OutputValue> fileprivate final let context: Exec fileprivate final var handler: (Result<OutputValue, SignalEnd>) -> Void { didSet { source.handlerContextNeedsRefresh = true } } // Base constructor sets the `source`, `context` and `handler` and implicitly activates if required. // // - Parameters: // - source: a `SignalHandler` is attached to its predecessor `Signal` for its lifetime // - dw: used for performing activation outside any enclosing mutex, if necessary // - context: where the `handler` function should be invoked fileprivate init(source: Signal<OutputValue>, dw: inout DeferredWork, context: Exec) { // Must be passed a `Signal` that does not already have a `signalHandler` assert(source.signalHandler == nil && source.unbalancedTryLock() == false) self.source = source self.context = context self.handler = { _ in } // Connect to the `Signal` source.signalHandler = self // Set the initial handler self.handler = initialHandlerInternal() #if DEBUG_LOGGING print("\(type(of: self)): created as the processor for \(source.count)") #endif // Propagate immediately if activeWithoutOutputsInternal { if activateInternal(dw: &dw) { let count = self.source.activationCount dw.append { self.endActivation(activationCount: count) } } } } // Default behavior does nothing prior to activation fileprivate func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) return { _ in } } // Convenience wrapper around the mutex from the `Signal` which is used to protect the handler // // - Parameter execute: the work to perform inside the mutex // - Returns: the result from the `execute closure // - Throws: basic rethrow from the `execute` closure fileprivate final func sync<OutputValue>(execute: () throws -> OutputValue) rethrows -> OutputValue { source.unbalancedLock() defer { source.unbalancedUnlock() } return try execute() } // True if this node activates predecessors even when it has no active successors fileprivate var activeWithoutOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) return false } deinit { var dw = DeferredWork() sync { if !source.delivery.isDisabled { source.changeDeliveryInternal(newDelivery: .disabled, dw: &dw) } source.signalHandler = nil } dw.runWork() } // Activation changes the delivery, based on whether there are preceeding `Signal`s. // If delivery is changed to synchronous, `endActivation` must be called in the deferred work. /// /// - Parameter dw: required /// - Returns: true if a transition to `.synchronous` occurred fileprivate final func activateInternal(dw: inout DeferredWork) -> Bool { assert(source.unbalancedTryLock() == false) if source.delivery.isDisabled { source.changeDeliveryInternal(newDelivery: .synchronous(0), dw: &dw) return true } return false } // Completes the transition to `.normal` delivery at the end of the `.synchronous` stage. /// /// - Parameter dw: required fileprivate final func endActivationInternal(dw: inout DeferredWork) { if source.delivery.isSynchronous { handleSynchronousToNormalInternal(dw: &dw) source.changeDeliveryInternal(newDelivery: .normal, dw: &dw) } } // Completes the transition to `.normal` delivery at the end of the `.synchronous` stage. /// /// - Parameter activationCount: must match the internal value or the attempt will be rejected fileprivate final func endActivation(activationCount: Int) { var dw = DeferredWork() sync { guard source.activationCount == activationCount else { return } endActivationInternal(dw: &dw) } dw.runWork() } // If this property returns false, attempts to connect more than one output will be rejected. The rejection information is used primarily by SignalJunction which performs disconnect and bind as two separate steps so it needs the rejection to ensure two threads haven't tried to bind simultaneously. fileprivate var multipleOutputsPermitted: Bool { return false } // Override point invoked from `endActivationInternal` used in `SignalCapture` // - Parameter dw: required fileprivate func handleSynchronousToNormalInternal(dw: inout DeferredWork) { } // Changes delivery to disabled *and* resets the handler to the initial handler. // - Parameter dw: required fileprivate final func deactivateInternal(dueToLackOfOutputs: Bool, dw: inout DeferredWork) { assert(source.unbalancedTryLock() == false) if !activeWithoutOutputsInternal || !dueToLackOfOutputs { source.changeDeliveryInternal(newDelivery: .disabled, dw: &dw) dw.append { [handler] in withExtendedLifetime(handler) {} // Outputs may release themselves on deactivation so we need to keep ourselves alive until outside the lock withExtendedLifetime(self) {} } if !activeWithoutOutputsInternal { handler = initialHandlerInternal() } else { handler = { _ in } } } } } // A hashable wrapper around an SignalPredecessor existential that also embeds an order value to allow ordering // NOTE 1: the order is *not* part of the equality or hashValue so a wrapper can be created with an arbitrary order to test for the presence of a given SignalPredecessor. // NOTE 2: if Swift gains an OrderedSet, it might be possible to replace this with `Hashable` conformance on `SignalPredecessor`. fileprivate struct OrderedSignalPredecessor: Hashable { let base: SignalPredecessor let order: Int init(base: SignalPredecessor, order: Int) { self.base = base self.order = order } func hash(into hasher: inout Hasher) { hasher.combine(Int(bitPattern: Unmanaged<AnyObject>.passUnretained(base).toOpaque())) } static func ==(lhs: OrderedSignalPredecessor, rhs: OrderedSignalPredecessor) -> Bool { return lhs.base === rhs.base } } // A protocol used for communicating from successor `Signal`s to predecessor `SignalProcessor`s in the signal graph. // Used for connectivity and activation. fileprivate protocol SignalPredecessor: AnyObject { func outputActivatedSuccessorInternal(_ successor: AnyObject, activationCount: Int, dw: inout DeferredWork) func outputCompletedActivationSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) func outputDeactivatedSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) func outputAddedSuccessorInternal(_ successor: AnyObject, param: Any?, activationCount: Int?, dw: inout DeferredWork) throws func outputRemovedSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) func predecessorsSuccessorInternal(loopCheck: AnyObject) -> Bool func outputSignals<U>(ofType: U.Type) -> [Signal<U>] var loopCheckValue: AnyObject { get } func wrappedWithOrder(_ order: Int) -> OrderedSignalPredecessor } // Easy construction of a hashable wrapper around an SignalPredecessor existential extension SignalPredecessor { func wrappedWithOrder(_ order: Int) -> OrderedSignalPredecessor { return OrderedSignalPredecessor(base: self, order: order) } } // All `Signal`s, except those with output handlers, are fed to another `Signal`. A `SignalProcessor` is how this is done. This is the abstract base for all handlers that connect to another `Signal`. The default implementation can only connect to a single output (concrete subclass `SignalMultiprocessor` is used for multiple outputs) but a majority of the architecture for any number of outputs is contained in this class. // This class allows its outputs to have a different value type compared to the Signal for this class, although only SignalTransformer, SignalTransformerWithState and SignalCombiner take advantage – all other subclasses derive from SignalProcessor<OutputValue, OutputValue>. public class SignalProcessor<OutputValue, U>: SignalHandler<OutputValue>, SignalPredecessor { typealias OutputsArray = Array<(destination: Weak<Signal<U>>, activationCount: Int?)> var outputs = OutputsArray() // Common implementation for a nextHandlerInternal. Currently used only from SignalCacheUntilActive and SignalCombiner // // - Parameters: // - processor: the `SignalProcessor` instance // - transform: the transformation applied from input to output // - Returns: a function usable as the return value to `nextHandlerInternal` fileprivate static func simpleNext(processor: SignalProcessor<OutputValue, U>, transform: @escaping (Result<OutputValue, SignalEnd>) -> Result<U, SignalEnd>) -> (Result<OutputValue, SignalEnd>) -> Void { assert(processor.source.unbalancedTryLock() == false) guard let output = processor.outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return processor.initialHandlerInternal() } let activated = processor.source.delivery.isNormal let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(processor) return { [weak outputSignal] r in outputSignal?.send(result: transform(r), predecessor: predecessor, activationCount: ac, activated: activated) } } // Determines if a `Signal` is one of the current outputs. // // - Parameter signal: possible output // - Returns: true if `signal` is contained in the outputs fileprivate final func isOutputInternal(_ signal: Signal<U>) -> Int? { assert(signal.unbalancedTryLock() == false) for (i, o) in outputs.enumerated() { if let d = o.destination.value, d === signal { return i } } return nil } /// Identity used for checking loops (needs to be the mutex since the mutex is shared vertically through the graph, any traversal looking for potential loops could deadlock before noticing a loop with any other value) fileprivate final var loopCheckValue: AnyObject { return source } // Performs a depth-first graph traversal looking for the specified `SignalPredecessor` // // - Parameter contains: the search value // - Returns: true if `contains` was found, false otherwise func predecessorsSuccessorInternal(loopCheck: AnyObject) -> Bool { // Only check the value when successors don't share the mutex (i.e. when we have a boundary of some kind). if loopCheck === self.loopCheckValue { return true } var result = false runSuccesorAction { // Don't need to traverse sortedPreceeding (unsorted is fine for an ancestor check) for p in source.preceeding { if p.base.predecessorsSuccessorInternal(loopCheck: loopCheck) { result = true return } } } return result } /// Returns the list of outputs, assuming they match the provided type. This method is used when attempting to remove a SignalMulti from the list of inputs to a SignalInputMulti since the whole list of outputs may need to be searched to find one that's actually connected to the SignalInputMulti. /// /// - Parameter ofType: specifies the input type of the SignalInputMulti (it will always match but we follow the type system, rather than force matching. /// - Returns: a strong array of outputs func outputSignals<U>(ofType: U.Type) -> [Signal<U>] { return sync { return outputs.compactMap { $0.destination.value as? Signal<U> } } } // Pushes activation values to newly joined outputs. By default, there is no activation so this function is intended to be overridden. Currently overridden by `SignalMultiProcessor` and `SignalCacheUntilActive`. // // - Parameters: // - index: identifies the output // - dw: required by pushInternal fileprivate func sendActivationToOutputInternal(index: Int, dw: inout DeferredWork) { } // When an output changes activation, this function is called. // // - Parameters: // - index: index of the activation changed output // - activationCount: new count received // - dw: required // - Returns: any response from `activateInternal` (true if started activating) fileprivate final func updateOutputInternal(index: Int, activationCount: Int?, dw: inout DeferredWork) -> Bool { assert(source.unbalancedTryLock() == false) assert(outputs[index].activationCount != activationCount) let previous = anyActiveOutputsInternal outputs[index].activationCount = activationCount dw.append { [handler] in withExtendedLifetime(handler) {} } handler = nextHandlerInternal() var result = false if activationCount != nil { sendActivationToOutputInternal(index: index, dw: &dw) result = activateInternal(dw: &dw) } else if activationCount == nil && !source.delivery.isDisabled && !activeWithoutOutputsInternal { var anyStillActive = false for o in outputs { if o.activationCount != nil { anyStillActive = true break } } if !anyStillActive { deactivateInternal(dueToLackOfOutputs: true, dw: &dw) } } if activationCount != nil, !previous { firstOutputActivatedInternal(dw: &dw) } else if activationCount == nil, !anyActiveOutputsInternal { lastOutputDeactivatedInternal(dw: &dw) } return result } // Helper function that applies the mutex around the supplied function, if needed. // // - parameter action: function to be run inside the mutex private final func runSuccesorAction(action: () -> Void) { sync { action() } } /// Helper function used before and after activation to determine if this handler should activate or deactivated. private final var anyActiveOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) for o in outputs { if o.destination.value != nil && o.activationCount != nil { return true } } return false } /// Overrideable function to attach behaviors to activation by an output /// /// - parameter dw: required fileprivate func firstOutputActivatedInternal(dw: inout DeferredWork) { } /// Overrideable function to attach behaviors to deactivation by an output /// /// - parameter dw: required fileprivate func lastOutputDeactivatedInternal(dw: inout DeferredWork) { } /// Overrideable function to attach behaviors to output removal /// /// - parameter dw: required fileprivate func lastOutputRemovedInternal(dw: inout DeferredWork) { } // Invoked from successor `Signal`s when they activate // // - Parameters: // - successor: a `Signal` (must be a Signal<U>) // - activationCount: new activation count value for the `Signal` // - dw: required fileprivate final func outputActivatedSuccessorInternal(_ successor: AnyObject, activationCount: Int, dw: inout DeferredWork) { runSuccesorAction { guard let sccr = successor as? Signal<U> else { fatalError() } if let i = isOutputInternal(sccr) { _ = updateOutputInternal(index: i, activationCount: activationCount, dw: &dw) } } } // Invoked from successor when it completes activation and transitions to `.normal` delivery // // - Parameters: // - successor: the successor whose activation status has changed (must be a Signal<U>) // - dw: required func outputCompletedActivationSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) { runSuccesorAction { guard let sccr = successor as? Signal<U> else { fatalError() } if let _ = isOutputInternal(sccr), case .synchronous = source.delivery { endActivationInternal(dw: &dw) } } } // Invoked from successor `Signal`s when they deactivate // // - Parameters: // - successor: must be a Signal<U> // - dw: required fileprivate final func outputDeactivatedSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) { runSuccesorAction { guard let sccr = successor as? Signal<U> else { fatalError() } if let i = self.isOutputInternal(sccr) { _ = updateOutputInternal(index: i, activationCount: nil, dw: &dw) } } } // Overrideable function to receive additional information when a successor attaches. Used by SignalJunction and SignalCapture to pass "onEnd" closures via the successor into the It shouldn't be possible to pass a parameter unless one is expected, so the default implementation is a `fatalError`. // // - parameter param: usually a closure. fileprivate func handleParamFromSuccessor(param: Any) { fatalError() } // Typical processors *don't* need to check their predecessors for a loop (only junctions do) fileprivate var needsPredecessorCheck: Bool { return false } // A successor connected // // - Parameters: // - successor: must be a Signal<U> // - param: see `handleParamFromSuccessor` // - activationCount: initial activation count to use // - dw: required // - Throws: a possible SignalBindError if there's a connection failure. fileprivate final func outputAddedSuccessorInternal(_ successor: AnyObject, param: Any?, activationCount: Int?, dw: inout DeferredWork) throws { var error: SignalBindError<OutputValue>? = nil runSuccesorAction { guard outputs.isEmpty || multipleOutputsPermitted else { error = SignalBindError<OutputValue>.duplicate(nil) return } guard let sccr = successor as? Signal<U> else { fatalError() } if needsPredecessorCheck, let predecessor = sccr.signalHandler as? SignalPredecessor { // Don't need to traverse sortedPreceeding (unsorted is fine for an ancestor check) for p in source.preceeding { if p.base.predecessorsSuccessorInternal(loopCheck: predecessor.loopCheckValue) { // Throw an error here and trigger the preconditionFailure outside the lock (otherwise precondition catching tests may deadlock). error = SignalBindError<OutputValue>.loop dw.append { preconditionFailure("Signals must not be joined in a loop.") } return } } } outputs.append((destination: Weak(sccr), activationCount: nil)) #if DEBUG_LOGGING print("\(type(of: sccr)): \(sccr.count) added as successor to \(source.count)") #endif if let p = param { handleParamFromSuccessor(param: p) } if let ac = activationCount { if updateOutputInternal(index: outputs.count - 1, activationCount: ac, dw: &dw) { let count = self.source.activationCount dw.append { self.endActivation(activationCount: count) } } } } if let e = error { throw e } } // Called when a successor is removed // // - Parameters: // - successor: must be a Signal<U> // - dw: required fileprivate final func outputRemovedSuccessorInternal(_ successor: AnyObject, dw: inout DeferredWork) { runSuccesorAction { guard let sccr = successor as? Signal<U> else { fatalError() } for i in outputs.indices.reversed() { let match: Bool if let d = outputs[i].destination.value, d === sccr { match = true } else { match = false } if match || outputs[i].destination.value == nil { if outputs[i].activationCount != nil { _ = updateOutputInternal(index: i, activationCount: nil, dw: &dw) } outputs.remove(at: i) #if DEBUG_LOGGING print("\(type(of: sccr)): \(sccr.count) removed as successor from \(source.count)") #endif if outputs.isEmpty { lastOutputRemovedInternal(dw: &dw) } } } } } /// Default handler should not be used fileprivate func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { preconditionFailure() } } private extension Exec { var isImmediateNonDirect: Bool { if case .direct = self { return false } return type.isImmediateAlways } } private enum ActiveWithoutOutputs { case always case never case ifNonEmpty func active(valuesIsEmpty: Bool) -> Bool { switch self { case .always: return true case .never: return false case .ifNonEmpty where valuesIsEmpty: return false case .ifNonEmpty: return true } } } // Implementation of a processor that can output to multiple `Signal`s. Used by `continuous(initial:)`, `continuous`, `continuousWhileActive`, `playback`, `multicast`, `customActivation` and `preclosed`. fileprivate final class SignalMultiProcessor<OutputValue>: SignalProcessor<OutputValue, OutputValue> { typealias Updater = (_ activationValues: inout Array<OutputValue>, _ preclosed: inout SignalEnd?, _ result: Result<OutputValue, SignalEnd>) -> (Array<OutputValue>, SignalEnd?) let updater: Updater? var activationValues: Array<OutputValue> var preclosed: SignalEnd? let userUpdated: Bool let activeWithoutOutputs: ActiveWithoutOutputs // Rather than using different subclasses for each of the "multi" `Signal`s, this one subclass is used for all. However, that requires a few different parameters to enable different behaviors. // // - Parameters: // - source: the predecessor signal // - values: the initial activation values and error // - userUpdated: whether the `updater` is user-supplied and needs value-copying to ensure thread-safety // - activeWithoutOutputs: whether the handler should immediately activate // - dw: required // - context: where the `updater` will be run // - updater: when a new source is received, updates the cached activation values and error init(source: Signal<OutputValue>, values: (Array<OutputValue>, SignalEnd?), userUpdated: Bool, activeWithoutOutputs: ActiveWithoutOutputs, dw: inout DeferredWork, context: Exec, updater: Updater?) { precondition((values.1 == nil && values.0.isEmpty) || updater != nil, "Non empty activation values requires always active.") self.updater = (userUpdated && context.isImmediateNonDirect) ? updater.map { u in { a, b, c in context.invokeSync { u(&a, &b, c) } } } : updater self.activationValues = values.0 self.preclosed = values.1 self.userUpdated = userUpdated self.activeWithoutOutputs = activeWithoutOutputs super.init(source: source, dw: &dw, context: context) } // Multicast and continuousWhileActive are not preactivated but all others are not. fileprivate override var activeWithoutOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) return activeWithoutOutputs.active(valuesIsEmpty: activationValues.isEmpty) && preclosed == nil } // Multiprocessor can handle multiple outputs fileprivate override var multipleOutputsPermitted: Bool { return true } // Any values or errors are sent on activation. // // - Parameters: // - index: identifies the output // - dw: required fileprivate final override func sendActivationToOutputInternal(index: Int, dw: inout DeferredWork) { guard !activationValues.isEmpty || preclosed != nil else { return } // Push as *not* activated (i.e. this is the activation) outputs[index].destination.value?.pushInternal(values: activationValues, end: preclosed, activated: false, dw: &dw) } // Multiprocessors are (usually – not multicast) preactivated and may cache the values or errors // - Returns: a function to use as the handler prior to activation fileprivate override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) return { [weak self] r in guard let self = self else { return } _ = self.updater?(&self.activationValues, &self.preclosed, r) } } // On result, update any activation values. // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) // There's a tricky point here: for multicast, we only want to send to outputs that were connected *before* we started sending this value; otherwise values could be sent to the wrong outputs following asychronous graph manipulations. // HOWEVER, when activation values exist, we must ensure that any output that was sent the *old* activation values will receive this new value *regardless* of when it connects. // To balance these needs, the outputs array is copied here for "multicast" but isn't copied until immediately after updating the `activationValues` in all other cases // There's an additional assumption: (updater == nil) is only possible for "multicast" var outs: OutputsArray? = updater != nil ? nil : outputs let activated = source.delivery.isNormal // NOTE: the output signals in the `outs` array are already weakly retained return { [weak self] r in guard let self = self else { return } if let u = self.updater { if self.userUpdated { var values = [OutputValue]() var error: SignalEnd? // Mutably copy the activation values and error self.sync { values = self.activationValues error = self.preclosed } // Perform the update on the copies let expired = u(&values, &error, r) // Change the authoritative activation values and error self.sync { self.activationValues = values self.preclosed = error if outs == nil { outs = self.outputs } } // Make sure any reference to the originals is released *outside* the mutex withExtendedLifetime(expired) {} } else { var expired: (Array<OutputValue>, SignalEnd?)? = nil // Perform the update on the copies self.sync { expired = u(&self.activationValues, &self.preclosed, r) if outs == nil { outs = self.outputs } } // Make sure any expired content is released *outside* the mutex withExtendedLifetime(expired) {} } } // Send the result *before* changing the authoritative activation values and error let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) for o in outs ?? [] { if let d = o.destination.value, let ac = o.activationCount { d.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } } } // Implementation of a processor that combines SignalTransformerWithState and SignalMultiProcessor functionality into a single processor (avoiding the need for a clumsy state sharing arrangement if the two are separate). fileprivate final class SignalReducer<OutputValue, State>: SignalProcessor<OutputValue, State> { typealias Initializer = (_ message: Result<OutputValue, SignalEnd>) -> Result<State?, SignalEnd> typealias Reducer = (_ state: State, _ message: Result<OutputValue, SignalEnd>) -> Result<State, SignalEnd> enum StateOrInitializer { case state(State) case initializer(Initializer) } let reducer: Reducer var stateOrInitializer: StateOrInitializer var end: SignalEnd? init(source: Signal<OutputValue>, state: State, end: SignalEnd?, dw: inout DeferredWork, context: Exec, reducer: @escaping Reducer) { self.reducer = context.isImmediateNonDirect ? { a, b in context.invokeSync { reducer(a, b) } } : reducer self.end = end self.stateOrInitializer = .state(state) super.init(source: source, dw: &dw, context: context) } init(source: Signal<OutputValue>, initializer: @escaping Initializer, end: SignalEnd?, dw: inout DeferredWork, context: Exec, reducer: @escaping Reducer) { self.reducer = context.isImmediateNonDirect ? { a, b in context.invokeSync { reducer(a, b) } } : reducer self.end = end self.stateOrInitializer = .initializer(initializer) super.init(source: source, dw: &dw, context: context) } fileprivate override var activeWithoutOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) return end == nil } fileprivate override var multipleOutputsPermitted: Bool { return true } fileprivate final override func sendActivationToOutputInternal(index: Int, dw: inout DeferredWork) { guard case .state(let state) = stateOrInitializer else { return } // Push as *not* activated (i.e. this is the activation) outputs[index].destination.value?.pushInternal(values: [state], end: end, activated: false, dw: &dw) } // Multiprocessors are (usually – not multicast) preactivated and may cache the values or errors // - Returns: a function to use as the handler prior to activation override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) return { [weak self] r in guard let self = self else { return } // Copy the state under the mutex let stateOrInitializer = self.sync { self.stateOrInitializer } let next: Result<State, SignalEnd> switch stateOrInitializer { case .state(let state): next = self.reducer(state, r) case .initializer(let initializer): switch initializer(r) { case .success(nil): return case .success(let s?): next = .success(s) case .failure(let e): next = .failure(e) } } // Apply the change to the authoritative version under the mutex self.sync { switch next { case .success(let v): self.stateOrInitializer = .state(v) case .failure(let e): self.end = e } } // Ensure any old references are released outside the mutex withExtendedLifetime(stateOrInitializer) {} } } // On result, update any activation values. // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) let activated = source.delivery.isNormal return { [weak self] r in guard let self = self else { return } // Copy the state under the mutex let stateOrInitializer = self.sync { self.stateOrInitializer } let next: Result<State, SignalEnd> switch stateOrInitializer { case .state(let state): next = self.reducer(state, r) case .initializer(let initializer): switch initializer(r) { case .success(nil): return case .success(let s?): next = .success(s) case .failure(let e): next = .failure(e) } } // Apply the change to the authoritative version under the mutex var outputs: OutputsArray = [] var result = Signal<State>.Result.failure(.complete) self.sync { switch next { case .success(let v): self.stateOrInitializer = .state(v) result = .success(v) case .failure(let e): self.end = e result = .failure(e) } outputs = self.outputs } // Ensure any old references are released outside the mutex withExtendedLifetime(stateOrInitializer) {} let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) for o in outputs { if let d = o.destination.value, let ac = o.activationCount { d.send(result: result, predecessor: predecessor, activationCount: ac, activated: activated) } } } } } // A handler which starts receiving `Signal`s immediately and caches them until an output connects fileprivate final class SignalCacheUntilActive<OutputValue>: SignalProcessor<OutputValue, OutputValue> { var cachedValues: Array<OutputValue> var cachedEnd: SignalEnd? = nil // Construct a SignalCacheUntilActive handler // // - Parameters: // - source: the predecessor signal // - dw: required init(source: Signal<OutputValue>, precached: [OutputValue]?, dw: inout DeferredWork) { cachedValues = precached ?? [] super.init(source: source, dw: &dw, context: .direct) } // Is always active fileprivate override var activeWithoutOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) return true } // Sends the cached values when an output connects // // - Parameters: // - index: identifies the output // - dw: required fileprivate final override func sendActivationToOutputInternal(index: Int, dw: inout DeferredWork) { guard !cachedValues.isEmpty || cachedEnd != nil else { return } // Push as *not* activated (i.e. this is the activation) outputs[index].destination.value?.pushInternal(values: cachedValues, end: cachedEnd, activated: false, dw: &dw) } /// Caches values prior to an output connecting // - Returns: a function to use as the handler prior to activation override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) return { [weak self] r in switch r { case .success(let v): self?.cachedValues.append(v) case .failure(let e): self?.cachedEnd = e } } } // Clears the cache immediately after an output connects // // - Parameter dw: required fileprivate override func firstOutputActivatedInternal(dw: inout DeferredWork) { let tuple = (self.cachedValues, self.cachedEnd) self.cachedValues = [] self.cachedEnd = nil dw.append { withExtendedLifetime(tuple) {} } } // Once an output is connected, the handler function is a basic passthrough // - Returns: a function to use as the handler after activation override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { return SignalProcessor.simpleNext(processor: self) { r in r } } } // A transformer applies a user transformation to any signal. It's the typical "between two `Signal`s" handler. fileprivate final class SignalTransformer<OutputValue, U>: SignalProcessor<OutputValue, U> { typealias UserProcessorType = (Result<OutputValue, SignalEnd>) -> Signal<U>.Next let userProcessor: UserProcessorType // Constructs a `SignalTransformer` // // - Parameters: // - source: the predecessor signal // - dw: required // - context: where the `handler` will be invoked // - processor: the user supplied processing function init(source: Signal<OutputValue>, dw: inout DeferredWork, context: Exec, _ processor: @escaping UserProcessorType) { self.userProcessor = context.isImmediateNonDirect ? { a in context.invokeSync { processor(a) } } : processor super.init(source: source, dw: &dw, context: context) } /// Invoke the user handler and block if the `next` gains an additional reference count in the process. // - Returns: a function to use as the handler after activation override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) let activated = source.delivery.isNormal return { [userProcessor, weak outputSignal] r in let transformedResult = userProcessor(r) switch transformedResult { case .none: break case .single(let r): if let os = outputSignal { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } case .array(let a): if let os = outputSignal { for r in a { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } } } } // A transformer applies a user transformation to any signal. It's the typical "between two `Signal`s" handler. fileprivate final class SignalActivationTransformer<OutputValue, U>: SignalProcessor<OutputValue, U> { typealias UserProcessorType = (Result<OutputValue, SignalEnd>) -> Signal<U>.Next let activationProcessor: UserProcessorType let userProcessor: UserProcessorType var useActivation: Bool = false // Constructs a `SignalTransformer` // // - Parameters: // - source: the predecessor signal // - dw: required // - context: where the `handler` will be invoked // - processor: the user supplied processing function init(source: Signal<OutputValue>, dw: inout DeferredWork, context: Exec, activationProcessor: @escaping UserProcessorType, _ processor: @escaping UserProcessorType) { self.activationProcessor = context.isImmediateNonDirect ? { a in context.invokeSync { activationProcessor(a) } } : activationProcessor self.userProcessor = context.isImmediateNonDirect ? { a in context.invokeSync { processor(a) } } : processor super.init(source: source, dw: &dw, context: context) } override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { useActivation = true return super.initialHandlerInternal() } override func handleSynchronousToNormalInternal(dw: inout DeferredWork) { useActivation = false handler = nextHandlerInternal() } /// Invoke the user handler and block if the `next` gains an additional reference count in the process. // - Returns: a function to use as the handler after activation override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) return { [useActivation, userProcessor, activationProcessor, weak outputSignal] r in let transformedResult: Signal<U>.Next if useActivation { transformedResult = activationProcessor(r) } else { transformedResult = userProcessor(r) } switch transformedResult { case .none: break case .single(let r): if let os = outputSignal { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: !useActivation) } case .array(let a): if let os = outputSignal { for r in a { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: !useActivation) } } } } } } /// Same as `SignalTransformer` plus a `state` value that is passed `inout` to the handler each time so state can be safely retained between invocations. This `state` value is reset to its `initialState` if the signal graph is deactivated. fileprivate final class SignalTransformerWithState<OutputValue, U, S>: SignalProcessor<OutputValue, U> { typealias UserProcessorType = (inout S, Result<OutputValue, SignalEnd>) -> Signal<U>.Next let userProcessor: UserProcessorType let initialState: S // Constructs a `SignalTransformer` // // - Parameters: // - source: the predecessor signal // - initialState: initial value to use for the "state" passed to the processing handler on each iteration // - dw: required // - context: where the `handler` will be invoked // - processor: the user supplied processing function init(source: Signal<OutputValue>, initialState: S, dw: inout DeferredWork, context: Exec, _ processor: @escaping (inout S, Result<OutputValue, SignalEnd>) -> Signal<U>.Next) { self.userProcessor = context.isImmediateNonDirect ? { a, b in context.invokeSync { processor(&a, b) } } : processor self.initialState = initialState super.init(source: source, dw: &dw, context: context) } // Invoke the user handler and block if the `next` gains an additional reference count in the process. // - Returns: a function to use as the handler after activation override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let activated = source.delivery.isNormal let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) /// Every time the handler is recreated, the `state` value is initialized from the `initialState`. var state = initialState return { [userProcessor, weak outputSignal] r in let transformedResult = userProcessor(&state, r) switch transformedResult { case .none: break case .single(let r): if let os = outputSignal { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } case .array(let a): if let os = outputSignal { for r in a { os.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } } } } /// A processor used by `combine(...)` to transform incoming `Signal`s into the "combine" type. The handler function is typically just a wrap of the preceeding `Result` in a `EitherResultX.resultY`. Other than that, it's a basic passthrough transformer fileprivate final class SignalCombiner<OutputValue, U>: SignalProcessor<OutputValue, U> { let combineProcessor: (Result<OutputValue, SignalEnd>) -> U // Constructs a `SignalCombiner` // // - Parameters: // - source: the predecessor signal // - dw: required // - context: where the `handler` will be invoked // - processor: the user supplied processing function init(source: Signal<OutputValue>, dw: inout DeferredWork, context: Exec, processor: @escaping (Result<OutputValue, SignalEnd>) -> U) { self.combineProcessor = context.isImmediateNonDirect ? { a in context.invokeSync { processor(a) } } : processor super.init(source: source, dw: &dw, context: context) } /// Simple application of the handler // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { return SignalProcessor.simpleNext(processor: self) { [combineProcessor] r in Result<U, SignalEnd>.success(combineProcessor(r)) } } } // Common implementation of bind behavior used by `SignalJunction` and `SignalCapture`. // // - Parameters: // - processor: the `SignalJuction` or `SignalCapture` // - disconnect: receiver for a new `SignalInput` when the junction is disconnected. // - to: destination of the bind // - optionalEndHandler: passed as the `param` to `addPreceedingInternal` // - Throws: and `addPreceedingInternal` error or other `SignalBindError<OutputValue>.cancelled` errors if weak properties can't strongified. fileprivate func bindFunction<OutputValue>(processor: SignalProcessor<OutputValue, OutputValue>, disconnect: () -> SignalInput<OutputValue>?, to input: SignalInput<OutputValue>, optionalEndHandler: Any?) throws { var dw = DeferredWork() defer { dw.runWork() } assert(!(input is SignalMultiInput<OutputValue>)) if let nextSignal = input.signal { try nextSignal.sync { () throws -> () in guard input.activationCount == nextSignal.activationCount else { throw SignalBindError<OutputValue>.cancelled } nextSignal.removeAllPreceedingInternal(dw: &dw) do { try nextSignal.addPreceedingInternal(processor, param: optionalEndHandler, dw: &dw) } catch { switch error { case SignalBindError<OutputValue>.duplicate: throw SignalBindError<OutputValue>.duplicate(SignalInput<OutputValue>(signal: nextSignal, activationCount: nextSignal.activationCount)) default: throw error } } } } else { throw SignalBindError<OutputValue>.cancelled } } /// A junction is a point in the signal graph that can be disconnected and reconnected at any time. Constructed implicitly by calling `bind(to:...)` or explicitly by calling `junction()` on an `Signal`. public class SignalJunction<OutputValue>: SignalProcessor<OutputValue, OutputValue>, Lifetime { public typealias Handler = (SignalJunction<OutputValue>, SignalEnd, SignalInput<OutputValue>) -> () private var disconnectOnEnd: Handler? = nil // Constructs a "bind" handler // // - Parameters: // - source: the predecessor signal // - dw: required init(source: Signal<OutputValue>, dw: inout DeferredWork) { super.init(source: source, dw: &dw, context: .direct) } // Typical processors *don't* need to check their predecessors for a loop (only junctions do) fileprivate override var needsPredecessorCheck: Bool { return true } // If a `disconnectOnEnd` handler is configured, then `failure` signals are not sent through the junction. Instead, the junction is disconnected and the `disconnectOnEnd` function is given an opportunity to handle the `SignalJunction` (`self`) and `SignalInput` (from the `disconnect`). // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let activated = source.delivery.isNormal let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) let disconnectAction = disconnectOnEnd return { [weak outputSignal, weak self] r in if let d = disconnectAction, case .failure(let e) = r, let s = self, let input = s.disconnect() { d(s, e, input) } else { _ = outputSignal?.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } /// Disconnects the succeeding `Signal` (if any). /// /// - returns: the new `SignalInput` for the succeeding `Signal` (if any `Signal` was connected) otherwise nil. If the `SignalInput` value is non-nil and is released, the succeeding `Signal` will be closed. public func disconnect() -> SignalInput<OutputValue>? { var previous: SignalJunction<OutputValue>.Handler? = nil let result = sync { () -> Signal<OutputValue>? in previous = disconnectOnEnd return outputs.first?.destination.value }?.newInput(forDisconnector: self) withExtendedLifetime(previous) {} return result } /// Implementation of `Lifetime` simply invokes a `disconnect()` public func cancel() { _ = disconnect() } // Implementation of `Lifetime` requires `cancel` is called in the `deinit` deinit { cancel() } // The `disconnectOnEnd` needs to be set inside the mutex, if-and-only-if a successor connects successfully. To allow this to work, the desired `disconnectOnEnd` function is passed into this function via the `outputAddedSuccessorInternal` called from `addPreceedingInternal` in the `bindFunction`. // // - Parameter param: received through `addPreceedingInternal` – should be the onEnd handler from `bind(to:resend:onEnd:)` fileprivate override func handleParamFromSuccessor(param: Any) { if let p = param as? SignalJunction<OutputValue>.Handler { disconnectOnEnd = p } } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameter to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalJunction` will still be `disconnect`ed. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind<U: SignalInputInterface>(to: U) throws where U.InputValue == OutputValue { try bindFunction(processor: self, disconnect: self.disconnect, to: to.input.singleInput(), optionalEndHandler: nil) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalJunction` will still be `disconnect`ed. /// - onEnd: if nil, errors from self will be passed through to `to`'s `Signal` normally. If non-nil, errors will not be sent, instead, the `Signal` will be disconnected and the `onEnd` function will be invoked with the disconnected `SignalJunction` and the input created by calling `disconnect` on it. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind<U: SignalInputInterface>(to: U, onEnd: @escaping SignalJunction<OutputValue>.Handler) throws where U.InputValue == OutputValue { try bindFunction(processor: self, disconnect: self.disconnect, to: to.input.singleInput(), optionalEndHandler: onEnd) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameter to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalJunction` will still be `disconnect`ed. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind(to: SignalMergedInput<OutputValue>, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool = false) throws { try bindFunction(processor: self, disconnect: self.disconnect, to: to.singleInput(closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate), optionalEndHandler: nil) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalJunction` will still be `disconnect`ed. /// - onEnd: if nil, errors from self will be passed through to `to`'s `Signal` normally. If non-nil, errors will not be sent, instead, the `Signal` will be disconnected and the `onEnd` function will be invoked with the disconnected `SignalJunction` and the input created by calling `disconnect` on it. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind(to: SignalMergedInput<OutputValue>, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool = false, onEnd: @escaping (SignalJunction<OutputValue>, Error, SignalInput<OutputValue>) -> ()) throws { try bindFunction(processor: self, disconnect: self.disconnect, to: to.singleInput(closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate), optionalEndHandler: onEnd) } /// Disconnect and reconnect to the same input, to deliberately deactivate and reactivate. If `disconnect` returns `nil`, no further action will be taken. Any error attempting to reconnect will be sent to the input. public func rebind() { if let input = disconnect() { do { try bind(to: input) } catch { input.send(result: .failure(.other(error))) } } } /// Disconnect and reconnect to the same input, to deliberately deactivate and reactivate. If `disconnect` returns `nil`, no further action will be taken. Any error attempting to reconnect will be sent to the input. /// /// - Parameter onEnd: passed through to `bind` public func rebind(onEnd: @escaping SignalJunction<OutputValue>.Handler) { if let input = disconnect() { do { try bind(to: input, onEnd: onEnd) } catch { input.send(result: .failure(.other(error))) } } } } // Used to hold the handler function for onEnd behavior for `SignalCapture` private struct SignalCaptureParam<OutputValue> { let resend: SignalActivationSelection let disconnectOnEnd: SignalCapture<OutputValue>.Handler? } /// A "capture" handler separates activation signals (those sent immediately on connection) from normal signals. This allows activation signals to be handled separately or removed from the stream entirely. /// NOTE: this handler *blocks* delivery between capture and connecting to the output. Signals sent in the meantime are queued. public final class SignalCapture<OutputValue>: SignalProcessor<OutputValue, OutputValue>, Lifetime { public struct FailedToEmit: Error {} public typealias Handler = (SignalCapture<OutputValue>, SignalEnd, SignalInput<OutputValue>) -> () private var resend: SignalActivationSelection = .none private var capturedEnd: SignalEnd? = nil private var capturedValues: [OutputValue] = [] private var blockActivationCount: Int = 0 private var disconnectOnEnd: SignalCapture<OutputValue>.Handler? = nil // Constructs a capture handler // // - Parameters: // - source: the predecessor signal // - dw: required fileprivate init(source: Signal<OutputValue>, dw: inout DeferredWork) { super.init(source: source, dw: &dw, context: .direct) } // Once an output is connected, `SignalCapture` becomes a no-special-behaviors passthrough handler. fileprivate override var activeWithoutOutputsInternal: Bool { assert(super.source.unbalancedTryLock() == false) return outputs.count > 0 ? false : true } /// Accessor for any captured values. Activation signals captured can be accessed through this property between construction and activating an output (after that point, capture signals are cleared). /// /// - Returns: and array of values (which may be empty) and an optional error, which are the signals received during activation. public var values: [OutputValue] { return sync { return capturedValues } } /// Accessor for any captured error. Activation signals captured can be accessed through this property between construction and activating an output (after that point, capture signals are cleared). /// /// - Returns: and array of values (which may be empty) and an optional error, which are the signals received during activation. public var end: SignalEnd? { return sync { return capturedEnd } } /// Accessor for the last captured value, if any. /// /// - Returns: the last captured value /// - Throws: if no captured value but captured end, the `SignalEnd` is thrown. If neither value nor end, `SignalCapture.FailedToEmit` is thrown. public func get() throws -> OutputValue { return try sync { if let last = capturedValues.last { return last } else if let end = capturedEnd { throw end } else { throw FailedToEmit() } } } /// Accessor for the last captured value, if any. /// /// - Returns: the last captured value /// - Throws: if no captured value but captured end, the `SignalEnd` is thrown. If neither value nor end, `SignalCapture.FailedToEmit` is thrown. public func peek() -> OutputValue? { return sync { capturedValues.last } } // Typical processors *don't* need to check their predecessors for a loop (only junctions do) fileprivate override var needsPredecessorCheck: Bool { return true } // The initial behavior is to capture // - Returns: a function to use as the handler prior to activation fileprivate override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { guard outputs.isEmpty else { return { r in } } assert(super.source.unbalancedTryLock() == false) capturedEnd = nil capturedValues = [] return { [weak self] r in guard let s = self else { return } switch r { case .success(let v): s.capturedValues.append(v) case .failure(let e): s.capturedEnd = e } } } // After the initial "capture" phase, the queue is blocked, causing any non-activation signals to queue. // - Parameter dw: required fileprivate override func handleSynchronousToNormalInternal(dw: inout DeferredWork) { if outputs.isEmpty { let (vs, err) = super.source.pullQueuedSynchronousInternal() capturedValues.append(contentsOf: vs) if let e = err { capturedEnd = e } super.source.blockInternal() blockActivationCount = super.source.activationCount } } // If this handler disconnected, then it reactivates and reverts to being a "capture". // - Parameter dw: required fileprivate override func lastOutputRemovedInternal(dw: inout DeferredWork) { guard super.source.delivery.isDisabled else { return } // While a capture has an output connected – even an inactive output – it doesn't self-activate. When the last output is removed, we need to re-activate. dw.append { [handler] in withExtendedLifetime(handler) {} } handler = initialHandlerInternal() if activateInternal(dw: &dw) { let count = super.source.activationCount dw.append { self.endActivation(activationCount: count) } } } // When an output activates, if `sendAsNormal` is true, the new output is sent any captured values. In all cases, the captured values are cleared at this point and the queue is unblocked. // - Parameter dw: required fileprivate override func firstOutputActivatedInternal(dw: inout DeferredWork) { if resend != .none, let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount { // Don't deliver errors if `disconnectOnEnd` is set if let d = disconnectOnEnd, let e = capturedEnd { // NOTE: we use the successors "internal" functon here since this is always called from successor's `updateActivationInternal` function // Push as *activated* (i.e. this is deferred from activation to normal) switch resend { case .all: outputSignal.pushInternal(values: capturedValues, end: nil, activated: false, dw: &dw) case .deferred: outputSignal.pushInternal(values: capturedValues, end: nil, activated: true, dw: &dw) case .first: outputSignal.pushInternal(values: capturedValues.first.map { [$0] } ?? [], end: nil, activated: false, dw: &dw) outputSignal.pushInternal(values: Array(capturedValues.dropFirst()), end: nil, activated: true, dw: &dw) case .last: outputSignal.pushInternal(values: capturedValues.last.map { [$0] } ?? [], end: nil, activated: false, dw: &dw) case .none: fatalError("Unreachable") } dw.append { // We need to use a specialized version of disconnect that ensures another disconnect hasn't happened in the meantime. Since it's theoretically possible that this handler could be disconnected and reconnected in the meantime (or deactivated and reactivated) we need to check the output and activationCount to ensure everything's still the same. var previous: SignalCapture<OutputValue>.Handler? = nil let input = self.sync { () -> Signal<OutputValue>? in if let o = self.outputs.first, let os = o.destination.value, os === outputSignal, ac == o.activationCount { previous = self.disconnectOnEnd return os } else { return nil } }?.newInput(forDisconnector: self) withExtendedLifetime(previous) {} if let i = input { d(self, e, i) } } } else { // NOTE: we use the successors "internal" functon here since this is always called from successor's `updateActivationInternal` function // Push as *activated* (i.e. this is deferred from activation to normal) switch resend { case .all: outputSignal.pushInternal(values: capturedValues, end: capturedEnd, activated: false, dw: &dw) case .deferred: outputSignal.pushInternal(values: capturedValues, end: capturedEnd, activated: true, dw: &dw) case .first: outputSignal.pushInternal(values: capturedValues.first.map { [$0] } ?? [], end: nil, activated: false, dw: &dw) outputSignal.pushInternal(values: Array(capturedValues.dropFirst()), end: capturedEnd, activated: true, dw: &dw) case .last: outputSignal.pushInternal(values: capturedValues.last.map { [$0] } ?? [], end: capturedEnd, activated: false, dw: &dw) case .none: fatalError("Unreachable") } } } super.source.unblockInternal(activationCountAtBlock: blockActivationCount) super.source.resumeIfPossibleInternal(dw: &dw) let tuple = (self.capturedValues, self.capturedEnd) self.capturedValues = [] self.capturedEnd = nil dw.append { withExtendedLifetime(tuple) {} } } // Like a `SignalJunction`, a capture can respond to an error by disconnecting instead of delivering. // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(super.source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let activated = super.source.delivery.isNormal let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) let disconnectAction = disconnectOnEnd return { [weak outputSignal, weak self] r in if let d = disconnectAction, case .failure(let e) = r, let s = self, let input = s.disconnect() { d(s, e, input) } else { _ = outputSignal?.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } /// Disconnects the succeeding `Signal` (if any). /// /// - returns: the new `SignalInput` for the succeeding `Signal` (if any `Signal` was connected) otherwise nil. If the `SignalInput` value is non-nil and is released, the succeeding `Signal` will be closed. public func disconnect() -> SignalInput<OutputValue>? { var previous: SignalCapture<OutputValue>.Handler? = nil let result = sync { () -> Signal<OutputValue>? in previous = disconnectOnEnd return outputs.first?.destination.value }?.newInput(forDisconnector: self) withExtendedLifetime(previous) {} return result } /// Implementation of `Lifetime` simply invokes a `disconnect()` public func cancel() { _ = self.disconnect() } // Implementation of `Lifetime` requires `cancel` is called in the `deinit` deinit { cancel() } // The `disconnectOnEnd` needs to be set inside the mutex, if-and-only-if a successor connects successfully. To allow this to work, the desired `disconnectOnEnd` function is passed into this function via the `outputAddedSuccessorInternal` called from `addPreceedingInternal` in the `bindFunction`. // // - Parameter param: received through `addPreceedingInternal` – should be the onEnd handler from `bind(to:resend:onEnd:)` fileprivate override func handleParamFromSuccessor(param: Any) { if let p = param as? SignalCaptureParam<OutputValue> { disconnectOnEnd = p.disconnectOnEnd resend = p.resend } } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalCapture` will still be `disconnect`ed. /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind<U: SignalInputInterface>(to: U, resend: SignalActivationSelection = .none) throws where U.InputValue == OutputValue { let param = SignalCaptureParam<OutputValue>(resend: resend, disconnectOnEnd: nil) try bindFunction(processor: self, disconnect: self.disconnect, to: to.input.singleInput(), optionalEndHandler: param) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalCapture` will still be `disconnect`ed. /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - onEnd: if nil, errors from self will be passed through to `to`'s `Signal` normally. If non-nil, errors will not be sent, instead, the `Signal` will be disconnected and the `onEnd` function will be invoked with the disconnected `SignalCapture` and the input created by calling `disconnect` on it. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind<U: SignalInputInterface>(to: U, resend: SignalActivationSelection = .none, onEnd: @escaping SignalCapture<OutputValue>.Handler) throws where U.InputValue == OutputValue { let param = SignalCaptureParam<OutputValue>(resend: resend, disconnectOnEnd: onEnd) try bindFunction(processor: self, disconnect: self.disconnect, to: to.input.singleInput(), optionalEndHandler: param) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalCapture` will still be `disconnect`ed. /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind(to: SignalMergedInput<OutputValue>, resend: SignalActivationSelection = .none, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool) throws { let param = SignalCaptureParam<OutputValue>(resend: resend, disconnectOnEnd: nil) try bindFunction(processor: self, disconnect: self.disconnect, to: to.singleInput(closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate), optionalEndHandler: param) } /// Invokes `disconnect` on self before attemping to bind this junction to a successor, identified by its `SignalInput`. /// /// - Parameters: /// - to: used to identify an `Signal`. If this `SignalInput` is not the active input for its `Signal`, then no bind attempt will occur (although this `SignalCapture` will still be `disconnect`ed. /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - onEnd: if nil, errors from self will be passed through to `to`'s `Signal` normally. If non-nil, errors will not be sent, instead, the `Signal` will be disconnected and the `onEnd` function will be invoked with the disconnected `SignalCapture` and the input created by calling `disconnect` on it. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func bind(to: SignalMergedInput<OutputValue>, resend: SignalActivationSelection = .none, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool, onEnd: @escaping SignalCapture<OutputValue>.Handler) throws { let param = SignalCaptureParam<OutputValue>(resend: resend, disconnectOnEnd: onEnd) try bindFunction(processor: self, disconnect: self.disconnect, to: to.singleInput(closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate), optionalEndHandler: param) } /// Appends a `Signal` that will resume the stream interrupted by the `SignalCapture`. /// /// - Parameters: /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - returns: the created `Signal` public func resume(resend: SignalActivationSelection = .none) -> Signal<OutputValue> { let (input, output) = Signal<OutputValue>.create() // This could be `duplicate` but that's a precondition failure try! bind(to: input, resend: resend) return output } /// Appends a `Signal` that will resume the stream interrupted by the `SignalCapture`. /// /// - Parameters: /// - resend: if true, captured values are sent to the new output as the first values in the stream, otherwise, captured values are not sent (default is false) /// - onEnd: if nil, errors from self will be passed through to `to`'s `Signal` normally. If non-nil, errors will not be sent, instead, the `Signal` will be disconnected and the `onEnd` function will be invoked with the disconnected `SignalCapture` and the input created by calling `disconnect` on it. /// - returns: the created `SignalOutput` public func resume(resend: SignalActivationSelection = .none, onEnd: @escaping SignalCapture<OutputValue>.Handler) -> Signal<OutputValue> { let (input, output) = Signal<OutputValue>.create() // This could be `duplicate` but that's a precondition failure try! bind(to: input, resend: resend, onEnd: onEnd) return output } } /// When an input to a `SignalMergedInput` sends an error, this behavior determines the effect on the merge set and its output /// /// - none: the input signal is removed from the merge set but the error is not propagated through to the output. /// - errors: if the error is not an instance of `SignalComplete`, then the error is propagated through to the output. This is the default. /// - close: any error, including `SignalEnd.complete`, is progagated through to the output public enum SignalEndPropagation { case none case errors case all /// Determines whether the error should be sent or if the input should be removed instead. /// /// - Parameter error: sent from one of the inputs /// - Returns: if `false`, the input that sent the error should be removed but the error should not be sent. If `true`, the error should be sent to the `SignalMergedInput`'s output (whether or not the input is removed is then determined by the `removeOnDeactivate` property). public func shouldPropagateEnd(_ end: SignalEnd) -> Bool { switch self { case .none: return false case .errors: return end.isOther case .all: return true } } } // A handler that apples the different rules required for inputs to a `SignalMergedInput`. fileprivate class SignalMultiInputProcessor<InputValue>: SignalProcessor<InputValue, InputValue> { let closePropagation: SignalEndPropagation let removeOnDeactivate: Bool // The input is added here to keep it alive at least as long as there are active inputs. You can `cancel` an input to remove all active inputs. let multiInput: SignalMultiInput<InputValue> // Constructs a `SignalMultiInputProcessor` // // - Parameters: // - signal: destination of the `SignalMergedInput` // - closePropagation: rules to use when this processor handles an error // - removeOnDeactivate: behavior to apply on deactivate // - mergedInput: the mergedInput that manages this processor // - dw: required init(source: Signal<InputValue>, multiInput: SignalMultiInput<InputValue>, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool, dw: inout DeferredWork) { self.multiInput = multiInput self.closePropagation = closePropagation self.removeOnDeactivate = removeOnDeactivate super.init(source: source, dw: &dw, context: .direct) } // If `removeOnDeactivate` is true, then deactivating this `Signal` removes it from the set // // - parameter dw: required fileprivate override func lastOutputDeactivatedInternal(dw: inout DeferredWork) { if removeOnDeactivate { guard let output = outputs.first, let os = output.destination.value, let ac = output.activationCount else { return } os.sync { guard os.activationCount == ac else { return } _ = os.removePreceedingWithoutInterruptionInternal(self, dw: &dw) } } } // The handler is largely a passthrough but allso applies `sourceClosesOutput` logic – removing error sending signals that don't close the output. // - Returns: a function to use as the handler after activation fileprivate override func nextHandlerInternal() -> (Result<InputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) guard let output = outputs.first, let outputSignal = output.destination.value, let ac = output.activationCount else { return initialHandlerInternal() } let activated = source.delivery.isNormal let predecessor: Unmanaged<AnyObject>? = Unmanaged.passUnretained(self) let propagation = closePropagation return { [weak outputSignal, weak self] r in if case .failure(let e) = r, !propagation.shouldPropagateEnd(e), let os = outputSignal, let s = self { var dw = DeferredWork() os.sync { guard os.activationCount == ac else { return } _ = os.removePreceedingWithoutInterruptionInternal(s, dw: &dw) s.multiInput.checkForLastInputRemovedInternal(signal: os, dw: &dw) } dw.runWork() } else { _ = outputSignal?.send(result: r, predecessor: predecessor, activationCount: ac, activated: activated) } } } } /// The `SignalMultiInput` class is used as a persistent, rebindable input to a `Signal`. /// You can use `SignalMultiInput` as the parameter to `bind(to:)` multiple times, versus `SignalInput` for which subsequent uses after the first will have no effect. /// When sending an error to `SignalMultiInput`, the preceeding branch of the signal graph will be disconnected but the close will not be propagated to the output signal. This is in accordance with the idea that `SignalMultiInput` is a shared interface – the `SignalMultiInput` remains open until all inputs are closed and the `SignalMultiInput` itself is released. // If you need more precise control about whether incoming signals have the ability to close the outgoing signal, use the `SignalMergedInput` subclass – the default behavior of `SignalMergedInput` is to propgate "unexpected" errors (non-`SignalComplete` errors). /// Another difference is that a `SignalInput` is invalidated when the graph deactivates whereas `SignalMultiInput` remains valid. public class SignalMultiInput<InputValue>: SignalInput<InputValue> { // Constructs a `SignalMergedInput` (typically called from `Signal<InputValue>.createMergedInput`) // // - Parameter signal: the destination `Signal` fileprivate init(signal: Signal<InputValue>) { super.init(signal: signal, activationCount: 0) } /// Connect a new predecessor to the `Signal` /// /// - Parameters: /// - source: the `Signal` to connect as a new predecessor /// - closePropagation: behavior to use when `source` sends an error. See `SignalEndPropagation` for more. /// - removeOnDeactivate: if true, then when the output is deactivated, this source will be removed from the merge set. If false, then the source will remain connected through deactivation. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public func add<U: SignalInterface>(_ source: U) where U.OutputValue == InputValue { self.add(source, closePropagation: .none) } // See the comments on the public override in `SignalMergedInput` fileprivate func add<U: SignalInterface>(_ source: U, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool = false) where U.OutputValue == InputValue { guard let sig = signal else { return } let processor = source.signal.attach { (s, dw) -> SignalMultiInputProcessor<InputValue> in SignalMultiInputProcessor<InputValue>(source: s, multiInput: self, closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate, dw: &dw) } var dw = DeferredWork() sig.sync { // This can't be `duplicate` since this a a new processor but `loop` is a precondition failure try! sig.addPreceedingInternal(processor, param: nil, dw: &dw) } dw.runWork() } private func remove(mp: SignalMultiInputProcessor<InputValue>, from sig: Signal<InputValue>) -> Bool { var dw = DeferredWork() let result = sig.sync { () -> Bool in let r = sig.removePreceedingWithoutInterruptionInternal(mp, dw: &dw) checkForLastInputRemovedInternal(signal: sig, dw: &dw) return r } dw.runWork() return result } /// Removes a predecessor from the merge set /// /// NOTE: if the predecessor is a `SignalMulti` with multiple connections to the merge set, only the first match will be removed. /// /// - Parameter source: the predecessor to remove public final func remove<U: SignalInterface>(_ source: U) where U.OutputValue == InputValue { guard let targetSignal = signal else { return } let sourceSignal = source.signal if let multi = sourceSignal as? SignalMulti<InputValue> { let signals = multi.preceeding.first!.base.outputSignals(ofType: InputValue.self) let mergeProcessors = signals.compactMap { s in s.sync { s.signalHandler as? SignalMultiInputProcessor<InputValue> } } for mp in mergeProcessors { if remove(mp: mp, from: targetSignal) { break } } } else { if let mp = sourceSignal.sync(execute: { sourceSignal.signalHandler as? SignalMultiInputProcessor<InputValue> }) { _ = remove(mp: mp, from: targetSignal) } } } // Overridden by SignalMergeSet to send an error immediately upon last input removed fileprivate func checkForLastInputRemovedInternal(signal: Signal<InputValue>, dw: inout DeferredWork) { } /// Connects a new `SignalInput<InputValue>` to `self`. A single input may be faster than a multi-input over multiple `send` operations. public override func singleInput() -> SignalInput<InputValue> { let (input, signal) = Signal<InputValue>.create() self.add(signal) return input } /// The primary signal sending function /// /// NOTE: on `SignalMultiInput` this is a relatively low performance convenience method; it calls `singleInput()` on each send. If you plan to send multiple results, it is more efficient to call `singleInput()`, retain the `SignalInput` that creates and call `SignalInput` on that single input. /// /// - Parameter result: the value or error to send, composed as a `Result` /// - Returns: `nil` on success. Non-`nil` values include `SignalSendError.disconnected` if the `predecessor` or `activationCount` fail to match, `SignalSendError.inactive` if the current `delivery` state is `.disabled`. public final override func send(result: Result<InputValue, SignalEnd>) -> SignalSendError? { return singleInput().send(result: result) } /// Implementation of `Lifetime` removes all inputs and sends a `SignalComplete.cancelled` to the destination. public final override func cancel() { guard let sig = signal else { return } var dw = DeferredWork() sig.sync { sig.removeAllPreceedingInternal(dw: &dw) sig.pushInternal(values: [], end: SignalEnd.cancelled, activated: true, dw: &dw) } dw.runWork() } } /// A SignalMergeSet is a very similar to a SignalMultiInput but offering additional customization as expected by common transformations. The reason why this customization is not offered directly on `SignalMultiInput` is that these are behavior customizations you don't generally want to expose in an interface. /// /// In particular: /// * The SignalMergeSet can be configured to send a specific Error (e.g. SignalEnd.complete) when the last input is removed. This is helpful when merging a specific set of inputs and running until they're all complete. /// * The SignalMergeSet can be configured to send a specific Error on deinit (i.e. when there are no inputs and the class is not otherwise retained). SignalMultiInput sends a `.cancelled` in this scenario but SignalMergeSet sends a `.closed` and can be configured to send something else as desired. /// * A SignalMultiInput rejects all attempts to send errors through it (closes, cancels, or otherwise) and merely disconnects the input that sent the error. A SignalMergeSet can be configured to similar reject all (`.none`) or it can permit all (`.all`), or permit only non-close errors (`.errors`). The latter is the *default* for SignalMultiInput (except when using `singleInput` which keeps the `.none` behavior). This default marks a difference in behavior, relative to SignalMultiInput, which always uses `.none`. /// Exposing `SignalMergedInput` in an interface is not particularly common. It is typically used for internal subgraphs where specific control is required. /// /// WARNING: `SignalMergedInput` changes the default `SignalEndPropagation` behavior from `.none` to `.errors`. This is because `SignalMergedInput` is primarily used for implementing transformations like `flatMap` which expect this type of propagation. public class SignalMergedInput<InputValue>: SignalMultiInput<InputValue> { fileprivate let onLastInputClosed: SignalEnd? fileprivate let onDeinit: SignalEnd fileprivate init(signal: Signal<InputValue>, onLastInputClosed: SignalEnd? = nil, onDeinit: SignalEnd = .cancelled) { self.onLastInputClosed = onLastInputClosed self.onDeinit = onDeinit super.init(signal: signal) } /// Changes the default closePropagation to `.all` public override func add<U: SignalInterface>(_ source: U) where U.OutputValue == InputValue { self.add(source, closePropagation: .errors, removeOnDeactivate: false) } fileprivate override func checkForLastInputRemovedInternal(signal sig: Signal<InputValue>, dw: inout DeferredWork) { if sig.preceeding.count == 0, let e = onLastInputClosed { sig.pushInternal(values: [], end: e, activated: true, dw: &dw) } } /// Connect a new predecessor to the `Signal` /// /// - Parameters: /// - source: the `Signal` to connect as a new predecessor /// - closePropagation: behavior to use when `source` sends an error. See `SignalEndPropagation` for more. /// - removeOnDeactivate: f true, then when the output is deactivated, this source will be removed from the merge set. If false, then the source will remain connected through deactivation. /// - Throws: may throw a `SignalBindError` (see that type for possible cases) public override func add<U: SignalInterface>(_ source: U, closePropagation: SignalEndPropagation, removeOnDeactivate: Bool = false) where U.OutputValue == InputValue { super.add(source, closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate) } /// Creates a new `SignalInput`/`Signal` pair, immediately adds the `Signal` to this `SignalMergedInput` and returns the `SignalInput`. /// /// - Parameters: /// - closePropagation: passed to `add(_:closePropagation:removeOnDeactivate:) internally /// - removeOnDeactivate: passed to `add(_:closePropagation:removeOnDeactivate:) internally /// - Returns: the `SignalInput` that will now feed into this `SignalMergedInput`. public final func singleInput(closePropagation: SignalEndPropagation, removeOnDeactivate: Bool = false) -> SignalInput<InputValue> { let (input, signal) = Signal<InputValue>.create() self.add(signal, closePropagation: closePropagation, removeOnDeactivate: removeOnDeactivate) return input } /// Connects a new `SignalInput<InputValue>` to `self`. A single input may be faster than a multi-input over multiple `send` operations. public override func singleInput() -> SignalInput<InputValue> { let (input, signal) = Signal<InputValue>.create() self.add(signal, closePropagation: .none, removeOnDeactivate: false) return input } // SignalMergeSet suppresses the standard cancel on deinit behavior in favor of sending its own chosen error. fileprivate override func cancelOnDeinit() { guard let sig = signal else { return } var dw = DeferredWork() sig.sync { sig.pushInternal(values: [], end: onDeinit, activated: true, dw: &dw) } dw.runWork() } } /// The primary "exit point" for a signal graph. `SignalOutput` provides two important functions: /// 1. a `handler` function which receives signal values and errors /// 2. upon connecting to the graph, `SignalOutput` "activates" the signal graph (which allows sending through the graph to occur and may trigger some "on activation" behavior). /// This class is instantiated by calling `subscribe` on any `Signal`. public final class SignalOutput<OutputValue>: SignalHandler<OutputValue>, Lifetime { private let userHandler: (Result<OutputValue, SignalEnd>) -> Void /// Constructor called from `subscribe` /// /// - Parameters: /// - signal: the source signal /// - dw: required /// - context: where `handler` will be run /// - handler: invoked when a new signal is received fileprivate init(source: Signal<OutputValue>, dw: inout DeferredWork, context: Exec, handler: @escaping (Result<OutputValue, SignalEnd>) -> Void) { self.userHandler = context.isImmediateNonDirect ? { a in context.invokeSync { handler(a) } } : handler super.init(source: source, dw: &dw, context: context) } // Can't have an `output` so this intial handler is the *only* handler // - Returns: a function to use as the handler prior to activation fileprivate override func initialHandlerInternal() -> (Result<OutputValue, SignalEnd>) -> Void { assert(source.unbalancedTryLock() == false) return { [userHandler] r in userHandler(r) } } // A `SignalOutput` is active until closed (receives a `failure` signal) fileprivate override var activeWithoutOutputsInternal: Bool { assert(source.unbalancedTryLock() == false) return true } /// A simple test for whether this output has received an error, yet. Not generally needed (responding to state changes is best done through the handler function itself). public var isClosed: Bool { return sync { source.delivery.isDisabled } } /// Implementatation of `Lifetime` forces deactivation public func cancel() { var dw = DeferredWork() sync { if !source.delivery.isDisabled { deactivateInternal(dueToLackOfOutputs: false, dw: &dw) } } dw.runWork() } // This is likely redundant but it's required by `Lifetime` deinit { cancel() } } @available(*, deprecated, message:"Renamed to SignalOutput") public typealias SignalEndpoint<T> = SignalOutput<T> /// Reflects the activation state of a `Signal` /// - normal: Signal will deliver results according to the default behavior of the processing context /// - disabled: Signal is closed or otherwise inactive. Attempts to send new sseiignals will have no effect. context /// - synchronous: Signal will attempt to deliver the first `Int` results in the queue synchronously. Results received from synchronous predecessors prior to the completion of activation will be inserted in the queue at the `Int` index and the `Int` value increased. Results received from predecessors with other states will be appended at the end of the queue. context fileprivate enum SignalDelivery { case normal case disabled case synchronous(Int) var isDisabled: Bool { if case .disabled = self { return true } else { return false } } var isSynchronous: Bool { if case .synchronous = self { return true } else { return false } } var isNormal: Bool { if case .normal = self { return true } else { return false } } } @available(*, unavailable, message: "SignalEnd[.closed|.cancelled], SignalSendError[.disconnected|.inactive] or SignalReactiveError.timeout instead") public typealias SignalError = SignalEnd @available(*, unavailable, message: "SignalEnd instead") public typealias SignalComplete = SignalEnd /// An enum used to represent the two "expected" end-of-stream cases. /// /// - complete: indicates the end-of-stream was reached by calling close /// - cancelled: indicates the end-of-stream was reached because an input was disconnected or cancelled /// /// There may be rare cases where `.cancelled` indicates a scenario you might want to handle specially but for all handling within the CwlSignal framework, these two are treated identically – this is expected to be the common situation in user code. There are situations where `.cancelled` may indicate programmer error (i.e. failure to retain `SignalInput` correctly) so distinguishing between the two may be important for debugging. /// /// NOTE: SignalEnd conforms to `Equatable` but this comparison merely matches cases on this enum (any two errors will compare "equal"). /// /// See also: `isSignalComplete` on `Error` and `Result<T, SignalEnd>` for easily testing if a given `Error` or `Result` contains a `SignalComplete`. public enum SignalEnd: Error, Equatable { case complete case cancelled case other(Error) public var isOther: Bool { if case .other = self { return true } else { return false } } public var isComplete: Bool { if case .complete = self { return true } else { return false } } public var isCancelled: Bool { if case .cancelled = self { return true } else { return false } } public var otherError: Error? { if case .other(let e) = self { return e } else { return nil } } public static func == (lhs: SignalEnd, rhs: SignalEnd) -> Bool { switch (lhs, rhs) { case (.complete, .complete): return true case (.cancelled, .cancelled): return true case (.other, .other): return true default: return false } } } /// For `capture`, it is possible to resend any captured values on resume. This type describe the ways which this can be done. /// /// NOTE: this applies to captured *values*. Any captured `SignalEnd` will always be emitted in the same manner as the previous value. /// /// - all: all values are resent as "activation values (exactly as they were captured) /// - deferred: all values are resent as "normal" values (not activation values) /// - first: the first captured value is sent as an "activation" value but the remainder are send as "normal" values /// - last: all except the last captured value is dropped and the last value is emitted as an "activation" value /// - none: no captured values are emitted public enum SignalActivationSelection { case all case deferred case first case last case none } /// Possible send-failure return results when sending to a `SignalInput`. This type is used as a discardable return type so it does not need to conform to Swift.Error. /// /// - disconnected: the signal input has been disconnected from its target signal /// - inactive: the signal graph is not activated (no outputs in the graph) and the Result was not sent public enum SignalSendError { case disconnected case inactive } /// Attempts to bind a `SignalInput` to a bindable handler (`SignalMergeSet`, `SignalJunction` or `SignalCapture`) can fail in two different ways. /// - cancelled: the destination `SignalInput`/`SignalMergeSet` was no longer the active input for its `Signal` (either its `Signal` is joined to something else or `Signal` has been deactivated, invalidating old inputs) /// - duplicate(`SignalInput<OutputValue>`): the source `Signal` already had an output connected and doesn't support multiple outputs so the bind failed. If the bind destination was a single `SignalInput` then that `SignalInput` was consumed by the attempt so the associated value will be a new `SignalInput` replacing the old one. public enum SignalBindError<OutputValue>: Error { case cancelled case loop case duplicate(SignalInput<OutputValue>?) } /// Used by the Signal<OutputValue>.combine(second:context:handler:) method public enum EitherResult2<U, V> { case result1(Signal<U>.Result) case result2(Signal<V>.Result) } /// Used by the Signal<OutputValue>.combine(second:third:context:handler:) method public enum EitherResult3<U, V, W> { case result1(Signal<U>.Result) case result2(Signal<V>.Result) case result3(Signal<W>.Result) } /// Used by the Signal<OutputValue>.combine(second:third:fourth:context:handler:) method public enum EitherResult4<U, V, W, X> { case result1(Signal<U>.Result) case result2(Signal<V>.Result) case result3(Signal<W>.Result) case result4(Signal<X>.Result) } /// Used by the Signal<OutputValue>.combine(second:third:fourth:fifth:context:handler:) method public enum EitherResult5<U, V, W, X, Y> { case result1(Signal<U>.Result) case result2(Signal<V>.Result) case result3(Signal<W>.Result) case result4(Signal<X>.Result) case result5(Signal<Y>.Result) }
isc
cb9cae98b6ed2a45c2baa2c26d4c61e0
50.902483
521
0.731565
3.820545
false
false
false
false
groovelab/SwiftBBS
SwiftBBS/SwiftBBS Server/UserHandler.swift
1
10803
// // UserHandler.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/16. // Copyright GrooveLab // import PerfectLib class UserHandler: BaseRequestHandler { // MARK: forms class RegisterForm : FormType { var name: String! var password: String! var password2: String! var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "name": [ ValidationType.Required, ValidationType.Length(min: 1, max: nil), ], "password": [ ValidationType.Required, ValidationType.Length(min: 8, max: nil), ], "password2": [ ValidationType.Required, ValidationType.Length(min: 8, max: nil), ValidationType.Identical(targetKey: "password") ], ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "name": name = newValue! as! String case "password": password = newValue! as! String case "password2": password2 = newValue! as! String default: break } } } } class EditForm : FormType { var name: String! var password: String? var password2: String? var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "name": [ ValidationType.Required, ValidationType.Length(min: 1, max: nil), ], "password": [ ValidationType.Length(min: 8, max: nil), ], "password2": [ ValidationType.Length(min: 8, max: nil), ValidationType.Identical(targetKey: "password") ], ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "name": name = newValue! as! String case "password": password = newValue as? String case "password2": password2 = newValue as? String default: break } } } } class LoginForm : FormType { var name: String! var password: String! var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "name": [ ValidationType.Required, ValidationType.Length(min: 1, max: nil), ], "password": [ ValidationType.Required, ValidationType.Length(min: 1, max: nil), ], ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "name": name = newValue! as! String case "password": password = newValue! as! String default: break } } } } class ApnsDeviceTokenForm : FormType { var devieToken: String! var validationRules: ValidatorManager.ValidationKeyAndRules { return [ "device_token": [ ValidationType.Required, ValidationType.Length(min: 1, max: 200), ], ] } subscript (key: String) -> Any? { get { return nil } // not use set { switch key { case "device_token": devieToken = newValue! as! String default: break } } } } // MARK: life cycle override init() { super.init() // define action acl needLoginActions = ["index", "mypage", "logout", "edit", "delete", "device_token"] redirectUrlIfNotLogin = "/user/login" noNeedLoginActions = ["login", "add"] redirectUrlIfLogin = "/" } override func dispatchAction(action: String) throws -> ActionResponse { switch request.action { case "login" where request.requestMethod() == "POST": return try doLoginAction() case "login": return try loginAction() case "logout": return try logoutAction() case "register" where request.requestMethod() == "POST": return try doRegisterAction() case "register": return try registerAction() case "edit" where request.requestMethod() == "POST": return try doEditAction() case "edit": return try editAction() case "delete" where request.requestMethod() == "POST": return try doDeleteAction() case "apns_device_token" where request.requestMethod() == "POST": return try doApnsDeviceTokenAction() default: return try mypageAction() } } // MARK: actions func mypageAction() throws -> ActionResponse { return .Output(templatePath: "user_mypage.mustache", values: [String: Any]()) } func editAction() throws -> ActionResponse { return .Output(templatePath: "user_edit.mustache", values: [String: Any]()) } func doEditAction() throws -> ActionResponse { var form = EditForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // update let userEntity = UserEntity(id: try userIdInSession(), name: form.name, password: form.password) try userRepository.update(userEntity) if request.acceptJson { var values = [String: Any]() values["status"] = "success" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/user/mypage") } } func doDeleteAction() throws -> ActionResponse { // delete guard let userEntity = try getUser(userIdInSession()) else { return .Error(status: 404, message: "not found user") } try userRepository.delete(userEntity) logout() if request.acceptJson { var values = [String: Any]() values["status"] = "success" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/bbs") } } func registerAction() throws -> ActionResponse { return .Output(templatePath: "user_register.mustache", values: [String: Any]()) } func doRegisterAction() throws -> ActionResponse { var form = RegisterForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // insert let userEntity = UserEntity(id: nil, name: form.name, password: form.password) try userRepository.insert(userEntity) // do login let isLoginSuccess = try login(form.name, password: form.password) if request.acceptJson { var values = [String: Any]() values["status"] = isLoginSuccess ? "success" : "failed" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: isLoginSuccess ? "/bbs" : "/user/login") /// TODO:add login success or failed message } } func loginAction() throws -> ActionResponse { var values = [String: Any]() values["lineLoginEnabled"] = !Config.lineChannelId.isEmpty values["githubLoginEnabled"] = !Config.gitHubClientId.isEmpty values["facebookLoginEnabled"] = !Config.facebookAppId.isEmpty values["googleLoginEnabled"] = !Config.googleClientId.isEmpty return .Output(templatePath: "user_login.mustache", values: values) } func doLoginAction() throws -> ActionResponse { var form = LoginForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // check exist let isLoginSuccess = try login(form.name, password: form.password) if request.acceptJson { var values = [String: Any]() values["status"] = isLoginSuccess ? "success" : "failed" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: isLoginSuccess ? "/bbs" : "/user/login") /// TODO:add login success or failed message } } func logoutAction() throws -> ActionResponse { logout() if request.acceptJson { var values = [String: Any]() values["status"] = "success" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/user/login") } } func doApnsDeviceTokenAction() throws -> ActionResponse { var form = ApnsDeviceTokenForm() do { try form.validate(request) } catch let error as FormError { return .Error(status: 500, message: "invalidate request parameter. " + error.description) } // update var userEntity = try getUser(userIdInSession())! userEntity.apnsDeviceToken = form.devieToken try userRepository.update(userEntity) if request.acceptJson { var values = [String: Any]() values["status"] = "success" return .Output(templatePath: nil, values: values) } else { return .Redirect(url: "/user/mypage") } } // TODO: create UserService with login method private func login(name: String, password: String) throws -> Bool { if let userEntity = try userRepository.findByName(name, password: password), let userId = userEntity.id { // success login session["id"] = String(userId) return true } else { return false } } // TODO: create UserService with logout method private func logout() { session["id"] = nil } }
mit
8152edac56498b300477d2a0cd89fbc6
32.24
121
0.520689
4.846568
false
false
false
false
elimelec/boids
Boid/Rules.swift
1
3223
import UIKit class Rule: NSObject { var velocity: CGPoint! var weight: CGFloat var frame: CGRect var weighted: CGPoint { return CGPoint(x: velocity.x * weight, y: velocity.y * weight) } init(weight: CGFloat, frame: CGRect) { self.weight = weight self.frame = frame super.init() clear() } func clear() { velocity = CGPoint(x: 0.0, y: 0.0) } func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { clear() } } class AlignmentRule: Rule { let factor: CGFloat = 2.0 let range = 300.0 override func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { super.evaluate(targetNode: targetNode, birdNodes: birdNodes) var boidsInCurrentGroup = 0 for birdNode in birdNodes { if birdNode == targetNode { continue } if distanceBetween(birdNode.position, targetNode.position) > range { continue } boidsInCurrentGroup += 1 velocity.x += birdNode.velocity.x velocity.y += birdNode.velocity.y } if boidsInCurrentGroup <= 1 { return } velocity.x /= CGFloat(boidsInCurrentGroup) velocity.y /= CGFloat(boidsInCurrentGroup) velocity.x = (velocity.x - targetNode.velocity.x) / factor velocity.y = (velocity.y - targetNode.velocity.y) / factor } } class CohesionRule: Rule { var factorX: CGFloat { return CGRectGetWidth(frame) } var factorY: CGFloat { return CGRectGetHeight(frame) } let range = 300.0 override func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { super.evaluate(targetNode: targetNode, birdNodes: birdNodes) var boidsInCurrentGroup = 0 for birdNode in birdNodes { if birdNode == targetNode { continue } if distanceBetween(birdNode.position, targetNode.position) > range { continue } boidsInCurrentGroup += 1 velocity.x += birdNode.position.x velocity.y += birdNode.position.y } if boidsInCurrentGroup <= 1 { return } velocity.x /= CGFloat(boidsInCurrentGroup) velocity.y /= CGFloat(boidsInCurrentGroup) velocity.x = (velocity.x - targetNode.position.x) / factorX velocity.y = (velocity.y - targetNode.position.y) / factorY } } class NoiseRule: Rule { override func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { super.evaluate(targetNode: targetNode, birdNodes: birdNodes) velocity = CGPoint(x:drand48() - 0.5, y:drand48() - 0.5) } } class SeparationRule: Rule { let threshold = 30.0 override func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { super.evaluate(targetNode: targetNode, birdNodes: birdNodes) for birdNode in birdNodes { if birdNode != targetNode { if distanceBetween(targetNode.position, birdNode.position) < threshold { velocity.x -= birdNode.position.x - targetNode.position.x velocity.y -= birdNode.position.y - targetNode.position.y } } } } }
mit
4dae3422a36aedbb5c0f012dd2283052
24.579365
88
0.623022
3.91616
false
false
false
false
RayTao/CoreAnimation_Collection
CoreAnimation_Collection/ZYSpreadButtonViewController.swift
1
7562
// // ZYSpreadButtonViewController.swift // CoreAnimation_Collection // // Created by ray on 16/2/23. // Copyright © 2016年 ray. All rights reserved. // import UIKit class ZYSpreadButtonViewController: UIViewController { lazy var changePositionModeButton: UIButton = { let button = UIButton.init(frame: CGRect(x: 0, y: 0, width: 200, height: 45)) button.center = self.view.center button.setTitle(" ModeFixed ", for: UIControlState()) button.addTarget(self, action: #selector(ZYSpreadButtonViewController.changePositionMode(_:)), for: UIControlEvents.touchUpInside) return button }() var spreadButton: SpreadButton! //swift var zySpreadButton: ZYSpreadButton! //objc override func viewDidLoad() { super.viewDidLoad() configureButtonCorner() // runWithSwiftCode(); runWithObjcCode(); self.view.addSubview(self.changePositionModeButton) } //ObjC func runWithObjcCode() { let btn1 = ZYSpreadSubButton(backgroundImage: UIImage(named: "clock"), highlight: UIImage(named: "clock_highlight")) { (index, sender) -> Void in print("第\(index+1)个按钮被按了") }! let btn2 = ZYSpreadSubButton(backgroundImage: UIImage(named: "pencil"), highlight: UIImage(named: "pencil_highlight")) { (index, sender) -> Void in print("第\(index+1)个按钮被按了") }! let btn3 = ZYSpreadSubButton(backgroundImage: UIImage(named: "juice"), highlight: UIImage(named: "juice_highlight")) { (index, sender) -> Void in print("第\(index+1)个按钮被按了") }! let btn4 = ZYSpreadSubButton(backgroundImage: UIImage(named: "service"), highlight: UIImage(named: "service_highlight")) { (index, sender) -> Void in print("第\(index+1)个按钮被按了") }! let btn5 = ZYSpreadSubButton(backgroundImage: UIImage(named: "shower"), highlight: UIImage(named: "shower_highlight")) { (index, sender) -> Void in print("第\(index+1)个按钮被按了") }! let zySpreadButton = ZYSpreadButton(backgroundImage: UIImage(named: "powerButton"), highlight: UIImage(named: "powerButton_highlight"), position: CGPoint(x: 40, y: UIScreen.main.bounds.height - 40)) self.zySpreadButton = zySpreadButton; zySpreadButton?.subButtons = [btn1, btn2, btn3, btn4, btn5] zySpreadButton?.mode = SpreadModeSickleSpread zySpreadButton?.direction = SpreadDirectionRightUp zySpreadButton?.radius = 120 zySpreadButton?.positionMode = SpreadPositionModeFixed /* and you can assign a newValue to change the default spreadButton?.animationDuring = 0.2 spreadButton?.animationDuringClose = 0.25 spreadButton?.radius = 180 spreadButton?.coverAlpha = 0.3 spreadButton?.coverColor = UIColor.yellowColor() spreadButton?.touchBorderMargin = 10.0 */ //you can assign the Blocks like this zySpreadButton?.buttonWillSpreadBlock = { print("\(String(describing: $0?.frame.maxY)) will spread") } zySpreadButton?.buttonDidSpreadBlock = { _ in print("did spread") } zySpreadButton?.buttonWillCloseBlock = { _ in print("will closed") } zySpreadButton?.buttonDidCloseBlock = { _ in print("did closed") } if zySpreadButton != nil { self.view.addSubview(zySpreadButton!) } } //Swift func runWithSwiftCode() { let btn1 = SpreadSubButton(backgroundImage: UIImage(named: "clock"), highlightImage: UIImage(named: "clock_highlight")) { (index, sender) -> Void in print("first") } let btn2 = SpreadSubButton(backgroundImage: UIImage(named: "pencil"), highlightImage: UIImage(named: "pencil_highlight")) { (index, sender) -> Void in print("second") } let btn3 = SpreadSubButton(backgroundImage: UIImage(named: "juice"), highlightImage: UIImage(named: "juice_highlight")) { (index, sender) -> Void in print("third") } let btn4 = SpreadSubButton(backgroundImage: UIImage(named: "service"), highlightImage: UIImage(named: "service_highlight")) { (index, sender) -> Void in print("fourth") } let btn5 = SpreadSubButton(backgroundImage: UIImage(named: "shower"), highlightImage: UIImage(named: "shower_highlight")) { (index, sender) -> Void in print("fifth") } let spreadButton = SpreadButton(image: UIImage(named: "powerButton"), highlightImage: UIImage(named: "powerButton_highlight"), position: CGPoint(x: 40, y: UIScreen.main.bounds.height - 40)) self.spreadButton = spreadButton spreadButton?.setSubButtons([btn1, btn2, btn3, btn4, btn5]) spreadButton?.mode = SpreadMode.spreadModeSickleSpread spreadButton?.direction = SpreadDirection.spreadDirectionRightUp spreadButton?.radius = 120 spreadButton?.positionMode = SpreadPositionMode.spreadPositionModeFixed /* and you can assign a newValue to change the default spreadButton?.animationDuring = 0.2 spreadButton?.animationDuringClose = 0.25 spreadButton?.radius = 180 spreadButton?.coverAlpha = 0.3 spreadButton?.coverColor = UIColor.yellowColor() spreadButton?.touchBorderMargin = 10.0 */ //you can assign the Blocks like this spreadButton?.buttonWillSpreadBlock = { print($0.frame.maxY) } spreadButton?.buttonDidSpreadBlock = { _ in print("did spread") } spreadButton?.buttonWillCloseBlock = { _ in print("will closed") } spreadButton?.buttonDidCloseBlock = { _ in print("did closed") } if spreadButton != nil { self.view.addSubview(spreadButton!) } } func changePositionMode(_ sender: AnyObject) { //display with Swift Code if spreadButton != nil { if spreadButton?.positionMode == SpreadPositionMode.spreadPositionModeFixed { spreadButton?.positionMode = SpreadPositionMode.spreadPositionModeTouchBorder sender.setTitle(" ModeTouchBorder ", for: UIControlState()) } else { spreadButton?.positionMode = SpreadPositionMode.spreadPositionModeFixed sender.setTitle(" ModeFixed ", for: UIControlState()) } } //display with OC Code if zySpreadButton != nil { if zySpreadButton.positionMode == SpreadPositionModeFixed { zySpreadButton.positionMode = SpreadPositionModeTouchBorder sender.setTitle(" ModeTouchBorder ", for: UIControlState()) } else { zySpreadButton.positionMode = SpreadPositionModeFixed sender.setTitle(" ModeFixed ", for: UIControlState()) } } } func configureButtonCorner() { changePositionModeButton.layer.cornerRadius = changePositionModeButton.bounds.height/2 changePositionModeButton.layer.masksToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9f11c90e2e8a7dae72786afaa71dcb9d
40.605556
206
0.623715
4.527811
false
false
false
false
rawrjustin/Bridge
BridgeExamples.playground/Contents.swift
1
3571
//: Playground - noun: a place where people can play import UIKit import Bridge import XCPlayground import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true // QUERY: GET request to http://httpbin.org/ip // RESPONSE: Returns Dictionary<String, AnyObject> Bridge.sharedInstance.baseURL = URL(string: "http://httpbin.org/")! GET<Dict>("http://httpbin.org/ip").execute(success: { (response) in let ip: Dict = response }) // This is an example of using variables within your endpoints // This is useful when you have resource ids // QUERY: GET request to http://jsonplaceholder.typicode.com/posts/# where '#' is a variable // RESPONSE: Returns a Post object or a Post collection Bridge.sharedInstance.baseURL = URL(string: "http://jsonplaceholder.typicode.com/")! class Post: Parseable { var userID: Int? var title: String? static func parseResponseObject(_ responseObject: Any) throws -> Any { if let dict = responseObject as? Dict { let post = Post() post.userID = dict["userId"] as? Int post.title = dict["title"] as? String return post } else if let dicts = responseObject as? Array<Dict> { var posts = Array<Post>() for dict in dicts { if let serializedPost = try? Post.parseResponseObject(dict), let post = serializedPost as? Post { posts.append(post) } } return posts } // If parsing encounters an error, throw enum that conforms to ErrorType. throw BridgeErrorType.parsing } } let postID = "1" GET<Post>("posts/#").execute(postID, success: { (response) in let userID = response.userID let title = response.title }) GET<Array<Post>>("posts").execute("", success: { (response) in let posts = response }) // This is an example of using a custom class as a return type. // QUERY: GET request to https://api.github.com/users/rawrjustin // RESPONSE: Returns a User object class NSUser: NSObject, Parseable { var name: String? var email: String? var pictureURL: URL? static func parseResponseObject(_ responseObject: Any) throws -> Any { if let dict = responseObject as? Dict { let user = NSUser() user.name = dict["name"] as? String user.email = dict["email"] as? String user.pictureURL = URL(string: dict["avatar_url"] as! String) return user } // If parsing encounters an error, throw enum that conforms to ErrorType. throw BridgeErrorType.parsing } } class User: Parseable { var name: String? var email: String? var pictureURL: URL? static func parseResponseObject(_ responseObject: Any) throws -> Any { if let dict = responseObject as? Dict { let user = User() user.name = dict["name"] as? String user.email = dict["email"] as? String user.pictureURL = URL(string: dict["avatar_url"] as! String) return user } // If parsing encounters an error, throw enum that conforms to ErrorType. throw BridgeErrorType.parsing } } GET<NSUser>("https://api.github.com/users/rawrjustin").execute(success: { (user: NSUser) in let name = user.name let email = user.email let url = user.pictureURL }) GET<User>("https://api.github.com/users/johnny-zumper").execute(success: { (user: User) in let name = user.name let email = user.email let url = user.pictureURL })
mit
8f055e224ce817e1e540c4a6b735aa2d
31.171171
113
0.635396
4.186401
false
false
false
false
YoungGary/DYTV
DouyuTV/DouyuTV/Class/First(首页)/View/TopicCollectionView.swift
1
3086
// // TopicCollectionView.swift // DouyuTV // // Created by YOUNG on 2017/4/7. // Copyright © 2017年 Young. All rights reserved. // 游戏页面中的上方的游戏collectionView import UIKit import Kingfisher private let topicCell = "topic" class TopicCollectionView: UIView { var dataArr : [Groups] = [Groups](){ didSet{ dataArr.removeFirst() if dataArr.count > 15 { dataArr.removeLast(dataArr.count - 15) let more = Groups() more.tag_name = "更多" dataArr.append(more) }else{ } collectionView.reloadData() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! class func loadViewWithNib() -> TopicCollectionView{ return (Bundle.main.loadNibNamed("TopicCollectionView", owner: nil, options: nil)?.first) as! TopicCollectionView } override func awakeFromNib() { super.awakeFromNib() self.autoresizingMask = UIViewAutoresizing() flowLayout.itemSize = CGSize(width: kScreenWidth/4, height: 100) flowLayout.scrollDirection = .horizontal flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.dataSource = self collectionView.backgroundColor = UIColor.white collectionView.contentSize = CGSize(width: kScreenWidth * 2, height: 200) let nib = UINib(nibName: "SelectCollectionViewCell", bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: topicCell) } } extension TopicCollectionView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: topicCell, for: indexPath) as! SelectCollectionViewCell let model = dataArr[indexPath.row] //label cell.label.text = model.tag_name cell.label.font = UIFont.systemFont(ofSize: 12) //image let url = URL(string: model.icon_url) let placeholder = UIImage(named: "home_column_more_49x49_") cell.back_image.kf.setImage(with: url, placeholder: placeholder) cell.back_image.layer .cornerRadius = cell.back_image.bounds.size.width/2 cell.back_image.layer.masksToBounds = true return cell } }
mit
c1fb70bb07b9ad3182e5a11e998ffc41
29.57
130
0.596663
5.588665
false
false
false
false
DanielFulton/ImageLibraryTests
Pods/AlamofireImage/Source/ImageCache.swift
2
12776
// ImageCache.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(OSX) import Cocoa #endif // MARK: ImageCache /// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache. public protocol ImageCache { /// Adds the image to the cache with the given identifier. func addImage(image: Image, withIdentifier identifier: String) /// Removes the image from the cache matching the given identifier. func removeImageWithIdentifier(identifier: String) -> Bool /// Removes all images stored in the cache. func removeAllImages() -> Bool /// Returns the image in the cache associated with the given identifier. func imageWithIdentifier(identifier: String) -> Image? } /// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and /// fetching images from a cache given an `NSURLRequest` and additional identifier. public protocol ImageRequestCache: ImageCache { /// Adds the image to the cache using an identifier created from the request and additional identifier. func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String?) /// Removes the image from the cache using an identifier created from the request and additional identifier. func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool /// Returns the image from the cache associated with an identifier created from the request and additional identifier. func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Image? } // MARK: - /// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When /// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously /// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the /// internal access date of the image is updated. public class AutoPurgingImageCache: ImageRequestCache { private class CachedImage { let image: Image let identifier: String let totalBytes: UInt64 var lastAccessDate: NSDate init(_ image: Image, identifier: String) { self.image = image self.identifier = identifier self.lastAccessDate = NSDate() self.totalBytes = { #if os(iOS) || os(tvOS) || os(watchOS) let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale) #elseif os(OSX) let size = CGSize(width: image.size.width, height: image.size.height) #endif let bytesPerPixel: CGFloat = 4.0 let bytesPerRow = size.width * bytesPerPixel let totalBytes = UInt64(bytesPerRow) * UInt64(size.height) return totalBytes }() } func accessImage() -> Image { lastAccessDate = NSDate() return image } } // MARK: Properties /// The current total memory usage in bytes of all images stored within the cache. public var memoryUsage: UInt64 { var memoryUsage: UInt64 = 0 dispatch_sync(synchronizationQueue) { memoryUsage = self.currentMemoryUsage } return memoryUsage } /// The total memory capacity of the cache in bytes. public let memoryCapacity: UInt64 /// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory /// capacity drops below this limit. public let preferredMemoryUsageAfterPurge: UInt64 private let synchronizationQueue: dispatch_queue_t private var cachedImages: [String: CachedImage] private var currentMemoryUsage: UInt64 // MARK: Initialization /** Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage after purge limit. Please note, the memory capacity must always be greater than or equal to the preferred memory usage after purge. - parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default. - parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default. - returns: The new `AutoPurgingImageCache` instance. */ public init(memoryCapacity: UInt64 = 100_000_000, preferredMemoryUsageAfterPurge: UInt64 = 60_000_000) { self.memoryCapacity = memoryCapacity self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge precondition( memoryCapacity >= preferredMemoryUsageAfterPurge, "The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge`" ) self.cachedImages = [:] self.currentMemoryUsage = 0 self.synchronizationQueue = { let name = String(format: "com.alamofire.autopurgingimagecache-%08x%08x", arc4random(), arc4random()) return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT) }() #if os(iOS) || os(tvOS) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(AutoPurgingImageCache.removeAllImages), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil ) #endif } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Add Image to Cache /** Adds the image to the cache using an identifier created from the request and optional identifier. - parameter image: The image to add to the cache. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. */ public func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) addImage(image, withIdentifier: requestIdentifier) } /** Adds the image to the cache with the given identifier. - parameter image: The image to add to the cache. - parameter identifier: The identifier to use to uniquely identify the image. */ public func addImage(image: Image, withIdentifier identifier: String) { dispatch_barrier_async(synchronizationQueue) { let cachedImage = CachedImage(image, identifier: identifier) if let previousCachedImage = self.cachedImages[identifier] { self.currentMemoryUsage -= previousCachedImage.totalBytes } self.cachedImages[identifier] = cachedImage self.currentMemoryUsage += cachedImage.totalBytes } dispatch_barrier_async(synchronizationQueue) { if self.currentMemoryUsage > self.memoryCapacity { let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge var sortedImages = [CachedImage](self.cachedImages.values) sortedImages.sortInPlace { let date1 = $0.lastAccessDate let date2 = $1.lastAccessDate return date1.timeIntervalSinceDate(date2) < 0.0 } var bytesPurged = UInt64(0) for cachedImage in sortedImages { self.cachedImages.removeValueForKey(cachedImage.identifier) bytesPurged += cachedImage.totalBytes if bytesPurged >= bytesToPurge { break } } self.currentMemoryUsage -= bytesPurged } } } // MARK: Remove Image from Cache /** Removes the image from the cache using an identifier created from the request and optional identifier. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. - returns: `true` if the image was removed, `false` otherwise. */ public func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) return removeImageWithIdentifier(requestIdentifier) } /** Removes the image from the cache matching the given identifier. - parameter identifier: The unique identifier for the image. - returns: `true` if the image was removed, `false` otherwise. */ public func removeImageWithIdentifier(identifier: String) -> Bool { var removed = false dispatch_barrier_async(synchronizationQueue) { if let cachedImage = self.cachedImages.removeValueForKey(identifier) { self.currentMemoryUsage -= cachedImage.totalBytes removed = true } } return removed } /** Removes all images stored in the cache. - returns: `true` if images were removed from the cache, `false` otherwise. */ @objc public func removeAllImages() -> Bool { var removed = false dispatch_sync(synchronizationQueue) { if !self.cachedImages.isEmpty { self.cachedImages.removeAll() self.currentMemoryUsage = 0 removed = true } } return removed } // MARK: Fetch Image from Cache /** Returns the image from the cache associated with an identifier created from the request and optional identifier. - parameter request: The request used to generate the image's unique identifier. - parameter identifier: The additional identifier to append to the image's unique identifier. - returns: The image if it is stored in the cache, `nil` otherwise. */ public func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) -> Image? { let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier) return imageWithIdentifier(requestIdentifier) } /** Returns the image in the cache associated with the given identifier. - parameter identifier: The unique identifier for the image. - returns: The image if it is stored in the cache, `nil` otherwise. */ public func imageWithIdentifier(identifier: String) -> Image? { var image: Image? dispatch_sync(synchronizationQueue) { if let cachedImage = self.cachedImages[identifier] { image = cachedImage.accessImage() } } return image } // MARK: Private - Helper Methods private func imageCacheKeyFromURLRequest( request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> String { var key = request.URLString if let identifier = identifier { key += "-\(identifier)" } return key } }
mit
71d076805be5991e312644e96335e9b8
37.715152
126
0.668284
5.455167
false
false
false
false
ever223/Fissure
Fissure/GameView.swift
1
4743
// // GameView.swift // Fissure // // Created by xiaoo_gan on 10/17/15. // Copyright © 2015 xiaoo_gan. All rights reserved. // import SpriteKit class GameView: UIView { let menuSizeRatio: CGFloat = 0.85 let menuButtonVertInsert: CGFloat = 10 let menuButtonHorzInsert: CGFloat = 10 let numOfLevels = 36 let numOfRows = 6 let numOfCols = 6 var sceneView: SKView! var scene: GameScene! let menuButton = UIButton(type: .Custom) let restartButton = UIButton(type: .Custom) let closeMenuButton = UIButton(type: .Custom) let snapButton = UIButton() let nextButton = UIButton() var levelMenuView: UIView! var levelButtons = [UIButton]() var starImageViews = [UIImageView]() var titleImage: UIImageView! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clearColor() sceneView = SKView(frame: bounds) sceneView.showsFPS = false sceneView.showsNodeCount = false sceneView.showsDrawCount = false addSubview(sceneView) scene = GameScene(size: bounds.size) sceneView.presentScene(scene) menuButton.frame = CGRect(x: bounds.size.width - 40, y: 0, width: 40, height: 40) let mImage = UIImageView(image: UIImage(named: "icon_menu")) mImage.frame = CGRect(x: 15, y: 5, width: 20, height: 20) mImage.alpha = 1.0 menuButton.addSubview(mImage) addSubview(menuButton) restartButton.frame = CGRect(x: bounds.size.width - 40, y: bounds.size.height - 40, width: 40, height: 40) let rImage = UIImageView(image: UIImage(named: "icon_restart")) rImage.frame = CGRect(x: 15, y: 15, width: 20, height: 20) rImage.alpha = 1.0 restartButton.addSubview(rImage) addSubview(restartButton) levelMenuView = UIView(frame: bounds) levelMenuView.alpha = 0 levelMenuView.backgroundColor = UIColor(white: 1, alpha: 1) titleImage = UIImageView(image: UIImage(named: "title")) titleImage.center = CGPoint(x: bounds.size.width / 2, y: 29) levelMenuView.addSubview(titleImage) closeMenuButton.frame = levelMenuView.bounds levelMenuView.addSubview(closeMenuButton) addSubview(levelMenuView) loadLevelButtons() } private func loadLevelButtons() { let menuWidth = bounds.size.width * menuSizeRatio let menuHeight = bounds.size.height * menuSizeRatio let initalXOffset = ((bounds.size.width - menuWidth) / 2) let initalYOffset = ((bounds.size.height - menuHeight) / 2) let buttonWidth = (menuWidth - (numOfCols + 1).cgf * menuButtonHorzInsert) / numOfCols.cgf let buttonHeight = (menuHeight - (numOfRows + 1).cgf * menuButtonVertInsert) / numOfRows.cgf let buttonOffsetX = buttonWidth + menuButtonHorzInsert let buttonOffsetY = buttonHeight + menuButtonVertInsert var levelIndex = 0 for i in 0..<numOfRows { for j in 0..<numOfCols { let levelButton = UIButton(type: .Custom) levelButton.backgroundColor = UIColor(red: 0.92, green: 0.92, blue: 0.92, alpha: 1.0) levelButton.frame = CGRect(x: CGFloat(j) * buttonOffsetX + menuButtonHorzInsert + initalXOffset, y: CGFloat(i) * buttonOffsetY + menuButtonVertInsert + initalYOffset, width: buttonWidth, height: buttonHeight) let levelTitle = LevelManager.shareInstance().levelIdAtPosition(levelIndex) let bImage = UIImage(named: levelTitle) levelButton.setImage(bImage, forState: .Normal) levelButton.tag = levelIndex levelButton.layer.shadowColor = UIColor.blackColor().CGColor levelButton.layer.shadowOffset = CGSize(width: 0, height: 0) levelButton.layer.shadowOpacity = 0.5 levelButton.layer.shadowRadius = 2 levelButton.layer.shouldRasterize = true levelButton.layer.rasterizationScale = UIScreen.mainScreen().scale levelMenuView.addSubview(levelButton) levelButtons.append(levelButton) levelIndex++ let star = UIImageView(image: UIImage(named: "star-mini")) star.center = CGPoint(x: buttonWidth - 2, y: buttonHeight - 3) levelButton.addSubview(star) starImageViews.append(star) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bf7ae2dae670be55aab1f241a788ad82
38.848739
224
0.620835
4.49053
false
false
false
false
rudkx/swift
test/type/opaque.swift
1
17358
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify -requirement-machine-abstract-signatures=verify %s protocol P { func paul() mutating func priscilla() } protocol Q { func quinn() } extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } class C {} class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {}; func d() {} } let property: some P = 1 let deflessLet: some P // expected-error{{has no initializer}} {{educational-notes=opaque-type-inference}} var deflessVar: some P // expected-error{{has no initializer}} struct GenericProperty<T: P> { var x: T var property: some P { return x } } let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}} var computedProperty: some P { get { return 1 } set { _ = newValue + 1 } // expected-error{{cannot convert value of type 'some P' to expected argument type 'Int'}} } struct SubscriptTest { subscript(_ x: Int) -> some P { return x } } func bar() -> some P { return 1 } func bas() -> some P & Q { return 1 } func zim() -> some C { return D() } func zang() -> some C & P & Q { return D() } func zung() -> some AnyObject { return D() } func zoop() -> some Any { return D() } func zup() -> some Any & P { return D() } func zip() -> some AnyObject & P { return D() } func zorp() -> some Any & C & P { return D() } func zlop() -> some C & AnyObject & P { return D() } // Don't allow opaque types to propagate by inference into other global decls' // types struct Test { let inferredOpaque = bar() // expected-error{{inferred type}} let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}} let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}} } let zingle = {() -> some P in 1 } // expected-error{{'some' types are only permitted}} func twoOpaqueTypes() -> (some P, some P) { return (1, 2) } func asArrayElem() -> [some P] { return [1] } // Invalid positions typealias Foo = some P // expected-error{{'some' types are only permitted}} func blibble(blobble: some P) {} func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}} func blab() -> some P? { return 1 } // expected-error{{must specify only}} expected-note{{did you mean to write an optional of an 'opaque' type?}} func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only permitted}} func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only permitted}} expected-error{{cannot convert}} protocol OP: some P {} // expected-error{{'some' types are only permitted}} func foo() -> some P { let x = (some P).self // expected-error*{{}} return 1 } // Invalid constraints let zug: some Int = 1 // FIXME expected-error{{must specify only}} let zwang: some () = () // FIXME expected-error{{must specify only}} let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}} // Type-checking of expressions of opaque type func alice() -> some P { return 1 } func bob() -> some P { return 1 } func grace<T: P>(_ x: T) -> some P { return x } func typeIdentity() { do { var a = alice() a = alice() a = bob() // expected-error{{}} a = grace(1) // expected-error{{}} a = grace("two") // expected-error{{}} } do { var af = alice af = alice af = bob // expected-error{{}} af = grace // expected-error{{generic parameter 'T' could not be inferred}} // expected-error@-1 {{cannot assign value of type '(T) -> some P' to type '() -> some P'}} } do { var b = bob() b = alice() // expected-error{{}} b = bob() b = grace(1) // expected-error{{}} b = grace("two") // expected-error{{}} } do { var gi = grace(1) gi = alice() // expected-error{{}} gi = bob() // expected-error{{}} gi = grace(2) gi = grace("three") // expected-error{{}} } do { var gs = grace("one") gs = alice() // expected-error{{}} gs = bob() // expected-error{{}} gs = grace(2) // expected-error{{}} gs = grace("three") } // The opaque type should conform to its constraining protocols do { let gs = grace("one") var ggs = grace(gs) ggs = grace(gs) } // The opaque type should expose the members implied by its protocol // constraints do { var a = alice() a.paul() a.priscilla() } } func recursion(x: Int) -> some P { if x == 0 { return 0 } return recursion(x: x - 1) } func noReturnStmts() -> some P {} // expected-error {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} {{educational-notes=opaque-type-inference}} func returnUninhabited() -> some P { // expected-note {{opaque return type declared here}} fatalError() // expected-error{{return type of global function 'returnUninhabited()' requires that 'Never' conform to 'P'}} } func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}} {{educational-notes=opaque-type-inference}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}} if true { return 0 // expected-note{{underlying type 'Int'}} } else { return "" // expected-note{{underlying type 'String'}} } } struct MismatchedReturnTypesSubscript { subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } } func jan() -> some P { return [marcia(), marcia(), marcia()] } func marcia() -> some P { return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}} {{educational-notes=opaque-type-inference}} } protocol R { associatedtype S: P, Q // expected-note*{{}} func r_out() -> S func r_in(_: S) } extension Int: R { func r_out() -> String { return "" } func r_in(_: String) {} } func candace() -> some R { return 0 } func doug() -> some R { return 0 } func gary<T: R>(_ x: T) -> some R { return x } func sameType<T>(_: T, _: T) {} func associatedTypeIdentity() { let c = candace() let d = doug() var cr = c.r_out() cr = candace().r_out() cr = doug().r_out() // expected-error{{}} var dr = d.r_out() dr = candace().r_out() // expected-error{{}} dr = doug().r_out() c.r_in(cr) c.r_in(c.r_out()) c.r_in(dr) // expected-error{{}} c.r_in(d.r_out()) // expected-error{{}} d.r_in(cr) // expected-error{{}} d.r_in(c.r_out()) // expected-error{{}} d.r_in(dr) d.r_in(d.r_out()) cr.paul() cr.priscilla() cr.quinn() dr.paul() dr.priscilla() dr.quinn() sameType(cr, c.r_out()) sameType(dr, d.r_out()) sameType(cr, dr) // expected-error {{conflicting arguments to generic parameter 'T' ('(some R).S' (result type of 'candace') vs. '(some R).S' (result type of 'doug'))}} sameType(gary(candace()).r_out(), gary(candace()).r_out()) sameType(gary(doug()).r_out(), gary(doug()).r_out()) // TODO(diagnostics): This is not great but the problem comes from the way solver discovers and attempts bindings, if we could detect that // `(some R).S` from first reference to `gary()` in incosistent with the second one based on the parent type of `S` it would be much easier to diagnose. sameType(gary(doug()).r_out(), gary(candace()).r_out()) // expected-error@-1:12 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} // expected-error@-2:34 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} } func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } func redeclaration() -> Any { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} struct RedeclarationTest { func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some P { return 0 } // expected-note 2{{previously declared}} subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some Q { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> P { return 0 } } func diagnose_requirement_failures() { struct S { var foo: some P { return S() } // expected-note {{declared here}} // expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}} subscript(_: Int) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}} } func bar() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}} } static func baz(x: String) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}} } } func fn() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}} } } func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}} return 42 as Double // expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}} } func recursive_func_is_invalid_opaque() { func rec(x: Int) -> some P { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} if x == 0 { return rec(x: 0) } return rec(x: x - 1) } } func closure() -> some P { _ = { return "test" } return 42 } protocol HasAssocType { associatedtype Assoc func assoc() -> Assoc } struct GenericWithOpaqueAssoc<T>: HasAssocType { func assoc() -> some Any { return 0 } } struct OtherGeneric<X, Y, Z> { var x: GenericWithOpaqueAssoc<X>.Assoc var y: GenericWithOpaqueAssoc<Y>.Assoc var z: GenericWithOpaqueAssoc<Z>.Assoc } protocol P_51641323 { associatedtype T var foo: Self.T { get } } func rdar_51641323() { struct Foo: P_51641323 { var foo: some P_51641323 { // expected-note {{required by opaque return type of property 'foo'}} {} // expected-error {{type '() -> ()' cannot conform to 'P_51641323'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} } } } // Protocol requirements cannot have opaque return types protocol OpaqueProtocolRequirement { // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{21-27=<#AssocType#>}} func method1() -> some P // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: C & P & Q\n}}{{21-35=<#AssocType#>}} func method2() -> some C & P & Q // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: Nonsense\n}}{{21-34=<#AssocType#>}} func method3() -> some Nonsense // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{13-19=<#AssocType#>}} var prop: some P { get } // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{18-24=<#AssocType#>}} subscript() -> some P { get } } func testCoercionDiagnostics() { var opaque = foo() opaque = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaque = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} opaque = computedProperty // expected-error {{cannot assign value of type 'some P' (type of 'computedProperty') to type 'some P' (result of 'foo()')}} {{none}} opaque = SubscriptTest()[0] // expected-error {{cannot assign value of type 'some P' (result of 'SubscriptTest.subscript(_:)') to type 'some P' (result of 'foo()')}} {{none}} var opaqueOpt: Optional = opaque opaqueOpt = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaqueOpt = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} } var globalVar: some P = 17 let globalLet: some P = 38 struct Foo { static var staticVar: some P = 17 static let staticLet: some P = 38 var instanceVar: some P = 17 let instanceLet: some P = 38 } protocol P_52528543 { init() associatedtype A: Q_52528543 var a: A { get } } protocol Q_52528543 { associatedtype B // expected-note 2 {{associated type 'B'}} var b: B { get } } extension P_52528543 { func frob(a_b: A.B) -> some P_52528543 { return self } } func foo<T: P_52528543>(x: T) -> some P_52528543 { return x .frob(a_b: x.a.b) .frob(a_b: x.a.b) // expected-error {{cannot convert}} } struct GenericFoo<T: P_52528543, U: P_52528543> { let x: some P_52528543 = T() let y: some P_52528543 = U() mutating func bump() { var xab = f_52528543(x: x) xab = f_52528543(x: y) // expected-error{{cannot assign}} } } func f_52528543<T: P_52528543>(x: T) -> T.A.B { return x.a.b } func opaque_52528543<T: P_52528543>(x: T) -> some P_52528543 { return x } func invoke_52528543<T: P_52528543, U: P_52528543>(x: T, y: U) { let x2 = opaque_52528543(x: x) let y2 = opaque_52528543(x: y) var xab = f_52528543(x: x2) xab = f_52528543(x: y2) // expected-error{{cannot assign}} } protocol Proto {} struct I : Proto {} dynamic func foo<S>(_ s: S) -> some Proto { return I() } @_dynamicReplacement(for: foo) func foo_repl<S>(_ s: S) -> some Proto { return I() } protocol SomeProtocolA {} protocol SomeProtocolB {} struct SomeStructC: SomeProtocolA, SomeProtocolB {} let someProperty: SomeProtocolA & some SomeProtocolB = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{35-40=}}{{19-19=some }} // An opaque result type on a protocol extension member effectively // contains an invariant reference to 'Self', and therefore cannot // be referenced on an existential type. protocol OpaqueProtocol {} extension OpaqueProtocol { var asSome: some OpaqueProtocol { return self } func getAsSome() -> some OpaqueProtocol { return self } subscript(_: Int) -> some OpaqueProtocol { return self } } func takesOpaqueProtocol(existential: OpaqueProtocol) { // These are okay because we erase to the opaque type bound let a = existential.asSome let _: Int = a // expected-error{{cannot convert value of type 'any OpaqueProtocol' to specified type 'Int'}} _ = existential.getAsSome() _ = existential[0] } func takesOpaqueProtocol<T : OpaqueProtocol>(generic: T) { // these are all OK: _ = generic.asSome _ = generic.getAsSome() _ = generic[0] } func opaquePlaceholderFunc() -> some _ { 1 } // expected-error {{type placeholder not allowed here}} var opaquePlaceholderVar: some _ = 1 // expected-error {{type placeholder not allowed here}} // rdar://90456579 - crash in `OpaqueUnderlyingTypeChecker` func test_diagnostic_with_contextual_generic_params() { struct S { func test<T: Q>(t: T) -> some Q { // expected-error@-1 {{function declares an opaque return type 'some Q', but the return statements in its body do not have matching underlying types}} if true { return t // expected-note {{return statement has underlying type 'T'}} } return "" // String conforms to `Q` // expected-note@-1 {{return statement has underlying type 'String'}} } } }
apache-2.0
1295c80bb95e0cf52565cd3d6b4db5b6
31.44486
220
0.642931
3.441316
false
false
false
false
DeFrenZ/BonBon
Tests/BonBonTests/ObservableTests.swift
1
3682
import XCTest import BonBon final class ObservableTests: XCTestCase { // MARK: Setup private var observableNumber: Observable<Int> = .init(0) private var expectedUpdate: (Int, Int)? private var expectedMappedUpdate: (String, String)? // MARK: Unit tests func test_whenObservableUpdates_thenItNotifiesObservers() { observableNumber.subscribe(self, onUpdate: { self.expectedUpdate = $0 }) observableNumber.value = 1 XCTAssert(expectedUpdate! == (0, 1), "The update block should've been triggered.") } func test_whenObservableUpdates_andValueIsChanged_thenItNotifiesChangeObservers() { observableNumber.subscribe(self, onChange: { self.expectedUpdate = $0 }) observableNumber.value = 1 XCTAssert(expectedUpdate! == (0, 1), "The update block should've been triggered.") } func test_whenObservableUpdates_andValueIsntChanged_thenItDoesntNotifyChangeObservers() { observableNumber.subscribe(self, onChange: { self.expectedUpdate = $0 }) observableNumber.value = 0 XCTAssertNil(expectedUpdate, "The update block shouldn't have been triggered.") } func test_whenObservableUpdates_andAnObserverIsUnsubscribed_thenItDoesntNotifyIt() { observableNumber.subscribe(self, onUpdate: { self.expectedUpdate = $0 }) observableNumber.unsubscribe(self) observableNumber.value = 1 XCTAssertNil(expectedUpdate, "The update block shouldn't have been triggered.") } func test_whenObservableUpdates_andAnObserverGotReleased_thenItDoesntNotifyIt() { do { let observer = SubscriptionOwner() observableNumber.subscribe(observer, onUpdate: { self.expectedUpdate = $0 }) } observableNumber.value = 1 XCTAssertNil(expectedUpdate, "The update block shouldn't have been triggered.") } func test_whenObservableUpdates_andItsMappedToAnother_thenTheOtherNotifiesObservers() { let observableString = observableNumber.map(String.init) observableString.subscribe(self, onUpdate: { self.expectedMappedUpdate = $0 }) observableNumber.value = 1 XCTAssert(expectedMappedUpdate! == ("0", "1"), "The update block shouldn't have been triggered.") } func test_whenObservableUpdates_andItsFlatMappedToAnother_thenTheOtherNotifiesObservers() { let observableString = observableNumber.flatMap({ Observable(String($0)) }) observableString.subscribe(self, onUpdate: { self.expectedMappedUpdate = $0 }) observableNumber.value = 1 XCTAssert(expectedMappedUpdate! == ("0", "1"), "The update block shouldn't have been triggered.") } // MARK: Linux support static var allTests: [(String, (ObservableTests) -> () throws -> Void)] { return [ ("test_whenObservableUpdates_thenItNotifiesObservers", test_whenObservableUpdates_thenItNotifiesObservers), ("test_whenObservableUpdates_andValueIsChanged_thenItNotifiesChangeObservers", test_whenObservableUpdates_andValueIsChanged_thenItNotifiesChangeObservers), ("test_whenObservableUpdates_andValueIsntChanged_thenItDoesntNotifyChangeObservers", test_whenObservableUpdates_andValueIsntChanged_thenItDoesntNotifyChangeObservers), ("test_whenObservableUpdates_andAnObserverIsUnsubscribed_thenItDoesntNotifyIt", test_whenObservableUpdates_andAnObserverIsUnsubscribed_thenItDoesntNotifyIt), ("test_whenObservableUpdates_andAnObserverGotReleased_thenItDoesntNotifyIt", test_whenObservableUpdates_andAnObserverGotReleased_thenItDoesntNotifyIt), ("test_whenObservableUpdates_andItsMappedToAnother_thenTheOtherNotifiesObservers", test_whenObservableUpdates_andItsMappedToAnother_thenTheOtherNotifiesObservers), ("test_whenObservableUpdates_andItsFlatMappedToAnother_thenTheOtherNotifiesObservers", test_whenObservableUpdates_andItsFlatMappedToAnother_thenTheOtherNotifiesObservers), ] } }
mit
eb9c386903dd6a14844eb58935f24b79
48.756757
174
0.80201
3.993492
false
true
false
false
nanthi1990/LocationPicker
Demo/LocationPickerDemo/ViewController.swift
1
1188
// // ViewController.swift // LocationPickerDemo // // Created by Almas Sapargali on 7/29/15. // Copyright (c) 2015 almassapargali. All rights reserved. // import UIKit import LocationPicker import CoreLocation import MapKit class ViewController: UIViewController { @IBOutlet weak var locationNameLabel: UILabel! var location: Location? { didSet { locationNameLabel.text = location.flatMap({ $0.title }) ?? "No location selected" } } override func viewDidLoad() { super.viewDidLoad() let coordinates = CLLocationCoordinate2D(latitude: 43.25, longitude: 76.95) location = Location(name: "Test", location: nil, placemark: MKPlacemark(coordinate: coordinates, addressDictionary: [:])) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "LocationPicker" { let locationPicker = segue.destinationViewController as! LocationPickerViewController locationPicker.location = location locationPicker.showCurrentLocationButton = true locationPicker.useCurrentLocationAsHint = true locationPicker.showCurrentLocationInitially = true locationPicker.completion = { self.location = $0 } } } }
mit
5c79058ab6c2d08e3efe80117eb6f435
27.97561
88
0.753367
4.212766
false
false
false
false
JoeLago/MHGDB-iOS
Pods/GRDB.swift/GRDB/QueryInterface/Column.swift
2
1238
/// A column in the database /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct Column : SQLExpression { /// The hidden rowID column public static let rowID = Column("rowid") /// The name of the column public let name: String private var qualifier: SQLTableQualifier? /// Creates a column given its name. public init(_ name: String) { self.name = name } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { if let qualifierName = qualifier?.name { return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: public func qualified(by qualifier: SQLTableQualifier) -> Column { if self.qualifier != nil { // Never requalify return self } var column = self column.qualifier = qualifier return column } }
mit
67a21060710bef4ec6fd7d6a07604154
29.95
95
0.617124
4.60223
false
false
false
false
yopicpic/RIABrowser
RIABrowser/viewcontroller/ObjectsTableViewController.swift
1
2980
// // ObjectsTableViewController.swift // RIABrowser // // Created by Yoshiyuki Tanaka on 2015/04/04. // Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved. // import UIKit class ObjectsTableViewController : UITableViewController { var className = "" var objects:[RIAObject] = [] var selectedObject:RIAObject! override func viewDidLoad() { navigationItem.title = className + "(\(objects.count))" // objects = RABModelAnalyzer.sharedInstance().objectsWithClassName(className) as! [RABObject] } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){ if segue.identifier == "toObjectDetailTableViewController" { var objectDetailTableViewController = segue.destinationViewController as! ObjectDetailTableViewController objectDetailTableViewController.object = selectedObject } } //MARK:Private Method private func propertyValueToString(property:RIAProperty) -> String { if let stringProperty = property as? RIAStringProperty { return "\(stringProperty.name) = \(stringProperty.value())" } else if let dataProperty = property as? RIADataProperty { return "\(dataProperty.name) = \(dataProperty.value().bytes) byte" } else if let objectProperty = property as? RIAObjectProperty { let object = objectProperty.value() return "\(objectProperty.name) = \(object.name) instance" } else if let arrayProperty = property as? RIAArrayProperty { return "\(arrayProperty.name) = array data" } return "" } //MARK:UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { selectedObject = objects[indexPath.row] return indexPath } //MARK:UITableViewDatasource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ObjectsTableViewCell")! let object = objects[indexPath.row] let properties:[RIAProperty] = object.properties var text:String? = nil for property:RIAProperty in properties { if text == nil { text = propertyValueToString(property) } if let primaryKey = object.primaryKey { if property.name == primaryKey { text = propertyValueToString(property) break } } } cell.textLabel?.text = "\(indexPath.row): " + text! return cell } //MARK: IBAction @IBAction func pressCloseButton(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
545b8af885055a3dc80321cf2a1931f8
31.747253
116
0.708389
4.85342
false
false
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Commands/Sketch+Combined.playground/Pages/BeyondNapoleon2.xcplaygroundpage/Contents.swift
1
1484
import Cocoa import PlaygroundSupport import EulerSketchOSX let sketch = Sketch() sketch.addPoint("A", hint: (145, 230)) sketch.addPoint("B", hint: (445, 230)) sketch.addPoint("C", hint: (393, 454)) sketch.addTriangle("ABC") sketch.addBisector("a", ofSegment: "BC", style: .extra) sketch.addBisector("b", ofSegment: "AC", style: .extra) sketch.addBisector("c", ofSegment: "AB", style: .extra) sketch.addPoint("A1", onLine: "a", hint: (462, 342)) sketch.addPoint("B1", onLine: "b", hint: (230, 400)) sketch.addPoint("C1", onLine: "c", hint: (300, 145)) sketch.addTriangle("A1B1C1") sketch.addMidPoint("A2", ofSegment: "BC") sketch.addMidPoint("B2", ofSegment: "AC") sketch.addMidPoint("C2", ofSegment: "AB") sketch.addPerpendicular("A2A3", toSegment: "B1C1", style: .emphasized) sketch.addPerpendicular("B2B3", toSegment: "A1C1", style: .emphasized) sketch.addPerpendicular("C2C3", toSegment: "A1B1", style: .emphasized) sketch.addIntersection("X", ofLine: "A2A3", andLine: "B2B3") sketch.point("A2", setNameLocation: .bottomLeft) sketch.point("A3", setNameLocation: .bottomLeft) sketch.point("C1", setNameLocation: .bottomRight) // result sketch.assert("Lines A2A3, B2B3, C2C3 are concurrent") { [unowned sketch] in let A2A3 = try sketch.getLine("A2A3") let B2B3 = try sketch.getLine("B2B3") let C2C3 = try sketch.getLine("C2C3") return concurrent(lines: [A2A3, B2B3, C2C3]) } sketch.eval() // live view PlaygroundPage.current.liveView = sketch.quickView()
mit
b44e260ae6c87c923f7f25ad2c952ea2
28.68
76
0.708895
2.732965
false
false
false
false
aberger/SwiftMite
SwiftMite/ViewControllers/MainVC.swift
1
1812
// // MainVC.swift // SwiftMite // // Created by Alex Berger on 6/11/14. // Copyright (c) 2014 aberger.me. All rights reserved. // import UIKit class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var miteSync: MiteSync? var projectsArray = AnyObject[]() var theTableView: UITableView? override func viewDidLoad() { super.viewDidLoad() self.theTableView = UITableView() if let tv = self.theTableView { tv.delegate = self tv.dataSource = self tv.frame = self.view.frame } self.view.addSubview(self.theTableView) self.miteSync = MiteClient.sharedManager.sharedMiteSync() downloadProjects() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.projectsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") let dict: Dictionary<String, Dictionary<String, String>> = self.projectsArray[indexPath.row] as Dictionary<String, Dictionary<String, String>> let projectDict: Dictionary<String, String> = dict["project"]! let projectName: String = projectDict["name"]! cell.textLabel.text = projectName return cell } func downloadProjects() { self.miteSync?.projects( projectID: nil, projectName: nil, customerID: nil, customerName: nil, limit: nil, archived: false, parameters: Dictionary<String, String>(), onSuccess: { (data : AnyObject) in self.projectsArray = data as AnyObject[] self.theTableView!.reloadData() }, onFailure: { (error: NSError) in println(error.localizedDescription) }) } }
mit
f132646b80fb150e324fdcfe22e5ffc4
25.647059
144
0.721854
3.814737
false
false
false
false
warnerbros/cpe-manifest-ios-experience
Source/Shared Views/MenuItemCell.swift
1
824
// // MenuItemCell.swift // import UIKit import QuartzCore class MenuItemCell: UITableViewCell { static let NibName = "MenuItemCell" static let ReuseIdentifier = "MenuItemCellReuseIdentifier" @IBOutlet weak var titleLabel: UILabel! @IBOutlet var titleLabelLargePaddingConstraint: NSLayoutConstraint! var menuItem: MenuItem? { didSet { titleLabel.text = menuItem?.title } } var active = false { didSet { updateCellStyle() } } override func prepareForReuse() { super.prepareForReuse() menuItem = nil active = false titleLabelLargePaddingConstraint.isActive = true } func updateCellStyle() { titleLabel.textColor = (self.active ? UIColor.themePrimary : UIColor.white) } }
apache-2.0
b8bce655d6305bf0520d53b237639595
19.6
83
0.639563
5.08642
false
false
false
false
Stosyk/stosyk-service
Sources/AppLogic/Controllers/Admin/AdminController.swift
1
1983
import Vapor import HTTP final class AdminController: ResourceRepresentable { func index(request: Request) throws -> ResponseRepresentable { return try containerFor(items: Admin.all()).converted(to: JSON.self) } func create(request: Request) throws -> ResponseRepresentable { guard let json = request.json else { throw Abort.badRequest } var item = try Admin(node: json) try item.save() let container = try containerFor(items: [item]) return try Response(status: .created, json: JSON(node: container)) } func show(request: Request, item: Admin) throws -> ResponseRepresentable { let container = try containerFor(items: [item]) return try JSON(node: container) } func delete(request: Request, item: Admin) throws -> ResponseRepresentable { try item.delete() return Response(status: .noContent, body: .data([])) } func update(request: Request, item: Admin) throws -> ResponseRepresentable { guard let data = request.json?.node else { throw Abort.badRequest } var item = item if let name = data[Admin.Keys.name]?.string, !name.isEmpty { item.name = name } if let email = data[Admin.Keys.email]?.string, !email.isEmpty { item.email = email } try item.save() let container = try containerFor(items: [item]) return try JSON(node: container) } private func containerFor(items: [Admin], meta: [String: Int]? = nil) throws -> Node { var result = [Admin.Keys.table: try items.makeNode()] if meta != nil { result["_meta"] = try meta?.makeNode() } return .object(result) } func makeResource() -> Resource<Admin> { return Resource( index: index, store: create, show: show, modify: update, destroy: delete ) } }
mit
7bbe05e6a506b750e00b46bc491200b5
32.05
90
0.593041
4.496599
false
false
false
false
caxco93/peliculas
DemoWS/DALC/HorarioDALC.swift
1
2221
// // HorarioDALC.swift // DemoWS // // Created by B303-01 on 20/10/16. // Copyright © 2016 Core Data Media. All rights reserved. // import UIKit import CoreData class HorarioDALC: NSObject { class func obtener(paraIdPelicula idPelicula : String, paraIdSucursal idSucursal : String, enArrayHorarios arrayHorarios : NSArray) -> Horario?{ if arrayHorarios.count == 0 { return nil } let predicado = NSPredicate(format: "pelicula.pelicula_id == %@ && sucursal.sucursal_id == %@", idPelicula, idSucursal) let arrayResultado = arrayHorarios.filtered(using: predicado) return arrayResultado.count != 0 ? arrayResultado[0] as? Horario : nil } @discardableResult class func agregar(horario objHorario : HorarioBE, conArrayPeliculas arrayPeliculas : NSArray, conArraySucursales arraySucursales : NSArray, enArrayHorario arrayHorario : NSArray, conContexto contexto : NSManagedObjectContext) -> Horario{ var objDM = self.obtener(paraIdPelicula: objHorario.horario_idPelicula!, paraIdSucursal: objHorario.horario_idSucursal!, enArrayHorarios: arrayHorario) if objDM == nil { objDM = NSEntityDescription.insertNewObject(forEntityName: "Horario", into: contexto) as? Horario } objDM?.horario_horario = objHorario.horario_horario! let objPelicula = PeliculaDALC.obtener(paraIdPelicula: objHorario.horario_idPelicula!, enArrayPeliculas: arrayPeliculas) let objSucursal = SucursalDALC.obtener(porIdSucursal: objHorario.horario_idSucursal!, enArraySucursales: arraySucursales) objPelicula?.addToHorarios(objDM!) objSucursal?.addToHorarios(objDM!) return objDM! } class func listarTodasLosHorarios(conContexto contexto : NSManagedObjectContext) -> NSArray { let fetchRequest : NSFetchRequest<Horario> = Horario.fetchRequest() do { return try contexto.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) as NSArray }catch{ return NSArray() } } }
mit
efeeaef93996e5bc164a770164a00ca3
33.6875
261
0.65991
3.706177
false
false
false
false
andrewlowson/Visiocast
Visucast/Reachability.swift
1
1225
// // Reachability.swift // Visiocast // // Created by Andrew Lowson on 11/08/2015. // Copyright (c) 2015 Andrew Lowson. All rights reserved. // // Code taken from stackoverflow result: // http://stackoverflow.com/questions/25398664/check-for-internet-connection-availability-in-swift import Foundation import SystemConfiguration // Class to check if device is attached to a network. public class Reachability { class func isConnectedToNetwork() throws -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return false } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.ConnectionRequired) return (isReachable && !needsConnection)// } }
gpl-2.0
a8f2897f606fae5c71b58222c1cf0905
28.902439
99
0.662857
4.979675
false
false
false
false
GiantForJ/GYGestureUnlock
GYGestureUnlock/Classes/GYCircleConst.swift
1
4373
// // GYCircleConst.swift // GYGestureUnlock // // Created by zhuguangyang on 16/8/19. // Copyright © 2016年 Giant. All rights reserved. // import UIKit /// 单个圆的背景色 public var CircleBackgroundColor = UIColor.clear /// 解锁背景色 public var CircleViewBackgroundColor = UIColor.colorWithRgba(13, g: 52, b: 89, a: 1) /// 普通状态下外空心颜色 public var CircleStateNormalOutsideColor = UIColor.colorWithRgba(241, g: 241, b: 241, a: 1) /// 选中状态下外空心圆颜色 public var CircleStateSelectedOutsideColor = UIColor.colorWithRgba(34, g: 178, b: 246, a: 1) /// 错误状态下外空心圆颜色 public var CircleStateErrorOutsideColor = UIColor.colorWithRgba(254, g: 82, b: 92, a: 1) /// 普通状态下内实心圆颜色 public var CircleStateNormalInsideColor = UIColor.clear /// 选中状态下内实心圆颜色 public var CircleStateSelectedInsideColor = UIColor.colorWithRgba(34, g: 178, b: 246, a: 1) /// 错误状态内实心圆颜色 public var CircleStateErrorInsideColor = UIColor.colorWithRgba(254, g: 82, b: 92, a: 1) /// 普通状态下三角形颜色 public var CircleStateNormalTrangleColor = UIColor.clear /// 选中状态下三角形颜色 public var CircleStateSelectedTrangleColor = UIColor.colorWithRgba(34, g: 178, b: 246, a: 1) /// 错误状态三角形颜色 public var CircleStateErrorTrangleColor = UIColor.colorWithRgba(254, g: 82, b: 92, a: 1) /// 三角形边长 public var kTrangleLength:CGFloat = 10.0 /// 普通时连线颜色 public var CircleConnectLineNormalColor = UIColor.colorWithRgba(34, g: 178, b: 246, a: 1) /// 错误时连线颜色 public var CircleConnectLineErrorColor = UIColor.colorWithRgba(254, g: 82, b: 92, a: 1) /// 连线宽度 public var CircleConnectLineWidth:CGFloat = 1.0 /// 单个圆的半径 public var CircleRadius:CGFloat = 30.0 /// 单个圆的圆心 public var CircleCenter = CGPoint(x: CircleRadius, y: CircleRadius) /// 空心圆圆环宽度 public var CircleEdgeWidth:CGFloat = 1.0 /// 九宫格展示infoView 单个圆的半径 public var CircleInfoRadius:CGFloat = 5.0 /// 内部实心圆占空心圆的比例系数 public var CircleRadio:CGFloat = 0.4 /// 整个解锁View居中时,距离屏幕左边和右边的距离 public var CircleViewEdgeMargin:CGFloat = 30.0 /// 整个解锁View的Center.y值 在当前屏幕的3/5位置 public var CircleViewCenterY = UIScreen.main.bounds.size.height * 3/5 /// 连接的圆最少的个数 public var CircleSetCountLeast = 4 /// 错误状态下回显的时间 public var kdisplayTime:CGFloat = 1.0 /// 最终的手势密码存储key public var gestureFinalSaveKey = "gestureFinalSaveKey" /// 第一个手势密码存储key public var gestureOneSaveKey = "gestureOneSaveKey" /// 普通状态下文字提示的颜色 public var textColorNormalState = UIColor.colorWithRgba(241, g: 241, b: 241, a: 1) /// 警告状态下文字提示的颜色 public var textColorWarningState = UIColor.colorWithRgba(254, g: 82, b: 92, a: 1) /// 绘制解锁界面准备好时,提示文字 public var gestureTextBeforeSet = "绘制解锁图案" /// 设置时,连线个数少,提示文字 public var gestureTextConnectLess = NSString(format: "最少连接%@点,请重新输入",CircleSetCountLeast) /// 确认图案,提示再次绘制 public var gestureTextDrawAgain = "再次绘制解锁图案" /// 再次绘制不一致,提示文字 public var gestureTextDrawAgainError = "与上次绘制不一致,请重新绘制" /// 设置成功 public var gestureTextSetSuccess = "设置成功" /// 请输入原手势密码 public var gestureTextOldGesture = "请输入原手势密码" /// 密码错误 public var gestureTextGestureVerifyError = "密码错误" public class GYCircleConst: NSObject { /** 偏好设置:存字符串(手势密码) - parameter gesture: 字符串对象 - parameter key: 存储key */ public static func saveGesture(_ gesture: String?,key: String) { UserDefaults.standard.set(gesture, forKey: key) UserDefaults.standard.synchronize() } /** 取字符串手势密码 - parameter key: 字符串对象 */ public static func getGestureWithKey(_ key: String) -> String?{ return UserDefaults.standard.object(forKey: key) as? String ?? nil } }
mit
2fe9fe04aee8312032dbccea2ae5c020
23
92
0.723356
3.094737
false
false
false
false
qvik/qvik-swift-ios
QvikSwift/QvikSwift.playground/Contents.swift
1
791
//: Playground - noun: a place where people can play import UIKit extension Data { public func floatValue(bigEndian: Bool = true) -> Float? { if self.count != 4 { // Incorrect amount of bytes to represent a 32bit Float type return nil } if bigEndian { return Float(bitPattern: UInt32(bigEndian: self.withUnsafeBytes { $0.pointee })) } else { return Float(bitPattern: UInt32(littleEndian: self.withUnsafeBytes { $0.pointee })) } } convenience init(floatValue: Float) { let bits = value.bitPattern.bigEndian self.init(bytes: &bits, count: 4) //let data = Data(bytes: &bits, count: 4) } } let float1 = 123.456 let data1 = Data(floatValue: float1) print(data1)
mit
1746d4e13e385415dce33ff9450a6cc0
26.275862
95
0.606827
4.05641
false
false
false
false
ohwutup/ReactiveCocoa
ReactiveCocoaTests/UIKit/UIScrollViewSpec.swift
1
3485
import ReactiveSwift import ReactiveCocoa import UIKit import Quick import Nimble import enum Result.NoError private final class UIScrollViewDelegateForZooming: NSObject, UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return scrollView.subviews.first! } } class UIScrollViewSpec: QuickSpec { override func spec() { var scrollView: UIScrollView! weak var _scrollView: UIScrollView? beforeEach { scrollView = UIScrollView(frame: .zero) _scrollView = scrollView } afterEach { scrollView = nil expect(_scrollView).to(beNil()) } it("should accept changes from bindings to its content inset value") { scrollView.contentInset = .zero let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe() scrollView.reactive.contentInset <~ SignalProducer(pipeSignal) observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)) expect(scrollView.contentInset) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) observer.send(value: .zero) expect(scrollView.contentInset) == UIEdgeInsets.zero } it("should accept changes from bindings to its scroll indicator insets value") { scrollView.scrollIndicatorInsets = .zero let (pipeSignal, observer) = Signal<UIEdgeInsets, NoError>.pipe() scrollView.reactive.scrollIndicatorInsets <~ SignalProducer(pipeSignal) observer.send(value: UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)) expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4) observer.send(value: .zero) expect(scrollView.scrollIndicatorInsets) == UIEdgeInsets.zero } it("should accept changes from bindings to its scroll enabled state") { scrollView.isScrollEnabled = true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() scrollView.reactive.isScrollEnabled <~ SignalProducer(pipeSignal) observer.send(value: true) expect(scrollView.isScrollEnabled) == true observer.send(value: false) expect(scrollView.isScrollEnabled) == false } it("should accept changes from bindings to its zoom scale value") { let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) scrollView.addSubview(contentView) let delegate = UIScrollViewDelegateForZooming() scrollView.delegate = delegate scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = 5 scrollView.zoomScale = 1 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.zoomScale <~ SignalProducer(pipeSignal) observer.send(value: 3) expect(scrollView.zoomScale) == 3 observer.send(value: 1) expect(scrollView.zoomScale) == 1 } it("should accept changes from bindings to its minimum zoom scale value") { scrollView.minimumZoomScale = 0 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.minimumZoomScale <~ SignalProducer(pipeSignal) observer.send(value: 42) expect(scrollView.minimumZoomScale) == 42 observer.send(value: 0) expect(scrollView.minimumZoomScale) == 0 } it("should accept changes from bindings to its maximum zoom scale value") { scrollView.maximumZoomScale = 0 let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe() scrollView.reactive.maximumZoomScale <~ SignalProducer(pipeSignal) observer.send(value: 42) expect(scrollView.maximumZoomScale) == 42 observer.send(value: 0) expect(scrollView.maximumZoomScale) == 0 } } }
mit
6745e594d20e388a3aa9c5058f475ca9
30.396396
97
0.736872
4.071262
false
false
false
false
LeoNatan/LNPopupController
LNPopupControllerExample/LNPopupControllerExample/MusicCell.swift
1
1792
// // MusicCell.swift // LNPopupControllerExample // // Created by Leo Natan on 8/7/15. // Copyright © 2015 Leo Natan. All rights reserved. // import UIKit class MusicCell: UITableViewCell { let selectionEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial)) required init?(coder: NSCoder) { super.init(coder: coder) selectionEffectView.frame = bounds selectionEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] selectionEffectView.isHidden = true addSubview(selectionEffectView) sendSubviewToBack(selectionEffectView) selectionStyle = .none } override func layoutSubviews() { super.layoutSubviews() imageView?.frame = CGRect(x: self.layoutMargins.left, y: bounds.height / 2 - 24, width: 48, height: 48) imageView?.layer.cornerRadius = 3 textLabel?.frame = CGRect(x: imageView!.frame.maxX + 20, y: textLabel!.frame.minY, width: accessoryView!.frame.minX - imageView!.frame.maxX - 40, height: textLabel!.frame.height) detailTextLabel?.frame = CGRect(x: imageView!.frame.maxX + 20, y: detailTextLabel!.frame.minY, width: accessoryView!.frame.minX - imageView!.frame.maxX - 40, height: detailTextLabel!.frame.height) separatorInset = UIEdgeInsets(top: 0, left: textLabel!.frame.origin.x, bottom: 0, right: 0) } override func setHighlighted(_ highlighted: Bool, animated: Bool) { guard isHighlighted != highlighted else { return } super.setHighlighted(highlighted, animated: animated) selectionEffectView.alpha = highlighted ? 0.0 : 1.0 selectionEffectView.isHidden = false UIView.animate(withDuration: highlighted ? 0.0 : 0.35) { self.selectionEffectView.alpha = highlighted ? 1.0 : 0.0 } completion: { _ in self.selectionEffectView.isHidden = highlighted == false } } }
mit
c23ca6bcfab0798f3d31f26a938c30c1
32.792453
198
0.733668
3.843348
false
false
false
false
pinterest/tulsi
src/TulsiGeneratorTests/MockWorkspaceInfoExtractor.swift
1
3260
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @testable import TulsiGenerator class MockBazelSettingsProvider: BazelSettingsProviderProtocol { var universalFlags: BazelFlags { return BazelFlags() } func tulsiFlags( hasSwift: Bool, options: TulsiOptionSet?, features: Set<BazelSettingFeature> ) -> BazelFlagsSet { return BazelFlagsSet() } func buildSettings( bazel: String, bazelExecRoot: String, options: TulsiOptionSet, features: Set<BazelSettingFeature>, buildRuleEntries: Set<RuleEntry> ) -> BazelBuildSettings { return BazelBuildSettings( bazel: bazel, bazelExecRoot: bazelExecRoot, defaultPlatformConfigIdentifier: "", platformConfigurationFlags: nil, swiftTargets: [], tulsiCacheAffectingFlagsSet: BazelFlagsSet(), tulsiCacheSafeFlagSet: BazelFlagsSet(), tulsiSwiftFlagSet: BazelFlagsSet(), tulsiNonSwiftFlagSet: BazelFlagsSet(), swiftFeatures: [], nonSwiftFeatures: [], projDefaultFlagSet: BazelFlagsSet(), projTargetFlagSets: [:]) } } class MockWorkspaceInfoExtractor: BazelWorkspaceInfoExtractorProtocol { let bazelSettingsProvider: BazelSettingsProviderProtocol = MockBazelSettingsProvider() var labelToRuleEntry = [BuildLabel: RuleEntry]() /// The set of labels passed to ruleEntriesForLabels that could not be found in the /// labelToRuleEntry dictionary. var invalidLabels = Set<BuildLabel>() var bazelURL = URL(fileURLWithPath: "") var bazelBinPath = "bazel-bin" var bazelExecutionRoot = "/private/var/tmp/_bazel_localhost/1234567890abcdef1234567890abcdef/execroot/workspace_dir" var workspaceRootURL = URL(fileURLWithPath: "") func extractRuleInfoFromProject(_ project: TulsiProject) -> [RuleInfo] { return [] } func ruleEntriesForLabels( _ labels: [BuildLabel], startupOptions: TulsiOption, extraStartupOptions: TulsiOption, buildOptions: TulsiOption, compilationModeOption: TulsiOption, platformConfigOption: TulsiOption, prioritizeSwiftOption: TulsiOption, features: Set<BazelSettingFeature> ) throws -> RuleEntryMap { invalidLabels.removeAll(keepingCapacity: true) let ret = RuleEntryMap() for label in labels { guard let entry = labelToRuleEntry[label] else { invalidLabels.insert(label) continue } ret.insert(ruleEntry: entry) } return ret } func extractBuildfiles<T: Collection>(_ forTargets: T) -> Set<BuildLabel> where T.Iterator.Element == BuildLabel { return Set() } func logQueuedInfoMessages() {} func hasQueuedInfoMessages() -> Bool { return false } }
apache-2.0
84377a71c882af6821b1447e72660cb3
29.46729
97
0.724233
4.546722
false
false
false
false
kalanyuz/SwiftR
SwiftRDemo_macOS/Sources/RoundProgressView.swift
1
8533
// // RoundProgressView.swift // SMKTunes // // Created by Kalanyu Zintus-art on 11/1/15. // Copyright © 2015 KoikeLab. All rights reserved. // import Cocoa import SwiftR protocol RoundProgressProtocol { func roundProgressClicked(_ sender: NSView) } @IBDesignable class RoundProgressView: NSView { fileprivate let innerRing = CAShapeLayer() fileprivate let outerRing = CAShapeLayer() fileprivate var state = NSOffState fileprivate let lineWidth : CGFloat = 10 open let titleLabel = NSTextLabel() var showMarker = false var roundDelegate : RoundProgressProtocol? var loadSeconds = 1.0 var title : String { get { return titleLabel.stringValue } set { titleLabel.stringValue = newValue } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { super.init(coder: coder) self.wantsLayer = true self.layer?.addSublayer(innerRing) self.layer?.addSublayer(outerRing) innerRing.shouldRasterize = true innerRing.rasterizationScale = 2 innerRing.strokeColor = PrismColor()[1].cgColor innerRing.fillColor = NSColor.clear.cgColor innerRing.lineWidth = lineWidth * 0.8 innerRing.lineCap = kCALineCapRound innerRing.lineDashPattern = nil innerRing.lineDashPhase = 0.0 //testLayer.strokeEnd = 0 outerRing.shouldRasterize = true outerRing.rasterizationScale = 2 outerRing.strokeColor = NSColor.white.cgColor outerRing.fillColor = NSColor.clear.cgColor outerRing.lineWidth = lineWidth outerRing.lineCap = kCALineCapRound outerRing.lineDashPattern = nil outerRing.lineDashPhase = 0.0 titleLabel.textColor = NSColor.white self.addSubview(titleLabel) self.titleLabel.font = NSFont.boldSystemFont(ofSize: 20) self.titleLabel.translatesAutoresizingMaskIntoConstraints = false var countFieldConstraint = NSLayoutConstraint(item: self.titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0) self.addConstraint(countFieldConstraint) countFieldConstraint = NSLayoutConstraint(item: self.titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0) self.addConstraint(countFieldConstraint) titleLabel.stringValue = "Title" } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if let currentContext = NSGraphicsContext.current() { //CGPathMoveToPoint(path, nil, 0, 0) //CGPathAddArc(path, nil, 0, 0, 300, 0, CGFloat(M_PI), false) let path = CGMutablePath() // Swift.print(self.bounds.width) var circleSize : CGFloat = min(self.bounds.width/2, self.bounds.height/2) let margin = lineWidth + 10 // CGPathAddArc(path, nil, self.bounds.midX, self.bounds.midY, circleSize - (lineWidth + innerRing.lineWidth) , CGFloat(-M_PI/2), CGFloat(19 * M_PI / 12.6), true) let midPoint = CGPoint(x: self.bounds.midX, y: self.bounds.midY) path.addArc(center: midPoint, radius: circleSize - (lineWidth + innerRing.lineWidth), startAngle: CGFloat(-M_PI/2), endAngle: CGFloat(19 * M_PI / 12.6), clockwise: true) //CGPathAddArc(path, nil, 100, 100, 100, 0, (360 * CGFloat(M_PI))/180, true); circleSize = min(self.bounds.width, self.bounds.height) - margin let path2 = CGMutablePath() // CGPathAddEllipseInRect(path2, nil, CGRect(x: self.bounds.midX - (circleSize/2), y: self.bounds.midY - (circleSize/2), width: circleSize, height: circleSize)) path2.addEllipse(in: CGRect(x: self.bounds.midX - (circleSize/2), y: self.bounds.midY - (circleSize/2), width: circleSize, height: circleSize)) outerRing.path = path2 innerRing.path = path innerRing.strokeEnd = 0 if showMarker { currentContext.cgContext.saveGState() //3 - move top left of context to the previous center position currentContext.cgContext.translateBy(x: bounds.width/2, y: bounds.height/2) let markerHeight = self.lineWidth / 4 let markerWidth = self.lineWidth * 2.5 for i in 0...1 { let markerPath = CGPath(rect: CGRect(x: -markerHeight / 2, y: 0, width: markerHeight, height: markerWidth), transform: nil) //4 - save the centred context currentContext.cgContext.saveGState() //5 - calculate the rotation angle //rotate and translate currentContext.cgContext.rotate(by: deg2rad(180.0 * CGFloat(i)) + CGFloat(M_PI/2)) currentContext.cgContext.translateBy(x: 0, y: circleSize/2 - markerWidth) currentContext.cgContext.addPath(markerPath) let color = PrismColor() color[3].set() //6 - fill the marker rectangle currentContext.cgContext.fillPath() currentContext.cgContext.restoreGState() } currentContext.cgContext.restoreGState() } // Drawing code here. } } override func layout() { super.layout() titleLabel.font = NSFont.boldSystemFont(ofSize: resizeFontWithString(titleLabel.stringValue)) titleLabel.sizeToFit() titleLabel.frame.origin = CGPoint(x: self.bounds.midX - titleLabel.bounds.width/2, y: self.bounds.midY - titleLabel.bounds.height/2) } fileprivate func loadProgressForSeconds(_ seconds: Double) { CATransaction.begin() // CATransaction.setCompletionBlock { // self.state = NSOnState // } let animate = CABasicAnimation(keyPath: "strokeEnd") animate.toValue = 1 animate.duration = seconds animate.repeatCount = 1 animate.fillMode = kCAFillModeForwards animate.isRemovedOnCompletion = false innerRing.add(animate, forKey: "strokeEnd") CATransaction.commit() } fileprivate func removeProgress() { CATransaction.begin() CATransaction.setCompletionBlock({ let animate = CABasicAnimation(keyPath: "strokeEnd") animate.toValue = 0 animate.duration = 0 animate.repeatCount = 1 animate.fillMode = kCAFillModeForwards animate.isRemovedOnCompletion = false self.innerRing.add(animate, forKey: "strokeEnd") CATransaction.commit() }) let animate = CABasicAnimation(keyPath: "opacity") animate.toValue = 0 animate.duration = 0.5 animate.repeatCount = 1 animate.fillMode = kCAFillModeForwards animate.isRemovedOnCompletion = true innerRing.add(animate, forKey: "opacity") CATransaction.commit() } fileprivate func resizeFontWithString(_ title: String) -> CGFloat { // defer { // Swift.print(textSize, self.bounds, displaySize) // } let smallestSize : CGFloat = 10 let largestSize : CGFloat = 40 var textSize = CGSize.zero var displaySize = smallestSize while displaySize < largestSize { let nsTitle = NSString(string: title) let attributes = [NSFontAttributeName: NSFont.boldSystemFont(ofSize: displaySize)] textSize = nsTitle.size(withAttributes: attributes) if textSize.width < self.bounds.width - (lineWidth * 2) * 4 { // Swift.print(displaySize, "increasing") displaySize += 1 } else { Swift.print(displaySize) return displaySize } } return largestSize } override func mouseDown(with theEvent: NSEvent) { state = (state == NSOnState ? NSOffState : NSOnState) if let delegate = roundDelegate { if state == NSOnState { delegate.roundProgressClicked(self) loadProgressForSeconds(self.loadSeconds) } else { removeProgress() } } } fileprivate func deg2rad(_ degree: CGFloat) -> CGFloat { return degree * CGFloat(M_PI) / CGFloat(180.0) } }
apache-2.0
952f052bbcb385c00b12d46ea09cc896
35.618026
179
0.618847
4.732113
false
false
false
false
devpunk/velvet_room
Source/Model/Connect/PTPDelegateWrite.swift
1
4253
import Foundation import CocoaAsyncSocket class PTPDelegateWrite:NSObject, GCDAsyncSocketDelegate { var step:Int = 0 var dataToWrite:Data? var totalWritten:Int = 0 let maxBlockSize:Int = 32756 weak var connected:MConnectConnected? func socket(_ sock:GCDAsyncSocket, didWriteDataWithTag tag:Int) { if step == 0 { step = 1 sendStart(sock:sock) } else if step == 1 { guard let dataToWrite:Data = self.dataToWrite else { return } let size:Int = dataToWrite.count let remain:Int = size - totalWritten let type:UInt32 let toWrite:Int print("remain: \(remain)") if remain > maxBlockSize { print("send data") type = 10 //PTPIP_DATA_PACKET toWrite = maxBlockSize } else { print("end data") type = 12 //PTPIP_END_DATA_PACKET toWrite = remain step = 2 } let endIndex:Int = toWrite + totalWritten let writingData:Data = dataToWrite.subdata(in:totalWritten..<endIndex) let length:UInt32 = UInt32(toWrite + 12) var pars:[UInt32] = [length, type, connected!.transactionId] var data:Data = Data() data.append(UnsafeBufferPointer(start:&pars, count:pars.count)) data.append(writingData) totalWritten += toWrite sock.write(data, withTimeout:100, tag:0) } else if step == 2 { step = 3 connected?.capabilitiesSent() } else if step == 3 { step = 4 sendStart(sock:sock) } else if step == 4 { guard let dataToWrite:Data = self.dataToWrite else { return } let size:Int = dataToWrite.count let remain:Int = size - totalWritten let type:UInt32 let toWrite:Int print("remain: \(remain)") if remain > maxBlockSize { print("send data") type = 10 //PTPIP_DATA_PACKET toWrite = maxBlockSize } else { print("end data") type = 12 //PTPIP_END_DATA_PACKET toWrite = remain step = 5 } let endIndex:Int = toWrite + totalWritten let writingData:Data = dataToWrite.subdata(in:totalWritten..<endIndex) let length:UInt32 = UInt32(toWrite + 12) var pars:[UInt32] = [length, type, connected!.transactionId] var data:Data = Data() data.append(UnsafeBufferPointer(start:&pars, count:pars.count)) data.append(writingData) totalWritten += toWrite sock.write(data, withTimeout:100, tag:0) } else if step == 5 { step = 6 connected?.otherCapsSent() } } func sendStart(sock:GCDAsyncSocket) { guard let dataToWrite:Data = self.dataToWrite else { return } totalWritten = 0 let length:UInt32 = 20 let sendType:UInt32 = 9 //PTPIP_START_DATA_PACKET let dataSize:UInt32 = UInt32(dataToWrite.count) // plus one for null ending let start:UInt32 = 0 var pars:[UInt32] = [length, sendType, connected!.transactionId, dataSize, start] var data = Data() data.append(UnsafeBufferPointer(start:&pars, count:pars.count)) print("write send start") sock.write(data, withTimeout:100, tag:0) } }
mit
c644d0ea78c95c8d7873977424379bdd
26.980263
89
0.462027
5.093413
false
false
false
false
crossroadlabs/Swirl
Sources/Swirl/Dialect.swift
1
1429
//===--- Dialect.swift ------------------------------------------------------===// //Copyright (c) 2017 Crossroad Labs s.r.o. // //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. //===----------------------------------------------------------------------===// public protocol Dialect { var proto: String {get} //affected rows count key var affected: String {get} func render<DS: Dataset, Ret : Rep>(select ret: Ret, from dataset:DS, filter:Predicate, limit:Limit?) -> SQL //inserts func render<DS: Table, Ret: Rep>(insert row: [ErasedRep], into table:DS, ret: Ret) -> SQL func render<DS: Table, Ret: Rep>(insert rows: [[ErasedRep]], into table:DS, ret: Ret) -> SQL //update func render<DS: Table, Ret: Rep>(update values: [ErasedRep], into table:DS, ret: Ret, matching: Predicate) -> SQL //delete func render<DS: Table>(delete table:DS, matching: Predicate) -> SQL }
apache-2.0
33e754eae7af3fca28db76b8e6bd6054
41.029412
117
0.620714
4.202941
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/DigitalWallet.swift
1
1625
// // DigitalWallet.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Digital wallet, such as Apple Pay, which can be used for accelerated /// checkouts. public enum DigitalWallet: String { /// Android Pay. case androidPay = "ANDROID_PAY" /// Apple Pay. case applePay = "APPLE_PAY" /// Google Pay. case googlePay = "GOOGLE_PAY" /// Shopify Pay. case shopifyPay = "SHOPIFY_PAY" case unknownValue = "" } }
mit
c6276c68c208f87f8ac1c1f12a28e67b
33.574468
81
0.723077
3.963415
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/PriceRangeFilter.swift
1
3003
// // PriceRangeFilter.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// A filter used to view a subset of products in a collection matching a /// specific price range. open class PriceRangeFilter { /// The minimum price in the range. Defaults to zero. open var min: Input<Double> /// The maximum price in the range. Empty indicates no max price. open var max: Input<Double> /// Creates the input object. /// /// - parameters: /// - min: The minimum price in the range. Defaults to zero. /// - max: The maximum price in the range. Empty indicates no max price. /// public static func create(min: Input<Double> = .undefined, max: Input<Double> = .undefined) -> PriceRangeFilter { return PriceRangeFilter(min: min, max: max) } private init(min: Input<Double> = .undefined, max: Input<Double> = .undefined) { self.min = min self.max = max } /// Creates the input object. /// /// - parameters: /// - min: The minimum price in the range. Defaults to zero. /// - max: The maximum price in the range. Empty indicates no max price. /// @available(*, deprecated, message: "Use the static create() method instead.") public convenience init(min: Double? = nil, max: Double? = nil) { self.init(min: min.orUndefined, max: max.orUndefined) } internal func serialize() -> String { var fields: [String] = [] switch min { case .value(let min): guard let min = min else { fields.append("min:null") break } fields.append("min:\(min)") case .undefined: break } switch max { case .value(let max): guard let max = max else { fields.append("max:null") break } fields.append("max:\(max)") case .undefined: break } return "{\(fields.joined(separator: ","))}" } } }
mit
b0fc786ceb5b1f2b99eb33af1c185b6e
32
115
0.67699
3.730435
false
false
false
false
shial4/SLChat
Tests/SLChatTests/SLClientTests.swift
1
2498
// // testSLClient.swift // SLChat // // Created by Shial on 19/08/2017. // // import XCTest @testable import SLChat class SLClientTests: XCTestCase { static let allTests = [ ("testSLClient", testSLClient), ("testSLClientSendMessage", testSLClientSendMessage), ("testSLClientStatusMessageDefault", testSLClientStatusMessageDefault), ("testSLClientStatusMessage", testSLClientStatusMessage), ("testSLClientProtocol", testSLClientProtocol), ("testSLClientStatus", testSLClientStatus), ("testSLClientMessage", testSLClientMessage) ] override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testSLClient() { struct Client: SLClient {} let cl = Client() XCTAssertNotNil(cl) } func testSLClientSendMessage() { struct Client: SLClient { static var handler: Bool = false static func sendMessage(_ message: SLMessage, from client: String) { handler = true } } Client.sendMessage(SLMessage(command: .connected), from: "") XCTAssert(Client.handler) } func testSLClientStatusMessageDefault() { struct Client: SLClient {} XCTAssertNil(Client.statusMessage(.disconnected, from: "")) } func testSLClientStatusMessage() { struct Client: SLClient { static func statusMessage(_ command: SLMessageCommand, from client: String) -> [String]? { return [] } } XCTAssertNotNil(Client.statusMessage(.disconnected, from: "")) } func testSLClientProtocol() { struct Client: SLClient { static func sendMessage(_ message: SLMessage, from client: String) { } static func statusMessage(_ command: SLMessageCommand, from client: String) -> [String]? { return nil } } let cl = Client() XCTAssertNotNil(cl) } func testSLClientStatus() { struct Client: SLClient { static func statusMessage(_ command: SLMessageCommand, from client: String) -> [String]? { return nil } } let cl = Client() XCTAssertNotNil(cl) } func testSLClientMessage() { struct Client: SLClient { static func sendMessage(_ message: SLMessage, from client: String) { } } let cl = Client() XCTAssertNotNil(cl) } }
mit
6f87e0f0e9a3a462358630494c13d987
28.388235
115
0.60008
4.776291
false
true
false
false
Nickelfox/PaginationUIManager
Source/Classes/PaginationUIManager.swift
1
8655
// // PaginationUIManager-Example.swift // PaginationUIManager-Example // // Created by Ravindra Soni on 07/09/17. // Copyright © 2017 Nickelfox. All rights reserved. // import Foundation import SSPullToRefresh public protocol PaginationUIManagerDelegate { func refreshAll(completion: @escaping (_ hasMoreData: Bool) -> Void) func loadMore(completion: @escaping (_ hasMoreData: Bool) -> Void) } public enum PullToRefreshType { case none case basic case custom(PullToRefreshContentView) } public class PaginationUIManager: NSObject { fileprivate weak var scrollView: UIScrollView? fileprivate var refreshControl: UIRefreshControl? fileprivate var bottomLoader: UIView? fileprivate var isObservingKeyPath: Bool = false fileprivate var pullToRefreshView: PullToRefreshView? public var delegate: PaginationUIManagerDelegate? fileprivate var pullToRefreshContentView: UIView? = nil fileprivate var pullToRefreshType: PullToRefreshType { didSet { self.setupPullToRefresh() } } var isLoading = false var hasMoreDataToLoad = false public init(scrollView: UIScrollView, pullToRefreshType: PullToRefreshType = .basic) { self.scrollView = scrollView self.pullToRefreshType = pullToRefreshType super.init() self.setupPullToRefresh() } deinit { self.removeScrollViewOffsetObserver() } public func load(completion: @escaping () -> Void) { self.refresh { completion() } } public func endLoading() { self.isLoading = false self.endRefreshing() self.removeBottomLoader() } } extension PaginationUIManager { fileprivate func setupPullToRefresh() { switch self.pullToRefreshType { case .none: self.removeRefreshControl() self.removeCustomPullToRefreshView() case .basic: self.removeCustomPullToRefreshView() self.addRefreshControl() case .custom(let view): self.removeRefreshControl() self.addCustomPullToRefreshView(view) } } fileprivate func addRefreshControl() { self.refreshControl = UIRefreshControl() self.scrollView?.addSubview(self.refreshControl!) self.refreshControl?.addTarget( self, action: #selector(PaginationUIManager.handleRefresh), for: .valueChanged) } fileprivate func addCustomPullToRefreshView(_ contentView: PullToRefreshContentView) { guard let scrollView = self.scrollView else { return } self.pullToRefreshView = PullToRefreshView(scrollView: scrollView, delegate: self) self.pullToRefreshView?.contentView = contentView } fileprivate func removeRefreshControl() { self.refreshControl?.removeTarget( self, action: #selector(PaginationUIManager.handleRefresh), for: .valueChanged) self.refreshControl?.removeFromSuperview() self.refreshControl = nil } fileprivate func removeCustomPullToRefreshView() { self.pullToRefreshView = nil } @objc fileprivate func handleRefresh() { self.refresh { } } fileprivate func refresh(completion: @escaping () -> Void) { if self.isLoading { self.endRefreshing() return } self.isLoading = true self.delegate?.refreshAll(completion: { [weak self] hasMoreData in guard let this = self else { return } this.isLoading = false this.hasMoreDataToLoad = hasMoreData this.endRefreshing() if hasMoreData { this.addScrollViewOffsetObserver() this.addBottomLoader() } completion() }) } fileprivate func endRefreshing() { self.refreshControl?.endRefreshing() self.pullToRefreshView?.finishLoading() } } extension PaginationUIManager { fileprivate func addBottomLoader() { guard let scrollView = self.scrollView else { return } let view = UIView() view.frame.size = CGSize(width: scrollView.frame.width, height: 60) view.frame.origin = CGPoint(x: 0, y: scrollView.contentSize.height) view.backgroundColor = UIColor.clear let activity = UIActivityIndicatorView(style: .gray) activity.frame = view.bounds activity.startAnimating() view.addSubview(activity) self.bottomLoader = view scrollView.contentInset.bottom = view.frame.height } fileprivate func showBottomLoader() { guard let scrollView = self.scrollView, let loader = self.bottomLoader else { return } scrollView.addSubview(loader) } fileprivate func hideBottomLoader() { self.bottomLoader?.removeFromSuperview() } fileprivate func removeBottomLoader() { self.bottomLoader?.removeFromSuperview() self.scrollView?.contentInset.bottom = 0 } func addScrollViewOffsetObserver() { if self.isObservingKeyPath { return } self.scrollView?.addObserver( self, forKeyPath: "contentOffset", options: [.new], context: nil) self.isObservingKeyPath = true } func removeScrollViewOffsetObserver() { if self.isObservingKeyPath { self.scrollView?.removeObserver(self, forKeyPath: "contentOffset") } self.isObservingKeyPath = false } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let object = object as? UIScrollView, let keyPath = keyPath, let newValue = change?[.newKey] as? CGPoint, object == self.scrollView, keyPath == "contentOffset" else { return } self.setContentOffSet(newValue) } fileprivate func setContentOffSet(_ offset: CGPoint) { guard let scrollView = self.scrollView else { return } self.bottomLoader?.frame.origin.y = scrollView.contentSize.height if !scrollView.isDragging && !scrollView.isDecelerating { return } if self.isLoading || !self.hasMoreDataToLoad { return } let offsetY = offset.y let contentHeight = scrollView.contentSize.height let frameHeight = scrollView.frame.size.height if contentHeight >= frameHeight, offsetY >= contentHeight - frameHeight { self.isLoading = true self.showBottomLoader() self.delegate?.loadMore(completion: { [weak self] hasMoreData in guard let this = self else { return } this.hideBottomLoader() this.isLoading = false this.hasMoreDataToLoad = hasMoreData if !hasMoreData { this.removeBottomLoader() this.removeScrollViewOffsetObserver() } }) } } } extension PaginationUIManager: PullToRefreshViewDelegate { public func pull(toRefreshViewDidStartLoading view: PullToRefreshView!) { self.load { } self.pullToRefreshView?.finishLoading() } public func pull(toRefreshViewDidFinishLoading view: PullToRefreshView!) { self.endRefreshing() } public func pull(toRefreshViewShouldStartLoading view: SSPullToRefreshView!) -> Bool { return true } public func pull(_ view: SSPullToRefreshView!, didUpdateContentInset contentInset: UIEdgeInsets) { if self.hasMoreDataToLoad { if let bottomLoader = self.bottomLoader { self.scrollView?.contentInset.bottom = bottomLoader.frame.height } } } public func pull(_ view: SSPullToRefreshView!, didTransitionTo toState: SSPullToRefreshViewState, from fromState: SSPullToRefreshViewState, animated: Bool) { } public func pull(_ view: SSPullToRefreshView!, willTransitionTo toState: SSPullToRefreshViewState, from fromState: SSPullToRefreshViewState, animated: Bool) { } }
mit
09917f47f3b9ade878b276598ee36a8b
31.171004
90
0.614745
5.57244
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Lint/NSLocalizedStringRequireBundleRule.swift
1
2423
import SwiftSyntax struct NSLocalizedStringRequireBundleRule: SwiftSyntaxRule, OptInRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "nslocalizedstring_require_bundle", name: "NSLocalizedString Require Bundle", description: "Calls to NSLocalizedString should specify the bundle which contains the strings file.", kind: .lint, nonTriggeringExamples: [ Example(""" NSLocalizedString("someKey", bundle: .main, comment: "test") """), Example(""" NSLocalizedString("someKey", tableName: "a", bundle: Bundle(for: A.self), comment: "test") """), Example(""" NSLocalizedString("someKey", tableName: "xyz", bundle: someBundle, value: "test" comment: "test") """), Example(""" arbitraryFunctionCall("something") """) ], triggeringExamples: [ Example(""" ↓NSLocalizedString("someKey", comment: "test") """), Example(""" ↓NSLocalizedString("someKey", tableName: "a", comment: "test") """), Example(""" ↓NSLocalizedString("someKey", tableName: "xyz", value: "test", comment: "test") """) ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } } private extension NSLocalizedStringRequireBundleRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: FunctionCallExprSyntax) { if let identifierExpr = node.calledExpression.as(IdentifierExprSyntax.self), identifierExpr.identifier.tokenKind == .identifier("NSLocalizedString"), !node.argumentList.containsArgument(named: "bundle") { violations.append(node.positionAfterSkippingLeadingTrivia) } } } } private extension TupleExprElementListSyntax { func containsArgument(named name: String) -> Bool { contains { arg in arg.label?.tokenKind == .identifier(name) } } }
mit
37476a1ad8a78c2b120784f8613813d8
34.544118
109
0.562267
5.909535
false
true
false
false
Virpik/T
src/UI/[T][Style]/[T][StyleSupport]/TStyleSupportlabel.swift
1
1920
// // TStyleSupportView.swift // T // // Created by Virpik on 24/02/2018. // import Foundation public struct TStyleSupportLabelImpl: TStyleSupportLabel { var getTextColor: (() -> UIColor) var setTextColor: ((UIColor) -> Void) var getTextFont: (() -> UIFont) var setTextFont: ((UIFont) -> Void) var getTextAlignment: (() -> NSTextAlignment) var setTextAlignment: ((NSTextAlignment) -> Void) public var aTextColor: UIColor { get { return self.getTextColor() } set (value) { self.setTextColor(value) } } public var aTextFont: UIFont { get { return self.getTextFont() } set (value) { self.setTextFont(value) } } public var aTextAlignment: NSTextAlignment { get { return self.getTextAlignment() } set (value) { self.setTextAlignment(value) } } } public protocol TStyleSupportLabel { var aTextColor: UIColor { get set } var aTextFont: UIFont { get set } var aTextAlignment: NSTextAlignment { get set } } extension TStyleSupportLabel { public var labelStyle: T.Styles.Label { var style = T.Styles.Label() style.textColor = self.aTextColor style.textFont = self.aTextFont style.textAligment = self.aTextAlignment return style } @discardableResult public func apply(_ style: T.Styles.Label?) -> Self { guard let style = style else { return self } var obj = self obj.aTextAlignment = style.textAligment obj.aTextFont = style.textFont ?? UIFont.systemFont(ofSize: UIFont.systemFontSize) obj.aTextColor = style.textColor ?? .black return obj } }
mit
a51b60bf25d80da6bd711a48d0d8bd71
21.068966
90
0.557813
4.615385
false
false
false
false
apple/swift-nio
Sources/NIOPerformanceTester/SchedulingBenchmark.swift
1
1652
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import NIOCore import NIOPosix final class SchedulingBenchmark: Benchmark { private var group: MultiThreadedEventLoopGroup! private var loop: EventLoop! private let numTasks: Int init(numTasks: Int) { self.numTasks = numTasks } func setUp() throws { group = MultiThreadedEventLoopGroup(numberOfThreads: 1) loop = group.next() // We are preheating the EL to avoid growing the `ScheduledTask` `PriorityQueue` // during the actual test try! self.loop.submit { var counter: Int = 0 for _ in 0..<self.numTasks { self.loop.scheduleTask(in: .nanoseconds(0)) { counter &+= 1 } } }.wait() } func tearDown() { } func run() -> Int { let counter = try! self.loop.submit { () -> Int in var counter: Int = 0 for _ in 0..<self.numTasks { self.loop.scheduleTask(in: .hours(1)) { counter &+= 1 } } return counter }.wait() return counter } }
apache-2.0
f5562a84e0fe0b4b5b90f22bb0171798
26.081967
88
0.515133
4.975904
false
false
false
false
bamurph/FeedKit
Sources/Model/Atom/AtomFeedEntryLink.swift
2
7873
// // AtomFeedEntryLink.swift // // Copyright (c) 2016 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 /** The "atom:link" element defines a reference from an entry or feed to a Web resource. This specification assigns no meaning to the content (if any) of this element. */ open class AtomFeedEntryLink { /** The element's attributes */ open class Attributes { /** The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose value MUST be a IRI reference [RFC3987]. */ open var href: String? /** The atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate". The value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, implementations MUST consider the link relation type equivalent to the same name registered within the IANA Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning of the link, but does not impose any behavioral requirements on Atom Processors. This document defines five initial values for the Registry of Link Relations: 1. The value "alternate" signifies that the IRI in the value of the href attribute identifies an alternate version of the resource described by the containing element. 2. The value "related" signifies that the IRI in the value of the href attribute identifies a resource related to the resource described by the containing element. For example, the feed for a site that discusses the performance of the search engine at "http://search.example.com" might contain, as a child of atom:feed: <link rel="related" href="http://search.example.com/"/> An identical link might appear as a child of any atom:entry whose content contains a discussion of that same search engine. 3. The value "self" signifies that the IRI in the value of the href attribute identifies a resource equivalent to the containing element. 4. The value "enclosure" signifies that the IRI in the value of the href attribute identifies a related resource that is potentially large in size and might require special handling. For atom:link elements with rel="enclosure", the length attribute SHOULD be provided. 5. The value "via" signifies that the IRI in the value of the href attribute identifies a resource that is the source of the information provided in the containing element. */ open var rel: String? /** On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note that the type attribute does not override the actual media type returned with the representation. Link elements MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. */ open var type: String? /** The "hreflang" attribute's content describes the language of the resource pointed to by the href attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. */ open var hreflang: String? /** The "title" attribute conveys human-readable information about the link. The content of the "title" attribute is Language-Sensitive. Entities such as "&amp;" and "&lt;" represent their corresponding characters ("&" and "<", respectively), not markup. Link elements MAY have a title attribute. */ open var title: String? /** The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about the content length of the representation returned when the IRI in the href attribute is mapped to a URI and dereferenced. Note that the length attribute does not override the actual content length of the representation as reported by the underlying protocol. Link elements MAY have a length attribute. */ open var length: Int64? } /** The element's attributes */ open var attributes: Attributes? } // MARK: - Initializers extension AtomFeedEntryLink { /** Initializes the `AtomFeedEntryLink` with the attributes of the "atom:link" element - parameter attributeDict: A dictionary with the attributes of the "atom:link" element - returns: An `AtomFeedEntryLink` instance */ convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = AtomFeedEntryLink.Attributes(attributes: attributeDict) } } extension AtomFeedEntryLink.Attributes { /** Initializes the `Attributes` of the `AtomFeedEntryLink` - parameter: A dictionary with the attributes of the "atom:link" element - returns: An `AtomFeedEntryLink.Attributes` instance */ convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.href = attributeDict["href"] self.hreflang = attributeDict["hreflang"] self.type = attributeDict["type"] self.rel = attributeDict["rel"] self.title = attributeDict["title"] self.length = Int64(attributeDict["length"] ?? "") } }
mit
5623c92c24aef92bcb8d1db2990e78e5
35.962441
91
0.634955
5.149117
false
false
false
false
mnisn/zhangchu
zhangchu/zhangchu/classes/common/UILabelCommon.swift
1
628
// // UILabelCommon.swift // zhangchu // // Created by 苏宁 on 2016/10/21. // Copyright © 2016年 suning. All rights reserved. // import Foundation import UIKit extension UILabel { class func createLabel(text:String?, textAlignment:NSTextAlignment?, font:UIFont?) ->UILabel { let label = UILabel() if let tmpText = text { label.text = tmpText } if let tmpAlignment = textAlignment { label.textAlignment = tmpAlignment } if let tmpFont = font { label.font = tmpFont } return label } }
mit
29ef49a88fb23c5c6ececd63528d727f
19.064516
96
0.566828
4.3125
false
false
false
false
Yvent/QQMusic
QQMusic/QQMusic/CustomProtocols.swift
1
2374
// // CustomProtocols.swift // Pigs have spread // // Created by 周逸文 on 17/2/8. // Copyright © 2017年 Devil. All rights reserved. // import Foundation import UIKit ///'class' not have will error protocol ZYWBackViewDelegate: class { func zywdidleftitem() func zywdidrightitem() func zywdidcenterleftitem() func zywdidcenterrightitem() func zywsetBackView(backView: UIView)} extension ZYWBackViewDelegate where Self: UIViewController{ func zywdidleftitem() { print("Click leftitem") } func zywdidrightitem() { print("Click rightitem") } func zywdidcenterleftitem() { print("Click centerleftitem") } func zywdidcenterrightitem() { print("Click centerrightitem") } func zywsetBackView(backView: UIView) { self.view.addSubview(backView) backView.snp.makeConstraints { (make) in make.left.right.top.equalTo(view) make.height.equalTo(64) } } } //MARK: 关于 UITABLEVIEW==================== protocol NibLoadableView: class { } extension NibLoadableView where Self: UIView { static var NibName: String { return String(describing: self) } } //MARK: 关键字class=此协议针对类 protocol ReusableView: class {} //MARK: where = self 和 UIView 的联系,这里的self指具体的cell extension ReusableView where Self: UIView { static var defaultReuseIdentifier: String { return String(describing: self) } } extension UITableViewCell: ReusableView {} extension UITableView { func register<T: UITableViewCell>(_: T.Type) where T: ReusableView { register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } // func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { // // let Nib = UINib(nibName: T.NibName, bundle: nil) // register(Nib, forCellReuseIdentifier: T.defaultReuseIdentifier) // } func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } }
mit
6af8dc2510dffc715d7cd13ab478db39
25.05618
115
0.661061
4.255046
false
false
false
false
matthewpurcell/firefox-ios
Client/Frontend/Widgets/SiteTableViewController.swift
7
5365
/* 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 struct SiteTableViewControllerUX { static let HeaderHeight = CGFloat(25) static let RowHeight = CGFloat(58) static let HeaderBorderColor = UIColor(rgb: 0xCFD5D9).colorWithAlphaComponent(0.8) static let HeaderTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x232323) static let HeaderBackgroundColor = UIColor(rgb: 0xECF0F3).colorWithAlphaComponent(0.3) static let HeaderFont = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium) static let HeaderTextMargin = CGFloat(10) } class SiteTableViewHeader : UITableViewHeaderFooterView { // I can't get drawRect to play nicely with the glass background. As a fallback // we just use views for the top and bottom borders. let topBorder = UIView() let bottomBorder = UIView() let titleLabel = UILabel() override var textLabel: UILabel? { return titleLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) topBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor titleLabel.font = SiteTableViewControllerUX.HeaderFont titleLabel.textColor = SiteTableViewControllerUX.HeaderTextColor titleLabel.textAlignment = .Left contentView.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor addSubview(topBorder) addSubview(bottomBorder) contentView.addSubview(titleLabel) topBorder.snp_makeConstraints { make in make.left.right.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } bottomBorder.snp_makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } titleLabel.snp_makeConstraints { make in make.left.equalTo(contentView).offset(SiteTableViewControllerUX.HeaderTextMargin) make.right.equalTo(contentView).offset(-SiteTableViewControllerUX.HeaderTextMargin) make.centerY.equalTo(contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /** * Provides base shared functionality for site rows and headers. */ class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private let CellIdentifier = "CellIdentifier" private let HeaderIdentifier = "HeaderIdentifier" var profile: Profile! { didSet { reloadData() } } var data: Cursor<Site> = Cursor<Site>(status: .Success, msg: "No data set") var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp_makeConstraints { make in make.edges.equalTo(self.view) return } tableView.delegate = self tableView.dataSource = self tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: CellIdentifier) tableView.registerClass(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier) tableView.layoutMargins = UIEdgeInsetsZero tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag tableView.backgroundColor = UIConstants.PanelBackgroundColor tableView.separatorColor = UIConstants.SeparatorColor tableView.accessibilityIdentifier = "SiteTable" if #available(iOS 9, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } func reloadData() { if data.status != .Success { print("Err: \(data.statusMessage)", terminator: "\n") } else { self.tableView.reloadData() } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterViewWithIdentifier(HeaderIdentifier) } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return SiteTableViewControllerUX.HeaderHeight } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return SiteTableViewControllerUX.RowHeight } }
mpl-2.0
6951074989a68e7eeb047ecab7c180db
36.78169
123
0.703262
5.430162
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Topic/TopicCoordinator.swift
1
2933
// // TopicCoordinator.swift // MusicApp // // Created by Hưng Đỗ on 6/29/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift protocol TopicCoordinator { func presentTopicDetail(_ topic: Topic, index: Int) -> Observable<Void> func registerTopicPreview(in view: UIView) -> Observable<Void> func removeTopicDetailInfos() } class MATopicCoordinator: NSObject, TopicCoordinator { // MARK: Coordinator weak var sourceViewController: TopicViewController! var getDestinationViewController: (() -> TopicDetailViewController)! func presentTopicDetail(_ topic: Topic, index: Int) -> Observable<Void> { let destinationViewController = getDestinationViewController(topic, page: index) sourceViewController?.show(destinationViewController, sender: nil) return .empty() } func registerTopicPreview(in view: UIView) -> Observable<Void> { if sourceViewController.traitCollection.forceTouchCapability != .unavailable { sourceViewController.registerForPreviewing(with: self, sourceView: view) } return .empty() } // MARK: Controller + Caching private let cache = ItemCache<TopicDetailInfo>() fileprivate func getDestinationViewController(_ topic: Topic, page: Int) -> TopicDetailViewController { let destinationVC = getDestinationViewController() destinationVC.topic = topic destinationVC.topicDetailInfoOutput .subscribe(onNext: { [weak self] info in self?.cache.setItem(info, for: "page\(page)") }) .addDisposableTo(rx_disposeBag) destinationVC.topicDetailInfoInput = cache.getItem("page\(page)") return destinationVC } func removeTopicDetailInfos() { cache.removeAllItems() } } // MARK: View Controller Transitioning extension MATopicCoordinator: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let location = sourceViewController.tableView.convert(location, from: previewingContext.sourceView) guard let indexPath = sourceViewController.tableView.indexPathForRow(at: location) else { return nil } let topicIndex = indexPath.row let topic = sourceViewController.store.topics.value[topicIndex] let destinationViewController = getDestinationViewController( topic, page: topicIndex ) return destinationViewController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { sourceViewController?.show(viewControllerToCommit, sender: nil) } }
mit
e1c0a590f7764fd9bc86b34e264de1aa
31.533333
143
0.681011
5.663443
false
false
false
false
silt-lang/silt
Sources/Mantle/Solve.swift
1
18005
/// Solve.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere import Moho typealias ConstraintID = Int typealias SolverConstraints = [(Set<Meta>, SolverConstraint)] /// The solve phase uses McBride-Gundry Unification to assign unifiers to /// metavariables. /// /// We implement a significantly less powerful form of the Ambulando /// Solver present in McBride and Gundry's papers and Epigram. /// Manipulations of the proof context occur as side effecting operations /// on the signature. Hence when McBride and Gundry speak of moving /// "left" or "right" we must instead "strengthen" and "weaken" corresponding /// substitutions. /// /// McBride-Gundry unification is complicated and hard to describe, let alone /// get right. Nevertheless, we currently implement the following strategies: /// /// - Intensional (Syntactic) Equality /// - Eta-expansion and contraction /// - Rigid-rigid decomposition /// - Inversion /// - Intersection /// - Pruning /// /// Pientka notes that we ought to try /// /// - Pruning despite non-linearity. /// - Flattening Sigmas /// - Lowering (if we model tuples in TT). /// /// The goal is to try to reduce a term involving metavariables to one that is /// in Miller (and Pfenning's) "Pattern Fragment" (where metavariables are /// applied to spines of distinct bound variables). Terms in the pattern /// fragment have a number of desirable properties to a type solver: decidable /// unification and the presence of most-general unifiers. However, we are /// not lucky enough to always be in this state, so the algorithm implements /// constraint postponement in the hope that we *will* be at some point in the /// future. public final class SolvePhaseState { var constraints: SolverConstraints = [] var constraintGraph: ConstraintGraph = ConstraintGraph() public init() {} } extension TypeChecker { /// Solves a series of heterogeneous constraints yielding the environment of /// the solver when it finishes. func solve(_ constraints: [Constraint]) -> Environment { let solver = TypeChecker<SolvePhaseState>(self.signature, self.environment, SolvePhaseState(), self.engine, options) for c in constraints { solver.solve(c) } return self.environment } } /// Implements homogeneous constraints for the solver. struct SolverConstraint: CustomDebugStringConvertible, Hashable { indirect enum RawConstraint: CustomDebugStringConvertible { /// Under the given context, and given that each term has the specified /// type, synthesize or check for a common unifier between the two terms. case unify(Context, Type<TT>, Term<TT>, Term<TT>) /// Under the given context, and given that the type of an application's /// spine ultimately has a particular type, check that the elims in the /// spines of two terms have a common unifier between them. case unifySpines(Context, Type<TT>, Term<TT>?, [Elim<Term<TT>>], [Elim<Term<TT>>]) /// The conjunction of multiple constraints. case conjoin([RawConstraint]) /// The hypothetical form of two constraints: If the first constraint is /// satisfied, we may move on to the second. Else we fail the solution set. case suppose(RawConstraint, RawConstraint) func getMetas() -> FreeMetas { switch self { case let .unify(_, ty, t1, t2): return freeMetas(ty) .union(freeMetas(t1)) .union(freeMetas(t2)) case let .unifySpines(_, t1, .some(head), _, _): return freeMetas(t1).union(freeMetas(head)) case let .unifySpines(_, t1, .none, _, _): return freeMetas(t1) case let .conjoin(cs): let metas = Set<Meta>() return cs.reduce(into: metas) { acc, next in acc.formUnion(next.getMetas()) } case let .suppose(left, right): return left.getMetas().union(right.getMetas()) } } var simplify: RawConstraint? { func flatten(sconstraint: RawConstraint) -> [RawConstraint] { switch sconstraint { case let .conjoin(constrs): return constrs.flatMap(flatten) default: return [sconstraint] } } switch self { case let .conjoin(xs) where xs.isEmpty: return nil case let .conjoin(xs) where xs.count == 1: return xs.first!.simplify case let .conjoin(xs): return xs.flatMap(flatten).reduce(nil) { $0 ?? $1.simplify } default: return self } } var debugDescription: String { switch self { case let .unify(_, ty, tm1, tm2): return "\(tm1) : \(ty) == \(tm2) : \(ty)" case let .suppose(con1, con2): return "(\(con1.debugDescription)) => (\(con2.debugDescription))" case let .conjoin(cs): return cs.map({$0.debugDescription}).joined(separator: " AND ") case let .unifySpines(_, ty, mbH, elims1, elims2): let desc = zip(elims1, elims2).map({ (e1, e2) in return "\(e1) == \(e2)" }).joined(separator: " , ") return "(\(mbH?.description ?? "??")[\(desc)] : \(ty))" } } } private static var constraintCount: ConstraintID = 0 var raw: RawConstraint let id: ConstraintID init(raw: RawConstraint) { defer { SolverConstraint.constraintCount += 1 } self.raw = raw self.id = SolverConstraint.constraintCount } // Decomposes a heterogeneous constraint into a homogeneous constraint. init(_ c: Constraint) { defer { SolverConstraint.constraintCount += 1 } self.id = SolverConstraint.constraintCount switch c { case let .equal(ctx, ty1, t1, ty2, t2): self.raw = .suppose(.unify(ctx, TT.type, ty1, ty2), .unify(ctx, ty1, t1, t2)) } } func getMetas() -> FreeMetas { return self.raw.getMetas() } var debugDescription: String { return self.raw.debugDescription } var simplify: SolverConstraint? { return self.raw.simplify.map(SolverConstraint.init) } public func hash(into hasher: inout Hasher) { self.id.hash(into: &hasher) } static func == (lhs: SolverConstraint, rhs: SolverConstraint) -> Bool { return lhs.hashValue == rhs.hashValue } } extension TypeChecker where PhaseState == SolvePhaseState { var constraintGraph: ConstraintGraph { return self.state.state.constraintGraph } func solve(_ c: Constraint) { let initialConstraint = SolverConstraint(c) self.state.state.constraints.append(([], SolverConstraint(c))) self.constraintGraph.addConstraint(initialConstraint) var progress = false var newConstr = SolverConstraints() while true { // Pull out the next candidate constraint and its downstream metas. guard let (mvs, constr) = self.state.state.constraints.popLast() else { // If we've got no more constraints to solve, check if the last problem // generated any more constraints and stick them onto the work queue. self.state.state.constraints.append(contentsOf: newConstr) if progress { newConstr.removeAll() progress = false continue } else { for (_, constr) in newConstr { self.constraintGraph.addConstraint(constr) } return } } /// Attempt to pull out any bindings that may have occured in downstream /// metas while we were working on other constraints. let mvsBindings = mvs.map(self.signature.lookupMetaBinding) let anyNewBindings = mvsBindings.contains { $0 != nil } if mvsBindings.isEmpty || anyNewBindings { // If we may make forward progress on this constraint, solve it // and return any fresh constraints it generates to the queue. let newConstrs = self.solveConstraint(constr.raw) newConstr.append(contentsOf: newConstrs) progress = true } else { // Return the constraint to the work queue if we can't make progress on // it. newConstr.append((mvs, constr)) } } } /// Attempt to solve a homogeneous constraint returning any new constraints /// that may have arisen from the process of doing so. private func solveConstraint( _ scon: SolverConstraint.RawConstraint) -> SolverConstraints { switch scon { case let .conjoin(constrs): return constrs.flatMap(self.solveConstraint) case let .unify(ctx, ty, t1, t2): return self.unify((ctx, ty, t1, t2)) case let .suppose(constr1, constr2): let extraConstrs = self.solveConstraint(constr1).compactMap({ (mv, csr) in return csr.simplify.map { c in [(mv, c)] } }).joined() if extraConstrs.isEmpty { return self.solveConstraint(constr2) } let mzero = (Set<Meta>(), SolverConstraint.RawConstraint.conjoin([])) let (mvs, newAnte) : (Set<Meta>, SolverConstraint.RawConstraint) = extraConstrs.reduce(mzero) { (acc, next) in let (nextSet, nextConstr) = next switch (acc.1, nextConstr.raw) { case let (.conjoin(cs1), .conjoin(cs2)): return (acc.0.union(nextSet), .conjoin(cs1 + cs2)) case let (.conjoin(cs1), c2): return (acc.0.union(nextSet), .conjoin(cs1 + [c2])) case let (c1, .conjoin(cs2)): return (acc.0.union(nextSet), .conjoin([c1] + cs2)) case let (c1, c2): return (acc.0.union(nextSet), .conjoin([c1, c2])) } } return [(mvs, .init(raw: .suppose(newAnte, constr2)))] case let .unifySpines(ctx, ty, mbH, elims1, elims2): return self.equalSpines(ctx, ty, mbH, elims1, elims2) } } } extension TypeChecker where PhaseState == SolvePhaseState { typealias UnifyFrame = (Context, Type<TT>, Term<TT>, Term<TT>) enum EqualityProgress { case done(SolverConstraints) case notDone(UnifyFrame) } func unify(_ frame: UnifyFrame) -> SolverConstraints { let strategies = [ self.checkEqualTerms, self.etaExpandTerms, self.interactWithMetas, ] var args: UnifyFrame = frame for strat in strategies { switch strat(args) { case let .done(constrs): return constrs case let .notDone(nextFrame): args = nextFrame } } return self.compareTerms(args) } private func checkEqualTerms(_ frame: UnifyFrame) -> EqualityProgress { let (ctx, type, t1, t2) = frame let t1Norm = self.toWeakHeadNormalForm(t1).ignoreBlocking let t2Norm = self.toWeakHeadNormalForm(t2).ignoreBlocking guard t1Norm == t2Norm else { return EqualityProgress.notDone((ctx, type, t1Norm, t2Norm)) } return EqualityProgress.done([]) } private func etaExpandTerms(_ frame: UnifyFrame) -> EqualityProgress { let (ctx, type, t1, t2) = frame let etaT1 = self.etaExpand(type, t1) let etaT2 = self.etaExpand(type, t2) return EqualityProgress.notDone((ctx, type, etaT1, etaT2)) } private func interactWithMetas(_ frame: UnifyFrame) -> EqualityProgress { let (ctx, type, t1, t2) = frame let blockedT1 = self.toWeakHeadNormalForm(t1) let t1Norm = blockedT1.ignoreBlocking let blockedT2 = self.toWeakHeadNormalForm(t2) let t2Norm = blockedT2.ignoreBlocking switch (blockedT1, blockedT2) { case let (.onHead(mv1, els1), .onHead(mv2, els2)) where mv1 == mv2: guard !self.tryIntersection(mv1, els1, els2) else { return .done([]) } return .done([([mv1], .init(raw: .unify(ctx, type, t1Norm, t2Norm)))]) case let (.onHead(mv, elims), .onHead(mv2, _)): let rep1 = self.constraintGraph.getRepresentative(mv) let rep2 = self.constraintGraph.getRepresentative(mv2) self.constraintGraph.mergeEquivalenceClasses(rep1, rep2) return .done(self.bindMeta(in: ctx, type, mv, elims, t2)) case let (.onHead(mv, elims), _): return .done(self.bindMeta(in: ctx, type, mv, elims, t2)) case let (_, .onHead(mv, elims)): return .done(self.bindMeta(in: ctx, type, mv, elims, t1)) case (.notBlocked(_), .notBlocked(_)): return .notDone((ctx, type, t1Norm, t2Norm)) default: print(blockedT1, blockedT2) fatalError() } } private func bindMeta( in ctx: Context, _ type: Type<TT>, _ meta: Meta, _ elims: [Elim<Term<TT>>], _ term: Term<TT> ) -> SolverConstraints { let inversionResult = self.invert(elims) guard case let .success(inv) = inversionResult else { guard case let .failure(mvs) = inversionResult else { fatalError() } let fvs = freeVars(term).all guard let prunedMeta = self.tryPruneSpine(fvs, meta, elims) else { let metaTerm = TT.apply(.meta(meta), elims) return [(mvs.union([meta]), .init(raw: .unify(ctx, type, metaTerm, term)))] } let elimedMeta = self.eliminate(prunedMeta, elims) return self.unify((ctx, type, elimedMeta, term)) } let prunedTerm = self.pruneTerm(Set(inv.substitution.map {$0.0}), term) let inv0 = self.applyInversion(inv, to: prunedTerm, in: ctx) switch inv0 { case let .success(mvb): guard !freeMetas(mvb.body).contains(meta) else { // FIXME: Make this a diagnostic. fatalError("Occurs check failed!") } self.signature.instantiateMeta(meta, mvb) self.constraintGraph.bindMeta(meta, to: mvb) return [] case let .failure(.collect(mvs)): let mvT = TT.apply(.meta(meta), elims) return [(mvs, .init(raw: .unify(ctx, type, mvT, term)))] case let .failure(.fail(v)): fatalError("Free variable in term! \(v)") } } private func compareTerms(_ frame: UnifyFrame) -> SolverConstraints { let (ctx, type, tm1, tm2) = frame let typeView = self.toWeakHeadNormalForm(type).ignoreBlocking let t1View = self.toWeakHeadNormalForm(tm1).ignoreBlocking let t2View = self.toWeakHeadNormalForm(tm2).ignoreBlocking switch (typeView, t1View, t2View) { case (.type, .type, .type): return [] case let (.apply(.definition(_), typeParameters), .constructor(constr1, constrArgs1), .constructor(constr2, constrArgs2)): guard constr1 == constr2 else { fatalError("Created a constraint with mismatched record constructors?") } guard let applyParams = typeParameters.mapM({ $0.applyTerm }) else { fatalError() } let (_, openedData) = self.getOpenedDefinition(constr1.key) guard case let .dataConstructor(_, _, dataConType) = openedData else { fatalError() } // Apply available arguments up to the type of the constructor itself. let appliedDataConType = self.openContextualType(dataConType, applyParams) return self.equalSpines(ctx, appliedDataConType, nil, constrArgs1.map(Elim<TT>.apply), constrArgs2.map(Elim<TT>.apply)) case let (.pi(dom, cod), .lambda(body1), .lambda(body2)): let ctx2 = ctx + [(wildcardName, dom)] return self.unify((ctx2, cod, body1, body2)) case let (_, .apply(head1, elims1), .apply(head2, elims2)): guard head1 == head2 else { print(typeView, t1View, t2View) fatalError("Terms not equal") } let headTy = self.infer(head1, in: ctx) let headTm = TT.apply(head1, []) return self.equalSpines(ctx, headTy, headTm, elims1, elims2) case let (.type, .pi(dom1, cod1), .pi(dom2, cod2)): let piType = { () -> Type<TT> in let avar = TT.apply(.variable(Var(wildcardName, 0)), []) return TT.pi(.type, .pi(.pi(avar, .type), .type)) }() let cod1p = TT.lambda(cod1) let cod2p = TT.lambda(cod2) return self.equalSpines(ctx, piType, nil, [dom1, cod1p].map(Elim<TT>.apply), [dom2, cod2p].map(Elim<TT>.apply)) default: print(typeView, t1View, t2View) fatalError("Terms not equal") } } private func equalSpines( _ ctx: Context, _ ty: Type<TT>, _ h: Term<TT>?, _ elims1: [Elim<Term<TT>>], _ elims2: [Elim<Term<TT>>] ) -> SolverConstraints { guard !(elims1.isEmpty && elims1.isEmpty) else { return [] } guard elims1.count == elims2.count else { print(ty.description, elims1, elims2) fatalError("Spines not equal") } var type = ty var head = h var constrs = SolverConstraints() var idx = 1 for (elim1, elim2) in zip(elims1, elims2) { defer { idx += 1 } switch (elim1, elim2) { case let (.apply(arg1), .apply(arg2)): let piType = self.toWeakHeadNormalForm(type).ignoreBlocking guard case let .pi(domain, codomain) = piType else { fatalError() } let argFrame: UnifyFrame = (ctx, domain, arg1, arg2) let unifyFrame = self.unify(argFrame) switch try? codomain.applySubstitution(.strengthen(1), self.eliminate) { case .none: let instCod = codomain .forceApplySubstitution(.instantiate(arg1), self.eliminate) let unifyRestOfSpine: SolverConstraint.RawConstraint = .unifySpines(ctx, instCod, head, [Elim<TT>](elims1.dropFirst(idx)), [Elim<TT>](elims2.dropFirst(idx))) return unifyFrame + self.solveConstraint(unifyRestOfSpine) case let .some(substCodomain): type = substCodomain constrs.append(contentsOf: unifyFrame) } // case let (.project(proj1), .project(proj2)): // fatalError() default: print(type.description, elims1, elims2) fatalError("Spines not equal") } } return constrs } }
mit
8c14590536e6f35005913f2901748d5d
35.971253
80
0.629047
3.73006
false
false
false
false
tad-iizuka/swift-sdk
Source/TradeoffAnalyticsV1/Models/Resolution.swift
3
7487
/** * Copyright IBM Corporation 2016 * * 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 import RestKit /// A resolution to a decision problem. public struct Resolution: JSONDecodable { /// The two-dimensional position of the option on the map polygon displayed by the /// Tradeoff Analytics visualization. public let map: Map? /// Analytical data per option. public let solutions: [Solution] /// Used internally to initialize a `Resolution` model from JSON. public init(json: JSON) throws { map = try? json.decode(at: "map") solutions = try json.decodedArray(at: "solutions", type: Solution.self) } } /// The two-dimensional position of an option on the map /// polygon displayed by the Tradeoff Analytics visualization. public struct Map: JSONDecodable { /// A representation of the vertices for the objectives and their positions on the map /// visualization. public let anchors: [Anchor] /// A cell on the map visualization. Each cell in the array includes coordinates that /// describe the position on the map of the glyphs for one or more listed options, which /// are identified by their keys. public let nodes: [MapNode] /// Used internally to initialize a `Map` model from JSON. public init(json: JSON) throws { anchors = try json.decodedArray(at: "anchors", type: Anchor.self) nodes = try json.decodedArray(at: "nodes", type: MapNode.self) } } /// A representation of the vertices for an objective and its positions on the map visualization. public struct Anchor: JSONDecodable { /// Anchor point name. public let name: String /// Anchor point position. public let position: MapNodeCoordinates /// Used internally to initialize an `Anchor` model from JSON. public init(json: JSON) throws { name = try json.getString(at: "name") position = try json.decode(at: "position") } } /// A cell on the map visualization. public struct MapNode: JSONDecodable { /// The position of the cell on the map visualization. public let coordinates: MapNodeCoordinates /// References to solutions (the keys for options) positioned on this cell. public let solutionRefs: [String] /// Used internally to initialize a `MapNode` model from JSON. public init(json: JSON) throws { coordinates = try json.decode(at: "coordinates") solutionRefs = try json.decodedArray(at: "solution_refs", type: String.self) } } /// The position of a cell on the map visualization. public struct MapNodeCoordinates: JSONDecodable { /// X-axis coordinate on the map visualization. public let x: Double /// Y-axis coordinate on the map visualization. public let y: Double /// Used internally to initialize a `MapNodeCoordinates` model from JSON. public init(json: JSON) throws { x = try json.getDouble(at: "x") y = try json.getDouble(at: "y") } } /// Analytical data for a particular option. public struct Solution: JSONDecodable { /// A list of references to solutions that shadow this solution. public let shadowMe: [String]? /// A list of references to solutions that are shadowed by this solution. public let shadows: [String]? /// The key that uniquely identifies the option in the decision problem. public let solutionRef: String /// The status of the option (i.e. `Front`, `Excluded`, `Incomplete`, /// or `DoesNotMeetPreference`). public let status: SolutionStatus /// If the status is `Incomplete` or `DoesNotMeetPreference`, a description that provides /// more information about the cause of the status. public let statusCause: StatusCause? /// Used internally to initialize a `Solution` model from JSON. public init(json: JSON) throws { shadowMe = try? json.decodedArray(at: "shadow_me", type: String.self) shadows = try? json.decodedArray(at: "shadows", type: String.self) solutionRef = try json.getString(at: "solution_ref") statusCause = try? json.decode(at: "status_cause") guard let status = SolutionStatus(rawValue: try json.decode(at: "status")) else { throw JSON.Error.valueNotConvertible(value: json, to: Solution.self) } self.status = status } } /// The status of an option. public enum SolutionStatus: String { /// `Front` indicates that the option is included among the top options for the problem. case front = "FRONT" /// `Excluded` indicates that another option is strictly better than the option. case excluded = "EXCLUDED" /// `Incomplete` indicates that either the option's specification does not include a value /// for one of the columns or its value for one of the columns lies outside the range specified /// for the column. Only a column whose `isObjective` property is set to `true` can generate /// this status. case incomplete = "INCOMPLETE" /// `DoesNotMeetPreference` indicates that the option specifies a value for a `Categorical` /// column that is not included in the column's preference. case doesNotMeetPreference = "DOES_NOT_MEET_PREFERENCE" } /// Additional information about the cause of an option's status. public struct StatusCause: JSONDecodable { /// An error code that specifies the cause of the option's status. public let errorCode: TradeoffAnalyticsError /// A description in English of the cause for the option's status. public let message: String /// An array of values used to describe the cause for the option's status. The strings /// appear in the message field. public let tokens: [String] /// Used internally to initialize a `StatusCause` model from JSON. public init(json: JSON) throws { guard let errorCode = TradeoffAnalyticsError(rawValue: try json.getString(at: "error_code")) else { throw JSON.Error.valueNotConvertible(value: json, to: StatusCause.self) } self.errorCode = errorCode message = try json.getString(at: "message") tokens = try json.decodedArray(at: "tokens", type: String.self) } } /// An error that specifies the cause of an option's status. public enum TradeoffAnalyticsError: String { /// Indicates that a column for which the `isObjective` property is `true` is absent from /// the option's specification. case missingObjectiveValue = "MISSING_OBJECTIVE_VALUE" /// Indicates that the option's specifications defines a value that is outside of the range /// specified for an objective. case rangeMismatch = "RANGE_MISMATCH" /// Indicates that a `Categorical` column value for the option is not in the preference /// for that column. case doesNotMeetPreference = "DOES_NOT_MEET_PREFERENCE" }
apache-2.0
6e0cb2095bc6d25f403f0b100f13a391
37.005076
107
0.684921
4.483234
false
false
false
false
groue/GRDB.swift
GRDB/Core/Support/Foundation/SQLiteDateParser.swift
1
7171
import Foundation // inspired by: http://jordansmith.io/performant-date-parsing/ @usableFromInline struct SQLiteDateParser { @usableFromInline init() { } func components(from dateString: String) -> DatabaseDateComponents? { dateString.withCString { cString in components(cString: cString, length: strlen(cString)) } } @usableFromInline func components(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? { assert(strlen(cString) == length) // "HH:MM" is the shortest valid string guard length >= 5 else { return nil } // "YYYY-..." -> datetime if cString[4] == UInt8(ascii: "-") { var components = DateComponents() var parser = Parser(cString: cString, length: length) guard let format = parseDatetimeFormat(parser: &parser, into: &components), parser.length == 0 else { return nil } return DatabaseDateComponents(components, format: format) } // "HH-:..." -> time if cString[2] == UInt8(ascii: ":") { var components = DateComponents() var parser = Parser(cString: cString, length: length) guard let format = parseTimeFormat(parser: &parser, into: &components), parser.length == 0 else { return nil } return DatabaseDateComponents(components, format: format) } // Invalid return nil } // - YYYY-MM-DD // - YYYY-MM-DD HH:MM // - YYYY-MM-DD HH:MM:SS // - YYYY-MM-DD HH:MM:SS.SSS // - YYYY-MM-DDTHH:MM // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS private func parseDatetimeFormat( parser: inout Parser, into components: inout DateComponents) -> DatabaseDateComponents.Format? { guard let year = parser.parseNNNN(), parser.parse("-"), let month = parser.parseNN(), parser.parse("-"), let day = parser.parseNN() else { return nil } components.year = year components.month = month components.day = day if parser.length == 0 { return .YMD } guard parser.parse(" ") || parser.parse("T") else { return nil } switch parseTimeFormat(parser: &parser, into: &components) { case .HM: return .YMD_HM case .HMS: return .YMD_HMS case .HMSS: return .YMD_HMSS default: return nil } } // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS private func parseTimeFormat( parser: inout Parser, into components: inout DateComponents) -> DatabaseDateComponents.Format? { guard let hour = parser.parseNN(), parser.parse(":"), let minute = parser.parseNN() else { return nil } components.hour = hour components.minute = minute if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { return .HM } guard parser.parse(":"), let second = parser.parseNN() else { return nil } components.second = second if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { return .HMS } guard parser.parse(".") else { return nil } // Parse one to three digits // Rationale: https://github.com/groue/GRDB.swift/pull/362 var nanosecond = 0 guard parser.parseDigit(into: &nanosecond) else { return nil } if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { components.nanosecond = nanosecond * 100_000_000 return .HMSS } guard parser.parseDigit(into: &nanosecond) else { return nil } if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { components.nanosecond = nanosecond * 10_000_000 return .HMSS } guard parser.parseDigit(into: &nanosecond) else { return nil } components.nanosecond = nanosecond * 1_000_000 while parser.parseDigit() != nil { } _ = parseTimeZone(parser: &parser, into: &components) return .HMSS } private func parseTimeZone( parser: inout Parser, into components: inout DateComponents) -> Bool { if parser.parse("Z") { components.timeZone = TimeZone(secondsFromGMT: 0) return true } if parser.parse("+"), let hour = parser.parseNN(), parser.parse(":"), let minute = parser.parseNN() { components.timeZone = TimeZone(secondsFromGMT: hour * 3600 + minute * 60) return true } if parser.parse("-"), let hour = parser.parseNN(), parser.parse(":"), let minute = parser.parseNN() { components.timeZone = TimeZone(secondsFromGMT: -(hour * 3600 + minute * 60)) return true } return false } private struct Parser { var cString: UnsafePointer<CChar> var length: Int private mutating func shift() { cString += 1 length -= 1 } mutating func parse(_ scalar: Unicode.Scalar) -> Bool { guard length > 0, cString[0] == UInt8(ascii: scalar) else { return false } shift() return true } mutating func parseDigit() -> Int? { guard length > 0 else { return nil } let char = cString[0] let digit = char - CChar(bitPattern: UInt8(ascii: "0")) guard digit >= 0 && digit <= 9 else { return nil } shift() return Int(digit) } mutating func parseDigit(into number: inout Int) -> Bool { guard let digit = parseDigit() else { return false } number = number * 10 + digit return true } mutating func parseNNNN() -> Int? { var number = 0 guard parseDigit(into: &number) && parseDigit(into: &number) && parseDigit(into: &number) && parseDigit(into: &number) else { // Don't restore self to initial state because we don't need it return nil } return number } mutating func parseNN() -> Int? { var number = 0 guard parseDigit(into: &number) && parseDigit(into: &number) else { // Don't restore self to initial state because we don't need it return nil } return number } } }
mit
9366ceb2eaab4b4dfb1900c637dd1088
30.590308
98
0.510807
4.812752
false
false
false
false
PingStart/pingstart_sdk_iOS
NbtPSSDKDev/NbtPSSDKDevSwift/Classes/NativeAdVC.swift
1
2530
// // NativeAdVC.swift // PSSDK-Example-Swift // // Created by nbt on 2016/12/30. // Copyright © 2016年 nbt. All rights reserved. // import UIKit import NbtPingStart class NativeAdVC: UIViewController,PSNativeDelegate { fileprivate var adView : PSNativeView? fileprivate lazy var activityView : UIActivityIndicatorView = { [unowned self] in var aView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:.gray) aView.hidesWhenStopped = true aView.center = self.view.center self.view.addSubview(aView) return aView }() fileprivate lazy var textView : UITextView = { [unowned self] in var tView = UITextView(frame: CGRect(x:0, y:self.topLayoutGuide.length, width:self.view.frame.size.width, height:self.view.frame.size.height-self.topLayoutGuide.length)) tView.isEditable = false tView.autoresizingMask = [.flexibleBottomMargin,.flexibleWidth,.flexibleHeight] tView.font = UIFont.systemFont(ofSize: 16) self.view.addSubview(tView) return tView }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.title = "native" let barItem = UIBarButtonItem(title: "load", style: .plain, target: self, action: #selector(rightBtnAction)) self.navigationItem.rightBarButtonItem = barItem adView = PSNativeView(publisherId: "5418", slotId: "1002000") adView?.delegate = self } func rightBtnAction() { adView?.loadAd() } // MARK: - delegate func psAdViewWillLoad(_ view: PSBaseView) { activityView.startAnimating() } func psAdView(_ view: PSBaseView, didFailToReceiveAdWithError error: PSError) { activityView.stopAnimating() print("\(error)") let alertVC = UIAlertController(title: "error", message: "\(error)", preferredStyle: .alert); alertVC.addAction(UIAlertAction(title: "ok", style: .cancel, handler: nil)) self.present(alertVC, animated: true, completion: nil) } func psAdViewNativeDidLoad(_ view: PSNativeView) { activityView.stopAnimating() let nativeAd = view.nativeAd textView.text = "【title】\(nativeAd?.title)\n【desc】\(nativeAd?.desc)\n【calltoaction】\(nativeAd?.calltoaction)\n【iconUrl】\(nativeAd?.iconUrl)\n【coverimageUrl】\(nativeAd?.coverimageUrl)" } }
mit
aa5fcf4a16c642dc3c6035c859b49210
33.819444
191
0.654567
4.500898
false
false
false
false
MJHee/QRCode
QRCode/QRCode/AppDelegate.swift
1
4717
// // AppDelegate.swift // QRCode // // Created by MJHee on 2017/3/18. // Copyright © 2017年 MJBaby. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let navigation = UINavigationController(rootViewController: ViewController()) self.window?.rootViewController = navigation self.window?.backgroundColor = UIColor.white return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "QRCode") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
75a2e2d9c6957577117b6080a052f470
47.597938
285
0.684769
5.877805
false
false
false
false
pablogsIO/MadridShops
MadridShops/Model/JSONParser/JSONParser.swift
1
4066
// // JSONParser.swift // MadridShops // // Created by Pablo García on 26/09/2017. // Copyright © 2017 KC. All rights reserved. // import Foundation func parseCityDataInformation(data: Data) -> CityDataInformationList { let cityDataInformationList = CityDataInformationList() do { let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary<String, Any> let result = jsonObject["result"] as! [Dictionary<String, Any>] for shopJson in result { let cityDataInformation = CityDataInformation(name: shopJson["name"]! as! String) cityDataInformation.address = shopJson["address"]! as! String cityDataInformation.logo = shopJson["logo_img"] as! String cityDataInformation.image = shopJson["img"] as! String cityDataInformation.bookingData = shopJson["booking_data"]! as! String cityDataInformation.bookingOperation = shopJson["booking_operation"]! as! String cityDataInformation.email = shopJson["email"]! as! String if let latitude = shopJson["gps_lat"]! as? String{ cityDataInformation.latitude = Double(latitude.trimmingCharacters(in: CharacterSet.whitespaces).replacingOccurrences(of: ",", with: "")) } if let longitude = shopJson["gps_lon"]! as? String{ cityDataInformation.longitude = Double(longitude.trimmingCharacters(in: CharacterSet.whitespaces).replacingOccurrences(of: ",", with: "")) } cityDataInformation.id = shopJson["id"]! as! String cityDataInformation.logo = shopJson["logo_img"] as! String cityDataInformation.image = shopJson["img"] as! String cityDataInformation.description = createLanguageDictionary(english: shopJson["description_en"]! as? String, spanish_es: shopJson["description_es"]! as? String, spanish_mx: shopJson["description_mx"]! as? String, spanish_cl: shopJson["description_cl"]! as? String, japanese: shopJson["description_jp"]! as? String, chinese: shopJson["description_cn"]! as? String ) cityDataInformation.keywords = createLanguageDictionary(english: shopJson["keywords_en"]! as? String, spanish_es: shopJson["keywords_es"]! as? String, spanish_mx: shopJson["keywords_mx"]! as? String, spanish_cl: shopJson["keywords_cl"]! as? String, japanese: shopJson["keywords_jp"]! as? String, chinese: shopJson["keywords_cn"]! as? String) cityDataInformation.openingHours = createLanguageDictionary(english: shopJson["opening_hours_en"]! as? String, spanish_es: shopJson["opening_hours_es"]! as? String, spanish_mx: shopJson["opening_hours_mx"]! as? String, spanish_cl: shopJson["opening_hours_cl"]! as? String, japanese: shopJson["opening_hours_jp"]! as? String, chinese: shopJson["opening_hours_cn"]! as? String ) if let so = shopJson["special_offer"]! as? String{ cityDataInformation.specialOffer = so.stringToBool() } cityDataInformation.telephone = shopJson["telephone"]! as! String cityDataInformation.shopUrl = shopJson["url"]! as! String cityDataInformationList.add(cityDataInformation: cityDataInformation) } } catch { print("Error parsing JSON") } return cityDataInformationList }
mit
fcd733dd2efcc5c001f66ba3cf0edfd5
53.186667
149
0.568406
4.703704
false
false
false
false
austintaylor/minitray
MiniTray/AppDelegate.swift
1
1508
// // AppDelegate.swift // MiniTray // // Created by Austin Taylor on 7/31/14. // Copyright (c) 2014 Austin Taylor. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { var _window: NSWindow init(window: NSWindow) { self._window = window } class func createWindow() { let application = NSApplication.sharedApplication() let window = NSWindow(contentRect: NSMakeRect(0, 0, 160, 24), styleMask: NSBorderlessWindowMask, backing: .Buffered, defer: false) window.level = Int(CGShieldingWindowLevel()) window.collectionBehavior = .CanJoinAllSpaces window.backgroundColor = NSColor.clearColor() window.opaque = false window.makeKeyAndOrderFront(window) let applicationDelegate = AppDelegate(window: window) application.delegate = applicationDelegate application.run() } func applicationDidFinishLaunching(aNotification: NSNotification?) { let sf = NSScreen.mainScreen().visibleFrame let screens = NSScreen.screens() let wf = _window.frame _window.setFrameOrigin(NSPoint( x: sf.size.width - wf.size.width, y: 0 )) let view = MiniTray(frame: NSMakeRect(0, 0, wf.width, wf.height), window: _window) _window.contentView = view } func applicationWillTerminate(aNotification: NSNotification?) { // Insert code here to tear down your application } }
mit
4f7cac1ee25af07965fe0a928be9104a
31.085106
138
0.656499
4.654321
false
false
false
false
G-Rex2595/LocalChat
Chat/Chat/BlockListView.swift
3
2385
// // BlockListView.swift // Chat // // Created by Vishal Gill on 12/4/15. // Copyright © 2015 Vishal Gill. All rights reserved. // import Foundation import UIKit class BlockListView: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var blockListTable: UITableView! @IBOutlet weak var settings: UIButton! override func viewDidLoad() { super.viewDidLoad() self.settings.tintColor = Singleton.sharedInstance.textColor self.settings.titleLabel!.font = UIFont(name: Singleton.sharedInstance.font, size:(settings.titleLabel!.font.pointSize))! self.blockListTable.delegate = self self.blockListTable.dataSource = self // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(blockListTable: UITableView) -> Int { return 1; } func tableView(blockListTable: UITableView, numberOfRowsInSection section: Int) -> Int { return Singleton.sharedInstance.blockList.count } func tableView(blockListTable: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let tableCell = UITableViewCell() tableCell.textLabel?.text = Singleton.sharedInstance.blockList[indexPath.row] return tableCell } func tableView(blockListTable: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 35.0 } // func tableView(blockListTable: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // // Singleton.sharedInstance.blockList.removeAtIndex(indexPath.row) // // blockListTable.reloadData() // // // // } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { Singleton.sharedInstance.blockList.removeAtIndex(indexPath.row) blockListTable.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } }
mit
e5696dad8579d729fe1e2e27042977cb
29.974026
148
0.686242
5.46789
false
false
false
false
bachonk/InitialsImageView
InitialsImageView.swift
1
7358
// // InitialsImageView.swift // // // Created by Tom Bachant on 1/28/17. // // import UIKit let kFontResizingProportion: CGFloat = 0.4 let kColorMinComponent: Int = 30 let kColorMaxComponent: Int = 214 public typealias GradientColors = (top: UIColor, bottom: UIColor) typealias HSVOffset = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) let kGradientTopOffset: HSVOffset = (hue: -0.025, saturation: 0.05, brightness: 0, alpha: 0) let kGradientBotomOffset: HSVOffset = (hue: 0.025, saturation: -0.05, brightness: 0, alpha: 0) extension UIImageView { public func setImageForName(_ string: String, backgroundColor: UIColor? = nil, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false) { setImageForName(string, backgroundColor: backgroundColor, circular: circular, textAttributes: textAttributes, gradient: gradient, gradientColors: nil) } public func setImageForName(_ string: String, gradientColors: GradientColors, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?) { setImageForName(string, backgroundColor: nil, circular: circular, textAttributes: textAttributes, gradient: true, gradientColors: gradientColors) } private func setImageForName(_ string: String, backgroundColor: UIColor?, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false, gradientColors: GradientColors?) { let initials: String = initialsFromString(string: string) let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor(for: string) let gradientColors = gradientColors ?? topAndBottomColors(for: color) let attributes: [NSAttributedString.Key: AnyObject] = (textAttributes != nil) ? textAttributes! : [ NSAttributedString.Key.font: self.fontForFontName(name: nil), NSAttributedString.Key.foregroundColor: UIColor.white ] self.image = imageSnapshot(text: initials, backgroundColor: color, circular: circular, textAttributes: attributes, gradient: gradient, gradientColors: gradientColors) } private func fontForFontName(name: String?) -> UIFont { let fontSize = self.bounds.width * kFontResizingProportion guard let name = name else { return .systemFont(ofSize: fontSize) } guard let customFont = UIFont(name: name, size: fontSize) else { return .systemFont(ofSize: fontSize) } return customFont } private func imageSnapshot(text imageText: String, backgroundColor: UIColor, circular: Bool, textAttributes: [NSAttributedString.Key : AnyObject], gradient: Bool, gradientColors: GradientColors) -> UIImage { let scale: CGFloat = UIScreen.main.scale var size: CGSize = self.bounds.size if (self.contentMode == .scaleToFill || self.contentMode == .scaleAspectFill || self.contentMode == .scaleAspectFit || self.contentMode == .redraw) { size.width = (size.width * scale) / scale size.height = (size.height * scale) / scale } UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context: CGContext = UIGraphicsGetCurrentContext() else { return UIImage() } if circular { // Clip context to a circle let path: CGPath = CGPath(ellipseIn: self.bounds, transform: nil) context.addPath(path) context.clip() } if gradient { // Draw a gradient from the top to the bottom let baseSpace = CGColorSpaceCreateDeviceRGB() let colors = [gradientColors.top.cgColor, gradientColors.bottom.cgColor] if let gradient = CGGradient(colorsSpace: baseSpace, colors: colors as CFArray, locations: nil) { let startPoint = CGPoint(x: self.bounds.midX, y: self.bounds.minY) let endPoint = CGPoint(x: self.bounds.midX, y: self.bounds.maxY) context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } } else { // Fill background of context context.setFillColor(backgroundColor.cgColor) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) } // Draw text in the context let textSize: CGSize = imageText.size(withAttributes: textAttributes) let bounds: CGRect = self.bounds imageText.draw(in: CGRect(x: bounds.midX - textSize.width / 2, y: bounds.midY - textSize.height / 2, width: textSize.width, height: textSize.height), withAttributes: textAttributes) guard let snapshot: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() } UIGraphicsEndImageContext() return snapshot } } private func initialsFromString(string: String) -> String { var nameComponents = string.uppercased().components(separatedBy: CharacterSet.letters.inverted) nameComponents.removeAll(where: {$0.isEmpty}) let firstInitial = nameComponents.first?.first let lastInitial = nameComponents.count > 1 ? nameComponents.last?.first : nil return (firstInitial != nil ? "\(firstInitial!)" : "") + (lastInitial != nil ? "\(lastInitial!)" : "") } private func randomColorComponent() -> Int { let limit = kColorMaxComponent - kColorMinComponent return kColorMinComponent + Int(drand48() * Double(limit)) } private func randomColor(for string: String) -> UIColor { srand48(string.hashValue) let red = CGFloat(randomColorComponent()) / 255.0 let green = CGFloat(randomColorComponent()) / 255.0 let blue = CGFloat(randomColorComponent()) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } private func clampColorComponent(_ value: CGFloat) -> CGFloat { return min(max(value, 0), 1) } private func correctColorComponents(of color: UIColor, withHSVOffset offset: HSVOffset) -> UIColor { var hue = CGFloat(0) var saturation = CGFloat(0) var brightness = CGFloat(0) var alpha = CGFloat(0) if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { hue = clampColorComponent(hue + offset.hue) saturation = clampColorComponent(saturation + offset.saturation) brightness = clampColorComponent(brightness + offset.brightness) alpha = clampColorComponent(alpha + offset.alpha) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } return color } private func topAndBottomColors(for color: UIColor, withTopHSVOffset topHSVOffset: HSVOffset = kGradientTopOffset, withBottomHSVOffset bottomHSVOffset: HSVOffset = kGradientBotomOffset) -> GradientColors { let topColor = correctColorComponents(of: color, withHSVOffset: topHSVOffset) let bottomColor = correctColorComponents(of: color, withHSVOffset: bottomHSVOffset) return (top: topColor, bottom: bottomColor) }
mit
2abf8770a339b4400d1a739d981ac350
44.419753
211
0.665806
4.747097
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/PictureDetailViewController.swift
1
15985
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_TextFields_TextFields // swiftlint:disable line_length import third_party_objective_c_material_components_ios_components_private_KeyboardWatcher_KeyboardWatcher // swiftlint:enable line_length /// The detail view controller of a picture which shows the picture in a zooming, panning view and /// allows for caption editing. class PictureDetailViewController: MaterialHeaderViewController, UITextFieldDelegate, CaptionableNoteDetailController { // MARK: - Properties private var cancelCaptionEditTapRecognizer: UITapGestureRecognizer? private let captionWrapper = UIView() private var captionWrapperBottomConstraint: NSLayoutConstraint? private var textFieldLeadingConstraint: NSLayoutConstraint? private var textFieldTrailingConstraint: NSLayoutConstraint? private var textFieldBottomConstraint: NSLayoutConstraint? private var imageViewHeightConstraint: NSLayoutConstraint? private weak var delegate: ExperimentItemDelegate? private var displayPicture: DisplayPictureNote private let imageView = UIImageView() private var menuBarButton = MaterialMenuBarButtonItem() private let metadataManager: MetadataManager private let scrollView = UIScrollView() private let textField = MDCTextField() private var textFieldController: MDCTextInputController? private let preferenceManager: PreferenceManager private let experimentInteractionOptions: ExperimentInteractionOptions private let exportType: UserExportType private let saveToFilesHandler = SaveToFilesHandler() private var horizontalTextFieldPaddingForDisplayType: CGFloat { var padding: CGFloat { switch displayType { case .compact, .compactWide: return 32 case .regular: return 100 case .regularWide: return 300 } } return padding + view.safeAreaInsetsOrZero.left + view.safeAreaInsetsOrZero.right } // Should the view controller make the caption field first responder the first time it appears? private var shouldJumpToCaptionOnLoad: Bool // MARK: - NoteDetailController var displayNote: DisplayNote { get { return displayPicture } set { if let pictureNote = newValue as? DisplayPictureNote { displayPicture = pictureNote updateViewForDisplayNote() } } } var currentCaption: String? { get { return textField.text } set { textField.text = newValue } } // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - displayPicture: A display picture. /// - experimentInteractionOptions: Experiment interaction options. /// - exportType: The export option type to show. /// - delegate: The item delegate. /// - jumpToCaption: Whether the view should jump to the caption on first load. /// - analyticsReporter: The analytics reporter. /// - metadataManager: The metadata manager. /// - preferenceManager: The preference manager. init(displayPicture: DisplayPictureNote, experimentInteractionOptions: ExperimentInteractionOptions, exportType: UserExportType, delegate: ExperimentItemDelegate?, jumpToCaption: Bool, analyticsReporter: AnalyticsReporter, metadataManager: MetadataManager, preferenceManager: PreferenceManager) { self.displayPicture = displayPicture self.experimentInteractionOptions = experimentInteractionOptions self.exportType = exportType self.delegate = delegate self.shouldJumpToCaptionOnLoad = jumpToCaption self.metadataManager = metadataManager self.preferenceManager = preferenceManager super.init(analyticsReporter: analyticsReporter) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black appBar.headerViewController.headerView.backgroundColor = .black let backMenuItem = MaterialBackBarButtonItem(target: self, action: #selector(backButtonPressed)) navigationItem.leftBarButtonItem = backMenuItem menuBarButton.button.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside) menuBarButton.button.setImage(UIImage(named: "ic_more_horiz"), for: .normal) navigationItem.rightBarButtonItem = menuBarButton let doubleTapGesture = UITapGestureRecognizer() doubleTapGesture.numberOfTapsRequired = 2 doubleTapGesture.addTarget(self, action: #selector(handleDoubleTapGesture(_:))) scrollView.addGestureRecognizer(doubleTapGesture) view.addSubview(scrollView) scrollView.delegate = self scrollView.maximumZoomScale = 6 scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.topAnchor .constraint(equalTo: appBar.headerViewController.view.bottomAnchor).isActive = true scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true if let imagePath = displayPicture.imagePath { setImage(withPath: imagePath) } imageView.contentMode = .scaleAspectFit scrollView.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.pinToEdgesOfView(scrollView) imageView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true imageViewHeightConstraint = imageView.heightAnchor.constraint(equalTo: scrollView.heightAnchor) imageViewHeightConstraint?.isActive = true if #available(iOS 11.0, *) { imageView.accessibilityIgnoresInvertColors = true } view.addSubview(captionWrapper) captionWrapper.translatesAutoresizingMaskIntoConstraints = false captionWrapper.backgroundColor = .white captionWrapper.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true captionWrapper.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true captionWrapperBottomConstraint = captionWrapper.bottomAnchor.constraint( equalTo: view.bottomAnchor) captionWrapperBottomConstraint?.isActive = true captionWrapper.addSubview(textField) textField.delegate = self textField.text = displayPicture.caption textField.translatesAutoresizingMaskIntoConstraints = false textField.placeholder = experimentInteractionOptions.shouldAllowEdits ? String.noteCaptionHint : String.noteCaptionHintReadOnly textField.isUserInteractionEnabled = experimentInteractionOptions.shouldAllowEdits textField.clearButtonMode = .never textField.topAnchor.constraint(equalTo: captionWrapper.topAnchor).isActive = true textFieldLeadingConstraint = textField.leadingAnchor.constraint(equalTo: captionWrapper.leadingAnchor) textFieldLeadingConstraint?.isActive = true textFieldTrailingConstraint = textField.trailingAnchor.constraint(equalTo: captionWrapper.trailingAnchor) textFieldTrailingConstraint?.isActive = true textFieldBottomConstraint = textField.bottomAnchor.constraint( equalTo: captionWrapper.bottomAnchor) textFieldBottomConstraint?.isActive = true textField.setContentCompressionResistancePriority(.required, for: .vertical) let controller = MDCTextInputControllerUnderline(textInput: textField) controller.floatingPlaceholderNormalColor = .appBarReviewBackgroundColor controller.activeColor = .appBarReviewBackgroundColor textFieldController = controller updateCaptionLayout() NotificationCenter.default.addObserver( self, selector: #selector(handleKeyboardNotification(_:)), name: Notification.Name.MDCKeyboardWatcherKeyboardWillChangeFrame, object: nil) // Listen to notifications of newly downloaded assets. NotificationCenter.default.addObserver(self, selector: #selector(downloadedImages), name: .driveSyncManagerDownloadedImages, object: nil) } func updateCaptionLayout() { let scrollViewBottomConstraintConstant: CGFloat if !experimentInteractionOptions.shouldAllowEdits && displayPicture.caption == nil { captionWrapper.isHidden = true scrollViewBottomConstraintConstant = 0 } else { // Set the scroll view bottom constraint to the height of the text field. It is not anchored // to the text field because we don't want it to move when the text field moves due to // keyboard changes. captionWrapper.isHidden = false scrollViewBottomConstraintConstant = textField.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height } scrollView.bottomAnchor.constraint( equalTo: view.bottomAnchor, constant: -scrollViewBottomConstraintConstant).isActive = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateConstraintsForDisplayType() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if shouldJumpToCaptionOnLoad { textField.becomeFirstResponder() shouldJumpToCaptionOnLoad = false } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Save the note's caption if necessary. view.endEditing(true) let newCaptionText = textField.text?.trimmedOrNil if newCaptionText != displayPicture.caption { displayPicture.caption = textField.text?.trimmedOrNil delegate?.detailViewControllerDidUpdateCaptionForNote(displayPicture) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() appBar.headerViewController.updateTopLayoutGuide() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !textField.isFirstResponder { let bottomInset = -view.safeAreaInsetsOrZero.bottom textFieldBottomConstraint?.constant = bottomInset imageViewHeightConstraint?.constant = bottomInset } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (_) in self.updateConstraintsForDisplayType() }) } override func viewSafeAreaInsetsDidChange() { updateConstraintsForDisplayType() } // MARK: - Private private func updateConstraintsForDisplayType() { textFieldLeadingConstraint?.constant = horizontalTextFieldPaddingForDisplayType / 2 textFieldTrailingConstraint?.constant = -horizontalTextFieldPaddingForDisplayType / 2 } // MARK: - UIScrollViewDelegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } // MARK: - UITextFieldDelegate func textFieldDidBeginEditing(_ textField: UITextField) { scrollView.isScrollEnabled = false let cancelTapRecognizer = UITapGestureRecognizer() cancelTapRecognizer.addTarget(self, action: #selector(handleTapGesture(_:))) scrollView.addGestureRecognizer(cancelTapRecognizer) cancelCaptionEditTapRecognizer = cancelTapRecognizer } func textFieldDidEndEditing(_ textField: UITextField) { scrollView.isScrollEnabled = true if let cancelCaptionEditTapRecognizer = cancelCaptionEditTapRecognizer { scrollView.removeGestureRecognizer(cancelCaptionEditTapRecognizer) } } // MARK: - Notifications @objc func handleKeyboardNotification(_ notification: Notification) { guard let captionWrapperBottomConstraint = captionWrapperBottomConstraint else { return } let keyboardHeight = MDCKeyboardWatcher.shared().visibleKeyboardHeight let duration = MDCKeyboardWatcher.animationDuration(fromKeyboardNotification: notification) let options = MDCKeyboardWatcher.animationCurveOption(fromKeyboardNotification: notification) UIView.animate(withDuration: duration, delay: 0, options: options, animations: { captionWrapperBottomConstraint.constant = -keyboardHeight self.textFieldBottomConstraint?.constant = 0 self.view.layoutIfNeeded() }) } @objc private func downloadedImages(notification: Notification) { guard Thread.isMainThread else { DispatchQueue.main.async { self.downloadedImages(notification: notification) } return } guard let pictureImagePath = displayPicture.imagePath, let imagePaths = notification.userInfo?[DriveSyncUserInfoConstants.downloadedImagePathsKey] as? [String] else { return } if imagePaths.contains(pictureImagePath) { setImage(withPath: pictureImagePath) } } // MARK: - Private @objc private func handleTapGesture(_ gesture: UITapGestureRecognizer) { textField.endEditing(true) } @objc private func handleDoubleTapGesture(_ gesture: UITapGestureRecognizer) { scrollView.setZoomScale(scrollView.zoomScale == 1 ? 4 : 1, animated: true) } private func updateViewForDisplayNote() { updateCaptionFromDisplayNote() updateCaptionLayout() } private func setImage(withPath imagePath: String) { imageView.image = metadataManager.image(forFullImagePath: imagePath) } // MARK: - User actions @objc private func backButtonPressed() { navigationController?.popViewController(animated: true) } @objc private func menuButtonPressed() { // Info. let popUpMenu = PopUpMenuViewController() popUpMenu.addAction(PopUpMenuAction(title: String.pictureDetailInfo, icon: UIImage(named: "ic_info")) { _ in self.navigationController?.pushViewController( PictureInfoViewController(displayPicture: self.displayPicture, analyticsReporter: self.analyticsReporter, metadataManager: self.metadataManager), animated: true) }) // Export if displayPicture.imageFileExists, let imagePath = displayPicture.imagePath { switch exportType { case .saveToFiles: popUpMenu.addAction(PopUpMenuAction.saveToFiles(withFilePath: imagePath, presentingViewController: self, saveToFilesHandler: saveToFilesHandler)) case .share: popUpMenu.addAction(PopUpMenuAction.share(withFilePath: imagePath, presentingViewController: self, sourceView: menuBarButton.button)) } } // Delete. func addDeleteAction() { popUpMenu.addAction(PopUpMenuAction(title: String.deleteNoteMenuItem, icon: UIImage(named: "ic_delete")) { _ in self.delegate?.detailViewControllerDidDeleteNote(self.displayPicture) self.navigationController?.popViewController(animated: true) }) } if experimentInteractionOptions.shouldAllowDeletes { addDeleteAction() } popUpMenu.present(from: self, position: .sourceView(menuBarButton.button)) } }
apache-2.0
7e7e020c247e5d308f7a853e0dd48a4f
37.150358
105
0.733312
5.546495
false
false
false
false
yomajkel/RingGraph
RingGraph/RingGraph/Geometry.swift
1
2726
// // Geometry.swift // RingGraph // // Created by Kreft, Michal on 15.04.15. // Copyright (c) 2015 Michał Kreft. All rights reserved. // import UIKit internal let fullCircleRadians = 2.0 * CGFloat(Double.pi) internal let startAngle = -0.25 * fullCircleRadians internal let halfRingAngle = startAngle + CGFloat(Double.pi) internal let shadowEndingAngle = startAngle + fullCircleRadians * 0.93 private let diameterToRingWidthFactor = CGFloat(0.11) private let minDrawableValue = CGFloat(0.00001) internal struct Geometry { let centerPoint: CGPoint let ringWidth: CGFloat private let size: CGSize private let ringGraph: RingGraph private let diameter: CGFloat private let maxRadius: CGFloat init(ringGraph: RingGraph, drawingSize: CGSize) { self.ringGraph = ringGraph size = drawingSize centerPoint = CGPoint(x: drawingSize.width / 2, y: drawingSize.height / 2) diameter = min(drawingSize.width, drawingSize.height) ringWidth = diameter * diameterToRingWidthFactor maxRadius = (diameter - ringWidth) / 2.0 } func framesForDescriptionLabels() -> [CGRect] { var frames = [CGRect]() for (index, _) in ringGraph.meters.enumerated() { let radius = radiusForIndex(index) let origin = CGPoint(x: centerPoint.x - maxRadius, y: centerPoint.y - radius - ringWidth / 2.0) let size = CGSize(width: maxRadius - ringWidth / 1.5, height: ringWidth) frames.append(CGRect(origin: origin, size: size)) } return frames } func frameForDescriptionText() -> CGRect { var frame = CGRect() frame.origin.x = centerPoint.x - size.width * 0.3 frame.origin.y = centerPoint.y - size.height * 0.2 frame.size.width = size.width * 0.6 frame.size.height = size.height * 0.4 return frame } func framesForRingSymbols() -> [CGRect] { var frames = [CGRect]() for (index, _) in ringGraph.meters.enumerated() { let radius = radiusForIndex(index) let width = ringWidth * 0.6 let origin = CGPoint(x: centerPoint.x - width / 2.0, y: centerPoint.y - radius - width / 2.0) let size = CGSize(width: width, height: width) frames.append(CGRect(origin: origin, size: size)) } return frames } func radiusForIndex(_ index: Int) -> CGFloat { return maxRadius - CGFloat(ringWidth + 1) * CGFloat(index) } func angleForValue(_ value: CGFloat) -> CGFloat { return (value > 0.0 ? value : minDrawableValue) * fullCircleRadians + startAngle } }
mit
f9febaf1243eeace13e35e78d0391bce
32.641975
107
0.623486
4.135053
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/MyPresentation/ViewController.swift
1
6125
// // ViewController.swift // MyPresentation // // Created by Chris Mendez on 2/25/16. // Copyright © 2016 Chris Mendez. All rights reserved. // import UIKit import Presentation class ViewController: PresentationController { struct BackgroundImage { let name: String let left: CGFloat let top: CGFloat let speed: CGFloat init(name: String, left: CGFloat, top: CGFloat, speed: CGFloat) { self.name = name self.left = left self.top = top self.speed = speed } func positionAt(index: Int) -> Position? { var position: Position? if index == 0 || speed != 0.0 { let currentLeft = left + CGFloat(index) * speed position = Position(left: currentLeft, top: top) } return position } } lazy var leftButton: UIBarButtonItem = { [unowned self] in let leftButton = UIBarButtonItem( title: "Previous", style: .Plain, target: self, action: "previous") leftButton.setTitleTextAttributes( [NSForegroundColorAttributeName : UIColor.blackColor()], forState: .Normal) return leftButton }() lazy var rightButton: UIBarButtonItem = { [unowned self] in let rightButton = UIBarButtonItem( title: "Next", style: .Plain, target: self, action: "next") rightButton.setTitleTextAttributes( [NSForegroundColorAttributeName : UIColor.blackColor()], forState: .Normal) return rightButton }() override func viewDidLoad() { super.viewDidLoad() setNavigationTitle = false navigationItem.leftBarButtonItem = leftButton navigationItem.rightBarButtonItem = rightButton view.backgroundColor = UIColor.blueColor() configureSlides() configureBackground() } // MARK: - Configuration func configureSlides() { let font = UIFont(name: "HelveticaNeue", size: 34.0)! let color = UIColor.grayColor() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.Center let attributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle] let titles = [ "Parallax is a displacement or difference in the apparent position of an object viewed along two different lines of sight.", "It's measured by the angle or semi-angle of inclination between those two lines.", "The term is derived from the Greek word παράλλαξις (parallaxis), meaning 'alteration'.", "Nearby objects have a larger parallax than more distant objects when observed from different positions.", "http://en.wikipedia.org/wiki/Parallax"].map { title -> Content in let label = UILabel(frame: CGRect(x: 0, y: 0, width: 550, height: 200)) label.numberOfLines = 5 label.attributedText = NSAttributedString(string: title, attributes: attributes) let position = Position(left: 0.7, top: 0.35) return Content(view: label, position: position) } var slides = [SlideController]() for index in 0...4 { let controller = SlideController(contents: [titles[index]]) controller.addAnimations([Content.centerTransitionForSlideContent(titles[index])]) slides.append(controller) } add(slides) } func configureBackground() { let backgroundImages = [ BackgroundImage(name: "Trees", left: 0.0, top: 0.743, speed: -0.3), BackgroundImage(name: "Bus", left: 0.02, top: 0.77, speed: 0.25), BackgroundImage(name: "Truck", left: 1.3, top: 0.73, speed: -1.5), BackgroundImage(name: "Roadlines", left: 0.0, top: 0.79, speed: -0.24), BackgroundImage(name: "Houses", left: 0.0, top: 0.627, speed: -0.16), BackgroundImage(name: "Hills", left: 0.0, top: 0.51, speed: -0.08), BackgroundImage(name: "Mountains", left: 0.0, top: 0.29, speed: 0.0), BackgroundImage(name: "Clouds", left: -0.415, top: 0.14, speed: 0.18), BackgroundImage(name: "Sun", left: 0.8, top: 0.07, speed: 0.0) ] var contents = [Content]() for backgroundImage in backgroundImages { let imageView = UIImageView(image: UIImage(named: backgroundImage.name)) if let position = backgroundImage.positionAt(0) { contents.append(Content(view: imageView, position: position, centered: false)) } } addToBackground(contents) for row in 1...4 { for (column, backgroundImage) in backgroundImages.enumerate() { if let position = backgroundImage.positionAt(row), content = contents.at(column) { addAnimation(TransitionAnimation(content: content, destination: position, duration: 2.0, dumping: 1.0), forPage: row) } } } let groundView = UIView(frame: CGRect(x: 0, y: 0, width: 1024, height: 60)) groundView.backgroundColor = UIColor.redColor() let groundContent = Content(view: groundView, position: Position(left: 0.0, bottom: 0.063), centered: false) contents.append(groundContent) addToBackground([groundContent]) } } extension Array { func at(index: Int?) -> Element? { var object: Element? if let index = index where index >= 0 && index < endIndex { object = self[index] } return object } }
mit
4170ba07d4b21941aa2b336f7bd97c14
33.937143
136
0.56755
4.848533
false
false
false
false
garethknowles/JBDatePicker
JBDatePicker/Classes/JBDatePickerSelectionView.swift
2
3535
// // JBDatePickerSelectionView.swift // JBDatePicker // // Created by Joost van Breukelen on 19-10-16. // Copyright © 2016 Joost van Breukelen. All rights reserved. // import UIKit class JBDatePickerSelectionView: UIView { // MARK: - Computed properties private let padding: CGFloat = 10 private var radius: CGFloat { return (min(frame.height, frame.width) - padding) / 2 } private var circlePath: CGPath { let arcCenter = CGPoint(x: frame.width / 2, y: frame.height / 2) let startAngle = CGFloat(0) let endAngle = CGFloat.pi * 2.0 let clockwise = true let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise).cgPath return path } private var squarePath: CGPath { let pathSize = radius * 2 let center = CGPoint(x: frame.width / 2, y: frame.height / 2) let startPoint = CGPoint(x: center.x - radius, y: center.y - radius) let path = UIBezierPath(rect: CGRect(x: startPoint.x, y: startPoint.y, width: pathSize, height: pathSize)) return path.cgPath } private var roundedRectPath: CGPath { let pathSize = radius * 2 let cornerRadiusForShape = radius / 2 let center = CGPoint(x: frame.width / 2, y: frame.height / 2) let startPoint = CGPoint(x: center.x - radius, y: center.y - radius) let path = UIBezierPath(roundedRect: CGRect(x: startPoint.x, y: startPoint.y, width: pathSize, height: pathSize), cornerRadius: cornerRadiusForShape) return path.cgPath } private var fillColor: UIColor { switch isSemiSelected { case true: return (dayView.datePickerView.delegate?.colorForSemiSelectedSelectionCircle)! case false: switch dayView.isToday { case true: return (dayView.datePickerView.delegate?.colorForSelectionCircleForToday)! case false: return (dayView.datePickerView.delegate?.colorForSelectionCircleForOtherDate)! } } } private var selectionPath: CGPath { guard let delegate = dayView.datePickerView.delegate else { return circlePath } switch delegate.selectionShape { case .circle: return circlePath case .square: return squarePath case .roundedRect: return roundedRectPath } } // MARK: - Stored properties private unowned let dayView: JBDatePickerDayView var isSemiSelected: Bool // MARK: - Initialization init(dayView: JBDatePickerDayView, frame: CGRect, isSemiSelected: Bool) { self.dayView = dayView self.isSemiSelected = isSemiSelected super.init(frame: frame) backgroundColor = .clear shapeLayer().fillColor = fillColor.cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override class var layerClass: AnyClass { return CAShapeLayer.self } private func shapeLayer() -> CAShapeLayer { return layer as! CAShapeLayer } // MARK: - Drawing override func layoutSubviews() { super.layoutSubviews() shapeLayer().path = selectionPath } }
mit
6975bc6711e7628225bb523950377212
27.967213
157
0.602434
4.854396
false
false
false
false
apple/swift-nio-extras
Sources/NIOSOCKS/Messages/ClientGreeting.swift
1
2183
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /// Clients begin the SOCKS handshake process /// by providing an array of suggested authentication /// methods. public struct ClientGreeting: Hashable, Sendable { /// The protocol version. public let version: UInt8 = 5 /// The client-supported authentication methods. /// The SOCKS server will select one to use. public var methods: [AuthenticationMethod] /// Creates a new ``ClientGreeting`` /// - parameter methods: The client-supported authentication methods. public init(methods: [AuthenticationMethod]) { self.methods = methods } } extension ByteBuffer { mutating func readClientGreeting() throws -> ClientGreeting? { return try self.parseUnwindingIfNeeded { buffer in guard try buffer.readAndValidateProtocolVersion() != nil, let numMethods = buffer.readInteger(as: UInt8.self), buffer.readableBytes >= numMethods else { return nil } // safe to bang as we've already checked the buffer size let methods = buffer.readBytes(length: Int(numMethods))!.map { AuthenticationMethod(value: $0) } return .init(methods: methods) } } @discardableResult mutating func writeClientGreeting(_ greeting: ClientGreeting) -> Int { var written = 0 written += self.writeInteger(greeting.version) written += self.writeInteger(UInt8(greeting.methods.count)) for method in greeting.methods { written += self.writeInteger(method.value) } return written } }
apache-2.0
f0fbb8bb53a49e9d98e00306074b0d7a
32.075758
108
0.591846
5.247596
false
false
false
false
duke-compsci408-fall2014/Pawns
BayAreaChess/BayAreaChess/FrostedSidebar.swift
1
18267
// // FrostedSidebar.swift // CustomStuff // // Created by Evan Dekhayser on 7/9/14. // Copyright (c) 2014 Evan Dekhayser. All rights reserved. // import UIKit import QuartzCore public protocol FrostedSidebarDelegate{ func sidebar(sidebar: FrostedSidebar, willShowOnScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didShowOnScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, willDismissFromScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didDismissFromScreenAnimated animated: Bool) func sidebar(sidebar: FrostedSidebar, didTapItemAtIndex index: Int) func sidebar(sidebar: FrostedSidebar, didEnable itemEnabled: Bool, itemAtIndex index: Int) } var sharedSidebar: FrostedSidebar? public class FrostedSidebar: UIViewController { //MARK: Public Properties public var width: CGFloat = 110.0 public var showFromRight: Bool = false public var animationDuration: CGFloat = 0.25 public var itemSize: CGSize = CGSize(width: 70.0, height: 70.0) public var tintColor: UIColor = UIColor(white: 0.2, alpha: 0.73) public var itemBackgroundColor: UIColor = UIColor(white: 1, alpha: 0.25) public var borderWidth: CGFloat = 2 public var delegate: FrostedSidebarDelegate? = nil public var actionForIndex: [Int : ()->()] = [:] public var selectedIndices: NSMutableIndexSet = NSMutableIndexSet() //Only one of these properties can be used at a time. If one is true, the other automatically is false public var isSingleSelect: Bool = false{ didSet{ if isSingleSelect{ calloutsAlwaysSelected = false } } } public var calloutsAlwaysSelected: Bool = false{ didSet{ if calloutsAlwaysSelected{ isSingleSelect = false selectedIndices = NSMutableIndexSet(indexesInRange: NSRange(location: 0,length: images.count) ) } } } //MARK: Private Properties private var contentView: UIScrollView = UIScrollView() private var blurView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) private var dimView: UIView = UIView() private var tapGesture: UITapGestureRecognizer? = nil private var images: [UIImage] = [] private var borderColors: [UIColor]? = nil private var itemViews: [CalloutItem] = [] //MARK: Public Methods required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(itemImages: [UIImage], colors: [UIColor]?, selectedItemIndices: NSIndexSet?){ contentView.alwaysBounceHorizontal = false contentView.alwaysBounceVertical = true contentView.bounces = true contentView.clipsToBounds = false contentView.showsHorizontalScrollIndicator = false contentView.showsVerticalScrollIndicator = false if colors != nil{ assert(itemImages.count == colors!.count, "If item color are supplied, the itemImages and colors arrays must be of the same size.") } selectedIndices = selectedItemIndices != nil ? NSMutableIndexSet(indexSet: selectedItemIndices!) : NSMutableIndexSet() borderColors = colors images = itemImages for (index, image) in enumerate(images){ let view = CalloutItem(index: index) view.clipsToBounds = true view.imageView.image = image contentView.addSubview(view) itemViews += [view] if borderColors != nil{ if selectedIndices.containsIndex(index){ let color = borderColors![index] view.layer.borderColor = color.CGColor } } else{ view.layer.borderColor = UIColor.clearColor().CGColor } } super.init(nibName: nil, bundle: nil) } public override func loadView() { super.loadView() view.backgroundColor = UIColor.clearColor() view.addSubview(dimView) view.addSubview(blurView) view.addSubview(contentView) tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") view.addGestureRecognizer(tapGesture!) } public override func shouldAutorotate() -> Bool { return true } public override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.All.rawValue); } public override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration) if isViewLoaded(){ dismissAnimated(false, completion: nil) } } public func showInViewController(viewController: UIViewController, animated: Bool){ if let bar = sharedSidebar{ bar.dismissAnimated(false, completion: nil) } delegate?.sidebar(self, willShowOnScreenAnimated: animated) sharedSidebar = self addToParentViewController(viewController, callingAppearanceMethods: true) view.frame = viewController.view.bounds dimView.backgroundColor = UIColor.blackColor() dimView.alpha = 0 dimView.frame = view.bounds let parentWidth = view.bounds.size.width var contentFrame = view.bounds contentFrame.origin.x = showFromRight ? parentWidth : -width contentFrame.size.width = width contentView.frame = contentFrame contentView.contentOffset = CGPoint(x: 0, y: 0) layoutItems() var blurFrame = CGRect(x: showFromRight ? view.bounds.size.width : 0, y: 0, width: 0, height: view.bounds.size.height) blurView.frame = blurFrame blurView.contentMode = showFromRight ? UIViewContentMode.TopRight : UIViewContentMode.TopLeft blurView.clipsToBounds = true view.insertSubview(blurView, belowSubview: contentView) contentFrame.origin.x = showFromRight ? parentWidth - width : 0 blurFrame.origin.x = contentFrame.origin.x blurFrame.size.width = width let animations: () -> () = { self.contentView.frame = contentFrame self.blurView.frame = blurFrame self.dimView.alpha = 0.25 } let completion: (Bool) -> Void = { finished in if finished{ self.delegate?.sidebar(self, didShowOnScreenAnimated: animated) } } if animated{ UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.allZeros, animations: animations, completion: completion); } else{ animations() completion(true) } for (index, item) in enumerate(itemViews){ item.layer.transform = CATransform3DMakeScale(0.3, 0.3, 1) item.alpha = 0 item.originalBackgroundColor = itemBackgroundColor item.layer.borderWidth = borderWidth animateSpringWithView(item, idx: index, initDelay: animationDuration) } } public func dismissAnimated(animated: Bool, completion: ((Bool) -> Void)?){ let completionBlock: (Bool) -> Void = {finished in self.removeFromParentViewControllerCallingAppearanceMethods(true) self.delegate?.sidebar(self, didDismissFromScreenAnimated: true) self.layoutItems() if completion != nil{ completion!(finished) } } delegate?.sidebar(self, willDismissFromScreenAnimated: animated) if animated{ let parentWidth = view.bounds.size.width var contentFrame = contentView.frame contentFrame.origin.x = showFromRight ? parentWidth : -width var blurFrame = blurView.frame blurFrame.origin.x = showFromRight ? parentWidth : 0 blurFrame.size.width = 0 UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.contentView.frame = contentFrame self.blurView.frame = blurFrame self.dimView.alpha = 0 }, completion: completionBlock) } else{ completionBlock(true) } } //MARK: Private Classes private class CalloutItem: UIView{ var imageView: UIImageView = UIImageView() var itemIndex: Int var originalBackgroundColor:UIColor? { didSet{ self.backgroundColor = originalBackgroundColor } } required init(coder aDecoder: NSCoder) { self.itemIndex = 0 super.init(coder: aDecoder) } init(index: Int){ imageView.backgroundColor = UIColor.clearColor() imageView.contentMode = UIViewContentMode.ScaleAspectFit itemIndex = index super.init(frame: CGRect.zeroRect) addSubview(imageView) } override func layoutSubviews() { super.layoutSubviews() let inset: CGFloat = bounds.size.height/2 imageView.frame = CGRect(x: 0, y: 0, width: inset, height: inset) imageView.center = CGPoint(x: inset, y: inset) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 let darkenFactor: CGFloat = 0.3 var darkerColor: UIColor if originalBackgroundColor != nil && originalBackgroundColor!.getRed(&r, green: &g, blue: &b, alpha: &a){ darkerColor = UIColor(red: max(r - darkenFactor, 0), green: max(g - darkenFactor, 0), blue: max(b - darkenFactor, 0), alpha: a) } else if originalBackgroundColor != nil && originalBackgroundColor!.getWhite(&r, alpha: &a){ darkerColor = UIColor(white: max(r - darkenFactor, 0), alpha: a) } else{ darkerColor = UIColor.clearColor() assert(false, "Item color should be RBG of White/Alpha in order to darken the button") } backgroundColor = darkerColor } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { super.touchesEnded(touches, withEvent: event) backgroundColor = originalBackgroundColor } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) backgroundColor = originalBackgroundColor } } //MARK: Private Methods private func animateSpringWithView(view: CalloutItem, idx: Int, initDelay: CGFloat){ let delay: NSTimeInterval = NSTimeInterval(initDelay) + NSTimeInterval(idx) * 0.1 UIView.animateWithDuration(0.5, delay: delay, usingSpringWithDamping: 10.0, initialSpringVelocity: 50.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { view.layer.transform = CATransform3DIdentity view.alpha = 1 }, completion: nil) } @objc private func handleTap(recognizer: UITapGestureRecognizer){ let location = recognizer.locationInView(view) if !CGRectContainsPoint(contentView.frame, location){ dismissAnimated(true, completion: nil) } else{ let tapIndex = indexOfTap(recognizer.locationInView(contentView)) if tapIndex != nil{ didTapItemAtIndex(tapIndex!) } } } private func didTapItemAtIndex(index: Int){ let didEnable = !selectedIndices.containsIndex(index) if borderColors != nil{ let stroke = borderColors![index] let item = itemViews[index] if didEnable{ if isSingleSelect{ selectedIndices.removeAllIndexes() for (index, item) in enumerate(itemViews){ item.layer.borderColor = UIColor.clearColor().CGColor } } item.layer.borderColor = stroke.CGColor var borderAnimation = CABasicAnimation(keyPath: "borderColor") borderAnimation.fromValue = UIColor.clearColor().CGColor borderAnimation.toValue = stroke.CGColor borderAnimation.duration = 0.5 item.layer.addAnimation(borderAnimation, forKey: nil) selectedIndices.addIndex(index) } else{ if !isSingleSelect{ if !calloutsAlwaysSelected{ item.layer.borderColor = UIColor.clearColor().CGColor selectedIndices.removeIndex(index) } } } let pathFrame = CGRect(x: -CGRectGetMidX(item.bounds), y: -CGRectGetMidY(item.bounds), width: item.bounds.size.width, height: item.bounds.size.height) let path = UIBezierPath(roundedRect: pathFrame, cornerRadius: item.layer.cornerRadius) let shapePosition = view.convertPoint(item.center, fromView: contentView) let circleShape = CAShapeLayer() circleShape.path = path.CGPath circleShape.position = shapePosition circleShape.fillColor = UIColor.clearColor().CGColor circleShape.opacity = 0 circleShape.strokeColor = stroke.CGColor circleShape.lineWidth = borderWidth view.layer.addSublayer(circleShape) let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = NSValue(CATransform3D: CATransform3DIdentity) scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2.5, 2.5, 1)) let alphaAnimation = CABasicAnimation(keyPath: "opacity") alphaAnimation.fromValue = 1 alphaAnimation.toValue = 0 let animation = CAAnimationGroup() animation.animations = [scaleAnimation, alphaAnimation] animation.duration = 0.5 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) circleShape.addAnimation(animation, forKey: nil) } if let action = actionForIndex[index]{ action() } delegate?.sidebar(self, didTapItemAtIndex: index) delegate?.sidebar(self, didEnable: didEnable, itemAtIndex: index) } private func layoutSubviews(){ let x = showFromRight ? parentViewController!.view.bounds.size.width - width : 0 contentView.frame = CGRect(x: x, y: 0, width: width, height: parentViewController!.view.bounds.size.height) blurView.frame = contentView.frame layoutItems() } private func layoutItems(){ let leftPadding: CGFloat = (width - itemSize.width) / 2 let topPadding: CGFloat = leftPadding+20 for (index, item) in enumerate(itemViews){ let idx: CGFloat = CGFloat(index) let frame = CGRect(x: leftPadding, y: topPadding*idx + itemSize.height*idx + topPadding, width:itemSize.width, height: itemSize.height) item.frame = frame item.layer.cornerRadius = frame.size.width / 2 item.layer.borderColor = UIColor.clearColor().CGColor item.alpha = 0 if selectedIndices.containsIndex(index){ if borderColors != nil{ item.layer.borderColor = borderColors![index].CGColor } } } let itemCount = CGFloat(itemViews.count) contentView.contentSize = CGSizeMake(0, itemCount * (itemSize.height + topPadding) + topPadding) } private func indexOfTap(location: CGPoint) -> Int? { var index: Int? for (idx, item) in enumerate(itemViews){ if CGRectContainsPoint(item.frame, location){ index = idx break } } return index } private func addToParentViewController(viewController: UIViewController, callingAppearanceMethods: Bool){ if (parentViewController != nil){ removeFromParentViewControllerCallingAppearanceMethods(callingAppearanceMethods) } if callingAppearanceMethods{ beginAppearanceTransition(true, animated: false) } viewController.addChildViewController(self) viewController.view.addSubview(self.view) didMoveToParentViewController(self) if callingAppearanceMethods{ endAppearanceTransition() } } private func removeFromParentViewControllerCallingAppearanceMethods(callAppearanceMethods: Bool){ if callAppearanceMethods{ beginAppearanceTransition(false, animated: false) } willMoveToParentViewController(nil) view.removeFromSuperview() removeFromParentViewController() if callAppearanceMethods{ endAppearanceTransition() } } }
mit
5941e81f1a8280eff0a6f0a8da403c62
41.483721
174
0.602836
5.565814
false
false
false
false
PasDeChocolat/LearningSwift
PLAYGROUNDS/APPLE/Balloons.playground/section-15.swift
2
411
let wait = SKAction.waitForDuration(1.0, withRange: 0.05) let pause = SKAction.waitForDuration(0.55, withRange: 0.05) let left = SKAction.runBlock { fireCannon(leftBalloonCannon) } let right = SKAction.runBlock { fireCannon(rightBalloonCannon) } let leftFire = SKAction.sequence([wait, left, pause, left, pause, left, wait]) let rightFire = SKAction.sequence([pause, right, pause, right, pause, right, wait])
gpl-3.0
8fdad111dd4105f3e80a4862c0bd6661
50.375
83
0.756691
3.543103
false
false
false
false
alobanov/ALFormBuilder
Sources/FormBuilder/Vendors/extension/String+Common.swift
1
1865
import UIKit extension String { // func contains(find: String) -> Bool { // return self.range(of: find) != nil // } static let numberFormatter: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.decimalSeparator = "." return numberFormatter }() func replace(string:String, replacement:String) -> String { return self.replacingOccurrences(of: string, with: replacement, options: String.CompareOptions.literal, range: nil) } func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } func removeAllWhitespace() -> String { return self.replace(string: " ", replacement: "") } var strToInt: Int? { return String.numberFormatter.number(from: self)?.intValue } var strToFloat: Float? { return String.numberFormatter.number(from: self)?.floatValue } func strToBool() -> Bool { switch self { case "1": return true case "true": return true default: return false } } var capitalizeFirst: String { if isEmpty { return "" } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).uppercased()) return result } var lowercaseFirst: String { if isEmpty { return "" } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) return result } subscript (i: Int) -> Character { return self[index(startIndex, offsetBy: i)] } subscript (i: Int) -> String { if self.isEmpty { return "" } else { return String(self[i] as Character) } } subscript (r: Range<Int>) -> String { let start = index(startIndex, offsetBy: r.lowerBound) let end = index(startIndex, offsetBy: r.upperBound) return String(self[Range(start ..< end)]) } }
mit
76d7055e5dee3716c518293f37c940de
24.547945
119
0.653619
4.277523
false
false
false
false
xxxAIRINxxx/ViewPagerController
Proj/Demo/DetailViewController.swift
1
1816
// // DetailViewController.swift // Demo // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import UIKit final class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { weak var parentController : UIViewController? @IBOutlet weak var tableView : UITableView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("DetailViewController viewWillAppear - " + self.title!) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("DetailViewController viewWillDisappear - " + self.title!) } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 40 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = self.title return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController controller.view.clipsToBounds = true controller.title = "pushed " + self.title! self.parentController?.navigationController?.pushViewController(controller, animated: true) } }
mit
80f188b5767d9b108ca4b1024ac63671
32
126
0.684298
5.550459
false
false
false
false
petrone/PetroneAPI_swift
PetroneAPI/Packets/PetronePacketLedMode2.swift
1
1509
// // PetronePacketLedMode2.swift // Petrone // // Created by Byrobot on 2017. 8. 8.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation class PetronePacketLedMode2 : PetronePacket { public var led1:PetroneLedModeBase = PetroneLedModeBase() public var led2:PetroneLedModeBase = PetroneLedModeBase() override init() { super.init() size = 6 } override func getBluetoothData() -> Data { var sendArray = Data() sendArray.append(PetroneDataType.LedMode2.rawValue) sendArray.append(led1.mode) sendArray.append(led1.color) sendArray.append(led1.interval) sendArray.append(led2.mode) sendArray.append(led2.color) sendArray.append(led2.interval) return sendArray } override func getSerialData() -> Data { var baseArray = Data() baseArray.append(PetroneDataType.LedMode2.rawValue) baseArray.append(UInt8(size)) baseArray.append(led1.mode) baseArray.append(led1.color) baseArray.append(led1.interval) baseArray.append(led2.mode) baseArray.append(led2.color) baseArray.append(led2.interval) var sendArray = Data() sendArray.append(UInt8(0x0a)) sendArray.append(UInt8(0x55)) sendArray.append(baseArray) sendArray.append(contentsOf: PetroneCRC.getCRC(data: baseArray, dataLength: size+2)) return sendArray } }
mit
834323ab178219dcabd93da0fc9ff9ab
27.415094
92
0.641434
3.65534
false
false
false
false
Railsreactor/json-data-sync-swift
JDSKit/Core/SyncService.swift
1
7288
// // SyncService.swift // JDSKit // // Created by Igor Reshetnikov on 3/1/16. // Copyright © 2016 RailsReactor. All rights reserved. // import Foundation import PromiseKit import CocoaLumberjack //import When public enum SyncError: Error { case checkForUpdates(Date) } public typealias SyncInfo = [String] private let ZeroDate = Date(timeIntervalSince1970: 0) private let EventKey = String(describing: Event.self) open class AbstractSyncService: CoreService { open var liteSyncEnabled = false // *************************** Override ******************************* // if you want to split some update info between different users or something... open func filterIDForEntityKey(_ key: String) -> String? { return nil } open func shouldSyncEntityOfType(_ managedEntityKey: String, lastUpdateDate: Date?) -> Bool { return true } // ************************************************************************* open var lastSyncDate = ZeroDate open var lastSuccessSyncDate = ZeroDate open lazy var updateInfoGateway: UpdateInfoGateway = { return UpdateInfoGateway(self.localManager) } () internal func entitiesToSync() -> [String] { let extracted = ExtractAllReps(CDManagedEntity.self) return extracted.flatMap { let name = ($0 as! CDManagedEntity.Type).entityName if name == "ManagedEntity" { return nil } return name } } internal func checkForUpdates(_ eventSyncDate: Date) -> Promise<SyncInfo> { DDLogDebug("Checking for updates... \(eventSyncDate)") let systemDate = eventSyncDate.toSystemString() let predicate = NSComparisonPredicate(format: "created_at_gt == %@", optionals: [systemDate]); return self.remoteManager.loadEntities(Event.self, filters: [predicate], include: nil, fields: liteSyncEnabled ? ["relatedEntityName", "relatedEntityId", "action"] : nil).thenInBGContext { (events: [Event]) -> SyncInfo in var itemsToSync = Set<String>() let requiredItems = Set(self.entitiesToSync()) for event in events { guard let entityName = event.relatedEntityName else { continue } if let date = event.updateDate, self.lastSyncDate.compare(date) == ComparisonResult.orderedAscending { self.lastSyncDate = date } if let id = event.relatedEntityId, event.action == Action.Deleted { do { try AbstractRegistryService.mainRegistryService.entityServiceByKey(entityName).entityGateway()?.deleteEntityWithID(id) DDLogDebug("Deleted \(entityName) with id: \(id)") } catch { } } else if requiredItems.contains(entityName) { if !itemsToSync.contains(entityName) { DDLogDebug("Will sync: \(entityName)...") } itemsToSync.insert(event.relatedEntityName!) } } return Array(itemsToSync) } } internal func syncInternal() -> Promise<Void> { return self.runOnBackgroundContext { () -> SyncInfo in if let eventSyncInfo = try self.updateInfoGateway.updateInfoForKey(EventKey, filterID: self.filterIDForEntityKey(EventKey)) { throw SyncError.checkForUpdates(eventSyncInfo.updateDate!) } else { DDLogDebug("Going to sync at first time...") return self.entitiesToSync() } }.recover(on: .global()) { error -> Promise<SyncInfo> in switch error { case SyncError.checkForUpdates(let syncInfo): return self.checkForUpdates(syncInfo) default: throw error } }.thenInBGContext { updateEntitiesKeys -> [Promise<Date>] in var syncPromises = [Promise<Date>]() for entityKey in updateEntitiesKeys { let service = AbstractRegistryService.mainRegistryService.entityServiceByKey(entityKey) let filter = self.filterIDForEntityKey(entityKey) let syncDate = try self.updateInfoGateway.updateInfoForKey(entityKey, filterID: filter)?.updateDate ?? ZeroDate if !self.shouldSyncEntityOfType(entityKey, lastUpdateDate: syncDate) { continue } let syncPromise = service.syncEntityDelta(syncDate).thenInBGContext { _ -> Date in let updateInfo: CDUpdateInfo = try self.updateInfoGateway.updateInfoForKey(entityKey, filterID: filter, createIfNeed: true)! var finalSyncDate = ZeroDate if self.lastSyncDate == ZeroDate { let topMostEntity: ManagedEntity? = try service.entityGateway()?.fetchEntities(nil, sortDescriptors: ["-updateDate"].sortDescriptors()).first finalSyncDate = topMostEntity?.updateDate ?? syncDate } else { finalSyncDate = self.lastSyncDate } updateInfo.updateDate = finalSyncDate return finalSyncDate } syncPromises.append(syncPromise) } return syncPromises }.then(on: .global()) { promises in return when(fulfilled: promises) }.thenInBGContext { dates -> Void in let eventSyncInfo = try self.updateInfoGateway.updateInfoForKey(EventKey, filterID: self.filterIDForEntityKey(EventKey), createIfNeed: true) if let eventSync = eventSyncInfo?.updateDate { if self.lastSyncDate == ZeroDate { var latestDate = ZeroDate dates.forEach { if latestDate.compare($0) == ComparisonResult.orderedAscending { latestDate = $0 } } self.lastSyncDate = latestDate.timeIntervalSince1970 > eventSync.timeIntervalSince1970 ? latestDate : eventSync } } self.lastSuccessSyncDate = self.lastSyncDate eventSyncInfo?.updateDate = self.lastSyncDate }.recover(on: .global()) { error -> Void in self.localManager.saveSyncSafe() throw error }.then(on: .global()) { self.localManager.saveSyncSafe() } // .always(on: .global()) { // self.localManager.saveSyncSafe() // } } open func sync() -> Promise<Void> { return DispatchQueue.global().promise {}.then(on: .global()) { _ in if self.trySync() { return self.syncInternal().always { self.endSync() } } else { self.waitForSync() return Promise(value:()) } } } }
mit
ffc927553e5e8f8359a0af547f32a058
39.709497
229
0.553451
5.219914
false
false
false
false
willlarche/material-components-ios
components/TextFields/examples/TextFieldManualLayoutLegacyExample.swift
2
11307
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length import MaterialComponents.MaterialTextFields final class TextFieldManualLayoutLegacySwiftExample: UIViewController { private enum LayoutConstants { static let largeMargin: CGFloat = 16 static let smallMargin: CGFloat = 8 static let floatingHeight: CGFloat = 84 static let defaultHeight: CGFloat = 62 static let stateWidth: CGFloat = 80 } let scrollView = UIScrollView() let name: MDCTextField = { let name = MDCTextField() name.autocapitalizationType = .words return name }() let address: MDCTextField = { let address = MDCTextField() address.autocapitalizationType = .words return address }() let city: MDCTextField = { let city = MDCTextField() city.autocapitalizationType = .words return city }() let cityController: MDCTextInputControllerLegacyDefault let state: MDCTextField = { let state = MDCTextField() state.autocapitalizationType = .allCharacters return state }() let zip: MDCTextField = { let zip = MDCTextField() return zip }() let zipController: MDCTextInputControllerLegacyDefault let phone: MDCTextField = { let phone = MDCTextField() return phone }() let stateZip = UIView() var allTextFieldControllers = [MDCTextInputControllerLegacyDefault]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { cityController = MDCTextInputControllerLegacyDefault(textInput: city) zipController = MDCTextInputControllerLegacyDefault(textInput: zip) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white:0.97, alpha: 1.0) title = "Legacy Manual Text Fields" setupScrollView() setupTextFields() updateLayout() registerKeyboardNotifications() addGestureRecognizer() let styleButton = UIBarButtonItem(title: "Style", style: .plain, target: self, action: #selector(buttonDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = styleButton } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scrollView.frame = view.bounds } func setupTextFields() { scrollView.addSubview(name) let nameController = MDCTextInputControllerLegacyDefault(textInput: name) name.delegate = self nameController.placeholderText = "Name" allTextFieldControllers.append(nameController) scrollView.addSubview(address) let addressController = MDCTextInputControllerLegacyDefault(textInput: address) address.delegate = self addressController.placeholderText = "Address" allTextFieldControllers.append(addressController) scrollView.addSubview(city) city.delegate = self cityController.placeholderText = "City" allTextFieldControllers.append(cityController) scrollView.addSubview(stateZip) stateZip.addSubview(state) let stateController = MDCTextInputControllerLegacyDefault(textInput: state) state.delegate = self stateController.placeholderText = "State" allTextFieldControllers.append(stateController) stateZip.addSubview(zip) zip.delegate = self zipController.placeholderText = "Zip Code" zipController.helperText = "XXXXX" allTextFieldControllers.append(zipController) scrollView.addSubview(phone) let phoneController = MDCTextInputControllerLegacyDefault(textInput: phone) phone.delegate = self phoneController.placeholderText = "Phone Number" allTextFieldControllers.append(phoneController) var tag = 0 for controller in allTextFieldControllers { guard let textField = controller.textInput as? MDCTextField else { continue } textField.tag = tag tag += 1 } } func setupScrollView() { view.addSubview(scrollView) scrollView.contentSize = CGSize(width: scrollView.bounds.width - 2 * LayoutConstants.largeMargin, height: 500.0) } func addGestureRecognizer() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDidTouch(sender: ))) self.scrollView.addGestureRecognizer(tapRecognizer) } func updateLayout() { let commonWidth = view.bounds.width - 2 * LayoutConstants.largeMargin var height = LayoutConstants.floatingHeight if let controller = allTextFieldControllers.first { height = controller.isFloatingEnabled ? LayoutConstants.floatingHeight : LayoutConstants.defaultHeight } name.frame = CGRect(x: LayoutConstants.largeMargin, y: LayoutConstants.smallMargin, width: commonWidth, height: height) address.frame = CGRect(x: LayoutConstants.largeMargin, y: name.frame.minY + height + LayoutConstants.smallMargin, width: commonWidth, height: height) city.frame = CGRect(x: LayoutConstants.largeMargin, y: address.frame.minY + height + LayoutConstants.smallMargin, width: commonWidth, height: height) stateZip.frame = CGRect(x: LayoutConstants.largeMargin, y: city.frame.minY + height + LayoutConstants.smallMargin, width: commonWidth, height: height) state.frame = CGRect(x: 0, y: 0, width: LayoutConstants.stateWidth, height: height) zip.frame = CGRect(x: LayoutConstants.stateWidth + LayoutConstants.smallMargin, y: 0, width: stateZip.bounds.width - LayoutConstants.stateWidth - LayoutConstants.smallMargin, height: height) phone.frame = CGRect(x: LayoutConstants.largeMargin, y: stateZip.frame.minY + height + LayoutConstants.smallMargin, width: commonWidth, height: height) } // MARK: - Actions @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } @objc func buttonDidTouch(sender: Any) { let alert = UIAlertController(title: "Floating Enabled", message: nil, preferredStyle: .actionSheet) let defaultAction = UIAlertAction(title: "Default (Yes)", style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = true }) self.updateLayout() } alert.addAction(defaultAction) let floatingAction = UIAlertAction(title: "No", style: .default) { _ in self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = false }) self.updateLayout() } alert.addAction(floatingAction) present(alert, animated: true, completion: nil) } } extension TextFieldManualLayoutLegacySwiftExample: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let rawText = textField.text else { return true } let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string) if textField == zip { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters), fullString[range].characters.count > 0 { zipController.setErrorText("Error: Zip can only contain numbers", errorAccessibilityValue: nil) } else if fullString.characters.count > 5 { zipController.setErrorText("Error: Zip can only contain five digits", errorAccessibilityValue: nil) } else { zipController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == city { if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits), fullString[range].characters.count > 0 { cityController.setErrorText("Error: City can only contain letters", errorAccessibilityValue: nil) } else { cityController.setErrorText(nil, errorAccessibilityValue: nil) } } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let index = textField.tag if index + 1 < allTextFieldControllers.count, let nextField = allTextFieldControllers[index + 1].textInput { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } } // MARK: - Keyboard Handling extension TextFieldManualLayoutLegacySwiftExample { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: .UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: frame.height, right: 0.0) } @objc func keyboardWillHide(notif: Notification) { scrollView.contentInset = UIEdgeInsets() } } // MARK: - Status Bar Style extension TextFieldManualLayoutLegacySwiftExample { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } // MARK: - CatalogByConvention extension TextFieldManualLayoutLegacySwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Text Field", "[Legacy] Manual Layout"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } }
apache-2.0
73d51e27977cff86c2577417884dae68
31.398281
91
0.660476
5.384286
false
false
false
false
OscarSwanros/swift
test/ClangImporter/MixedSource/broken-bridging-header.swift
14
1981
// RUN: %empty-directory(%t) // RUN: not %target-swift-frontend -typecheck %S/../../Inputs/empty.swift -import-objc-header %t/fake.h 2>&1 | %FileCheck -check-prefix=MISSING-HEADER %s // RUN: cp %S/Inputs/error-on-define.h %t // RUN: not %target-swift-frontend -typecheck %S/../../Inputs/empty.swift -import-objc-header %t/error-on-define.h 2>&1 | %FileCheck -check-prefix=MISSING-OTHER-HEADER %s // RUN: cp %S/Inputs/error-on-define-impl.h %t // RUN: not %target-swift-frontend -typecheck %S/../../Inputs/empty.swift -import-objc-header %t/error-on-define.h -Xcc -DERROR 2>&1 | %FileCheck -check-prefix=HEADER-ERROR %s // RUN: %target-swift-frontend -emit-module -o %t -module-name HasBridgingHeader %S/../../Inputs/empty.swift -import-objc-header %t/error-on-define.h // RUN: %target-swift-frontend -typecheck %s -I %t -Xcc -DERROR -verify -show-diagnostics-after-fatal // RUN: not %target-swift-frontend -typecheck %s -I %t -Xcc -DERROR 2>&1 | %FileCheck -check-prefix=HEADER-ERROR %s // RUN: rm %t/error-on-define-impl.h // RUN: %target-swift-frontend -typecheck %s -I %t -verify -show-diagnostics-after-fatal // RUN: not %target-swift-frontend -typecheck %s -I %t 2>&1 | %FileCheck -check-prefix=MISSING-OTHER-HEADER %s // REQUIRES: objc_interop import HasBridgingHeader // expected-error {{failed to import bridging header}} expected-error {{failed to load module 'HasBridgingHeader'}} // MISSING-HEADER: error: bridging header '{{.*}}/fake.h' does not exist // MISSING-HEADER-NOT: error: // MISSING-OTHER-HEADER: error: 'error-on-define-impl.h' file not found // MISSING-OTHER-HEADER-NOT: error: // MISSING-OTHER-HEADER: error: failed to import bridging header '{{.*}}/error-on-define.h' // MISSING-OTHER-HEADER-NOT: error: // HEADER-ERROR: error: "badness" // HEADER-ERROR-NOT: error: // HEADER-ERROR: error: failed to import bridging header '{{.*}}/error-on-define.h' // HEADER-ERROR-NOT: error: let _ = x // expected-error {{use of unresolved identifier 'x'}}
apache-2.0
0e77d5fe8c5608ea430ff989c05e62d7
52.540541
175
0.704695
3.105016
false
false
false
false
kinetic-fit/sensors-swift
Sources/SwiftySensors/Sensor.swift
1
10173
// // Sensor.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import CoreBluetooth import Signals /** Sensor wraps a CoreBluetooth Peripheral and manages the hierarchy of Services and Characteristics. */ open class Sensor: NSObject { // Internal Constructor. SensorManager manages the instantiation and destruction of Sensor objects /// :nodoc: required public init(peripheral: CBPeripheral, advertisements: [CBUUID] = []) { self.peripheral = peripheral self.advertisements = advertisements super.init() peripheral.delegate = self peripheral.addObserver(self, forKeyPath: "state", options: [.new, .old], context: &myContext) } deinit { peripheral.removeObserver(self, forKeyPath: "state") peripheral.delegate = nil rssiPingTimer?.invalidate() } /// Backing CoreBluetooth Peripheral public let peripheral: CBPeripheral /// Discovered Services public fileprivate(set) var services = Dictionary<String, Service>() /// Advertised UUIDs public let advertisements: [CBUUID] /// Raw Advertisement Data public internal(set) var advertisementData: [String: Any]? { didSet { onAdvertisementDataUpdated => advertisementData } } /// Advertisement Data Changed Signal public let onAdvertisementDataUpdated = Signal<([String: Any]?)>() /// Name Changed Signal public let onNameChanged = Signal<Sensor>() /// State Changed Signal public let onStateChanged = Signal<Sensor>() /// Service Discovered Signal public let onServiceDiscovered = Signal<(Sensor, Service)>() /// Service Features Identified Signal public let onServiceFeaturesIdentified = Signal<(Sensor, Service)>() /// Characteristic Discovered Signal public let onCharacteristicDiscovered = Signal<(Sensor, Characteristic)>() /// Characteristic Value Updated Signal public let onCharacteristicValueUpdated = Signal<(Sensor, Characteristic)>() /// Characteristic Value Written Signal public let onCharacteristicValueWritten = Signal<(Sensor, Characteristic)>() /// RSSI Changed Signal public let onRSSIChanged = Signal<(Sensor, Int)>() /// Most recent RSSI value public internal(set) var rssi: Int = Int.min { didSet { onRSSIChanged => (self, rssi) } } /// Last time of Sensor Communication with the Sensor Manager (Time Interval since Reference Date) public fileprivate(set) var lastSensorActivity = Date.timeIntervalSinceReferenceDate /** Get a service by its UUID or by Type - parameter uuid: UUID string - returns: Service */ public func service<T: Service>(_ uuid: String? = nil) -> T? { if let uuid = uuid { return services[uuid] as? T } for service in services.values { if let s = service as? T { return s } } return nil } /** Check if a Sensor advertised a specific UUID Service - parameter uuid: UUID string - returns: `true` if the sensor advertised the `uuid` service */ open func advertisedService(_ uuid: String) -> Bool { let service = CBUUID(string: uuid) for advertisement in advertisements { if advertisement.isEqual(service) { return true } } return false } ////////////////////////////////////////////////////////////////// // Private / Internal Classes, Properties and Constants ////////////////////////////////////////////////////////////////// internal weak var serviceFactory: SensorManager.ServiceFactory? private var rssiPingTimer: Timer? private var myContext = 0 /// :nodoc: override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &myContext { if keyPath == "state" { peripheralStateChanged() } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } fileprivate var rssiPingEnabled: Bool = false { didSet { if rssiPingEnabled { if rssiPingTimer == nil { rssiPingTimer = Timer.scheduledTimer(timeInterval: SensorManager.RSSIPingInterval, target: self, selector: #selector(Sensor.rssiPingTimerHandler), userInfo: nil, repeats: true) } } else { rssi = Int.min rssiPingTimer?.invalidate() rssiPingTimer = nil } } } } // Private Funtions extension Sensor { fileprivate func peripheralStateChanged() { switch peripheral.state { case .connected: rssiPingEnabled = true case .connecting: break case .disconnected: fallthrough default: rssiPingEnabled = false services.removeAll() } SensorManager.logSensorMessage?("Sensor: peripheralStateChanged: \(peripheral.state.rawValue)") onStateChanged => self } fileprivate func serviceDiscovered(_ cbs: CBService) { if let service = services[cbs.uuid.uuidString], service.cbService == cbs { return } if let ServiceType = serviceFactory?.serviceTypes[cbs.uuid.uuidString] { let service = ServiceType.init(sensor: self, cbs: cbs) services[cbs.uuid.uuidString] = service onServiceDiscovered => (self, service) SensorManager.logSensorMessage?("Sensor: Service Created: \(service)") if let sp = service as? ServiceProtocol { let charUUIDs: [CBUUID] = type(of: sp).characteristicTypes.keys.map { uuid in return CBUUID(string: uuid) } peripheral.discoverCharacteristics(charUUIDs.count > 0 ? charUUIDs : nil, for: cbs) } } else { SensorManager.logSensorMessage?("Sensor: Service Ignored: \(cbs)") } } fileprivate func characteristicDiscovered(_ cbc: CBCharacteristic, cbs: CBService) { guard let service = services[cbs.uuid.uuidString] else { return } if let characteristic = service.characteristic(cbc.uuid.uuidString), characteristic.cbCharacteristic == cbc { return } guard let sp = service as? ServiceProtocol else { return } if let CharType = type(of: sp).characteristicTypes[cbc.uuid.uuidString] { let characteristic = CharType.init(service: service, cbc: cbc) service.characteristics[cbc.uuid.uuidString] = characteristic characteristic.onValueUpdated.subscribe(with: self) { [weak self] c in if let s = self { s.onCharacteristicValueUpdated => (s, c) } } characteristic.onValueWritten.subscribe(with: self) { [weak self] c in if let s = self { s.onCharacteristicValueWritten => (s, c) } } SensorManager.logSensorMessage?("Sensor: Characteristic Created: \(characteristic)") onCharacteristicDiscovered => (self, characteristic) } else { SensorManager.logSensorMessage?("Sensor: Characteristic Ignored: \(cbc)") } } @objc func rssiPingTimerHandler() { if peripheral.state == .connected { peripheral.readRSSI() } } internal func markSensorActivity() { lastSensorActivity = Date.timeIntervalSinceReferenceDate } } extension Sensor: CBPeripheralDelegate { /// :nodoc: public func peripheralDidUpdateName(_ peripheral: CBPeripheral) { onNameChanged => self markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let cbss = peripheral.services else { return } for cbs in cbss { serviceDiscovered(cbs) } markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard let cbcs = service.characteristics else { return } for cbc in cbcs { characteristicDiscovered(cbc, cbs: service) } markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard let service = services[characteristic.service.uuid.uuidString] else { return } guard let char = service.characteristics[characteristic.uuid.uuidString] else { return } if char.cbCharacteristic !== characteristic { char.cbCharacteristic = characteristic } char.valueUpdated() markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { guard let service = services[characteristic.service.uuid.uuidString] else { return } guard let char = service.characteristics[characteristic.uuid.uuidString] else { return } if char.cbCharacteristic !== characteristic { char.cbCharacteristic = characteristic } char.valueWritten() markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { if RSSI.intValue < 0 { rssi = RSSI.intValue markSensorActivity() } } }
mit
b6d116fa0a8c3ea20082df2e0674a994
32.13355
196
0.600767
5.270466
false
false
false
false
skarppi/cavok
CAVOK/Weather/Models/Taf.swift
1
3054
// // Taf.swift // CAVOK // // Created by Juho Kolehmainen on 05.07.15. // Copyright © 2016 Juho Kolehmainen. All rights reserved. // import Foundation public class Taf: Observation { @objc public dynamic var from = Date() @objc public dynamic var to = Date() // swiftlint:disable:next function_body_length override public func parse(raw: String) { super.parse(raw: raw) let parser = Tokenizer(raw: self.raw) if parser.peek() == "TAF" { parser.next() } if let type = parser.peek() { if type.contains(["COR", "AMD"]) { self.type = type parser.next() } } // identifier self.identifier = parser.pop()! let time = parseDate(value: parser.peek()) if let time = time { self.datetime = time parser.next() } // validity start and end if let (from, to) = parse(validity: parser.pop()) { if time == nil { self.datetime = from } self.from = from self.to = to } else { print("No TAF validity for \(raw)") self.from = self.datetime self.to = zuluCalendar().date(byAdding: .hour, value: 24, to: self.datetime)! } if let wind = parseWind(value: parser.peek()) { self.wind = wind parser.next() } else { self.wind = WindData() } if parseWindVariability(value: parser.peek()) { self.windVariability = parser.pop() } if let vis = parseVisibility(value: parser.peek()) { self.visibility = vis self.visibilityGroup = parser.pop() } else { self.visibility = nil self.visibilityGroup = nil } self.weather = parser.loop { current in return isSkyCondition(field: current) }.joined(separator: " ") self.clouds = parser.loop { current in return !isSkyCondition(field: current) }.joined(separator: " ") self.cloudHeight = getCombinedCloudHeight() self.supplements = parser.all().joined(separator: " ") // post-process if self.visibility == nil && isCavok() { self.visibility = 10000 } self.condition = self.parseCondition().rawValue } private func parse(validity: String?) -> (Date, Date)? { if let validity = validity, validity != "NIL", !validity.hasSuffix("Z") { let components = validity.components(separatedBy: "/").map { component -> Date in if component.hasSuffix("24") { let day = component.subString(0, length: 2) return self.parseDate(value: "\(day)0000Z", dayOffset: 1)! } return self.parseDate(value: "\(component)00Z")! } return (components[0], components[1]) } return nil } }
mit
6dc11c6e6c39ccb8f4001a5e11b6e27f
26.754545
93
0.522437
4.3
false
false
false
false
erhoffex/SwiftAnyPic
SwiftAnyPic/PAPConstants.swift
6
4963
enum PAPTabBarControllerViewControllerIndex: Int { case HomeTabBarItemIndex = 0, EmptyTabBarItemIndex, ActivityTabBarItemIndex } // Ilya 400680 // James 403902 // David 1225726 // Bryan 4806789 // Thomas 6409809 // Ashley 12800553 // Héctor 121800083 // Kevin 500011038 // Chris 558159381 // Matt 723748661 let kPAPParseEmployeeAccounts = ["400680", "403902", "1225726", "4806789", "6409809", "12800553", "121800083", "500011038", "558159381", "723748661"] let kPAPUserDefaultsActivityFeedViewControllerLastRefreshKey = "com.parse.Anypic.userDefaults.activityFeedViewController.lastRefresh" let kPAPUserDefaultsCacheFacebookFriendsKey = "com.parse.Anypic.userDefaults.cache.facebookFriends" // MARK:- Launch URLs let kPAPLaunchURLHostTakePicture = "camera" // MARK:- NSNotification let PAPAppDelegateApplicationDidReceiveRemoteNotification = "com.parse.Anypic.appDelegate.applicationDidReceiveRemoteNotification" let PAPUtilityUserFollowingChangedNotification = "com.parse.Anypic.utility.userFollowingChanged" let PAPUtilityUserLikedUnlikedPhotoCallbackFinishedNotification = "com.parse.Anypic.utility.userLikedUnlikedPhotoCallbackFinished" let PAPUtilityDidFinishProcessingProfilePictureNotification = "com.parse.Anypic.utility.didFinishProcessingProfilePictureNotification" let PAPTabBarControllerDidFinishEditingPhotoNotification = "com.parse.Anypic.tabBarController.didFinishEditingPhoto" let PAPTabBarControllerDidFinishImageFileUploadNotification = "com.parse.Anypic.tabBarController.didFinishImageFileUploadNotification" let PAPPhotoDetailsViewControllerUserDeletedPhotoNotification = "com.parse.Anypic.photoDetailsViewController.userDeletedPhoto" let PAPPhotoDetailsViewControllerUserLikedUnlikedPhotoNotification = "com.parse.Anypic.photoDetailsViewController.userLikedUnlikedPhotoInDetailsViewNotification" let PAPPhotoDetailsViewControllerUserCommentedOnPhotoNotification = "com.parse.Anypic.photoDetailsViewController.userCommentedOnPhotoInDetailsViewNotification" // MARK:- User Info Keys let PAPPhotoDetailsViewControllerUserLikedUnlikedPhotoNotificationUserInfoLikedKey = "liked" let kPAPEditPhotoViewControllerUserInfoCommentKey = "comment" // MARK:- Installation Class // Field keys let kPAPInstallationUserKey = "user" // MARK:- Activity Class // Class key let kPAPActivityClassKey = "Activity" // Field keys let kPAPActivityTypeKey = "type" let kPAPActivityFromUserKey = "fromUser" let kPAPActivityToUserKey = "toUser" let kPAPActivityContentKey = "content" let kPAPActivityPhotoKey = "photo" // Type values let kPAPActivityTypeLike = "like" let kPAPActivityTypeFollow = "follow" let kPAPActivityTypeComment = "comment" let kPAPActivityTypeJoined = "joined" // MARK:- User Class // Field keys let kPAPUserDisplayNameKey = "displayName" let kPAPUserFacebookIDKey = "facebookId" let kPAPUserPhotoIDKey = "photoId" let kPAPUserProfilePicSmallKey = "profilePictureSmall" let kPAPUserProfilePicMediumKey = "profilePictureMedium" let kPAPUserFacebookFriendsKey = "facebookFriends" let kPAPUserAlreadyAutoFollowedFacebookFriendsKey = "userAlreadyAutoFollowedFacebookFriends" let kPAPUserEmailKey = "email" let kPAPUserAutoFollowKey = "autoFollow" // MARK:- Photo Class // Class key let kPAPPhotoClassKey = "Photo" // Field keys let kPAPPhotoPictureKey = "image" let kPAPPhotoThumbnailKey = "thumbnail" let kPAPPhotoUserKey = "user" let kPAPPhotoOpenGraphIDKey = "fbOpenGraphID" // MARK:- Cached Photo Attributes // keys let kPAPPhotoAttributesIsLikedByCurrentUserKey = "isLikedByCurrentUser"; let kPAPPhotoAttributesLikeCountKey = "likeCount" let kPAPPhotoAttributesLikersKey = "likers" let kPAPPhotoAttributesCommentCountKey = "commentCount" let kPAPPhotoAttributesCommentersKey = "commenters" // MARK:- Cached User Attributes // keys let kPAPUserAttributesPhotoCountKey = "photoCount" let kPAPUserAttributesIsFollowedByCurrentUserKey = "isFollowedByCurrentUser" // MARK:- Push Notification Payload Keys let kAPNSAlertKey = "alert" let kAPNSBadgeKey = "badge" let kAPNSSoundKey = "sound" // the following keys are intentionally kept short, APNS has a maximum payload limit let kPAPPushPayloadPayloadTypeKey = "p" let kPAPPushPayloadPayloadTypeActivityKey = "a" let kPAPPushPayloadActivityTypeKey = "t" let kPAPPushPayloadActivityLikeKey = "l" let kPAPPushPayloadActivityCommentKey = "c" let kPAPPushPayloadActivityFollowKey = "f" let kPAPPushPayloadFromUserObjectIdKey = "fu" let kPAPPushPayloadToUserObjectIdKey = "tu" let kPAPPushPayloadPhotoObjectIdKey = "pid"
cc0-1.0
c6f64b38e2ba589db0ecbce4dfed17e1
41.775862
162
0.759371
4.121262
false
false
false
false
2794129697/-----mx
CoolXuePlayer/HistoryUnLoginTipVC.swift
1
2588
// // HistoryUnLoginTipVC.swift // CoolXuePlayer // // Created by lion-mac on 15/7/23. // Copyright (c) 2015年 lion-mac. All rights reserved. // import UIKit class HistoryUnLoginTipVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setView() } func setView(){ self.view.backgroundColor = UIColor.whiteColor() var tipLabel = UILabel(frame: CGRectMake((self.view.bounds.width - 200)/2, 100, 200, 40)) tipLabel.font = UIFont.systemFontOfSize(12) tipLabel.text = "登录后才能查看播放历史" tipLabel.textAlignment = NSTextAlignment.Center self.view.addSubview(tipLabel) var bnLogin = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton bnLogin.backgroundColor = UIColor.redColor() bnLogin.frame = CGRectMake((self.view.bounds.width - 100)/2, 150, 100, 40) bnLogin.titleLabel?.textColor = UIColor.blueColor() bnLogin.titleLabel?.text = "登录" bnLogin.setTitle("登录", forState: UIControlState.Normal) bnLogin.addTarget(self, action: "ToLoginVC", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(bnLogin) self.navigationController?.title = "播放历史" } func ToLoginVC(){ var s = UIStoryboard(name: "Main", bundle: nil) var tab = s.instantiateViewControllerWithIdentifier("loginTab") as? LoginUITabBarController self.navigationController?.pushViewController(tab!, animated: true) } override func viewWillAppear(animated: Bool) { //super.viewWillAppear(animated) if LoginTool.isLogin == true { self.navigationController?.popViewControllerAnimated(true) // for v in self.navigationController!.viewControllers { // if v.isKindOfClass(UserCenterVC){ // v.performSegueWithIdentifier("ToHistoryVC", sender: nil) // break // } // } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
lgpl-3.0
b3627d38f65123fdc11ca1ccad63294c
34.887324
106
0.647567
4.649635
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Sources/Portal.swift
2
5249
// // Portal.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import SceneKit public final class Portal: Item, Toggleable, NodeConstructible { // MARK: Static static let enterAnimation: CAAnimation = { return loadAnimation(WorldConfiguration.portalDir + "PortalEnter")! }() static let exitAnimation: CAAnimation = { return loadAnimation(WorldConfiguration.portalDir + "PortalExit")! }() // MARK: Private private let activateKey = "PortalActivation-Key" private var animationNode: SCNNode { return scnNode.childNode(withName: "CHARACTER_PortalA", recursively: true) ?? scnNode } private var colorMaterials: [SCNMaterial] { return [ "glyphGEO", "diskGEO", "eyebrowGEO", "cupGEO", "portalFlareGEO", "outerFlareGEO", "crackGlowGEO1", "crackGlowGEO2", "crackGlowGEO3", "crackGlowGEO4", "crackGlowGEO5", "crackGlowGEO6" ].flatMap { nodeName -> SCNMaterial? in return scnNode.childNode(withName: nodeName, recursively: true)?.firstGeometry?.firstMaterial } } // MARK: Properties public var linkedPortal: Portal? { didSet { // Automatically set the reverse link. linkedPortal?.linkedPortal = self linkedPortal?.color = color if let coordinate = linkedPortal?.coordinate { scnNode.setName(forCoordinate: coordinate) } } } /// Tracks the state of the portal seperate from its animation. private var _isActive = true /// State of the portal. An active portal transports a character that moves onto it, while an inactive portal does not. Portals are active by default. public var isActive: Bool { get { return _isActive } set { guard _isActive != newValue else { return } _isActive = newValue linkedPortal?.isActive = isActive if world?.isAnimated == true { world?.add(action: .toggle(toggleable: worldIndex, active: isActive)) } else { setActive(isActive, animated: false) } } } public var color: Color { didSet { setColor() } } // MARK: Item public static let identifier: WorldNodeIdentifier = .portal public weak var world: GridWorld? { didSet { if let world = world { // Remove tops of blocks where the portal will be. world.removeTop(at: coordinate) } else { // Add the top back when removing the portal. let topBlock = oldValue?.topBlock(at: coordinate) topBlock?.addTop() } } } public let node: NodeWrapper public var worldIndex = -1 // MARK: Initialization public init(color: Color) { self.color = color node = NodeWrapper(identifier: .portal) // lightNode?.light?.categoryBitMask = WorldConfiguration.characterLightBitMask } init?(node: SCNNode) { guard node.identifier == .portal else { return nil } self.color = .blue self.node = NodeWrapper(node) let loadedColor = colorMaterials.first?.emission.contents as? _Color ?? _Color.blue self.color = Color(loadedColor) } func enter(atSpeed speed: Float = 1.0) { let animation = Portal.enterAnimation animation.speed = speed animationNode.add(animation, forKey: activateKey) } func exit(atSpeed speed: Float = 1.0) { let animation = Portal.exitAnimation animation.speed = speed animationNode.add(animation, forKey: activateKey) } // MARK: Setters func setActive(_ active: Bool, animated: Bool) { _isActive = active let speed = Double(GridWorld.commandSpeed) let duration = animated ? 1 / speed : 0 SCNTransaction.begin() SCNTransaction.animationDuration = duration setColor() SCNTransaction.commit() } func setColor() { // The color representing the portal's active and inactive states. let activeColor: Color = isActive ? self.color : .gray for material in colorMaterials { material.diffuse.contents = activeColor.rawValue } } public func loadGeometry() { guard scnNode.childNodes.isEmpty else { return } let firstChild = loadTemplate(named: "\(WorldConfiguration.portalDir)NeutralPose") firstChild.enumerateHierarchy { node, _ in node.castsShadow = false } scnNode.addChildNode(firstChild) setColor() } } import PlaygroundSupport extension Portal: MessageConstructor { // MARK: MessageConstructor var message: PlaygroundValue { return .array(baseMessage + stateInfo) } var stateInfo: [PlaygroundValue] { return [.boolean(isActive), color.message] } }
mit
a119bd42e7c6b97e0a243c7e0700a24b
27.840659
154
0.582587
4.837788
false
false
false
false
steelwheels/KiwiComponents
Source/Application/KMFiler.swift
1
2422
/* * @file KMFiler.swift * @brief Define KMFiler class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import KiwiEngine import Canary import JavaScriptCore import Foundation #if os(OSX) public class KMFiler { public static let SelectInputFileItem = "select_input_file" public static let SelectDirectoryItem = "select_directory" private var mContext: KEContext public init(context ctxt: KEContext){ mContext = ctxt } public func setup(propertyTable ptable: KEPropertyTable) { /* Set "select_input_file" method */ let selfilemethod: @convention(block) (_ extensions: JSValue) -> JSValue = { (_ extensions: JSValue) -> JSValue in return self.select_input_file(extensions) } ptable.set(KMFiler.SelectInputFileItem, JSValue(object: selfilemethod, in: mContext)) /* Set "select_directory " method */ let seldirmethod: @convention(block) () -> JSValue = { () -> JSValue in return self.select_directory() } ptable.set(KMFiler.SelectDirectoryItem, JSValue(object: seldirmethod, in: mContext)) } public class func accessType(propertyName name: String) -> CNAccessType? { var result: CNAccessType? switch name { case KMFiler.SelectInputFileItem: result = .ReadOnlyAccess case KMFiler.SelectDirectoryItem: result = .ReadOnlyAccess default: result = nil } return result } private func select_input_file(_ exts: JSValue) -> JSValue { var extensions : Array<String> = [] if let extnames = exts.toArray() as? Array<String> { for extname in extnames { extensions.append(extname) } } if extensions.count <= 0 { NSLog("Invalid parameter: \(exts)") return JSValue(undefinedIn: mContext) } var result: JSValue? = nil CNExecuteInMainThread(doSync: true, execute: { if let url = URL.openPanel(title: "Select input file", selection: .SelectFile, fileTypes: extensions) { let str = url.absoluteString result = JSValue(object: NSString(string: str), in: self.mContext) } }) if let r = result { return r } else { return JSValue(undefinedIn: mContext) } } private func select_directory() -> JSValue { let types: Array<String> = [] if let url = URL.openPanel(title: "Select directory", selection: .SelectDirectory, fileTypes: types){ let str = url.absoluteString return JSValue(object: NSString(string: str), in: mContext) } else { return JSValue(undefinedIn: mContext) } } } #endif
lgpl-2.1
46c61d99586fe57bf50624ec3f49e511
25.615385
106
0.705202
3.354571
false
false
false
false
sjrmanning/Birdsong
Source/Channel.swift
1
2630
// // Channel.swift // Pods // // Created by Simon Manning on 24/06/2016. // // import Foundation open class Channel { // MARK: - Properties open let topic: String open let params: Socket.Payload fileprivate weak var socket: Socket? fileprivate(set) open var state: State fileprivate(set) open var presence: Presence fileprivate var callbacks: [String: (Response) -> ()] = [:] fileprivate var presenceStateCallback: ((Presence) -> ())? init(socket: Socket, topic: String, params: Socket.Payload = [:]) { self.socket = socket self.topic = topic self.params = params self.state = .Closed self.presence = Presence() // Register presence handling. on("presence_state") { [weak self] (response) in self?.presence.sync(response) guard let presence = self?.presence else {return} self?.presenceStateCallback?(presence) } on("presence_diff") { [weak self] (response) in self?.presence.sync(response) } } // MARK: - Control @discardableResult open func join() -> Push? { state = .Joining return send(Socket.Event.Join, payload: params)?.receive("ok", callback: { response in self.state = .Joined }) } @discardableResult open func leave() -> Push? { state = .Leaving return send(Socket.Event.Leave, payload: [:])?.receive("ok", callback: { response in self.callbacks.removeAll() self.presence.onJoin = nil self.presence.onLeave = nil self.presence.onStateChange = nil self.state = .Closed }) } @discardableResult open func send(_ event: String, payload: Socket.Payload) -> Push? { let message = Push(event, topic: topic, payload: payload) return socket?.send(message) } // MARK: - Raw events func received(_ response: Response) { if let callback = callbacks[response.event] { callback(response) } } // MARK: - Callbacks @discardableResult open func on(_ event: String, callback: @escaping (Response) -> ()) -> Self { callbacks[event] = callback return self } @discardableResult open func onPresenceUpdate(_ callback: @escaping (Presence) -> ()) -> Self { presenceStateCallback = callback return self } // MARK: - States public enum State: String { case Closed = "closed" case Errored = "errored" case Joined = "joined" case Joining = "joining" case Leaving = "leaving" } }
mit
ccc4baaa03348b8027b2804d8a91bd65
24.047619
94
0.592395
4.262561
false
false
false
false
Vienta/kuafu
kuafu/kuafu/src/Controller/KFEventViewController.swift
1
15673
// // ViewController.handShaked // kuafu // // Created by Vienta on 15/6/4. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit import ObjectiveC import MGSwipeTableCell import MKEventKit import DAAlertController var kAssociateRowKey: UInt8 = 1 class KFEventViewController: UIViewController,UITableViewDataSource, UITableViewDelegate, MGSwipeTableCellDelegate, ZoomTransitionProtocol{ // MARK: - Property @IBOutlet weak var tbvEvents: UITableView! @IBOutlet weak var lblEmpty: UILabel! var pullCalendar: KFPullCalendarView! var pullCalendarFlag: Bool! var animationController: ZoomTransition? var events: NSMutableArray! // MARK: - IBActions @IBAction func btnTapped(sender: AnyObject) { self.popWriteEventViewControllerWithEvent(nil) } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "KF_EVENT_CONTROLLER_TITLE".localized self.tbvEvents.rowHeight = UITableViewAutomaticDimension self.tbvEvents.estimatedRowHeight = 78.0 self.tbvEvents.registerNib(UINib(nibName: "KFEventCell", bundle: nil), forCellReuseIdentifier: "KFEventCell") var addButtonItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "btnTapped:") self.navigationItem.rightBarButtonItem = addButtonItem self.view.backgroundColor = KF_BG_COLOR self.pullCalendar = LOAD_NIB("KFPullCalendarView") as! KFPullCalendarView self.pullCalendar.alpha = 0 self.pullCalendar.center = CGPointMake(DEVICE_WIDTH/2, 64) self.view.addSubview(self.pullCalendar) self.pullCalendarFlag = false if let navigationController = self.navigationController { self.animationController = ZoomTransition(navigationController: navigationController) } self.navigationController?.delegate = animationController self.navigationController?.interactivePopGestureRecognizer.enabled = true self.navigationController?.interactivePopGestureRecognizer.delegate = nil NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTask", name: KF_NOTIFICATION_UPDATE_TASK, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTask", name: UIApplicationWillEnterForegroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "handShaked", name: KF_NOTIFICATION_SHAKE, object: nil) self.events = NSMutableArray(capacity: 0) self.showTaskData() DELAY(3, { () -> () in let eventStore = EKEventStore() eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted, error) -> Void in println("granted:\(granted)") }) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Private Methods func popWriteEventViewControllerWithEvent(eventDO: KFEventDO!) -> Void { var eventWriteViewController: KFEventWriteViewController = KFEventWriteViewController(nibName: "KFEventWriteViewController", bundle: nil) eventWriteViewController.eventDO = eventDO var eventWriteNavigationController: UINavigationController = UINavigationController(rootViewController: eventWriteViewController) self.navigationController?.presentViewController(eventWriteNavigationController, animated: true, completion: nil) } func deleteEventCellWithAnimation(sectionDict: NSDictionary, eventsInSection: NSArray, indexPath: NSIndexPath, eventDO: KFEventDO) -> Void { var sectionDict: NSDictionary = sectionDict var eventsMArrInSection: NSMutableArray = NSMutableArray(array: eventsInSection) as NSMutableArray var targetEvent: KFEventDO! for (index, event : AnyObject) in enumerate(eventsMArrInSection) { var subEvent: KFEventDO = event as! KFEventDO if subEvent.eventid.integerValue == eventDO.eventid.integerValue { targetEvent = subEvent } } if targetEvent != nil { KFLocalPushManager.sharedManager.deleteLocalPushWithEvent(targetEvent) eventsMArrInSection.removeObject(targetEvent) } if eventsMArrInSection.count == 0 { self.events.removeObjectAtIndex(indexPath.section) self.tbvEvents.reloadData() } else { var updateEventDict: NSDictionary = ["title": sectionDict.objectForKey("title") as! String,"events": eventsMArrInSection] let section: Int = indexPath.section self.events.replaceObjectAtIndex(section, withObject: updateEventDict) self.tbvEvents.beginUpdates() self.tbvEvents.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Bottom) self.tbvEvents.endUpdates() DELAY(0.4, { () -> () in self.tbvEvents.reloadSections(NSIndexSet(index: section), withRowAnimation: UITableViewRowAnimation.None) }) } } func showTaskData() -> Void { self.updateTask() } func handShaked() -> Void { var createTaskAction: DAAlertAction = DAAlertAction(title: "KF_NEW_TODO_TITLE".localized, style: DAAlertActionStyle.Default, handler: { () -> Void in self.popWriteEventViewControllerWithEvent(nil) }) var fobiddenShakeAction: DAAlertAction = DAAlertAction(title: "KF_ALERT_CLOSE_SHAKE".localized, style: DAAlertActionStyle.Default, handler: { () -> Void in NSUserDefaults.standardUserDefaults().setBool(false, forKey: KF_SHAKE_CREATE_TASK) NSNotificationCenter.defaultCenter().postNotificationName(KF_NOTIFICATION_SHAKE_VALUE_CHANGED, object: nil) }) var cancelAction: DAAlertAction = DAAlertAction(title: "KF_CANCEL".localized, style: DAAlertActionStyle.Destructive, handler: nil) DAAlertController.showAlertViewInViewController(self, withTitle: "KF_NEW_TODO_TITLE".localized + "?", message: nil, actions: [createTaskAction,fobiddenShakeAction,cancelAction]) } func updateTask() -> Void { self.events.removeAllObjects() var allEvents: NSMutableArray = NSMutableArray(array: KFEventDAO.sharedManager.getAllNoArchiveAndNoDeleteEvents()) if allEvents.count == 0 { self.lblEmpty.hidden = false self.tbvEvents.hidden = true return } else { self.lblEmpty.hidden = true self.tbvEvents.hidden = false } //逾期任务 var overDueEvents: NSMutableArray = NSMutableArray(capacity: 0) //普通任务 既无提醒时间,也无逾期时间 var normalEvents: NSMutableArray = NSMutableArray(capacity: 0) //今日任务 提醒时间或者逾期时间是今天 var todayEvents: NSMutableArray = NSMutableArray(capacity: 0) var currentDateStamp: NSTimeInterval = NSDate().timeIntervalSince1970 allEvents.enumerateObjectsUsingBlock { (element, index, stop) -> Void in let subEvent = element as! KFEventDO if subEvent.endtime.doubleValue > 0 { if currentDateStamp > subEvent.endtime.doubleValue { overDueEvents.addObject(subEvent) } } if subEvent.starttime.doubleValue > 0 || subEvent.endtime.doubleValue > 0 { var isStartTimeToday: Bool = NSCalendar.currentCalendar().isDateInToday(KFUtil.dateFromTimeStamp(subEvent.starttime.doubleValue)) var isEndTimeToday: Bool = NSCalendar.currentCalendar().isDateInToday(KFUtil.dateFromTimeStamp(subEvent.endtime.doubleValue)) var isToday: Bool = (isStartTimeToday || isEndTimeToday) if isToday == true && (currentDateStamp < subEvent.endtime.doubleValue) { todayEvents.addObject(subEvent) } } } allEvents.removeObjectsInArray(overDueEvents as [AnyObject]) allEvents.removeObjectsInArray(todayEvents as [AnyObject]) if overDueEvents.count > 0 { var overDueEventDict: NSDictionary = ["title": "KF_OVERDUE_TASK".localized,"events": overDueEvents] self.events.addObject(overDueEventDict) } if todayEvents.count > 0 { var todayEventDict: NSDictionary = ["title": "KF_TODAY_TASK".localized,"events": todayEvents] self.events.addObject(todayEventDict) } normalEvents = allEvents if normalEvents.count > 0 { var normalEventDict: NSDictionary = ["title": "KF_NORMAL_TASK".localized,"events": normalEvents] self.events.addObject(normalEventDict) } self.tbvEvents.reloadData() } // MARK: - MGSwipeTableCellDelegate func swipeTableCell(cell: MGSwipeTableCell!, tappedButtonAtIndex index: Int, direction: MGSwipeDirection, fromExpansion: Bool) -> Bool { var eventDO = objc_getAssociatedObject(cell, &kAssociateKey) as! KFEventDO var indexPath = objc_getAssociatedObject(cell, &kAssociateRowKey) as! NSIndexPath if direction == MGSwipeDirection.LeftToRight { if index == 0 { eventDO.status = NSNumber(integerLiteral: KEventStatus.Achieve.rawValue) KFEventDAO.sharedManager.saveEvent(eventDO) var sectionDict: NSDictionary = self.events.objectAtIndex(indexPath.section) as! NSDictionary self.deleteEventCellWithAnimation(sectionDict as NSDictionary, eventsInSection: sectionDict.objectForKey("events") as! NSArray, indexPath: indexPath, eventDO: eventDO) } } if direction == MGSwipeDirection.RightToLeft { if index == 0 { eventDO.status = NSNumber(integerLiteral: KEventStatus.Delete.rawValue) KFEventDAO.sharedManager.saveEvent(eventDO) var sectionDict: NSDictionary = self.events.objectAtIndex(indexPath.section) as! NSDictionary self.deleteEventCellWithAnimation(sectionDict as NSDictionary, eventsInSection: sectionDict.objectForKey("events") as! NSArray, indexPath: indexPath, eventDO: eventDO) } if index == 1 { self.popWriteEventViewControllerWithEvent(eventDO) } } return true } // MARK: - UITableViewDelegate && UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { if self.events.count == 0 { self.lblEmpty.hidden = false self.tbvEvents.hidden = true } return self.events.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var currentEventDict: NSDictionary = self.events.objectAtIndex(section) as! NSDictionary var currentEvents: NSArray = currentEventDict.objectForKey("events") as! NSArray return currentEvents.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var currentEventSectionTitle: String = self.events.objectAtIndex(section).objectForKey("title") as! String return currentEventSectionTitle } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header = view as! UITableViewHeaderFooterView header.textLabel.textColor = UIColor.grayColor() header.textLabel.font = UIFont.systemFontOfSize(14) header.contentView.backgroundColor = KF_BG_COLOR } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 24.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var eventCell: KFEventCell = tableView.dequeueReusableCellWithIdentifier("KFEventCell") as! KFEventCell eventCell.leftButtons = [MGSwipeButton(title: "KF_ARCHIEVE".localized, backgroundColor: UIColor(red: 0.13, green: 0.41, blue: 1, alpha: 1)) { (cell: MGSwipeTableCell!) -> Bool in return true }] eventCell.leftExpansion.fillOnTrigger = true eventCell.rightButtons = [ MGSwipeButton(title: " " + "KF_DELETE".localized + " ", backgroundColor: UIColor(red: 1, green: 0, blue: 0.13, alpha: 1)) { (cell: MGSwipeTableCell!) -> Bool in return true }, MGSwipeButton(title: " " + "KF_EDIT".localized + " ", backgroundColor: UIColor(red: 0.8, green: 0.76, blue: 0.81, alpha: 1)) { (cell: MGSwipeTableCell!) -> Bool in return true } ] eventCell.rightExpansion.fillOnTrigger = true eventCell.leftExpansion.buttonIndex = 0 eventCell.rightExpansion.buttonIndex = 0 eventCell.delegate = self var eventDict: NSDictionary = self.events[indexPath.section] as! NSDictionary var eventInSection: NSArray = eventDict.objectForKey("events") as! NSArray var eventDO: KFEventDO = eventInSection[indexPath.row] as! KFEventDO eventCell.configData(eventDO) objc_setAssociatedObject(eventCell, &kAssociateKey, eventDO, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) objc_setAssociatedObject(eventCell, &kAssociateRowKey, indexPath, objc_AssociationPolicy(OBJC_ASSOCIATION_COPY_NONATOMIC)) return eventCell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if (scrollView.contentOffset.y <= -160.0) { if pullCalendarFlag == false { pullCalendarFlag = true let calendarViewController: KFCalendarViewController = KFCalendarViewController(nibName: "KFCalendarViewController", bundle: nil) self.navigationController?.pushViewController(calendarViewController, animated: true) DELAY(0.3, { () -> () in self.pullCalendarFlag = false }) } } } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { var offsetY: CGFloat = scrollView.contentOffset.y if offsetY < -130 { self.pullCalendar.center = CGPointMake(DEVICE_WIDTH/2, (fabs(offsetY) - 64)/2 + 64) self.pullCalendar.alpha = (fabs(offsetY) - 130) * 1.0 / 40 } else { self.pullCalendar.alpha = 0 } } // MARK: - ZoomTransitionProtocol func viewForTransition() -> UIView { return self.pullCalendar } }
mit
7aeb09864368582377c2fa38023c9bd1
44.072254
189
0.65925
5.043661
false
false
false
false
DavidSkrundz/Lua
Sources/Lua/Enums/Status.swift
1
1063
// // Status.swift // Lua // import CLua internal enum Status: RawRepresentable { case OK case Yield case RunError case SyntaxError case MemoryError case ErrGCMM case Error case IOError internal typealias RawValue = Int32 internal init(rawValue: RawValue) { switch rawValue { case LUA_OK: self = .OK case LUA_YIELD: self = .Yield case LUA_ERRRUN: self = .RunError case LUA_ERRSYNTAX: self = .SyntaxError case LUA_ERRMEM: self = .MemoryError case LUA_ERRGCMM: self = .ErrGCMM case LUA_ERRERR: self = .Error case LUA_ERRFILE: self = .IOError default: fatalError("Unhandled value: \(rawValue)") } } internal var rawValue: RawValue { switch self { case .OK: return LUA_OK case .Yield: return LUA_YIELD case .RunError: return LUA_ERRRUN case .SyntaxError: return LUA_ERRSYNTAX case .MemoryError: return LUA_ERRMEM case .ErrGCMM: return LUA_ERRGCMM case .Error: return LUA_ERRERR case .IOError: return LUA_ERRFILE } } }
lgpl-3.0
68d45201eb45763750fe3e4e3af6bda4
22.108696
65
0.652869
3.045845
false
false
false
false
SiddharthNarsimhan/DecorUI
DecorMainUI/DecorMainUI/CollectionListDetail.swift
1
3240
// // CollectionListDetail.swift // DecorMainUI // // Created by Siddharth Narsimhan on 12/29/16. // Copyright © 2016 Siddharth Narsimhan. All rights reserved. // import Foundation import UIKit class collectionDetail: BaseCell, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.backgroundColor = UIColor.white return cv }() override func setup() { super.setup() let cellid = "cellid" collectionView.dataSource = self collectionView.delegate = self addSubview(collectionView) addConstraintsWithFormat("H:|-[v0]-|", [], views: collectionView) addConstraintsWithFormat("V:|-100-[v0]-|", [], views: collectionView) collectionView.register(detailCell.self, forCellWithReuseIdentifier: cellid) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: "cellid", for: indexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: frame.width, height: 100) }} class detailCell : BaseCell { let productImage : UIView = { let pImage = UIImageView() pImage.image = UIImage(named: "r01_c05") pImage.contentMode = .scaleAspectFill pImage.layer.cornerRadius = 8 pImage.layer.masksToBounds = true return pImage }() let details : UITextView = { let text = UITextView() text.text = "This the description of the furniture part of this collection list." if #available(iOS 10.0, *) { text.adjustsFontForContentSizeCategory = true } else { // Fallback on earlier versions } text.font? = UIFont.boldSystemFont(ofSize: 14) text.textColor = UIColor.lightGray return text }() let nameLabel: UILabel = { let label = UILabel() label.text = "Product Name" label.font = UIFont.systemFont(ofSize: 16) return label }() override func setup() { super.setup() // backgroundColor = UIColor.yellow addSubview(productImage) addSubview(nameLabel) addSubview(details) addConstraintsWithFormat("H:|-[v0(100)]-[v1]-|", [], views: productImage, nameLabel) addConstraintsWithFormat("V:|-[v0]-|", [], views: productImage) addConstraintsWithFormat("H:[v0]-[v1]-|", [], views: productImage, details) addConstraintsWithFormat("V:|-[v0]-[v1]-|", [.alignAllLeft], views: nameLabel,details) } }
apache-2.0
a5342143c71e5490a10619a192b1dba8
33.094737
160
0.631676
5.190705
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Live/View/ChatView/ChatToolsView.swift
1
3041
// // ChatToolsView.swift // GYJTV // // Created by 田全军 on 2017/5/23. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit //MARK: 信息回调协议 protocol ChatToolsViewDelegate : class{ func chatTiilsView(chatToolsView : ChatToolsView, message: String) } class ChatToolsView: UIView , NibLoadable{ // MARK: 属性 @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var sendMsgBtn: UIButton! fileprivate lazy var emoticonBtn : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) fileprivate lazy var emotionView : EmotionView = EmotionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 250)) weak var delegate : ChatToolsViewDelegate? override func awakeFromNib() { super.awakeFromNib() onfinishViews() } @IBAction func sendButtonclick(_ sender: UIButton) { //获取内容 guard let message = inputTextField.text else { return } if message == "" { sender.isEnabled = false return } ///清空内容 inputTextField.text = "" //发送消息 delegate?.chatTiilsView(chatToolsView: self, message: message) } @IBAction func textFieldDidChanged(_ sender: UITextField) { sendMsgBtn.isEnabled = sender.text!.count != 0 } } // MARK:初始化界面 extension ChatToolsView{ fileprivate func onfinishViews(){ // 1.初始化inputView中rightView emoticonBtn.setImage(UIImage(named: "chat_btn_emoji"), for: .normal) emoticonBtn.setImage(UIImage(named: "chat_btn_keyboard"), for: .selected) emoticonBtn.addTarget(self, action: #selector(emoticonBtnClick(_:)), for: .touchUpInside) inputTextField.rightView = emoticonBtn inputTextField.rightViewMode = .always inputTextField.allowsEditingTextAttributes = true //可编辑 // 2.设置emotionView的闭包(weak当对象销毁值, 会自动将指针指向nil) emotionView.emotionClickCallBack = {[weak self] emoticon in // 1.判断是否是删除按钮 if emoticon.emoticonName == "delete-n" { self?.inputTextField.deleteBackward() return } // 2.获取光标位置 guard let range = self?.inputTextField.selectedTextRange else { return } self?.inputTextField.replace(range, withText: emoticon.emoticonName) } } } // MARK: 事件监听 extension ChatToolsView{ @objc fileprivate func emoticonBtnClick(_ button : UIButton){ button.isSelected = !button.isSelected //切换键盘 //获取光标所在位置 let range = inputTextField.selectedTextRange inputTextField.resignFirstResponder() inputTextField.inputView = inputTextField.inputView == nil ? emotionView : nil inputTextField.becomeFirstResponder() inputTextField.selectedTextRange = range } }
mit
841e6a618882ae68adb8df2e2309a89c
31.224719
125
0.641562
4.610932
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Utils/Fill.swift
5
8489
// // Fill.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartFillType) public enum FillType: Int { case empty case color case linearGradient case radialGradient case image case tiledImage case layer } @objc(ChartFill) open class Fill: NSObject { fileprivate var _type: FillType = FillType.empty fileprivate var _color: CGColor? fileprivate var _gradient: CGGradient? fileprivate var _gradientAngle: CGFloat = 0.0 fileprivate var _gradientStartOffsetPercent: CGPoint = CGPoint() fileprivate var _gradientStartRadiusPercent: CGFloat = 0.0 fileprivate var _gradientEndOffsetPercent: CGPoint = CGPoint() fileprivate var _gradientEndRadiusPercent: CGFloat = 0.0 fileprivate var _image: CGImage? fileprivate var _layer: CGLayer? // MARK: Properties @objc open var type: FillType { return _type } @objc open var color: CGColor? { return _color } @objc open var gradient: CGGradient? { return _gradient } @objc open var gradientAngle: CGFloat { return _gradientAngle } @objc open var gradientStartOffsetPercent: CGPoint { return _gradientStartOffsetPercent } @objc open var gradientStartRadiusPercent: CGFloat { return _gradientStartRadiusPercent } @objc open var gradientEndOffsetPercent: CGPoint { return _gradientEndOffsetPercent } @objc open var gradientEndRadiusPercent: CGFloat { return _gradientEndRadiusPercent } @objc open var image: CGImage? { return _image } @objc open var layer: CGLayer? { return _layer } // MARK: Constructors public override init() { } @objc public init(CGColor: CGColor) { _type = .color _color = CGColor } @objc public convenience init(color: NSUIColor) { self.init(CGColor: color.cgColor) } @objc public init(linearGradient: CGGradient, angle: CGFloat) { _type = .linearGradient _gradient = linearGradient _gradientAngle = angle } @objc public init( radialGradient: CGGradient, startOffsetPercent: CGPoint, startRadiusPercent: CGFloat, endOffsetPercent: CGPoint, endRadiusPercent: CGFloat ) { _type = .radialGradient _gradient = radialGradient _gradientStartOffsetPercent = startOffsetPercent _gradientStartRadiusPercent = startRadiusPercent _gradientEndOffsetPercent = endOffsetPercent _gradientEndRadiusPercent = endRadiusPercent } @objc public convenience init(radialGradient: CGGradient) { self.init( radialGradient: radialGradient, startOffsetPercent: CGPoint(x: 0.0, y: 0.0), startRadiusPercent: 0.0, endOffsetPercent: CGPoint(x: 0.0, y: 0.0), endRadiusPercent: 1.0 ) } @objc public init(CGImage: CGImage, tiled: Bool) { _type = tiled ? .tiledImage : .image _image = CGImage } @objc public convenience init(image: NSUIImage, tiled: Bool) { self.init(CGImage: image.cgImage!, tiled: tiled) } @objc public convenience init(CGImage: CGImage) { self.init(CGImage: CGImage, tiled: false) } @objc public convenience init(image: NSUIImage) { self.init(image: image, tiled: false) } @objc public init(CGLayer: CGLayer) { _type = .layer _layer = CGLayer } // MARK: Constructors @objc open class func fillWithCGColor(_ CGColor: CGColor) -> Fill { return Fill(CGColor: CGColor) } @objc open class func fillWithColor(_ color: NSUIColor) -> Fill { return Fill(color: color) } @objc open class func fillWithLinearGradient( _ linearGradient: CGGradient, angle: CGFloat) -> Fill { return Fill(linearGradient: linearGradient, angle: angle) } @objc open class func fillWithRadialGradient( _ radialGradient: CGGradient, startOffsetPercent: CGPoint, startRadiusPercent: CGFloat, endOffsetPercent: CGPoint, endRadiusPercent: CGFloat ) -> Fill { return Fill( radialGradient: radialGradient, startOffsetPercent: startOffsetPercent, startRadiusPercent: startRadiusPercent, endOffsetPercent: endOffsetPercent, endRadiusPercent: endRadiusPercent ) } @objc open class func fillWithRadialGradient(_ radialGradient: CGGradient) -> Fill { return Fill(radialGradient: radialGradient) } @objc open class func fillWithCGImage(_ CGImage: CGImage, tiled: Bool) -> Fill { return Fill(CGImage: CGImage, tiled: tiled) } @objc open class func fillWithImage(_ image: NSUIImage, tiled: Bool) -> Fill { return Fill(image: image, tiled: tiled) } @objc open class func fillWithCGImage(_ CGImage: CGImage) -> Fill { return Fill(CGImage: CGImage) } @objc open class func fillWithImage(_ image: NSUIImage) -> Fill { return Fill(image: image) } @objc open class func fillWithCGLayer(_ CGLayer: CGLayer) -> Fill { return Fill(CGLayer: CGLayer) } // MARK: Drawing code /// Draws the provided path in filled mode with the provided area @objc open func fillPath( context: CGContext, rect: CGRect) { let fillType = _type if fillType == .empty { return } context.saveGState() switch fillType { case .color: context.setFillColor(_color!) context.fillPath() case .image: context.clip() context.draw(_image!, in: rect) case .tiledImage: context.clip() context.draw(_image!, in: rect, byTiling: true) case .layer: context.clip() context.draw(_layer!, in: rect) case .linearGradient: let radians = ChartUtils.Math.FDEG2RAD * (360.0 - _gradientAngle) let centerPoint = CGPoint(x: rect.midX, y: rect.midY) let xAngleDelta = cos(radians) * rect.width / 2.0 let yAngleDelta = sin(radians) * rect.height / 2.0 let startPoint = CGPoint( x: centerPoint.x - xAngleDelta, y: centerPoint.y - yAngleDelta ) let endPoint = CGPoint( x: centerPoint.x + xAngleDelta, y: centerPoint.y + yAngleDelta ) context.clip() context.drawLinearGradient(_gradient!, start: startPoint, end: endPoint, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation] ) case .radialGradient: let centerPoint = CGPoint(x: rect.midX, y: rect.midY) let radius = max(rect.width, rect.height) / 2.0 context.clip() context.drawRadialGradient(_gradient!, startCenter: CGPoint( x: centerPoint.x + rect.width * _gradientStartOffsetPercent.x, y: centerPoint.y + rect.height * _gradientStartOffsetPercent.y ), startRadius: radius * _gradientStartRadiusPercent, endCenter: CGPoint( x: centerPoint.x + rect.width * _gradientEndOffsetPercent.x, y: centerPoint.y + rect.height * _gradientEndOffsetPercent.y ), endRadius: radius * _gradientEndRadiusPercent, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation] ) case .empty: break } context.restoreGState() } }
apache-2.0
e1d43b9a85ecd328fd271bbb34e2803b
25.281734
86
0.570503
4.842556
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ClearCache.swift
1
6740
// // ClearCache.swift // Telegram // // Created by Mikhail Filimonov on 03/08/2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import Postbox import TelegramCore private let cacheQueue = Queue(name: "org.telegram.clearCacheQueue") private let cleanQueue = Queue(name: "org.telegram.cleanupQueue") func scanFiles(at path: String, anyway: ((String, Int)) -> Void) { guard let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: path), includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey], options: [.skipsSubdirectoryDescendants], errorHandler: nil) else { return } while let item = enumerator.nextObject() { guard let url = item as? NSURL else { continue } guard let resourceValues = try? url.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey]) else { continue } if let value = resourceValues[.isDirectoryKey] as? Bool, value { continue } if let file = url.path { let size = (resourceValues[.fileSizeKey] as? NSNumber)?.intValue ?? 0 if size > 0 { anyway((file, size)) } } } } private func clearCache(_ files: [(String, Int)], excludes: [(partial: String, complete: String)], start: TimeInterval) -> Signal<Float, NoError> { return Signal { subscriber in var cancelled = false let files = files.filter { file in if let fileSize = fs(file.0), fileSize == 0 { return true } return !excludes.contains(where: { $0.partial == file.0 || $0.complete == file.0 }) } let total: Int = files.reduce(0, { $0 + $1.1 }) var cleaned: Int = 0 for file in files { if !cancelled { let url = URL(fileURLWithPath: file.0) guard let resourceValues = try? url.resourceValues(forKeys: [.contentModificationDateKey]) else { continue } let date = resourceValues.contentModificationDate?.timeIntervalSince1970 ?? start if date <= start { try? FileManager.default.removeItem(atPath: file.0) } cleaned += file.1 subscriber.putNext(Float(cleaned) / Float(total)) } else { break } } subscriber.putNext(1.0) subscriber.putCompletion() return ActionDisposable { cancelled = true } } |> runOn(cleanQueue) } private final class CCTask : Equatable { static func == (lhs: CCTask, rhs: CCTask) -> Bool { return lhs === rhs } private let disposable = MetaDisposable() private var progressValue: ValuePromise<Float> = ValuePromise(0) private var progress: Atomic<Float> = Atomic(value: 0) init(_ account: Account, completion: @escaping()->Void) { let signal: Signal<Float, NoError> = combineLatest(account.postbox.mediaBox.allFileContextResourceIds(), account.postbox.mediaBox.allFileContexts()) |> deliverOn(cacheQueue) |> mapToSignal { ids, excludes in var files:[(String, Int)] = [] scanFiles(at: account.postbox.mediaBox.basePath, anyway: { value in files.append(value) }) scanFiles(at: account.postbox.mediaBox.basePath + "/cache", anyway: { value in files.append(value) }) return account.postbox.mediaBox.removeCachedResources(ids) |> then(clearCache(files, excludes: excludes, start: Date().timeIntervalSince1970)) } |> deliverOn(cacheQueue) self.disposable.set(signal.start(next: { [weak self] value in guard let `self` = self else { return } self.progressValue.set(self.progress.with { _ in return value }) if value == 1.0 { cacheQueue.after(0.2, completion) } })) } func getCurrentProgress() -> Float { return progress.with { $0 } } func updatedProgress() -> Signal<Float, NoError> { return progressValue.get() } } final class CCTaskData : Equatable { static func == (lhs: CCTaskData, rhs: CCTaskData) -> Bool { return lhs === rhs } private let task: CCTask fileprivate init?(_ task: CCTask?) { guard let task = task else { return nil } self.task = task } var currentProgress: Float { return self.task.getCurrentProgress() } var progress: Signal<Float, NoError> { return self.task.updatedProgress() } } private class CCContext { private let account: Account private let currentTaskValue: Atomic<CCTask?> = Atomic(value: nil) private let currentTask: ValuePromise<CCTask?> = ValuePromise(nil) init(account: Account) { self.account = account } func makeAndRunTask() { let account = self.account currentTask.set(currentTaskValue.modify { task in if let task = task { return task } return CCTask(account, completion: { [weak self] in if let `self` = self { cacheQueue.justDispatch { self.currentTask.set(self.currentTaskValue.modify { _ in return nil } ) } } }) }) } func cancel() { self.currentTask.set(self.currentTaskValue.modify { _ in return nil } ) } func getTask() -> Signal<CCTaskData? ,NoError> { return currentTask.get() |> map { CCTaskData($0) } } } final class AccountClearCache { private let context: QueueLocalObject<CCContext> init(account: Account) { context = QueueLocalObject(queue: cacheQueue, generate: { return CCContext(account: account) }) } var task: Signal<CCTaskData?, NoError> { let signal: Signal<Signal<CCTaskData?, NoError>, NoError> = context.signalWith({ ctx, subscriber in subscriber.putNext(ctx.getTask()) subscriber.putCompletion() return EmptyDisposable }) return signal |> switchToLatest } func run() { context.with { ctx in ctx.makeAndRunTask() } } func cancel() { context.with { ctx in ctx.cancel() } } }
gpl-2.0
cef6d16b811db8737e338ab29e10702c
29.912844
218
0.556908
4.647586
false
false
false
false
AdamZikmund/strv
strv/strv/Classes/Controller/TodayViewController.swift
1
3913
// // TodayViewController.swift // strv // // Created by Adam Zikmund on 12.05.15. // Copyright (c) 2015 Adam Zikmund. All rights reserved. // import UIKit class TodayViewController: UIViewController, LocationHandlerProtocol { @IBOutlet var weatherIcon: UIImageView! @IBOutlet var locationLabel: UILabel! @IBOutlet var weatherLabel: UILabel! @IBOutlet var humidityLabel: UILabel! @IBOutlet var rainLabel: UILabel! @IBOutlet var pressureLabel: UILabel! @IBOutlet var windSpeedLabel: UILabel! @IBOutlet var windDirectionLabel: UILabel! @IBAction func sharePressed(sender: AnyObject) { self.presentViewController(activityController, animated: true, completion: nil) } let activityController = UIActivityViewController(activityItems: ["Weather", "http://openweathermap.org"], applicationActivities: nil) let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) var city : City? = LocationHandler.sharedInstance.getCity() override func viewDidLoad() { super.viewDidLoad() self.title = "Today" self.navigationItem.setRightBarButtonItem(UIBarButtonItem(image: UIImage(named: "Location"), style: UIBarButtonItemStyle.Plain, target: self, action: "locationsButtonPressed:"), animated: false) unknownView() activityIndicator.frame = self.view.frame LocationHandler.sharedInstance.registerListener(self) } override func viewDidAppear(animated: Bool) { if city == nil { city = LocationHandler.sharedInstance.getCity() } if let city = city { self.view.addSubview(activityIndicator) activityIndicator.startAnimating() city.updateWeather({ () -> Void in self.refreshView() self.activityIndicator.stopAnimating() self.activityIndicator.removeFromSuperview() }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationsButtonPressed(sender : AnyObject){ performSegueWithIdentifier("locationSegue", sender: self) } func cityDidChanged(city: City) { self.city = city self.view.addSubview(activityIndicator) activityIndicator.startAnimating() city.updateWeather({ () -> Void in self.refreshView() self.activityIndicator.stopAnimating() self.activityIndicator.removeFromSuperview() }) } private func unknownView(){ let unknown = "Unknown" locationLabel.text = unknown weatherLabel.text = unknown humidityLabel.text = unknown rainLabel.text = unknown pressureLabel.text = unknown windSpeedLabel.text = unknown windDirectionLabel.text = unknown } private func refreshView(){ let unknown = "Unknown" if let city = city { locationLabel.text = "\(city.name), \(city.stateName!)" if let weather = city.weather { weatherIcon.image = UIImage(named: weather.icon.imageNames().1) weatherLabel.text = "\(weather.temperatureString().0)\(weather.temperatureString().1) | \(weather.icon.stringValue())" humidityLabel.text = weather.humidityString() rainLabel.text = weather.rainString() pressureLabel.text = weather.pressureString() windSpeedLabel.text = weather.windSpeedString() windDirectionLabel.text = weather.windDirectionString() } }else{ locationLabel.text = unknown } } }
mit
cfa91a8c9f6ca11b536cc9b68b959390
33.026087
202
0.628163
5.488079
false
false
false
false
Yoseob/Trevi
Lime/Lime/Middleware/BodyParser.swift
1
4708
// // BodyParser.swift // Trevi // // Created by LeeYoseob on 2015. 11. 30.. // Copyright © 2015년 LeeYoseob. All rights reserved. // import Foundation import Trevi private protocol parseAble{ func parse() -> [String:AnyObject!]! } struct ParserdData { var name : String? var value : String? var type : String? var data : NSData? } /* This class is the middleware as one of the most important Consisting of many ways is easily allows us to write the user body. Now Support Json, Text, urlencoded parser */ public class BodyParser: Middleware{ public var name = MiddlewareName.BodyParser public init(){ } public func handle(req: IncomingMessage, res: ServerResponse, next: NextCallback?) { } public static func getBody(req: IncomingMessage, _ cb: (body: String)->()){ var body = "" func ondata(dt : String){ body += dt } func onend(){ cb(body: body) } req.on("data", ondata) req.on("end", onend) } public static func read(req: IncomingMessage, _ next: NextCallback?, parse: ((req: IncomingMessage, next: NextCallback , body: String!)->())){ getBody(req) { body in parse(req: req, next: next!, body: body) } } public static func urlencoded() -> HttpCallback{ func parse(req: IncomingMessage, _ next: NextCallback? , _ bodyData: String!){ var body = bodyData if body != nil { if body.containsString(CRLF){ body.removeAtIndex(body.endIndex.predecessor()) } var resultBody = [String:String]() for component in body.componentsSeparatedByString("&") { let trim = component.componentsSeparatedByString("=") resultBody[trim.first!] = trim.last! } req.body = resultBody next!() }else { } } func urlencoded(req: IncomingMessage, res: ServerResponse, next: NextCallback?) { guard req.header[Content_Type] == "application/x-www-form-urlencoded" else { return next!() } guard req.hasBody == true else{ return next!() } guard req.method == .POST || req.method == .PUT else{ return next!() } read(req, next!,parse: parse) } return urlencoded } public static func json() -> HttpCallback { func parse(req: IncomingMessage, _ next: NextCallback? , _ body: String!){ do { let data = body.dataUsingEncoding(NSUTF8StringEncoding) let result = try NSJSONSerialization.JSONObjectWithData (data! , options: .AllowFragments ) as? [String:String] if let ret = result { req.json = ret return next!() }else { // error handle } } catch { } } func jsonParser(req: IncomingMessage, res: ServerResponse, next: NextCallback?) { guard req.header[Content_Type] == "application/json" else { return next!() } guard req.hasBody == true else{ return next!() } guard req.method == .POST || req.method == .PUT else{ return next!() } read(req, next!,parse: parse) } return jsonParser } public static func text() -> HttpCallback{ func parse(req: IncomingMessage, _ next: NextCallback? , _ body: String!){ if let ret = body { req.bodyText = ret return next!() }else { // error handle } } func textParser(req: IncomingMessage, res: ServerResponse, next: NextCallback?) { guard req.header[Content_Type] == "text/plain" else { return next!() } guard req.hasBody == true else{ return next!() } guard req.method == .POST || req.method == .PUT else{ return next!() } read(req, next!,parse: parse) } return textParser } }
apache-2.0
ac7fee4914aea29528ad281e35f0310d
25.432584
148
0.479915
5.032086
false
false
false
false
apple/swift-docc-symbolkit
Sources/SymbolKit/SymbolGraph/SymbolGraph.swift
1
3310
/* This source file is part of the Swift.org open source project Copyright (c) 2021 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 Swift project authors */ /** A symbol graph is a set of *nodes* that represent the symbols in a module and a set of directed *edges* that represent the relationships between symbols. */ public struct SymbolGraph: Codable { /// Metadata about the symbol graph. public var metadata: Metadata /// The module that this symbol graph represents. public var module: Module /// The symbols in a module: the nodes in a graph, mapped by precise identifier. public var symbols: [String: Symbol] /// The relationships between symbols: the edges in a graph. public var relationships: [Relationship] public init(metadata: Metadata, module: Module, symbols: [Symbol], relationships: [Relationship]) { self.metadata = metadata self.module = module self.symbols = [String: Symbol](symbols.lazy.map({ ($0.identifier.precise, $0) }), uniquingKeysWith: { old, new in SymbolGraph._symbolToKeepInCaseOfPreciseIdentifierConflict(old, new) }) self.relationships = relationships } // MARK: - Codable public enum CodingKeys: String, CodingKey { case metadata case module case symbols case relationships } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let metadata = try container.decode(Metadata.self, forKey: .metadata) let module = try container.decode(Module.self, forKey: .module) let symbols = try container.decode([Symbol].self, forKey: .symbols) let relationships = try container.decode([Relationship].self, forKey: .relationships) self.init(metadata: metadata, module: module, symbols: symbols, relationships: relationships) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(metadata, forKey: .metadata) try container.encode(module, forKey: .module) try container.encode(Array(symbols.values), forKey: .symbols) try container.encode(relationships, forKey: .relationships) } public static func _symbolToKeepInCaseOfPreciseIdentifierConflict(_ lhs: Symbol, _ rhs: Symbol) -> Symbol { if lhs.declarationContainsAsyncKeyword() { return rhs } else if rhs.declarationContainsAsyncKeyword() { return lhs } else { // It's not expected to ever end up here, but if we do, we return the symbol with the longer name // to have consistent results. return lhs.names.title.count < rhs.names.title.count ? rhs : lhs } } } extension SymbolGraph.Symbol { fileprivate func declarationContainsAsyncKeyword() -> Bool { return (mixins[DeclarationFragments.mixinKey] as? DeclarationFragments)?.declarationFragments.contains(where: { fragment in fragment.kind == .keyword && fragment.spelling == "async" }) == true } }
apache-2.0
73df94631dd844400eb98a8e8f44d5c3
39.365854
131
0.683686
4.655415
false
false
false
false
frankrue/AmazonS3RequestManager
AmazonS3RequestManagerTests/AmazonS3ACLTests.swift
1
9497
// // AmazonS3ACLTests.swift // AmazonS3RequestManager // // Created by Anthony Miller on 6/9/15. // Copyright (c) 2015 Anthony Miller. All rights reserved. // import Quick import Nimble import AmazonS3RequestManager class AmazonS3ACLSpec: QuickSpec { override func spec() { describe("PredefinedACL") { context(".Private") { let acl = AmazonS3PredefinedACL.Private it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("private")) } } context(".Public") { let acl = AmazonS3PredefinedACL.Public it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read-write")) } } context(".PublicReadOnly") { let acl = AmazonS3PredefinedACL.PublicReadOnly it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read")) } } context(".AuthenticatedReadOnly") { let acl = AmazonS3PredefinedACL.AuthenticatedReadOnly it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("authenticated-read")) } } context(".BucketOwnerReadOnly") { let acl = AmazonS3PredefinedACL.BucketOwnerReadOnly it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-read")) } } context(".BucketOwnerFullControl") { let acl = AmazonS3PredefinedACL.BucketOwnerFullControl it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-full-control")) } } context(".LogDeliveryWrite") { let acl = AmazonS3PredefinedACL.LogDeliveryWrite it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("log-delivery-write")) } } } describe("ACL Permission Grant") { describe("With Permission") { func aclWithPermission(permission: AmazonS3ACLPermission) -> AmazonS3ACLPermissionGrant { let grantee = AmazonS3ACLGrantee.AuthenticatedUsers return AmazonS3ACLPermissionGrant(permission: permission, grantee: grantee) } describe("Read") { let permission = AmazonS3ACLPermission.Read let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).toNot(beNil()) } } describe("Write") { let permission = AmazonS3ACLPermission.Write let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write"] expect(aclHeader).toNot(beNil()) } } describe("Read ACL") { let permission = AmazonS3ACLPermission.ReadACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read-acp"] expect(aclHeader).toNot(beNil()) } } describe("Write ACL") { let permission = AmazonS3ACLPermission.WriteACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write-acp"] expect(aclHeader).toNot(beNil()) } } describe("Full Control") { let permission = AmazonS3ACLPermission.FullControl let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-full-control"] expect(aclHeader).toNot(beNil()) } } } describe("With Grantee") { func aclWithGrantee(grantee: AmazonS3ACLGrantee) -> AmazonS3ACLPermissionGrant { let permission = AmazonS3ACLPermission.Read return AmazonS3ACLPermissionGrant(permission: permission, grantee: grantee) } describe("Grantee: Authenticated Users") { let grantee = AmazonS3ACLGrantee.AuthenticatedUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\"")) } } describe("Grantee: All Users") { let grantee = AmazonS3ACLGrantee.AllUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AllUsers\"")) } } describe("Grantee: Log Delivery Group") { let grantee = AmazonS3ACLGrantee.LogDeliveryGroup let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/s3/LogDelivery\"")) } } describe("Grantee: Email") { let grantee = AmazonS3ACLGrantee.EmailAddress("[email protected]") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("emailAddress=\"[email protected]\"")) } } describe("Grantee: User ID") { let grantee = AmazonS3ACLGrantee.UserID("123456") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("id=\"123456\"")) } } } describe("With Multiple Grantees") { func aclWithGrantees(grantees: Set<AmazonS3ACLGrantee>) -> AmazonS3ACLPermissionGrant { let permission = AmazonS3ACLPermission.Read return AmazonS3ACLPermissionGrant(permission: permission, grantees: grantees) } it("sets ACL request headers") { let acl = aclWithGrantees([ AmazonS3ACLGrantee.EmailAddress("[email protected]"), AmazonS3ACLGrantee.UserID("123456")]) var request = NSMutableURLRequest() acl.setACLHeaders(forRequest: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("emailAddress=\"[email protected]\", id=\"123456\"")) } } } } }
mit
f71d70f7d668dd168ccc5f73256168c9
33.40942
108
0.57555
5.290808
false
false
false
false
wujunyang/swiftProject
Pods/SwifterSwift/Source/Extensions/StringExtensions.swift
2
23317
// // StringExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Properties public extension String { /// SwifterSwift: String decoded from base64 (if applicable). public var base64Decoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift guard let decodedData = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } /// SwifterSwift: String encoded in base64 (if applicable). public var base64Encoded: String? { // https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift let plainData = data(using: .utf8) return plainData?.base64EncodedString() } /// SwifterSwift: Array of characters of a string. public var charactersArray: [Character] { return Array(characters) } /// SwifterSwift: CamelCase of string. public var camelCased: String { let source = lowercased() if source.characters.contains(" ") { let first = source.substring(to: source.index(after: source.startIndex)) let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "") let rest = String(camel.characters.dropFirst()) return first + rest } let first = source.lowercased().substring(to: source.index(after: source.startIndex)) let rest = String(source.characters.dropFirst()) return first + rest } /// SwifterSwift: Check if string contains one or more emojis. public var containEmoji: Bool { // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji for scalar in unicodeScalars { switch scalar.value { case 0x3030, 0x00AE, 0x00A9, // Special Characters 0x1D000...0x1F77F, // Emoticons 0x2100...0x27BF, // Misc symbols and Dingbats 0xFE00...0xFE0F, // Variation Selectors 0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs return true default: continue } } return false } /// SwifterSwift: First character of string (if applicable). public var firstCharacter: String? { guard let first = characters.first else { return nil } return String(first) } /// SwifterSwift: Check if string contains one or more letters. public var hasLetters: Bool { return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil } /// SwifterSwift: Check if string contains one or more numbers. public var hasNumbers: Bool { return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil } /// SwifterSwift: Check if string contains only letters. public var isAlphabetic: Bool { return hasLetters && !hasNumbers } /// SwifterSwift: Check if string contains at least one letter and one number. public var isAlphaNumeric: Bool { return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers } /// SwifterSwift: Check if string is valid email format. public var isEmail: Bool { // http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift return matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}") } /// SwifterSwift: Check if string is a valid URL. public var isValidUrl: Bool { return URL(string: self) != nil } /// SwifterSwift: Check if string is a valid schemed URL. public var isValidSchemedUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme != nil } /// SwifterSwift: Check if string is a valid https URL. public var isValidHttpsUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "https" } /// SwifterSwift: Check if string is a valid http URL. public var isValidHttpUrl: Bool { guard let url = URL(string: self) else { return false } return url.scheme == "http" } /// SwifterSwift: Check if string contains only numbers. public var isNumeric: Bool { return !hasLetters && hasNumbers } /// SwifterSwift: Last character of string (if applicable). public var lastCharacter: String? { guard let last = characters.last else { return nil } return String(last) } /// SwifterSwift: Latinized string. public var latinized: String { return folding(options: .diacriticInsensitive, locale: Locale.current) } /// SwifterSwift: Number of characters in string. public var length: Int { return characters.count } /// SwifterSwift: Array of strings separated by new lines. public var lines: [String] { var result = [String]() enumerateLines { line, _ in result.append(line) } return result } /// SwifterSwift: The most common character in string. public var mostCommonCharacter: String { let mostCommon = withoutSpacesAndNewLines.characters.reduce([Character: Int]()) { var counts = $0 counts[$1] = ($0[$1] ?? 0) + 1 return counts }.max { $0.1 < $1.1 }?.0 return mostCommon?.string ?? "" } /// SwifterSwift: Reversed string. public var reversed: String { return String(characters.reversed()) } /// SwifterSwift: Bool value from string (if applicable). public var bool: Bool? { let selfLowercased = trimmed.lowercased() if selfLowercased == "true" || selfLowercased == "1" { return true } else if selfLowercased == "false" || selfLowercased == "0" { return false } return nil } /// SwifterSwift: Date object from "yyyy-MM-dd" formatted string public var date: Date? { let selfLowercased = trimmed.lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd" return formatter.date(from: selfLowercased) } /// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string. public var dateTime: Date? { let selfLowercased = trimmed.lowercased() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.date(from: selfLowercased) } /// SwifterSwift: Double value from string (if applicable). public var double: Double? { let formatter = NumberFormatter() return formatter.number(from: self) as? Double } /// SwifterSwift: Float value from string (if applicable). public var float: Float? { let formatter = NumberFormatter() return formatter.number(from: self) as? Float } /// SwifterSwift: Float32 value from string (if applicable). public var float32: Float32? { let formatter = NumberFormatter() return formatter.number(from: self) as? Float32 } /// SwifterSwift: Float64 value from string (if applicable). public var float64: Float64? { let formatter = NumberFormatter() return formatter.number(from: self) as? Float64 } /// SwifterSwift: Integer value from string (if applicable). public var int: Int? { return Int(self) } /// SwifterSwift: Int16 value from string (if applicable). public var int16: Int16? { return Int16(self) } /// SwifterSwift: Int32 value from string (if applicable). public var int32: Int32? { return Int32(self) } /// SwifterSwift: Int64 value from string (if applicable). public var int64: Int64? { return Int64(self) } /// SwifterSwift: Int8 value from string (if applicable). public var int8: Int8? { return Int8(self) } /// SwifterSwift: URL from string (if applicable). public var url: URL? { return URL(string: self) } /// SwifterSwift: String with no spaces or new lines in beginning and end. public var trimmed: String { return trimmingCharacters(in: .whitespacesAndNewlines) } /// SwifterSwift: Array with unicodes for all characters in a string. public var unicodeArray: [Int] { return unicodeScalars.map({$0.hashValue}) } /// SwifterSwift: Readable string from a URL string. public var urlDecoded: String { return removingPercentEncoding ?? self } /// SwifterSwift: URL escaped string. public var urlEncoded: String { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } /// SwifterSwift: String without spaces and new lines. public var withoutSpacesAndNewLines: String { return replacing(" ", with: "").replacing("\n", with: "") } } // MARK: - Methods public extension String { /// SwifterSwift: Safely subscript string with index. /// /// - Parameter i: index. public subscript(i: Int) -> String? { guard i >= 0 && i < characters.count else { return nil } return String(self[index(startIndex, offsetBy: i)]) } /// SwifterSwift: Safely subscript string within a half-open range. /// /// - Parameter range: Half-open range. public subscript(range: CountableRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else { return nil } return self[lowerIndex..<upperIndex] } /// SwifterSwift: Safely subscript string within a closed range. /// /// - Parameter range: Closed range. public subscript(range: ClosedRange<Int>) -> String? { guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else { return nil } guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else { return nil } return self[lowerIndex..<upperIndex] } #if os(iOS) || os(macOS) /// SwifterSwift: Copy string to global pasteboard. public func copyToPasteboard() { #if os(iOS) UIPasteboard.general.string = self #elseif os(macOS) NSPasteboard.general().clearContents() NSPasteboard.general().setString(self, forType: NSPasteboardTypeString) #endif } #endif /// SwifterSwift: Converts string format to CamelCase. public mutating func camelize() { self = camelCased } /// SwifterSwift: Check if string contains one or more instance of substring. /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string contains one or more instance of substring. public func contains(_ string: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return range(of: string, options: .caseInsensitive) != nil } return range(of: string) != nil } /// SwifterSwift: Count of substring in string. /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: count of appearance of substring in string. public func count(of string: String, caseSensitive: Bool = true) -> Int { if !caseSensitive { return lowercased().components(separatedBy: string.lowercased()).count - 1 } return components(separatedBy: string).count - 1 } /// SwifterSwift: Check if string ends with substring. /// /// - Parameters: /// - suffix: substring to search if string ends with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string ends with substring. public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasSuffix(suffix.lowercased()) } return hasSuffix(suffix) } /// SwifterSwift: First index of substring in string. /// /// - Parameter string: substring to search for. /// - Returns: first index of substring in string (if applicable). public func firstIndex(of string: String) -> Int? { return Array(characters).map({String($0)}).index(of: string) } /// SwifterSwift: Latinize string. public mutating func latinize() { self = latinized } /// SwifterSwift: Random string of given length. /// /// - Parameter length: number of characters in string. /// - Returns: random string of given length. public static func random(ofLength length: Int) -> String { guard length > 0 else { return "" } let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" return (0..<length).reduce("") { let randomIndex = arc4random_uniform(UInt32(base.characters.count)) let randomCharacter = "\(base[base.index(base.startIndex, offsetBy: IndexDistance(randomIndex))])" return $0.0 + randomCharacter } } /// SwifterSwift: String by replacing part of string with another string. /// /// - Parameters: /// - substring: old substring to find and replace. /// - newString: new string to insert in old string place. /// - Returns: string after replacing substring with newString. public func replacing(_ substring: String, with newString: String) -> String { return replacingOccurrences(of: substring, with: newString) } /// SwifterSwift: Reverse string. public mutating func reverse() { self = String(characters.reversed()) } /// SwifterSwift: Sliced string from a start index with length. /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. /// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World") public func slicing(from i: Int, length: Int) -> String? { guard length >= 0, i >= 0, i < characters.count else { return nil } guard i.advanced(by: length) <= characters.count else { return slicing(at: i) } guard length > 0 else { return "" } return self[i..<i.advanced(by: length)] } /// SwifterSwift: Slice given string from a start index with length (if applicable). /// /// - Parameters: /// - i: string index the slicing should start from. /// - length: amount of characters to be sliced after given index. public mutating func slice(from i: Int, length: Int) { if let str = slicing(from: i, length: length) { self = str } } /// SwifterSwift: Sliced string from a start index to an end index. /// /// - Parameters: /// - start: string index the slicing should start from. /// - end: string index the slicing should end at. /// - Returns: sliced substring starting from start index, and ends at end index (if applicable) (example: "Hello World".slicing(from: 6, to: 11) -> "World") public func slicing(from start: Int, to end: Int) -> String? { guard end >= start else { return nil } return self[start..<end] } /// SwifterSwift: Slice given string from a start index to an end index (if applicable). /// /// - Parameters: /// - start: string index the slicing should start from. /// - end: string index the slicing should end at. public mutating func slice(from start: Int, to end: Int) { if let str = slicing(from: start, to: end) { self = str } } /// SwifterSwift: Sliced string from a start index. /// /// - Parameter i: string index the slicing should start from. /// - Returns: sliced substring starting from start index (if applicable) (example: "Hello world".slicing(at: 6) -> "world") public func slicing(at i: Int) -> String? { guard i < characters.count else { return nil } return self[i..<characters.count] } /// SwifterSwift: Slice given string from a start index (if applicable). /// /// - Parameter i: string index the slicing should start from. public mutating func slice(at i: Int) { if let str = slicing(at: i) { self = str } } /// SwifterSwift: Array of strings separated by given string. /// /// - Parameter separator: separator to split string by. /// - Returns: array of strings separated by given string. public func splitted(by separator: Character) -> [String] { return characters.split{$0 == separator}.map(String.init) } /// SwifterSwift: Check if string starts with substring. /// /// - Parameters: /// - suffix: substring to search if string starts with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string starts with substring. public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasPrefix(prefix.lowercased()) } return hasPrefix(prefix) } /// SwifterSwift: Date object from string of date format. /// /// - Parameter format: date format. /// - Returns: Date object from string (if applicable). public func date(withFormat format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) } /// SwifterSwift: Removes spaces and new lines in beginning and end of string. public mutating func trim() { self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// SwifterSwift: Truncate string (cut it to a given number of characters). /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string (default is "..."). public mutating func truncate(toLength: Int, trailing: String? = "...") { guard toLength > 0 else { return } if characters.count > toLength { self = substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "") } } /// SwifterSwift: Truncated string (limited to a given number of characters). /// /// - Parameters: /// - toLength: maximum number of characters before cutting. /// - trailing: string to add at the end of truncated string. /// - Returns: truncated string (this is an extr...). public func truncated(toLength: Int, trailing: String? = "...") -> String { guard 1..<characters.count ~= toLength else { return self } return substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "") } /// SwifterSwift: Convert URL string to readable string. public mutating func urlDecode() { if let decoded = removingPercentEncoding { self = decoded } } /// SwifterSwift: Escape string. public mutating func urlEncode() { if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { self = encoded } } /// SwifterSwift: Verify if string matches the regex pattern. /// /// - Parameter pattern: Pattern to verify. /// - Returns: true if string matches the pattern. func matches(pattern: String) -> Bool { return range(of: pattern, options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil } } // MARK: - Operators public extension String { /// SwifterSwift: Repeat string multiple times. /// /// - Parameters: /// - lhs: string to repeat. /// - rhs: number of times to repeat character. /// - Returns: new string with given string repeated n times. public static func * (lhs: String, rhs: Int) -> String { guard rhs > 0 else { return "" } return String(repeating: lhs, count: rhs) } /// SwifterSwift: Repeat string multiple times. /// /// - Parameters: /// - lhs: number of times to repeat character. /// - rhs: string to repeat. /// - Returns: new string with given string repeated n times. public static func * (lhs: Int, rhs: String) -> String { guard lhs > 0 else { return "" } return String(repeating: rhs, count: lhs) } } // MARK: - Initializers public extension String { /// SwifterSwift: Create a new string from a base64 string (if applicable). /// /// - Parameter base64: base64 string. public init?(base64: String) { guard let str = base64.base64Decoded else { return nil } self.init(str) } /// SwifterSwift: Create a new random string of given length. /// /// - Parameter length: number of characters in string. public init(randomOfLength length: Int) { self = String.random(ofLength: length) } } // MARK: - NSAttributedString extensions public extension String { #if !os(tvOS) && !os(watchOS) /// SwifterSwift: Bold string. public var bold: NSAttributedString { #if os(macOS) return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize())]) #else return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) #endif } #endif /// SwifterSwift: Underlined string public var underline: NSAttributedString { return NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) } /// SwifterSwift: Strikethrough string. public var strikethrough: NSAttributedString { return NSAttributedString(string: self, attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]) } #if os(iOS) /// SwifterSwift: Italic string. public var italic: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) } #endif #if os(macOS) /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: NSColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) } #else /// SwifterSwift: Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: UIColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) } #endif } //MARK: - NSString extensions public extension String { /// SwifterSwift: NSString from a string. public var nsString: NSString { return NSString(string: self) } /// SwifterSwift: NSString lastPathComponent. public var lastPathComponent: String { return (self as NSString).lastPathComponent } /// SwifterSwift: NSString pathExtension. public var pathExtension: String { return (self as NSString).pathExtension } /// SwifterSwift: NSString deletingLastPathComponent. public var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } /// SwifterSwift: NSString deletingPathExtension. public var deletingPathExtension: String { return (self as NSString).deletingPathExtension } /// SwifterSwift: NSString pathComponents. public var pathComponents: [String] { return (self as NSString).pathComponents } /// SwifterSwift: NSString appendingPathComponent(str: String) /// /// - Parameter str: the path component to append to the receiver. /// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator. public func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } /// SwifterSwift: NSString appendingPathExtension(str: String) /// /// - Parameter str: The extension to append to the receiver. /// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable). public func appendingPathExtension(_ str: String) -> String? { return (self as NSString).appendingPathExtension(str) } }
apache-2.0
7d4b861368adffdcf2489a438955c6cc
30.046605
158
0.69952
3.812296
false
false
false
false
DeliciousRaspberryPi/ShameGame
Sources/ShameGame/Models.swift
1
6416
import Foundation import SwiftyJSON import SwiftKuery import SwiftKueryPostgreSQL // This has to go... var sharedPersonDatabase = [String:Person]() //MARK: Person class class Person { var name: String var avatarURL: URL var habits: [String:Habit] = [:] init?(json: JSON) { guard let name = json["name"].string, let avatarURLString = json["avatarURL"].string, let avatarURL = URL(string: avatarURLString) else { self.name = "" self.avatarURL = URL(string: "")! self.habits = [:] return nil } self.name = name self.avatarURL = avatarURL json["habits"].arrayValue.flatMap({ Habit(json: $0) }).forEach({ self.habits[$0.name] = $0 }) } init(name: String, avatarURL: URL, habits: [String:Habit]) { self.name = name self.avatarURL = avatarURL self.habits = habits } } // Utility Protocols extension Person: CustomStringConvertible { var description: String { get { return "<Person - name: \(name)>\n\tavatarURL: \(avatarURL)\n\thabits: [\(habits.map({ (_, habit) in habit.name}).joined(separator: ", "))]>" } } } extension Person: Equatable { } func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.avatarURL.absoluteString == rhs.avatarURL.absoluteString } extension Person: StringValuePairConvertible { var stringValuePairs: StringValuePair { return [ "name": name, "avatarURL": avatarURL.absoluteString, "habits": habits.map { (_, habit) in habit.stringValuePairs } ] } } //MARK: Habit class class Habit { var name: String var entriesContainer: HabitType init?(json: JSON) { guard let name = json["name"].string, let entriesContainer = HabitType(json: json["entries"]) else { self.name = "" self.entriesContainer = .count([]) return nil } self.name = name self.entriesContainer = entriesContainer } init(name: String, entries: HabitType) { self.name = name self.entriesContainer = entries } } // Utility Protocols extension Habit: Equatable { } func ==(lhs: Habit, rhs: Habit) -> Bool { return lhs.name == rhs.name } extension Habit: StringValuePairConvertible { var stringValuePairs: StringValuePair { return [ "name": name, "entries": entriesContainer.stringValuePairs ] } } //MARK: HabitType Enum enum HabitType { case count([CountEntry]) case elapsed([ElapsedTimeEntry]) init?(json: JSON) { if let countEntries = json["count"].array { self = .count(countEntries.flatMap { CountEntry(json: $0) } ) } else if let elapsedEntries = json["elapsed"].array { self = .elapsed(elapsedEntries.flatMap { ElapsedTimeEntry(json: $0) } ) } else { self = .count([]) return nil } } mutating func merge(other: HabitType) { switch self { case .count(let habits): if case .count(let otherHabits) = other { self = .count(habits + otherHabits) } case .elapsed(let habits): if case .elapsed(let otherHabits) = other { self = .elapsed(habits + otherHabits) } } } } // Utility protocols extension HabitType: Equatable { } func ==(lhs: HabitType, rhs: HabitType) -> Bool { if case .count(let entries1) = lhs, case .count(let entries2) = rhs { guard entries1.count == entries2.count else { return false } for (index, item) in entries1.enumerated() { if !(item == entries2[index]) { return false } } return true } else if case .elapsed(let entries1) = lhs, case .elapsed(let entries2) = rhs { guard entries1.count == entries2.count else { return false } for (index, item) in entries1.enumerated() { if !(item == entries2[index]) { return false } } return true } return false } extension HabitType: StringValuePairConvertible { var stringValuePairs: StringValuePair { switch self { case .elapsed(let entries): return ["elapsed": entries.stringValuePairs] case .count(let entries): return ["count": entries.stringValuePairs] } } } //MARK: Entry enums for habits class CountEntry { let createdAt: Date init?(json: JSON) { guard let dateString = json["createdAt"].string, let date = formatter.date(from: dateString) else { self.createdAt = Date() return nil } self.createdAt = date } } // Utility protocols extension CountEntry: Equatable { } func ==(lhs: CountEntry, rhs: CountEntry) -> Bool { return lhs.createdAt == rhs.createdAt } extension CountEntry: StringValuePairConvertible { var stringValuePairs: StringValuePair { return ["createdAt": formatter.string(from: createdAt)] } } class ElapsedTimeEntry { let createdAt: Date let elapsedTime: TimeInterval init?(json: JSON) { guard let createdAtString = json["createdAt"].string, let createdAt = formatter.date(from: createdAtString), let elapsedTimeInterval = json["elapsedTime"].double else { self.createdAt = Date() elapsedTime = 0.0 return nil } self.createdAt = createdAt self.elapsedTime = elapsedTimeInterval } } // Utility protocols extension ElapsedTimeEntry: Equatable { } func ==(lhs: ElapsedTimeEntry, rhs: ElapsedTimeEntry) -> Bool { return lhs.createdAt == rhs.createdAt && lhs.elapsedTime == rhs.elapsedTime } extension ElapsedTimeEntry: StringValuePairConvertible { var stringValuePairs: StringValuePair { return [ "createdAt": formatter.string(from: createdAt), "elapsedTime": elapsedTime ] } } fileprivate let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }()
apache-2.0
45d1315d3da19abddc0b4cfd3d67f351
27.264317
157
0.583853
4.461752
false
false
false
false
keyeMyria/DeckRocket
Source/Mac/MenuView.swift
1
1867
// // MenuView.swift // DeckRocket // // Created by JP Simard on 6/14/14. // Copyright (c) 2014 JP Simard. All rights reserved. // import Cocoa // FIXME: Use system-defined constant once accessible from Swift. let NSVariableStatusItemLength: CGFloat = -1 final class MenuView: NSView, NSMenuDelegate { private var highlight = false private let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength) // MARK: Initializers init() { super.init(frame: NSRect(x: 0, y: 0, width: 24, height: 24)) statusItem.view = self setupMenu() } required convenience init(coder: NSCoder) { self.init() } // MARK: Menu private func setupMenu() { menu = NSMenu() menu?.autoenablesItems = false menu?.addItemWithTitle("Not Connected", action: nil, keyEquivalent: "") menu?.itemAtIndex(0)?.enabled = false menu?.addItemWithTitle("Send Slides", action: "sendSlides", keyEquivalent: "") menu?.itemAtIndex(1)?.enabled = false menu?.addItemWithTitle("Quit DeckRocket", action: "quit", keyEquivalent: "") menu?.delegate = self } override func mouseDown(theEvent: NSEvent) { super.mouseDown(theEvent) if let menu = menu { statusItem.popUpStatusItemMenu(menu) } } func menuWillOpen(menu: NSMenu) { highlight = true needsDisplay = true } func menuDidClose(menu: NSMenu) { highlight = false needsDisplay = true } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) statusItem.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: highlight) "🚀".drawInRect(CGRectOffset(dirtyRect, 4, -1), withAttributes: [NSFontAttributeName: NSFont.menuBarFontOfSize(14)]) } }
mit
4c7a8f8e5ae257204232cf1423338fa6
27.242424
123
0.647532
4.546341
false
false
false
false
Lollipop95/WeiBo
WeiBo/WeiBo/Classes/Tools/Extensions/Date+Extensions.swift
1
1941
// // Date+Extensions.swift // WeiBo // // Created by Ning Li on 2017/5/7. // Copyright © 2017年 Ning Li. All rights reserved. // import Foundation private let dateFormatter: DateFormatter = DateFormatter() private let calendar: Calendar = Calendar.current extension Date { /// 将新浪格式的字符串转换成日期 /// /// - Parameter string: 日期字符串 /// - Returns: 日期 static func ln_sinaDate(string: String) -> Date? { dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy" dateFormatter.locale = Locale(identifier: "en_US") let date = dateFormatter.date(from: string) return date } /// 日期描述字符串 var ln_dateDescription: String { // 今天 if calendar.isDateInToday(self) { let detla = -Int(timeIntervalSinceNow) // 1分钟内 if detla < 60 { return "刚刚" } // 1小时内 if detla < 3600 { return "\(detla / 60)分钟前" } // 当天 return "\(detla / 3600)小时前" } var formatter: String = "HH:mm" // 一天前 if calendar.isDateInYesterday(self) { formatter = "昨天" + formatter } else { // 今年 formatter = "MM-dd " + formatter let year = calendar.component(.year, from: self) let thisYear = calendar.component(.year, from: Date()) // 更早 if year != thisYear { formatter = "yyyy-" + formatter } } dateFormatter.dateFormat = formatter let string = dateFormatter.string(from: self) return string } }
mit
6b4f1256ec54ec86c7999c3e71968d4a
23.052632
66
0.477024
4.699229
false
false
false
false
VladiMihaylenko/omim
iphone/Maps/Classes/DeepLinkHandler.swift
2
3204
fileprivate enum DeeplinkType { case geo case file case common } @objc @objcMembers class DeepLinkHandler: NSObject { static let shared = DeepLinkHandler() private(set) var isLaunchedByDeeplink = false private(set) var deeplinkURL: URL? var needExtraWelcomeScreen: Bool { guard let host = deeplinkURL?.host else { return false } return host == "catalogue" || host == "guides_page" } private var canHandleLink = false private var deeplinkType: DeeplinkType = .common private override init() { super.init() } func applicationDidFinishLaunching(_ options: [UIApplication.LaunchOptionsKey : Any]? = nil) { if let userActivityOptions = options?[.userActivityDictionary] as? [UIApplication.LaunchOptionsKey : Any], let userActivityType = userActivityOptions[.userActivityType] as? String, userActivityType == NSUserActivityTypeBrowsingWeb { isLaunchedByDeeplink = true } if let launchDeeplink = options?[UIApplication.LaunchOptionsKey.url] as? URL { isLaunchedByDeeplink = true deeplinkURL = launchDeeplink } } func applicationDidOpenUrl(_ url: URL) -> Bool { guard let dlType = deeplinkType(url) else { return false } deeplinkType = dlType deeplinkURL = url if canHandleLink { handleInternal() } return true } private func setUniversalLink(_ url: URL) -> Bool { let dlUrl = convertUniversalLink(url) guard let dlType = deeplinkType(dlUrl), deeplinkURL == nil else { return false } deeplinkType = dlType deeplinkURL = dlUrl return true } func applicationDidReceiveUniversalLink(_ url: URL) -> Bool { var result = false if let host = url.host, host == "mapsme.onelink.me" { URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach { if $0.name == "af_dp" { guard let value = $0.value, let dl = URL(string: value) else { return } result = setUniversalLink(dl) } } } else { result = setUniversalLink(url) } if canHandleLink { handleInternal() } return result } func handleDeeplink() { canHandleLink = true if deeplinkURL != nil { handleInternal() } } func handleDeeplink(_ url: URL) { deeplinkURL = url handleDeeplink() } func reset() { isLaunchedByDeeplink = false deeplinkURL = nil } private func convertUniversalLink(_ universalLink: URL) -> URL { let convertedLink = String(format: "mapsme:/%@?%@", universalLink.path, universalLink.query ?? "") return URL(string: convertedLink)! } private func deeplinkType(_ deeplink: URL) -> DeeplinkType? { switch deeplink.scheme { case "geo", "ge0": return .geo case "file": return .file case "mapswithme", "mapsme", "mwm": return .common default: return nil } } private func handleInternal() { guard let url = deeplinkURL else { assertionFailure() return } switch deeplinkType { case .geo: DeepLinkHelper.handleGeoUrl(url) case .file: DeepLinkHelper.handleFileUrl(url) case .common: DeepLinkHelper.handleCommonUrl(url) } } }
apache-2.0
94c2be869768f29fb73b06b1a84f8b90
25.04878
110
0.656679
4.353261
false
false
false
false
typelift/Focus
Sources/Focus/ArrayZipper.swift
1
2703
// // ArrayZipper.swift // Focus // // Created by Alexander Ronald Altman on 8/4/14. // Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved. // #if SWIFT_PACKAGE import Operadics #endif /// An `ArrayZipper` is a structure for walking an array of values and /// manipulating it in constant time. /// /// Zippers are convenient ways of traversing and modifying a structure using a /// cursor to focus on its individual parts. public struct ArrayZipper<A> : ExpressibleByArrayLiteral { public typealias Element = A /// The underlying array of values. public let values : [A] /// The position of the cursor within the Array. public let position : Int public init(_ values : [A] = [], _ position : Int = 0) { if position < 0 { self.position = 0 } else if position >= values.count { self.position = values.count - 1 } else { self.position = position } self.values = values } /// Creates an ArrayZipper pointing at the head of a given list of elements. public init(arrayLiteral elements : Element...) { self.init(elements, 0) } /// Creates an `ArrayZipper` with the cursor adjusted by n in the direction /// of the sign of the given value. public func move(_ n : Int = 1) -> ArrayZipper<A> { return ArrayZipper(values, position + n) } /// Creates an `ArrayZipper` with the cursor set to a given position value. public func moveTo(_ pos : Int) -> ArrayZipper<A> { return ArrayZipper(values, pos) } /// Returns whether the cursor of the receiver is at the end of its /// underlying Array. public var isAtEnd : Bool { return position >= (values.count - 1) } } extension ArrayZipper /*: Functor*/ { public func map<B>(_ f : (A) -> B) -> ArrayZipper<B> { return ArrayZipper<B>(self.values.map(f), self.position) } } public func <^> <A, B>(f : (A) -> B, xz : ArrayZipper<A>) -> ArrayZipper<B> { return xz.map(f) } extension ArrayZipper /*: Copointed*/ { /// Extracts the value at the position of the receiver's cursor. /// /// This function is not total, but makes the guarantee that if /// `zipper.isAtEnd` returns false it is safe to call. public func extract() -> A { return self.values[self.position] } } extension ArrayZipper /*: Comonad*/ { public func duplicate() -> ArrayZipper<ArrayZipper<A>> { return ArrayZipper<ArrayZipper<A>>((0 ..< self.values.count).map { ArrayZipper(self.values, $0) }, self.position) } public func extend<B>(_ f : (ArrayZipper<A>) -> B) -> ArrayZipper<B> { return ArrayZipper<B>((0 ..< self.values.count).map { f(ArrayZipper(self.values, $0)) }, self.position) } } public func ->> <A, B>(xz : ArrayZipper<A>, f: (ArrayZipper<A>) -> B) -> ArrayZipper<B> { return xz.extend(f) }
mit
65e63dbd3eb755e4a42af0510378e1dc
28.380435
115
0.671476
3.168816
false
false
false
false
crewshin/GasLog
GasLogger/Controllers/BaseTableViewController.swift
1
3695
// // BaseTableViewController.swift // GasLogger // // Created by Gene Crucean on 1/8/16. // Copyright © 2016 Dagger Dev. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Tab bar appearance. UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent tabBarController?.tabBar.translucent = false // Nav bar logo. let navBarLogo = StyleKit.imageOfNavbar_logo_small let navBarLogoView = UIImageView(image: navBarLogo) self.navigationItem.titleView = navBarLogoView navigationController?.navigationBar.barTintColor = StyleKit.blue navigationController?.navigationBar.translucent = false UIApplication.sharedApplication().statusBarHidden = false navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.view.backgroundColor = StyleKit.blue } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 0 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return 0 // } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false 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 false 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
723e7d20286554765057217bcb84aa1d
32.889908
157
0.675961
5.588502
false
false
false
false
AaoIi/AASnackbar
AASnackbar/AASnackbar/AASnackbar.swift
1
6465
// // AASnackbar.swift // AASnackbar // // Created by AaoIi on 11/26/15. // Copyright © 2015 Saad Albasha. All rights reserved. // import UIKit @available (iOS 9,*) public class AASnackbar: UIView { // MARK: private properties @IBOutlet fileprivate weak var label: UILabel! @IBOutlet fileprivate weak var button: UIButton!{ didSet{ button.isHidden = true } } @IBOutlet private var contentView:UIView! @IBOutlet private weak var parentView:UIView! fileprivate var timer : Timer! public var animationType : Type! public enum `Type`:Int{ case fade = 0 , translation = 1 } //MARK:- Customization public static var barHeight : CGFloat = 100 private var contentViewBackgroundColor : UIColor = UIColor(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0) // MARK: Constructors init public init(addedToView: UIView,title:String,buttonTitle:String,duration:TimeInterval,animationType:Type) { super.init(frame: addedToView.frame) commonInit() self.parentView = addedToView self.animationType = animationType self.showAASnackBar(title,withButton: true,buttonTitle: buttonTitle,duration: duration,animationType:animationType) } public init(addedToView: UIView,title:String,duration:TimeInterval,animationType:Type) { super.init(frame: addedToView.frame) commonInit() self.parentView = addedToView self.animationType = animationType self.showAASnackBar(title,withButton: false,buttonTitle: "",duration: duration,animationType:animationType) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func commonInit() { let bundle = Bundle(path: Bundle(for: AASnackbar.self).path(forResource: "AASnackbar", ofType: "bundle")!) bundle?.loadNibNamed("AASnackbar", owner: self, options: nil) guard let content = contentView else { return } content.frame = self.bounds content.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.addSubview(content) } // MARK: AASnackbar initialization fileprivate func showAASnackBar(_ textTitle:String,withButton:Bool,buttonTitle:String,duration:TimeInterval,animationType:Type){ var safeAreaBottomPadding : CGFloat? = 0 if #available(iOS 11.0, *) { let window = UIApplication.shared.keyWindow safeAreaBottomPadding = window?.safeAreaInsets.bottom } self.frame = CGRect(x: 0 , y: (self.frame.size.height) - AASnackbar.barHeight - (safeAreaBottomPadding ?? 0), width: self.frame.size.width, height: AASnackbar.barHeight) contentView.backgroundColor = contentViewBackgroundColor // Create label label.text = textTitle label.textColor = UIColor.white label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 14) // Create button if withButton == true { button.isHidden = false button.setTitle(buttonTitle, for: .normal) button.setTitleColor(UIColor(red: 76/255, green: 175/255, blue: 80/255, alpha: 1.0), for: .normal) button.addTarget(self, action: #selector(AASnackbar.invalidateTimer(_:)), for: .touchUpInside) } // Set and animate translation animation if animationType == .translation { self.transform = CGAffineTransform(translationX: 0, y: 500) UIView.animate(withDuration: 1.0, delay: 0.0, options: [], animations: { () -> Void in self.transform = CGAffineTransform.identity }) { (finished) -> Void in self.timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(AASnackbar.invalidateTimer(_:)), userInfo: nil, repeats: false) } }else { // Set and animate fade animation self.alpha = 0.0 UIView.animate(withDuration: 1.0, delay: 0.0, options: [], animations: { () -> Void in self.alpha = 1.0 }) { (finished) -> Void in self.timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(AASnackbar.invalidateTimer(_:)), userInfo: nil, repeats: false) } } } public func show(){ parentView.addSubview(self) } @objc fileprivate func invalidateTimer(_ sender:AnyObject){ if let timer = sender as? Timer { timer.invalidate() } if animationType == .translation { hideWithTranslation(1.0, delay: 0.0) }else { hideWithFade(1.0, delay: 0.0) } } // MARK: Property setters public func setTextColor(_ color:UIColor){ self.label.textColor = color } public func setBackgroundColor(_ color:UIColor){ self.contentView.backgroundColor = color } public func setButtonTextColor(_ color:UIColor){ self.button.setTitleColor(color, for: .normal) } public func addButtonAction(_ selector:Selector,view:UIViewController){ self.button.addTarget(view, action: selector, for: .touchUpInside) } // MARK: Hide Actions public func hideWithTranslation(_ duration:TimeInterval = 1,delay:TimeInterval = 0){ UIView.animate(withDuration: duration , delay: delay, options: [], animations: { () -> Void in self.transform = CGAffineTransform(translationX: 0, y: 500) }) { (finished) -> Void in self.removeFromSuperview() self.parentView = nil } } public func hideWithFade(_ duration:TimeInterval = 1,delay:TimeInterval = 0){ UIView.animate(withDuration: duration , delay: delay, options: [], animations: { () -> Void in self.alpha = 0.0 }) { (finished) -> Void in self.removeFromSuperview() self.parentView = nil } } }
mit
a0fb8654dbe49c99fec46f923ee7702c
32.492228
177
0.589418
4.89697
false
false
false
false
abarisain/skugga
Apple/macOS/Share/ShareViewController.swift
1
1652
// // ShareViewController.swift // Share // // Created by Arnaud Barisain Monrose on 11/02/2015. // // import Cocoa class ShareViewController: NSViewController { override var nibName: String? { return "ShareViewController" } override func loadView() { super.loadView() // Insert code here to customize the view let item = self.extensionContext!.inputItems[0] as! NSExtensionItem if let attachments = item.attachments { if attachments.count > 0 { let attachment = attachments.first as! NSItemProvider if attachment.hasItemConformingToTypeIdentifier(kUTTypeFileURL as String) { attachment.loadItem(forTypeIdentifier: kUTTypeFileURL as String, options: nil, completionHandler: { (item: NSSecureCoding?, error: Error!) -> Void in if let urlItem = item as? URL { RMSharedUserDefaults.standard.set(urlItem, forKey: "shareExtensionURL") } } ) self.extensionContext!.completeRequest(returningItems: [item], completionHandler: nil) return } } } else { NSLog("No Attachments") } let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) self.extensionContext!.cancelRequest(withError: cancelError) } }
apache-2.0
c8d027144edc5d829086eda10733e1bb
31.392157
106
0.535714
5.879004
false
false
false
false
ikhsan/FutureOfRamadhan
FutureRamadhans/ViewController.swift
1
4295
import UIKit class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { // MARK: variables for visualization // change city and years let city = "London" let years = 25 let cellIdentifier = "TheCell" let headerIdentifier = "HeaderCell" var summaries: [RamadhanSummary] var durationRange = (0.0, 24.0) init() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Vertical layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 20, right: 20) layout.minimumLineSpacing = 10 summaries = [] super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = UIColor.whiteColor() configureDefaultCells() configureTitleHeaderCell() configureRamadhanSummaries() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { collectionView?.collectionViewLayout.invalidateLayout() collectionView?.reloadData() } } // MARK: Actions extension ViewController { func configureRamadhanSummaries() { RamadhanSummary.summariesForCity(city, initialYear: 1437, durationInYears: years) { summaries in self.summaries = summaries self.durationRange = ( summaries.map { $0.duration }.reduce(24.0) { min($0, $1) }, 19.0 ) self.collectionView?.reloadData() } } func saveInfographicToImage() { guard let collectionView = collectionView else { return } let snapshot = collectionView.rmdn_takeSnapshot() let imagePath = snapshot.rmdn_saveImageWithName(city) print("open '\(imagePath)'") } } // MARK: Cells extension ViewController { func configureDefaultCells() { collectionView?.registerClass(SummaryCell.self, forCellWithReuseIdentifier: cellIdentifier) } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return summaries.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! SummaryCell cell.summary = summaries[indexPath.item] cell.durationRange = durationRange return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: CGRectGetWidth(collectionView.bounds) - 40.0 , height: 40.0) } } // MARK: Header extension ViewController { func configureTitleHeaderCell() { collectionView?.registerClass(HeaderCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: CGRectGetWidth(collectionView.bounds), height: 60.0) } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if (kind == UICollectionElementKindSectionHeader) { let headerCell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! HeaderCell headerCell.label.text = "\(city)'s Ramadhan in the next \(years) years" headerCell.tapHandler = self.saveInfographicToImage return headerCell } return UICollectionReusableView() } }
mit
0d8b1df002f4e2f5d4de9e97076a63bd
33.087302
180
0.690338
5.82768
false
false
false
false
AboutObjects/Modelmatic
Example/Modelmatic/AuthorObjectStore.swift
1
7010
// // Copyright (C) 2015 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation import CoreData import Modelmatic let authorsModelName = "Authors" let authorsFileName = "Authors" private let restUrlString = "http://www.aboutobjects.com/modelmatic?resource=Authors" enum StorageMode { case webService case file } class AuthorObjectStore: NSObject { let model: NSManagedObjectModel! let authorEntity: NSEntityDescription! let bookEntity: NSEntityDescription! var version: NSNumber = 0 var authors: [Author]? private var storageMode = StorageMode.file { willSet { segmentedControl.selectedSegmentIndex = newValue == .file ? 1 : 0 } } @IBOutlet private weak var segmentedControl: UISegmentedControl! required override init() { let bundle = Bundle(for: AuthorObjectStore.self) guard let modelURL = bundle.url(forResource: authorsModelName, withExtension: "momd") else { fatalError("Unable to find model named \(authorsModelName).momd in bundle \(bundle)") } model = NSManagedObjectModel(contentsOf: modelURL) authorEntity = model.entitiesByName[Author.entityName] bookEntity = model.entitiesByName[Book.entityName] super.init() AuthorObjectStore.initialization } private static let initialization: Void = { configureValueTransformers() configureURLProtocols() }() } // MARK: - Persistence API extension AuthorObjectStore { func fetch(_ completion: @escaping () -> Void) { if case StorageMode.webService = storageMode { fetchObjects(fromWeb: restUrlString, mainQueueHandler: completion) } else { fetchObjects(fromFile: authorsFileName, completion: completion) } } func save() { if case StorageMode.webService = storageMode { save(toWeb: restUrlString) } else { save(toFile: authorsFileName) } } func toggleStorageMode() { storageMode = storageMode == .file ? .webService : .file } } // MARK: - Storing and retrieving data extension AuthorObjectStore { private func fetchObjects(fromFile fileName: String, completion: () -> Void) { guard let dict = NSDictionary.dictionary(contentsOfJSONFile: fileName), let authorDicts = dict["authors"] as? [JsonDictionary] else { return } version = dict["version"] as? NSNumber ?? NSNumber(value: 0) authors = authorDicts.map { Author(dictionary: $0, entity: authorEntity) } completion() } private func fetchObjects(fromWeb urlString: String, mainQueueHandler: @escaping () -> Void) { guard let url = URL(string: urlString) else { fatalError("Invalid url string: \(urlString)") } let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in self?.handleFetch(data: data, response: response, error: error, mainQueueHandler: mainQueueHandler) } task.resume() } private func handleFetch(data: Data?, response: URLResponse?, error: Error?, mainQueueHandler: @escaping () -> Void) { guard error == nil else { print("WARNING: Save error: \(error!)") return } guard (response as? HTTPURLResponse)?.valid == true else { print("WARNING: Invalid response code \((response as? HTTPURLResponse)?.statusCode ?? 0)") return } decodeAuthors(data) OperationQueue.main.addOperation { mainQueueHandler() } } private func save(toWeb urlString: String) { guard let url = URL(string: urlString) else { fatalError("Invalid url string: \(urlString)") } guard let data = encodeAuthors() else { print("WARNING: save failed with url: \(urlString)"); return } let request = URLRequest.putRequest(url: url, data: data) let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in self?.handleSave(data: data, response: response, error: error) } task.resume() } private func handleSave(data: Data?, response: URLResponse?, error: Error?) { guard error == nil else { print("WARNING: Save error: \(error!)") return } guard (response as? HTTPURLResponse)?.valid == true else { print("WARNING: Invalid response code \((response as? HTTPURLResponse)?.statusCode ?? 0)") return } } private func save(toFile fileName: String) { guard let data = encodeAuthors(), let url = URL.documentDirectoryURL(forFileName: authorsFileName, type: "json") else { return } do { try data.write(to: url, options: NSData.WritingOptions(rawValue: 0)) } catch { print("WARNING: Unable to save data as JSON") } } } // MARK: - Encoding/decoding extension AuthorObjectStore { private func encodeAuthors() -> Data? { guard let authors = authors else { return nil } let dict: NSDictionary = ["version": version, "authors": authors.dictionaryRepresentation] return try? dict.serializeAsJson(pretty: true) } private func decodeAuthors(_ data: Data?) { guard let data = data, let d = try? data.deserializeJson(), let dict = d as? JsonDictionary, let authorDicts = dict["authors"] as? [JsonDictionary] else { return } version = dict["version"] as? NSNumber ?? NSNumber(value: 0) authors = authorDicts.map { Author(dictionary: $0, entity: authorEntity) } } } // MARK: - DataSource support extension AuthorObjectStore { func titleForSection(_ section: NSInteger) -> String { return authors?[section].fullName ?? "" } func numberOfSections() -> NSInteger { return authors?.count ?? 0 } func numberOfRows(inSection section: NSInteger) -> NSInteger { return authors?[section].books?.count ?? 0 } func bookAtIndexPath(_ indexPath: IndexPath) -> Book? { return authors?[(indexPath as NSIndexPath).section].books?[(indexPath as NSIndexPath).row] } func removeBookAtIndexPath(_ indexPath: IndexPath) { authors?[(indexPath as NSIndexPath).section].books?.remove(at: (indexPath as NSIndexPath).row) } } // MARK: - URL protocols and value transformers extension AuthorObjectStore { private class func configureValueTransformers() { ValueTransformer.setValueTransformer(DateTransformer(), forName: DateTransformer.transformerName) ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: StringArrayTransformer.transformerName) } private class func configureURLProtocols() { URLProtocol.registerClass(HttpSessionProtocol.self) } }
mit
f8fee71277ec2ab899ff125ce73ed724
33.362745
141
0.642368
4.742896
false
false
false
false
bppr/Swiftest
src/Swiftest/Client/Listeners/DocFormatListener.swift
1
1622
public class DocFormatListener : Listener { public var printer = Printer() var passedCount = 0 var failedExamples : [Example] = [] var pendingCount = 0 var offset = 0 public override func suiteFinished() { printer.lineBreak() for ex in failedExamples { printer.call("× \"\(ex.subject)\" failed:") printer.indent() for exp in ex.expectations.filter(Status.equals(.Fail)) { printer.call("\(exp.msg) (\(exp.cursor.file):\(exp.cursor.line))") } printer.lineBreak() printer.dedent() } printer.call( ":: RESULTS :: " + "✓ \(passedCount)/\(runCount()) examples passed :: " + "× \(failedExamples.count) failed :: " + "★ \(pendingCount) pending\n" ) } public override func finished(spec: Specification) { if spec.parents == [nullSpec] { printSpec(spec) } } func printExample(example: Example) { if example.status == .Pass { passedCount += 1 printer.call("✓ \(example.subject)") } else if example.status == .Fail { failedExamples.append(example) printer.call("× \(example.subject)") } else { pendingCount += 1 printer.call("★ \(example.subject)") } } func printSpec(spec: Specification) { if spec.parents == [nullSpec] { printer.lineBreak() } printer.call(spec.subject) printer.indent() for ex in spec.examples { printExample(ex) } for s in spec.children { printSpec(s) } printer.dedent() } func runCount() -> Int { return [passedCount, failedExamples.count, pendingCount].reduce(0, combine: +) } }
mit
b7e8c0beda2480d366136084940ea4e0
23.784615
82
0.605835
3.826603
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBTests/FTS4TableBuilderTests.swift
1
11221
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif class FTS4TableBuilderTests: GRDBTestCase { override func setUp() { super.setUp() dbConfiguration.trace = { [unowned self] sql in // Ignore virtual table logs if !sql.hasPrefix("--") { self.sqlQueries.append(sql) } } } func testWithoutBody() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4") try db.execute("INSERT INTO documents VALUES (?)", arguments: ["abc"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1) } } func testOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", ifNotExists: true, using: FTS4()) assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts4") try db.execute("INSERT INTO documents VALUES (?)", arguments: ["abc"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1) } } func testSimpleTokenizer() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .simple } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=simple)") } } func testPorterTokenizer() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .porter } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=porter)") } } func testUnicode61Tokenizer() throws { #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .unicode61() } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61)") } } func testUnicode61TokenizerRemoveDiacritics() throws { #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .unicode61(removeDiacritics: false) } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61 \"remove_diacritics=0\")") } } func testUnicode61TokenizerSeparators() throws { #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .unicode61(separators: ["X"]) } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61 \"separators=X\")") } } func testUnicode61TokenizerTokenCharacters() throws { #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.tokenizer = .unicode61(tokenCharacters: Set(".-".characters)) } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(tokenize=unicode61 \"tokenchars=-.\")") } } func testColumns() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "books", using: FTS4()) { t in t.column("author") t.column("title") t.column("body") } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"books\" USING fts4(author, title, body)") try db.execute("INSERT INTO books VALUES (?, ?, ?)", arguments: ["Melville", "Moby Dick", "Call me Ishmael."]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["Melville"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["title:Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE title MATCH ?", arguments: ["Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["author:Melville"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE author MATCH ?", arguments: ["Melville"])!, 1) } } func testNotIndexedColumns() throws { #if !USING_CUSTOMSQLITE && !USING_SQLCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "books", using: FTS4()) { t in t.column("author").notIndexed() t.column("title") t.column("body").notIndexed() } assertDidExecute(sql: "CREATE VIRTUAL TABLE \"books\" USING fts4(author, notindexed=author, title, body, notindexed=body)") try db.execute("INSERT INTO books VALUES (?, ?, ?)", arguments: ["Melville", "Moby Dick", "Call me Ishmael."]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["Dick"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["title:Dick"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE title MATCH ?", arguments: ["Dick"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["author:Dick"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE author MATCH ?", arguments: ["Dick"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["title:Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE title MATCH ?", arguments: ["Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: ["author:Melville"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE author MATCH ?", arguments: ["Melville"])!, 0) } } func testFTS4Options() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.content = "" t.compress = "zip" t.uncompress = "unzip" t.matchinfo = "fts3" t.prefixes = [2, 4] t.column("content") t.column("lid").asLanguageId() } print(sqlQueries) assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, languageid=\"lid\", content=\"\", compress=\"zip\", uncompress=\"unzip\", matchinfo=\"fts3\", prefix=\"2,4\")") try db.execute("INSERT INTO documents (docid, content, lid) VALUES (?, ?, ?)", arguments: [1, "abc", 0]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ? AND lid=0", arguments: ["abc"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM documents WHERE documents MATCH ? AND lid=1", arguments: ["abc"])!, 0) } } func testFTS4Synchronization() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "documents") { t in t.column("id", .integer).primaryKey() t.column("content", .text) } try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) try db.create(virtualTable: "ft_documents", using: FTS4()) { t in t.synchronize(withTable: "documents") t.column("content") } // Prepopulated XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["foo"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 0) // Synchronized on update try db.execute("UPDATE documents SET content = ?", arguments: ["bar"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["foo"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1) // Synchronized on insert try db.execute("INSERT INTO documents (content) VALUES (?)", arguments: ["foo"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["foo"])!, 1) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1) // Synchronized on delete try db.execute("DELETE FROM documents WHERE content = ?", arguments: ["foo"]) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["foo"])!, 0) XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1) } } }
mit
b2c911ac91879fc71dd893aad948755e
47.366379
201
0.579004
4.608214
false
true
false
false
zixun/GodEye
GodEye/Classes/Main/Model/LogRecordModel.swift
1
2443
// // LogRecordModel.swift // Pods // // Created by zixun on 16/12/28. // // import Foundation enum LogRecordModelType:Int { case asl = 1 case log = 2 case warning = 3 case error = 4 func string() -> String { switch self { case .asl: return "ASL" case .log: return "LOG" case .warning: return "WARNING" case .error: return "ERROR" } } func color() -> UIColor { switch self { case .asl: return UIColor(hex: 0x94C76F) case .log: return UIColor(hex: 0x94C76F) case .warning: return UIColor(hex: 0xFEC42E) case .error: return UIColor(hex: 0xDF1921) } } } final class LogRecordModel: NSObject { private(set) var type: LogRecordModelType! /// date for Time stamp private(set) var date: String? /// thread which log the message private(set) var thread: String? /// filename with extension private(set) var file: String? /// number of line in source code file private(set) var line: Int? /// name of the function which log the message private(set) var function: String? /// message be logged private(set) var message: String! init(model:LogModel) { super.init() self.type = self.type(of: model.type) self.date = model.date.string(with: "yyyy-MM-dd HH:mm:ss") self.thread = model.thread.threadName self.file = model.file self.line = model.line self.function = model.function self.message = model.message } init(type:LogRecordModelType, message:String, date:String? = nil, thread:String? = nil, file: String? = nil, line: Int? = nil, function: String? = nil) { super.init() self.type = type self.message = message self.date = date self.thread = thread self.file = file self.line = line self.function = function } private func type(of log4gType:Log4gType) -> LogRecordModelType { switch log4gType { case .log: return LogRecordModelType.log case .warning: return LogRecordModelType.warning case .error: return LogRecordModelType.error } } }
mit
fcb5af6f3769f4a95310470fb20ca57c
22.95098
69
0.548097
4.105882
false
false
false
false
amosavian/FileProvider
Sources/SMBTypes/SMB2FileOperation.swift
2
7741
// // SMB2FileOperation.swift // ExtDownloader // // Created by Amir Abbas Mousavian on 4/30/95. // Copyright © 1395 Mousavian. All rights reserved. // import Foundation extension SMB2 { // MARK: SMB2 Read struct ReadRequest: SMBRequestBody { static var command: SMB2.Command = .READ let size: UInt16 fileprivate let padding: UInt8 let flags: ReadRequest.Flags let length: UInt32 let offset: UInt64 let fileId: FileId let minimumLength: UInt32 let channel: Channel let remainingBytes: UInt32 fileprivate let channelInfoOffset: UInt16 fileprivate let channelInfoLength: UInt16 fileprivate let channelBuffer: UInt8 init (fileId: FileId, offset: UInt64, length: UInt32, flags: ReadRequest.Flags = [], minimumLength: UInt32 = 0, remainingBytes: UInt32 = 0, channel: Channel = .NONE) { self.size = 49 self.padding = 0 self.flags = flags self.length = length self.offset = offset self.fileId = fileId self.minimumLength = minimumLength self.channel = channel self.remainingBytes = remainingBytes self.channelInfoOffset = 0 self.channelInfoLength = 0 self.channelBuffer = 0 } struct Flags: OptionSet { let rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static let UNBUFFERED = Flags(rawValue: 0x01) } } struct ReadRespone: SMBResponseBody { struct Header { let size: UInt16 let offset: UInt8 fileprivate let reserved: UInt8 let length: UInt32 let remaining: UInt32 fileprivate let reserved2: UInt32 } let header: ReadRespone.Header let buffer: Data init?(data: Data) { guard data.count > 16 else { return nil } self.header = data.scanValue()! let headersize = MemoryLayout<Header>.size self.buffer = data.subdata(in: headersize..<data.count) } } struct Channel: Option { init(rawValue: UInt32) { self.rawValue = rawValue } let rawValue: UInt32 public static let NONE = Channel(rawValue: 0x00000000) public static let RDMA_V1 = Channel(rawValue: 0x00000001) public static let RDMA_V1_INVALIDATE = Channel(rawValue: 0x00000002) } // MARK: SMB2 Write struct WriteRequest: SMBRequestBody { static var command: SMB2.Command = .WRITE let header: WriteRequest.Header let channelInfo: ChannelInfo? let fileData: Data struct Header { let size: UInt16 let dataOffset: UInt16 let length: UInt32 let offset: UInt64 let fileId: FileId let channel: Channel let remainingBytes: UInt32 let channelInfoOffset: UInt16 let channelInfoLength: UInt16 let flags: WriteRequest.Flags } // codebeat:disable[ARITY] init(fileId: FileId, offset: UInt64, remainingBytes: UInt32 = 0, data: Data, channel: Channel = .NONE, channelInfo: ChannelInfo? = nil, flags: WriteRequest.Flags = []) { var channelInfoOffset: UInt16 = 0 var channelInfoLength: UInt16 = 0 if channel != .NONE, let _ = channelInfo { channelInfoOffset = UInt16(MemoryLayout<SMB2.Header>.size + MemoryLayout<WriteRequest.Header>.size) channelInfoLength = UInt16(MemoryLayout<SMB2.ChannelInfo>.size) } let dataOffset = UInt16(MemoryLayout<SMB2.Header>.size + MemoryLayout<WriteRequest.Header>.size) + channelInfoLength self.header = WriteRequest.Header(size: UInt16(49), dataOffset: dataOffset, length: UInt32(data.count), offset: offset, fileId: fileId, channel: channel, remainingBytes: remainingBytes, channelInfoOffset: channelInfoOffset, channelInfoLength: channelInfoLength, flags: flags) self.channelInfo = channelInfo self.fileData = data } // codebeat:enable[ARITY] func data() -> Data { var result = Data(value: self.header) if let channelInfo = channelInfo { result.append(channelInfo.data()) } result.append(fileData) return result } struct Flags: OptionSet { let rawValue: UInt32 init(rawValue: UInt32) { self.rawValue = rawValue } static let THROUGH = Flags(rawValue: 0x00000001) static let UNBUFFERED = Flags(rawValue: 0x00000002) } } struct WriteResponse: SMBResponseBody { let size: UInt16 fileprivate let reserved: UInt16 let writtenBytes: UInt32 fileprivate let remaining: UInt32 fileprivate let channelInfoOffset: UInt16 fileprivate let channelInfoLength: UInt16 } struct ChannelInfo: SMBRequestBody { static var command: SMB2.Command = .WRITE let offset: UInt64 let token: UInt32 let length: UInt32 } // MARK: SMB2 Lock struct LockElement: SMBRequestBody { static var command: SMB2.Command = .LOCK let offset: UInt64 let length: UInt64 let flags: LockElement.Flags fileprivate let reserved: UInt32 struct Flags: OptionSet { let rawValue: UInt32 init(rawValue: UInt32) { self.rawValue = rawValue } static let SHARED_LOCK = Flags(rawValue: 0x00000001) static let EXCLUSIVE_LOCK = Flags(rawValue: 0x00000002) static let UNLOCK = Flags(rawValue: 0x00000004) static let FAIL_IMMEDIATELY = Flags(rawValue: 0x00000010) } } struct LockRequest: SMBRequestBody { static var command: SMB2.Command = .LOCK let header: LockRequest.Header let locks: [LockElement] init(fileId: FileId,locks: [LockElement], lockSequenceNumber : Int8 = 0, lockSequenceIndex: UInt32 = 0) { self.header = LockRequest.Header(size: 48, lockCount: UInt16(locks.count), lockSequence: UInt32(lockSequenceNumber << 28) + lockSequenceIndex, fileId: fileId) self.locks = locks } func data() -> Data { var result = Data(value: header) for lock in locks { result.append(Data(value: lock)) } return result } struct Header { let size: UInt16 fileprivate let lockCount: UInt16 let lockSequence: UInt32 let fileId : FileId } } struct LockResponse: SMBResponseBody { let size: UInt16 let reserved: UInt16 init() { self.size = 4 self.reserved = 0 } } // MARK: SMB2 Cancel struct CancelRequest: SMBRequestBody { static var command: SMB2.Command = .CANCEL let size: UInt16 let reserved: UInt16 init() { self.size = 4 self.reserved = 0 } } }
mit
30830b43dec74c7f51876459fba33f43
31.25
287
0.557106
4.777778
false
false
false
false
modulo-dm/modulo
Modules/ELCodable/ELCodable/JSON.swift
1
18434
// // JSON2.swift // THGModel // // Created by Brandon Sneed on 9/12/15. // Copyright © 2015 theholygrail. All rights reserved. // import Foundation public enum JSONError: Error { case invalidJSON } public enum JSONType: Int { case number case string case bool case array case dictionary case null case unknown } public struct JSON { public var object: Any? public init() { self.object = nil } public init(_ object: Any?) { self.object = object } public init(json: JSON) { self.object = json.object } public init?(data: Data?) { if let data = data { do { let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments) self.object = object } catch let error as NSError { debugPrint(error) } } else { return nil } } public init?(path: String) { let exists = FileManager.default.fileExists(atPath: path) if exists { let data = try? Data(contentsOf: Foundation.URL(fileURLWithPath: path)) self.init(data: data) } else { return nil } } /** Initialize an instance given a JSON file contained within the bundle. - parameter bundle: The bundle to attempt to load from. - parameter string: A string containing the name of the file to load from resources. */ public init?(bundleClass: AnyClass, filename: String) { let bundle = Bundle(for: bundleClass) self.init(bundle: bundle, filename: filename) } public init?(bundle: Bundle, filename: String) { let filepath: String? = bundle.path(forResource: filename, ofType: nil) if let filepath = filepath { self.init(path: filepath) } else { return nil } } /** If the object in question is a dictionary, this will return the value of the key at the specified index. If the object is an array, it will return the value at the specified index. This subscript is currently readonly. */ public subscript(index: Int) -> JSON? { get { /** NSDictionary is used because it currently performs better than a native Swift dictionary. The reason for this is that [String : AnyObject] is bridged to NSDictionary deep down the call stack, and this bridging operation is relatively expensive. Until Swift is ABI stable and/or doesn't require a bridge to Objective-C, NSDictionary will be used here */ if let dictionary = object as? NSDictionary { if let keys = dictionary.allKeys as? [String] { let key = keys[index] let value = dictionary[key] if let value = value { return JSON(value as AnyObject?) } } } else if let array = object as? NSArray { let value = array[index] return JSON(value as AnyObject?) } return nil } } /** Returns or sets the key to a given value. */ public subscript(key: String) -> JSON? { set { if var tempObject = object as? [String : Any] { tempObject[key] = newValue?.object self.object = tempObject as Any? } else { var tempObject: [String : Any] = [:] tempObject[key] = newValue?.object self.object = tempObject as Any? } } get { /** NSDictionary is used because it currently performs better than a native Swift dictionary. The reason for this is that [String : AnyObject] is bridged to NSDictionary deep down the call stack, and this bridging operation is relatively expensive. Until Swift is ABI stable and/or doesn't require a bridge to Objective-C, NSDictionary will be used here */ if let dictionary = object as? NSDictionary { let value = dictionary[key] if let value = value { return JSON(value as AnyObject?) } } return nil } } } extension JSON { public func data() -> Data? { if let object = object { return try? JSONSerialization.data(withJSONObject: object, options: .prettyPrinted) } return nil } } // MARK: - Types (Debugging) extension JSON { public var type: JSONType { if let object = object { switch object { case is NSString: return .string case is NSArray: return .array case is NSDictionary: return .dictionary case is NSNumber: let number = object as! NSNumber let type = String(cString: number.objCType) // there's no such thing as a 'char' in json, but that's // what the serializer types it as. if type == "c" { return .bool } return .number case is NSNull: return .null default: return .unknown } } else { return .unknown } } public var objectType: String { if let object = object { return "\(Swift.type(of: object))" } else { return "Unknown" } } } // MARK: - CustomStringConvertible extension JSON: CustomStringConvertible { public var description: String { if let object: Any = object { switch object { case is String, is NSNumber, is Float, is Double, is Int, is UInt, is Bool: return "\(object)" case is [Any], is [String : Any]: if let data = try? JSONSerialization.data(withJSONObject: object, options: .prettyPrinted) { return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? ?? "" } default: return "" } } return "\(String(describing: object))" } } // MARK: - CustomDebugStringConvertible extension JSON: CustomDebugStringConvertible { public var debugDescription: String { return description } } // MARK: - NilLiteralConvertible extension JSON: ExpressibleByNilLiteral { public init(nilLiteral: ()) { self.init() } } // MARK: - StringLiteralConvertible extension JSON: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as AnyObject?) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as AnyObject?) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as AnyObject?) } } // MARK: - FloatLiteralConvertible extension JSON: ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as AnyObject?) } } // MARK: - IntegerLiteralConvertible extension JSON: ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as AnyObject?) } } // MARK: - BooleanLiteralConvertible extension JSON: ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as AnyObject?) } } // MARK: - ArrayLiteralConvertible extension JSON: ExpressibleByArrayLiteral { public init(arrayLiteral elements: AnyObject...) { self.init(elements as AnyObject?) } } // MARK: - DictionaryLiteralConvertible extension JSON: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, AnyObject)...) { var object: [String : AnyObject] = [:] for (key, value) in elements { object[key] = value } self.init(object as AnyObject?) } } // MARK: - String extension JSON { public var string: String? { if let object = object { var value: String? = nil switch object { case is String: value = object as? String case is NSDecimalNumber: value = (object as? NSDecimalNumber)?.stringValue case is NSNumber: value = (object as? NSNumber)?.stringValue default: break } return value } else { return nil } } } // MARK: - NSNumber extension JSON { public var number: NSNumber? { if let object = object { var value: NSNumber? = nil switch object { case is NSNumber: value = object as? NSNumber case is String: value = NSDecimalNumber(string: object as? String) default: break } return value } else { return nil } } } // MARK: - NSDecimalNumber extension JSON { public var decimal: NSDecimalNumber? { if let object = object { var value: NSDecimalNumber? = nil switch object { case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue) } case is NSDecimalNumber: value = object as? NSDecimalNumber case is NSNumber: // We need to jump through some hoops here. NSNumber's decimalValue doesn't guarantee // exactness for float and double types. See "decimalValue" on NSNumber. let number = object as! NSNumber let type = String(cString: number.objCType) // type encodings can be found here: // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html switch(type) { // treat the integer based ones the same and just use // the largest type. No worries here about rounding. case "c", "i", "s", "l", "q": value = NSDecimalNumber(value: number.int64Value as Int64) break // do the same with the unsigned types. case "C", "I", "S", "L", "Q": value = NSDecimalNumber(value: number.uint64Value as UInt64) break // and again with precision types. case "f", "d": value = NSDecimalNumber(value: number.doubleValue as Double) // not sure if we need to handle this, but just in case. // it shouldn't hurt anything. case "*": value = NSDecimalNumber(string: number.stringValue) // probably don't need this one either, but oh well. case "B": value = NSDecimalNumber(value: number.boolValue as Bool) default: break } default: break } return value } else { return nil } } } // MARK: - Float extension JSON { public var float: Float? { if let object = object { var value: Float? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.floatValue case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).floatValue } default: break; } return value } else { return nil } } } // MARK: - Double extension JSON { public var double: Double? { if let object = object { var value: Double? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.doubleValue case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).doubleValue } default: break; } return value } else { return nil } } } // MARK: - Int extension JSON { public var int: Int? { if let object = object { var value: Int? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.intValue case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).intValue } default: break; } return value } else { return nil } } public var int64: Int64? { if let object = object { var value: Int64? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.int64Value case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).int64Value } default: break; } return value } else { return nil } } } // MARK: - UInt extension JSON { public var uInt: UInt? { if let object = object { var value: UInt? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.uintValue case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).uintValue } default: break; } return value } else { return nil } } public var uInt64: UInt64? { if let object = object { var value: UInt64? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.uint64Value case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).uint64Value } default: break; } return value } else { return nil } } } // MARK: - Bool extension JSON { public var bool: Bool? { if let object = object { var value: Bool? = nil switch object { case is NSNumber: value = (object as? NSNumber)?.boolValue case is String: let stringValue = object as? String if let stringValue = stringValue { value = NSDecimalNumber(string: stringValue).boolValue } default: break; } return value } else { return nil } } } // MARK: - NSURL extension JSON { public var URL: Foundation.URL? { if let urlString = string { return Foundation.URL(string: urlString) } return nil } } // MARK: - Array extension JSON { public var array: [JSON]? { if let array = object as? [AnyObject] { return array.map { JSON($0) } } return nil } //public var arrayValue: [JSON] { return array ?? [] } } // MARK: - Dictionary extension JSON { public var dictionary: [String : JSON]? { if let dictionary = object as? [String : AnyObject] { return Dictionary(dictionary.map { ($0, JSON($1)) }) } return nil } //public var dictionaryValue: [String : JSON] { return dictionary ?? [:] } } extension Dictionary { fileprivate init(_ pairs: [Element]) { self.init() for (key, value) in pairs { self[key] = value } } } // MARK: - Equatable extension JSON: Equatable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { if let lhsObject: Any = lhs.object, let rhsObject: Any = rhs.object { switch (lhsObject, rhsObject) { case (let left as String, let right as String): return left == right case (let left as Double, let right as Double): return left == right case (let left as Float, let right as Float): return left == right case (let left as Int, let right as Int): return left == right case (let left as Int64, let right as Int64): return left == right case (let left as UInt, let right as UInt): return left == right case (let left as UInt64, let right as UInt64): return left == right case (let left as Bool, let right as Bool): return left == right case (let left as [Any], let right as [Any]): return left.map { JSON($0) } == right.map { JSON ($0) } case (let left as [String : Any], let right as [String : Any]): return Dictionary(left.map { ($0, JSON($1)) }) == Dictionary(right.map { ($0, JSON($1)) }) default: return false } } return false }
mit
0c9cc6d7604dc29efcad65e87d91fdd2
27.402157
138
0.513807
5.157527
false
false
false
false
iosprogrammingwithswift/iosprogrammingwithswift
16_WebKit_Final/SwiftWebView/ViewController.swift
1
1793
// // ViewController.swift // SwiftWebView // // Created by Andreas Wittmann on 11/01/15. // Copyright (c) 2015 🐨 + 🙉. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView.backgroundColor = UIColor.whiteColor() webView.scalesPageToFit = true webView.dataDetectorTypes = .All let url:NSURL = NSURL(string: "http://www.google.de")! let request = NSURLRequest(URL: url) webView.loadRequest(request) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: WebViewDelegate func webViewDidStartLoad(webView: UIWebView){ UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func webViewDidFinishLoad(webView: UIWebView){ UIApplication.sharedApplication().networkActivityIndicatorVisible = false } func webView(webView: UIWebView, didFailLoadWithError error: NSError?){ // Show the error inside the web view let localizedErrorMessage = NSLocalizedString("An error occured:", comment: "") let errorHTML = "<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">\(localizedErrorMessage) \(error.localizedDescription)</div></body></html>" webView.loadHTMLString(errorHTML, baseURL: nil) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } }
mit
84a3209a183bf5b7cf5685dbeebae267
30.910714
193
0.659205
5.366366
false
false
false
false